text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright 2019 Global Phasing Ltd.
//
// MTZ info
#include <gemmi/mtz.hpp>
#include <gemmi/fileutil.hpp> // for file_open
#include <gemmi/gz.hpp> // for MaybeGzipped
#include <gemmi/input.hpp> // for FileStream, MemoryStream
#define GEMMI_PROG mtz
#include "options.h"
#include <stdio.h>
using gemmi::Mtz;
enum OptionIndex { Headers=4, Dump, PrintTsv, PrintStats,
CheckAsu, ToggleEndian, NoIsym };
static const option::Descriptor Usage[] = {
{ NoOp, 0, "", "", Arg::None,
"Usage:\n " EXE_NAME " [options] MTZ_FILE[...]"
"\nPrint informations from an mtz file."},
CommonUsage[Help],
CommonUsage[Version],
CommonUsage[Verbose],
{ Headers, 0, "H", "headers", Arg::None,
" -H, --headers \tPrint raw headers, until the END record." },
{ Dump, 0, "d", "dump", Arg::None,
" -d, --dump \tPrint a subset of CCP4 mtzdmp informations." },
{ PrintTsv, 0, "", "tsv", Arg::None,
" --tsv \tPrint all the data as tab-separated values." },
{ PrintStats, 0, "", "stats", Arg::None,
" --stats \tPrint column statistics (completeness, mean, etc)." },
{ CheckAsu, 0, "", "check-asu", Arg::None,
" --check-asu \tCheck if reflections are in conventional ASU." },
{ ToggleEndian, 0, "", "toggle-endian", Arg::None,
" --toggle-endian \tToggle assumed endiannes (little <-> big)." },
{ NoIsym, 0, "", "no-isym", Arg::None,
" --no-isym \tDo not apply symmetry from M/ISYM column." },
{ 0, 0, 0, 0, 0, 0 }
};
static void dump(const Mtz& mtz) {
printf("Title: %s\n", mtz.title.c_str());
printf("Number of Datasets = %zu\n\n", mtz.datasets.size());
for (const Mtz::Dataset& ds : mtz.datasets) {
printf("Dataset %4d %s > %s > %s:\n",
ds.id, ds.project_name.c_str(),
ds.crystal_name.c_str(), ds.dataset_name.c_str());
printf(" cell %g %7g %7g %6g %6g %6g\n",
ds.cell.a, ds.cell.b, ds.cell.c,
ds.cell.alpha, ds.cell.beta, ds.cell.gamma);
printf(" wavelength %g\n", ds.wavelength);
}
printf("\nNumber of Columns = %zu\n", mtz.columns.size());
printf("Number of Reflections = %d\n", mtz.nreflections);
printf("Number of Batches = %zu\n", mtz.batches.size());
printf("Missing values marked as: %g\n", mtz.valm);
printf("Global Cell (obsolete): %7.3f %7.3f %7.3f %g %g %g\n",
mtz.cell.a, mtz.cell.b, mtz.cell.c,
mtz.cell.alpha, mtz.cell.beta, mtz.cell.gamma);
printf("Resolution: %.2f - %.2f A\n",
mtz.resolution_high(), mtz.resolution_low());
printf("Sort Order: %d %d %d %d %d\n",
mtz.sort_order[0], mtz.sort_order[1], mtz.sort_order[2],
mtz.sort_order[3], mtz.sort_order[4]);
printf("Space Group: %s\n", mtz.spacegroup_name.c_str());
printf("Space Group Number: %d\n", mtz.spacegroup_number);
printf("\nColumn Type Dataset Min Max\n");
for (const Mtz::Column& col : mtz.columns)
printf("%-12s %c %2d %12.6g %10.6g\n",
col.label.c_str(), col.type, col.dataset_id,
col.min_value, col.max_value);
if (mtz.history.empty()) {
printf("\nNo history in the file.\n");
} else {
printf("\nHistory (%zu lines):\n", mtz.history.size());
for (const std::string& hline : mtz.history)
printf("%s\n", hline.c_str());
}
}
static void print_tsv(const Mtz& mtz) {
size_t ncol = mtz.columns.size();
for (size_t i = 0; i < ncol; ++i)
printf("%s%c", mtz.columns[i].label.c_str(), i + 1 != ncol ? '\t' : '\n');
for (size_t i = 0; i < mtz.nreflections * ncol; ++i)
printf("%g%c", mtz.data[i], (i + 1) % ncol != 0 ? '\t' : '\n');
}
struct ColumnStats {
float min_value = INFINITY;
float max_value = -INFINITY;
gemmi::Variance var;
};
static void print_stats(const Mtz& mtz) {
std::vector<ColumnStats> column_stats(mtz.columns.size());
for (size_t i = 0; i != mtz.data.size(); ++i) {
float v = mtz.data[i];
if (!std::isnan(v)) {
ColumnStats& stat = column_stats[i % column_stats.size()];
if (v < stat.min_value)
stat.min_value = v;
if (v > stat.max_value)
stat.max_value = v;
stat.var.add_point(v);
}
}
printf("column type @dataset completeness min max"
" mean stddev\n");
for (size_t i = 0; i != column_stats.size(); ++i) {
const Mtz::Column& col = mtz.columns[i];
const ColumnStats& stat = column_stats[i];
printf("%-14s %c @%d %d (%6.2f%%) %9.5g %9.5g %9.5g %8.4g\n",
col.label.c_str(), col.type, col.dataset_id,
stat.var.n, 100.0 * stat.var.n / mtz.nreflections,
stat.min_value, stat.max_value,
stat.var.mean_x, std::sqrt(stat.var.for_population()));
}
}
static void check_asu(const Mtz& mtz) {
size_t ncol = mtz.columns.size();
const gemmi::SpaceGroup* sg = mtz.spacegroup;
if (!sg)
gemmi::fail("no spacegroup in the MTZ file.");
int counter = 0;
gemmi::HklAsuChecker hkl_asu(sg);
for (int i = 0; i < mtz.nreflections; ++i) {
int h = (int) mtz.data[i * ncol + 0];
int k = (int) mtz.data[i * ncol + 1];
int l = (int) mtz.data[i * ncol + 2];
if (hkl_asu.is_in(h, k, l))
++counter;
}
printf("spacegroup: %s\n", sg->xhm().c_str());
printf("ccp4 ASU convention wrt. standard setting: %s\n",
hkl_asu.condition_str());
printf("inside / outside of ASU: %d / %d\n",
counter, mtz.nreflections - counter);
}
template<typename Stream>
void print_mtz_info(Stream&& stream, const char* path,
const std::vector<option::Option>& options) {
Mtz mtz;
try {
mtz.read_first_bytes(stream);
if (options[ToggleEndian])
mtz.toggle_endiannes();
} catch (std::runtime_error& e) {
gemmi::fail(std::string(e.what()) + ": " + path);
}
if (options[Headers]) {
char buf[81] = {0};
mtz.seek_headers(stream);
while (stream.read(buf, 80)) {
printf("%s\n", gemmi::rtrim_str(buf).c_str());
if (gemmi::ialpha3_id(buf) == gemmi::ialpha3_id("END"))
break;
}
}
if (options[Verbose])
mtz.warnings = stderr;
mtz.read_main_headers(stream);
mtz.read_history_and_batch_headers(stream);
mtz.setup_spacegroup();
if (options[Dump])
dump(mtz);
if (options[PrintTsv] || options[PrintStats] || options[CheckAsu]) {
mtz.read_raw_data(stream);
if (!options[NoIsym])
mtz.apply_isym();
}
if (options[PrintTsv])
print_tsv(mtz);
if (options[PrintStats])
print_stats(mtz);
if (options[CheckAsu])
check_asu(mtz);
}
int GEMMI_MAIN(int argc, char **argv) {
OptParser p(EXE_NAME);
p.simple_parse(argc, argv, Usage);
p.require_input_files_as_args();
try {
for (int i = 0; i < p.nonOptionsCount(); ++i) {
const char* path = p.nonOption(i);
if (i != 0)
printf("\n\n");
if (p.options[Verbose])
fprintf(stderr, "Reading %s ...\n", path);
gemmi::MaybeGzipped input(path);
if (input.is_stdin()) {
print_mtz_info(gemmi::FileStream{stdin}, path, p.options);
} else if (std::unique_ptr<char[]> mem = input.memory()) {
gemmi::MemoryStream stream(mem.get(), mem.get() + input.memory_size());
print_mtz_info(std::move(stream), path, p.options);
} else {
gemmi::fileptr_t f = gemmi::file_open(input.path().c_str(), "rb");
print_mtz_info(gemmi::FileStream{f.get()}, path, p.options);
}
}
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR: %s\n", e.what());
return 1;
}
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<commit_msg>gemmi-mtz: when invoked without options print the same as with --dump<commit_after>// Copyright 2019 Global Phasing Ltd.
//
// MTZ info
#include <gemmi/mtz.hpp>
#include <gemmi/fileutil.hpp> // for file_open
#include <gemmi/gz.hpp> // for MaybeGzipped
#include <gemmi/input.hpp> // for FileStream, MemoryStream
#define GEMMI_PROG mtz
#include "options.h"
#include <stdio.h>
using gemmi::Mtz;
enum OptionIndex { Headers=4, Dump, PrintTsv, PrintStats,
CheckAsu, ToggleEndian, NoIsym };
static const option::Descriptor Usage[] = {
{ NoOp, 0, "", "", Arg::None,
"Usage:\n " EXE_NAME " [options] MTZ_FILE[...]"
"\nPrint informations from an mtz file."},
CommonUsage[Help],
CommonUsage[Version],
CommonUsage[Verbose],
{ Headers, 0, "H", "headers", Arg::None,
" -H, --headers \tPrint raw headers, until the END record." },
{ Dump, 0, "d", "dump", Arg::None,
" -d, --dump \tPrint a subset of CCP4 mtzdmp informations." },
{ PrintTsv, 0, "", "tsv", Arg::None,
" --tsv \tPrint all the data as tab-separated values." },
{ PrintStats, 0, "", "stats", Arg::None,
" --stats \tPrint column statistics (completeness, mean, etc)." },
{ CheckAsu, 0, "", "check-asu", Arg::None,
" --check-asu \tCheck if reflections are in conventional ASU." },
{ ToggleEndian, 0, "", "toggle-endian", Arg::None,
" --toggle-endian \tToggle assumed endiannes (little <-> big)." },
{ NoIsym, 0, "", "no-isym", Arg::None,
" --no-isym \tDo not apply symmetry from M/ISYM column." },
{ 0, 0, 0, 0, 0, 0 }
};
static void dump(const Mtz& mtz) {
printf("Title: %s\n", mtz.title.c_str());
printf("Number of Datasets = %zu\n\n", mtz.datasets.size());
for (const Mtz::Dataset& ds : mtz.datasets) {
printf("Dataset %4d %s > %s > %s:\n",
ds.id, ds.project_name.c_str(),
ds.crystal_name.c_str(), ds.dataset_name.c_str());
printf(" cell %g %7g %7g %6g %6g %6g\n",
ds.cell.a, ds.cell.b, ds.cell.c,
ds.cell.alpha, ds.cell.beta, ds.cell.gamma);
printf(" wavelength %g\n", ds.wavelength);
}
printf("\nNumber of Columns = %zu\n", mtz.columns.size());
printf("Number of Reflections = %d\n", mtz.nreflections);
printf("Number of Batches = %zu\n", mtz.batches.size());
printf("Missing values marked as: %g\n", mtz.valm);
printf("Global Cell (obsolete): %7.3f %7.3f %7.3f %g %g %g\n",
mtz.cell.a, mtz.cell.b, mtz.cell.c,
mtz.cell.alpha, mtz.cell.beta, mtz.cell.gamma);
printf("Resolution: %.2f - %.2f A\n",
mtz.resolution_high(), mtz.resolution_low());
printf("Sort Order: %d %d %d %d %d\n",
mtz.sort_order[0], mtz.sort_order[1], mtz.sort_order[2],
mtz.sort_order[3], mtz.sort_order[4]);
printf("Space Group: %s\n", mtz.spacegroup_name.c_str());
printf("Space Group Number: %d\n", mtz.spacegroup_number);
printf("\nColumn Type Dataset Min Max\n");
for (const Mtz::Column& col : mtz.columns)
printf("%-12s %c %2d %12.6g %10.6g\n",
col.label.c_str(), col.type, col.dataset_id,
col.min_value, col.max_value);
if (mtz.history.empty()) {
printf("\nNo history in the file.\n");
} else {
printf("\nHistory (%zu lines):\n", mtz.history.size());
for (const std::string& hline : mtz.history)
printf("%s\n", hline.c_str());
}
}
static void print_tsv(const Mtz& mtz) {
size_t ncol = mtz.columns.size();
for (size_t i = 0; i < ncol; ++i)
printf("%s%c", mtz.columns[i].label.c_str(), i + 1 != ncol ? '\t' : '\n');
for (size_t i = 0; i < mtz.nreflections * ncol; ++i)
printf("%g%c", mtz.data[i], (i + 1) % ncol != 0 ? '\t' : '\n');
}
struct ColumnStats {
float min_value = INFINITY;
float max_value = -INFINITY;
gemmi::Variance var;
};
static void print_stats(const Mtz& mtz) {
std::vector<ColumnStats> column_stats(mtz.columns.size());
for (size_t i = 0; i != mtz.data.size(); ++i) {
float v = mtz.data[i];
if (!std::isnan(v)) {
ColumnStats& stat = column_stats[i % column_stats.size()];
if (v < stat.min_value)
stat.min_value = v;
if (v > stat.max_value)
stat.max_value = v;
stat.var.add_point(v);
}
}
printf("column type @dataset completeness min max"
" mean stddev\n");
for (size_t i = 0; i != column_stats.size(); ++i) {
const Mtz::Column& col = mtz.columns[i];
const ColumnStats& stat = column_stats[i];
printf("%-14s %c @%d %d (%6.2f%%) %9.5g %9.5g %9.5g %8.4g\n",
col.label.c_str(), col.type, col.dataset_id,
stat.var.n, 100.0 * stat.var.n / mtz.nreflections,
stat.min_value, stat.max_value,
stat.var.mean_x, std::sqrt(stat.var.for_population()));
}
}
static void check_asu(const Mtz& mtz) {
size_t ncol = mtz.columns.size();
const gemmi::SpaceGroup* sg = mtz.spacegroup;
if (!sg)
gemmi::fail("no spacegroup in the MTZ file.");
int counter = 0;
gemmi::HklAsuChecker hkl_asu(sg);
for (int i = 0; i < mtz.nreflections; ++i) {
int h = (int) mtz.data[i * ncol + 0];
int k = (int) mtz.data[i * ncol + 1];
int l = (int) mtz.data[i * ncol + 2];
if (hkl_asu.is_in(h, k, l))
++counter;
}
printf("spacegroup: %s\n", sg->xhm().c_str());
printf("ccp4 ASU convention wrt. standard setting: %s\n",
hkl_asu.condition_str());
printf("inside / outside of ASU: %d / %d\n",
counter, mtz.nreflections - counter);
}
template<typename Stream>
void print_mtz_info(Stream&& stream, const char* path,
const std::vector<option::Option>& options) {
Mtz mtz;
try {
mtz.read_first_bytes(stream);
if (options[ToggleEndian])
mtz.toggle_endiannes();
} catch (std::runtime_error& e) {
gemmi::fail(std::string(e.what()) + ": " + path);
}
if (options[Headers]) {
char buf[81] = {0};
mtz.seek_headers(stream);
while (stream.read(buf, 80)) {
printf("%s\n", gemmi::rtrim_str(buf).c_str());
if (gemmi::ialpha3_id(buf) == gemmi::ialpha3_id("END"))
break;
}
}
if (options[Verbose])
mtz.warnings = stderr;
mtz.read_main_headers(stream);
mtz.read_history_and_batch_headers(stream);
mtz.setup_spacegroup();
if (options[Dump] ||
!(options[PrintTsv] || options[PrintStats] || options[CheckAsu] ||
options[Headers]))
dump(mtz);
if (options[PrintTsv] || options[PrintStats] || options[CheckAsu]) {
mtz.read_raw_data(stream);
if (!options[NoIsym])
mtz.apply_isym();
}
if (options[PrintTsv])
print_tsv(mtz);
if (options[PrintStats])
print_stats(mtz);
if (options[CheckAsu])
check_asu(mtz);
}
int GEMMI_MAIN(int argc, char **argv) {
OptParser p(EXE_NAME);
p.simple_parse(argc, argv, Usage);
p.require_input_files_as_args();
try {
for (int i = 0; i < p.nonOptionsCount(); ++i) {
const char* path = p.nonOption(i);
if (i != 0)
printf("\n\n");
if (p.options[Verbose])
fprintf(stderr, "Reading %s ...\n", path);
gemmi::MaybeGzipped input(path);
if (input.is_stdin()) {
print_mtz_info(gemmi::FileStream{stdin}, path, p.options);
} else if (std::unique_ptr<char[]> mem = input.memory()) {
gemmi::MemoryStream stream(mem.get(), mem.get() + input.memory_size());
print_mtz_info(std::move(stream), path, p.options);
} else {
gemmi::fileptr_t f = gemmi::file_open(input.path().c_str(), "rb");
print_mtz_info(gemmi::FileStream{f.get()}, path, p.options);
}
}
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR: %s\n", e.what());
return 1;
}
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013-2014 Phokham Nonava
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
#include "pulse.h"
#include "perft.h"
#include <string>
#include <iostream>
int main(int argc, char* argv[]) {
try {
if (argc == 2) {
std::string token(argv[1]);
if (token == "perft") {
std::unique_ptr<pulse::Perft> perft(new pulse::Perft());
perft->run();
}
} else {
std::unique_ptr<pulse::Pulse> uci(new pulse::Pulse());
uci->run();
}
} catch (std::exception e) {
std::cout << "Exiting Pulse due to an exception: " << e.what() << std::endl;
return 1;
}
}
<commit_msg>Fix variable name<commit_after>/*
* Copyright (C) 2013-2014 Phokham Nonava
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
#include "pulse.h"
#include "perft.h"
#include <string>
#include <iostream>
int main(int argc, char* argv[]) {
try {
if (argc == 2) {
std::string token(argv[1]);
if (token == "perft") {
std::unique_ptr<pulse::Perft> perft(new pulse::Perft());
perft->run();
}
} else {
std::unique_ptr<pulse::Pulse> pulse(new pulse::Pulse());
pulse->run();
}
} catch (std::exception e) {
std::cout << "Exiting Pulse due to an exception: " << e.what() << std::endl;
return 1;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Fondazione Istituto Italiano di Tecnologia
* Authors: Silvio Traversaro
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*
*/
#include <iDynTree/Core/EigenHelpers.h>
#include <iDynTree/Estimation/SimpleLeggedOdometry.h>
#include <iDynTree/Model/ForwardKinematics.h>
#include <iDynTree/Model/Indeces.h>
#include <iDynTree/Model/ModelTransformers.h>
#include <iDynTree/ModelIO/URDFModelImport.h>
#include <iDynTree/ModelIO/URDFGenericSensorsImport.h>
#include <sstream>
namespace iDynTree
{
SimpleLeggedOdometry::SimpleLeggedOdometry(): m_model(),
m_traversal(),
m_isModelValid(false),
m_kinematicsUpdated(false),
m_isOdometryInitialized(false),
m_fixedLinkIndex(iDynTree::LINK_INVALID_INDEX),
m_world_H_fixedLink(Transform::Identity())
{
}
SimpleLeggedOdometry::~SimpleLeggedOdometry()
{
}
bool SimpleLeggedOdometry::init(const std::string& initialFixedFrame,
const Transform& world_H_initialFixedFrame)
{
FrameIndex initialFixedFrameIndex = this->m_model.getFrameIndex(initialFixedFrame);
return init(initialFixedFrameIndex,world_H_initialFixedFrame);
}
bool SimpleLeggedOdometry::init(const FrameIndex initialFixedFrameIndex,
const Transform& world_H_initialFixedFrame)
{
if( !m_isModelValid )
{
reportError("SimpleLeggedOdometry",
"init",
"Model not initialised.");
return false;
}
if( !m_model.isValidFrameIndex(initialFixedFrameIndex) )
{
reportError("SimpleLeggedOdometry",
"init","invalid frame passed");
return false;
}
m_fixedLinkIndex = m_model.getFrameLink(initialFixedFrameIndex);
Transform initialFixedFrame_H_fixedLink = m_model.getFrameTransform(initialFixedFrameIndex).inverse();
m_world_H_fixedLink = world_H_initialFixedFrame*initialFixedFrame_H_fixedLink;
m_isOdometryInitialized = true;
return true;
}
bool SimpleLeggedOdometry::init(const std::string& initialFixedFrame,
const std::string& initialWorldFrame)
{
return this->init(m_model.getFrameIndex(initialFixedFrame),
m_model.getFrameIndex(initialWorldFrame));
}
bool SimpleLeggedOdometry::init(const FrameIndex initialFixedFrameIndex,
const FrameIndex initialWorldFrameIndex)
{
if( !m_isModelValid )
{
reportError("SimpleLeggedOdometry",
"init",
"Model not initialised.");
return false;
}
if( !m_model.isValidFrameIndex(initialFixedFrameIndex) ||
!m_model.isValidFrameIndex(initialWorldFrameIndex)
)
{
reportError("SimpleLeggedOdometry",
"init","invalid frame passed");
return false;
}
if( ! m_kinematicsUpdated )
{
reportError("SimpleLeggedOdometry",
"init","updateKinematics never called");
return false;
}
// Set the fixed link
m_fixedLinkIndex = m_model.getFrameLink(initialFixedFrameIndex);
// TODO : we need a simple class to get arbitrary transform in a model,
// something even simpler then KinDynComputations to address this
// kind of computation that appear from time to time
// Set the world_H_fixedLink transform
LinkIndex linkAttachedToWorldFrameIndex = m_model.getFrameLink(initialWorldFrameIndex);
Transform worldFrame_H_linkAttachedToWorldFrame = m_model.getFrameTransform(initialWorldFrameIndex).inverse();
Transform linkAttachedToWorldFrameIndex_H_floatingBase = m_base_H_link(linkAttachedToWorldFrameIndex).inverse();
Transform floatingBase_H_fixedLink = m_base_H_link(m_fixedLinkIndex);
m_world_H_fixedLink = worldFrame_H_linkAttachedToWorldFrame*linkAttachedToWorldFrameIndex_H_floatingBase*floatingBase_H_fixedLink;
m_isOdometryInitialized = true;
return true;
}
bool SimpleLeggedOdometry::updateKinematics(JointPosDoubleArray& jointPos)
{
if( !m_isModelValid )
{
reportError("SimpleLeggedOdometry",
"updateKinematics","model not valid");
return false;
}
if( !jointPos.isConsistent(m_model) )
{
reportError("SimpleLeggedOdometry",
"updateKinematics","error in size of input jointPos");
return false;
}
bool ok = ForwardPositionKinematics(m_model,m_traversal,
Transform::Identity(),jointPos,
m_base_H_link);
m_kinematicsUpdated = ok;
return ok;
}
const Model& SimpleLeggedOdometry::model() const
{
return m_model;
}
bool SimpleLeggedOdometry::setModel(const Model& _model)
{
m_model = _model;
// resize the data structures
m_model.computeFullTreeTraversal(m_traversal);
// set that the model is valid
m_isModelValid = true;
// Set the kinematics and the odometry is not initialized
m_isOdometryInitialized = false;
m_kinematicsUpdated = false;
// Resize the linkPositions
m_base_H_link.resize(m_model);
return true;
}
bool SimpleLeggedOdometry::loadModelFromFile(const std::string filename,
const std::string /*filetype*/)
{
Model _model;
bool parsingCorrect = false;
parsingCorrect = modelFromURDF(filename,_model);
if( !parsingCorrect )
{
reportError("SimpleLeggedOdometry",
"loadModelFromFile",
"Error in parsing model from URDF.");
return false;
}
return setModel(_model);
}
bool SimpleLeggedOdometry::loadModelFromFileWithSpecifiedDOFs(const std::string filename,
const std::vector< std::string >& consideredDOFs,
const std::string filetype)
{
Model _modelFull;
bool parsingCorrect = false;
parsingCorrect = modelFromURDF(filename,_modelFull);
if( !parsingCorrect )
{
reportError("SimpleLeggedOdometry",
"loadModelFromFileWithSpecifiedDOFs",
"Error in parsing model from URDF.");
return false;
}
Model _modelReduced;
// Create a reduced model: this will lump all not considered joints
iDynTree::createReducedModel(_modelFull,consideredDOFs,_modelReduced);
return setModel(_modelReduced);
}
std::string SimpleLeggedOdometry::getCurrentFixedLink()
{
if( this->m_isModelValid && this->m_isOdometryInitialized )
{
return this->m_model.getLinkName(this->m_fixedLinkIndex);
}
else
{
reportError("SimpleLeggedOdometry",
"getCurrentFixedLink",
"getCurrentFixedLink was called, but no model is available or the odometry is not initialized.");
return "";
}
}
bool SimpleLeggedOdometry::changeFixedFrame(const FrameIndex newFixedFrame)
{
if( !this->m_kinematicsUpdated )
{
reportError("SimpleLeggedOdometry",
"changeFixedFrame",
"changeFixedFrame was called, but the kinematics info was never setted.");
return false;
}
LinkIndex newFixedLink = this->m_model.getFrameLink(newFixedFrame);
if( newFixedLink == LINK_INVALID_INDEX )
{
reportError("SimpleLeggedOdometry",
"changeFixedFrame",
"changeFixedFrame was called, but the provided new fixed frame is unknown.");
return false;
}
Transform world_H_oldFixed = this->m_world_H_fixedLink;
LinkIndex oldFixedLink = m_fixedLinkIndex;
Transform oldFixed_H_newFixed = m_base_H_link(oldFixedLink).inverse()*m_base_H_link(newFixedLink);
Transform world_H_newFixed = world_H_oldFixed*oldFixed_H_newFixed;
this->m_world_H_fixedLink = world_H_newFixed;
this->m_fixedLinkIndex = newFixedLink;
return true;
}
bool SimpleLeggedOdometry::changeFixedFrame(const std::string& newFixedFrame)
{
iDynTree::FrameIndex newFixedFrameIndex = this->m_model.getFrameIndex(newFixedFrame);
if( newFixedFrameIndex == FRAME_INVALID_INDEX )
{
reportError("SimpleLeggedOdometry",
"changeFixedFrame",
"changeFixedFrame was called, but the provided new fixed frame is unknown.");
return false;
}
return this->changeFixedFrame(newFixedFrameIndex);
}
Transform SimpleLeggedOdometry::getWorldLinkTransform(const LinkIndex link_index)
{
if( !this->m_kinematicsUpdated || !this->m_isOdometryInitialized )
{
reportError("SimpleLeggedOdometry",
"getWorldLinkTransform",
"getWorldLinkTransform was called, but the kinematics update or the odometry init was never setted.");
return Transform::Identity();
}
if( !this->m_model.isValidLinkIndex(link_index) )
{
reportError("SimpleLeggedOdometry",
"getWorldLinkTransform",
"getWorldLinkTransform was called, but the request linkindex is not part of the model");
return Transform::Identity();
}
std::cerr << m_fixedLinkIndex << std::endl;
std::cerr << m_base_H_link.getNrOfLinks() << std::endl;
assert(m_fixedLinkIndex < m_base_H_link.getNrOfLinks());
Transform base_H_fixed = m_base_H_link(m_fixedLinkIndex);
Transform base_H_link = m_base_H_link(link_index);
std::cerr << "base_H_fixed " << base_H_fixed.toString() << std::endl;
std::cerr << "base_H_link " << base_H_link.toString() << std::endl;
std::cerr << "m_world_H_fixedLink " << m_world_H_fixedLink.toString() << std::endl;
return m_world_H_fixedLink*base_H_fixed.inverse()*base_H_link;
}
}
<commit_msg>[estimation] Removed spurious prints<commit_after>/*
* Copyright (C) 2016 Fondazione Istituto Italiano di Tecnologia
* Authors: Silvio Traversaro
* CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
*
*/
#include <iDynTree/Core/EigenHelpers.h>
#include <iDynTree/Estimation/SimpleLeggedOdometry.h>
#include <iDynTree/Model/ForwardKinematics.h>
#include <iDynTree/Model/Indeces.h>
#include <iDynTree/Model/ModelTransformers.h>
#include <iDynTree/ModelIO/URDFModelImport.h>
#include <iDynTree/ModelIO/URDFGenericSensorsImport.h>
#include <sstream>
namespace iDynTree
{
SimpleLeggedOdometry::SimpleLeggedOdometry(): m_model(),
m_traversal(),
m_isModelValid(false),
m_kinematicsUpdated(false),
m_isOdometryInitialized(false),
m_fixedLinkIndex(iDynTree::LINK_INVALID_INDEX),
m_world_H_fixedLink(Transform::Identity())
{
}
SimpleLeggedOdometry::~SimpleLeggedOdometry()
{
}
bool SimpleLeggedOdometry::init(const std::string& initialFixedFrame,
const Transform& world_H_initialFixedFrame)
{
FrameIndex initialFixedFrameIndex = this->m_model.getFrameIndex(initialFixedFrame);
return init(initialFixedFrameIndex,world_H_initialFixedFrame);
}
bool SimpleLeggedOdometry::init(const FrameIndex initialFixedFrameIndex,
const Transform& world_H_initialFixedFrame)
{
if( !m_isModelValid )
{
reportError("SimpleLeggedOdometry",
"init",
"Model not initialised.");
return false;
}
if( !m_model.isValidFrameIndex(initialFixedFrameIndex) )
{
reportError("SimpleLeggedOdometry",
"init","invalid frame passed");
return false;
}
m_fixedLinkIndex = m_model.getFrameLink(initialFixedFrameIndex);
Transform initialFixedFrame_H_fixedLink = m_model.getFrameTransform(initialFixedFrameIndex).inverse();
m_world_H_fixedLink = world_H_initialFixedFrame*initialFixedFrame_H_fixedLink;
m_isOdometryInitialized = true;
return true;
}
bool SimpleLeggedOdometry::init(const std::string& initialFixedFrame,
const std::string& initialWorldFrame)
{
return this->init(m_model.getFrameIndex(initialFixedFrame),
m_model.getFrameIndex(initialWorldFrame));
}
bool SimpleLeggedOdometry::init(const FrameIndex initialFixedFrameIndex,
const FrameIndex initialWorldFrameIndex)
{
if( !m_isModelValid )
{
reportError("SimpleLeggedOdometry",
"init",
"Model not initialised.");
return false;
}
if( !m_model.isValidFrameIndex(initialFixedFrameIndex) ||
!m_model.isValidFrameIndex(initialWorldFrameIndex)
)
{
reportError("SimpleLeggedOdometry",
"init","invalid frame passed");
return false;
}
if( ! m_kinematicsUpdated )
{
reportError("SimpleLeggedOdometry",
"init","updateKinematics never called");
return false;
}
// Set the fixed link
m_fixedLinkIndex = m_model.getFrameLink(initialFixedFrameIndex);
// TODO : we need a simple class to get arbitrary transform in a model,
// something even simpler then KinDynComputations to address this
// kind of computation that appear from time to time
// Set the world_H_fixedLink transform
LinkIndex linkAttachedToWorldFrameIndex = m_model.getFrameLink(initialWorldFrameIndex);
Transform worldFrame_H_linkAttachedToWorldFrame = m_model.getFrameTransform(initialWorldFrameIndex).inverse();
Transform linkAttachedToWorldFrameIndex_H_floatingBase = m_base_H_link(linkAttachedToWorldFrameIndex).inverse();
Transform floatingBase_H_fixedLink = m_base_H_link(m_fixedLinkIndex);
m_world_H_fixedLink = worldFrame_H_linkAttachedToWorldFrame*linkAttachedToWorldFrameIndex_H_floatingBase*floatingBase_H_fixedLink;
m_isOdometryInitialized = true;
return true;
}
bool SimpleLeggedOdometry::updateKinematics(JointPosDoubleArray& jointPos)
{
if( !m_isModelValid )
{
reportError("SimpleLeggedOdometry",
"updateKinematics","model not valid");
return false;
}
if( !jointPos.isConsistent(m_model) )
{
reportError("SimpleLeggedOdometry",
"updateKinematics","error in size of input jointPos");
return false;
}
bool ok = ForwardPositionKinematics(m_model,m_traversal,
Transform::Identity(),jointPos,
m_base_H_link);
m_kinematicsUpdated = ok;
return ok;
}
const Model& SimpleLeggedOdometry::model() const
{
return m_model;
}
bool SimpleLeggedOdometry::setModel(const Model& _model)
{
m_model = _model;
// resize the data structures
m_model.computeFullTreeTraversal(m_traversal);
// set that the model is valid
m_isModelValid = true;
// Set the kinematics and the odometry is not initialized
m_isOdometryInitialized = false;
m_kinematicsUpdated = false;
// Resize the linkPositions
m_base_H_link.resize(m_model);
return true;
}
bool SimpleLeggedOdometry::loadModelFromFile(const std::string filename,
const std::string /*filetype*/)
{
Model _model;
bool parsingCorrect = false;
parsingCorrect = modelFromURDF(filename,_model);
if( !parsingCorrect )
{
reportError("SimpleLeggedOdometry",
"loadModelFromFile",
"Error in parsing model from URDF.");
return false;
}
return setModel(_model);
}
bool SimpleLeggedOdometry::loadModelFromFileWithSpecifiedDOFs(const std::string filename,
const std::vector< std::string >& consideredDOFs,
const std::string filetype)
{
Model _modelFull;
bool parsingCorrect = false;
parsingCorrect = modelFromURDF(filename,_modelFull);
if( !parsingCorrect )
{
reportError("SimpleLeggedOdometry",
"loadModelFromFileWithSpecifiedDOFs",
"Error in parsing model from URDF.");
return false;
}
Model _modelReduced;
// Create a reduced model: this will lump all not considered joints
iDynTree::createReducedModel(_modelFull,consideredDOFs,_modelReduced);
return setModel(_modelReduced);
}
std::string SimpleLeggedOdometry::getCurrentFixedLink()
{
if( this->m_isModelValid && this->m_isOdometryInitialized )
{
return this->m_model.getLinkName(this->m_fixedLinkIndex);
}
else
{
reportError("SimpleLeggedOdometry",
"getCurrentFixedLink",
"getCurrentFixedLink was called, but no model is available or the odometry is not initialized.");
return "";
}
}
bool SimpleLeggedOdometry::changeFixedFrame(const FrameIndex newFixedFrame)
{
if( !this->m_kinematicsUpdated )
{
reportError("SimpleLeggedOdometry",
"changeFixedFrame",
"changeFixedFrame was called, but the kinematics info was never setted.");
return false;
}
LinkIndex newFixedLink = this->m_model.getFrameLink(newFixedFrame);
if( newFixedLink == LINK_INVALID_INDEX )
{
reportError("SimpleLeggedOdometry",
"changeFixedFrame",
"changeFixedFrame was called, but the provided new fixed frame is unknown.");
return false;
}
Transform world_H_oldFixed = this->m_world_H_fixedLink;
LinkIndex oldFixedLink = m_fixedLinkIndex;
Transform oldFixed_H_newFixed = m_base_H_link(oldFixedLink).inverse()*m_base_H_link(newFixedLink);
Transform world_H_newFixed = world_H_oldFixed*oldFixed_H_newFixed;
this->m_world_H_fixedLink = world_H_newFixed;
this->m_fixedLinkIndex = newFixedLink;
return true;
}
bool SimpleLeggedOdometry::changeFixedFrame(const std::string& newFixedFrame)
{
iDynTree::FrameIndex newFixedFrameIndex = this->m_model.getFrameIndex(newFixedFrame);
if( newFixedFrameIndex == FRAME_INVALID_INDEX )
{
reportError("SimpleLeggedOdometry",
"changeFixedFrame",
"changeFixedFrame was called, but the provided new fixed frame is unknown.");
return false;
}
return this->changeFixedFrame(newFixedFrameIndex);
}
Transform SimpleLeggedOdometry::getWorldLinkTransform(const LinkIndex link_index)
{
if( !this->m_kinematicsUpdated || !this->m_isOdometryInitialized )
{
reportError("SimpleLeggedOdometry",
"getWorldLinkTransform",
"getWorldLinkTransform was called, but the kinematics update or the odometry init was never setted.");
return Transform::Identity();
}
if( !this->m_model.isValidLinkIndex(link_index) )
{
reportError("SimpleLeggedOdometry",
"getWorldLinkTransform",
"getWorldLinkTransform was called, but the request linkindex is not part of the model");
return Transform::Identity();
}
assert(m_fixedLinkIndex < m_base_H_link.getNrOfLinks());
Transform base_H_fixed = m_base_H_link(m_fixedLinkIndex);
Transform base_H_link = m_base_H_link(link_index);
return m_world_H_fixedLink*base_H_fixed.inverse()*base_H_link;
}
}
<|endoftext|> |
<commit_before>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* 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.
*
* \file mbed_usbserial.cpp
* This file implements an USB-Serial driver on top of the mbed
* library. Currently it is tested on the LPC23xx processors.
*
* @author Balazs Racz
* @date 4 May 2013
*/
#include "mbed.h"
#include "USBSerial.h"
#include "serial.h"
#include "os/os.h"
#ifdef TARGET_LPC2368
#endif
#define TX_DATA_SIZE 64
#define RX_DATA_SIZE 64
#include <stdlib.h>
void * operator new(size_t size);
void * operator new[](size_t size);
void operator delete(void * ptr);
void operator delete[](void * ptr);
__extension__ typedef int __guard __attribute__((mode (__DI__)));
extern "C" int __cxa_guard_acquire(__guard *);
extern "C" void __cxa_guard_release (__guard *);
extern "C" void __cxa_guard_abort (__guard *);
extern "C" void __cxa_pure_virtual(void);
/** This class is an empty wrapper around MBed's USB CDC class. The difference
between this and mbed::USBSerial is that this class does not have any
buffering and no interaction with stdio, whereas mbed::USBSerial has the
following buffering:
* it has a 128-byte receive buffer.
* it has an fd
* it has a FILE* with a default-sized send/receive buffer
* it requires mbed's custom glue code in the open(2) method, without which
it crashes.
*/
class MbedRawUSBSerial : public USBCDC
{
public:
MbedRawUSBSerial(SerialPriv* serialPriv, uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001): USBCDC(vendor_id, product_id, product_release), serialPriv(serialPriv), txPending(false)
{
os_sem_init(&rxSem, 0);
os_thread_t thread;
os_thread_create(&thread, "usbserial.rx", 2, 1024, &_RxThread, this);
}
~MbedRawUSBSerial()
{
os_sem_destroy(&rxSem);
}
void Transmit()
{
if (txPending) return;
txPending = true;
// At this point we know there is no outstading send, thus there can't
// be an incoming TX interrupt either. Thus we don't need a critical
// section.
int count;
for (count = 0; count < TX_DATA_SIZE; count++)
{
if (os_mq_timedreceive(serialPriv->txQ, txData+count, 0) != OS_MQ_NONE)
{
/* no more data left to transmit */
break;
}
}
TxHelper(count);
}
protected:
virtual bool EP2_OUT_callback()
{
// we read the packet received to our assembly buffer
readEP(rxData, &rxSize);
// and wake up the RX thread.
os_sem_post_from_isr(&rxSem);
return true;
}
virtual bool EP2_IN_callback()
{
int count;
for (count = 0; count < MAX_TX_PACKET_LENGTH; count++)
{
if (os_mq_receive_from_isr(serialPriv->txQ, &txData[count]) != OS_MQ_NONE)
{
/* no more data left to transmit */
break;
}
}
TxHelper(count);
return true;
}
private:
static const int MAX_TX_PACKET_LENGTH = 64;
static const int MAX_RX_PACKET_LENGTH = 64;
/** Transmits count bytes from the txData buffer. Sets txPending and
bytesLost as needed. */
void TxHelper(int count)
{
if (!count)
{
txPending = false;
return;
}
if ((!configured()) ||
(!terminal_connected))
{
// An error occured, data was lost.
txPending = false;
serialPriv->overrunCount += count;
return;
}
sendNB(txData, count);
txPending = true;
}
void RxThread()
{
while(1)
{
os_sem_wait(&rxSem);
for (uint32_t i = 0; i < rxSize; i++)
{
os_mq_send(serialPriv->rxQ, rxData+i);
}
// We reactivate the endpoint to receive next characters
readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
}
}
static void* _RxThread(void* arg)
{
((MbedRawUSBSerial*)arg)->RxThread();
return NULL;
}
uint8_t txData[MAX_TX_PACKET_LENGTH]; /**< packet assemby buffer to host */
uint32_t rxSize; /**< number of valis characters in rxData */
uint8_t rxData[MAX_RX_PACKET_LENGTH]; /**< packet assembly buffer from host */
SerialPriv* serialPriv;
bool txPending; /**< transmission currently pending */
os_sem_t rxSem;
};
/** Private data for this implementation of Serial port
*/
class MbedSerialPriv
{
public:
MbedSerialPriv() : serial(NULL) {}
SerialPriv serialPriv; /**< common private data */
MbedRawUSBSerial* serial; /*< USB implementation object */
};
/** private data for the can device */
static MbedSerialPriv serial_private[1];
static int mbed_usbserial_init(devtab_t *dev);
static void ignore_dev_function(devtab_t *dev);
static void mbed_usbserial_tx_msg(devtab_t *dev);
void * operator new(size_t size)
{
return malloc(size);
}
void * operator new[](size_t size)
{
return malloc(size);
}
void operator delete(void * ptr)
{
free(ptr);
}
void operator delete[](void * ptr)
{
free(ptr);
}
int __cxa_guard_acquire(__guard *g) {return !*(char *)(g);};
void __cxa_guard_release (__guard *g) {*(char *)g = 1;};
void __cxa_guard_abort (__guard *) {};
void __cxa_pure_virtual(void) {};
/** initialize the device
* @param dev device to initialize
* @return 0 upon success
*/
static int mbed_usbserial_init(devtab_t *dev)
{
MbedSerialPriv *priv = (MbedSerialPriv*)dev->priv;
int r = serial_init(dev);
if (r) return r;
priv->serial = new MbedRawUSBSerial(&priv->serialPriv);
priv->serialPriv.enable = ignore_dev_function;
priv->serialPriv.disable = ignore_dev_function;
priv->serialPriv.tx_char = mbed_usbserial_tx_msg;
//priv->serial->attach(priv, &MbedSerialPriv::RxCallback);
//priv->serial->txattach(priv, &MbedSerialPriv::TxCallback);
return r;
}
/** Empty device function. Does nothing.
* @param dev device
*/
static void ignore_dev_function(devtab_t *dev) {}
/** Try and transmit a message. Does nothing if there is no message to transmit
* or no write buffers to transmit via.
* @param dev device to transmit message on
*/
static void mbed_usbserial_tx_msg(devtab_t *dev)
{
MbedSerialPriv *priv = (MbedSerialPriv*)dev->priv;
priv->serial->Transmit();
}
/** Device table entry for serial device */
static SERIAL_DEVTAB_ENTRY(serUSB0, "/dev/serUSB0", mbed_usbserial_init, &serial_private[0]);
<commit_msg>Fixes a race condition in the MBED usbserial implementation.<commit_after>/** \copyright
* Copyright (c) 2013, Balazs Racz
* 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.
*
* 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.
*
* \file mbed_usbserial.cpp
* This file implements an USB-Serial driver on top of the mbed
* library. Currently it is tested on the LPC23xx processors.
*
* @author Balazs Racz
* @date 4 May 2013
*/
#include "mbed.h"
#include "USBSerial.h"
#include "serial.h"
#include "os/os.h"
#ifdef TARGET_LPC2368
#endif
#define TX_DATA_SIZE 64
#define RX_DATA_SIZE 64
#include <stdlib.h>
void * operator new(size_t size);
void * operator new[](size_t size);
void operator delete(void * ptr);
void operator delete[](void * ptr);
__extension__ typedef int __guard __attribute__((mode (__DI__)));
extern "C" int __cxa_guard_acquire(__guard *);
extern "C" void __cxa_guard_release (__guard *);
extern "C" void __cxa_guard_abort (__guard *);
extern "C" void __cxa_pure_virtual(void);
/** This class is an empty wrapper around MBed's USB CDC class. The difference
between this and mbed::USBSerial is that this class does not have any
buffering and no interaction with stdio, whereas mbed::USBSerial has the
following buffering:
* it has a 128-byte receive buffer.
* it has an fd
* it has a FILE* with a default-sized send/receive buffer
* it requires mbed's custom glue code in the open(2) method, without which
it crashes.
*/
class MbedRawUSBSerial : public USBCDC
{
public:
MbedRawUSBSerial(SerialPriv* serialPriv, uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001): USBCDC(vendor_id, product_id, product_release), serialPriv(serialPriv), txPending(false)
{
os_sem_init(&rxSem, 0);
os_thread_t thread;
os_thread_create(&thread, "usbserial.rx", 2, 1024, &_RxThread, this);
}
~MbedRawUSBSerial()
{
os_sem_destroy(&rxSem);
}
void Transmit()
{
// Without this critical section there were cases when we deadlocked
// with txPending == true but no interrupt coming in to clear it.
taskENTER_CRITICAL();
if (txPending) {
taskEXIT_CRITICAL();
return;
}
txPending = true;
int count;
for (count = 0; count < TX_DATA_SIZE; count++)
{
if (os_mq_timedreceive(serialPriv->txQ, txData+count, 0) != OS_MQ_NONE)
{
/* no more data left to transmit */
break;
}
}
TxHelper(count);
taskEXIT_CRITICAL();
}
protected:
virtual bool EP2_OUT_callback()
{
// we read the packet received to our assembly buffer
readEP(rxData, &rxSize);
// and wake up the RX thread.
os_sem_post_from_isr(&rxSem);
return true;
}
virtual bool EP2_IN_callback()
{
int count;
configASSERT(txPending);
for (count = 0; count < MAX_TX_PACKET_LENGTH; count++)
{
if (os_mq_receive_from_isr(serialPriv->txQ, &txData[count]) != OS_MQ_NONE)
{
/* no more data left to transmit */
break;
}
}
TxHelper(count);
return true;
}
private:
static const int MAX_TX_PACKET_LENGTH = 64;
static const int MAX_RX_PACKET_LENGTH = 64;
/** Transmits count bytes from the txData buffer. Sets txPending and
bytesLost as needed. */
void TxHelper(int count)
{
if (!count)
{
txPending = false;
return;
}
if ((!configured()) ||
(!terminal_connected))
{
// An error occured, data was lost.
txPending = false;
serialPriv->overrunCount += count;
return;
}
txPending = true;
sendNB(txData, count);
}
void RxThread()
{
while(1)
{
os_sem_wait(&rxSem);
for (uint32_t i = 0; i < rxSize; i++)
{
os_mq_send(serialPriv->rxQ, rxData+i);
}
// We reactivate the endpoint to receive next characters
readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
}
}
static void* _RxThread(void* arg)
{
((MbedRawUSBSerial*)arg)->RxThread();
return NULL;
}
uint8_t txData[MAX_TX_PACKET_LENGTH]; /**< packet assemby buffer to host */
uint32_t rxSize; /**< number of valis characters in rxData */
uint8_t rxData[MAX_RX_PACKET_LENGTH]; /**< packet assembly buffer from host */
SerialPriv* serialPriv;
bool txPending; /**< transmission currently pending */
os_sem_t rxSem;
};
/** Private data for this implementation of Serial port
*/
class MbedSerialPriv
{
public:
MbedSerialPriv() : serial(NULL) {}
SerialPriv serialPriv; /**< common private data */
MbedRawUSBSerial* serial; /*< USB implementation object */
};
/** private data for the can device */
static MbedSerialPriv serial_private[1];
static int mbed_usbserial_init(devtab_t *dev);
static void ignore_dev_function(devtab_t *dev);
static void mbed_usbserial_tx_msg(devtab_t *dev);
void * operator new(size_t size)
{
return malloc(size);
}
void * operator new[](size_t size)
{
return malloc(size);
}
void operator delete(void * ptr)
{
free(ptr);
}
void operator delete[](void * ptr)
{
free(ptr);
}
int __cxa_guard_acquire(__guard *g) {return !*(char *)(g);};
void __cxa_guard_release (__guard *g) {*(char *)g = 1;};
void __cxa_guard_abort (__guard *) {};
void __cxa_pure_virtual(void) {};
/** initialize the device
* @param dev device to initialize
* @return 0 upon success
*/
static int mbed_usbserial_init(devtab_t *dev)
{
MbedSerialPriv *priv = (MbedSerialPriv*)dev->priv;
int r = serial_init(dev);
if (r) return r;
priv->serial = new MbedRawUSBSerial(&priv->serialPriv);
priv->serialPriv.enable = ignore_dev_function;
priv->serialPriv.disable = ignore_dev_function;
priv->serialPriv.tx_char = mbed_usbserial_tx_msg;
//priv->serial->attach(priv, &MbedSerialPriv::RxCallback);
//priv->serial->txattach(priv, &MbedSerialPriv::TxCallback);
return r;
}
/** Empty device function. Does nothing.
* @param dev device
*/
static void ignore_dev_function(devtab_t *dev) {}
/** Try and transmit a message. Does nothing if there is no message to transmit
* or no write buffers to transmit via.
* @param dev device to transmit message on
*/
static void mbed_usbserial_tx_msg(devtab_t *dev)
{
MbedSerialPriv *priv = (MbedSerialPriv*)dev->priv;
priv->serial->Transmit();
}
/** Device table entry for serial device */
static SERIAL_DEVTAB_ENTRY(serUSB0, "/dev/serUSB0", mbed_usbserial_init, &serial_private[0]);
<|endoftext|> |
<commit_before>// See: CodinGame demo interview question
#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
int main()
{
std::vector<double> v = {1.0, 2.0, 3.0};
auto min_value = *std::min_element(std::begin(v), std::end(v));
std::cout << "Minimal value: " << min_value << "\n";
return 0;
}
<commit_msg>Use uniform initialization syntax.<commit_after>// See: CodinGame demo interview question
#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
int main()
{
std::vector<double> v{1.0, 2.0, 3.0};
auto min_value = *std::min_element(std::begin(v), std::end(v));
std::cout << "Minimal value: " << min_value << "\n";
return 0;
}
<|endoftext|> |
<commit_before>//===--------------------------- new.cpp ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#define _LIBCPP_BUILDING_NEW
#include <stdlib.h>
#include "new"
#if defined(__APPLE__) && !defined(LIBCXXRT) && \
!defined(_LIBCPP_BUILDING_HAS_NO_ABI_LIBRARY)
#include <cxxabi.h>
#ifndef _LIBCPPABI_VERSION
// On Darwin, there are two STL shared libraries and a lower level ABI
// shared library. The global holding the current new handler is
// in the ABI library and named __cxa_new_handler.
#define __new_handler __cxxabiapple::__cxa_new_handler
#endif
#else // __APPLE__
#if defined(LIBCXXRT) || defined(LIBCXX_BUILDING_LIBCXXABI)
#include <cxxabi.h>
#endif // defined(LIBCXX_BUILDING_LIBCXXABI)
#if defined(_LIBCPP_BUILDING_HAS_NO_ABI_LIBRARY) || \
(!defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__))
static std::new_handler __new_handler;
#endif // _LIBCPPABI_VERSION
#endif
#ifndef __GLIBCXX__
// Implement all new and delete operators as weak definitions
// in this shared library, so that they can be overridden by programs
// that define non-weak copies of the functions.
_LIBCPP_WEAK
void *
operator new(std::size_t size) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
void* p;
while ((p = ::malloc(size)) == 0)
{
// If malloc fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
break;
#endif
}
return p;
}
_LIBCPP_WEAK
void *
operator new(std::size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
if (static_cast<size_t>(alignment) < sizeof(void*))
alignment = std::align_val_t(sizeof(void*));
void* p;
#if defined(_LIBCPP_MSVCRT)
while ((p = _aligned_malloc(size, static_cast<size_t>(alignment))) == nullptr)
#else
while (::posix_memalign(&p, static_cast<size_t>(alignment), size) != 0)
#endif
{
// If posix_memalign fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else {
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
p = nullptr; // posix_memalign doesn't initialize 'p' on failure
break;
#endif
}
}
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size) _THROW_BAD_ALLOC
{
return ::operator new(size);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
return ::operator new(size, alignment);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void
operator delete(void* ptr) _NOEXCEPT
{
if (ptr)
::free(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t) _NOEXCEPT
{
if (ptr)
#if defined(_LIBCPP_MSVCRT)
::_aligned_free(ptr);
#else
::free(ptr);
#endif
}
_LIBCPP_WEAK
void
operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t) _NOEXCEPT
{
::operator delete[](ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
#endif // !__GLIBCXX__
namespace std
{
#ifndef __GLIBCXX__
const nothrow_t nothrow = {};
#endif
#ifndef _LIBCPPABI_VERSION
#ifndef __GLIBCXX__
new_handler
set_new_handler(new_handler handler) _NOEXCEPT
{
return __sync_lock_test_and_set(&__new_handler, handler);
}
new_handler
get_new_handler() _NOEXCEPT
{
return __sync_fetch_and_add(&__new_handler, nullptr);
}
#endif // !__GLIBCXX__
#ifndef LIBCXXRT
bad_alloc::bad_alloc() _NOEXCEPT
{
}
#ifndef __GLIBCXX__
bad_alloc::~bad_alloc() _NOEXCEPT
{
}
const char*
bad_alloc::what() const _NOEXCEPT
{
return "std::bad_alloc";
}
#endif // !__GLIBCXX__
bad_array_new_length::bad_array_new_length() _NOEXCEPT
{
}
#ifndef __GLIBCXX__
bad_array_new_length::~bad_array_new_length() _NOEXCEPT
{
}
const char*
bad_array_new_length::what() const _NOEXCEPT
{
return "bad_array_new_length";
}
#endif // !__GLIBCXX__
#endif //LIBCXXRT
bad_array_length::bad_array_length() _NOEXCEPT
{
}
#ifndef __GLIBCXX__
bad_array_length::~bad_array_length() _NOEXCEPT
{
}
const char*
bad_array_length::what() const _NOEXCEPT
{
return "bad_array_length";
}
#endif // !__GLIBCXX__
#endif // _LIBCPPABI_VERSION
#ifndef LIBSTDCXX
void
__throw_bad_alloc()
{
#ifndef _LIBCPP_NO_EXCEPTIONS
throw bad_alloc();
#else
_VSTD::abort();
#endif
}
#endif // !LIBSTDCXX
} // std
<commit_msg>[NFC] Group aligned new/delete definitions together in new.cpp<commit_after>//===--------------------------- new.cpp ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#define _LIBCPP_BUILDING_NEW
#include <stdlib.h>
#include "new"
#if defined(__APPLE__) && !defined(LIBCXXRT) && \
!defined(_LIBCPP_BUILDING_HAS_NO_ABI_LIBRARY)
#include <cxxabi.h>
#ifndef _LIBCPPABI_VERSION
// On Darwin, there are two STL shared libraries and a lower level ABI
// shared library. The global holding the current new handler is
// in the ABI library and named __cxa_new_handler.
#define __new_handler __cxxabiapple::__cxa_new_handler
#endif
#else // __APPLE__
#if defined(LIBCXXRT) || defined(LIBCXX_BUILDING_LIBCXXABI)
#include <cxxabi.h>
#endif // defined(LIBCXX_BUILDING_LIBCXXABI)
#if defined(_LIBCPP_BUILDING_HAS_NO_ABI_LIBRARY) || \
(!defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__))
static std::new_handler __new_handler;
#endif // _LIBCPPABI_VERSION
#endif
#ifndef __GLIBCXX__
// Implement all new and delete operators as weak definitions
// in this shared library, so that they can be overridden by programs
// that define non-weak copies of the functions.
_LIBCPP_WEAK
void *
operator new(std::size_t size) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
void* p;
while ((p = ::malloc(size)) == 0)
{
// If malloc fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
break;
#endif
}
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size) _THROW_BAD_ALLOC
{
return ::operator new(size);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void
operator delete(void* ptr) _NOEXCEPT
{
if (ptr)
::free(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr) _NOEXCEPT
{
::operator delete(ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t) _NOEXCEPT
{
::operator delete[](ptr);
}
_LIBCPP_WEAK
void *
operator new(std::size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
if (size == 0)
size = 1;
if (static_cast<size_t>(alignment) < sizeof(void*))
alignment = std::align_val_t(sizeof(void*));
void* p;
#if defined(_LIBCPP_MSVCRT)
while ((p = _aligned_malloc(size, static_cast<size_t>(alignment))) == nullptr)
#else
while (::posix_memalign(&p, static_cast<size_t>(alignment), size) != 0)
#endif
{
// If posix_memalign fails and there is a new_handler,
// call it to try free up memory.
std::new_handler nh = std::get_new_handler();
if (nh)
nh();
else {
#ifndef _LIBCPP_NO_EXCEPTIONS
throw std::bad_alloc();
#else
p = nullptr; // posix_memalign doesn't initialize 'p' on failure
break;
#endif
}
}
return p;
}
_LIBCPP_WEAK
void*
operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new(size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment) _THROW_BAD_ALLOC
{
return ::operator new(size, alignment);
}
_LIBCPP_WEAK
void*
operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
void* p = 0;
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
p = ::operator new[](size, alignment);
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
return p;
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t) _NOEXCEPT
{
if (ptr)
#if defined(_LIBCPP_MSVCRT)
::_aligned_free(ptr);
#else
::free(ptr);
#endif
}
_LIBCPP_WEAK
void
operator delete(void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete(void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment) _NOEXCEPT
{
::operator delete(ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, std::align_val_t alignment, const std::nothrow_t&) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
_LIBCPP_WEAK
void
operator delete[] (void* ptr, size_t, std::align_val_t alignment) _NOEXCEPT
{
::operator delete[](ptr, alignment);
}
#endif // !__GLIBCXX__
namespace std
{
#ifndef __GLIBCXX__
const nothrow_t nothrow = {};
#endif
#ifndef _LIBCPPABI_VERSION
#ifndef __GLIBCXX__
new_handler
set_new_handler(new_handler handler) _NOEXCEPT
{
return __sync_lock_test_and_set(&__new_handler, handler);
}
new_handler
get_new_handler() _NOEXCEPT
{
return __sync_fetch_and_add(&__new_handler, nullptr);
}
#endif // !__GLIBCXX__
#ifndef LIBCXXRT
bad_alloc::bad_alloc() _NOEXCEPT
{
}
#ifndef __GLIBCXX__
bad_alloc::~bad_alloc() _NOEXCEPT
{
}
const char*
bad_alloc::what() const _NOEXCEPT
{
return "std::bad_alloc";
}
#endif // !__GLIBCXX__
bad_array_new_length::bad_array_new_length() _NOEXCEPT
{
}
#ifndef __GLIBCXX__
bad_array_new_length::~bad_array_new_length() _NOEXCEPT
{
}
const char*
bad_array_new_length::what() const _NOEXCEPT
{
return "bad_array_new_length";
}
#endif // !__GLIBCXX__
#endif //LIBCXXRT
bad_array_length::bad_array_length() _NOEXCEPT
{
}
#ifndef __GLIBCXX__
bad_array_length::~bad_array_length() _NOEXCEPT
{
}
const char*
bad_array_length::what() const _NOEXCEPT
{
return "bad_array_length";
}
#endif // !__GLIBCXX__
#endif // _LIBCPPABI_VERSION
#ifndef LIBSTDCXX
void
__throw_bad_alloc()
{
#ifndef _LIBCPP_NO_EXCEPTIONS
throw bad_alloc();
#else
_VSTD::abort();
#endif
}
#endif // !LIBSTDCXX
} // std
<|endoftext|> |
<commit_before>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 AiiiiiiiiiiiNY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include <boost/assign.hpp>
#include <ubiquity_motor/motor_hardware.h>
#include <ubiquity_motor/motor_message.h>
#include <boost/math/special_functions/round.hpp>
//#define SENSOR_DISTANCE 0.002478
// 60 tics per revolution of the motor (pre gearbox)
//17.2328767123
// gear ratio of 4.29411764706:1
#define TICS_PER_RADIAN (41.0058030317/2)
#define SECONDS_PER_VELOCITY_READ 10.0 //read = ticks / (100 ms), so we have scale of 10 for ticks/second
#define CURRENT_FIRMWARE_VERSION 18
MotorHardware::MotorHardware(ros::NodeHandle nh){
ros::V_string joint_names = boost::assign::list_of("left_wheel_joint")("right_wheel_joint");
for (unsigned int i = 0; i < joint_names.size(); i++) {
hardware_interface::JointStateHandle joint_state_handle(joint_names[i],
&joints_[i].position, &joints_[i].velocity, &joints_[i].effort);
joint_state_interface_.registerHandle(joint_state_handle);
hardware_interface::JointHandle joint_handle(
joint_state_handle, &joints_[i].velocity_command);
velocity_joint_interface_.registerHandle(joint_handle);
}
registerInterface(&joint_state_interface_);
registerInterface(&velocity_joint_interface_);
std::string sPort;
int sBaud;
double sLoopRate;
if (!nh.getParam("ubiquity_motor/serial_port", sPort))
{
sPort.assign("/dev/ttyS0");
nh.setParam("ubiquity_motor/serial_port", sPort);
}
if (!nh.getParam("ubiquity_motor/serial_baud", sBaud))
{
sBaud = 9600;
nh.setParam("ubiquity_motor/serial_baud", sBaud);
}
if (!nh.getParam("ubiquity_motor/serial_loop_rate", sLoopRate))
{
sLoopRate = 100;
nh.setParam("ubiquity_motor/serial_loop_rate", sLoopRate);
}
motor_serial_ = new MotorSerial(sPort,sBaud,sLoopRate);
}
MotorHardware::~MotorHardware(){
delete motor_serial_;
}
void MotorHardware::readInputs(){
while(motor_serial_->commandAvailable()){
MotorMessage mm;
mm = motor_serial_-> receiveCommand();
if(mm.getType() == MotorMessage::TYPE_RESPONSE){
switch(mm.getRegister()){
case MotorMessage::REG_FIRMWARE_VERSION:
if (!mm.getData() > CURRENT_FIRMWARE_VERSION) {
ROS_FATAL("Firmware version %d, expect %d or above",
mm.getData(), CURRENT_FIRMWARE_VERSION);
}
else {
ROS_INFO("Firmware version %d", mm.getData());
}
break;
case MotorMessage::REG_LEFT_ODOM:
joints_[0].position += mm.getData()/TICS_PER_RADIAN;
break;
case MotorMessage::REG_RIGHT_ODOM:
joints_[1].position += mm.getData()/TICS_PER_RADIAN;
break;
case MotorMessage::REG_LEFT_SPEED_MEASURED:
joints_[0].velocity = mm.getData()*SECONDS_PER_VELOCITY_READ/TICS_PER_RADIAN;
break;
case MotorMessage::REG_RIGHT_SPEED_MEASURED:
joints_[1].velocity = mm.getData()*SECONDS_PER_VELOCITY_READ/TICS_PER_RADIAN;
break;
default:
ROS_ERROR("Got type: 0x%02x, handling not implemented", mm.getRegister());
}
}
}
}
void MotorHardware::writeSpeeds(){
std::vector<MotorMessage> commands(6);
//requestOdometry();
//requestVelocity();
//requestVersion();
MotorMessage left_odom;
left_odom.setRegister(MotorMessage::REG_LEFT_ODOM);
left_odom.setType(MotorMessage::TYPE_READ);
left_odom.setData(0);
commands.push_back(left_odom);
MotorMessage right_odom;
right_odom.setRegister(MotorMessage::REG_RIGHT_ODOM);
right_odom.setType(MotorMessage::TYPE_READ);
right_odom.setData(0);
commands.push_back(right_odom);
MotorMessage left_vel;
left_vel.setRegister(MotorMessage::REG_LEFT_SPEED_MEASURED);
left_vel.setType(MotorMessage::TYPE_READ);
left_vel.setData(0);
commands.push_back(left_vel);
MotorMessage right_vel;
right_vel.setRegister(MotorMessage::REG_RIGHT_SPEED_MEASURED);
right_vel.setType(MotorMessage::TYPE_READ);
right_vel.setData(0);
commands.push_back(right_vel);
MotorMessage left;
left.setRegister(MotorMessage::REG_LEFT_SPEED_SET);
left.setType(MotorMessage::TYPE_WRITE);
left.setData(boost::math::lround(joints_[0].velocity_command*TICS_PER_RADIAN/SECONDS_PER_VELOCITY_READ));
commands.push_back(left);
MotorMessage right;
right.setRegister(MotorMessage::REG_RIGHT_SPEED_SET);
right.setType(MotorMessage::TYPE_WRITE);
right.setData(boost::math::lround(joints_[1].velocity_command*TICS_PER_RADIAN/SECONDS_PER_VELOCITY_READ));
commands.push_back(right);
//Send all commands to serial thread in one go to reduce locking
motor_serial_->transmitCommands(commands);
//ROS_ERROR("velocity_command %f rad/s %f rad/s", joints_[0].velocity_command, joints_[1].velocity_command);
// ROS_ERROR("SPEEDS %d %d", left.getData(), right.getData());
}
void MotorHardware::requestVersion(){
MotorMessage version;
version.setRegister(MotorMessage::REG_FIRMWARE_VERSION);
version.setType(MotorMessage::TYPE_READ);
version.setData(0);
motor_serial_->transmitCommand(version);
}
void MotorHardware::requestOdometry(){
std::vector<MotorMessage> commands;
_addOdometryRequest(commands);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::requestVelocity(){
std::vector<MotorMessage> commands;
_addVelocityRequest(commands);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::setPid(int32_t p_set, int32_t i_set, int32_t d_set, int32_t denominator_set){
p_value = p_set;
i_value = i_set;
d_value = d_set;
denominator_value = denominator_set;
}
void MotorHardware::sendPid() {
std::vector<MotorMessage> commands(4);
MotorMessage p;
p.setRegister(MotorMessage::REG_PARAM_P);
p.setType(MotorMessage::TYPE_WRITE);
p.setData(p_value);
commands.push_back(p);
MotorMessage i;
i.setRegister(MotorMessage::REG_PARAM_I);
i.setType(MotorMessage::TYPE_WRITE);
i.setData(i_value);
commands.push_back(i);
MotorMessage d;
d.setRegister(MotorMessage::REG_PARAM_D);
d.setType(MotorMessage::TYPE_WRITE);
d.setData(d_value);
commands.push_back(d);
MotorMessage denominator;
denominator.setRegister(MotorMessage::REG_PARAM_C);
denominator.setType(MotorMessage::TYPE_WRITE);
denominator.setData(denominator_value);
commands.push_back(denominator);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::setDebugLeds(bool led_1, bool led_2) {
std::vector<MotorMessage> commands(2);
MotorMessage led1;
led1.setRegister(MotorMessage::REG_LED_1);
led1.setType(MotorMessage::TYPE_WRITE);
if(led_1) {
led1.setData(0x00000001);
}
else {
led1.setData(0x00000000);
}
commands.push_back(led1);
MotorMessage led2;
led2.setRegister(MotorMessage::REG_LED_2);
led2.setType(MotorMessage::TYPE_WRITE);
if(led_2) {
led2.setData(0x00000001);
}
else {
led2.setData(0x00000000);
}
commands.push_back(led2);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::_addOdometryRequest(std::vector<MotorMessage>& commands) const{
MotorMessage left_odom;
left_odom.setRegister(MotorMessage::REG_LEFT_ODOM);
left_odom.setType(MotorMessage::TYPE_READ);
left_odom.setData(0);
commands.push_back(left_odom);
MotorMessage right_odom;
right_odom.setRegister(MotorMessage::REG_RIGHT_ODOM);
right_odom.setType(MotorMessage::TYPE_READ);
right_odom.setData(0);
commands.push_back(right_odom);
}
void MotorHardware::_addVelocityRequest(std::vector<MotorMessage>& commands) const{
MotorMessage left_vel;
left_vel.setRegister(MotorMessage::REG_LEFT_SPEED_MEASURED);
left_vel.setType(MotorMessage::TYPE_READ);
left_vel.setData(0);
commands.push_back(left_vel);
MotorMessage right_vel;
right_vel.setRegister(MotorMessage::REG_RIGHT_SPEED_MEASURED);
right_vel.setType(MotorMessage::TYPE_READ);
right_vel.setData(0);
commands.push_back(right_vel);
}<commit_msg>use add request functions instead of duplicated code<commit_after>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 AiiiiiiiiiiiNY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#include <boost/assign.hpp>
#include <ubiquity_motor/motor_hardware.h>
#include <ubiquity_motor/motor_message.h>
#include <boost/math/special_functions/round.hpp>
//#define SENSOR_DISTANCE 0.002478
// 60 tics per revolution of the motor (pre gearbox)
//17.2328767123
// gear ratio of 4.29411764706:1
#define TICS_PER_RADIAN (41.0058030317/2)
#define SECONDS_PER_VELOCITY_READ 10.0 //read = ticks / (100 ms), so we have scale of 10 for ticks/second
#define CURRENT_FIRMWARE_VERSION 18
MotorHardware::MotorHardware(ros::NodeHandle nh){
ros::V_string joint_names = boost::assign::list_of("left_wheel_joint")("right_wheel_joint");
for (unsigned int i = 0; i < joint_names.size(); i++) {
hardware_interface::JointStateHandle joint_state_handle(joint_names[i],
&joints_[i].position, &joints_[i].velocity, &joints_[i].effort);
joint_state_interface_.registerHandle(joint_state_handle);
hardware_interface::JointHandle joint_handle(
joint_state_handle, &joints_[i].velocity_command);
velocity_joint_interface_.registerHandle(joint_handle);
}
registerInterface(&joint_state_interface_);
registerInterface(&velocity_joint_interface_);
std::string sPort;
int sBaud;
double sLoopRate;
if (!nh.getParam("ubiquity_motor/serial_port", sPort))
{
sPort.assign("/dev/ttyS0");
nh.setParam("ubiquity_motor/serial_port", sPort);
}
if (!nh.getParam("ubiquity_motor/serial_baud", sBaud))
{
sBaud = 9600;
nh.setParam("ubiquity_motor/serial_baud", sBaud);
}
if (!nh.getParam("ubiquity_motor/serial_loop_rate", sLoopRate))
{
sLoopRate = 100;
nh.setParam("ubiquity_motor/serial_loop_rate", sLoopRate);
}
motor_serial_ = new MotorSerial(sPort,sBaud,sLoopRate);
}
MotorHardware::~MotorHardware(){
delete motor_serial_;
}
void MotorHardware::readInputs(){
while(motor_serial_->commandAvailable()){
MotorMessage mm;
mm = motor_serial_-> receiveCommand();
if(mm.getType() == MotorMessage::TYPE_RESPONSE){
switch(mm.getRegister()){
case MotorMessage::REG_FIRMWARE_VERSION:
if (!mm.getData() > CURRENT_FIRMWARE_VERSION) {
ROS_FATAL("Firmware version %d, expect %d or above",
mm.getData(), CURRENT_FIRMWARE_VERSION);
}
else {
ROS_INFO("Firmware version %d", mm.getData());
}
break;
case MotorMessage::REG_LEFT_ODOM:
joints_[0].position += mm.getData()/TICS_PER_RADIAN;
break;
case MotorMessage::REG_RIGHT_ODOM:
joints_[1].position += mm.getData()/TICS_PER_RADIAN;
break;
case MotorMessage::REG_LEFT_SPEED_MEASURED:
joints_[0].velocity = mm.getData()*SECONDS_PER_VELOCITY_READ/TICS_PER_RADIAN;
break;
case MotorMessage::REG_RIGHT_SPEED_MEASURED:
joints_[1].velocity = mm.getData()*SECONDS_PER_VELOCITY_READ/TICS_PER_RADIAN;
break;
default:
ROS_ERROR("Got type: 0x%02x, handling not implemented", mm.getRegister());
}
}
}
}
void MotorHardware::writeSpeeds(){
std::vector<MotorMessage> commands(6);
//requestOdometry();
//requestVelocity();
//requestVersion();
_addOdometryRequest(commands);
_addVelocityRequest(commands);
MotorMessage left;
left.setRegister(MotorMessage::REG_LEFT_SPEED_SET);
left.setType(MotorMessage::TYPE_WRITE);
left.setData(boost::math::lround(joints_[0].velocity_command*TICS_PER_RADIAN/SECONDS_PER_VELOCITY_READ));
commands.push_back(left);
MotorMessage right;
right.setRegister(MotorMessage::REG_RIGHT_SPEED_SET);
right.setType(MotorMessage::TYPE_WRITE);
right.setData(boost::math::lround(joints_[1].velocity_command*TICS_PER_RADIAN/SECONDS_PER_VELOCITY_READ));
commands.push_back(right);
//Send all commands to serial thread in one go to reduce locking
motor_serial_->transmitCommands(commands);
//ROS_ERROR("velocity_command %f rad/s %f rad/s", joints_[0].velocity_command, joints_[1].velocity_command);
// ROS_ERROR("SPEEDS %d %d", left.getData(), right.getData());
}
void MotorHardware::requestVersion(){
MotorMessage version;
version.setRegister(MotorMessage::REG_FIRMWARE_VERSION);
version.setType(MotorMessage::TYPE_READ);
version.setData(0);
motor_serial_->transmitCommand(version);
}
void MotorHardware::requestOdometry(){
std::vector<MotorMessage> commands;
_addOdometryRequest(commands);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::requestVelocity(){
std::vector<MotorMessage> commands;
_addVelocityRequest(commands);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::setPid(int32_t p_set, int32_t i_set, int32_t d_set, int32_t denominator_set){
p_value = p_set;
i_value = i_set;
d_value = d_set;
denominator_value = denominator_set;
}
void MotorHardware::sendPid() {
std::vector<MotorMessage> commands(4);
MotorMessage p;
p.setRegister(MotorMessage::REG_PARAM_P);
p.setType(MotorMessage::TYPE_WRITE);
p.setData(p_value);
commands.push_back(p);
MotorMessage i;
i.setRegister(MotorMessage::REG_PARAM_I);
i.setType(MotorMessage::TYPE_WRITE);
i.setData(i_value);
commands.push_back(i);
MotorMessage d;
d.setRegister(MotorMessage::REG_PARAM_D);
d.setType(MotorMessage::TYPE_WRITE);
d.setData(d_value);
commands.push_back(d);
MotorMessage denominator;
denominator.setRegister(MotorMessage::REG_PARAM_C);
denominator.setType(MotorMessage::TYPE_WRITE);
denominator.setData(denominator_value);
commands.push_back(denominator);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::setDebugLeds(bool led_1, bool led_2) {
std::vector<MotorMessage> commands(2);
MotorMessage led1;
led1.setRegister(MotorMessage::REG_LED_1);
led1.setType(MotorMessage::TYPE_WRITE);
if(led_1) {
led1.setData(0x00000001);
}
else {
led1.setData(0x00000000);
}
commands.push_back(led1);
MotorMessage led2;
led2.setRegister(MotorMessage::REG_LED_2);
led2.setType(MotorMessage::TYPE_WRITE);
if(led_2) {
led2.setData(0x00000001);
}
else {
led2.setData(0x00000000);
}
commands.push_back(led2);
motor_serial_->transmitCommands(commands);
}
void MotorHardware::_addOdometryRequest(std::vector<MotorMessage>& commands) const{
MotorMessage left_odom;
left_odom.setRegister(MotorMessage::REG_LEFT_ODOM);
left_odom.setType(MotorMessage::TYPE_READ);
left_odom.setData(0);
commands.push_back(left_odom);
MotorMessage right_odom;
right_odom.setRegister(MotorMessage::REG_RIGHT_ODOM);
right_odom.setType(MotorMessage::TYPE_READ);
right_odom.setData(0);
commands.push_back(right_odom);
}
void MotorHardware::_addVelocityRequest(std::vector<MotorMessage>& commands) const{
MotorMessage left_vel;
left_vel.setRegister(MotorMessage::REG_LEFT_SPEED_MEASURED);
left_vel.setType(MotorMessage::TYPE_READ);
left_vel.setData(0);
commands.push_back(left_vel);
MotorMessage right_vel;
right_vel.setRegister(MotorMessage::REG_RIGHT_SPEED_MEASURED);
right_vel.setType(MotorMessage::TYPE_READ);
right_vel.setData(0);
commands.push_back(right_vel);
}<|endoftext|> |
<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 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 <string>
#include <memory>
#include <vector>
#include <google/protobuf/unittest_proto3.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
using proto3_unittest::TestAllTypes;
namespace protobuf {
namespace {
// We selectively set/check a few representative fields rather than all fields
// as this test is only expected to cover the basics of lite support.
void SetAllFields(TestAllTypes* m) {
m->set_optional_int32(100);
m->set_optional_string("asdf");
m->set_optional_bytes("jkl;");
m->mutable_optional_nested_message()->set_bb(42);
m->mutable_optional_foreign_message()->set_c(43);
m->set_optional_nested_enum(
proto3_unittest::TestAllTypes_NestedEnum_BAZ);
m->set_optional_foreign_enum(
proto3_unittest::FOREIGN_BAZ);
m->mutable_optional_lazy_message()->set_bb(45);
m->add_repeated_int32(100);
m->add_repeated_string("asdf");
m->add_repeated_bytes("jkl;");
m->add_repeated_nested_message()->set_bb(46);
m->add_repeated_foreign_message()->set_c(47);
m->add_repeated_nested_enum(
proto3_unittest::TestAllTypes_NestedEnum_BAZ);
m->add_repeated_foreign_enum(
proto3_unittest::FOREIGN_BAZ);
m->add_repeated_lazy_message()->set_bb(49);
m->set_oneof_uint32(1);
m->mutable_oneof_nested_message()->set_bb(50);
m->set_oneof_string("test"); // only this one remains set
}
void ExpectAllFieldsSet(const TestAllTypes& m) {
EXPECT_EQ(100, m.optional_int32());
EXPECT_EQ("asdf", m.optional_string());
EXPECT_EQ("jkl;", m.optional_bytes());
EXPECT_EQ(true, m.has_optional_nested_message());
EXPECT_EQ(42, m.optional_nested_message().bb());
EXPECT_EQ(true, m.has_optional_foreign_message());
EXPECT_EQ(43, m.optional_foreign_message().c());
EXPECT_EQ(proto3_unittest::TestAllTypes_NestedEnum_BAZ,
m.optional_nested_enum());
EXPECT_EQ(proto3_unittest::FOREIGN_BAZ,
m.optional_foreign_enum());
EXPECT_EQ(true, m.has_optional_lazy_message());
EXPECT_EQ(45, m.optional_lazy_message().bb());
EXPECT_EQ(1, m.repeated_int32_size());
EXPECT_EQ(100, m.repeated_int32(0));
EXPECT_EQ(1, m.repeated_string_size());
EXPECT_EQ("asdf", m.repeated_string(0));
EXPECT_EQ(1, m.repeated_bytes_size());
EXPECT_EQ("jkl;", m.repeated_bytes(0));
EXPECT_EQ(1, m.repeated_nested_message_size());
EXPECT_EQ(46, m.repeated_nested_message(0).bb());
EXPECT_EQ(1, m.repeated_foreign_message_size());
EXPECT_EQ(47, m.repeated_foreign_message(0).c());
EXPECT_EQ(1, m.repeated_nested_enum_size());
EXPECT_EQ(proto3_unittest::TestAllTypes_NestedEnum_BAZ,
m.repeated_nested_enum(0));
EXPECT_EQ(1, m.repeated_foreign_enum_size());
EXPECT_EQ(proto3_unittest::FOREIGN_BAZ,
m.repeated_foreign_enum(0));
EXPECT_EQ(1, m.repeated_lazy_message_size());
EXPECT_EQ(49, m.repeated_lazy_message(0).bb());
EXPECT_EQ(proto3_unittest::TestAllTypes::kOneofString,
m.oneof_field_case());
EXPECT_EQ("test", m.oneof_string());
}
// In this file we only test some basic functionalities of in proto3 and expect
// the rest is fully tested in proto2 unittests because proto3 shares most code
// with proto2.
TEST(Proto3LiteTest, Parsing) {
TestAllTypes original;
SetAllFields(&original);
TestAllTypes msg;
msg.ParseFromString(original.SerializeAsString());
ExpectAllFieldsSet(msg);
}
TEST(Proto3LiteTest, Swap) {
// Test Swap().
TestAllTypes msg1;
TestAllTypes msg2;
msg1.set_optional_string("123");
msg2.set_optional_string("3456");
msg1.Swap(&msg2);
EXPECT_EQ("3456", msg1.optional_string());
EXPECT_EQ("123", msg2.optional_string());
EXPECT_EQ(msg1.ByteSize(), msg2.ByteSize() + 1);
}
} // namespace
} // namespace protobuf
} // namespace google
<commit_msg>Fixed up proto3_lite_unittest.cc<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 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 <string>
#include <memory>
#include <vector>
#include <google/protobuf/unittest_proto3_lite.pb.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/testing/googletest.h>
#include <gtest/gtest.h>
namespace google {
using proto3_lite_unittest::TestAllTypes;
namespace protobuf {
namespace {
// We selectively set/check a few representative fields rather than all fields
// as this test is only expected to cover the basics of lite support.
void SetAllFields(TestAllTypes* m) {
m->set_optional_int32(100);
m->set_optional_string("asdf");
m->set_optional_bytes("jkl;");
m->mutable_optional_nested_message()->set_bb(42);
m->mutable_optional_foreign_message()->set_c(43);
m->set_optional_nested_enum(
proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ);
m->set_optional_foreign_enum(
proto3_lite_unittest::FOREIGN_BAZ);
m->mutable_optional_lazy_message()->set_bb(45);
m->add_repeated_int32(100);
m->add_repeated_string("asdf");
m->add_repeated_bytes("jkl;");
m->add_repeated_nested_message()->set_bb(46);
m->add_repeated_foreign_message()->set_c(47);
m->add_repeated_nested_enum(
proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ);
m->add_repeated_foreign_enum(
proto3_lite_unittest::FOREIGN_BAZ);
m->add_repeated_lazy_message()->set_bb(49);
m->set_oneof_uint32(1);
m->mutable_oneof_nested_message()->set_bb(50);
m->set_oneof_string("test"); // only this one remains set
}
void ExpectAllFieldsSet(const TestAllTypes& m) {
EXPECT_EQ(100, m.optional_int32());
EXPECT_EQ("asdf", m.optional_string());
EXPECT_EQ("jkl;", m.optional_bytes());
EXPECT_EQ(true, m.has_optional_nested_message());
EXPECT_EQ(42, m.optional_nested_message().bb());
EXPECT_EQ(true, m.has_optional_foreign_message());
EXPECT_EQ(43, m.optional_foreign_message().c());
EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ,
m.optional_nested_enum());
EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ,
m.optional_foreign_enum());
EXPECT_EQ(true, m.has_optional_lazy_message());
EXPECT_EQ(45, m.optional_lazy_message().bb());
EXPECT_EQ(1, m.repeated_int32_size());
EXPECT_EQ(100, m.repeated_int32(0));
EXPECT_EQ(1, m.repeated_string_size());
EXPECT_EQ("asdf", m.repeated_string(0));
EXPECT_EQ(1, m.repeated_bytes_size());
EXPECT_EQ("jkl;", m.repeated_bytes(0));
EXPECT_EQ(1, m.repeated_nested_message_size());
EXPECT_EQ(46, m.repeated_nested_message(0).bb());
EXPECT_EQ(1, m.repeated_foreign_message_size());
EXPECT_EQ(47, m.repeated_foreign_message(0).c());
EXPECT_EQ(1, m.repeated_nested_enum_size());
EXPECT_EQ(proto3_lite_unittest::TestAllTypes_NestedEnum_BAZ,
m.repeated_nested_enum(0));
EXPECT_EQ(1, m.repeated_foreign_enum_size());
EXPECT_EQ(proto3_lite_unittest::FOREIGN_BAZ,
m.repeated_foreign_enum(0));
EXPECT_EQ(1, m.repeated_lazy_message_size());
EXPECT_EQ(49, m.repeated_lazy_message(0).bb());
EXPECT_EQ(proto3_lite_unittest::TestAllTypes::kOneofString,
m.oneof_field_case());
EXPECT_EQ("test", m.oneof_string());
}
// In this file we only test some basic functionalities of in proto3 and expect
// the rest is fully tested in proto2 unittests because proto3 shares most code
// with proto2.
TEST(Proto3LiteTest, Parsing) {
TestAllTypes original;
SetAllFields(&original);
TestAllTypes msg;
msg.ParseFromString(original.SerializeAsString());
ExpectAllFieldsSet(msg);
}
TEST(Proto3LiteTest, Swap) {
// Test Swap().
TestAllTypes msg1;
TestAllTypes msg2;
msg1.set_optional_string("123");
msg2.set_optional_string("3456");
msg1.Swap(&msg2);
EXPECT_EQ("3456", msg1.optional_string());
EXPECT_EQ("123", msg2.optional_string());
EXPECT_EQ(msg1.ByteSize(), msg2.ByteSize() + 1);
}
} // namespace
} // namespace protobuf
} // namespace google
<|endoftext|> |
<commit_before>#include "selected.h"
namespace UnTech {
namespace MetaSprite {
template <class BaseControllerT>
SelectedController<BaseControllerT>::SelectedController(BaseControllerT& controller)
: _controller(controller)
, _type(SelectedType::NONE)
{
_controller.frameController().signal_mapChanged().connect(
[this](void) {
if (_type == SelectedType::FRAME) {
_signal_listChanged.emit();
}
});
_controller.frameObjectController().signal_listChanged().connect(
[this](void) {
if (_type == SelectedType::FRAME_OBJECT) {
_signal_listChanged.emit();
}
});
_controller.actionPointController().signal_listChanged().connect(
[this](void) {
if (_type == SelectedType::ACTION_POINT) {
_signal_listChanged.emit();
}
});
_controller.entityHitboxController().signal_listChanged().connect(
[this](void) {
if (_type == SelectedType::ENTITY_HITBOX) {
_signal_listChanged.emit();
}
});
_controller.settingsController().layers().signal_layersChanged().connect(sigc::mem_fun(
*this, &SelectedController::selectNone));
_controller.frameObjectController().signal_selectedChanged().connect(
[this](void) {
if (_controller.frameObjectController().hasSelected()) {
_type = SelectedType::FRAME_OBJECT;
_signal_selectedChanged.emit();
}
else {
selectFrame();
}
});
_controller.actionPointController().signal_selectedChanged().connect(
[this](void) {
if (_controller.actionPointController().hasSelected()) {
_type = SelectedType::ACTION_POINT;
_signal_selectedChanged.emit();
}
else {
selectFrame();
}
});
_controller.entityHitboxController().signal_selectedChanged().connect(
[this](void) {
if (_controller.entityHitboxController().hasSelected()) {
_type = SelectedType::ENTITY_HITBOX;
_signal_selectedChanged.emit();
}
else {
selectFrame();
}
});
}
template <class T>
std::pair<SelectedType, size_t> SelectedController<T>::typeAndIndex() const
{
size_t id = 0;
switch (_type) {
case SelectedType::NONE:
case SelectedType::FRAME:
case SelectedType::TILE_HITBOX:
break;
case SelectedType::FRAME_OBJECT:
id = _controller.frameObjectController().selectedIndex().value();
break;
case SelectedType::ACTION_POINT:
id = _controller.actionPointController().selectedIndex().value();
break;
case SelectedType::ENTITY_HITBOX:
id = _controller.entityHitboxController().selectedIndex().value();
break;
}
return { _type, id };
}
template <class T>
void SelectedController<T>::selectNone()
{
_controller.frameController().selectNone();
}
template <class T>
void SelectedController<T>::selectFrame()
{
if (_controller.frameController().hasSelected()) {
if (_type != SelectedType::FRAME) {
_type = SelectedType::FRAME;
_signal_selectedChanged.emit();
}
}
else {
selectNone();
}
}
template <class T>
void SelectedController<T>::selectTileHitbox()
{
if (_controller.frameController().hasSelected()) {
if (_type != SelectedType::TILE_HITBOX) {
_type = SelectedType::TILE_HITBOX;
_signal_selectedChanged.emit();
}
}
else {
selectNone();
}
}
template <class T>
void SelectedController<T>::selectFrameItem(const idstring& frameId, SelectedType type, size_t index)
{
if (_controller.frameController().selectedId() != frameId) {
_controller.frameController().selectId(frameId);
}
if (_controller.frameController().hasSelected()) {
switch (type) {
case SelectedType::NONE:
case SelectedType::FRAME:
selectFrame();
break;
case SelectedType::TILE_HITBOX:
break;
case SelectedType::FRAME_OBJECT:
_controller.frameObjectController().selectIndex(index);
break;
case SelectedType::ACTION_POINT:
_controller.actionPointController().selectIndex(index);
break;
case SelectedType::ENTITY_HITBOX:
_controller.entityHitboxController().selectIndex(index);
break;
}
}
}
template <class T>
const std::string& SelectedController<T>::typeString() const
{
const static std::string nullString;
const static std::string tileHitboxString = "Tile Hitbox";
switch (_type) {
case SelectedType::NONE:
return nullString;
case SelectedType::FRAME:
return _controller.frameController().HUMAN_TYPE_NAME;
case SelectedType::TILE_HITBOX:
return tileHitboxString;
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().HUMAN_TYPE_NAME;
case SelectedType::ACTION_POINT:
return _controller.actionPointController().HUMAN_TYPE_NAME;
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().HUMAN_TYPE_NAME;
}
}
template <class T>
bool SelectedController<T>::canCreateSelected() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canCreate();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canCreate();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canCreate();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canCloneSelected() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canCloneSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canCloneSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canCloneSelected();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canRemoveSelected() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canRemoveSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canRemoveSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canRemoveSelected();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canMoveSelectedUp() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canMoveSelectedUp();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canMoveSelectedUp();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canMoveSelectedUp();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canMoveSelectedDown() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canMoveSelectedDown();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canMoveSelectedDown();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canMoveSelectedDown();
default:
return false;
}
}
template <class T>
void SelectedController<T>::createNewOfSelectedType()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().create();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().create();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().create();
default:
return;
}
}
template <class T>
void SelectedController<T>::cloneSelected()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().cloneSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().cloneSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().cloneSelected();
default:
return;
}
}
template <class T>
void SelectedController<T>::removeSelected()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().removeSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().removeSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().removeSelected();
default:
return;
}
}
template <class T>
void SelectedController<T>::moveSelectedUp()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().moveSelectedUp();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().moveSelectedUp();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().moveSelectedUp();
default:
return;
}
}
template <class T>
void SelectedController<T>::moveSelectedDown()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().moveSelectedDown();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().moveSelectedDown();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().moveSelectedDown();
default:
return;
}
}
}
}
<commit_msg>fix: Deselect TILE_HITBOX if the frame is not solid<commit_after>#include "selected.h"
namespace UnTech {
namespace MetaSprite {
template <class BaseControllerT>
SelectedController<BaseControllerT>::SelectedController(BaseControllerT& controller)
: _controller(controller)
, _type(SelectedType::NONE)
{
_controller.frameController().signal_dataChanged().connect(
[this](void) {
// deselect TILE_HITBOX is frame is not solid
if (_type == SelectedType::TILE_HITBOX) {
auto& f = _controller.frameController().selected();
if (f.solid == false) {
selectFrame();
}
}
});
_controller.frameController().signal_mapChanged().connect(
[this](void) {
if (_type == SelectedType::FRAME || _type == SelectedType::TILE_HITBOX) {
_signal_listChanged.emit();
}
});
_controller.frameObjectController().signal_listChanged().connect(
[this](void) {
if (_type == SelectedType::FRAME_OBJECT) {
_signal_listChanged.emit();
}
});
_controller.actionPointController().signal_listChanged().connect(
[this](void) {
if (_type == SelectedType::ACTION_POINT) {
_signal_listChanged.emit();
}
});
_controller.entityHitboxController().signal_listChanged().connect(
[this](void) {
if (_type == SelectedType::ENTITY_HITBOX) {
_signal_listChanged.emit();
}
});
_controller.settingsController().layers().signal_layersChanged().connect(sigc::mem_fun(
*this, &SelectedController::selectNone));
_controller.frameObjectController().signal_selectedChanged().connect(
[this](void) {
if (_controller.frameObjectController().hasSelected()) {
_type = SelectedType::FRAME_OBJECT;
_signal_selectedChanged.emit();
}
else {
selectFrame();
}
});
_controller.actionPointController().signal_selectedChanged().connect(
[this](void) {
if (_controller.actionPointController().hasSelected()) {
_type = SelectedType::ACTION_POINT;
_signal_selectedChanged.emit();
}
else {
selectFrame();
}
});
_controller.entityHitboxController().signal_selectedChanged().connect(
[this](void) {
if (_controller.entityHitboxController().hasSelected()) {
_type = SelectedType::ENTITY_HITBOX;
_signal_selectedChanged.emit();
}
else {
selectFrame();
}
});
}
template <class T>
std::pair<SelectedType, size_t> SelectedController<T>::typeAndIndex() const
{
size_t id = 0;
switch (_type) {
case SelectedType::NONE:
case SelectedType::FRAME:
case SelectedType::TILE_HITBOX:
break;
case SelectedType::FRAME_OBJECT:
id = _controller.frameObjectController().selectedIndex().value();
break;
case SelectedType::ACTION_POINT:
id = _controller.actionPointController().selectedIndex().value();
break;
case SelectedType::ENTITY_HITBOX:
id = _controller.entityHitboxController().selectedIndex().value();
break;
}
return { _type, id };
}
template <class T>
void SelectedController<T>::selectNone()
{
_controller.frameController().selectNone();
}
template <class T>
void SelectedController<T>::selectFrame()
{
if (_controller.frameController().hasSelected()) {
if (_type != SelectedType::FRAME) {
_type = SelectedType::FRAME;
_signal_selectedChanged.emit();
}
}
else {
selectNone();
}
}
template <class T>
void SelectedController<T>::selectTileHitbox()
{
if (_controller.frameController().selected().solid) {
if (_type != SelectedType::TILE_HITBOX) {
_type = SelectedType::TILE_HITBOX;
_signal_selectedChanged.emit();
}
}
else {
selectFrame();
}
}
template <class T>
void SelectedController<T>::selectFrameItem(const idstring& frameId, SelectedType type, size_t index)
{
if (_controller.frameController().selectedId() != frameId) {
_controller.frameController().selectId(frameId);
}
if (_controller.frameController().hasSelected()) {
switch (type) {
case SelectedType::NONE:
case SelectedType::FRAME:
selectFrame();
break;
case SelectedType::TILE_HITBOX:
break;
case SelectedType::FRAME_OBJECT:
_controller.frameObjectController().selectIndex(index);
break;
case SelectedType::ACTION_POINT:
_controller.actionPointController().selectIndex(index);
break;
case SelectedType::ENTITY_HITBOX:
_controller.entityHitboxController().selectIndex(index);
break;
}
}
}
template <class T>
const std::string& SelectedController<T>::typeString() const
{
const static std::string nullString;
const static std::string tileHitboxString = "Tile Hitbox";
switch (_type) {
case SelectedType::NONE:
return nullString;
case SelectedType::FRAME:
return _controller.frameController().HUMAN_TYPE_NAME;
case SelectedType::TILE_HITBOX:
return tileHitboxString;
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().HUMAN_TYPE_NAME;
case SelectedType::ACTION_POINT:
return _controller.actionPointController().HUMAN_TYPE_NAME;
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().HUMAN_TYPE_NAME;
}
}
template <class T>
bool SelectedController<T>::canCreateSelected() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canCreate();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canCreate();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canCreate();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canCloneSelected() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canCloneSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canCloneSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canCloneSelected();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canRemoveSelected() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canRemoveSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canRemoveSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canRemoveSelected();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canMoveSelectedUp() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canMoveSelectedUp();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canMoveSelectedUp();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canMoveSelectedUp();
default:
return false;
}
}
template <class T>
bool SelectedController<T>::canMoveSelectedDown() const
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().canMoveSelectedDown();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().canMoveSelectedDown();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().canMoveSelectedDown();
default:
return false;
}
}
template <class T>
void SelectedController<T>::createNewOfSelectedType()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().create();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().create();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().create();
default:
return;
}
}
template <class T>
void SelectedController<T>::cloneSelected()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().cloneSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().cloneSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().cloneSelected();
default:
return;
}
}
template <class T>
void SelectedController<T>::removeSelected()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().removeSelected();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().removeSelected();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().removeSelected();
default:
return;
}
}
template <class T>
void SelectedController<T>::moveSelectedUp()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().moveSelectedUp();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().moveSelectedUp();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().moveSelectedUp();
default:
return;
}
}
template <class T>
void SelectedController<T>::moveSelectedDown()
{
switch (_type) {
case SelectedType::FRAME_OBJECT:
return _controller.frameObjectController().moveSelectedDown();
case SelectedType::ACTION_POINT:
return _controller.actionPointController().moveSelectedDown();
case SelectedType::ENTITY_HITBOX:
return _controller.entityHitboxController().moveSelectedDown();
default:
return;
}
}
}
}
<|endoftext|> |
<commit_before>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include "SpaghettiInfillPathGenerator.h"
#include "../infill.h"
#include "../FffGcodeWriter.h"
namespace cura {
bool SpaghettiInfillPathGenerator::processSpaghettiInfill(const SliceDataStorage& storage, const FffGcodeWriter& fff_gcode_writer, LayerPlan& gcode_layer, const SliceMeshStorage& mesh, const int extruder_nr, const PathConfigStorage::MeshPathConfigs& mesh_config, const SliceLayerPart& part, unsigned int layer_nr, int infill_line_distance, int infill_overlap, int infill_angle)
{
if (extruder_nr != mesh.getSettingAsExtruderNr("infill_extruder_nr"))
{
return false;
}
bool added_something = false;
const GCodePathConfig* config = mesh_config.getInfillConfig(layer_nr, 0);
const EFillMethod pattern = mesh.getSettingAsFillMethod("infill_pattern");
const unsigned int infill_line_width = config->getLineWidth();
const int64_t z = layer_nr * mesh.getSettingInMicrons("layer_height");
const int64_t infill_shift = 0;
const int64_t outline_offset = 0;
const double layer_height_mm = (layer_nr == 0)? mesh.getSettingInMillimeters("layer_height_0") : mesh.getSettingInMillimeters("layer_height");
// For each part on this layer which is used to fill that part and parts below:
for (const std::pair<Polygons, double>& filling_area : part.spaghetti_infill_volumes)
{
Polygons infill_lines;
Polygons infill_polygons;
const Polygons& area = filling_area.first; // Area of the top within which to move while extruding (might be empty if the spaghetti_inset was too large)
const double total_volume = filling_area.second * mesh.getSettingAsRatio("spaghetti_flow") + mesh.getSettingInCubicMillimeters("spaghetti_infill_extra_volume"); // volume to be extruded
if (total_volume <= 0.0)
{
continue;
}
// generate zigzag print head paths
Polygons* perimeter_gaps_output = nullptr;
const bool connected_zigzags = true;
const bool use_endpieces = false;
Infill infill_comp(pattern, area, outline_offset, infill_line_width, infill_line_distance, infill_overlap, infill_angle, z, infill_shift, perimeter_gaps_output, connected_zigzags, use_endpieces);
infill_comp.generate(infill_polygons, infill_lines, &mesh);
// add paths to plan with a higher flow ratio in order to extrude the required amount.
const coord_t total_length = infill_polygons.polygonLength() + infill_lines.polyLineLength();
if (total_length > 0)
{ // zigzag path generation actually generated paths
// calculate the normal volume extruded when using the layer height and line width to calculate extrusion
const double normal_volume = INT2MM(INT2MM(total_length * infill_line_width)) * layer_height_mm;
assert(normal_volume > 0.0);
const float flow_ratio = total_volume / normal_volume;
assert(flow_ratio / mesh.getSettingAsRatio("spaghetti_flow") >= 0.9);
assert(!std::isnan(flow_ratio) && !std::isinf(flow_ratio));
if (!infill_polygons.empty() || !infill_lines.empty())
{
added_something = true;
fff_gcode_writer.setExtruder_addPrime(storage, gcode_layer, layer_nr, extruder_nr);
gcode_layer.addPolygonsByOptimizer(infill_polygons, config, nullptr, EZSeamType::SHORTEST, Point(0, 0), 0, false, flow_ratio);
if (pattern == EFillMethod::GRID || pattern == EFillMethod::LINES || pattern == EFillMethod::TRIANGLES || pattern == EFillMethod::CUBIC || pattern == EFillMethod::TETRAHEDRAL || pattern == EFillMethod::CUBICSUBDIV)
{
gcode_layer.addLinesByOptimizer(infill_lines, config, SpaceFillType::Lines, mesh.getSettingInMicrons("infill_wipe_dist"), flow_ratio);
}
else
{
gcode_layer.addLinesByOptimizer(infill_lines, config, (pattern == EFillMethod::ZIG_ZAG)? SpaceFillType::PolyLines : SpaceFillType::Lines, 0, flow_ratio);
}
}
}
else
{ // zigzag path generation couldn't generate paths, probably because the area was too small
// generate small path near the middle of the filling area
// note that we need a path with positive length because that is currently the only way to insert an extrusion in a layer plan
constexpr int path_length = 10;
Point middle = AABB(area).getMiddle();
if (!area.inside(middle))
{
PolygonUtils::ensureInsideOrOutside(area, middle, infill_line_width / 2);
}
const double normal_volume = INT2MM(INT2MM(path_length * infill_line_width)) * layer_height_mm;
const float flow_ratio = total_volume / normal_volume;
gcode_layer.addTravel(middle);
gcode_layer.addExtrusionMove(middle + Point(0, path_length), config, SpaceFillType::Lines, flow_ratio);
}
}
return added_something;
}
}//namespace cura
<commit_msg>Spread out extra spaghetti infill volume proportionally<commit_after>/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License */
#include "SpaghettiInfillPathGenerator.h"
#include "../infill.h"
#include "../FffGcodeWriter.h"
namespace cura {
bool SpaghettiInfillPathGenerator::processSpaghettiInfill(const SliceDataStorage& storage, const FffGcodeWriter& fff_gcode_writer, LayerPlan& gcode_layer, const SliceMeshStorage& mesh, const int extruder_nr, const PathConfigStorage::MeshPathConfigs& mesh_config, const SliceLayerPart& part, unsigned int layer_nr, int infill_line_distance, int infill_overlap, int infill_angle)
{
if (extruder_nr != mesh.getSettingAsExtruderNr("infill_extruder_nr"))
{
return false;
}
bool added_something = false;
const GCodePathConfig* config = mesh_config.getInfillConfig(layer_nr, 0);
const EFillMethod pattern = mesh.getSettingAsFillMethod("infill_pattern");
const unsigned int infill_line_width = config->getLineWidth();
const int64_t z = layer_nr * mesh.getSettingInMicrons("layer_height");
const int64_t infill_shift = 0;
const int64_t outline_offset = 0;
const double layer_height_mm = (layer_nr == 0)? mesh.getSettingInMillimeters("layer_height_0") : mesh.getSettingInMillimeters("layer_height");
const double default_spaghetti_infill_extra_volume = mesh.getSettingInCubicMillimeters("spaghetti_infill_extra_volume");
// For each part on this layer which is used to fill that part and parts below:
for (const std::pair<Polygons, double>& filling_area : part.spaghetti_infill_volumes)
{
Polygons infill_lines;
Polygons infill_polygons;
const Polygons& area = filling_area.first; // Area of the top within which to move while extruding (might be empty if the spaghetti_inset was too large)
// the extra infill volume will be spread out proportionally to each step
const double extra_infill_volume = filling_area.second / mesh.total_infill_volume_mm3 * default_spaghetti_infill_extra_volume;
const double total_volume = filling_area.second * mesh.getSettingAsRatio("spaghetti_flow") + extra_infill_volume; // volume to be extruded
if (total_volume <= 0.0)
{
continue;
}
// generate zigzag print head paths
Polygons* perimeter_gaps_output = nullptr;
const bool connected_zigzags = true;
const bool use_endpieces = false;
Infill infill_comp(pattern, area, outline_offset, infill_line_width, infill_line_distance, infill_overlap, infill_angle, z, infill_shift, perimeter_gaps_output, connected_zigzags, use_endpieces);
infill_comp.generate(infill_polygons, infill_lines, &mesh);
// add paths to plan with a higher flow ratio in order to extrude the required amount.
const coord_t total_length = infill_polygons.polygonLength() + infill_lines.polyLineLength();
if (total_length > 0)
{ // zigzag path generation actually generated paths
// calculate the normal volume extruded when using the layer height and line width to calculate extrusion
const double normal_volume = INT2MM(INT2MM(total_length * infill_line_width)) * layer_height_mm;
assert(normal_volume > 0.0);
const float flow_ratio = total_volume / normal_volume;
assert(flow_ratio / mesh.getSettingAsRatio("spaghetti_flow") >= 0.9);
assert(!std::isnan(flow_ratio) && !std::isinf(flow_ratio));
if (!infill_polygons.empty() || !infill_lines.empty())
{
added_something = true;
fff_gcode_writer.setExtruder_addPrime(storage, gcode_layer, layer_nr, extruder_nr);
gcode_layer.addPolygonsByOptimizer(infill_polygons, config, nullptr, EZSeamType::SHORTEST, Point(0, 0), 0, false, flow_ratio);
if (pattern == EFillMethod::GRID || pattern == EFillMethod::LINES || pattern == EFillMethod::TRIANGLES || pattern == EFillMethod::CUBIC || pattern == EFillMethod::TETRAHEDRAL || pattern == EFillMethod::CUBICSUBDIV)
{
gcode_layer.addLinesByOptimizer(infill_lines, config, SpaceFillType::Lines, mesh.getSettingInMicrons("infill_wipe_dist"), flow_ratio);
}
else
{
gcode_layer.addLinesByOptimizer(infill_lines, config, (pattern == EFillMethod::ZIG_ZAG)? SpaceFillType::PolyLines : SpaceFillType::Lines, 0, flow_ratio);
}
}
}
else
{ // zigzag path generation couldn't generate paths, probably because the area was too small
// generate small path near the middle of the filling area
// note that we need a path with positive length because that is currently the only way to insert an extrusion in a layer plan
constexpr int path_length = 10;
Point middle = AABB(area).getMiddle();
if (!area.inside(middle))
{
PolygonUtils::ensureInsideOrOutside(area, middle, infill_line_width / 2);
}
const double normal_volume = INT2MM(INT2MM(path_length * infill_line_width)) * layer_height_mm;
const float flow_ratio = total_volume / normal_volume;
gcode_layer.addTravel(middle);
gcode_layer.addExtrusionMove(middle + Point(0, path_length), config, SpaceFillType::Lines, flow_ratio);
}
}
return added_something;
}
}//namespace cura
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Sergey Ilinykh
*
* 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 "irisnetplugin.h"
#include <QNetworkInterface>
namespace XMPP {
class IrisQtName : public NameProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::NameProvider)
int currentId;
QHash<int,QDnsLookup*> lookups;
public:
IrisQtName(QObject *parent = 0) :
NameProvider(parent),
currentId(0)
{
}
bool supportsSingle() const
{
return true;
}
bool supportsRecordType(int type) const
{
// yes the types matched to ones from jdns, so it's fine.
static QVector<int> types = {
QDnsLookup::A, QDnsLookup::AAAA, QDnsLookup::ANY,
QDnsLookup::CNAME, QDnsLookup::MX, QDnsLookup::NS,
QDnsLookup::PTR, QDnsLookup::SRV, QDnsLookup::TXT};
return types.contains(type);
}
int resolve_start(const QByteArray &name, int qType, bool longLived)
{
Q_UNUSED(longLived); // FIXME handle local like in jdns name provider
QDnsLookup *lookup = new QDnsLookup((QDnsLookup::Type)qType, QString::fromLatin1(name), this);
connect(lookup, SIGNAL(finished()), this, SLOT(handleLookup()));
int id = currentId++;
lookup->setProperty("iid", id);
lookups.insert(id, lookup);
lookup->lookup();
return id;
}
void resolve_stop(int id)
{
QDnsLookup *lookup = lookups.take(id);
lookup->abort();
}
private slots:
void handleLookup()
{
QDnsLookup *lookup = static_cast<QDnsLookup *>(sender());
int id = lookup->property("iid").toInt();
lookups.remove(id);
if (lookup->error() != QDnsLookup::NoError) {
XMPP::NameResolver::Error e;
switch (lookup->error()) {
case QDnsLookup::InvalidReplyError:
e = XMPP::NameResolver::ErrorTimeout;
break;
case QDnsLookup::NotFoundError:
e = XMPP::NameResolver::ErrorNoName;
break;
case QDnsLookup::ResolverError:
case QDnsLookup::OperationCancelledError:
case QDnsLookup::InvalidRequestError:
case QDnsLookup::ServerFailureError:
case QDnsLookup::ServerRefusedError:
default:
e = XMPP::NameResolver::ErrorGeneric;
break;
}
emit resolve_error(id, e);
return;
}
QList<XMPP::NameRecord> results;
for (auto &qtr: lookup->hostAddressRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setAddress(qtr.value());
results += ir;
}
for (auto &qtr: lookup->mailExchangeRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setMx(qtr.exchange().toLatin1(), qtr.preference());
results += ir;
}
for (auto &qtr: lookup->nameServerRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setNs(qtr.value().toLatin1());
results += ir;
}
for (auto &qtr: lookup->pointerRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setPtr(qtr.value().toLatin1());
results += ir;
}
for (auto &qtr: lookup->canonicalNameRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setCname(qtr.value().toLatin1());
results += ir;
}
for (auto &qtr: lookup->serviceRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setSrv(qtr.target().toLatin1(),qtr.port(),qtr.priority(),qtr.weight());
results += ir;
}
for (auto &qtr: lookup->textRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setTxt(qtr.values());
results += ir;
}
lookup->deleteLater();
emit resolve_resultsReady(id, results);
}
};
class IrisQtNameProvider : public IrisNetProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::IrisNetProvider)
public:
NameProvider *createNameProviderInternet()
{
return new IrisQtName;
}
};
IrisNetProvider *irisnet_createQtNameProvider()
{
return new IrisQtNameProvider;
}
}
#include "netinterface_qtname.moc"
<commit_msg>Fix possible memory leaks and crashes in new QDnsLookup based resolver<commit_after>/*
* Copyright (C) 2017 Sergey Ilinykh
*
* 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 "irisnetplugin.h"
#include <QNetworkInterface>
namespace XMPP {
class IrisQtName : public NameProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::NameProvider)
int currentId;
QHash<int,QDnsLookup*> lookups;
public:
IrisQtName(QObject *parent = 0) :
NameProvider(parent),
currentId(0)
{
}
~IrisQtName()
{
qDeleteAll(lookups);
}
bool supportsSingle() const
{
return true;
}
bool supportsRecordType(int type) const
{
// yes the types matched to ones from jdns, so it's fine.
static QVector<int> types = {
QDnsLookup::A, QDnsLookup::AAAA, QDnsLookup::ANY,
QDnsLookup::CNAME, QDnsLookup::MX, QDnsLookup::NS,
QDnsLookup::PTR, QDnsLookup::SRV, QDnsLookup::TXT};
return types.contains(type);
}
int resolve_start(const QByteArray &name, int qType, bool longLived)
{
Q_UNUSED(longLived); // FIXME handle local like in jdns name provider
QDnsLookup *lookup = new QDnsLookup((QDnsLookup::Type)qType, QString::fromLatin1(name), this);
connect(lookup, SIGNAL(finished()), this, SLOT(handleLookup()));
int id = currentId++;
lookup->setProperty("iid", id);
lookups.insert(id, lookup);
QMetaObject::invokeMethod(lookup, "lookup", Qt::QueuedConnection);
return id;
}
void resolve_stop(int id)
{
QDnsLookup *lookup = lookups.value(id);
if (lookup) {
lookup->abort(); // handleLookup will catch it and delete
}
}
private slots:
void handleLookup()
{
QDnsLookup *lookup = static_cast<QDnsLookup *>(sender());
int id = lookup->property("iid").toInt();
lookups.remove(id);
if (lookup->error() != QDnsLookup::NoError) {
XMPP::NameResolver::Error e;
switch (lookup->error()) {
case QDnsLookup::InvalidReplyError:
e = XMPP::NameResolver::ErrorTimeout;
break;
case QDnsLookup::NotFoundError:
e = XMPP::NameResolver::ErrorNoName;
break;
case QDnsLookup::ResolverError:
case QDnsLookup::OperationCancelledError:
case QDnsLookup::InvalidRequestError:
case QDnsLookup::ServerFailureError:
case QDnsLookup::ServerRefusedError:
default:
e = XMPP::NameResolver::ErrorGeneric;
break;
}
if (lookup->error() != QDnsLookup::OperationCancelledError) { // don't report after resolve_stop()
emit resolve_error(id, e);
}
lookup->deleteLater();
return;
}
QList<XMPP::NameRecord> results;
for (auto &qtr: lookup->hostAddressRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setAddress(qtr.value());
results += ir;
}
for (auto &qtr: lookup->mailExchangeRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setMx(qtr.exchange().toLatin1(), qtr.preference());
results += ir;
}
for (auto &qtr: lookup->nameServerRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setNs(qtr.value().toLatin1());
results += ir;
}
for (auto &qtr: lookup->pointerRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setPtr(qtr.value().toLatin1());
results += ir;
}
for (auto &qtr: lookup->canonicalNameRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setCname(qtr.value().toLatin1());
results += ir;
}
for (auto &qtr: lookup->serviceRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setSrv(qtr.target().toLatin1(),qtr.port(),qtr.priority(),qtr.weight());
results += ir;
}
for (auto &qtr: lookup->textRecords()) {
XMPP::NameRecord ir(qtr.name().toLatin1(), qtr.timeToLive());
ir.setTxt(qtr.values());
results += ir;
}
lookup->deleteLater();
emit resolve_resultsReady(id, results);
}
};
class IrisQtNameProvider : public IrisNetProvider
{
Q_OBJECT
Q_INTERFACES(XMPP::IrisNetProvider)
public:
NameProvider *createNameProviderInternet()
{
return new IrisQtName;
}
};
IrisNetProvider *irisnet_createQtNameProvider()
{
return new IrisQtNameProvider;
}
}
#include "netinterface_qtname.moc"
<|endoftext|> |
<commit_before>/*
* Copyright 2012 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.
*/
// Author: [email protected] (Jeff Kaufman)
#include "ngx_base_fetch.h"
#include "ngx_pagespeed.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/util/public/google_message_handler.h"
#include "net/instaweb/util/public/message_handler.h"
namespace net_instaweb {
NgxBaseFetch::NgxBaseFetch(ngx_http_request_t* r, int pipe_fd)
: request_(r), done_called_(false), last_buf_sent_(false),
pipe_fd_(pipe_fd) {
if (pthread_mutex_init(&mutex_, NULL)) CHECK(0);
PopulateRequestHeaders();
}
NgxBaseFetch::~NgxBaseFetch() {
pthread_mutex_destroy(&mutex_);
}
void NgxBaseFetch::Lock() {
pthread_mutex_lock(&mutex_);
}
void NgxBaseFetch::Unlock() {
pthread_mutex_unlock(&mutex_);
}
void NgxBaseFetch::PopulateRequestHeaders() {
CopyHeadersFromTable<RequestHeaders>(&request_->headers_in.headers,
request_headers());
}
void NgxBaseFetch::PopulateResponseHeaders() {
CopyHeadersFromTable<ResponseHeaders>(&request_->headers_out.headers,
response_headers());
response_headers()->set_status_code(request_->headers_out.status);
// Manually copy over the content type because it's not included in
// request_->headers_out.headers.
response_headers()->Add(
HttpAttributes::kContentType,
ngx_psol::str_to_string_piece(request_->headers_out.content_type));
// TODO(oschaaf): ComputeCaching should be called in setupforhtml()?
response_headers()->ComputeCaching();
}
template<class HeadersT>
void NgxBaseFetch::CopyHeadersFromTable(ngx_list_t* headers_from,
HeadersT* headers_to) {
// http_version is the version number of protocol; 1.1 = 1001. See
// NGX_HTTP_VERSION_* in ngx_http_request.h
headers_to->set_major_version(request_->http_version / 1000);
headers_to->set_minor_version(request_->http_version % 1000);
// Standard nginx idiom for iterating over a list. See ngx_list.h
ngx_uint_t i;
ngx_list_part_t* part = &headers_from->part;
ngx_table_elt_t* header = static_cast<ngx_table_elt_t*>(part->elts);
for (i = 0 ; /* void */; i++) {
if (i >= part->nelts) {
if (part->next == NULL) {
break;
}
part = part->next;
header = static_cast<ngx_table_elt_t*>(part->elts);
i = 0;
}
StringPiece key = ngx_psol::str_to_string_piece(header[i].key);
StringPiece value = ngx_psol::str_to_string_piece(header[i].value);
headers_to->Add(key, value);
}
}
bool NgxBaseFetch::HandleWrite(const StringPiece& sp,
MessageHandler* handler) {
Lock();
buffer_.append(sp.data(), sp.size());
Unlock();
return true;
}
ngx_int_t NgxBaseFetch::CopyBufferToNginx(ngx_chain_t** link_ptr) {
// TODO(jefftk): if done_called_ && last_buf_sent_, should we just short
// circuit (return NGX_OK) here?
int rc = ngx_psol::string_piece_to_buffer_chain(
request_->pool, buffer_, link_ptr, done_called_ /* send_last_buf */);
if (rc != NGX_OK) {
return rc;
}
// Done with buffer contents now.
buffer_.clear();
if (done_called_) {
last_buf_sent_ = true;
}
return NGX_OK;
}
// There may also be a race condition if this is called between the last Write()
// and Done() such that we're sending an empty buffer with last_buf set, which I
// think nginx will reject.
ngx_int_t NgxBaseFetch::CollectAccumulatedWrites(ngx_chain_t** link_ptr) {
Lock();
ngx_int_t rc = CopyBufferToNginx(link_ptr);
Unlock();
if (rc == NGX_DECLINED) {
*link_ptr = NULL;
return NGX_OK;
}
return rc;
}
ngx_int_t NgxBaseFetch::CollectHeaders(ngx_http_headers_out_t* headers_out) {
// Copy from response_headers() into headers_out.
Lock();
const ResponseHeaders* pagespeed_headers = response_headers();
Unlock();
headers_out->status = pagespeed_headers->status_code();
ngx_int_t i;
for (i = 0 ; i < pagespeed_headers->NumAttributes() ; i++) {
const GoogleString& name_gs = pagespeed_headers->Name(i);
const GoogleString& value_gs = pagespeed_headers->Value(i);
ngx_str_t name, value;
name.len = name_gs.length();
name.data = reinterpret_cast<u_char*>(const_cast<char*>(name_gs.data()));
value.len = value_gs.length();
value.data = reinterpret_cast<u_char*>(const_cast<char*>(value_gs.data()));
// TODO(jefftk): If we're setting a cache control header we'd like to
// prevent any downstream code from changing it. Specifically, if we're
// serving a cache-extended resource the url will change if the resource
// does and so we've given it a long lifetime. If the site owner has done
// something like set all css files to a 10-minute cache lifetime, that
// shouldn't apply to our generated resources. See Apache code in
// net/instaweb/apache/header_util:AddResponseHeadersToRequest
// Make copies of name and value to put into headers_out.
u_char* value_s = ngx_pstrdup(request_->pool, &value);
if (value_s == NULL) {
return NGX_ERROR;
}
if (STR_EQ_LITERAL(name, "Content-Type")) {
// Unlike all the other headers, content_type is just a string.
headers_out->content_type.data = value_s;
headers_out->content_type.len = value.len;
headers_out->content_type_len = value.len;
// In ngx_http_test_content_type() nginx will allocate and calculate
// content_type_lowcase if we leave it as null.
headers_out->content_type_lowcase = NULL;
continue;
}
u_char* name_s = ngx_pstrdup(request_->pool, &name);
if (name_s == NULL) {
return NGX_ERROR;
}
ngx_table_elt_t* header = static_cast<ngx_table_elt_t*>(
ngx_list_push(&headers_out->headers));
if (header == NULL) {
return NGX_ERROR;
}
header->hash = 1; // Include this header in the output.
header->key.len = name.len;
header->key.data = name_s;
header->value.len = value.len;
header->value.data = value_s;
// Populate the shortcuts to commonly used headers.
if (STR_EQ_LITERAL(name, "Date")) {
headers_out->date = header;
} else if (STR_EQ_LITERAL(name, "Etag")) {
headers_out->etag = header;
} else if (STR_EQ_LITERAL(name, "Expires")) {
headers_out->expires = header;
} else if (STR_EQ_LITERAL(name, "Last-Modified")) {
headers_out->last_modified = header;
} else if (STR_EQ_LITERAL(name, "Location")) {
headers_out->location = header;
} else if (STR_EQ_LITERAL(name, "Server")) {
headers_out->server = header;
}
}
return NGX_OK;
}
void NgxBaseFetch::RequestCollection() {
int rc;
char c = 'A'; // What byte we write is arbitrary.
while (true) {
rc = write(pipe_fd_, &c, 1);
if (rc == 1) {
break;
} else if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
// TODO(jefftk): is this rare enough that spinning isn't a problem? Could
// we get into a case where the pipe fills up and we spin forever?
} else {
perror("NgxBaseFetch::RequestCollection");
break;
}
}
}
void NgxBaseFetch::HandleHeadersComplete() {
RequestCollection(); // Headers available.
}
bool NgxBaseFetch::HandleFlush(MessageHandler* handler) {
RequestCollection(); // A new part of the response body is available.
return true;
}
void NgxBaseFetch::HandleDone(bool success) {
done_called_ = true;
close(pipe_fd_); // Indicates to nginx that we're done with the rewrite.
pipe_fd_ = -1;
}
} // namespace net_instaweb
<commit_msg>ngx_base_fetch: fix extra chunks and race condition<commit_after>/*
* Copyright 2012 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.
*/
// Author: [email protected] (Jeff Kaufman)
#include "ngx_base_fetch.h"
#include "ngx_pagespeed.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/util/public/google_message_handler.h"
#include "net/instaweb/util/public/message_handler.h"
namespace net_instaweb {
NgxBaseFetch::NgxBaseFetch(ngx_http_request_t* r, int pipe_fd)
: request_(r), done_called_(false), last_buf_sent_(false),
pipe_fd_(pipe_fd) {
if (pthread_mutex_init(&mutex_, NULL)) CHECK(0);
PopulateRequestHeaders();
}
NgxBaseFetch::~NgxBaseFetch() {
pthread_mutex_destroy(&mutex_);
}
void NgxBaseFetch::Lock() {
pthread_mutex_lock(&mutex_);
}
void NgxBaseFetch::Unlock() {
pthread_mutex_unlock(&mutex_);
}
void NgxBaseFetch::PopulateRequestHeaders() {
CopyHeadersFromTable<RequestHeaders>(&request_->headers_in.headers,
request_headers());
}
void NgxBaseFetch::PopulateResponseHeaders() {
CopyHeadersFromTable<ResponseHeaders>(&request_->headers_out.headers,
response_headers());
response_headers()->set_status_code(request_->headers_out.status);
// Manually copy over the content type because it's not included in
// request_->headers_out.headers.
response_headers()->Add(
HttpAttributes::kContentType,
ngx_psol::str_to_string_piece(request_->headers_out.content_type));
// TODO(oschaaf): ComputeCaching should be called in setupforhtml()?
response_headers()->ComputeCaching();
}
template<class HeadersT>
void NgxBaseFetch::CopyHeadersFromTable(ngx_list_t* headers_from,
HeadersT* headers_to) {
// http_version is the version number of protocol; 1.1 = 1001. See
// NGX_HTTP_VERSION_* in ngx_http_request.h
headers_to->set_major_version(request_->http_version / 1000);
headers_to->set_minor_version(request_->http_version % 1000);
// Standard nginx idiom for iterating over a list. See ngx_list.h
ngx_uint_t i;
ngx_list_part_t* part = &headers_from->part;
ngx_table_elt_t* header = static_cast<ngx_table_elt_t*>(part->elts);
for (i = 0 ; /* void */; i++) {
if (i >= part->nelts) {
if (part->next == NULL) {
break;
}
part = part->next;
header = static_cast<ngx_table_elt_t*>(part->elts);
i = 0;
}
StringPiece key = ngx_psol::str_to_string_piece(header[i].key);
StringPiece value = ngx_psol::str_to_string_piece(header[i].value);
headers_to->Add(key, value);
}
}
bool NgxBaseFetch::HandleWrite(const StringPiece& sp,
MessageHandler* handler) {
Lock();
buffer_.append(sp.data(), sp.size());
Unlock();
return true;
}
ngx_int_t NgxBaseFetch::CopyBufferToNginx(ngx_chain_t** link_ptr) {
if (done_called_ && last_buf_sent_) {
return NGX_DECLINED;
}
int rc = ngx_psol::string_piece_to_buffer_chain(
request_->pool, buffer_, link_ptr, done_called_ /* send_last_buf */);
if (rc != NGX_OK) {
return rc;
}
// Done with buffer contents now.
buffer_.clear();
if (done_called_) {
last_buf_sent_ = true;
}
return NGX_OK;
}
// There may also be a race condition if this is called between the last Write()
// and Done() such that we're sending an empty buffer with last_buf set, which I
// think nginx will reject.
ngx_int_t NgxBaseFetch::CollectAccumulatedWrites(ngx_chain_t** link_ptr) {
Lock();
ngx_int_t rc = CopyBufferToNginx(link_ptr);
Unlock();
if (rc == NGX_DECLINED) {
*link_ptr = NULL;
return NGX_OK;
}
return rc;
}
ngx_int_t NgxBaseFetch::CollectHeaders(ngx_http_headers_out_t* headers_out) {
// Copy from response_headers() into headers_out.
Lock();
const ResponseHeaders* pagespeed_headers = response_headers();
Unlock();
headers_out->status = pagespeed_headers->status_code();
ngx_int_t i;
for (i = 0 ; i < pagespeed_headers->NumAttributes() ; i++) {
const GoogleString& name_gs = pagespeed_headers->Name(i);
const GoogleString& value_gs = pagespeed_headers->Value(i);
ngx_str_t name, value;
name.len = name_gs.length();
name.data = reinterpret_cast<u_char*>(const_cast<char*>(name_gs.data()));
value.len = value_gs.length();
value.data = reinterpret_cast<u_char*>(const_cast<char*>(value_gs.data()));
// TODO(jefftk): If we're setting a cache control header we'd like to
// prevent any downstream code from changing it. Specifically, if we're
// serving a cache-extended resource the url will change if the resource
// does and so we've given it a long lifetime. If the site owner has done
// something like set all css files to a 10-minute cache lifetime, that
// shouldn't apply to our generated resources. See Apache code in
// net/instaweb/apache/header_util:AddResponseHeadersToRequest
// Make copies of name and value to put into headers_out.
u_char* value_s = ngx_pstrdup(request_->pool, &value);
if (value_s == NULL) {
return NGX_ERROR;
}
if (STR_EQ_LITERAL(name, "Content-Type")) {
// Unlike all the other headers, content_type is just a string.
headers_out->content_type.data = value_s;
headers_out->content_type.len = value.len;
headers_out->content_type_len = value.len;
// In ngx_http_test_content_type() nginx will allocate and calculate
// content_type_lowcase if we leave it as null.
headers_out->content_type_lowcase = NULL;
continue;
}
u_char* name_s = ngx_pstrdup(request_->pool, &name);
if (name_s == NULL) {
return NGX_ERROR;
}
ngx_table_elt_t* header = static_cast<ngx_table_elt_t*>(
ngx_list_push(&headers_out->headers));
if (header == NULL) {
return NGX_ERROR;
}
header->hash = 1; // Include this header in the output.
header->key.len = name.len;
header->key.data = name_s;
header->value.len = value.len;
header->value.data = value_s;
// Populate the shortcuts to commonly used headers.
if (STR_EQ_LITERAL(name, "Date")) {
headers_out->date = header;
} else if (STR_EQ_LITERAL(name, "Etag")) {
headers_out->etag = header;
} else if (STR_EQ_LITERAL(name, "Expires")) {
headers_out->expires = header;
} else if (STR_EQ_LITERAL(name, "Last-Modified")) {
headers_out->last_modified = header;
} else if (STR_EQ_LITERAL(name, "Location")) {
headers_out->location = header;
} else if (STR_EQ_LITERAL(name, "Server")) {
headers_out->server = header;
}
}
return NGX_OK;
}
void NgxBaseFetch::RequestCollection() {
int rc;
char c = 'A'; // What byte we write is arbitrary.
while (true) {
rc = write(pipe_fd_, &c, 1);
if (rc == 1) {
break;
} else if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) {
// TODO(jefftk): is this rare enough that spinning isn't a problem? Could
// we get into a case where the pipe fills up and we spin forever?
} else {
perror("NgxBaseFetch::RequestCollection");
break;
}
}
}
void NgxBaseFetch::HandleHeadersComplete() {
RequestCollection(); // Headers available.
}
bool NgxBaseFetch::HandleFlush(MessageHandler* handler) {
RequestCollection(); // A new part of the response body is available.
return true;
}
void NgxBaseFetch::HandleDone(bool success) {
// TODO(jefftk): it's possible that instead of locking here we can just modify
// CopyBufferToNginx to only read done_called_ once.
Lock();
done_called_ = true;
Unlock();
close(pipe_fd_); // Indicates to nginx that we're done with the rewrite.
pipe_fd_ = -1;
}
} // namespace net_instaweb
<|endoftext|> |
<commit_before>/******************************************************************************
Configuration file for nomlib library
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#ifndef NOMLIB_CONFIG_HEADERS
#define NOMLIB_CONFIG_HEADERS
#include <iostream>
#include <cassert>
#include "nomlib_types.hpp"
#include "sys/Logger.hpp"
// nomlib version
#define NOMLIB_VERSION_MAJOR 0
#define NOMLIB_VERSION_MINOR 0
// Identification the operating system
#if defined ( _WIN32) || defined ( __WIN32__ )
#define NOMLIB_SYSTEM_WINDOWS
#elif defined ( linux ) || defined ( __linux )
#define NOMLIB_SYSTEM_LINUX
#elif defined ( __APPLE__ ) || defined ( MACOSX ) || defined ( macintosh ) || defined ( Macintosh )
#define NOMLIB_SYSTEM_OSX
#else
#warning This operating system is not officially supported by nomlib
#endif
// Function names and preferably also its type signature
#if defined ( _MSC_VER ) // MSVC++
// TODO: Presumably the same as GNU's __PRETTY_FUNCTION__ ?
//
// SOURCE: http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx
#define __func__ __FUNCSIG__
#else // We assume GNU v2+
// The type signature is nice because this shows if the function calling type
// is a virtual or not and even what arguments the function has
#define __func__ __PRETTY_FUNCTION__
#endif
// nomlib debugging
// Standard debug level; logging of warnings & errors
//#define NOMLIB_DEBUG
// Internal development; logging of class object construction and destruction
#define NOMLIB_DEBUG_ALL
// Pretty print C macros
#ifdef NOMLIB_DEBUG_ALL
// If all debugging is turned on, we show class construction and destruction
#define NOMLIB_LOG_INFO ( nom::Logger::info ( __func__ ) )
#else // We do not add any overhead
#define NOMLIB_LOG_INFO
#endif
#ifdef NOMLIB_DEBUG
// If all debugging is turned on, we show all errors logged
#define NOMLIB_LOG_ERR(message) ( nom::Logger::err ( __FILE__, __LINE__, message ) )
#define NOMLIB_ASSERT(expression) ( assert (expression) )
#else // We do not add any overhead
#define NOMLIB_LOG_ERR(message)
#define NOMLIB_ASSERT(expression)
#endif
#endif // NOMLIB_CONFIG_HEADERS defined
<commit_msg>Re-enable debugging<commit_after>/******************************************************************************
Configuration file for nomlib library
Copyright (c) 2013 Jeffrey Carpenter
******************************************************************************/
#ifndef NOMLIB_CONFIG_HEADERS
#define NOMLIB_CONFIG_HEADERS
#include <iostream>
#include <cassert>
#include "nomlib_types.hpp"
#include "sys/Logger.hpp"
// nomlib version
#define NOMLIB_VERSION_MAJOR 0
#define NOMLIB_VERSION_MINOR 0
// Identification the operating system
#if defined ( _WIN32) || defined ( __WIN32__ )
#define NOMLIB_SYSTEM_WINDOWS
#elif defined ( linux ) || defined ( __linux )
#define NOMLIB_SYSTEM_LINUX
#elif defined ( __APPLE__ ) || defined ( MACOSX ) || defined ( macintosh ) || defined ( Macintosh )
#define NOMLIB_SYSTEM_OSX
#else
#warning This operating system is not officially supported by nomlib
#endif
// Function names and preferably also its type signature
#if defined ( _MSC_VER ) // MSVC++
// TODO: Presumably the same as GNU's __PRETTY_FUNCTION__ ?
//
// SOURCE: http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx
#define __func__ __FUNCSIG__
#else // We assume GNU v2+
// The type signature is nice because this shows if the function calling type
// is a virtual or not and even what arguments the function has
#define __func__ __PRETTY_FUNCTION__
#endif
// nomlib debugging
// Standard debug level; logging of warnings & errors
#define NOMLIB_DEBUG
// Internal development; logging of class object construction and destruction
#define NOMLIB_DEBUG_ALL
// Pretty print C macros
#ifdef NOMLIB_DEBUG_ALL
// If all debugging is turned on, we show class construction and destruction
#define NOMLIB_LOG_INFO ( nom::Logger::info ( __func__ ) )
#else // We do not add any overhead
#define NOMLIB_LOG_INFO
#endif
#ifdef NOMLIB_DEBUG
// If all debugging is turned on, we show all errors logged
#define NOMLIB_LOG_ERR(message) ( nom::Logger::err ( __FILE__, __LINE__, message ) )
#define NOMLIB_ASSERT(expression) ( assert (expression) )
#else // We do not add any overhead
#define NOMLIB_LOG_ERR(message)
#define NOMLIB_ASSERT(expression)
#endif
#endif // NOMLIB_CONFIG_HEADERS defined
<|endoftext|> |
<commit_before>#ifndef option_manager_hh_INCLUDED
#define option_manager_hh_INCLUDED
#include "completion.hh"
#include "containers.hh"
#include "exception.hh"
#include "flags.hh"
#include "option_types.hh"
#include "vector.hh"
#include <memory>
#include <type_traits>
namespace Kakoune
{
class OptionManager;
enum class OptionFlags
{
None = 0,
Hidden = 1,
};
template<> struct WithBitOps<OptionFlags> : std::true_type {};
class OptionDesc
{
public:
OptionDesc(String name, String docstring, OptionFlags flags);
const String& name() const { return m_name; }
const String& docstring() const { return m_docstring; }
OptionFlags flags() const { return m_flags; }
private:
String m_name;
String m_docstring;
OptionFlags m_flags;
};
class Option
{
public:
virtual ~Option() = default;
template<typename T> const T& get() const;
template<typename T> T& get_mutable();
template<typename T> void set(const T& val, bool notify=true);
template<typename T> bool is_of_type() const;
virtual String get_as_string() const = 0;
virtual void set_from_string(StringView str) = 0;
virtual void add_from_string(StringView str) = 0;
virtual Option* clone(OptionManager& manager) const = 0;
OptionManager& manager() const { return m_manager; }
const String& name() const { return m_desc.name(); }
const String& docstring() const { return m_desc.docstring(); }
OptionFlags flags() const { return m_desc.flags(); }
protected:
Option(const OptionDesc& desc, OptionManager& manager);
OptionManager& m_manager;
const OptionDesc& m_desc;
};
class OptionManagerWatcher
{
public:
virtual ~OptionManagerWatcher() {}
virtual void on_option_changed(const Option& option) = 0;
};
class OptionManager : private OptionManagerWatcher
{
public:
OptionManager(OptionManager& parent);
~OptionManager();
Option& operator[] (StringView name);
const Option& operator[] (StringView name) const;
Option& get_local_option(StringView name);
void unset_option(StringView name);
using OptionList = Vector<const Option*>;
OptionList flatten_options() const;
void register_watcher(OptionManagerWatcher& watcher);
void unregister_watcher(OptionManagerWatcher& watcher);
void on_option_changed(const Option& option) override;
private:
OptionManager()
: m_parent(nullptr) {}
// the only one allowed to construct a root option manager
friend class Scope;
friend class OptionsRegistry;
Vector<std::unique_ptr<Option>, MemoryDomain::Options> m_options;
OptionManager* m_parent;
Vector<OptionManagerWatcher*, MemoryDomain::Options> m_watchers;
};
template<typename T>
class TypedOption : public Option
{
public:
TypedOption(OptionManager& manager, const OptionDesc& desc, const T& value)
: Option(desc, manager), m_value(value) {}
void set(T value, bool notify = true)
{
validate(value);
if (m_value != value)
{
m_value = std::move(value);
if (notify)
manager().on_option_changed(*this);
}
}
const T& get() const { return m_value; }
T& get_mutable() { return m_value; }
String get_as_string() const override
{
return option_to_string(m_value);
}
void set_from_string(StringView str) override
{
T val;
option_from_string(str, val);
set(std::move(val));
}
void add_from_string(StringView str) override
{
if (option_add(m_value, str))
m_manager.on_option_changed(*this);
}
using Alloc = Allocator<TypedOption, MemoryDomain::Options>;
static void* operator new (std::size_t sz)
{
kak_assert(sz == sizeof(TypedOption));
return Alloc{}.allocate(1);
}
static void operator delete (void* ptr)
{
return Alloc{}.deallocate(reinterpret_cast<TypedOption*>(ptr), 1);
}
private:
virtual void validate(const T& value) const {}
T m_value;
};
template<typename T, void (*validator)(const T&)>
class TypedCheckedOption : public TypedOption<T>
{
using TypedOption<T>::TypedOption;
Option* clone(OptionManager& manager) const override
{
return new TypedCheckedOption{manager, this->m_desc, this->get()};
}
void validate(const T& value) const override { if (validator != nullptr) validator(value); }
};
template<typename T> const T& Option::get() const
{
auto* typed_opt = dynamic_cast<const TypedOption<T>*>(this);
if (not typed_opt)
throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name()));
return typed_opt->get();
}
template<typename T> T& Option::get_mutable()
{
return const_cast<T&>(get<T>());
}
template<typename T> void Option::set(const T& val, bool notify)
{
auto* typed_opt = dynamic_cast<TypedOption<T>*>(this);
if (not typed_opt)
throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name()));
return typed_opt->set(val, notify);
}
template<typename T> bool Option::is_of_type() const
{
return dynamic_cast<const TypedOption<T>*>(this) != nullptr;
}
template<typename T>
auto find_option(T& container, StringView name) -> decltype(container.begin())
{
using ptr_type = decltype(*container.begin());
return find_if(container, [&name](const ptr_type& opt) { return opt->name() == name; });
}
class OptionsRegistry
{
public:
OptionsRegistry(OptionManager& global_manager) : m_global_manager(global_manager) {}
template<typename T, void (*validator)(const T&) = nullptr>
Option& declare_option(StringView name, StringView docstring,
const T& value,
OptionFlags flags = OptionFlags::None)
{
auto& opts = m_global_manager.m_options;
auto it = find_option(opts, name);
if (it != opts.end())
{
if ((*it)->is_of_type<T>() and (*it)->flags() == flags)
return **it;
throw runtime_error(format("option '{}' already declared with different type or flags", name));
}
m_descs.emplace_back(new OptionDesc{name.str(), format("({}): {}", option_type_name<T>::name(), docstring), flags});
opts.emplace_back(new TypedCheckedOption<T, validator>{m_global_manager, *m_descs.back(), value});
return *opts.back();
}
const OptionDesc* option_desc(StringView name) const
{
auto it = find_if(m_descs,
[&name](const std::unique_ptr<OptionDesc>& opt)
{ return opt->name() == name; });
return it != m_descs.end() ? it->get() : nullptr;
}
bool option_exists(StringView name) const { return option_desc(name) != nullptr; }
CandidateList complete_option_name(StringView prefix, ByteCount cursor_pos) const;
private:
OptionManager& m_global_manager;
Vector<std::unique_ptr<OptionDesc>, MemoryDomain::Options> m_descs;
};
}
#endif // option_manager_hh_INCLUDED
<commit_msg>Tweak format of option docstrings<commit_after>#ifndef option_manager_hh_INCLUDED
#define option_manager_hh_INCLUDED
#include "completion.hh"
#include "containers.hh"
#include "exception.hh"
#include "flags.hh"
#include "option_types.hh"
#include "vector.hh"
#include <memory>
#include <type_traits>
namespace Kakoune
{
class OptionManager;
enum class OptionFlags
{
None = 0,
Hidden = 1,
};
template<> struct WithBitOps<OptionFlags> : std::true_type {};
class OptionDesc
{
public:
OptionDesc(String name, String docstring, OptionFlags flags);
const String& name() const { return m_name; }
const String& docstring() const { return m_docstring; }
OptionFlags flags() const { return m_flags; }
private:
String m_name;
String m_docstring;
OptionFlags m_flags;
};
class Option
{
public:
virtual ~Option() = default;
template<typename T> const T& get() const;
template<typename T> T& get_mutable();
template<typename T> void set(const T& val, bool notify=true);
template<typename T> bool is_of_type() const;
virtual String get_as_string() const = 0;
virtual void set_from_string(StringView str) = 0;
virtual void add_from_string(StringView str) = 0;
virtual Option* clone(OptionManager& manager) const = 0;
OptionManager& manager() const { return m_manager; }
const String& name() const { return m_desc.name(); }
const String& docstring() const { return m_desc.docstring(); }
OptionFlags flags() const { return m_desc.flags(); }
protected:
Option(const OptionDesc& desc, OptionManager& manager);
OptionManager& m_manager;
const OptionDesc& m_desc;
};
class OptionManagerWatcher
{
public:
virtual ~OptionManagerWatcher() {}
virtual void on_option_changed(const Option& option) = 0;
};
class OptionManager : private OptionManagerWatcher
{
public:
OptionManager(OptionManager& parent);
~OptionManager();
Option& operator[] (StringView name);
const Option& operator[] (StringView name) const;
Option& get_local_option(StringView name);
void unset_option(StringView name);
using OptionList = Vector<const Option*>;
OptionList flatten_options() const;
void register_watcher(OptionManagerWatcher& watcher);
void unregister_watcher(OptionManagerWatcher& watcher);
void on_option_changed(const Option& option) override;
private:
OptionManager()
: m_parent(nullptr) {}
// the only one allowed to construct a root option manager
friend class Scope;
friend class OptionsRegistry;
Vector<std::unique_ptr<Option>, MemoryDomain::Options> m_options;
OptionManager* m_parent;
Vector<OptionManagerWatcher*, MemoryDomain::Options> m_watchers;
};
template<typename T>
class TypedOption : public Option
{
public:
TypedOption(OptionManager& manager, const OptionDesc& desc, const T& value)
: Option(desc, manager), m_value(value) {}
void set(T value, bool notify = true)
{
validate(value);
if (m_value != value)
{
m_value = std::move(value);
if (notify)
manager().on_option_changed(*this);
}
}
const T& get() const { return m_value; }
T& get_mutable() { return m_value; }
String get_as_string() const override
{
return option_to_string(m_value);
}
void set_from_string(StringView str) override
{
T val;
option_from_string(str, val);
set(std::move(val));
}
void add_from_string(StringView str) override
{
if (option_add(m_value, str))
m_manager.on_option_changed(*this);
}
using Alloc = Allocator<TypedOption, MemoryDomain::Options>;
static void* operator new (std::size_t sz)
{
kak_assert(sz == sizeof(TypedOption));
return Alloc{}.allocate(1);
}
static void operator delete (void* ptr)
{
return Alloc{}.deallocate(reinterpret_cast<TypedOption*>(ptr), 1);
}
private:
virtual void validate(const T& value) const {}
T m_value;
};
template<typename T, void (*validator)(const T&)>
class TypedCheckedOption : public TypedOption<T>
{
using TypedOption<T>::TypedOption;
Option* clone(OptionManager& manager) const override
{
return new TypedCheckedOption{manager, this->m_desc, this->get()};
}
void validate(const T& value) const override { if (validator != nullptr) validator(value); }
};
template<typename T> const T& Option::get() const
{
auto* typed_opt = dynamic_cast<const TypedOption<T>*>(this);
if (not typed_opt)
throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name()));
return typed_opt->get();
}
template<typename T> T& Option::get_mutable()
{
return const_cast<T&>(get<T>());
}
template<typename T> void Option::set(const T& val, bool notify)
{
auto* typed_opt = dynamic_cast<TypedOption<T>*>(this);
if (not typed_opt)
throw runtime_error(format("option '{}' is not of type '{}'", name(), typeid(T).name()));
return typed_opt->set(val, notify);
}
template<typename T> bool Option::is_of_type() const
{
return dynamic_cast<const TypedOption<T>*>(this) != nullptr;
}
template<typename T>
auto find_option(T& container, StringView name) -> decltype(container.begin())
{
using ptr_type = decltype(*container.begin());
return find_if(container, [&name](const ptr_type& opt) { return opt->name() == name; });
}
class OptionsRegistry
{
public:
OptionsRegistry(OptionManager& global_manager) : m_global_manager(global_manager) {}
template<typename T, void (*validator)(const T&) = nullptr>
Option& declare_option(StringView name, StringView docstring,
const T& value,
OptionFlags flags = OptionFlags::None)
{
auto& opts = m_global_manager.m_options;
auto it = find_option(opts, name);
if (it != opts.end())
{
if ((*it)->is_of_type<T>() and (*it)->flags() == flags)
return **it;
throw runtime_error(format("option '{}' already declared with different type or flags", name));
}
String doc = docstring.empty() ? format("[{}]", option_type_name<T>::name())
: format("[{}] - {}", option_type_name<T>::name(), docstring);
m_descs.emplace_back(new OptionDesc{name.str(), std::move(doc), flags});
opts.emplace_back(new TypedCheckedOption<T, validator>{m_global_manager, *m_descs.back(), value});
return *opts.back();
}
const OptionDesc* option_desc(StringView name) const
{
auto it = find_if(m_descs,
[&name](const std::unique_ptr<OptionDesc>& opt)
{ return opt->name() == name; });
return it != m_descs.end() ? it->get() : nullptr;
}
bool option_exists(StringView name) const { return option_desc(name) != nullptr; }
CandidateList complete_option_name(StringView prefix, ByteCount cursor_pos) const;
private:
OptionManager& m_global_manager;
Vector<std::unique_ptr<OptionDesc>, MemoryDomain::Options> m_descs;
};
}
#endif // option_manager_hh_INCLUDED
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/GLExtensions>
#include <osg/Texture2D>
#include <osg/State>
#include <osg/GLU>
typedef void (APIENTRY * MyCompressedTexImage2DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
using namespace osg;
Texture2D::Texture2D():
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
}
Texture2D::Texture2D(osg::Image* image):
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
setImage(image);
}
Texture2D::Texture2D(const Texture2D& text,const CopyOp& copyop):
Texture(text,copyop),
_image(copyop(text._image.get())),
_textureWidth(text._textureWidth),
_textureHeight(text._textureHeight),
_numMipmapLevels(text._numMipmapLevels),
_subloadCallback(text._subloadCallback)
{
}
Texture2D::~Texture2D()
{
}
int Texture2D::compare(const StateAttribute& sa) const
{
// check the types are equal and then create the rhs variable
// used by the COMPARE_StateAttribute_Paramter macro's below.
COMPARE_StateAttribute_Types(Texture2D,sa)
if (_image!=rhs._image) // smart pointer comparison.
{
if (_image.valid())
{
if (rhs._image.valid())
{
int result = _image->compare(*rhs._image);
if (result!=0) return result;
}
else
{
return 1; // valid lhs._image is greater than null.
}
}
else if (rhs._image.valid())
{
return -1; // valid rhs._image is greater than null.
}
}
int result = compareTexture(rhs);
if (result!=0) return result;
// compare each paramter in turn against the rhs.
COMPARE_StateAttribute_Parameter(_textureWidth)
COMPARE_StateAttribute_Parameter(_textureHeight)
COMPARE_StateAttribute_Parameter(_subloadCallback)
return 0; // passed all the above comparison macro's, must be equal.
}
void Texture2D::setImage(Image* image)
{
_image = image;
_modifiedTag.setAllElementsTo(0);
}
void Texture2D::apply(State& state) const
{
//state.setReportGLErrors(true);
// get the contextID (user defined ID of 0 upwards) for the
// current OpenGL context.
const unsigned int contextID = state.getContextID();
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject != 0)
{
textureObject->bind();
if (getTextureParameterDirty(state.getContextID()))
applyTexParameters(GL_TEXTURE_2D,state);
if (_subloadCallback.valid())
{
_subloadCallback->subload(*this,state);
}
else if (_image.valid() && getModifiedTag(contextID) != _image->getModifiedTag())
{
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
}
}
else if (_subloadCallback.valid())
{
_textureObjectBuffer[contextID] = textureObject = getTextureObjectManager()->generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
_subloadCallback->load(*this,state);
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else if (_image.valid() && _image->data())
{
// compute the internal texture format, this set the _internalFormat to an appropriate value.
computeInternalFormat();
// compute the dimensions of the texture.
computeRequiredTextureDimensions(state,*_image,_textureWidth, _textureHeight, _numMipmapLevels);
_textureObjectBuffer[contextID] = textureObject = getTextureObjectManager()->reuseOrGenerateTextureObject(
contextID,GL_TEXTURE_2D,_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
if (textureObject->isAllocated())
{
//std::cout<<"Reusing texture object"<<std::endl;
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
}
else
{
//std::cout<<"Creating new texture object"<<std::endl;
applyTexImage2D_load(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
textureObject->setAllocated(true);
}
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
if (_unrefImageDataAfterApply && areAllTextureObjectsLoaded())
{
Texture2D* non_const_this = const_cast<Texture2D*>(this);
non_const_this->_image = 0;
}
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else
{
glBindTexture( GL_TEXTURE_2D, 0 );
}
}
void Texture2D::computeInternalFormat() const
{
if (_image.valid()) computeInternalFormatWithImage(*_image);
}
void Texture2D::copyTexImage2D(State& state, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
// get the globj for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
if (width==(int)_textureWidth && height==(int)_textureHeight)
{
// we have a valid texture object which is the right size
// so lets play clever and use copyTexSubImage2D instead.
// this allows use to reuse the texture object and avoid
// expensive memory allocations.
copyTexSubImage2D(state,0 ,0, x, y, width, height);
return;
}
// the relevent texture object is not of the right size so
// needs to been deleted
// remove previously bound textures.
dirtyTextureObject();
// note, dirtyTextureObject() dirties all the texture objects for
// this texture, is this right? Perhaps we should dirty just the
// one for this context. Note sure yet will leave till later.
// RO July 2001.
}
// remove any previously assigned images as these are nolonger valid.
_image = NULL;
// switch off mip-mapping.
_min_filter = LINEAR;
_mag_filter = LINEAR;
_textureObjectBuffer[contextID] = textureObject = getTextureObjectManager()->generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
glCopyTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, x, y, width, height, 0 );
_textureWidth = width;
_textureHeight = height;
_numMipmapLevels = 1;
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
void Texture2D::copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
// we have a valid image
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
glCopyTexSubImage2D( GL_TEXTURE_2D, 0, xoffset,yoffset, x, y, width, height);
/* Redundant, delete later */
//glBindTexture( GL_TEXTURE_2D, handle );
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
else
{
// no texture object already exsits for this context so need to
// create it upfront - simply call copyTexImage2D.
copyTexImage2D(state,x,y,width,height);
}
}
<commit_msg>From Romano J M Silva, changed osg::Texture2D::copyTexImage2D so that it uses the _internalFormat for the texture format to read rather than default to GL_RGBA.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/GLExtensions>
#include <osg/Texture2D>
#include <osg/State>
#include <osg/GLU>
typedef void (APIENTRY * MyCompressedTexImage2DArbProc) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
using namespace osg;
Texture2D::Texture2D():
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
}
Texture2D::Texture2D(osg::Image* image):
_textureWidth(0),
_textureHeight(0),
_numMipmapLevels(0)
{
setUseHardwareMipMapGeneration(true);
setImage(image);
}
Texture2D::Texture2D(const Texture2D& text,const CopyOp& copyop):
Texture(text,copyop),
_image(copyop(text._image.get())),
_textureWidth(text._textureWidth),
_textureHeight(text._textureHeight),
_numMipmapLevels(text._numMipmapLevels),
_subloadCallback(text._subloadCallback)
{
}
Texture2D::~Texture2D()
{
}
int Texture2D::compare(const StateAttribute& sa) const
{
// check the types are equal and then create the rhs variable
// used by the COMPARE_StateAttribute_Paramter macro's below.
COMPARE_StateAttribute_Types(Texture2D,sa)
if (_image!=rhs._image) // smart pointer comparison.
{
if (_image.valid())
{
if (rhs._image.valid())
{
int result = _image->compare(*rhs._image);
if (result!=0) return result;
}
else
{
return 1; // valid lhs._image is greater than null.
}
}
else if (rhs._image.valid())
{
return -1; // valid rhs._image is greater than null.
}
}
int result = compareTexture(rhs);
if (result!=0) return result;
// compare each paramter in turn against the rhs.
COMPARE_StateAttribute_Parameter(_textureWidth)
COMPARE_StateAttribute_Parameter(_textureHeight)
COMPARE_StateAttribute_Parameter(_subloadCallback)
return 0; // passed all the above comparison macro's, must be equal.
}
void Texture2D::setImage(Image* image)
{
_image = image;
_modifiedTag.setAllElementsTo(0);
}
void Texture2D::apply(State& state) const
{
//state.setReportGLErrors(true);
// get the contextID (user defined ID of 0 upwards) for the
// current OpenGL context.
const unsigned int contextID = state.getContextID();
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject != 0)
{
textureObject->bind();
if (getTextureParameterDirty(state.getContextID()))
applyTexParameters(GL_TEXTURE_2D,state);
if (_subloadCallback.valid())
{
_subloadCallback->subload(*this,state);
}
else if (_image.valid() && getModifiedTag(contextID) != _image->getModifiedTag())
{
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
}
}
else if (_subloadCallback.valid())
{
_textureObjectBuffer[contextID] = textureObject = getTextureObjectManager()->generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
_subloadCallback->load(*this,state);
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else if (_image.valid() && _image->data())
{
// compute the internal texture format, this set the _internalFormat to an appropriate value.
computeInternalFormat();
// compute the dimensions of the texture.
computeRequiredTextureDimensions(state,*_image,_textureWidth, _textureHeight, _numMipmapLevels);
_textureObjectBuffer[contextID] = textureObject = getTextureObjectManager()->reuseOrGenerateTextureObject(
contextID,GL_TEXTURE_2D,_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
if (textureObject->isAllocated())
{
//std::cout<<"Reusing texture object"<<std::endl;
applyTexImage2D_subload(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
}
else
{
//std::cout<<"Creating new texture object"<<std::endl;
applyTexImage2D_load(state,GL_TEXTURE_2D,_image.get(),
_textureWidth, _textureHeight, _numMipmapLevels);
textureObject->setAllocated(true);
}
// update the modified tag to show that it is upto date.
getModifiedTag(contextID) = _image->getModifiedTag();
if (_unrefImageDataAfterApply && areAllTextureObjectsLoaded())
{
Texture2D* non_const_this = const_cast<Texture2D*>(this);
non_const_this->_image = 0;
}
// in theory the following line is redundent, but in practice
// have found that the first frame drawn doesn't apply the textures
// unless a second bind is called?!!
// perhaps it is the first glBind which is not required...
//glBindTexture( GL_TEXTURE_2D, handle );
}
else
{
glBindTexture( GL_TEXTURE_2D, 0 );
}
}
void Texture2D::computeInternalFormat() const
{
if (_image.valid()) computeInternalFormatWithImage(*_image);
}
void Texture2D::copyTexImage2D(State& state, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
if (_internalFormat==0) _internalFormat=GL_RGBA;
// get the globj for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
if (width==(int)_textureWidth && height==(int)_textureHeight)
{
// we have a valid texture object which is the right size
// so lets play clever and use copyTexSubImage2D instead.
// this allows use to reuse the texture object and avoid
// expensive memory allocations.
copyTexSubImage2D(state,0 ,0, x, y, width, height);
return;
}
// the relevent texture object is not of the right size so
// needs to been deleted
// remove previously bound textures.
dirtyTextureObject();
// note, dirtyTextureObject() dirties all the texture objects for
// this texture, is this right? Perhaps we should dirty just the
// one for this context. Note sure yet will leave till later.
// RO July 2001.
}
// remove any previously assigned images as these are nolonger valid.
_image = NULL;
// switch off mip-mapping.
_min_filter = LINEAR;
_mag_filter = LINEAR;
_textureObjectBuffer[contextID] = textureObject = getTextureObjectManager()->generateTextureObject(contextID,GL_TEXTURE_2D);
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
glCopyTexImage2D( GL_TEXTURE_2D, 0, _internalFormat, x, y, width, height, 0 );
_textureWidth = width;
_textureHeight = height;
_numMipmapLevels = 1;
textureObject->setAllocated(_numMipmapLevels,_internalFormat,_textureWidth,_textureHeight,1,0);
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
void Texture2D::copyTexSubImage2D(State& state, int xoffset, int yoffset, int x, int y, int width, int height )
{
const unsigned int contextID = state.getContextID();
if (_internalFormat==0) _internalFormat=GL_RGBA;
// get the texture object for the current contextID.
TextureObject* textureObject = getTextureObject(contextID);
if (textureObject)
{
// we have a valid image
textureObject->bind();
applyTexParameters(GL_TEXTURE_2D,state);
glCopyTexSubImage2D( GL_TEXTURE_2D, 0, xoffset,yoffset, x, y, width, height);
/* Redundant, delete later */
//glBindTexture( GL_TEXTURE_2D, handle );
// inform state that this texture is the current one bound.
state.haveAppliedAttribute(this);
}
else
{
// no texture object already exsits for this context so need to
// create it upfront - simply call copyTexImage2D.
copyTexImage2D(state,x,y,width,height);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletview.h"
#include "addressbookpage.h"
#include "askpassphrasedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "masternodeconfig.h"
#include "systemnodeconfig.h"
#include "optionsmodel.h"
#include "overviewpage.h"
#include "receivecoinsdialog.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "transactiontablemodel.h"
#include "transactionview.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "ui_interface.h"
#include <QAction>
#include <QActionGroup>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QProgressDialog>
#include <QPushButton>
#include <QVBoxLayout>
WalletView::WalletView(QWidget *parent):
QStackedWidget(parent),
clientModel(0),
walletModel(0)
{
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
QHBoxLayout *hbox_buttons = new QHBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
QPushButton *exportButton = new QPushButton(tr("&Export"), this);
exportButton->setToolTip(tr("Export the data in the current tab to a file"));
#ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
exportButton->setIcon(QIcon(":/icons/export"));
#endif
hbox_buttons->addStretch();
// Sum of selected transactions
QLabel *transactionSumLabel = new QLabel(); // Label
transactionSumLabel->setObjectName("transactionSumLabel"); // Label ID as CSS-reference
transactionSumLabel->setText(tr("Selected amount:"));
hbox_buttons->addWidget(transactionSumLabel);
transactionSum = new QLabel(); // Amount
transactionSum->setObjectName("transactionSum"); // Label ID as CSS-reference
transactionSum->setMinimumSize(200, 8);
transactionSum->setTextInteractionFlags(Qt::TextSelectableByMouse);
hbox_buttons->addWidget(transactionSum);
hbox_buttons->addWidget(exportButton);
vbox->addLayout(hbox_buttons);
transactionsPage->setLayout(vbox);
receiveCoinsPage = new ReceiveCoinsDialog();
sendCoinsPage = new SendCoinsDialog();
if (masternodeConfig.getCount() >= 0) {
masternodeListPage = new MasternodeList();
}
if (systemnodeConfig.getCount() >= 0) {
systemnodeListPage = new SystemnodeList();
}
addWidget(overviewPage);
addWidget(transactionsPage);
addWidget(receiveCoinsPage);
addWidget(sendCoinsPage);
if (masternodeConfig.getCount() >= 0) {
addWidget(masternodeListPage);
}
if (systemnodeConfig.getCount() >= 0) {
addWidget(systemnodeListPage);
}
// Clicking on a transaction on the overview pre-selects the transaction on the transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
// Update wallet with sum of selected transactions
connect(transactionView, SIGNAL(trxAmount(QString)), this, SLOT(trxAmount(QString)));
// Clicking on "Export" allows to export the transaction list
connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));
// Pass through messages from sendCoinsPage
connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
// Pass through messages from transactionView
connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
}
WalletView::~WalletView()
{
}
void WalletView::setBitcoinGUI(BitcoinGUI *gui)
{
if (gui)
{
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage()));
// Receive and report messages
connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));
// Pass through encryption status changed signals
connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));
// Pass through transaction notifications
connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString)));
}
}
void WalletView::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
overviewPage->setClientModel(clientModel);
sendCoinsPage->setClientModel(clientModel);
if (masternodeConfig.getCount() >= 0) {
masternodeListPage->setClientModel(clientModel);
}
if (systemnodeConfig.getCount() >= 0) {
systemnodeListPage->setClientModel(clientModel);
}
}
void WalletView::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setWalletModel(walletModel);
receiveCoinsPage->setModel(walletModel);
sendCoinsPage->setModel(walletModel);
if (masternodeConfig.getCount() >= 0) {
masternodeListPage->setWalletModel(walletModel);
}
if (systemnodeConfig.getCount() >= 0) {
systemnodeListPage->setWalletModel(walletModel);
}
if (walletModel)
{
// Receive and pass through messages from wallet model
connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
// Handle changes in encryption status
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int)));
updateEncryptionStatus();
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(processNewTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
// Show progress dialog
connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
}
}
void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/)
{
// Prevent balloon-spam when initial block download is in progress
if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
if (!ttm || ttm->processingQueuedTransactions())
return;
QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();
// If payment is 500 or 10000 CRW ask to create a Systemnode/Masternode
qint64 credit = ttm->index(start, TransactionTableModel::AmountCredit, parent).data(Qt::EditRole).toULongLong();
int typeEnum = ttm->index(start, TransactionTableModel::TypeEnum, parent).data(Qt::EditRole).toInt();
if (typeEnum == TransactionRecord::SendToSelf)
{
AvailableCoinsType coin_type = ONLY_500;
QString title = tr("Payment to yourself - ") +
BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), credit);
QString body = tr("Do you wat to create a new ");
if (credit == SYSTEMNODE_COLLATERAL * COIN)
{
body += "Systemnode?";
}
else if (credit == MASTERNODE_COLLATERAL * COIN)
{
body += "Masternode?";
coin_type = ONLY_10000;
}
// Display message box
QMessageBox::StandardButton retval = QMessageBox::question(this, title, body,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
QString hash = ttm->index(start, 0, parent).data(TransactionTableModel::TxHashRole).toString();
std::vector<COutput> vPossibleCoins;
pwalletMain->AvailableCoins(vPossibleCoins, true, NULL, coin_type);
BOOST_FOREACH(COutput& out, vPossibleCoins) {
if (out.tx->GetHash().ToString() == hash.toStdString())
{
COutPoint outpoint = COutPoint(out.tx->GetHash(), boost::lexical_cast<unsigned int>(out.i));
pwalletMain->LockCoin(outpoint);
// Generate a key
CKey secret;
secret.MakeNewKey(false);
std::string privateKey = CBitcoinSecret(secret).ToString();
systemnodeConfig.add("", "", privateKey, hash.toStdString(), strprintf("%d", out.i));
systemnodeListPage->updateMyNodeList(true);
}
}
}
}
emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}
void WalletView::gotoOverviewPage()
{
setCurrentWidget(overviewPage);
}
void WalletView::gotoHistoryPage()
{
setCurrentWidget(transactionsPage);
}
void WalletView::gotoReceiveCoinsPage()
{
setCurrentWidget(receiveCoinsPage);
}
void WalletView::gotoSendCoinsPage(QString addr)
{
setCurrentWidget(sendCoinsPage);
if (!addr.isEmpty())
sendCoinsPage->setAddress(addr);
}
void WalletView::gotoMasternodePage()
{
if (masternodeConfig.getCount() >= 0) {
setCurrentWidget(masternodeListPage);
}
}
void WalletView::gotoSystemnodePage()
{
if (systemnodeConfig.getCount() >= 0) {
setCurrentWidget(systemnodeListPage);
}
}
void WalletView::gotoMultisigTab()
{
// calls show() in showTab_SM()
MultisigDialog *multisigDialog = new MultisigDialog(this);
multisigDialog->setAttribute(Qt::WA_DeleteOnClose);
multisigDialog->setModel(walletModel);
multisigDialog->showTab(true);
}
void WalletView::gotoSignMessageTab(QString addr)
{
// calls show() in showTab_SM()
SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
signVerifyMessageDialog->setModel(walletModel);
signVerifyMessageDialog->showTab_SM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void WalletView::gotoVerifyMessageTab(QString addr)
{
// calls show() in showTab_VM()
SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
signVerifyMessageDialog->setModel(walletModel);
signVerifyMessageDialog->showTab_VM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
return sendCoinsPage->handlePaymentRequest(recipient);
}
void WalletView::showOutOfSyncWarning(bool fShow)
{
overviewPage->showOutOfSyncWarning(fShow);
}
void WalletView::updateEncryptionStatus()
{
emit encryptionStatusChanged(walletModel->getEncryptionStatus());
}
void WalletView::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
updateEncryptionStatus();
}
void WalletView::backupWallet()
{
QString filename = GUIUtil::getSaveFileName(this,
tr("Backup Wallet"), QString(),
tr("Wallet Data (*.dat)"), NULL);
if (filename.isEmpty())
return;
if (!walletModel->backupWallet(filename)) {
emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename),
CClientUIInterface::MSG_ERROR);
}
else {
emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename),
CClientUIInterface::MSG_INFORMATION);
}
}
void WalletView::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void WalletView::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if (walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
void WalletView::lockWallet()
{
if(!walletModel)
return;
walletModel->setWalletLocked(true);
}
void WalletView::usedSendingAddresses()
{
if(!walletModel)
return;
AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this);
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->setModel(walletModel->getAddressTableModel());
dlg->show();
}
void WalletView::usedReceivingAddresses()
{
if(!walletModel)
return;
AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this);
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->setModel(walletModel->getAddressTableModel());
dlg->show();
}
void WalletView::showProgress(const QString &title, int nProgress)
{
if (nProgress == 0)
{
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
}
else if (nProgress == 100)
{
if (progressDialog)
{
progressDialog->close();
progressDialog->deleteLater();
}
}
else if (progressDialog)
progressDialog->setValue(nProgress);
}
/** Update wallet with the sum of the selected transactions */
void WalletView::trxAmount(QString amount)
{
transactionSum->setText(amount);
}
<commit_msg>Fixed condition which asks to create a systemnode<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletview.h"
#include "addressbookpage.h"
#include "askpassphrasedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "masternodeconfig.h"
#include "systemnodeconfig.h"
#include "optionsmodel.h"
#include "overviewpage.h"
#include "receivecoinsdialog.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "transactiontablemodel.h"
#include "transactionview.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "ui_interface.h"
#include <QAction>
#include <QActionGroup>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QLabel>
#include <QProgressDialog>
#include <QPushButton>
#include <QVBoxLayout>
WalletView::WalletView(QWidget *parent):
QStackedWidget(parent),
clientModel(0),
walletModel(0)
{
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
QHBoxLayout *hbox_buttons = new QHBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
QPushButton *exportButton = new QPushButton(tr("&Export"), this);
exportButton->setToolTip(tr("Export the data in the current tab to a file"));
#ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
exportButton->setIcon(QIcon(":/icons/export"));
#endif
hbox_buttons->addStretch();
// Sum of selected transactions
QLabel *transactionSumLabel = new QLabel(); // Label
transactionSumLabel->setObjectName("transactionSumLabel"); // Label ID as CSS-reference
transactionSumLabel->setText(tr("Selected amount:"));
hbox_buttons->addWidget(transactionSumLabel);
transactionSum = new QLabel(); // Amount
transactionSum->setObjectName("transactionSum"); // Label ID as CSS-reference
transactionSum->setMinimumSize(200, 8);
transactionSum->setTextInteractionFlags(Qt::TextSelectableByMouse);
hbox_buttons->addWidget(transactionSum);
hbox_buttons->addWidget(exportButton);
vbox->addLayout(hbox_buttons);
transactionsPage->setLayout(vbox);
receiveCoinsPage = new ReceiveCoinsDialog();
sendCoinsPage = new SendCoinsDialog();
if (masternodeConfig.getCount() >= 0) {
masternodeListPage = new MasternodeList();
}
if (systemnodeConfig.getCount() >= 0) {
systemnodeListPage = new SystemnodeList();
}
addWidget(overviewPage);
addWidget(transactionsPage);
addWidget(receiveCoinsPage);
addWidget(sendCoinsPage);
if (masternodeConfig.getCount() >= 0) {
addWidget(masternodeListPage);
}
if (systemnodeConfig.getCount() >= 0) {
addWidget(systemnodeListPage);
}
// Clicking on a transaction on the overview pre-selects the transaction on the transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
// Update wallet with sum of selected transactions
connect(transactionView, SIGNAL(trxAmount(QString)), this, SLOT(trxAmount(QString)));
// Clicking on "Export" allows to export the transaction list
connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));
// Pass through messages from sendCoinsPage
connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
// Pass through messages from transactionView
connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
}
WalletView::~WalletView()
{
}
void WalletView::setBitcoinGUI(BitcoinGUI *gui)
{
if (gui)
{
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage()));
// Receive and report messages
connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));
// Pass through encryption status changed signals
connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));
// Pass through transaction notifications
connect(this, SIGNAL(incomingTransaction(QString,int,CAmount,QString,QString)), gui, SLOT(incomingTransaction(QString,int,CAmount,QString,QString)));
}
}
void WalletView::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
overviewPage->setClientModel(clientModel);
sendCoinsPage->setClientModel(clientModel);
if (masternodeConfig.getCount() >= 0) {
masternodeListPage->setClientModel(clientModel);
}
if (systemnodeConfig.getCount() >= 0) {
systemnodeListPage->setClientModel(clientModel);
}
}
void WalletView::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setWalletModel(walletModel);
receiveCoinsPage->setModel(walletModel);
sendCoinsPage->setModel(walletModel);
if (masternodeConfig.getCount() >= 0) {
masternodeListPage->setWalletModel(walletModel);
}
if (systemnodeConfig.getCount() >= 0) {
systemnodeListPage->setWalletModel(walletModel);
}
if (walletModel)
{
// Receive and pass through messages from wallet model
connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
// Handle changes in encryption status
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int)));
updateEncryptionStatus();
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(processNewTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
// Show progress dialog
connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
}
}
void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/)
{
// Prevent balloon-spam when initial block download is in progress
if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
if (!ttm || ttm->processingQueuedTransactions())
return;
QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();
// If payment is 500 or 10000 CRW ask to create a Systemnode/Masternode
qint64 credit = ttm->index(start, TransactionTableModel::AmountCredit, parent).data(Qt::EditRole).toULongLong();
int typeEnum = ttm->index(start, TransactionTableModel::TypeEnum, parent).data(Qt::EditRole).toInt();
if (typeEnum == TransactionRecord::SendToSelf && (credit == SYSTEMNODE_COLLATERAL * COIN || credit == MASTERNODE_COLLATERAL * COIN))
{
AvailableCoinsType coin_type = ONLY_500;
QString title = tr("Payment to yourself - ") +
BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), credit);
QString body = tr("Do you want to create a new ");
if (credit == SYSTEMNODE_COLLATERAL * COIN)
{
body += "Systemnode?";
}
else if (credit == MASTERNODE_COLLATERAL * COIN)
{
body += "Masternode?";
coin_type = ONLY_10000;
}
// Display message box
QMessageBox::StandardButton retval = QMessageBox::question(this, title, body,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
QString hash = ttm->index(start, 0, parent).data(TransactionTableModel::TxHashRole).toString();
std::vector<COutput> vPossibleCoins;
pwalletMain->AvailableCoins(vPossibleCoins, true, NULL, coin_type);
BOOST_FOREACH(COutput& out, vPossibleCoins) {
if (out.tx->GetHash().ToString() == hash.toStdString())
{
COutPoint outpoint = COutPoint(out.tx->GetHash(), boost::lexical_cast<unsigned int>(out.i));
pwalletMain->LockCoin(outpoint);
// Generate a key
CKey secret;
secret.MakeNewKey(false);
std::string privateKey = CBitcoinSecret(secret).ToString();
systemnodeConfig.add("", "", privateKey, hash.toStdString(), strprintf("%d", out.i));
systemnodeListPage->updateMyNodeList(true);
}
}
}
}
emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}
void WalletView::gotoOverviewPage()
{
setCurrentWidget(overviewPage);
}
void WalletView::gotoHistoryPage()
{
setCurrentWidget(transactionsPage);
}
void WalletView::gotoReceiveCoinsPage()
{
setCurrentWidget(receiveCoinsPage);
}
void WalletView::gotoSendCoinsPage(QString addr)
{
setCurrentWidget(sendCoinsPage);
if (!addr.isEmpty())
sendCoinsPage->setAddress(addr);
}
void WalletView::gotoMasternodePage()
{
if (masternodeConfig.getCount() >= 0) {
setCurrentWidget(masternodeListPage);
}
}
void WalletView::gotoSystemnodePage()
{
if (systemnodeConfig.getCount() >= 0) {
setCurrentWidget(systemnodeListPage);
}
}
void WalletView::gotoMultisigTab()
{
// calls show() in showTab_SM()
MultisigDialog *multisigDialog = new MultisigDialog(this);
multisigDialog->setAttribute(Qt::WA_DeleteOnClose);
multisigDialog->setModel(walletModel);
multisigDialog->showTab(true);
}
void WalletView::gotoSignMessageTab(QString addr)
{
// calls show() in showTab_SM()
SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
signVerifyMessageDialog->setModel(walletModel);
signVerifyMessageDialog->showTab_SM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void WalletView::gotoVerifyMessageTab(QString addr)
{
// calls show() in showTab_VM()
SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
signVerifyMessageDialog->setModel(walletModel);
signVerifyMessageDialog->showTab_VM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
return sendCoinsPage->handlePaymentRequest(recipient);
}
void WalletView::showOutOfSyncWarning(bool fShow)
{
overviewPage->showOutOfSyncWarning(fShow);
}
void WalletView::updateEncryptionStatus()
{
emit encryptionStatusChanged(walletModel->getEncryptionStatus());
}
void WalletView::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
updateEncryptionStatus();
}
void WalletView::backupWallet()
{
QString filename = GUIUtil::getSaveFileName(this,
tr("Backup Wallet"), QString(),
tr("Wallet Data (*.dat)"), NULL);
if (filename.isEmpty())
return;
if (!walletModel->backupWallet(filename)) {
emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename),
CClientUIInterface::MSG_ERROR);
}
else {
emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename),
CClientUIInterface::MSG_INFORMATION);
}
}
void WalletView::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void WalletView::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if (walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
void WalletView::lockWallet()
{
if(!walletModel)
return;
walletModel->setWalletLocked(true);
}
void WalletView::usedSendingAddresses()
{
if(!walletModel)
return;
AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this);
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->setModel(walletModel->getAddressTableModel());
dlg->show();
}
void WalletView::usedReceivingAddresses()
{
if(!walletModel)
return;
AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this);
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->setModel(walletModel->getAddressTableModel());
dlg->show();
}
void WalletView::showProgress(const QString &title, int nProgress)
{
if (nProgress == 0)
{
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
}
else if (nProgress == 100)
{
if (progressDialog)
{
progressDialog->close();
progressDialog->deleteLater();
}
}
else if (progressDialog)
progressDialog->setValue(nProgress);
}
/** Update wallet with the sum of the selected transactions */
void WalletView::trxAmount(QString amount)
{
transactionSum->setText(amount);
}
<|endoftext|> |
<commit_before>#include "read_temp_hum.h"
#include <dht.h>
#include "thermostat.h"
#include "tempe_control.h"
#define TEMPE_HISTORY 6 // How many temperature history value used for filter
using namespace core;
dht DHT;
// Return false if read failed.
bool doReadDHT22() {
delay(2); // TODO: it seems DHT not stable without this delay
int chk = DHT.read22(DHT22_PIN);
switch (chk) {
case DHTLIB_OK:
return true;
case DHTLIB_ERROR_CHECKSUM:
Serial.print(F("Checksum error,\n"));
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.print(F("Time out error,\n"));
break;
default:
Serial.print(F("Unknown error,\n"));
break;
}
return false;
}
idType idTempe, idHumi;
void setTempe(int16_t tempe) { store::setAnalog(idTempe, (uint16_t)tempe); }
void updateHumidity(uint16_t hum) { store::setAnalog(idHumi, hum); }
int16_t recentTempes[TEMPE_HISTORY];
uint8_t recentTempesIdx = 0;
int32_t tempeSum;
int16_t lastTempe;
int16_t lastLastTempe;
void updateTemperature(int16_t temp) {
// if lastTempe equals current one, probably it is real value, skip delta
// filter.
if (temp != lastTempe || lastLastTempe != lastTempe) {
lastLastTempe = lastTempe;
lastTempe = temp;
// Because dht22 actually has 0.2 precision, we only use the temperature
// only if
// dht reading has 0.2 changes.
int16_t cur = readTempe();
int16_t delta = abs(cur - temp);
if (delta < 2) {
return;
}
// it is unlikly temperature changes more than 2 degrees during
// DHT22_SAMPLE_RATE unless an error
if (delta > 20) {
return;
}
}
tempeSum -= recentTempes[recentTempesIdx];
recentTempes[recentTempesIdx] = temp;
tempeSum += temp;
if (++recentTempesIdx == TEMPE_HISTORY) {
recentTempesIdx = 0;
}
setTempe(tempeSum / TEMPE_HISTORY);
}
void readTempeHumiFirstTime() {
int16_t tempe = getTempeSetpoint();
uint16_t humi = 500;
if (doReadDHT22()) {
tempe = DHT.temperature;
humi = DHT.humidity;
}
for (int i = 0; i < TEMPE_HISTORY; i++) {
recentTempes[i] = tempe;
}
lastTempe = lastLastTempe = tempe;
tempeSum = tempe * TEMPE_HISTORY;
updateTemperature(tempe);
updateHumidity(humi);
}
void readDHT22() {
if (!doReadDHT22()) {
return;
}
updateTemperature(DHT.temperature);
updateHumidity(DHT.humidity);
}
void setupThemeHumi(void) {
idHumi = store::defineAnalog();
idTempe = store::defineAnalog();
setTempe(getTempeSetpoint());
clock::interval(DHT22_SAMPLE_RATE, readDHT22);
// At this time, no other modules hooks idTempe & idHumi,
// delays inital read, to trigger interested modules.
clock::delay(1, readTempeHumiFirstTime);
}
<commit_msg>Delay 1.5 second to read DHT22<commit_after>#include "read_temp_hum.h"
#include <dht.h>
#include "thermostat.h"
#include "tempe_control.h"
#define TEMPE_HISTORY 6 // How many temperature history value used for filter
using namespace core;
dht DHT;
// Return false if read failed.
bool doReadDHT22() {
int chk = DHT.read22(DHT22_PIN);
switch (chk) {
case DHTLIB_OK:
return true;
case DHTLIB_ERROR_CHECKSUM:
Serial.print(F("Checksum error,\n"));
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.print(F("Time out error,\n"));
break;
default:
Serial.print(F("Unknown error,\n"));
break;
}
return false;
}
idType idTempe, idHumi;
void setTempe(int16_t tempe) { store::setAnalog(idTempe, (uint16_t)tempe); }
void updateHumidity(uint16_t hum) { store::setAnalog(idHumi, hum); }
int16_t recentTempes[TEMPE_HISTORY];
uint8_t recentTempesIdx = 0;
int32_t tempeSum;
int16_t lastTempe;
int16_t lastLastTempe;
void updateTemperature(int16_t temp) {
// if lastTempe equals current one, probably it is real value, skip delta
// filter.
if (temp != lastTempe || lastLastTempe != lastTempe) {
lastLastTempe = lastTempe;
lastTempe = temp;
// Because dht22 actually has 0.2 precision, we only use the temperature
// only if
// dht reading has 0.2 changes.
int16_t cur = readTempe();
int16_t delta = abs(cur - temp);
if (delta < 2) {
return;
}
// it is unlikly temperature changes more than 2 degrees during
// DHT22_SAMPLE_RATE unless an error
if (delta > 20) {
return;
}
}
tempeSum -= recentTempes[recentTempesIdx];
recentTempes[recentTempesIdx] = temp;
tempeSum += temp;
if (++recentTempesIdx == TEMPE_HISTORY) {
recentTempesIdx = 0;
}
setTempe(tempeSum / TEMPE_HISTORY);
}
void readDHT22() {
if (!doReadDHT22()) {
return;
}
updateTemperature(DHT.temperature);
updateHumidity(DHT.humidity);
}
void readTempeHumiFirstTime() {
int16_t tempe = getTempeSetpoint();
uint16_t humi = 500;
if (doReadDHT22()) {
tempe = DHT.temperature;
humi = DHT.humidity;
}
for (int i = 0; i < TEMPE_HISTORY; i++) {
recentTempes[i] = tempe;
}
lastTempe = lastLastTempe = tempe;
tempeSum = tempe * TEMPE_HISTORY;
updateTemperature(tempe);
updateHumidity(humi);
clock::interval(DHT22_SAMPLE_RATE, readDHT22);
}
void setupThemeHumi(void) {
idHumi = store::defineAnalog();
idTempe = store::defineAnalog();
setTempe(getTempeSetpoint());
// At this time, no other modules hooks idTempe & idHumi,
// delays inital read, to trigger interested modules.
// DHT22 datasheet said, should not read DHT22 in first second after power up.
clock::delay(1500, readTempeHumiFirstTime);
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <fstream>
#include <stdexcept>
#include <iterator>
#include "reader.h"
using namespace std;
template<class T, class CharT = char, class Traits = char_traits<CharT>,
class Distance = ptrdiff_t >
struct theresnoescapefromthisiterator
: public iterator<input_iterator_tag, T, Distance, const T*, const T&>
{
public:
theresnoescapefromthisiterator() = default;
theresnoescapefromthisiterator(basic_istream<CharT, Traits> &stream) :
stream(&stream)
{
stream.seekg(0, ios_base::end);
file_size = stream.tellg();
fill();
}
theresnoescapefromthisiterator &operator++()
{
assert(stream);
pos += 1;
if (pos == file_size)
stream = NULL;
else
fill();
return *this;
}
bool operator==(const theresnoescapefromthisiterator &rhs)
{
return (stream && rhs.stream) ? (pos == rhs.pos)
: (stream == rhs.stream);
}
bool operator!=(const theresnoescapefromthisiterator &rhs)
{
return !(*this == rhs);
}
T operator*() const
{
return current.value;
}
private:
void fill()
{
stream->seekg(pos);
for (unsigned i = 0;i != sizeof(T);++i) {
char c;
stream->read(&c, 1);
current.pieces[i] = c;
}
}
basic_istream<CharT, Traits> *stream = NULL;
typename basic_istream<CharT, Traits>::pos_type pos = 0;
typename basic_istream<CharT, Traits>::pos_type file_size;
mutable union
{
T value;
uint8_t pieces[sizeof(T)];
} current;
};
class Reader {
public:
Reader(istream &stream);
theresnoescapefromthisiterator<uint8_t> begin();
theresnoescapefromthisiterator<uint8_t> end();
private:
theresnoescapefromthisiterator<uint8_t> begin_;
};
Reader::Reader(istream &stream)
: begin_(stream) {
}
theresnoescapefromthisiterator<uint8_t> Reader::begin() {
return begin_;
}
theresnoescapefromthisiterator<uint8_t> Reader::end() {
return {};
}
map<uint8_t, unsigned int> read(string file) {
ifstream stream(file);
if (stream.rdstate() & ios_base::failbit)
throw runtime_error("File do not exist");
map<uint8_t, unsigned int> map;
for (auto character : Reader(stream)) {
++map[character];
}
stream.close();
return map;
}
<commit_msg>fix: file iterator was failing on empty files<commit_after>#include <cassert>
#include <fstream>
#include <stdexcept>
#include <iterator>
#include "reader.h"
using namespace std;
template<class T, class CharT = char, class Traits = char_traits<CharT>,
class Distance = ptrdiff_t >
struct theresnoescapefromthisiterator
: public iterator<input_iterator_tag, T, Distance, const T*, const T&>
{
public:
theresnoescapefromthisiterator() = default;
theresnoescapefromthisiterator(basic_istream<CharT, Traits> &stream) :
stream(&stream)
{
stream.seekg(0, ios_base::end);
file_size = stream.tellg();
if (file_size)
fill();
else
stream = NULL;
}
theresnoescapefromthisiterator &operator++()
{
assert(stream);
pos += 1;
if (pos == file_size)
stream = NULL;
else
fill();
return *this;
}
bool operator==(const theresnoescapefromthisiterator &rhs)
{
return (stream && rhs.stream) ? (pos == rhs.pos)
: (stream == rhs.stream);
}
bool operator!=(const theresnoescapefromthisiterator &rhs)
{
return !(*this == rhs);
}
T operator*() const
{
return current.value;
}
private:
void fill()
{
stream->seekg(pos);
for (unsigned i = 0;i != sizeof(T);++i) {
char c;
stream->read(&c, 1);
current.pieces[i] = c;
}
}
basic_istream<CharT, Traits> *stream = NULL;
typename basic_istream<CharT, Traits>::pos_type pos = 0;
typename basic_istream<CharT, Traits>::pos_type file_size;
mutable union
{
T value;
uint8_t pieces[sizeof(T)];
} current;
};
class Reader {
public:
Reader(istream &stream);
theresnoescapefromthisiterator<uint8_t> begin();
theresnoescapefromthisiterator<uint8_t> end();
private:
theresnoescapefromthisiterator<uint8_t> begin_;
};
Reader::Reader(istream &stream)
: begin_(stream) {
}
theresnoescapefromthisiterator<uint8_t> Reader::begin() {
return begin_;
}
theresnoescapefromthisiterator<uint8_t> Reader::end() {
return {};
}
map<uint8_t, unsigned int> read(string file) {
ifstream stream(file);
if (stream.rdstate() & ios_base::failbit)
throw runtime_error("File do not exist");
map<uint8_t, unsigned int> map;
for (auto character : Reader(stream)) {
++map[character];
}
stream.close();
return map;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <fstream>
#include <stdexcept>
#include <iterator>
#include "reader.h"
using namespace std;
template<class T, class CharT = char, class Traits = char_traits<CharT>,
class Distance = ptrdiff_t >
struct theresnoescapefromthisiterator
: public iterator<input_iterator_tag, T, Distance, const T*, const T&>
{
public:
theresnoescapefromthisiterator() = default;
theresnoescapefromthisiterator(basic_istream<CharT, Traits> &stream) :
stream(&stream)
{
stream.seekg(0, ios_base::end);
file_size = stream.tellg();
if (file_size)
fill();
else
stream = NULL;
}
theresnoescapefromthisiterator &operator++()
{
assert(stream);
pos += 1;
if (pos == file_size)
stream = NULL;
else
fill();
return *this;
}
bool operator==(const theresnoescapefromthisiterator &rhs)
{
return (stream && rhs.stream) ? (pos == rhs.pos)
: (stream == rhs.stream);
}
bool operator!=(const theresnoescapefromthisiterator &rhs)
{
return !(*this == rhs);
}
T operator*() const
{
return current.value;
}
private:
void fill()
{
stream->seekg(pos);
for (unsigned i = 0;i != sizeof(T);++i) {
char c;
stream->read(&c, 1);
current.pieces[i] = c;
}
}
basic_istream<CharT, Traits> *stream = NULL;
typename basic_istream<CharT, Traits>::pos_type pos = 0;
typename basic_istream<CharT, Traits>::pos_type file_size;
mutable union
{
T value;
uint8_t pieces[sizeof(T)];
} current;
};
class Reader {
public:
Reader(istream &stream);
theresnoescapefromthisiterator<uint8_t> begin();
theresnoescapefromthisiterator<uint8_t> end();
private:
theresnoescapefromthisiterator<uint8_t> begin_;
};
Reader::Reader(istream &stream)
: begin_(stream) {
}
theresnoescapefromthisiterator<uint8_t> Reader::begin() {
return begin_;
}
theresnoescapefromthisiterator<uint8_t> Reader::end() {
return {};
}
map<uint8_t, unsigned int> read(string file) {
ifstream stream(file);
if (stream.rdstate() & ios_base::failbit)
throw runtime_error("File do not exist");
map<uint8_t, unsigned int> map;
for (auto character : Reader(stream)) {
++map[character];
}
stream.close();
return map;
}
<commit_msg>Fixes commit f732a598e345d67d624aa837a41ec23edaa62f59<commit_after>#include <cassert>
#include <fstream>
#include <stdexcept>
#include <iterator>
#include "reader.h"
using namespace std;
template<class T, class CharT = char, class Traits = char_traits<CharT>,
class Distance = ptrdiff_t >
struct theresnoescapefromthisiterator
: public iterator<input_iterator_tag, T, Distance, const T*, const T&>
{
public:
theresnoescapefromthisiterator() = default;
theresnoescapefromthisiterator(basic_istream<CharT, Traits> &stream) :
stream(&stream)
{
stream.seekg(0, ios_base::end);
file_size = stream.tellg();
if (file_size)
fill();
else
this->stream = NULL;
}
theresnoescapefromthisiterator &operator++()
{
assert(stream);
pos += 1;
if (pos == file_size)
stream = NULL;
else
fill();
return *this;
}
bool operator==(const theresnoescapefromthisiterator &rhs)
{
return (stream && rhs.stream) ? (pos == rhs.pos)
: (stream == rhs.stream);
}
bool operator!=(const theresnoescapefromthisiterator &rhs)
{
return !(*this == rhs);
}
T operator*() const
{
return current.value;
}
private:
void fill()
{
stream->seekg(pos);
for (unsigned i = 0;i != sizeof(T);++i) {
char c;
stream->read(&c, 1);
current.pieces[i] = c;
}
}
basic_istream<CharT, Traits> *stream = NULL;
typename basic_istream<CharT, Traits>::pos_type pos = 0;
typename basic_istream<CharT, Traits>::pos_type file_size;
mutable union
{
T value;
uint8_t pieces[sizeof(T)];
} current;
};
class Reader {
public:
Reader(istream &stream);
theresnoescapefromthisiterator<uint8_t> begin();
theresnoescapefromthisiterator<uint8_t> end();
private:
theresnoescapefromthisiterator<uint8_t> begin_;
};
Reader::Reader(istream &stream)
: begin_(stream) {
}
theresnoescapefromthisiterator<uint8_t> Reader::begin() {
return begin_;
}
theresnoescapefromthisiterator<uint8_t> Reader::end() {
return {};
}
map<uint8_t, unsigned int> read(string file) {
ifstream stream(file);
if (stream.rdstate() & ios_base::failbit)
throw runtime_error("File do not exist");
map<uint8_t, unsigned int> map;
for (auto character : Reader(stream)) {
++map[character];
}
stream.close();
return map;
}
<|endoftext|> |
<commit_before>#include <unordered_set>
#include <clang/Basic/TargetInfo.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Parse/ParseAST.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclGroup.h>
#include <clang/AST/Type.h>
#include <clang/AST/PrettyPrinter.h>
#include "c-import.h"
#include "typecheck.h"
#include "../ast/type.h"
#include "../ast/decl.h"
namespace {
clang::PrintingPolicy printingPolicy{clang::LangOptions()};
/** Prints the message to stderr if it hasn't been printed yet. */
void warnOnce(const llvm::Twine& message) {
static std::unordered_set<std::string> printedMessages;
llvm::SmallVector<char, 64> buffer;
if (printedMessages.count(message.toStringRef(buffer)) != 0) return;
llvm::errs() << "WARNING: " << *printedMessages.emplace(message.str()).first << '\n';
}
Type toDelta(clang::QualType qualtype) {
auto& type = *qualtype.getTypePtr();
switch (type.getTypeClass()) {
case clang::Type::Pointer: {
auto pointeeType = llvm::cast<clang::PointerType>(type).getPointeeType();
return Type(PtrType(llvm::make_unique<Type>(toDelta(pointeeType))));
}
case clang::Type::Builtin:
switch (llvm::cast<clang::BuiltinType>(type).getKind()) {
case clang::BuiltinType::Void: return Type(BasicType{"void"});
case clang::BuiltinType::Bool: return Type(BasicType{"bool"});
case clang::BuiltinType::Char_S:
case clang::BuiltinType::Char_U:return Type(BasicType{"char"});
case clang::BuiltinType::Int: return Type(BasicType{"int"});
case clang::BuiltinType::UInt: return Type(BasicType{"uint"});
default:
auto name = llvm::cast<clang::BuiltinType>(type).getName(printingPolicy);
warnOnce("Builtin type '" + name + "' not handled");
return Type(BasicType{"int"});
}
return Type(BasicType{llvm::cast<clang::BuiltinType>(type).getName(printingPolicy)});
case clang::Type::Typedef:
return toDelta(llvm::cast<clang::TypedefType>(type).desugar());
case clang::Type::Elaborated:
return toDelta(llvm::cast<clang::ElaboratedType>(type).getNamedType());
case clang::Type::Record:
return Type(BasicType{llvm::cast<clang::RecordType>(type).getDecl()->getName()});
default:
warnOnce(llvm::Twine(type.getTypeClassName()) + " not handled");
return Type(BasicType{"int"});
}
}
FuncDecl toDelta(const clang::FunctionDecl& decl) {
std::vector<ParamDecl> params;
for (auto* param : decl.parameters()) {
params.emplace_back(ParamDecl{"", toDelta(param->getType()), param->getNameAsString()});
}
return FuncDecl{decl.getNameAsString(), std::move(params), toDelta(decl.getReturnType())};
}
class CToDeltaConverter : public clang::ASTConsumer {
public:
bool HandleTopLevelDecl(clang::DeclGroupRef declGroup) final override {
for (clang::Decl* decl : declGroup) {
switch (decl->getKind()) {
case clang::Decl::Function:
addToSymbolTable(toDelta(llvm::cast<clang::FunctionDecl>(*decl)));
break;
default:
break;
}
}
return true; // continue parsing
}
};
// FIXME: Temporary hack for finding Clang builtin includes.
// See http://clang.llvm.org/docs/FAQ.html#i-get-errors-about-some-headers-being-missing-stddef-h-stdarg-h
std::string getClangBuiltinIncludePath() {
char path[64];
std::shared_ptr<FILE> f(popen("dirname $(dirname $(which clang))", "r"), pclose);
if (!f || fscanf(f.get(), "%63s", path) != 1) return "";
char version[6];
f.reset(popen("clang --version", "r"), pclose);
if (!f || fscanf(f.get(), "clang version %5s", version) != 1) return "";
return std::string(path) + "/lib/clang/" + version + "/include";
}
} // anonymous namespace
void importCHeader(llvm::StringRef headerName) {
clang::CompilerInstance ci;
clang::DiagnosticOptions diagnosticOptions;
ci.createDiagnostics();
std::shared_ptr<clang::TargetOptions> pto = std::make_shared<clang::TargetOptions>();
pto->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo* pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto);
ci.setTarget(pti);
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
ci.getHeaderSearchOpts().AddPath("/usr/include", clang::frontend::System, false, false);
ci.getHeaderSearchOpts().AddPath("/usr/local/include", clang::frontend::System, false, false);
std::string clangBuiltinIncludePath = getClangBuiltinIncludePath();
if (!clangBuiltinIncludePath.empty()) {
ci.getHeaderSearchOpts().AddPath(clangBuiltinIncludePath, clang::frontend::System, false, false);
} else {
llvm::errs() << "warning: clang not found, importing certain headers might not work\n";
}
ci.createPreprocessor(clang::TU_Complete);
ci.getPreprocessorOpts().UsePredefines = false;
ci.setASTConsumer(llvm::make_unique<CToDeltaConverter>());
ci.createASTContext();
const clang::DirectoryLookup* curDir = nullptr;
const clang::FileEntry* pFile = ci.getPreprocessor().getHeaderSearchInfo().LookupFile(
headerName, {}, false, nullptr, curDir, {}, nullptr, nullptr, nullptr, nullptr);
if (!pFile) {
llvm::errs() << "error: couldn't find header '" << headerName << "'\n";
abort();
}
ci.getSourceManager().setMainFileID(ci.getSourceManager().createFileID(
pFile, clang::SourceLocation(), clang::SrcMgr::C_System));
ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(), &ci.getPreprocessor());
clang::ParseAST(ci.getPreprocessor(), &ci.getASTConsumer(), ci.getASTContext());
ci.getDiagnosticClient().EndSourceFile();
}
<commit_msg>[c-import] initialize Clang builtins<commit_after>#include <unordered_set>
#include <clang/Basic/TargetInfo.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/Lex/HeaderSearch.h>
#include <clang/Parse/ParseAST.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclGroup.h>
#include <clang/AST/Type.h>
#include <clang/AST/PrettyPrinter.h>
#include "c-import.h"
#include "typecheck.h"
#include "../ast/type.h"
#include "../ast/decl.h"
namespace {
clang::PrintingPolicy printingPolicy{clang::LangOptions()};
/** Prints the message to stderr if it hasn't been printed yet. */
void warnOnce(const llvm::Twine& message) {
static std::unordered_set<std::string> printedMessages;
llvm::SmallVector<char, 64> buffer;
if (printedMessages.count(message.toStringRef(buffer)) != 0) return;
llvm::errs() << "WARNING: " << *printedMessages.emplace(message.str()).first << '\n';
}
Type toDelta(clang::QualType qualtype) {
auto& type = *qualtype.getTypePtr();
switch (type.getTypeClass()) {
case clang::Type::Pointer: {
auto pointeeType = llvm::cast<clang::PointerType>(type).getPointeeType();
return Type(PtrType(llvm::make_unique<Type>(toDelta(pointeeType))));
}
case clang::Type::Builtin:
switch (llvm::cast<clang::BuiltinType>(type).getKind()) {
case clang::BuiltinType::Void: return Type(BasicType{"void"});
case clang::BuiltinType::Bool: return Type(BasicType{"bool"});
case clang::BuiltinType::Char_S:
case clang::BuiltinType::Char_U:return Type(BasicType{"char"});
case clang::BuiltinType::Int: return Type(BasicType{"int"});
case clang::BuiltinType::UInt: return Type(BasicType{"uint"});
default:
auto name = llvm::cast<clang::BuiltinType>(type).getName(printingPolicy);
warnOnce("Builtin type '" + name + "' not handled");
return Type(BasicType{"int"});
}
return Type(BasicType{llvm::cast<clang::BuiltinType>(type).getName(printingPolicy)});
case clang::Type::Typedef:
return toDelta(llvm::cast<clang::TypedefType>(type).desugar());
case clang::Type::Elaborated:
return toDelta(llvm::cast<clang::ElaboratedType>(type).getNamedType());
case clang::Type::Record:
return Type(BasicType{llvm::cast<clang::RecordType>(type).getDecl()->getName()});
default:
warnOnce(llvm::Twine(type.getTypeClassName()) + " not handled");
return Type(BasicType{"int"});
}
}
FuncDecl toDelta(const clang::FunctionDecl& decl) {
std::vector<ParamDecl> params;
for (auto* param : decl.parameters()) {
params.emplace_back(ParamDecl{"", toDelta(param->getType()), param->getNameAsString()});
}
return FuncDecl{decl.getNameAsString(), std::move(params), toDelta(decl.getReturnType())};
}
class CToDeltaConverter : public clang::ASTConsumer {
public:
bool HandleTopLevelDecl(clang::DeclGroupRef declGroup) final override {
for (clang::Decl* decl : declGroup) {
switch (decl->getKind()) {
case clang::Decl::Function:
addToSymbolTable(toDelta(llvm::cast<clang::FunctionDecl>(*decl)));
break;
default:
break;
}
}
return true; // continue parsing
}
};
// FIXME: Temporary hack for finding Clang builtin includes.
// See http://clang.llvm.org/docs/FAQ.html#i-get-errors-about-some-headers-being-missing-stddef-h-stdarg-h
std::string getClangBuiltinIncludePath() {
char path[64];
std::shared_ptr<FILE> f(popen("dirname $(dirname $(which clang))", "r"), pclose);
if (!f || fscanf(f.get(), "%63s", path) != 1) return "";
char version[6];
f.reset(popen("clang --version", "r"), pclose);
if (!f || fscanf(f.get(), "clang version %5s", version) != 1) return "";
return std::string(path) + "/lib/clang/" + version + "/include";
}
} // anonymous namespace
void importCHeader(llvm::StringRef headerName) {
clang::CompilerInstance ci;
clang::DiagnosticOptions diagnosticOptions;
ci.createDiagnostics();
std::shared_ptr<clang::TargetOptions> pto = std::make_shared<clang::TargetOptions>();
pto->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo* pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto);
ci.setTarget(pti);
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
ci.getHeaderSearchOpts().AddPath("/usr/include", clang::frontend::System, false, false);
ci.getHeaderSearchOpts().AddPath("/usr/local/include", clang::frontend::System, false, false);
std::string clangBuiltinIncludePath = getClangBuiltinIncludePath();
if (!clangBuiltinIncludePath.empty()) {
ci.getHeaderSearchOpts().AddPath(clangBuiltinIncludePath, clang::frontend::System, false, false);
} else {
llvm::errs() << "warning: clang not found, importing certain headers might not work\n";
}
ci.createPreprocessor(clang::TU_Complete);
auto& pp = ci.getPreprocessor();
pp.getBuiltinInfo().initializeBuiltins(pp.getIdentifierTable(), pp.getLangOpts());
ci.setASTConsumer(llvm::make_unique<CToDeltaConverter>());
ci.createASTContext();
const clang::DirectoryLookup* curDir = nullptr;
const clang::FileEntry* pFile = ci.getPreprocessor().getHeaderSearchInfo().LookupFile(
headerName, {}, false, nullptr, curDir, {}, nullptr, nullptr, nullptr, nullptr);
if (!pFile) {
llvm::errs() << "error: couldn't find header '" << headerName << "'\n";
abort();
}
ci.getSourceManager().setMainFileID(ci.getSourceManager().createFileID(
pFile, clang::SourceLocation(), clang::SrcMgr::C_System));
ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(), &ci.getPreprocessor());
clang::ParseAST(ci.getPreprocessor(), &ci.getASTConsumer(), ci.getASTContext());
ci.getDiagnosticClient().EndSourceFile();
}
<|endoftext|> |
<commit_before>#include "Server.hpp"
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#include <iostream>
#include <cstdlib> // for random
#include <cmath> // for sin,cos in the server
#include <list>
#include "../functions.h"
#include "../Mech.h"
#include "../Projectile.h"
#include "../MovingObject.hpp"
#include "../types.h"
#include "../net/NetMessage.h"
namespace ap {
namespace server {
using namespace std;
Server::Server(uint32 port) :
mScores(new ap::ScoreListing()),
mPort(port)
{
std::cout << "[SERVER] Created a server."<< std::endl;
}
void Server::start() {
float dt; // delta-t between main loop iterations
std::cout << "[SERVER] Started the server."<<std::endl;
netdata = new net::NetData(net::NetData::SERVER, mPort);
if( !netdata ) {
std::cout << "[SERVER] Error initializing NetData, exiting!" << std::endl;
return;
}
std::cout << "[SERVER] Serving "<< ap::net::netobjectprototypes().size()<<" types of objects."<<std::endl;
netdata->insertObject(mScores);
newticks = nextupdate = getTicks();
while (1) { // Server main loop
netdata->receiveChanges();
oldticks = newticks; newticks = getTicks();
dt = float(newticks - oldticks)*0.001; // dt is in seconds
updateObjects(dt, netdata);
fireWeapons(newticks, netdata);
detectCollisions(netdata);
if (newticks >= nextupdate) {
int changes = netdata->sendChanges();
nextupdate = newticks + (1000/NetFPS); // 40 ms between updates, that's 25 network fps.
cout << "\rData rate: "<<changes<<" ";
cout.flush();
} // Seems to me that up to 100 is still okay!
// TODO: Ensure that usleep is available on Mac/Windows as well!
ap::mSleep(1); // sleep even a little bit so that dt is never 0
processEvents(netdata);
if (!pendingClients.empty()) processPendingClients(netdata);
} // Main loop
} // void Server::start()
void Server::processEvents(ap::net::NetData *pNetData) {
ap::net::NetEvent event;
while (pNetData->pollEvent(event))
{
switch (event.type)
{
case ap::net::NetData::EVENT_CONNECT:
{
cout << "[SERVER] Received a connection from "
<< uint2ipv4(pNetData->getUser(event.uid)->peer->address.host)
<<", uid " << event.uid;
pendingClients.insert(event.uid); // Remember him until later!
// If we add now, his NetUser is still uninitialized.
// createNewConnection(event.uid, pNetData);
// NetMessage connectMessage("!!! "+pNetData->getUser(event.uid)->nick+" has joined the game !!!");
// pNetData->sendMessage(connectMessage);
break;
}
case ap::net::NetData::EVENT_DISCONNECT:
{
cout << "[SERVER] Client "<<event.uid<<" disconnected."<<endl;
while (Mech *pM = pNetData->eachObject<Mech *>(ap::OBJECT_TYPE_MECH)) {
if (pM->uid == event.uid) pNetData->delObject(pM->id);
}
mScores->removeScore(event.uid);
pNetData->alertObject(mScores->id); // Refresh the score display to players
NetMessage disconnectMessage("!!! "+pNetData->getPastUser(event.uid)->nick+" has disconnected !!!");
pNetData->sendMessage(disconnectMessage);
break;
}
default:
break;
}
}
} // void Server::processEvents(netdata*)
void Server::processPendingClients(ap::net::NetData *pNetData) {
std::set<uint32>::iterator i = pendingClients.begin();
while (i != pendingClients.end()) {
if (pNetData->getUser(*i)->initialized) {
createNewConnection(*i, pNetData);
NetMessage connectMessage("!!! "+pNetData->getUser(*i)->nick+" has joined the game !!!");
pNetData->sendMessage(connectMessage);
pendingClients.erase(i++);
} else i++;
}
}
void Server::updateObjects(float dt, ap::net::NetData* pNetData) const {
while (NetObject *nop = pNetData->eachObject()) {
if (nop->advance(dt) == -1) pNetData->delObject(nop->id);
}
// Copy colors from NetUser data to Mechs they own
// TODO: think of some way of doing this only when necessary!
while (ap::Mech *pMech = pNetData->eachObject<ap::Mech*>(ap::OBJECT_TYPE_MECH)) {
if (pNetData->getUser(pMech->uid)) {
pMech->color = pNetData->getUser(pMech->uid)->color;
pNetData->alertObject(pMech->id);
}
}
} // void Server::updateObjects
void Server::fireWeapons(uint64 tstamp, ap::net::NetData *pNetData) {
while (ap::Mech *mech = pNetData->eachObject<ap::Mech *>(ap::OBJECT_TYPE_MECH))
if (mech->fireGun(tstamp)) weaponFired(pNetData, mech);
}
void Server::weaponFired(ap::net::NetData *pNetData, ap::MovingObject *source) {
Ogre::Vector3 facing = source->getFacing();
int newid = pNetData->insertObject(new ap::Projectile(facing * 150.0f)); //150 is velocity
ap::Projectile *bullet = pNetData->getObject<ap::Projectile *>(newid);
bullet->setWorldBoundaries(1500.0f,0.0f,0.0f,1500.0f);
bullet->setMaxSpeed(625.0f);
bullet->setPosition(source->getPosition() + facing*70.0f + Ogre::Vector3(0.0f, 80.0f, 0.0f));
bullet->setFacing(facing);
bullet->uid = source->uid;
}
void Server::detectCollisions(ap::net::NetData *pNetData) const {
while (ap::Mech *mech = pNetData->eachObject<ap::Mech *>(ap::OBJECT_TYPE_MECH))
{
while (ap::Projectile *proj = pNetData->eachObject<ap::Projectile *>(ap::OBJECT_TYPE_PROJECTILE))
{
if (proj->testCollision(*mech)) {
relocateSpawnedMech(mech);
// update scores.
ap::ScoreTuple projOwner;
projOwner.uid = proj->uid;
projOwner.kills = 1;
projOwner.deaths = 0;
projOwner.score = 1;
ap::ScoreTuple mechOwner;
mechOwner.uid = mech->uid;
mechOwner.kills = 0;
mechOwner.deaths = 1;
mechOwner.score = -1;
mScores->addScore(projOwner, false);
mScores->addScore(mechOwner, false);
mScores->setChanged();
mScores->print();
pNetData->delObject(proj->id);
pNetData->alertObject(mScores->id); // Refresh the score display to players
}
}
}
}
void Server::relocateSpawnedMech(ap::Mech *mech) const
{
Ogre::Vector3 newPosition = Ogre::Vector3(rand()%1500, 0, rand()%1500);
mech->setPosition(newPosition);
mech->setVelocity(Ogre::Vector3::ZERO);
}
void Server::createNewConnection(ap::uint32 userId, ap::net::NetData *pNetData)
{
ap::Mech *newAvatar = new ap::Mech();
int newid = pNetData->insertObject(newAvatar);
newAvatar->setWorldBoundaries(1500.0f,0.0f,0.0f,1500.0f);
newAvatar->setMaxSpeed(35.0f);
newAvatar->setFriction(8.0f);
newAvatar->uid = userId;
newAvatar->color = pNetData->getUser(userId)->color;
relocateSpawnedMech(newAvatar);
pNetData->getUser(userId)->setControlPtr(newAvatar->getControlPtr());
// Add scores:
ap::ScoreTuple newPlayer;
newPlayer.uid = userId;
newPlayer.nick = pNetData->getUser(userId)->nick;
newPlayer.kills = 0;
newPlayer.deaths = 0;
newPlayer.score = 0;
mScores->addScore(newPlayer, true);
mScores->setChanged();
pNetData->alertObject(mScores->id); // Refresh the score display to players
pNetData->sendChanges();
pNetData->setAvatarID(userId, newid);
}
} // namespace server
} // namespace ap
<commit_msg>Fixed server's processPendingClients to not crash if a client disconnects while pending.<commit_after>#include "Server.hpp"
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#include <iostream>
#include <cstdlib> // for random
#include <cmath> // for sin,cos in the server
#include <list>
#include "../functions.h"
#include "../Mech.h"
#include "../Projectile.h"
#include "../MovingObject.hpp"
#include "../types.h"
#include "../net/NetMessage.h"
namespace ap {
namespace server {
using namespace std;
Server::Server(uint32 port) :
mScores(new ap::ScoreListing()),
mPort(port)
{
std::cout << "[SERVER] Created a server."<< std::endl;
}
void Server::start() {
float dt; // delta-t between main loop iterations
std::cout << "[SERVER] Started the server."<<std::endl;
netdata = new net::NetData(net::NetData::SERVER, mPort);
if( !netdata ) {
std::cout << "[SERVER] Error initializing NetData, exiting!" << std::endl;
return;
}
std::cout << "[SERVER] Serving "<< ap::net::netobjectprototypes().size()<<" types of objects."<<std::endl;
netdata->insertObject(mScores);
newticks = nextupdate = getTicks();
while (1) { // Server main loop
netdata->receiveChanges();
oldticks = newticks; newticks = getTicks();
dt = float(newticks - oldticks)*0.001; // dt is in seconds
updateObjects(dt, netdata);
fireWeapons(newticks, netdata);
detectCollisions(netdata);
if (newticks >= nextupdate) {
int changes = netdata->sendChanges();
nextupdate = newticks + (1000/NetFPS); // 40 ms between updates, that's 25 network fps.
cout << "\rData rate: "<<changes<<" ";
cout.flush();
} // Seems to me that up to 100 is still okay!
// TODO: Ensure that usleep is available on Mac/Windows as well!
ap::mSleep(1); // sleep even a little bit so that dt is never 0
processEvents(netdata);
if (!pendingClients.empty()) processPendingClients(netdata);
} // Main loop
} // void Server::start()
void Server::processEvents(ap::net::NetData *pNetData) {
ap::net::NetEvent event;
while (pNetData->pollEvent(event))
{
switch (event.type)
{
case ap::net::NetData::EVENT_CONNECT:
{
cout << "[SERVER] Received a connection from "
<< uint2ipv4(pNetData->getUser(event.uid)->peer->address.host)
<<", uid " << event.uid;
pendingClients.insert(event.uid); // Remember him until later!
// If we add now, his NetUser is still uninitialized.
// createNewConnection(event.uid, pNetData);
// NetMessage connectMessage("!!! "+pNetData->getUser(event.uid)->nick+" has joined the game !!!");
// pNetData->sendMessage(connectMessage);
break;
}
case ap::net::NetData::EVENT_DISCONNECT:
{
cout << "[SERVER] Client "<<event.uid<<" disconnected."<<endl;
while (Mech *pM = pNetData->eachObject<Mech *>(ap::OBJECT_TYPE_MECH)) {
if (pM->uid == event.uid) pNetData->delObject(pM->id);
}
mScores->removeScore(event.uid);
pNetData->alertObject(mScores->id); // Refresh the score display to players
NetMessage disconnectMessage("!!! "+pNetData->getPastUser(event.uid)->nick+" has disconnected !!!");
pNetData->sendMessage(disconnectMessage);
break;
}
default:
break;
}
}
} // void Server::processEvents(netdata*)
void Server::processPendingClients(ap::net::NetData *pNetData) {
std::set<uint32>::iterator i = pendingClients.begin();
while (i != pendingClients.end()) {
if (!pNetData->getUser(*i)) {
pendingClients.erase(i++); // The user disconnected before finishing connection
} else if (pNetData->getUser(*i)->initialized) {
createNewConnection(*i, pNetData);
NetMessage connectMessage("!!! "+pNetData->getUser(*i)->nick+" has joined the game !!!");
pNetData->sendMessage(connectMessage);
pendingClients.erase(i++);
} else i++;
}
}
void Server::updateObjects(float dt, ap::net::NetData* pNetData) const {
while (NetObject *nop = pNetData->eachObject()) {
if (nop->advance(dt) == -1) pNetData->delObject(nop->id);
}
// Copy colors from NetUser data to Mechs they own
// TODO: think of some way of doing this only when necessary!
while (ap::Mech *pMech = pNetData->eachObject<ap::Mech*>(ap::OBJECT_TYPE_MECH)) {
if (pNetData->getUser(pMech->uid)) {
pMech->color = pNetData->getUser(pMech->uid)->color;
pNetData->alertObject(pMech->id);
}
}
} // void Server::updateObjects
void Server::fireWeapons(uint64 tstamp, ap::net::NetData *pNetData) {
while (ap::Mech *mech = pNetData->eachObject<ap::Mech *>(ap::OBJECT_TYPE_MECH))
if (mech->fireGun(tstamp)) weaponFired(pNetData, mech);
}
void Server::weaponFired(ap::net::NetData *pNetData, ap::MovingObject *source) {
Ogre::Vector3 facing = source->getFacing();
int newid = pNetData->insertObject(new ap::Projectile(facing * 150.0f)); //150 is velocity
ap::Projectile *bullet = pNetData->getObject<ap::Projectile *>(newid);
bullet->setWorldBoundaries(1500.0f,0.0f,0.0f,1500.0f);
bullet->setMaxSpeed(625.0f);
bullet->setPosition(source->getPosition() + facing*70.0f + Ogre::Vector3(0.0f, 80.0f, 0.0f));
bullet->setFacing(facing);
bullet->uid = source->uid;
}
void Server::detectCollisions(ap::net::NetData *pNetData) const {
while (ap::Mech *mech = pNetData->eachObject<ap::Mech *>(ap::OBJECT_TYPE_MECH))
{
while (ap::Projectile *proj = pNetData->eachObject<ap::Projectile *>(ap::OBJECT_TYPE_PROJECTILE))
{
if (proj->testCollision(*mech)) {
relocateSpawnedMech(mech);
// update scores.
ap::ScoreTuple projOwner;
projOwner.uid = proj->uid;
projOwner.kills = 1;
projOwner.deaths = 0;
projOwner.score = 1;
ap::ScoreTuple mechOwner;
mechOwner.uid = mech->uid;
mechOwner.kills = 0;
mechOwner.deaths = 1;
mechOwner.score = -1;
mScores->addScore(projOwner, false);
mScores->addScore(mechOwner, false);
mScores->setChanged();
mScores->print();
pNetData->delObject(proj->id);
pNetData->alertObject(mScores->id); // Refresh the score display to players
}
}
}
}
void Server::relocateSpawnedMech(ap::Mech *mech) const
{
Ogre::Vector3 newPosition = Ogre::Vector3(rand()%1500, 0, rand()%1500);
mech->setPosition(newPosition);
mech->setVelocity(Ogre::Vector3::ZERO);
}
void Server::createNewConnection(ap::uint32 userId, ap::net::NetData *pNetData)
{
ap::Mech *newAvatar = new ap::Mech();
int newid = pNetData->insertObject(newAvatar);
newAvatar->setWorldBoundaries(1500.0f,0.0f,0.0f,1500.0f);
newAvatar->setMaxSpeed(35.0f);
newAvatar->setFriction(8.0f);
newAvatar->uid = userId;
newAvatar->color = pNetData->getUser(userId)->color;
relocateSpawnedMech(newAvatar);
pNetData->getUser(userId)->setControlPtr(newAvatar->getControlPtr());
// Add scores:
ap::ScoreTuple newPlayer;
newPlayer.uid = userId;
newPlayer.nick = pNetData->getUser(userId)->nick;
newPlayer.kills = 0;
newPlayer.deaths = 0;
newPlayer.score = 0;
mScores->addScore(newPlayer, true);
mScores->setChanged();
pNetData->alertObject(mScores->id); // Refresh the score display to players
pNetData->sendChanges();
pNetData->setAvatarID(userId, newid);
}
} // namespace server
} // namespace ap
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestScenePicker.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
//
// Test class vtkScenePicker.
// Move your mouse around the scene and the underlying actor should be
// printed on standard output.
//
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCommand.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkScenePicker.h"
#include "vtkVolume16Reader.h"
#include "vtkProperty.h"
#include "vtkPolyDataNormals.h"
#include "vtkContourFilter.h"
#include <vtkstd/map>
#include <vtkstd/string>
//-----------------------------------------------------------------------------
// Create a few actors first
vtkActor *CreateActor1( int argc, char *argv[], vtkRenderer * aRenderer )
{
char* fname2 = vtkTestUtilities::ExpandDataFileName(
argc, argv, "Data/headsq/quarter");
vtkVolume16Reader *v16 = vtkVolume16Reader::New();
v16->SetDataDimensions (64,64);
v16->SetImageRange (1,93);
v16->SetDataByteOrderToLittleEndian();
v16->SetFilePrefix (fname2);
v16->SetDataSpacing (3.2, 3.2, 1.5);
// An isosurface, or contour value of 500 is known to correspond to the
// skin of the patient. Once generated, a vtkPolyDataNormals filter is
// is used to create normals for smooth surface shading during rendering.
vtkContourFilter *skinExtractor = vtkContourFilter::New();
skinExtractor->SetInputConnection(v16->GetOutputPort());
skinExtractor->SetValue(0, 500);
vtkPolyDataNormals *skinNormals = vtkPolyDataNormals::New();
skinNormals->SetInputConnection(skinExtractor->GetOutputPort());
skinNormals->SetFeatureAngle(60.0);
vtkPolyDataMapper *skinMapper = vtkPolyDataMapper::New();
skinMapper->SetInputConnection(skinNormals->GetOutputPort());
skinMapper->ScalarVisibilityOff();
vtkActor *skin = vtkActor::New();
skin->SetMapper(skinMapper);
skin->GetProperty()->SetColor(0.95,0.75,0.75);
aRenderer->AddActor(skin);
v16->Delete();
skinExtractor->Delete();
skinNormals->Delete();
skinMapper->Delete();
skin->Delete();
return skin;
}
//-----------------------------------------------------------------------------
// Create a few actors first
vtkActor * CreateActor2( int vtkNotUsed(argc), char **vtkNotUsed(argv), vtkRenderer * ren )
{
vtkSphereSource *ss = vtkSphereSource::New();
ss->SetThetaResolution(30);
ss->SetPhiResolution(30);
ss->SetRadius(150.0);
vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
mapper->SetInput(ss->GetOutput());
vtkActor *actor = vtkActor::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(0.0,1.0,0.0);
ren->AddActor(actor);
ss->Delete();
mapper->Delete();
actor->Delete();
return actor;
}
//-----------------------------------------------------------------------------
// Command to write out picked actors during mouse over.
class TestScenePickerCommand : public vtkCommand
{
public:
vtkScenePicker * m_Picker;
static TestScenePickerCommand *New()
{
return new TestScenePickerCommand;
}
virtual void Execute(vtkObject *caller, unsigned long vtkNotUsed(eventId), void* vtkNotUsed(callData))
{
vtkRenderWindowInteractor * iren = reinterpret_cast<
vtkRenderWindowInteractor *>(caller);
int e[2];
iren->GetEventPosition(e);
cout << "DisplayPosition : (" << e[0] << "," << e[1] << ")"
<< " Prop: " << m_ActorDescription[m_Picker->GetViewProp(e)].c_str();
<< " CellId: " << m_Picker->GetCellId(e)
<< " VertexId: " << m_Picker->GetVertexId(e)
<< endl;
}
void SetActorDescription( vtkProp *a, vtkstd::string s )
{
this->m_ActorDescription[a] = s;
}
vtkstd::map< vtkProp *, vtkstd::string > m_ActorDescription;
protected:
TestScenePickerCommand() { this->SetActorDescription((vtkActor*)NULL, "None"); }
virtual ~TestScenePickerCommand() {}
};
//-----------------------------------------------------------------------------
int TestScenePicker(int argc, char* argv[])
{
vtkRenderer *ren = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
renWin->AddRenderer(ren);
iren->SetRenderWindow(renWin);
ren->SetBackground(0.0, 0.0, 0.0);
renWin->SetSize(300, 300);
// Here comes the scene picker stuff. [ Just 2 lines ]
vtkScenePicker * picker = vtkScenePicker::New();
picker->SetRenderer(ren);
// Write some stuff for interactive stuff.
TestScenePickerCommand * command =
TestScenePickerCommand::New();
command->m_Picker = picker;
command->SetActorDescription( CreateActor1( argc, argv, ren ), "Head" );
command->SetActorDescription( CreateActor2( argc, argv, ren ), "Sphere" );
iren->AddObserver(vtkCommand::MouseMoveEvent, command);
renWin->Render();
iren->Initialize();
// Check if scene picking works.
int retVal = EXIT_SUCCESS;
int e[2] = {175, 215};
if (command->m_ActorDescription[picker->GetViewProp(e)] != "Head" ||
picker->GetCellId(e) != 50992)
{
retVal = EXIT_FAILURE;
}
for ( int i = 0; i < argc; ++i )
{
if ( ! strcmp( argv[i], "-I" ) )
{
iren->Start();
}
}
// Cleanups
command->Delete();
picker->Delete();
ren->Delete();
renWin->Delete();
iren->Delete();
return retVal;
}
<commit_msg>COMP: fix typo in my last commit<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestScenePicker.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
//
// Test class vtkScenePicker.
// Move your mouse around the scene and the underlying actor should be
// printed on standard output.
//
#include "vtkSphereSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkCommand.h"
#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"
#include "vtkScenePicker.h"
#include "vtkVolume16Reader.h"
#include "vtkProperty.h"
#include "vtkPolyDataNormals.h"
#include "vtkContourFilter.h"
#include <vtkstd/map>
#include <vtkstd/string>
//-----------------------------------------------------------------------------
// Create a few actors first
vtkActor *CreateActor1( int argc, char *argv[], vtkRenderer * aRenderer )
{
char* fname2 = vtkTestUtilities::ExpandDataFileName(
argc, argv, "Data/headsq/quarter");
vtkVolume16Reader *v16 = vtkVolume16Reader::New();
v16->SetDataDimensions (64,64);
v16->SetImageRange (1,93);
v16->SetDataByteOrderToLittleEndian();
v16->SetFilePrefix (fname2);
v16->SetDataSpacing (3.2, 3.2, 1.5);
// An isosurface, or contour value of 500 is known to correspond to the
// skin of the patient. Once generated, a vtkPolyDataNormals filter is
// is used to create normals for smooth surface shading during rendering.
vtkContourFilter *skinExtractor = vtkContourFilter::New();
skinExtractor->SetInputConnection(v16->GetOutputPort());
skinExtractor->SetValue(0, 500);
vtkPolyDataNormals *skinNormals = vtkPolyDataNormals::New();
skinNormals->SetInputConnection(skinExtractor->GetOutputPort());
skinNormals->SetFeatureAngle(60.0);
vtkPolyDataMapper *skinMapper = vtkPolyDataMapper::New();
skinMapper->SetInputConnection(skinNormals->GetOutputPort());
skinMapper->ScalarVisibilityOff();
vtkActor *skin = vtkActor::New();
skin->SetMapper(skinMapper);
skin->GetProperty()->SetColor(0.95,0.75,0.75);
aRenderer->AddActor(skin);
v16->Delete();
skinExtractor->Delete();
skinNormals->Delete();
skinMapper->Delete();
skin->Delete();
return skin;
}
//-----------------------------------------------------------------------------
// Create a few actors first
vtkActor * CreateActor2( int vtkNotUsed(argc), char **vtkNotUsed(argv), vtkRenderer * ren )
{
vtkSphereSource *ss = vtkSphereSource::New();
ss->SetThetaResolution(30);
ss->SetPhiResolution(30);
ss->SetRadius(150.0);
vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
mapper->SetInput(ss->GetOutput());
vtkActor *actor = vtkActor::New();
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(0.0,1.0,0.0);
ren->AddActor(actor);
ss->Delete();
mapper->Delete();
actor->Delete();
return actor;
}
//-----------------------------------------------------------------------------
// Command to write out picked actors during mouse over.
class TestScenePickerCommand : public vtkCommand
{
public:
vtkScenePicker * m_Picker;
static TestScenePickerCommand *New()
{
return new TestScenePickerCommand;
}
virtual void Execute(vtkObject *caller, unsigned long vtkNotUsed(eventId), void* vtkNotUsed(callData))
{
vtkRenderWindowInteractor * iren = reinterpret_cast<
vtkRenderWindowInteractor *>(caller);
int e[2];
iren->GetEventPosition(e);
cout << "DisplayPosition : (" << e[0] << "," << e[1] << ")"
<< " Prop: " << m_ActorDescription[m_Picker->GetViewProp(e)].c_str()
<< " CellId: " << m_Picker->GetCellId(e)
<< " VertexId: " << m_Picker->GetVertexId(e)
<< endl;
}
void SetActorDescription( vtkProp *a, vtkstd::string s )
{
this->m_ActorDescription[a] = s;
}
vtkstd::map< vtkProp *, vtkstd::string > m_ActorDescription;
protected:
TestScenePickerCommand() { this->SetActorDescription((vtkActor*)NULL, "None"); }
virtual ~TestScenePickerCommand() {}
};
//-----------------------------------------------------------------------------
int TestScenePicker(int argc, char* argv[])
{
vtkRenderer *ren = vtkRenderer::New();
vtkRenderWindow *renWin = vtkRenderWindow::New();
vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
renWin->AddRenderer(ren);
iren->SetRenderWindow(renWin);
ren->SetBackground(0.0, 0.0, 0.0);
renWin->SetSize(300, 300);
// Here comes the scene picker stuff. [ Just 2 lines ]
vtkScenePicker * picker = vtkScenePicker::New();
picker->SetRenderer(ren);
// Write some stuff for interactive stuff.
TestScenePickerCommand * command =
TestScenePickerCommand::New();
command->m_Picker = picker;
command->SetActorDescription( CreateActor1( argc, argv, ren ), "Head" );
command->SetActorDescription( CreateActor2( argc, argv, ren ), "Sphere" );
iren->AddObserver(vtkCommand::MouseMoveEvent, command);
renWin->Render();
iren->Initialize();
// Check if scene picking works.
int retVal = EXIT_SUCCESS;
int e[2] = {175, 215};
if (command->m_ActorDescription[picker->GetViewProp(e)] != "Head" ||
picker->GetCellId(e) != 50992)
{
retVal = EXIT_FAILURE;
}
for ( int i = 0; i < argc; ++i )
{
if ( ! strcmp( argv[i], "-I" ) )
{
iren->Start();
}
}
// Cleanups
command->Delete();
picker->Delete();
ren->Delete();
renWin->Delete();
iren->Delete();
return retVal;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "BBE/SimpleFile.h"
#include <fstream>
#include <iostream>
#include <stdlib.h>
bbe::List<char> bbe::simpleFile::readBinaryFile(const bbe::String & filepath)
{
//UNTESTED
std::cout << filepath.getLength() << std::endl;
std::cout << filepath.getRaw() << std::endl;
for(std::size_t i = 0; i<filepath.getLength(); i++){
std::cout << filepath.getRaw()[i] << std::endl;
}
std::cout << "Reading File: " << filepath << std::endl;
std::ifstream file(filepath.getRaw(), std::ios::binary | std::ios::ate);
if (file)
{
size_t fileSize = (size_t)file.tellg();
bbe::List<char> fileBuffer;
fileBuffer.resizeCapacityAndLength(fileSize);
file.seekg(0);
file.read(fileBuffer.getRaw(), fileSize);
file.close();
return fileBuffer;
}
else
{
throw std::runtime_error("Failed to open file!");
}
}
void bbe::simpleFile::writeFloatArrToFile(const bbe::String & filePath, float * arr, size_t size)
{
std::ofstream file(filePath.getRaw());
for (std::size_t i = 0; i < size; i++)
{
file << arr[i] << "\n";
}
file.close();
}
<commit_msg>Stable again! Reverted simpleFile to use old String class.<commit_after>#include "stdafx.h"
#include "BBE/SimpleFile.h"
#include <fstream>
#include <iostream>
#include <stdlib.h>
bbe::List<char> bbe::simpleFile::readBinaryFile(const bbe::String & filepath)
{
//UNTESTED
std::cout << filepath.getLength() << std::endl;
std::cout << filepath.getRaw() << std::endl;
for(std::size_t i = 0; i<filepath.getLength(); i++){
std::cout << filepath.getRaw()[i] << std::endl;
}
wchar_t path_w[1024];
char path[1024];
memset(path_w, 0, 1024*sizeof(wchar_t));
std::cout << "OLA!" << std::endl;
if(filepath.getLength() >= sizeof(path) - 1)
{
throw std::runtime_error("Path too long!");
}
for(std::size_t i = 0; i<filepath.getLength(); i++)
{
std::cout << "OLA!" << std::endl;
path_w[i] = filepath.getRaw()[i];
}
std::cout << "OLA!" << std::endl;
std::size_t length = wcstombs(path, path_w, sizeof(path));
if(length >= sizeof(path) - 1)
{
throw std::runtime_error("Path too long!");
}
std::cout << "Reading File: " << path << std::endl;
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (file)
{
size_t fileSize = (size_t)file.tellg();
bbe::List<char> fileBuffer;
fileBuffer.resizeCapacityAndLength(fileSize);
file.seekg(0);
file.read(fileBuffer.getRaw(), fileSize);
file.close();
return fileBuffer;
}
else
{
throw std::runtime_error("Failed to open file!");
}
}
void bbe::simpleFile::writeFloatArrToFile(const bbe::String & filePath, float * arr, size_t size)
{
char path[1024];
std::size_t length = wcstombs(path, filePath.getRaw(), sizeof(path));
if(length >= sizeof(path) - 1)
{
throw std::runtime_error("Path too long!");
}
std::ofstream file(path);
for (std::size_t i = 0; i < size; i++)
{
file << arr[i] << "\n";
}
file.close();
}
<|endoftext|> |
<commit_before>/*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
This program 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
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include "DescriptionFactory.h"
DescriptionFactory::DescriptionFactory() { }
DescriptionFactory::~DescriptionFactory() { }
double DescriptionFactory::GetAzimuth(const _Coordinate& A, const _Coordinate& B) const {
double lonDiff = (A.lon-B.lon)/100000.;
double angle = atan2(sin(lonDiff)*cos(B.lat/100000.),
cos(A.lat/100000.)*sin(B.lat/100000.)-sin(A.lat/100000.)*cos(B.lat/100000.)*cos(lonDiff));
angle*=180/M_PI;
while(angle < 0)
angle += 360;
return angle;
}
void DescriptionFactory::SetStartSegment(const PhantomNode & _startPhantom) {
startPhantom = _startPhantom;
AppendSegment(_startPhantom.location, _PathData(0, _startPhantom.nodeBasedEdgeNameID, 10, _startPhantom.weight1));
}
void DescriptionFactory::SetEndSegment(const PhantomNode & _targetPhantom) {
targetPhantom = _targetPhantom;
pathDescription.push_back(SegmentInformation(_targetPhantom.location, _targetPhantom.nodeBasedEdgeNameID, 0, _targetPhantom.weight1, 0, true) );
}
void DescriptionFactory::AppendSegment(const _Coordinate & coordinate, const _PathData & data ) {
pathDescription.push_back(SegmentInformation(coordinate, data.nameID, 0, data.durationOfSegment, data.turnInstruction) );
}
void DescriptionFactory::AppendEncodedPolylineString(std::string & output, bool isEncoded) {
if(isEncoded)
pc.printEncodedString(pathDescription, output);
else
pc.printUnencodedString(pathDescription, output);
}
void DescriptionFactory::AppendEncodedPolylineString(std::string &output) {
pc.printEncodedString(pathDescription, output);
}
void DescriptionFactory::AppendUnencodedPolylineString(std::string &output) {
pc.printUnencodedString(pathDescription, output);
}
void DescriptionFactory::Run(const unsigned zoomLevel, const unsigned duration) {
if(0 == pathDescription.size())
return;
unsigned entireLength = 0;
/** starts at index 1 */
pathDescription[0].length = 0;
for(unsigned i = 1; i < pathDescription.size(); ++i) {
pathDescription[i].length = ApproximateDistance(pathDescription[i-1].location, pathDescription[i].location);
}
unsigned lengthOfSegment = 0;
unsigned durationOfSegment = 0;
unsigned indexOfSegmentBegin = 0;
for(unsigned i = 1; i < pathDescription.size(); ++i) {
entireLength += pathDescription[i].length;
lengthOfSegment += pathDescription[i].length;
durationOfSegment += pathDescription[i].duration;
pathDescription[indexOfSegmentBegin].length = lengthOfSegment;
pathDescription[indexOfSegmentBegin].duration = durationOfSegment;
if(pathDescription[i].turnInstruction != 0) {
//INFO("Turn after " << lengthOfSegment << "m into way with name id " << segment.nameID);
assert(pathDescription[i].necessary);
lengthOfSegment = 0;
durationOfSegment = 0;
indexOfSegmentBegin = i;
}
}
//Post-processing to remove empty or nearly empty path segments
if(0. == startPhantom.ratio || 0 == pathDescription[0].length) {
if(pathDescription.size() > 2)
pathDescription.erase(pathDescription.begin());
pathDescription[0].turnInstruction = TurnInstructions.HeadOn;
pathDescription[0].necessary = true;
startPhantom.nodeBasedEdgeNameID = pathDescription[0].nameID;
} else {
pathDescription[0].duration *= startPhantom.ratio;
}
if(1. == targetPhantom.ratio || 0 == pathDescription.back().length) {
if(pathDescription.size() > 2)
pathDescription.pop_back();
pathDescription.back().necessary = true;
pathDescription.back().turnInstruction = TurnInstructions.NoTurn;
targetPhantom.nodeBasedEdgeNameID = (pathDescription.end()-2)->nameID;
// INFO("Deleting last turn instruction");
} else {
pathDescription[indexOfSegmentBegin].duration *= (1.-targetPhantom.ratio);
}
//Generalize poly line
dp.Run(pathDescription, zoomLevel);
//fix what needs to be fixed else
for(unsigned i = 0; i < pathDescription.size()-1 && pathDescription.size() >= 2; ++i){
if(pathDescription[i].necessary) {
int angle = 100*GetAzimuth(pathDescription[i].location, pathDescription[i+1].location);
pathDescription[i].bearing = angle/100.;
}
}
BuildRouteSummary(entireLength, duration);
return;
}
void DescriptionFactory::BuildRouteSummary(const unsigned distance, const unsigned time) {
summary.startName = startPhantom.nodeBasedEdgeNameID;
summary.destName = targetPhantom.nodeBasedEdgeNameID;
summary.BuildDurationAndLengthStrings(distance, time);
}
<commit_msg>Fixes test cucumber --tags @basic:63 and issue #105<commit_after>/*
open source routing machine
Copyright (C) Dennis Luxen, others 2010
This program 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
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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include "DescriptionFactory.h"
DescriptionFactory::DescriptionFactory() { }
DescriptionFactory::~DescriptionFactory() { }
double DescriptionFactory::GetAzimuth(const _Coordinate& A, const _Coordinate& B) const {
double lonDiff = (A.lon-B.lon)/100000.;
double angle = atan2(sin(lonDiff)*cos(B.lat/100000.),
cos(A.lat/100000.)*sin(B.lat/100000.)-sin(A.lat/100000.)*cos(B.lat/100000.)*cos(lonDiff));
angle*=180/M_PI;
while(angle < 0)
angle += 360;
return angle;
}
void DescriptionFactory::SetStartSegment(const PhantomNode & _startPhantom) {
startPhantom = _startPhantom;
AppendSegment(_startPhantom.location, _PathData(0, _startPhantom.nodeBasedEdgeNameID, 10, _startPhantom.weight1));
}
void DescriptionFactory::SetEndSegment(const PhantomNode & _targetPhantom) {
targetPhantom = _targetPhantom;
pathDescription.push_back(SegmentInformation(_targetPhantom.location, _targetPhantom.nodeBasedEdgeNameID, 0, _targetPhantom.weight1, 0, true) );
}
void DescriptionFactory::AppendSegment(const _Coordinate & coordinate, const _PathData & data ) {
pathDescription.push_back(SegmentInformation(coordinate, data.nameID, 0, data.durationOfSegment, data.turnInstruction) );
}
void DescriptionFactory::AppendEncodedPolylineString(std::string & output, bool isEncoded) {
if(isEncoded)
pc.printEncodedString(pathDescription, output);
else
pc.printUnencodedString(pathDescription, output);
}
void DescriptionFactory::AppendEncodedPolylineString(std::string &output) {
pc.printEncodedString(pathDescription, output);
}
void DescriptionFactory::AppendUnencodedPolylineString(std::string &output) {
pc.printUnencodedString(pathDescription, output);
}
void DescriptionFactory::Run(const unsigned zoomLevel, const unsigned duration) {
if(0 == pathDescription.size())
return;
unsigned entireLength = 0;
/** starts at index 1 */
pathDescription[0].length = 0;
for(unsigned i = 1; i < pathDescription.size(); ++i) {
pathDescription[i].length = ApproximateDistance(pathDescription[i-1].location, pathDescription[i].location);
}
unsigned lengthOfSegment = 0;
unsigned durationOfSegment = 0;
unsigned indexOfSegmentBegin = 0;
for(unsigned i = 1; i < pathDescription.size(); ++i) {
entireLength += pathDescription[i].length;
lengthOfSegment += pathDescription[i].length;
durationOfSegment += pathDescription[i].duration;
pathDescription[indexOfSegmentBegin].length = lengthOfSegment;
pathDescription[indexOfSegmentBegin].duration = durationOfSegment;
if(pathDescription[i].turnInstruction != 0) {
//INFO("Turn after " << lengthOfSegment << "m into way with name id " << segment.nameID);
assert(pathDescription[i].necessary);
lengthOfSegment = 0;
durationOfSegment = 0;
indexOfSegmentBegin = i;
}
}
// INFO("#segs: " << pathDescription.size());
//Post-processing to remove empty or nearly empty path segments
if(0 == pathDescription.back().length) {
// INFO("#segs: " << pathDescription.size() << ", last ratio: " << targetPhantom.ratio << ", length: " << pathDescription.back().length);
if(pathDescription.size() > 2){
pathDescription.pop_back();
pathDescription.back().necessary = true;
pathDescription.back().turnInstruction = TurnInstructions.NoTurn;
targetPhantom.nodeBasedEdgeNameID = (pathDescription.end()-2)->nameID;
// INFO("Deleting last turn instruction");
}
} else {
pathDescription[indexOfSegmentBegin].duration *= (1.-targetPhantom.ratio);
}
if(0 == pathDescription[0].length) {
if(pathDescription.size() > 2) {
pathDescription.erase(pathDescription.begin());
pathDescription[0].turnInstruction = TurnInstructions.HeadOn;
pathDescription[0].necessary = true;
startPhantom.nodeBasedEdgeNameID = pathDescription[0].nameID;
// INFO("Deleting first turn instruction, ratio: " << startPhantom.ratio << ", length: " << pathDescription[0].length);
}
} else {
pathDescription[0].duration *= startPhantom.ratio;
}
//Generalize poly line
dp.Run(pathDescription, zoomLevel);
//fix what needs to be fixed else
for(unsigned i = 0; i < pathDescription.size()-1 && pathDescription.size() >= 2; ++i){
if(pathDescription[i].necessary) {
int angle = 100*GetAzimuth(pathDescription[i].location, pathDescription[i+1].location);
pathDescription[i].bearing = angle/100.;
}
}
BuildRouteSummary(entireLength, duration);
return;
}
void DescriptionFactory::BuildRouteSummary(const unsigned distance, const unsigned time) {
summary.startName = startPhantom.nodeBasedEdgeNameID;
summary.destName = targetPhantom.nodeBasedEdgeNameID;
summary.BuildDurationAndLengthStrings(distance, time);
}
<|endoftext|> |
<commit_before>//
// TextureUnitManager.cpp
//
// Originally written by RJ.
//
// Copyright (c) 2006 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "vtlib/vtlib.h"
#include "textureunitmanager.h"
//
// RJ's warning: NONE OF THIS IS THREAD SAFE!!!
//
vtTextureUnitManager::vtTextureUnitManager(void)
{
m_bInitialised = false;
m_pAllocationArray = NULL;
}
vtTextureUnitManager::~vtTextureUnitManager(void)
{
if (NULL != m_pAllocationArray)
delete m_pAllocationArray;
}
void vtTextureUnitManager::Initialise()
{
#if VTLIB_OSG
osg::ref_ptr<osg::Texture::Extensions> pTextureExtensions = osg::Texture::getExtensions(0, true);
m_iNumTextureUnits = pTextureExtensions->numTextureUnits();
#else
// Assume four.
m_iNumTextureUnits = 4;
#endif
m_pAllocationArray = new bool[m_iNumTextureUnits];
for (int i = 0; i < m_iNumTextureUnits; i++)
m_pAllocationArray[i] = false;
m_bInitialised = true;
}
int vtTextureUnitManager::ReserveTextureUnit()
{
int iUnit = -1;
if (!m_bInitialised)
Initialise();
for (int i = 0; i < m_iNumTextureUnits; i++)
{
if (m_pAllocationArray[i] == false)
{
m_pAllocationArray[i] = true;
iUnit = i;
break;
}
}
return iUnit;
}
void vtTextureUnitManager::FreeTextureUnit(int iUnit)
{
if (!m_bInitialised || (iUnit >= m_iNumTextureUnits))
return;
m_pAllocationArray[iUnit] = false;
}
<commit_msg>fixed case on include<commit_after>//
// TextureUnitManager.cpp
//
// Originally written by RJ.
//
// Copyright (c) 2006 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#include "vtlib/vtlib.h"
#include "TextureUnitManager.h"
//
// RJ's warning: NONE OF THIS IS THREAD SAFE!!!
//
vtTextureUnitManager::vtTextureUnitManager(void)
{
m_bInitialised = false;
m_pAllocationArray = NULL;
}
vtTextureUnitManager::~vtTextureUnitManager(void)
{
if (NULL != m_pAllocationArray)
delete m_pAllocationArray;
}
void vtTextureUnitManager::Initialise()
{
#if VTLIB_OSG
osg::ref_ptr<osg::Texture::Extensions> pTextureExtensions = osg::Texture::getExtensions(0, true);
m_iNumTextureUnits = pTextureExtensions->numTextureUnits();
#else
// Assume four.
m_iNumTextureUnits = 4;
#endif
m_pAllocationArray = new bool[m_iNumTextureUnits];
for (int i = 0; i < m_iNumTextureUnits; i++)
m_pAllocationArray[i] = false;
m_bInitialised = true;
}
int vtTextureUnitManager::ReserveTextureUnit()
{
int iUnit = -1;
if (!m_bInitialised)
Initialise();
for (int i = 0; i < m_iNumTextureUnits; i++)
{
if (m_pAllocationArray[i] == false)
{
m_pAllocationArray[i] = true;
iUnit = i;
break;
}
}
return iUnit;
}
void vtTextureUnitManager::FreeTextureUnit(int iUnit)
{
if (!m_bInitialised || (iUnit >= m_iNumTextureUnits))
return;
m_pAllocationArray[iUnit] = false;
}
<|endoftext|> |
<commit_before>#include <string>
#include "sm-log-impl.h"
using namespace RCU;
namespace {
/* No point allocating these individually or repeatedly---they're
thread-private with a reasonably small maximum size (~10kB).
WARNING: this assumes that transactions are pinned to their
worker thread at least until pre-commit. If we ever implement
DORA we'll have to be more clever, because transactions would
change threads frequently, but for now it works great.
*/
static __thread log_request tls_log_requests[sm_log_recover_mgr::MAX_BLOCK_RECORDS];
/* Same goes for the sm_tx_log_impl object we give the caller, for that matter */
static __thread char LOG_ALIGN tls_log_space[sizeof(sm_tx_log_impl)];
static __thread bool tls_log_space_used = false;
static sm_tx_log_impl*
get_log_impl(sm_tx_log *x)
{
DIE_IF(x != (void*) tls_log_space,
"sm_tx_log object can only be safely used by the thread that created it");
DIE_IF(not tls_log_space_used, "Attempt to access unallocated memory");
return get_impl(x);
}
}
void
sm_tx_log::log_insert_index(FID f, OID o, fat_ptr ptr, int abits, fat_ptr *pdest) {
get_log_impl(this)->add_payload_request(LOG_INSERT_INDEX, f, o, ptr, abits, pdest);
}
void
sm_tx_log::log_insert(FID f, OID o, fat_ptr ptr, int abits, fat_ptr *pdest) {
get_log_impl(this)->add_payload_request(LOG_INSERT, f, o, ptr, abits, pdest);
}
void
sm_tx_log::log_update(FID f, OID o, fat_ptr ptr, int abits, fat_ptr *pdest) {
get_log_impl(this)->add_payload_request(LOG_UPDATE, f, o, ptr, abits, pdest);
}
void
sm_tx_log::log_fid(FID f, const std::string &name)
{
auto size = align_up(name.length()) + 1;
auto size_code = encode_size_aligned(size);
char *buf = (char *)malloc(size);
memset(buf, '\0', size);
memcpy(buf, (char *)name.c_str(), size-1);
ASSERT(buf[size-1] == '\0');
// only use the logrec's fid field, payload is name
get_log_impl(this)->add_payload_request(LOG_FID, f, 0,
fat_ptr::make(buf, size_code),
DEFAULT_ALIGNMENT_BITS, NULL);
}
static
void
format_extra_ptr(log_request &req)
{
auto p = req.extra_ptr = req.payload_ptr;
req.payload_ptr = fat_ptr::make(&req.extra_ptr, p.size_code());
req.payload_size = align_up(sizeof(req.extra_ptr));
}
static
log_request
make_log_request(log_record_type type, FID f, OID o, fat_ptr ptr, int abits) {
log_request req;
req.type = type;
req.fid = f;
req.oid = o;
req.pdest = NULL;
req.size_align_bits = abits;
req.payload_ptr = ptr;
req.payload_size = decode_size_aligned(ptr.size_code(), abits);
return req;
}
void
sm_tx_log::log_relocate(FID f, OID o, fat_ptr ptr, int abits) {
log_request req = make_log_request(LOG_RELOCATE, f, o, ptr, abits);
format_extra_ptr(req);
get_log_impl(this)->add_request(req);
}
void
sm_tx_log::log_delete(FID f, OID o) {
log_request req = make_log_request(LOG_DELETE, f, o, NULL_PTR, 0);
get_log_impl(this)->add_request(req);
}
LSN
sm_tx_log::get_clsn() {
/* The caller already has a published CLSN, so if this tx still
appears to not have a commit block it cannot possibly have an
earlier CLSN. INVALID_LSN is an appropriate
response. Otherwise, we have to race to finish installing a
commit block.
WARNING: Both this object and the commit block it points to
might have been freed by the time a thread calls this function,
so the caller must use an appropriate RCU transaction to avoid
use-after-free bugs.
*/
auto *impl = get_log_impl(this);
if (auto *a = volatile_read(impl->_commit_block)) {
a = impl->_install_commit_block(a);
return a->block->next_lsn();
}
return INVALID_LSN;
}
LSN
sm_tx_log::pre_commit() {
auto *impl = get_log_impl(this);
if (not impl->_commit_block)
impl->enter_precommit();
return impl->_commit_block->block->next_lsn();
}
LSN
sm_tx_log::commit(LSN *pdest) {
// make sure we acquired a commit block
LSN clsn = pre_commit();
auto *impl = get_log_impl(this);
// now copy log record data
impl->_populate_block(impl->_commit_block->block);
if (pdest)
*pdest = impl->_commit_block->block->lsn;
impl->_log->_lm.release(impl->_commit_block);
tls_log_space_used = false;
return clsn;
}
void
sm_tx_log::discard() {
auto *impl = get_log_impl(this);
if (impl->_commit_block)
impl->_log->_lm.discard(impl->_commit_block);
tls_log_space_used = false;
}
void *
sm_tx_log_impl::alloc_storage() {
DIE_IF(tls_log_space_used, "Only one transaction per worker thread is allowed");
tls_log_space_used = true;
return tls_log_space;
}
void
sm_tx_log_impl::add_payload_request(log_record_type type, FID f, OID o,
fat_ptr p, int abits, fat_ptr *pdest)
{
log_request req = make_log_request(type, f, o, p, abits);
// 4GB+ for a single object is just too big. Punt.
size_t psize = req.payload_size;
THROW_IF(psize > UINT32_MAX, illegal_argument,
"Log record payload must be less than 4GB (%zd requested, %zd bytes over limit)",
psize, psize - UINT32_MAX);
/* If the record's payload is too large (e.g. 8 of them would
overflow the block), then embed the payload directly in the log
(disguised as a skip record) and link the request to it.
*/
if (sm_log_recover_mgr::MAX_BLOCK_SIZE < log_block::wrapped_size(8, 8*psize)) {
log_allocation *a = _log->_lm.allocate(0, psize);
DEFER_UNLESS(it_worked, _log->_lm.discard(a));
log_block *b = a->block;
ASSERT(b->nrec == 0);
ASSERT(b->lsn != INVALID_LSN);
ASSERT(b->records->type == LOG_SKIP);
b->records->type = LOG_FAT_SKIP;
b->records->size_code = p.size_code();
b->records->size_align_bits = abits;
uint32_t csum = b->body_checksum();
b->checksum = adler32_memcpy(b->payload_begin(), p, psize, csum);
// update the request to point to the external record
req.type = (log_record_type) (req.type | LOG_FLAG_IS_EXT);
p = req.payload_ptr = _log->lsn2ptr(b->payload_lsn(0), false);
format_extra_ptr(req);
if (pdest) {
*pdest = p;
pdest = NULL;
}
it_worked = true;
_log->_lm.release(a);
}
// add to list
req.pdest = pdest;
add_request(req);
}
void sm_tx_log_impl::add_request(log_request const &req) {
ASSERT (not _commit_block);
auto new_nreq = _nreq+1;
bool too_many = (new_nreq > sm_log_recover_mgr::MAX_BLOCK_RECORDS);
auto new_payload_bytes = _payload_bytes + align_up(req.payload_size);
ASSERT(is_aligned(new_payload_bytes));
auto bsize = log_block::wrapped_size(new_nreq, new_payload_bytes);
bool too_big = bsize > sm_log_recover_mgr::MAX_BLOCK_SIZE;
if (too_many or too_big) {
spill_overflow();
return add_request(req);
}
tls_log_requests[_nreq] = req;
_nreq = new_nreq;
_payload_bytes = new_payload_bytes;
}
void
sm_tx_log_impl::_populate_block(log_block *b)
{
size_t i = 0;
uint32_t payload_end = 0;
uint32_t csum_payload = ADLER32_CSUM_INIT;
// link to previous overflow?
if (_prev_overflow != INVALID_LSN) {
log_record *r = &b->records[i++];
r->type = LOG_OVERFLOW;
r->size_code = INVALID_SIZE_CODE;
r->size_align_bits = 0;
r->payload_end = 0;
r->next_lsn = _prev_overflow;
}
// process normal log records
while (i < _nreq) {
log_request *it = &tls_log_requests[i];
DEFER(++i);
log_record *r = &b->records[i];
r->type = it->type;
r->fid = it->fid;
r->oid = it->oid;
if (it->type & LOG_FLAG_HAS_PAYLOAD) {
// fill out payload-related bits before calling payload_lsn()
r->size_code = it->payload_ptr.size_code();
r->size_align_bits = it->size_align_bits;
// copy and checksum the payload
if (it->pdest) {
bool is_ext = it->type & LOG_FLAG_IS_EXT;
*it->pdest = _log->lsn2ptr(b->payload_lsn(i), is_ext);
}
char *dest = b->payload_begin() + payload_end;
csum_payload = adler32_memcpy(dest, it->payload_ptr, it->payload_size, csum_payload);
payload_end += it->payload_size;
}
else {
r->size_code = INVALID_SIZE_CODE;
r->size_align_bits = -1;
}
r->payload_end = payload_end;
}
ASSERT (i == b->nrec);
ASSERT (b->payload_end() == b->payload_begin() + payload_end);
// finalize the checksum
uint32_t csum = b->body_checksum();
b->checksum = adler32_merge(csum, csum_payload, payload_end);
}
/* Transactions assign this value to their commit block as a signal of
their intent to enter pre-commit. It should never be accessed or
freed.
*/
static constexpr
log_allocation * const ENTERING_PRECOMMIT = (log_allocation*) 0x1;
/* Sometimes the log block overflows before a transaction completes
and we have to spill and overflow block to the log.
*/
void sm_tx_log_impl::spill_overflow() {
size_t inner_nreq = _nreq;
size_t outer_nreq = 0;
size_t pbytes = log_block::size(inner_nreq, _payload_bytes);
log_allocation *a = _log->_lm.allocate(outer_nreq, pbytes);
DEFER_UNLESS(it_worked, _log->_lm.discard(a));
log_block *b = a->block;
ASSERT(b->nrec == outer_nreq);
ASSERT(b->lsn != INVALID_LSN);
b->records->type = LOG_FAT_SKIP;
auto *inner = (log_block*) b->payload(0);
inner->nrec = inner_nreq;
inner->lsn = b->payload_lsn(0);
fill_skip_record(&inner->records[inner_nreq], INVALID_LSN, _payload_bytes, false);
_populate_block(inner);
uint32_t csum = b->body_checksum();
b->checksum = adler32_merge(csum, inner->checksum, pbytes);
_nreq = 1; // for the overflow LSN
_prev_overflow = inner->lsn;
_payload_bytes = 0;
it_worked = true;
_log->_lm.release(a);
}
/* This function is called by threads racing to install a commit
block. The transaction calls it as part of the pre-commit protocol,
and other threads call it to learn whether this transaction's CLSN
precedes theirs or not (and if so, its value). It should never be
called with a NULL _commit_block: the owner thread should signal
ENTERING_PRECOMMIT, and other threads should only call this if they
see a non-NULL value (which might be the signal, or might be an
already-installed commit block).
*/
log_allocation *sm_tx_log_impl::_install_commit_block(log_allocation *a) {
ASSERT(a);
if (a == ENTERING_PRECOMMIT) {
a = _log->_lm.allocate(_nreq, _payload_bytes);
auto *tmp = __sync_val_compare_and_swap(&_commit_block, ENTERING_PRECOMMIT, a);
if (tmp != ENTERING_PRECOMMIT) {
_log->_lm.discard(a);
a = tmp;
}
ASSERT(a != ENTERING_PRECOMMIT);
ASSERT(a->block->nrec == _nreq);
ASSERT(a->block->lsn != INVALID_LSN);
}
return a;
}
void sm_tx_log_impl::enter_precommit() {
_commit_block = ENTERING_PRECOMMIT;
auto *a = _install_commit_block(ENTERING_PRECOMMIT);
DEFER_UNLESS(it_worked, _log->_lm.discard(a));
// tzwang: avoid copying data here, commit() will do it
//_populate_block(a->block);
// leave these in place for late-comers to the race
//_nreq = 0;
//_prev_overflow = INVALID_LSN;
//_payload_bytes = 0;
it_worked = true;
// do this late to give races plenty of time to show up
ASSERT(_commit_block == a);
}
<commit_msg>Fix potential buf overflow in sm-tx-log.<commit_after>#include <string>
#include "sm-log-impl.h"
using namespace RCU;
namespace {
/* No point allocating these individually or repeatedly---they're
thread-private with a reasonably small maximum size (~10kB).
WARNING: this assumes that transactions are pinned to their
worker thread at least until pre-commit. If we ever implement
DORA we'll have to be more clever, because transactions would
change threads frequently, but for now it works great.
*/
static __thread log_request tls_log_requests[sm_log_recover_mgr::MAX_BLOCK_RECORDS];
/* Same goes for the sm_tx_log_impl object we give the caller, for that matter */
static __thread char LOG_ALIGN tls_log_space[sizeof(sm_tx_log_impl)];
static __thread bool tls_log_space_used = false;
static sm_tx_log_impl*
get_log_impl(sm_tx_log *x)
{
DIE_IF(x != (void*) tls_log_space,
"sm_tx_log object can only be safely used by the thread that created it");
DIE_IF(not tls_log_space_used, "Attempt to access unallocated memory");
return get_impl(x);
}
}
void
sm_tx_log::log_insert_index(FID f, OID o, fat_ptr ptr, int abits, fat_ptr *pdest) {
get_log_impl(this)->add_payload_request(LOG_INSERT_INDEX, f, o, ptr, abits, pdest);
}
void
sm_tx_log::log_insert(FID f, OID o, fat_ptr ptr, int abits, fat_ptr *pdest) {
get_log_impl(this)->add_payload_request(LOG_INSERT, f, o, ptr, abits, pdest);
}
void
sm_tx_log::log_update(FID f, OID o, fat_ptr ptr, int abits, fat_ptr *pdest) {
get_log_impl(this)->add_payload_request(LOG_UPDATE, f, o, ptr, abits, pdest);
}
void
sm_tx_log::log_fid(FID f, const std::string &name)
{
auto size = align_up(name.length() + 1);
auto size_code = encode_size_aligned(size);
char *buf = (char *)malloc(size);
memset(buf, '\0', size);
memcpy(buf, (char *)name.c_str(), name.length());
ASSERT(buf[name.length()] == '\0');
// only use the logrec's fid field, payload is name
get_log_impl(this)->add_payload_request(LOG_FID, f, 0,
fat_ptr::make(buf, size_code),
DEFAULT_ALIGNMENT_BITS, NULL);
}
static
void
format_extra_ptr(log_request &req)
{
auto p = req.extra_ptr = req.payload_ptr;
req.payload_ptr = fat_ptr::make(&req.extra_ptr, p.size_code());
req.payload_size = align_up(sizeof(req.extra_ptr));
}
static
log_request
make_log_request(log_record_type type, FID f, OID o, fat_ptr ptr, int abits) {
log_request req;
req.type = type;
req.fid = f;
req.oid = o;
req.pdest = NULL;
req.size_align_bits = abits;
req.payload_ptr = ptr;
req.payload_size = decode_size_aligned(ptr.size_code(), abits);
return req;
}
void
sm_tx_log::log_relocate(FID f, OID o, fat_ptr ptr, int abits) {
log_request req = make_log_request(LOG_RELOCATE, f, o, ptr, abits);
format_extra_ptr(req);
get_log_impl(this)->add_request(req);
}
void
sm_tx_log::log_delete(FID f, OID o) {
log_request req = make_log_request(LOG_DELETE, f, o, NULL_PTR, 0);
get_log_impl(this)->add_request(req);
}
LSN
sm_tx_log::get_clsn() {
/* The caller already has a published CLSN, so if this tx still
appears to not have a commit block it cannot possibly have an
earlier CLSN. INVALID_LSN is an appropriate
response. Otherwise, we have to race to finish installing a
commit block.
WARNING: Both this object and the commit block it points to
might have been freed by the time a thread calls this function,
so the caller must use an appropriate RCU transaction to avoid
use-after-free bugs.
*/
auto *impl = get_log_impl(this);
if (auto *a = volatile_read(impl->_commit_block)) {
a = impl->_install_commit_block(a);
return a->block->next_lsn();
}
return INVALID_LSN;
}
LSN
sm_tx_log::pre_commit() {
auto *impl = get_log_impl(this);
if (not impl->_commit_block)
impl->enter_precommit();
return impl->_commit_block->block->next_lsn();
}
LSN
sm_tx_log::commit(LSN *pdest) {
// make sure we acquired a commit block
LSN clsn = pre_commit();
auto *impl = get_log_impl(this);
// now copy log record data
impl->_populate_block(impl->_commit_block->block);
if (pdest)
*pdest = impl->_commit_block->block->lsn;
impl->_log->_lm.release(impl->_commit_block);
tls_log_space_used = false;
return clsn;
}
void
sm_tx_log::discard() {
auto *impl = get_log_impl(this);
if (impl->_commit_block)
impl->_log->_lm.discard(impl->_commit_block);
tls_log_space_used = false;
}
void *
sm_tx_log_impl::alloc_storage() {
DIE_IF(tls_log_space_used, "Only one transaction per worker thread is allowed");
tls_log_space_used = true;
return tls_log_space;
}
void
sm_tx_log_impl::add_payload_request(log_record_type type, FID f, OID o,
fat_ptr p, int abits, fat_ptr *pdest)
{
log_request req = make_log_request(type, f, o, p, abits);
// 4GB+ for a single object is just too big. Punt.
size_t psize = req.payload_size;
THROW_IF(psize > UINT32_MAX, illegal_argument,
"Log record payload must be less than 4GB (%zd requested, %zd bytes over limit)",
psize, psize - UINT32_MAX);
/* If the record's payload is too large (e.g. 8 of them would
overflow the block), then embed the payload directly in the log
(disguised as a skip record) and link the request to it.
*/
if (sm_log_recover_mgr::MAX_BLOCK_SIZE < log_block::wrapped_size(8, 8*psize)) {
log_allocation *a = _log->_lm.allocate(0, psize);
DEFER_UNLESS(it_worked, _log->_lm.discard(a));
log_block *b = a->block;
ASSERT(b->nrec == 0);
ASSERT(b->lsn != INVALID_LSN);
ASSERT(b->records->type == LOG_SKIP);
b->records->type = LOG_FAT_SKIP;
b->records->size_code = p.size_code();
b->records->size_align_bits = abits;
uint32_t csum = b->body_checksum();
b->checksum = adler32_memcpy(b->payload_begin(), p, psize, csum);
// update the request to point to the external record
req.type = (log_record_type) (req.type | LOG_FLAG_IS_EXT);
p = req.payload_ptr = _log->lsn2ptr(b->payload_lsn(0), false);
format_extra_ptr(req);
if (pdest) {
*pdest = p;
pdest = NULL;
}
it_worked = true;
_log->_lm.release(a);
}
// add to list
req.pdest = pdest;
add_request(req);
}
void sm_tx_log_impl::add_request(log_request const &req) {
ASSERT (not _commit_block);
auto new_nreq = _nreq+1;
bool too_many = (new_nreq > sm_log_recover_mgr::MAX_BLOCK_RECORDS);
auto new_payload_bytes = _payload_bytes + align_up(req.payload_size);
ASSERT(is_aligned(new_payload_bytes));
auto bsize = log_block::wrapped_size(new_nreq, new_payload_bytes);
bool too_big = bsize > sm_log_recover_mgr::MAX_BLOCK_SIZE;
if (too_many or too_big) {
spill_overflow();
return add_request(req);
}
tls_log_requests[_nreq] = req;
_nreq = new_nreq;
_payload_bytes = new_payload_bytes;
}
void
sm_tx_log_impl::_populate_block(log_block *b)
{
size_t i = 0;
uint32_t payload_end = 0;
uint32_t csum_payload = ADLER32_CSUM_INIT;
// link to previous overflow?
if (_prev_overflow != INVALID_LSN) {
log_record *r = &b->records[i++];
r->type = LOG_OVERFLOW;
r->size_code = INVALID_SIZE_CODE;
r->size_align_bits = 0;
r->payload_end = 0;
r->next_lsn = _prev_overflow;
}
// process normal log records
while (i < _nreq) {
log_request *it = &tls_log_requests[i];
DEFER(++i);
log_record *r = &b->records[i];
r->type = it->type;
r->fid = it->fid;
r->oid = it->oid;
if (it->type & LOG_FLAG_HAS_PAYLOAD) {
// fill out payload-related bits before calling payload_lsn()
r->size_code = it->payload_ptr.size_code();
r->size_align_bits = it->size_align_bits;
// copy and checksum the payload
if (it->pdest) {
bool is_ext = it->type & LOG_FLAG_IS_EXT;
*it->pdest = _log->lsn2ptr(b->payload_lsn(i), is_ext);
}
char *dest = b->payload_begin() + payload_end;
csum_payload = adler32_memcpy(dest, it->payload_ptr, it->payload_size, csum_payload);
payload_end += it->payload_size;
}
else {
r->size_code = INVALID_SIZE_CODE;
r->size_align_bits = -1;
}
r->payload_end = payload_end;
}
ASSERT (i == b->nrec);
ASSERT (b->payload_end() == b->payload_begin() + payload_end);
// finalize the checksum
uint32_t csum = b->body_checksum();
b->checksum = adler32_merge(csum, csum_payload, payload_end);
}
/* Transactions assign this value to their commit block as a signal of
their intent to enter pre-commit. It should never be accessed or
freed.
*/
static constexpr
log_allocation * const ENTERING_PRECOMMIT = (log_allocation*) 0x1;
/* Sometimes the log block overflows before a transaction completes
and we have to spill and overflow block to the log.
*/
void sm_tx_log_impl::spill_overflow() {
size_t inner_nreq = _nreq;
size_t outer_nreq = 0;
size_t pbytes = log_block::size(inner_nreq, _payload_bytes);
log_allocation *a = _log->_lm.allocate(outer_nreq, pbytes);
DEFER_UNLESS(it_worked, _log->_lm.discard(a));
log_block *b = a->block;
ASSERT(b->nrec == outer_nreq);
ASSERT(b->lsn != INVALID_LSN);
b->records->type = LOG_FAT_SKIP;
auto *inner = (log_block*) b->payload(0);
inner->nrec = inner_nreq;
inner->lsn = b->payload_lsn(0);
fill_skip_record(&inner->records[inner_nreq], INVALID_LSN, _payload_bytes, false);
_populate_block(inner);
uint32_t csum = b->body_checksum();
b->checksum = adler32_merge(csum, inner->checksum, pbytes);
_nreq = 1; // for the overflow LSN
_prev_overflow = inner->lsn;
_payload_bytes = 0;
it_worked = true;
_log->_lm.release(a);
}
/* This function is called by threads racing to install a commit
block. The transaction calls it as part of the pre-commit protocol,
and other threads call it to learn whether this transaction's CLSN
precedes theirs or not (and if so, its value). It should never be
called with a NULL _commit_block: the owner thread should signal
ENTERING_PRECOMMIT, and other threads should only call this if they
see a non-NULL value (which might be the signal, or might be an
already-installed commit block).
*/
log_allocation *sm_tx_log_impl::_install_commit_block(log_allocation *a) {
ASSERT(a);
if (a == ENTERING_PRECOMMIT) {
a = _log->_lm.allocate(_nreq, _payload_bytes);
auto *tmp = __sync_val_compare_and_swap(&_commit_block, ENTERING_PRECOMMIT, a);
if (tmp != ENTERING_PRECOMMIT) {
_log->_lm.discard(a);
a = tmp;
}
ASSERT(a != ENTERING_PRECOMMIT);
ASSERT(a->block->nrec == _nreq);
ASSERT(a->block->lsn != INVALID_LSN);
}
return a;
}
void sm_tx_log_impl::enter_precommit() {
_commit_block = ENTERING_PRECOMMIT;
auto *a = _install_commit_block(ENTERING_PRECOMMIT);
DEFER_UNLESS(it_worked, _log->_lm.discard(a));
// tzwang: avoid copying data here, commit() will do it
//_populate_block(a->block);
// leave these in place for late-comers to the race
//_nreq = 0;
//_prev_overflow = INVALID_LSN;
//_payload_bytes = 0;
it_worked = true;
// do this late to give races plenty of time to show up
ASSERT(_commit_block == a);
}
<|endoftext|> |
<commit_before>/*
* DynBetweenness.cpp
*
* Created on: 29.07.2014
* Author: ebergamini
*/
#include <stack>
#include <queue>
#include <memory>
#include "../auxiliary/PrioQueue.h"
#include "DynBetweenness.h"
#include "../auxiliary/PrioQueue.h"
#include "../auxiliary/Log.h"
#include "../graph/SSSP.h"
#include "../graph/Dijkstra.h"
#include "../graph/BFS.h"
namespace NetworKit {
DynBetweenness::DynBetweenness(const Graph& G, bool storePredecessors) : Centrality(G, normalized),
maxDistance(G.upperNodeIdBound()),
npaths(G.upperNodeIdBound(), std::vector<count>(G.upperNodeIdBound())),
distances(G.upperNodeIdBound(), std::vector<edgeweight>(G.upperNodeIdBound())),
dependencies(G.upperNodeIdBound(),std::vector<double>(G.upperNodeIdBound(), 0.0)),
storePreds(storePredecessors) {
}
inline bool logically_equal(double a, double b, double error_factor=1.0)
{
return a==b || std::abs(a-b)<std::abs(std::min(a,b))*std::numeric_limits<double>::epsilon()*error_factor;
}
void DynBetweenness::run() {
count z = G.upperNodeIdBound();
scoreData.clear();
scoreData.resize(z);
npaths.clear();
nPaths.resize(z);
distances.clear();
distance.resize(z);
dependencies.clear();
dependencies.resize(z);
if (storePreds) {
predecessors.clear();
predecessors.resize(G.upperNodeIdBound());
G.forNodes([&](node v){
predecessors[v].resize(G.upperNodeIdBound());
});
}
auto computeDependencies = [&](node s) {
// run SSSP algorithm and keep track of everything
std::unique_ptr<SSSP> sssp;
if (G.isWeighted()) {
sssp.reset(new Dijkstra(G, s, true, true));
} else {
sssp.reset(new BFS(G, s, true, true));
}
sssp->run();
G.forNodes([&](node t){
distances[s][t] = sssp->distance(t);
npaths[s][t] = sssp->numberOfPaths(t);
if (storePreds) {
predecessors[s][t] = sssp->getPredecessors(t);
}
});
// compute dependencies for nodes in order of decreasing distance from s
std::stack<node> stack = sssp->getStack();
// set maxDistance to the distance of the furthest vertex
maxDistance[s] = distances[s][stack.top()];
while (!stack.empty()) {
node t = stack.top();
stack.pop();
for (node p : sssp->getPredecessors(t)) {
dependencies[s][p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dependencies[s][t]);
}
if (t != s) {
scoreData[t] += dependencies[s][t];
}
}
};
G.forNodes(computeDependencies);
}
void DynBetweenness::updateUnweighted(GraphEvent e) {
G.forNodes([&] (node s){
node u_l, u_h;
if (distances[s][e.u] > distances[s][e.v]){
u_l = e.u;
u_h = e.v;
} else {
u_l = e.v;
u_h = e.u;
}
edgeweight difference = distances[s][u_l] - distances[s][u_h];
if (difference > 0) {
std::vector<count> new_npaths(G.upperNodeIdBound());
std::vector<edgeweight> new_dist(G.upperNodeIdBound());
G.forNodes([&] (node v){
new_npaths[v] = npaths[s][v];
new_dist[v] = distances[s][v];
});
std::vector<double> new_dep(G.upperNodeIdBound(), 0.0);
std::vector<int> touched(G.upperNodeIdBound(), 0);
std::vector<std::queue<node>> l_queues(maxDistance[s]+1);
std::queue<node> queue_BFS;
queue_BFS.push(u_l);
// one-level update
if (difference == 1) {
l_queues[distances[s][u_l]].push(u_l);
if (storePreds)
predecessors[s][u_l].push_back(u_h);
new_npaths[u_l] += npaths[s][u_h];
touched[u_l] = -1;
// BFS traversal from u_l
while (!queue_BFS.empty()) {
node v = queue_BFS.front();
DEBUG("extracted node ", v);
queue_BFS.pop();
G.forNeighborsOf(v, [&](node w) {
if (new_dist[w] == new_dist[v]+1) {
if (touched[w] == 0) {
touched[w] = -1;
queue_BFS.push(w);
l_queues[new_dist[w]].push(w);
}
new_npaths[w] = new_npaths[w] - npaths[s][v] + new_npaths[v];
}
});
}
} else if (difference > 1) {
new_dist[u_l] = distances[s][u_h] + 1;
l_queues[new_dist[u_l]].push(u_l);
// BFS traversal from u_l
while (!queue_BFS.empty()) {
node v = queue_BFS.front();
DEBUG("extracted node ",v);
if (storePreds) {
predecessors[s][v].clear();
}
queue_BFS.pop();
touched[v] = -1;
new_npaths[v] = 0;
G.forNeighborsOf(v, [&] (node w){
if (new_dist[w] + 1 == new_dist[v]) {
new_npaths[v] += new_npaths[w];
if (storePreds) {
predecessors[s][v].push_back(w);
}
}
if (new_dist[w] >= new_dist[v] && touched[w] == 0) {
if (new_dist[w] > new_dist[v])
new_dist[w] = new_dist[v]+1;
touched[w] = -1;
l_queues[new_dist[w]].push(w);
queue_BFS.push(w);
}
});
}
}
// dependencies accumulation
DEBUG("Dependency accumulation");
count level = maxDistance[s];
while(level > 0) {
while(!l_queues[level].empty()) {
node w = l_queues[level].front();
DEBUG("Node ",w);
l_queues[level].pop();
auto updateDependency = [&](node w, node v) {
if (new_dist[v] < new_dist[w]) {
if (touched[v] == 0) {
touched[v] = 1;
new_dep[v] = dependencies[s][v];
l_queues[level-1].push(v);
}
double new_contrib = double(new_npaths[v])/new_npaths[w]*(1+new_dep[w]);
new_dep[v] += new_contrib;
double old_contrib = double(npaths[s][v])/npaths[s][w]*(1+dependencies[s][w]);
if (touched[v] == 1 && (v != u_h or w!= u_l))
new_dep[v] -= old_contrib;
DEBUG("Parent ", v);
}
};
if (storePreds) {
for (node v : predecessors[s][w]) {
updateDependency(w, v);
}
}
else {
G.forNeighborsOf(w, [&](node v){
updateDependency(w, v);
});
}
if (w != s) {
scoreData[w] = scoreData[w] + new_dep[w] - dependencies[s][w];
}
}
level = level - 1;
}
// data structures update
G.forNodes([&] (node r){
distances[s][r] = new_dist[r];
npaths[s][r] = new_npaths[r];
if (touched[r] != 0)
dependencies[s][r] = new_dep[r];
});
}
/*
BFS sssp(G, s, true, true);
sssp.run();
G.forNodes([&](node t){
if(distances[s][t] != sssp.distance(t) || npaths[s][t] != sssp.numberOfPaths(t)) {
std::cout<<"Source: "<<s<<" Node "<<t<<std::endl;
std::cout<<"COMPUTED DISTANCE: "<<distances[s][t]<<" REAL DISTANCE: "<<sssp.distance(t)<<std::endl;
std::cout<<"COMPUTED NUMBER OF PATHS: "<<npaths[s][t]<<" REAL NUMBER OF PATHS: "<<sssp.numberOfPaths(t)<<std::endl;
}
});
// compute dependencies for nodes in order of decreasing distance from s
std::vector<double> dep(G.upperNodeIdBound());
std::stack<node> stack = sssp.getStack();
while (!stack.empty()) {
node t = stack.top();
stack.pop();
for (node p : sssp.getPredecessors(t)) {
dep[p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dep[t]);
}
}
G.forNodes([&](node t){
if((dependencies[s][t]-dep[t]>0.000001 || dependencies[s][t]-dep[t]<-0.000001) && s!=t) {
std::cout<<"Source: "<<s<<" Node "<<t<<std::endl;
std::cout<<"COMPUTED DEPENDENCY: "<<dependencies[s][t]<<" REAL DEPENDENCY: "<<dep[t]<<std::endl;
}
});
*/
});
}
void DynBetweenness::updateWeighted(GraphEvent e) {
G.forNodes([&] (node s){
scoreData[s] = 0.0;
});
G.forNodes([&] (node s){
// update of distances and number of shortest paths
Aux::PrioQueue<double, node> S(G.upperNodeIdBound());
G.forNodes([&] (node t){
auto updatePaths = [&](node u, node v, edgeweight w) {
if (distances[s][t] == distances[s][u] + w + distances[v][t]){
npaths[s][t] = npaths[s][t] + npaths[s][u] * npaths[v][t];
if (storePreds) {
if (t != v){
DEBUG("Adding predecessors from v to t to predecessors from s to t");
//predecessors[s][t].insert( predecessors[s][t].end(), predecessors[v][t].begin(), predecessors[v][t].end());
for (node pv : predecessors[v][t]) {
bool wasAlreadyPred = false;
for (node ps : predecessors[s][t]) {
if (ps == pv)
wasAlreadyPred = true;
}
if (!wasAlreadyPred)
predecessors[s][t].push_back(pv);
}
DEBUG("Finished adding");
}
else {
DEBUG("Adding u to the predecessors of v");
predecessors[s][t].push_back(u);
DEBUG("Finished adding");
}
}
}
if (distances[s][t] > distances[s][u] + w + distances[v][t]){
distances[s][t] = distances[s][u] + w + distances[v][t];
npaths[s][t] = npaths[s][u] * npaths[v][t];
if (storePreds) {
if (t != v) {
DEBUG("Replacing predecessors from v to t with predecessors from s to t");
predecessors[s][t] = predecessors[v][t];
DEBUG("Finished replacing");
}
else {
DEBUG("Replacing old predecessors of v with u");
predecessors[s][t].clear();
predecessors[s][t].push_back(u);
DEBUG("Finished replacing");
}
}
}
};
if (s != t) {
updatePaths(e.u, e.v, e.w);
updatePaths(e.v, e.u, e.w);
S.insert(-1*distances[s][t], t);
dependencies[s][t] = 0.0;
}
});
// dependency accumulation
while (S.size() != 0) {
// extract the node with the maximum distance
node t = S.extractMin().second;
if (storePreds) {
DEBUG("Computing dependencies");
for (node p : predecessors[s][t]) {
dependencies[s][p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dependencies[s][t]);
}
}
else {
G.forNeighborsOf(t, [&] (node p){
if (logically_equal(distances[s][t], distances[s][p] + G.weight(p, t))) {
dependencies[s][p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dependencies[s][t]);
}
});
}
if (t != s) {
scoreData[t] += dependencies[s][t];
}
}
});
}
void DynBetweenness::update(GraphEvent e) {
if (G.isWeighted())
updateWeighted(e);
else
updateUnweighted(e);
}
} /* namespace NetworKit */
<commit_msg>inserted cleaning of structures at the beginning of the run method in dynbetweenness<commit_after>/*
* DynBetweenness.cpp
*
* Created on: 29.07.2014
* Author: ebergamini
*/
#include <stack>
#include <queue>
#include <memory>
#include "../auxiliary/PrioQueue.h"
#include "DynBetweenness.h"
#include "../auxiliary/PrioQueue.h"
#include "../auxiliary/Log.h"
#include "../graph/SSSP.h"
#include "../graph/Dijkstra.h"
#include "../graph/BFS.h"
namespace NetworKit {
DynBetweenness::DynBetweenness(const Graph& G, bool storePredecessors) : Centrality(G, normalized),
maxDistance(G.upperNodeIdBound()),
npaths(G.upperNodeIdBound(), std::vector<count>(G.upperNodeIdBound())),
distances(G.upperNodeIdBound(), std::vector<edgeweight>(G.upperNodeIdBound())),
dependencies(G.upperNodeIdBound(),std::vector<double>(G.upperNodeIdBound(), 0.0)),
storePreds(storePredecessors) {
}
inline bool logically_equal(double a, double b, double error_factor=1.0)
{
return a==b || std::abs(a-b)<std::abs(std::min(a,b))*std::numeric_limits<double>::epsilon()*error_factor;
}
void DynBetweenness::run() {
count z = G.upperNodeIdBound();
scoreData.clear();
scoreData.resize(z);
npaths.clear();
npaths.resize(z);
distances.clear();
distances.resize(z);
dependencies.clear();
dependencies.resize(z);
if (storePreds) {
predecessors.clear();
predecessors.resize(G.upperNodeIdBound());
G.forNodes([&](node v){
predecessors[v].resize(G.upperNodeIdBound());
});
}
auto computeDependencies = [&](node s) {
// run SSSP algorithm and keep track of everything
std::unique_ptr<SSSP> sssp;
if (G.isWeighted()) {
sssp.reset(new Dijkstra(G, s, true, true));
} else {
sssp.reset(new BFS(G, s, true, true));
}
sssp->run();
G.forNodes([&](node t){
distances[s][t] = sssp->distance(t);
npaths[s][t] = sssp->numberOfPaths(t);
if (storePreds) {
predecessors[s][t] = sssp->getPredecessors(t);
}
});
// compute dependencies for nodes in order of decreasing distance from s
std::stack<node> stack = sssp->getStack();
// set maxDistance to the distance of the furthest vertex
maxDistance[s] = distances[s][stack.top()];
while (!stack.empty()) {
node t = stack.top();
stack.pop();
for (node p : sssp->getPredecessors(t)) {
dependencies[s][p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dependencies[s][t]);
}
if (t != s) {
scoreData[t] += dependencies[s][t];
}
}
};
G.forNodes(computeDependencies);
}
void DynBetweenness::updateUnweighted(GraphEvent e) {
G.forNodes([&] (node s){
node u_l, u_h;
if (distances[s][e.u] > distances[s][e.v]){
u_l = e.u;
u_h = e.v;
} else {
u_l = e.v;
u_h = e.u;
}
edgeweight difference = distances[s][u_l] - distances[s][u_h];
if (difference > 0) {
std::vector<count> new_npaths(G.upperNodeIdBound());
std::vector<edgeweight> new_dist(G.upperNodeIdBound());
G.forNodes([&] (node v){
new_npaths[v] = npaths[s][v];
new_dist[v] = distances[s][v];
});
std::vector<double> new_dep(G.upperNodeIdBound(), 0.0);
std::vector<int> touched(G.upperNodeIdBound(), 0);
std::vector<std::queue<node>> l_queues(maxDistance[s]+1);
std::queue<node> queue_BFS;
queue_BFS.push(u_l);
// one-level update
if (difference == 1) {
l_queues[distances[s][u_l]].push(u_l);
if (storePreds)
predecessors[s][u_l].push_back(u_h);
new_npaths[u_l] += npaths[s][u_h];
touched[u_l] = -1;
// BFS traversal from u_l
while (!queue_BFS.empty()) {
node v = queue_BFS.front();
DEBUG("extracted node ", v);
queue_BFS.pop();
G.forNeighborsOf(v, [&](node w) {
if (new_dist[w] == new_dist[v]+1) {
if (touched[w] == 0) {
touched[w] = -1;
queue_BFS.push(w);
l_queues[new_dist[w]].push(w);
}
new_npaths[w] = new_npaths[w] - npaths[s][v] + new_npaths[v];
}
});
}
} else if (difference > 1) {
new_dist[u_l] = distances[s][u_h] + 1;
l_queues[new_dist[u_l]].push(u_l);
// BFS traversal from u_l
while (!queue_BFS.empty()) {
node v = queue_BFS.front();
DEBUG("extracted node ",v);
if (storePreds) {
predecessors[s][v].clear();
}
queue_BFS.pop();
touched[v] = -1;
new_npaths[v] = 0;
G.forNeighborsOf(v, [&] (node w){
if (new_dist[w] + 1 == new_dist[v]) {
new_npaths[v] += new_npaths[w];
if (storePreds) {
predecessors[s][v].push_back(w);
}
}
if (new_dist[w] >= new_dist[v] && touched[w] == 0) {
if (new_dist[w] > new_dist[v])
new_dist[w] = new_dist[v]+1;
touched[w] = -1;
l_queues[new_dist[w]].push(w);
queue_BFS.push(w);
}
});
}
}
// dependencies accumulation
DEBUG("Dependency accumulation");
count level = maxDistance[s];
while(level > 0) {
while(!l_queues[level].empty()) {
node w = l_queues[level].front();
DEBUG("Node ",w);
l_queues[level].pop();
auto updateDependency = [&](node w, node v) {
if (new_dist[v] < new_dist[w]) {
if (touched[v] == 0) {
touched[v] = 1;
new_dep[v] = dependencies[s][v];
l_queues[level-1].push(v);
}
double new_contrib = double(new_npaths[v])/new_npaths[w]*(1+new_dep[w]);
new_dep[v] += new_contrib;
double old_contrib = double(npaths[s][v])/npaths[s][w]*(1+dependencies[s][w]);
if (touched[v] == 1 && (v != u_h or w!= u_l))
new_dep[v] -= old_contrib;
DEBUG("Parent ", v);
}
};
if (storePreds) {
for (node v : predecessors[s][w]) {
updateDependency(w, v);
}
}
else {
G.forNeighborsOf(w, [&](node v){
updateDependency(w, v);
});
}
if (w != s) {
scoreData[w] = scoreData[w] + new_dep[w] - dependencies[s][w];
}
}
level = level - 1;
}
// data structures update
G.forNodes([&] (node r){
distances[s][r] = new_dist[r];
npaths[s][r] = new_npaths[r];
if (touched[r] != 0)
dependencies[s][r] = new_dep[r];
});
}
/*
BFS sssp(G, s, true, true);
sssp.run();
G.forNodes([&](node t){
if(distances[s][t] != sssp.distance(t) || npaths[s][t] != sssp.numberOfPaths(t)) {
std::cout<<"Source: "<<s<<" Node "<<t<<std::endl;
std::cout<<"COMPUTED DISTANCE: "<<distances[s][t]<<" REAL DISTANCE: "<<sssp.distance(t)<<std::endl;
std::cout<<"COMPUTED NUMBER OF PATHS: "<<npaths[s][t]<<" REAL NUMBER OF PATHS: "<<sssp.numberOfPaths(t)<<std::endl;
}
});
// compute dependencies for nodes in order of decreasing distance from s
std::vector<double> dep(G.upperNodeIdBound());
std::stack<node> stack = sssp.getStack();
while (!stack.empty()) {
node t = stack.top();
stack.pop();
for (node p : sssp.getPredecessors(t)) {
dep[p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dep[t]);
}
}
G.forNodes([&](node t){
if((dependencies[s][t]-dep[t]>0.000001 || dependencies[s][t]-dep[t]<-0.000001) && s!=t) {
std::cout<<"Source: "<<s<<" Node "<<t<<std::endl;
std::cout<<"COMPUTED DEPENDENCY: "<<dependencies[s][t]<<" REAL DEPENDENCY: "<<dep[t]<<std::endl;
}
});
*/
});
}
void DynBetweenness::updateWeighted(GraphEvent e) {
G.forNodes([&] (node s){
scoreData[s] = 0.0;
});
G.forNodes([&] (node s){
// update of distances and number of shortest paths
Aux::PrioQueue<double, node> S(G.upperNodeIdBound());
G.forNodes([&] (node t){
auto updatePaths = [&](node u, node v, edgeweight w) {
if (distances[s][t] == distances[s][u] + w + distances[v][t]){
npaths[s][t] = npaths[s][t] + npaths[s][u] * npaths[v][t];
if (storePreds) {
if (t != v){
DEBUG("Adding predecessors from v to t to predecessors from s to t");
//predecessors[s][t].insert( predecessors[s][t].end(), predecessors[v][t].begin(), predecessors[v][t].end());
for (node pv : predecessors[v][t]) {
bool wasAlreadyPred = false;
for (node ps : predecessors[s][t]) {
if (ps == pv)
wasAlreadyPred = true;
}
if (!wasAlreadyPred)
predecessors[s][t].push_back(pv);
}
DEBUG("Finished adding");
}
else {
DEBUG("Adding u to the predecessors of v");
predecessors[s][t].push_back(u);
DEBUG("Finished adding");
}
}
}
if (distances[s][t] > distances[s][u] + w + distances[v][t]){
distances[s][t] = distances[s][u] + w + distances[v][t];
npaths[s][t] = npaths[s][u] * npaths[v][t];
if (storePreds) {
if (t != v) {
DEBUG("Replacing predecessors from v to t with predecessors from s to t");
predecessors[s][t] = predecessors[v][t];
DEBUG("Finished replacing");
}
else {
DEBUG("Replacing old predecessors of v with u");
predecessors[s][t].clear();
predecessors[s][t].push_back(u);
DEBUG("Finished replacing");
}
}
}
};
if (s != t) {
updatePaths(e.u, e.v, e.w);
updatePaths(e.v, e.u, e.w);
S.insert(-1*distances[s][t], t);
dependencies[s][t] = 0.0;
}
});
// dependency accumulation
while (S.size() != 0) {
// extract the node with the maximum distance
node t = S.extractMin().second;
if (storePreds) {
DEBUG("Computing dependencies");
for (node p : predecessors[s][t]) {
dependencies[s][p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dependencies[s][t]);
}
}
else {
G.forNeighborsOf(t, [&] (node p){
if (logically_equal(distances[s][t], distances[s][p] + G.weight(p, t))) {
dependencies[s][p] += (double(npaths[s][p]) / npaths[s][t]) * (1 + dependencies[s][t]);
}
});
}
if (t != s) {
scoreData[t] += dependencies[s][t];
}
}
});
}
void DynBetweenness::update(GraphEvent e) {
if (G.isWeighted())
updateWeighted(e);
else
updateUnweighted(e);
}
} /* namespace NetworKit */
<|endoftext|> |
<commit_before>#include "sdfloader.hpp"
Scene SDFloader::sdfLoad(std::string const& inputFile)
{
Scene scene;
std::fstream inputfile;
inputfile.open(inputFile);
if(inputfile.is_open())
{
std::string line;
std::string word;
std::map<std::string, std::shared_ptr<Shape>> tempshapesmap;
std::map<std::string, std::shared_ptr<Composite>> tempcompmap;
std::vector<std::shared_ptr<Composite>> composites;
while(std::getline(inputfile, line))
{
std::stringstream stream;
stream << line;
stream >> word;
if(word == "define")
{
stream >> word;
if(word == "material")
{
std::string matname;
Color ka;
Color kd;
Color ks;
float m;
stream >> matname;
stream >> ka.r;
stream >> ka.g;
stream >> ka.b;
stream >> kd.r;
stream >> kd.g;
stream >> kd.b;
stream >> ks.r;
stream >> ks.g;
stream >> ks.b;
stream >> m;
std::shared_ptr<Material> material = std::make_shared<Material>(matname, ka, kd, ks, m);
scene.materials_.insert(std::pair<std::string, std::shared_ptr<Material>>(matname, material));
std::cout << "\nmaterial added to scene " << matname;
}
else if(word == "shape")
{
stream >> word;
if(word == "box")
{
std::string boxname;
glm::vec3 min;
glm::vec3 max;
std::string matname;
stream >> boxname;
stream >> min.x;
stream >> min.y;
stream >> min.z;
stream >> max.x;
stream >> max.y;
stream >> max.z;
stream >> matname;
std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
std::shared_ptr<Shape> box = std::make_shared<Box>(min, max , material, boxname);
tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(boxname, box));
std::cout << "\nbox added to temshapepmap " << boxname;
}
else if (word == "sphere")
{
std::string spherename;
glm::vec3 center;
float r;
std::string matname;
stream >> spherename;
stream >> center.x;
stream >> center.y;
stream >> center.z;
stream >> r;
stream >> matname;
std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
std::shared_ptr<Shape> sphere = std::make_shared<Sphere>(center, r, material, spherename);
tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(spherename, sphere));
std::cout << "\nsphere added to tempshapemap " << spherename;
}
else if (word == "cone")
{
std::string conename;
glm::vec3 center;
float angle;
float height;
std::string matname;
stream >> conename;
stream >> center.x;
stream >> center.y;
stream >> center.z;
stream >> angle;
stream >> height;
stream >> matname;
std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
std::shared_ptr<Shape> cone = std::make_shared<Cone>(center, angle, height, material, conename);
tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(conename, cone));
}
else if (word == "cylinder")
{
}
else if (word == "triangle")
{
}
else if (word == "composite")
{
std::string compname;
std::string shapename;
stream >> compname;
std::vector<std::shared_ptr<Shape>> shapes;
while(!stream.eof())
{
stream >> shapename;
auto shape_ptr = tempshapesmap.find(shapename);
if(shape_ptr != tempshapesmap.end())
{
shapes.push_back(shape_ptr->second);
std::cout << "\nshape added from tempshapemap to tempvector " << shape_ptr->first;
}
auto comp_ptr = tempcompmap.find(shapename);
if(comp_ptr != tempcompmap.end())
{
shapes.push_back(comp_ptr->second);
std::cout << "\ncomp added from tempcompmap to tempvector " << comp_ptr->first;
}
}
std::shared_ptr<Composite> comp = std::make_shared<Composite>(compname, shapes);
tempcompmap.insert(std::pair<std::string, std::shared_ptr<Composite>>(compname, comp));
std::cout << "\ncomp added to tempcompmap " << compname;
}
}
else if (word == "light")
{
std::string lightname;
Color color;
glm::vec3 pos;
stream >> lightname;
if(lightname == "ambient")
{
stream >> color.r;
stream >> color.g;
stream >> color.b;
scene.ambient_ = color;
std::cout << "\nambientlight added to scene: " << lightname;
}
else
{
stream >> pos.x;
stream >> pos.y;
stream >> pos.z;
stream >> color.r;
stream >> color.g;
stream >> color.b;
std::shared_ptr<Light> light = std::make_shared<Light>(lightname, pos, color);
scene.lights_.push_back(light);
std::cout << "\nlight added to scene: " << lightname;
}
}
else if (word == "camera")
{
std::string cameraname;
float fov;
glm::vec3 eye;
glm::vec3 dir;
glm::vec3 up;
stream >> cameraname;
stream >> fov;
stream >> eye.x;
stream >> eye.y;
stream >> eye.z;
stream >> dir.x;
stream >> dir.y;
stream >> dir.z;
stream >> up.x;
stream >> up.y;
stream >> up.z;
scene.camera_ = Camera{cameraname, fov, eye, dir, up};
std::cout << "\ncamera added to scene: " << cameraname;
}
}
}
for(auto it = tempcompmap.cbegin(); it != tempcompmap.cend(); ++it)
{
composites.push_back(it->second);
std::cout << "\ncomp pushed from tempcompmap in compvector: " << it->first;
}
scene.shapes_ = composites;
std::cout << "\ncompvector added to scene";
}
else
{
std::cout << "File not found." << std::endl;
}
return scene;
}<commit_msg>sdfloader cylinder added<commit_after>#include "sdfloader.hpp"
Scene SDFloader::sdfLoad(std::string const& inputFile)
{
Scene scene;
std::fstream inputfile;
inputfile.open(inputFile);
if(inputfile.is_open())
{
std::string line;
std::string word;
std::map<std::string, std::shared_ptr<Shape>> tempshapesmap;
std::map<std::string, std::shared_ptr<Composite>> tempcompmap;
std::vector<std::shared_ptr<Composite>> composites;
while(std::getline(inputfile, line))
{
std::stringstream stream;
stream << line;
stream >> word;
if(word == "define")
{
stream >> word;
if(word == "material")
{
std::string matname;
Color ka;
Color kd;
Color ks;
float m;
stream >> matname;
stream >> ka.r;
stream >> ka.g;
stream >> ka.b;
stream >> kd.r;
stream >> kd.g;
stream >> kd.b;
stream >> ks.r;
stream >> ks.g;
stream >> ks.b;
stream >> m;
std::shared_ptr<Material> material = std::make_shared<Material>(matname, ka, kd, ks, m);
scene.materials_.insert(std::pair<std::string, std::shared_ptr<Material>>(matname, material));
std::cout << "\nmaterial added to scene " << matname;
}
else if(word == "shape")
{
stream >> word;
if(word == "box")
{
std::string boxname;
glm::vec3 min;
glm::vec3 max;
std::string matname;
stream >> boxname;
stream >> min.x;
stream >> min.y;
stream >> min.z;
stream >> max.x;
stream >> max.y;
stream >> max.z;
stream >> matname;
std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
std::shared_ptr<Shape> box = std::make_shared<Box>(min, max , material, boxname);
tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(boxname, box));
std::cout << "\nbox added to temshapepmap " << boxname;
}
else if (word == "sphere")
{
std::string spherename;
glm::vec3 center;
float r;
std::string matname;
stream >> spherename;
stream >> center.x;
stream >> center.y;
stream >> center.z;
stream >> r;
stream >> matname;
std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
std::shared_ptr<Shape> sphere = std::make_shared<Sphere>(center, r, material, spherename);
tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(spherename, sphere));
std::cout << "\nsphere added to tempshapemap " << spherename;
}
else if (word == "cone")
{
std::string conename;
glm::vec3 center;
float angle;
float height;
std::string matname;
stream >> conename;
stream >> center.x;
stream >> center.y;
stream >> center.z;
stream >> angle;
stream >> height;
stream >> matname;
std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
std::shared_ptr<Shape> cone = std::make_shared<Cone>(center, angle, height, material, conename);
tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(conename, cone));
}
else if (word == "cylinder")
{
std::string cylname;
glm::vec3 center;
float r;
float height;
std::string matname;
stream >> cylname;
stream >> center.x;
stream >> center.y;
stream >> center.z;
stream >> r;
stream >> height;
stream >> matname;
std::shared_ptr<Material> material = (scene.materials_.find(matname)->second);
std::shared_ptr<Shape> cyl = std::make_shared<Cylinder>(center, r, height, material, cylname);
tempshapesmap.insert(std::pair<std::string, std::shared_ptr<Shape>>(cylname, cyl));
}
else if (word == "triangle")
{
}
else if (word == "composite")
{
std::string compname;
std::string shapename;
stream >> compname;
std::vector<std::shared_ptr<Shape>> shapes;
while(!stream.eof())
{
stream >> shapename;
auto shape_ptr = tempshapesmap.find(shapename);
if(shape_ptr != tempshapesmap.end())
{
shapes.push_back(shape_ptr->second);
std::cout << "\nshape added from tempshapemap to tempvector " << shape_ptr->first;
}
auto comp_ptr = tempcompmap.find(shapename);
if(comp_ptr != tempcompmap.end())
{
shapes.push_back(comp_ptr->second);
std::cout << "\ncomp added from tempcompmap to tempvector " << comp_ptr->first;
}
}
std::shared_ptr<Composite> comp = std::make_shared<Composite>(compname, shapes);
tempcompmap.insert(std::pair<std::string, std::shared_ptr<Composite>>(compname, comp));
std::cout << "\ncomp added to tempcompmap " << compname;
}
}
else if (word == "light")
{
std::string lightname;
Color color;
glm::vec3 pos;
stream >> lightname;
if(lightname == "ambient")
{
stream >> color.r;
stream >> color.g;
stream >> color.b;
scene.ambient_ = color;
std::cout << "\nambientlight added to scene: " << lightname;
}
else
{
stream >> pos.x;
stream >> pos.y;
stream >> pos.z;
stream >> color.r;
stream >> color.g;
stream >> color.b;
std::shared_ptr<Light> light = std::make_shared<Light>(lightname, pos, color);
scene.lights_.push_back(light);
std::cout << "\nlight added to scene: " << lightname;
}
}
else if (word == "camera")
{
std::string cameraname;
float fov;
glm::vec3 eye;
glm::vec3 dir;
glm::vec3 up;
stream >> cameraname;
stream >> fov;
stream >> eye.x;
stream >> eye.y;
stream >> eye.z;
stream >> dir.x;
stream >> dir.y;
stream >> dir.z;
stream >> up.x;
stream >> up.y;
stream >> up.z;
scene.camera_ = Camera{cameraname, fov, eye, dir, up};
std::cout << "\ncamera added to scene: " << cameraname;
}
}
}
for(auto it = tempcompmap.cbegin(); it != tempcompmap.cend(); ++it)
{
composites.push_back(it->second);
std::cout << "\ncomp pushed from tempcompmap in compvector: " << it->first;
}
scene.shapes_ = composites;
std::cout << "\ncompvector added to scene";
}
else
{
std::cout << "File not found." << std::endl;
}
return scene;
}<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "VTestPlugin.h"
#include "StencilShadowTest.h"
#include "ParticleTest.h"
#include "TransparencyTest.h"
#include "TextureEffectsTest.h"
#include "CubeMappingTest.h"
#include "OgreResourceGroupManager.h"
VTestPlugin::VTestPlugin()
:SamplePlugin("VTestPlugin")
{
// add the playpen tests
addSample(new CubeMappingTest()); // no bg on Win
addSample(new ParticleTest());
addSample(new StencilShadowTest()); // should show ogre head, barrel, taurus
addSample(new TextureEffectsTest());
addSample(new TransparencyTest());
}
//---------------------------------------------------------------------
VTestPlugin::~VTestPlugin()
{
for (OgreBites::SampleSet::iterator i = mSamples.begin(); i != mSamples.end(); ++i)
{
delete *i;
}
mSamples.clear();
}
//---------------------------------------------------------------------
#ifndef OGRE_STATIC_LIB
VTestPlugin* testPlugin = 0;
extern "C" _OgreSampleExport void dllStartPlugin()
{
testPlugin = OGRE_NEW VTestPlugin();
Ogre::Root::getSingleton().installPlugin(testPlugin);
}
extern "C" _OgreSampleExport void dllStopPlugin()
{
Ogre::Root::getSingleton().uninstallPlugin(testPlugin);
OGRE_DELETE testPlugin;
}
#endif
<commit_msg>[vtests] Disable a stencil shadow test that crashes on Windows<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "VTestPlugin.h"
#include "StencilShadowTest.h"
#include "ParticleTest.h"
#include "TransparencyTest.h"
#include "TextureEffectsTest.h"
#include "CubeMappingTest.h"
#include "OgreResourceGroupManager.h"
VTestPlugin::VTestPlugin()
:SamplePlugin("VTestPlugin")
{
// add the playpen tests
addSample(new CubeMappingTest()); // no bg on Win
addSample(new ParticleTest());
// addSample(new StencilShadowTest()); // crashes on Windows; should show ogre head, barrel, taurus
addSample(new TextureEffectsTest());
addSample(new TransparencyTest());
}
//---------------------------------------------------------------------
VTestPlugin::~VTestPlugin()
{
for (OgreBites::SampleSet::iterator i = mSamples.begin(); i != mSamples.end(); ++i)
{
delete *i;
}
mSamples.clear();
}
//---------------------------------------------------------------------
#ifndef OGRE_STATIC_LIB
VTestPlugin* testPlugin = 0;
extern "C" _OgreSampleExport void dllStartPlugin()
{
testPlugin = OGRE_NEW VTestPlugin();
Ogre::Root::getSingleton().installPlugin(testPlugin);
}
extern "C" _OgreSampleExport void dllStopPlugin()
{
Ogre::Root::getSingleton().uninstallPlugin(testPlugin);
OGRE_DELETE testPlugin;
}
#endif
<|endoftext|> |
<commit_before>//
// board.cpp
// game_of_life
//
// Created by Chris Powell on 8/24/13.
// Copyright (c) 2013 Prylis Inc. All rights reserved.
//
#include "board.h"
int Board::getCell(const int x, const int y) const {
return _cells[x][y];
}
int Board::getLiveNeighborCountForCell(const int x, const int y) const {
int above = y-1;
if (above < 0)
above = BOARD_HEIGHT;
int below = y+1;
if (below >= BOARD_HEIGHT)
below = 0;
int left = x-1;
if (left < 0)
left = BOARD_WIDTH;
int right = x+1;
if (right >= BOARD_WIDTH) {
right = 0;
}
int live = 0;
for (int xx=left; xx<=right; ++xx) {
for (int yy=above; yy<=below; ++yy) {
if (xx==x && yy==y)
continue;
live += _cells[xx][yy];
}
}
return live;
}
int Board::evolveCell(const int curState, const int numLiveNeigbors) const {
//TODO bounds checking
// int state = _cells[x][y];
// int numNeighbors = getLiveNeighborCountForCell(x, y);
if (curState==ALIVE) {
if (numLiveNeigbors < 2 || numLiveNeigbors > 3)
return DEAD;
} else {
if (numLiveNeigbors == 3)
return ALIVE;
}
return curState;
}
void Board::evolve(const Board &previousBoard) {
for (int x=0; x<BOARD_WIDTH; ++x) {
for (int y=0; y<BOARD_HEIGHT; ++y) {
_cells[x][y] = evolveCell(previousBoard.getCell(x, y), previousBoard.getLiveNeighborCountForCell(x, y));
}
}
}
void Board::randomize(const int ratio) {
for (int y=0; y<BOARD_HEIGHT; ++y) {
for (int x=0; x<BOARD_WIDTH; ++x) {
if (rand() % 100 < ratio)
_cells[x][y]=1;
}
std::cout << std::endl;
}
}
void Board::print() {
for (int y=0; y<BOARD_HEIGHT; ++y) {
for (int x=0; x<BOARD_WIDTH; ++x) {
std::cout << _cells[x][y];
}
std::cout << std::endl;
}
std::cout << std::endl;
}<commit_msg>Nicer output makes it easier to see the shapes.<commit_after>//
// board.cpp
// game_of_life
//
// Created by Chris Powell on 8/24/13.
// Copyright (c) 2013 Prylis Inc. All rights reserved.
//
#include "board.h"
int Board::getCell(const int x, const int y) const {
return _cells[x][y];
}
int Board::getLiveNeighborCountForCell(const int x, const int y) const {
int above = y-1;
if (above < 0)
above = BOARD_HEIGHT;
int below = y+1;
if (below >= BOARD_HEIGHT)
below = 0;
int left = x-1;
if (left < 0)
left = BOARD_WIDTH;
int right = x+1;
if (right >= BOARD_WIDTH) {
right = 0;
}
int live = 0;
for (int xx=left; xx<=right; ++xx) {
for (int yy=above; yy<=below; ++yy) {
if (xx==x && yy==y)
continue;
live += _cells[xx][yy];
}
}
return live;
}
int Board::evolveCell(const int curState, const int numLiveNeigbors) const {
//TODO bounds checking
// int state = _cells[x][y];
// int numNeighbors = getLiveNeighborCountForCell(x, y);
if (curState==ALIVE) {
if (numLiveNeigbors < 2 || numLiveNeigbors > 3)
return DEAD;
} else {
if (numLiveNeigbors == 3)
return ALIVE;
}
return curState;
}
void Board::evolve(const Board &previousBoard) {
for (int x=0; x<BOARD_WIDTH; ++x) {
for (int y=0; y<BOARD_HEIGHT; ++y) {
_cells[x][y] = evolveCell(previousBoard.getCell(x, y), previousBoard.getLiveNeighborCountForCell(x, y));
}
}
}
void Board::randomize(const int ratio) {
for (int y=0; y<BOARD_HEIGHT; ++y) {
for (int x=0; x<BOARD_WIDTH; ++x) {
if (rand() % 100 < ratio)
_cells[x][y]=1;
}
std::cout << std::endl;
}
}
void Board::print() {
for (int y=0; y<BOARD_HEIGHT; ++y) {
for (int x=0; x<BOARD_WIDTH; ++x) {
if (_cells[x][y]==1)
std::cout<< "*";
else
std::cout<< " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}<|endoftext|> |
<commit_before>#include <QtCore/QFile>
#include <QtTest/QtTest>
#include <QMimeDatabase>
class tst_QMimeType : public QObject
{
Q_OBJECT
public:
tst_QMimeType();
~tst_QMimeType();
private Q_SLOTS:
void initTestCase();
void findByName_data();
void findByName();
void findByData_data();
void findByData();
void findByFile_data();
void findByFile();
private:
QMimeDatabase database;
};
tst_QMimeType::tst_QMimeType() :
database()
{
}
tst_QMimeType::~tst_QMimeType()
{
}
void tst_QMimeType::initTestCase()
{
}
void tst_QMimeType::findByName_data()
{
QTest::addColumn<QString>("filePath");
QTest::addColumn<QString>("mimeType");
QTest::addColumn<QString>("xFail");
QString prefix = QLatin1String(SRCDIR "testfiles/");
QFile f(prefix + QLatin1String("list"));
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray line(1024, Qt::Uninitialized);
while (!f.atEnd()) {
int len = f.readLine(line.data(), 1023);
if (len <= 2 || line.at(0) == '#')
continue;
QString string = QString::fromLatin1(line.constData(), len - 1).trimmed();
QStringList list = string.split(QLatin1Char(' '), QString::SkipEmptyParts);
QVERIFY(list.size() >= 2);
QString filePath = list.at(0);
QString mimeType = list.at(1);
QString xFail;
if (list.size() == 3)
xFail = list.at(2);
QTest::newRow(filePath.toLatin1().constData()) << prefix + filePath << mimeType << xFail;
}
}
void tst_QMimeType::findByName()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
const QString resultMimeTypeName = database.findByName(filePath).name();
// Results are ambiguous when multiple MIME types have the same glob
// -> accept the current result if the found MIME type actually
// matches the file's extension.
const QMimeType foundMimeType = database.mimeTypeForName(resultMimeTypeName);
const QString extension = QFileInfo(filePath).suffix();
//qDebug() << foundMimeType.globPatterns() << "extension=*." << extension;
if (foundMimeType.globPatterns().contains("*." + extension))
return;
const bool shouldFail = (xFail.length() >= 1 && xFail.at(0) == QLatin1Char('x'));
if (shouldFail) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
} else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
void tst_QMimeType::findByData_data()
{
findByName_data();
}
void tst_QMimeType::findByData()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
QFile f(filePath);
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray data = f.readAll();
const QString resultMimeTypeName = database.findByData(data).name();
if (xFail.length() >= 2 && xFail.at(1) == QLatin1Char('x'))
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
else
QCOMPARE(resultMimeTypeName, mimeType);
}
void tst_QMimeType::findByFile_data()
{
findByName_data();
}
void tst_QMimeType::findByFile()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
const QString resultMimeTypeName = database.findByFile(QFileInfo(filePath)).name();
if (xFail.length() >= 3 && xFail.at(2) == QLatin1Char('x'))
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
else
QCOMPARE(resultMimeTypeName, mimeType);
}
QTEST_APPLESS_MAIN(tst_QMimeType)
#include "tst_qmimedatabase.moc"
<commit_msg>Updated the debug output.<commit_after>#include <QtCore/QFile>
#include <QtTest/QtTest>
#include <QMimeDatabase>
class tst_QMimeType : public QObject
{
Q_OBJECT
public:
tst_QMimeType();
~tst_QMimeType();
private Q_SLOTS:
void initTestCase();
void findByName_data();
void findByName();
void findByData_data();
void findByData();
void findByFile_data();
void findByFile();
private:
QMimeDatabase database;
};
tst_QMimeType::tst_QMimeType() :
database()
{
}
tst_QMimeType::~tst_QMimeType()
{
}
void tst_QMimeType::initTestCase()
{
}
void tst_QMimeType::findByName_data()
{
QTest::addColumn<QString>("filePath");
QTest::addColumn<QString>("mimeType");
QTest::addColumn<QString>("xFail");
QString prefix = QLatin1String(SRCDIR "testfiles/");
QFile f(prefix + QLatin1String("list"));
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray line(1024, Qt::Uninitialized);
while (!f.atEnd()) {
int len = f.readLine(line.data(), 1023);
if (len <= 2 || line.at(0) == '#')
continue;
QString string = QString::fromLatin1(line.constData(), len - 1).trimmed();
QStringList list = string.split(QLatin1Char(' '), QString::SkipEmptyParts);
QVERIFY(list.size() >= 2);
QString filePath = list.at(0);
QString mimeType = list.at(1);
QString xFail;
if (list.size() == 3)
xFail = list.at(2);
QTest::newRow(filePath.toLatin1().constData()) << prefix + filePath << mimeType << xFail;
}
}
void tst_QMimeType::findByName()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
//qDebug() << Q_FUNC_INFO << filePath;
const QString resultMimeTypeName = database.findByName(filePath).name();
//qDebug() << Q_FUNC_INFO << "findByName() returned" << resultMimeTypeName;
// Results are ambiguous when multiple MIME types have the same glob
// -> accept the current result if the found MIME type actually
// matches the file's extension.
const QMimeType foundMimeType = database.mimeTypeForName(resultMimeTypeName);
const QString extension = QFileInfo(filePath).suffix();
//qDebug() << Q_FUNC_INFO << "globPatterns:" << foundMimeType.globPatterns() << "- extension:" << QString() + "*." + extension;
if (foundMimeType.globPatterns().contains("*." + extension))
return;
const bool shouldFail = (xFail.length() >= 1 && xFail.at(0) == QLatin1Char('x'));
if (shouldFail) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
} else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
void tst_QMimeType::findByData_data()
{
findByName_data();
}
void tst_QMimeType::findByData()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
QFile f(filePath);
QVERIFY(f.open(QIODevice::ReadOnly));
QByteArray data = f.readAll();
const QString resultMimeTypeName = database.findByData(data).name();
if (xFail.length() >= 2 && xFail.at(1) == QLatin1Char('x')) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
}
else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
void tst_QMimeType::findByFile_data()
{
findByName_data();
}
void tst_QMimeType::findByFile()
{
QFETCH(QString, filePath);
QFETCH(QString, mimeType);
QFETCH(QString, xFail);
const QString resultMimeTypeName = database.findByFile(QFileInfo(filePath)).name();
//qDebug() << Q_FUNC_INFO << filePath << "->" << resultMimeTypeName;
if (xFail.length() >= 3 && xFail.at(2) == QLatin1Char('x')) {
// Expected to fail
QVERIFY2(resultMimeTypeName != mimeType, qPrintable(resultMimeTypeName));
}
else {
QCOMPARE(resultMimeTypeName, mimeType);
}
}
QTEST_APPLESS_MAIN(tst_QMimeType)
#include "tst_qmimedatabase.moc"
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/nccl/nccl_gpu_common.h"
#include "paddle/fluid/platform/gpu_info.h"
namespace paddle {
namespace platform {
namespace {
// TODO(panyx0718): Where to destroy them.
std::unique_ptr<std::vector<ncclComm_t>> global_comms;
std::unique_ptr<std::unordered_map<int, int>> comm_id_map;
bool inited = false;
size_t last_num_gpus = -1;
}
int Communicator::GetCommId(int device_id) const {
return comm_id_map->at(device_id);
}
void Communicator::InitAll(const std::vector<int>& gpus) {
if (inited && last_num_gpus == gpus.size()) {
return;
}
last_num_gpus = gpus.size();
if (global_comms) {
for (size_t i = 0; i < global_comms->size(); ++i) {
// FIXME(dzh) : PADDLE_ENFORCE return void
dynload::ncclCommDestroy((*global_comms)[i]);
}
}
global_comms.reset(new std::vector<ncclComm_t>());
comm_id_map.reset(new std::unordered_map<int, int>());
global_comms->resize(gpus.size());
for (size_t i = 0; i < gpus.size(); ++i) {
(*comm_id_map)[gpus[i]] = i;
}
PADDLE_ENFORCE(
dynload::ncclCommInitAll(global_comms->data(), gpus.size(), gpus.data()));
inited = true;
}
const std::vector<ncclComm_t>& Communicator::comms() const {
return *global_comms;
}
} // namespace platform
} // namespace paddle
<commit_msg>Add lock<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/nccl/nccl_gpu_common.h"
#include "paddle/fluid/platform/gpu_info.h"
namespace paddle {
namespace platform {
namespace {
// TODO(panyx0718): Where to destroy them.
std::unique_ptr<std::vector<ncclComm_t>> global_comms;
std::unique_ptr<std::unordered_map<int, int>> comm_id_map;
bool inited = false;
size_t last_num_gpus = -1;
// TODO(panyx0718): Need to decide whether Paddle supports parallel
// runs with different number GPUs. If true, current solution is not enough.
std::mutex comm_mu;
}
int Communicator::GetCommId(int device_id) const {
std::lock_guard<std::mutex> guard(comm_mu);
return comm_id_map->at(device_id);
}
void Communicator::InitAll(const std::vector<int>& gpus) {
std::lock_guard<std::mutex> guard(comm_mu);
if (inited && last_num_gpus == gpus.size()) {
return;
}
last_num_gpus = gpus.size();
if (global_comms) {
for (size_t i = 0; i < global_comms->size(); ++i) {
// FIXME(dzh) : PADDLE_ENFORCE return void
dynload::ncclCommDestroy((*global_comms)[i]);
}
}
global_comms.reset(new std::vector<ncclComm_t>());
comm_id_map.reset(new std::unordered_map<int, int>());
global_comms->resize(gpus.size());
for (size_t i = 0; i < gpus.size(); ++i) {
(*comm_id_map)[gpus[i]] = i;
}
PADDLE_ENFORCE(
dynload::ncclCommInitAll(global_comms->data(), gpus.size(), gpus.data()));
inited = true;
}
const std::vector<ncclComm_t>& Communicator::comms() const {
std::lock_guard<std::mutex> guard(comm_mu);
return *global_comms;
}
} // namespace platform
} // namespace paddle
<|endoftext|> |
<commit_before>/*
* File: render.cpp
* Author: ivan
*
* Created on October 12, 2015, 11:04 PM
*/
#include "render.hpp"
#include <cmath>
#include <cairo/cairo.h>
#include <utki/util.hpp>
using namespace svgren;
namespace{
class CairoMatrixPush{
cairo_matrix_t m;
cairo_t* cr;
public:
CairoMatrixPush(cairo_t* cr) :
cr(cr)
{
ASSERT(this->cr)
cairo_get_matrix(this->cr, &this->m);
}
~CairoMatrixPush()noexcept{
cairo_set_matrix(this->cr, &this->m);
}
};
class Renderer : public svgdom::Renderer{
cairo_t* cr;
void applyTransformations(const svgdom::Transformable& transformable)const{
for(auto& t : transformable.transformations){
switch(t.type){
case svgdom::Transformation::EType::TRANSLATE:
cairo_translate(this->cr, t.x, t.y);
break;
case svgdom::Transformation::EType::MATRIX:
{
cairo_matrix_t matrix;
matrix.xx = t.a;
matrix.yx = t.b;
matrix.xy = t.c;
matrix.yy = t.d;
matrix.x0 = t.e;
matrix.y0 = t.f;
cairo_transform(this->cr, &matrix);
}
break;
case svgdom::Transformation::EType::SCALE:
cairo_scale(this->cr, t.x, t.y);
break;
case svgdom::Transformation::EType::ROTATE:
cairo_translate(this->cr, t.x, t.y);
cairo_rotate(this->cr, t.angle);
cairo_translate(this->cr, -t.x, -t.y);
break;
case svgdom::Transformation::EType::SKEWX:
{
cairo_matrix_t matrix;
matrix.xx = 1;
matrix.yx = 0;
matrix.xy = std::tan(t.angle);
matrix.yy = 1;
matrix.x0 = 0;
matrix.y0 = 0;
cairo_transform(this->cr, &matrix);
}
break;
case svgdom::Transformation::EType::SKEWY:
{
cairo_matrix_t matrix;
matrix.xx = 1;
matrix.yx = std::tan(t.angle);
matrix.xy = 0;
matrix.yy = 1;
matrix.x0 = 0;
matrix.y0 = 0;
cairo_transform(this->cr, &matrix);
}
break;
default:
ASSERT(false)
break;
}
}
}
public:
Renderer(cairo_t* cr) :
cr(cr)
{}
void render(const svgdom::GElement& e)override{
CairoMatrixPush cairoMatrixPush(this->cr);
this->applyTransformations(e);
e.Container::render(*this);
}
void render(const svgdom::SvgElement& e)override{
e.Container::render(*this);
}
void render(const svgdom::PathElement& e)override{
CairoMatrixPush cairoMatrixPush(this->cr);
this->applyTransformations(e);
cairo_set_source_rgb(cr, 1.0, 0, 0);
// const svgdom::PathElement::Step* prev = nullptr;
for(auto& s : e.path){
switch(s.type){
case svgdom::PathElement::Step::EType::MOVE_ABS:
cairo_move_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::MOVE_REL:
cairo_rel_move_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::LINE_ABS:
cairo_line_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::LINE_REL:
cairo_rel_line_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_ABS:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
y = 0;
}
cairo_line_to(this->cr, s.x, y);
}
break;
case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_REL:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
y = 0;
}
cairo_rel_line_to(this->cr, s.x, y);
}
break;
case svgdom::PathElement::Step::EType::VERTICAL_LINE_ABS:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
x = 0;
}
cairo_line_to(this->cr, x, s.y);
}
break;
case svgdom::PathElement::Step::EType::VERTICAL_LINE_REL:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
x = 0;
}
cairo_rel_line_to(this->cr, x, s.y);
}
break;
case svgdom::PathElement::Step::EType::CLOSE:
cairo_close_path(this->cr);
break;
case svgdom::PathElement::Step::EType::CUBIC_ABS:
cairo_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::CUBIC_REL:
cairo_rel_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
break;
// case svgdom::PathElement::Step::EType::CUBIC_SMOOTH_ABS:
// {
// double x, y;
// if(cairo_has_current_point(this->cr)){
// cairo_get_current_point(this->cr, &x, &y);
// }else{
// x = 0;
// y = 0;
// }
// double x1, y1;
// if(prev){
// x1 = -(prev->x2 - x) + x;
// y1 = -(prev->y2 - y) + y;
// }else{
// x1 = x;
// y1 = y;
// }
// cairo_curve_to(this->cr, x1, y1, s.x2, s.y2, s.x, s.y);
// }
// break;
default:
ASSERT(false)
break;
}
// prev = &s;
}
cairo_set_line_width (cr, 1);
cairo_stroke (cr);
}
};
}
std::vector<std::uint32_t> svgren::render(const svgdom::SvgElement& svg, unsigned width, unsigned height){
// int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
int stride = width * 4;
TRACE(<< "width = " << width << " stride = " << stride / 4 << std::endl)
std::vector<std::uint32_t> ret((stride / sizeof(std::uint32_t)) * height);
cairo_surface_t* surface = cairo_image_surface_create_for_data(
reinterpret_cast<unsigned char*>(&*ret.begin()),
CAIRO_FORMAT_ARGB32,
width,
height,
stride
);
if(!surface){
ret.clear();
return ret;
}
utki::ScopeExit scopeExitSurface([&surface](){
cairo_surface_destroy(surface);
});
cairo_t* cr = cairo_create(surface);
if(!cr){
ret.clear();
return ret;
}
utki::ScopeExit scopeExitContext([&cr](){
cairo_destroy(cr);
});
Renderer r(cr);
svg.render(r);
return ret;
}
<commit_msg>stuff<commit_after>/*
* File: render.cpp
* Author: ivan
*
* Created on October 12, 2015, 11:04 PM
*/
#include "render.hpp"
#include <cmath>
#include <cairo/cairo.h>
#include <utki/util.hpp>
using namespace svgren;
namespace{
class CairoMatrixPush{
cairo_matrix_t m;
cairo_t* cr;
public:
CairoMatrixPush(cairo_t* cr) :
cr(cr)
{
ASSERT(this->cr)
cairo_get_matrix(this->cr, &this->m);
}
~CairoMatrixPush()noexcept{
cairo_set_matrix(this->cr, &this->m);
}
};
class Renderer : public svgdom::Renderer{
cairo_t* cr;
void applyTransformations(const svgdom::Transformable& transformable)const{
for(auto& t : transformable.transformations){
switch(t.type){
case svgdom::Transformation::EType::TRANSLATE:
cairo_translate(this->cr, t.x, t.y);
break;
case svgdom::Transformation::EType::MATRIX:
{
cairo_matrix_t matrix;
matrix.xx = t.a;
matrix.yx = t.b;
matrix.xy = t.c;
matrix.yy = t.d;
matrix.x0 = t.e;
matrix.y0 = t.f;
cairo_transform(this->cr, &matrix);
}
break;
case svgdom::Transformation::EType::SCALE:
cairo_scale(this->cr, t.x, t.y);
break;
case svgdom::Transformation::EType::ROTATE:
cairo_translate(this->cr, t.x, t.y);
cairo_rotate(this->cr, t.angle);
cairo_translate(this->cr, -t.x, -t.y);
break;
case svgdom::Transformation::EType::SKEWX:
{
cairo_matrix_t matrix;
matrix.xx = 1;
matrix.yx = 0;
matrix.xy = std::tan(t.angle);
matrix.yy = 1;
matrix.x0 = 0;
matrix.y0 = 0;
cairo_transform(this->cr, &matrix);
}
break;
case svgdom::Transformation::EType::SKEWY:
{
cairo_matrix_t matrix;
matrix.xx = 1;
matrix.yx = std::tan(t.angle);
matrix.xy = 0;
matrix.yy = 1;
matrix.x0 = 0;
matrix.y0 = 0;
cairo_transform(this->cr, &matrix);
}
break;
default:
ASSERT(false)
break;
}
}
}
public:
Renderer(cairo_t* cr) :
cr(cr)
{}
void render(const svgdom::GElement& e)override{
CairoMatrixPush cairoMatrixPush(this->cr);
this->applyTransformations(e);
e.Container::render(*this);
}
void render(const svgdom::SvgElement& e)override{
e.Container::render(*this);
}
void render(const svgdom::PathElement& e)override{
CairoMatrixPush cairoMatrixPush(this->cr);
this->applyTransformations(e);
// const svgdom::PathElement::Step* prev = nullptr;
for(auto& s : e.path){
switch(s.type){
case svgdom::PathElement::Step::EType::MOVE_ABS:
cairo_move_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::MOVE_REL:
cairo_rel_move_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::LINE_ABS:
cairo_line_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::LINE_REL:
cairo_rel_line_to(this->cr, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_ABS:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
y = 0;
}
cairo_line_to(this->cr, s.x, y);
}
break;
case svgdom::PathElement::Step::EType::HORIZONTAL_LINE_REL:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
y = 0;
}
cairo_rel_line_to(this->cr, s.x, y);
}
break;
case svgdom::PathElement::Step::EType::VERTICAL_LINE_ABS:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
x = 0;
}
cairo_line_to(this->cr, x, s.y);
}
break;
case svgdom::PathElement::Step::EType::VERTICAL_LINE_REL:
{
double x, y;
if(cairo_has_current_point(this->cr)){
cairo_get_current_point(this->cr, &x, &y);
}else{
x = 0;
}
cairo_rel_line_to(this->cr, x, s.y);
}
break;
case svgdom::PathElement::Step::EType::CLOSE:
cairo_close_path(this->cr);
break;
case svgdom::PathElement::Step::EType::CUBIC_ABS:
cairo_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
break;
case svgdom::PathElement::Step::EType::CUBIC_REL:
cairo_rel_curve_to(this->cr, s.x1, s.y1, s.x2, s.y2, s.x, s.y);
break;
// case svgdom::PathElement::Step::EType::CUBIC_SMOOTH_ABS:
// {
// double x, y;
// if(cairo_has_current_point(this->cr)){
// cairo_get_current_point(this->cr, &x, &y);
// }else{
// x = 0;
// y = 0;
// }
// double x1, y1;
// if(prev){
// x1 = -(prev->x2 - x) + x;
// y1 = -(prev->y2 - y) + y;
// }else{
// x1 = x;
// y1 = y;
// }
// cairo_curve_to(this->cr, x1, y1, s.x2, s.y2, s.x, s.y);
// }
// break;
default:
ASSERT(false)
break;
}
// prev = &s;
}
auto fill = e.getStyleProperty(svgdom::EStyleProperty::FILL);
auto stroke = e.getStyleProperty(svgdom::EStyleProperty::STROKE);
if(fill && fill->effective){
svgdom::real opacity;
if(auto fillOpacity = e.getStyleProperty(svgdom::EStyleProperty::FILL_OPACITY)){
opacity = fillOpacity->floating;
}else{
opacity = 1;
}
auto fillRgb = fill->getRgb();
cairo_set_source_rgba(this->cr, fillRgb.r, fillRgb.g, fillRgb.b, opacity);
if(stroke && stroke->effective){
cairo_fill_preserve(this->cr);
}else{
cairo_fill(this->cr);
}
}
if(stroke && stroke->effective){
if(auto strokeWidth = e.getStyleProperty(svgdom::EStyleProperty::STROKE_WIDTH)){
cairo_set_line_width(cr, strokeWidth->length.value);
}else{
cairo_set_line_width(cr, 1);
}
auto rgb = stroke->getRgb();
cairo_set_source_rgb(this->cr, rgb.r, rgb.g, rgb.b);
cairo_stroke(this->cr);
}
}
};
}
std::vector<std::uint32_t> svgren::render(const svgdom::SvgElement& svg, unsigned width, unsigned height){
// int stride = cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, width);
int stride = width * 4;
TRACE(<< "width = " << width << " stride = " << stride / 4 << std::endl)
std::vector<std::uint32_t> ret((stride / sizeof(std::uint32_t)) * height);
for(auto& c : ret){
c = 0xffffffff;//TODO: fill 0
}
cairo_surface_t* surface = cairo_image_surface_create_for_data(
reinterpret_cast<unsigned char*>(&*ret.begin()),
CAIRO_FORMAT_ARGB32,
width,
height,
stride
);
if(!surface){
ret.clear();
return ret;
}
utki::ScopeExit scopeExitSurface([&surface](){
cairo_surface_destroy(surface);
});
cairo_t* cr = cairo_create(surface);
if(!cr){
ret.clear();
return ret;
}
utki::ScopeExit scopeExitContext([&cr](){
cairo_destroy(cr);
});
Renderer r(cr);
svg.render(r);
return ret;
}
<|endoftext|> |
<commit_before>/*
* Tests for the scalar example solving the test equation
*/
#include <cmath>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace ::testing;
#include <pfasst/quadrature.hpp>
#define PFASST_UNIT_TESTING
#include "../examples/scalar/scalar_sdc.cpp"
#undef PFASST_UNIT_TESTING
/*
* parameterized test that verifies that given sufficiently many nodes and iterations,
* SDC can reproduce the analytic solution with very high precision
*/
class HighPrecisionTest
: public TestWithParam<pfasst::QuadratureType>
{
protected:
pfasst::QuadratureType nodetype; // parameter
complex<double> lambda;
double Tend = 0.5;
size_t nsteps = 1;
size_t niters = 30;
size_t nnodes = 8;
size_t nnodes_in_call;
void set_parameters()
{
switch (this->nodetype)
{
case pfasst::QuadratureType::GaussLobatto:
break;
default:
break;
}
}
public:
virtual void SetUp()
{
this->nodetype = GetParam();
this->set_parameters();
}
virtual void TearDown()
{}
};
TEST_P(HighPrecisionTest, AllNodes)
{
}
INSTANTIATE_TEST_CASE_P(ScalarSDC, HighPrecisionTest,
Values(pfasst::QuadratureType::GaussLobatto,
pfasst::QuadratureType::GaussLegendre,
pfasst::QuadratureType::GaussRadau,
pfasst::QuadratureType::ClenshawCurtis,
pfasst::QuadratureType::Uniform)
);
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>high precision test for scalar now running: tolerance set to 5e-12<commit_after>/*
* Tests for the scalar example solving the test equation
*/
#include <cmath>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
using namespace ::testing;
#include <pfasst/quadrature.hpp>
#define PFASST_UNIT_TESTING
#include "../examples/scalar/scalar_sdc.cpp"
#undef PFASST_UNIT_TESTING
/*
* parameterized test that verifies that given sufficiently many nodes and iterations,
* SDC can reproduce the analytic solution with very high precision
*/
class HighPrecisionTest
: public TestWithParam<pfasst::QuadratureType>
{
protected:
pfasst::QuadratureType nodetype; // parameter
const complex<double> lambda = complex<double>(-1.0,1.0);
const double dt = 0.2; // = Tend for single step
const size_t nsteps = 1;
const size_t niters = 30;
const size_t nnodes = 8;
size_t nnodes_in_call;
double err;
void set_parameters()
{
switch (this->nodetype)
{
case pfasst::QuadratureType::GaussLobatto:
this->nnodes_in_call = this->nnodes;
break;
case pfasst::QuadratureType::GaussLegendre:
this->nnodes_in_call = this->nnodes + 2;
break;
case pfasst::QuadratureType::GaussRadau:
this->nnodes_in_call = this->nnodes + 1;
break;
case pfasst::QuadratureType::ClenshawCurtis:
this->nnodes_in_call = this->nnodes + 1;
break;
case pfasst::QuadratureType::Uniform:
this->nnodes_in_call = this->nnodes + 1;
break;
default:
break;
}
}
public:
virtual void SetUp()
{
this->nodetype = GetParam();
this->set_parameters();
this->err = run_scalar_sdc(this->nsteps, this->dt, this->nnodes_in_call,
this->niters, this->lambda, this->nodetype);
}
virtual void TearDown()
{}
};
TEST_P(HighPrecisionTest, AllNodes)
{
EXPECT_THAT(err, Le<double>(5e-12)) << "Failed to bring relative error below 5e-12";
}
INSTANTIATE_TEST_CASE_P(ScalarSDC, HighPrecisionTest,
Values(pfasst::QuadratureType::GaussLobatto,
pfasst::QuadratureType::GaussLegendre,
pfasst::QuadratureType::GaussRadau,
pfasst::QuadratureType::ClenshawCurtis,
pfasst::QuadratureType::Uniform)
);
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Matias Fontanini
* 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.
*
* 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 "tcp_ip/stream.h"
#ifdef TINS_HAVE_TCPIP
#include <limits>
#include <algorithm>
#include "memory.h"
#include "ip_address.h"
#include "ipv6_address.h"
#include "tcp.h"
#include "ip.h"
#include "ipv6.h"
#include "ethernetII.h"
#include "rawpdu.h"
#include "exceptions.h"
#include "memory_helpers.h"
using std::make_pair;
using std::bind;
using std::pair;
using std::runtime_error;
using std::numeric_limits;
using std::max;
using std::swap;
using Tins::Memory::OutputMemoryStream;
using Tins::Memory::InputMemoryStream;
namespace Tins {
namespace TCPIP {
Stream::Stream(PDU& packet, const timestamp_type& ts)
: client_flow_(extract_client_flow(packet)),
server_flow_(extract_server_flow(packet)), create_time_(ts),
last_seen_(ts), auto_cleanup_client_(true), auto_cleanup_server_(true),
is_partial_stream_(false), directions_recovery_mode_enabled_(0) {
const EthernetII* eth = packet.find_pdu<EthernetII>();
if (eth) {
client_hw_addr_ = eth->src_addr();
server_hw_addr_ = eth->dst_addr();
}
const TCP& tcp = packet.rfind_pdu<TCP>();
// If this is not the first packet of a stream (SYN), then it's a partial stream
is_partial_stream_ = tcp.flags() != TCP::SYN;
}
void Stream::process_packet(PDU& packet, const timestamp_type& ts) {
last_seen_ = ts;
if (client_flow_.packet_belongs(packet)) {
client_flow_.process_packet(packet);
}
else if (server_flow_.packet_belongs(packet)) {
server_flow_.process_packet(packet);
}
if (is_finished() && on_stream_closed_) {
on_stream_closed_(*this);
}
}
void Stream::process_packet(PDU& packet) {
return process_packet(packet, timestamp_type(0));
}
Flow& Stream::client_flow() {
return client_flow_;
}
const Flow& Stream::client_flow() const {
return client_flow_;
}
Flow& Stream::server_flow() {
return server_flow_;
}
const Flow& Stream::server_flow() const {
return server_flow_;
}
void Stream::stream_closed_callback(const stream_callback_type& callback) {
on_stream_closed_ = callback;
}
void Stream::client_data_callback(const stream_callback_type& callback) {
on_client_data_callback_ = callback;
}
void Stream::server_data_callback(const stream_callback_type& callback) {
on_server_data_callback_ = callback;
}
void Stream::client_out_of_order_callback(const stream_packet_callback_type& callback) {
on_client_out_of_order_callback_ = callback;
}
void Stream::server_out_of_order_callback(const stream_packet_callback_type& callback) {
on_server_out_of_order_callback_ = callback;
}
void Stream::ignore_client_data() {
client_flow().ignore_data_packets();
}
void Stream::ignore_server_data() {
server_flow().ignore_data_packets();
}
bool Stream::is_finished() const {
const Flow::State client_state = client_flow_.state();
const Flow::State server_state = server_flow_.state();
// If either peer sent a RST then the stream is done
if (client_state == Flow::RST_SENT || server_state == Flow::RST_SENT) {
return true;
}
else {
// Otherwise, only finish if both sent a FIN
return client_state == Flow::FIN_SENT && server_state == Flow::FIN_SENT;
}
}
bool Stream::is_v6() const {
return server_flow().is_v6();
}
IPv4Address Stream::client_addr_v4() const {
return server_flow().dst_addr_v4();
}
IPv6Address Stream::client_addr_v6() const {
return server_flow().dst_addr_v6();
}
const Stream::hwaddress_type& Stream::client_hw_addr() const {
return client_hw_addr_;
}
const Stream::hwaddress_type& Stream::server_hw_addr() const {
return server_hw_addr_;
}
IPv4Address Stream::server_addr_v4() const {
return client_flow().dst_addr_v4();
}
IPv6Address Stream::server_addr_v6() const {
return client_flow().dst_addr_v6();
}
uint16_t Stream::client_port() const {
return server_flow().dport();
}
uint16_t Stream::server_port() const {
return client_flow().dport();
}
const Stream::payload_type& Stream::client_payload() const {
return client_flow().payload();
}
Stream::payload_type& Stream::client_payload() {
return client_flow().payload();
}
const Stream::payload_type& Stream::server_payload() const {
return server_flow().payload();
}
Stream::payload_type& Stream::server_payload() {
return server_flow().payload();
}
const Stream::timestamp_type& Stream::create_time() const {
return create_time_;
}
const Stream::timestamp_type& Stream::last_seen() const {
return last_seen_;
}
Flow Stream::extract_client_flow(const PDU& packet) {
const TCP* tcp = packet.find_pdu<TCP>();
if (!tcp) {
throw invalid_packet();
}
if (const IP* ip = packet.find_pdu<IP>()) {
return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
}
else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
}
else {
throw invalid_packet();
}
}
Flow Stream::extract_server_flow(const PDU& packet) {
const TCP* tcp = packet.find_pdu<TCP>();
if (!tcp) {
throw invalid_packet();
}
if (const IP* ip = packet.find_pdu<IP>()) {
return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
}
else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
}
else {
throw invalid_packet();
}
}
void Stream::setup_flows_callbacks() {
using namespace std::placeholders;
client_flow_.data_callback(bind(&Stream::on_client_flow_data, this, _1));
server_flow_.data_callback(bind(&Stream::on_server_flow_data, this, _1));
client_flow_.out_of_order_callback(bind(&Stream::on_client_out_of_order,
this, _1, _2, _3));
server_flow_.out_of_order_callback(bind(&Stream::on_server_out_of_order,
this, _1, _2, _3));
}
void Stream::auto_cleanup_payloads(bool value) {
auto_cleanup_client_data(value);
auto_cleanup_server_data(value);
}
void Stream::auto_cleanup_client_data(bool value) {
auto_cleanup_client_ = value;
}
void Stream::auto_cleanup_server_data(bool value) {
auto_cleanup_server_ = value;
}
void Stream::enable_ack_tracking() {
client_flow().enable_ack_tracking();
server_flow().enable_ack_tracking();
}
bool Stream::ack_tracking_enabled() const {
return client_flow().ack_tracking_enabled() && server_flow().ack_tracking_enabled();
}
bool Stream::is_partial_stream() const {
return is_partial_stream_;
}
void Stream::enable_recovery_mode(uint32_t recovery_window) {
using namespace std::placeholders;
client_out_of_order_callback(bind(&Stream::client_recovery_mode_handler, _1, _2, _3,
client_flow_.sequence_number() + recovery_window,
on_client_out_of_order_callback_));
server_out_of_order_callback(bind(&Stream::server_recovery_mode_handler, _1, _2, _3,
server_flow_.sequence_number() + recovery_window,
on_server_out_of_order_callback_));
directions_recovery_mode_enabled_ = 2;
}
bool Stream::is_recovery_mode_enabled() const {
return directions_recovery_mode_enabled_ > 0;
}
void Stream::on_client_flow_data(const Flow& /*flow*/) {
if (on_client_data_callback_) {
on_client_data_callback_(*this);
}
if (auto_cleanup_client_) {
client_payload().clear();
}
}
void Stream::on_server_flow_data(const Flow& /*flow*/) {
if (on_server_data_callback_) {
on_server_data_callback_(*this);
}
if (auto_cleanup_server_) {
server_payload().clear();
}
}
void Stream::on_client_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
if (on_client_out_of_order_callback_) {
on_client_out_of_order_callback_(*this, seq, payload);
}
}
void Stream::on_server_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
if (on_server_out_of_order_callback_) {
on_server_out_of_order_callback_(*this, seq, payload);
}
}
void Stream::client_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
const payload_type& payload,
uint32_t recovery_sequence_number_end,
const stream_packet_callback_type& original_callback) {
if (!recovery_mode_handler(stream.client_flow(), sequence_number,
recovery_sequence_number_end)) {
stream.client_out_of_order_callback(original_callback);
stream.directions_recovery_mode_enabled_--;
}
if (original_callback) {
original_callback(stream, sequence_number, payload);
}
}
void Stream::server_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
const payload_type& payload,
uint32_t recovery_sequence_number_end,
const stream_packet_callback_type& original_callback) {
if (!recovery_mode_handler(stream.server_flow(), sequence_number,
recovery_sequence_number_end)) {
stream.server_out_of_order_callback(original_callback);
stream.directions_recovery_mode_enabled_--;
}
if (original_callback) {
original_callback(stream, sequence_number, payload);
}
}
bool Stream::recovery_mode_handler(Flow& flow, uint32_t sequence_number,
uint32_t recovery_sequence_number_end) {
// If this packet comes after our sequence number (would create a hole), skip it
if (sequence_number > flow.sequence_number() &&
sequence_number <= recovery_sequence_number_end) {
flow.advance_sequence(sequence_number);
}
// Return true iff we need to keep being in recovery mode
return recovery_sequence_number_end > sequence_number;
}
} // TCPIP
} // Tins
#endif // TINS_HAVE_TCPIP
<commit_msg>Execute original ooo callback first on recovery mode<commit_after>/*
* Copyright (c) 2016, Matias Fontanini
* 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.
*
* 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 "tcp_ip/stream.h"
#ifdef TINS_HAVE_TCPIP
#include <limits>
#include <algorithm>
#include "memory.h"
#include "ip_address.h"
#include "ipv6_address.h"
#include "tcp.h"
#include "ip.h"
#include "ipv6.h"
#include "ethernetII.h"
#include "rawpdu.h"
#include "exceptions.h"
#include "memory_helpers.h"
using std::make_pair;
using std::bind;
using std::pair;
using std::runtime_error;
using std::numeric_limits;
using std::max;
using std::swap;
using Tins::Memory::OutputMemoryStream;
using Tins::Memory::InputMemoryStream;
namespace Tins {
namespace TCPIP {
Stream::Stream(PDU& packet, const timestamp_type& ts)
: client_flow_(extract_client_flow(packet)),
server_flow_(extract_server_flow(packet)), create_time_(ts),
last_seen_(ts), auto_cleanup_client_(true), auto_cleanup_server_(true),
is_partial_stream_(false), directions_recovery_mode_enabled_(0) {
const EthernetII* eth = packet.find_pdu<EthernetII>();
if (eth) {
client_hw_addr_ = eth->src_addr();
server_hw_addr_ = eth->dst_addr();
}
const TCP& tcp = packet.rfind_pdu<TCP>();
// If this is not the first packet of a stream (SYN), then it's a partial stream
is_partial_stream_ = tcp.flags() != TCP::SYN;
}
void Stream::process_packet(PDU& packet, const timestamp_type& ts) {
last_seen_ = ts;
if (client_flow_.packet_belongs(packet)) {
client_flow_.process_packet(packet);
}
else if (server_flow_.packet_belongs(packet)) {
server_flow_.process_packet(packet);
}
if (is_finished() && on_stream_closed_) {
on_stream_closed_(*this);
}
}
void Stream::process_packet(PDU& packet) {
return process_packet(packet, timestamp_type(0));
}
Flow& Stream::client_flow() {
return client_flow_;
}
const Flow& Stream::client_flow() const {
return client_flow_;
}
Flow& Stream::server_flow() {
return server_flow_;
}
const Flow& Stream::server_flow() const {
return server_flow_;
}
void Stream::stream_closed_callback(const stream_callback_type& callback) {
on_stream_closed_ = callback;
}
void Stream::client_data_callback(const stream_callback_type& callback) {
on_client_data_callback_ = callback;
}
void Stream::server_data_callback(const stream_callback_type& callback) {
on_server_data_callback_ = callback;
}
void Stream::client_out_of_order_callback(const stream_packet_callback_type& callback) {
on_client_out_of_order_callback_ = callback;
}
void Stream::server_out_of_order_callback(const stream_packet_callback_type& callback) {
on_server_out_of_order_callback_ = callback;
}
void Stream::ignore_client_data() {
client_flow().ignore_data_packets();
}
void Stream::ignore_server_data() {
server_flow().ignore_data_packets();
}
bool Stream::is_finished() const {
const Flow::State client_state = client_flow_.state();
const Flow::State server_state = server_flow_.state();
// If either peer sent a RST then the stream is done
if (client_state == Flow::RST_SENT || server_state == Flow::RST_SENT) {
return true;
}
else {
// Otherwise, only finish if both sent a FIN
return client_state == Flow::FIN_SENT && server_state == Flow::FIN_SENT;
}
}
bool Stream::is_v6() const {
return server_flow().is_v6();
}
IPv4Address Stream::client_addr_v4() const {
return server_flow().dst_addr_v4();
}
IPv6Address Stream::client_addr_v6() const {
return server_flow().dst_addr_v6();
}
const Stream::hwaddress_type& Stream::client_hw_addr() const {
return client_hw_addr_;
}
const Stream::hwaddress_type& Stream::server_hw_addr() const {
return server_hw_addr_;
}
IPv4Address Stream::server_addr_v4() const {
return client_flow().dst_addr_v4();
}
IPv6Address Stream::server_addr_v6() const {
return client_flow().dst_addr_v6();
}
uint16_t Stream::client_port() const {
return server_flow().dport();
}
uint16_t Stream::server_port() const {
return client_flow().dport();
}
const Stream::payload_type& Stream::client_payload() const {
return client_flow().payload();
}
Stream::payload_type& Stream::client_payload() {
return client_flow().payload();
}
const Stream::payload_type& Stream::server_payload() const {
return server_flow().payload();
}
Stream::payload_type& Stream::server_payload() {
return server_flow().payload();
}
const Stream::timestamp_type& Stream::create_time() const {
return create_time_;
}
const Stream::timestamp_type& Stream::last_seen() const {
return last_seen_;
}
Flow Stream::extract_client_flow(const PDU& packet) {
const TCP* tcp = packet.find_pdu<TCP>();
if (!tcp) {
throw invalid_packet();
}
if (const IP* ip = packet.find_pdu<IP>()) {
return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
}
else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
return Flow(ip->dst_addr(), tcp->dport(), tcp->seq());
}
else {
throw invalid_packet();
}
}
Flow Stream::extract_server_flow(const PDU& packet) {
const TCP* tcp = packet.find_pdu<TCP>();
if (!tcp) {
throw invalid_packet();
}
if (const IP* ip = packet.find_pdu<IP>()) {
return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
}
else if (const IPv6* ip = packet.find_pdu<IPv6>()) {
return Flow(ip->src_addr(), tcp->sport(), tcp->ack_seq());
}
else {
throw invalid_packet();
}
}
void Stream::setup_flows_callbacks() {
using namespace std::placeholders;
client_flow_.data_callback(bind(&Stream::on_client_flow_data, this, _1));
server_flow_.data_callback(bind(&Stream::on_server_flow_data, this, _1));
client_flow_.out_of_order_callback(bind(&Stream::on_client_out_of_order,
this, _1, _2, _3));
server_flow_.out_of_order_callback(bind(&Stream::on_server_out_of_order,
this, _1, _2, _3));
}
void Stream::auto_cleanup_payloads(bool value) {
auto_cleanup_client_data(value);
auto_cleanup_server_data(value);
}
void Stream::auto_cleanup_client_data(bool value) {
auto_cleanup_client_ = value;
}
void Stream::auto_cleanup_server_data(bool value) {
auto_cleanup_server_ = value;
}
void Stream::enable_ack_tracking() {
client_flow().enable_ack_tracking();
server_flow().enable_ack_tracking();
}
bool Stream::ack_tracking_enabled() const {
return client_flow().ack_tracking_enabled() && server_flow().ack_tracking_enabled();
}
bool Stream::is_partial_stream() const {
return is_partial_stream_;
}
void Stream::enable_recovery_mode(uint32_t recovery_window) {
using namespace std::placeholders;
client_out_of_order_callback(bind(&Stream::client_recovery_mode_handler, _1, _2, _3,
client_flow_.sequence_number() + recovery_window,
on_client_out_of_order_callback_));
server_out_of_order_callback(bind(&Stream::server_recovery_mode_handler, _1, _2, _3,
server_flow_.sequence_number() + recovery_window,
on_server_out_of_order_callback_));
directions_recovery_mode_enabled_ = 2;
}
bool Stream::is_recovery_mode_enabled() const {
return directions_recovery_mode_enabled_ > 0;
}
void Stream::on_client_flow_data(const Flow& /*flow*/) {
if (on_client_data_callback_) {
on_client_data_callback_(*this);
}
if (auto_cleanup_client_) {
client_payload().clear();
}
}
void Stream::on_server_flow_data(const Flow& /*flow*/) {
if (on_server_data_callback_) {
on_server_data_callback_(*this);
}
if (auto_cleanup_server_) {
server_payload().clear();
}
}
void Stream::on_client_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
if (on_client_out_of_order_callback_) {
on_client_out_of_order_callback_(*this, seq, payload);
}
}
void Stream::on_server_out_of_order(const Flow& flow, uint32_t seq, const payload_type& payload) {
if (on_server_out_of_order_callback_) {
on_server_out_of_order_callback_(*this, seq, payload);
}
}
void Stream::client_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
const payload_type& payload,
uint32_t recovery_sequence_number_end,
const stream_packet_callback_type& original_callback) {
if (original_callback) {
original_callback(stream, sequence_number, payload);
}
if (!recovery_mode_handler(stream.client_flow(), sequence_number,
recovery_sequence_number_end)) {
stream.directions_recovery_mode_enabled_--;
stream.client_out_of_order_callback(original_callback);
}
}
void Stream::server_recovery_mode_handler(Stream& stream, uint32_t sequence_number,
const payload_type& payload,
uint32_t recovery_sequence_number_end,
const stream_packet_callback_type& original_callback) {
if (original_callback) {
original_callback(stream, sequence_number, payload);
}
if (!recovery_mode_handler(stream.server_flow(), sequence_number,
recovery_sequence_number_end)) {
stream.directions_recovery_mode_enabled_--;
stream.server_out_of_order_callback(original_callback);
}
}
bool Stream::recovery_mode_handler(Flow& flow, uint32_t sequence_number,
uint32_t recovery_sequence_number_end) {
// If this packet comes after our sequence number (would create a hole), skip it
if (sequence_number > flow.sequence_number() &&
sequence_number <= recovery_sequence_number_end) {
flow.advance_sequence(sequence_number);
}
// Return true iff we need to keep being in recovery mode
return recovery_sequence_number_end > sequence_number;
}
} // TCPIP
} // Tins
#endif // TINS_HAVE_TCPIP
<|endoftext|> |
<commit_before>#include <chrono>
#include <cinttypes>
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include "myworkcell_core/srv/localize_part.hpp"
// The ScanNPlan inherits from node, allowing it to act as a Node to do things like create clients
class ScanNPlan : public rclcpp::Node
{
public:
explicit ScanNPlan()
: Node("scan_n_plan")
{
vision_client_ = this->create_client<myworkcell_core::srv::LocalizePart>("localize_part");
}
void start(const std::string& base_frame)
{
// Need to wait until vision node has data
rclcpp::Rate rate(std::chrono::duration<int, std::milli>(1000));
rate.sleep();
RCLCPP_INFO(this->get_logger(), "Attempting to localize part in frame: %s", base_frame.c_str());
// The vision client needs to wait until the service appears
while (!vision_client_->wait_for_service(std::chrono::duration<int, std::milli>(500))) {
if (!rclcpp::ok()) {
RCLCPP_ERROR(this->get_logger(), "client interrupted while waiting for service to appear.");
return;
}
RCLCPP_INFO(this->get_logger(), "waiting for service to appear...");
}
// Create a request for the LocalizePart service call
auto request = std::make_shared<myworkcell_core::srv::LocalizePart::Request>();
// The base_frame that is passed in is used to fill the request
request->base_frame = base_frame;
using ServiceResponseFuture =
rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedFuture; //holds results of async call
auto response_received_callback = [this](ServiceResponseFuture future) {
auto result = future.get();
RCLCPP_INFO(this->get_logger(), "Part Localized: w: %f, x: %f, y: %f, z: %f",
result->pose.orientation.w,
result->pose.position.x,
result->pose.position.y,
result->pose.position.z);
rclcpp::shutdown();
};
auto future = vision_client_->async_send_request(request, response_received_callback);
//auto larry = rclcpp::Node::get_node_base_interface();
rclcpp::spin(rclcpp::Node::get_node_base_interface()); //this needs to be tested
}
private:
//
rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedPtr vision_client_;
};
int main(int argc, char **argv)
{
// This must be called before anything else ROS-related
rclcpp::init(argc, argv);
// Create the ScanNPlan object and node
auto app = std::make_shared<ScanNPlan>();
// Create client to get parameters
auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(app);
// String to store the base_frame parameter after getting it from the Node's parameter client
std::string base_frame;
app->declare_parameter("base_frame");
app->get_parameter("base_frame", base_frame);
RCLCPP_INFO(app->get_logger(), "ScanNPlan node has been initialized");
// Call the vision client's LocalizePart service using base_frame as a parameter
app->start(base_frame);
// Spin on the node so we don't exit the program
rclcpp::spin(app);
rclcpp::shutdown();
return 0;
}
<commit_msg>Add spin on node base interface inside start<commit_after>#include <chrono>
#include <cinttypes>
#include <memory>
#include <rclcpp/rclcpp.hpp>
#include "myworkcell_core/srv/localize_part.hpp"
// The ScanNPlan inherits from node, allowing it to act as a Node to do things like create clients
class ScanNPlan : public rclcpp::Node
{
public:
explicit ScanNPlan()
: Node("scan_n_plan")
{
vision_client_ = this->create_client<myworkcell_core::srv::LocalizePart>("localize_part");
}
void start(const std::string& base_frame)
{
// Need to wait until vision node has data
rclcpp::Rate rate(std::chrono::duration<int, std::milli>(1000));
rate.sleep();
RCLCPP_INFO(this->get_logger(), "Attempting to localize part in frame: %s", base_frame.c_str());
// The vision client needs to wait until the service appears
while (!vision_client_->wait_for_service(std::chrono::duration<int, std::milli>(500))) {
if (!rclcpp::ok()) {
RCLCPP_ERROR(this->get_logger(), "client interrupted while waiting for service to appear.");
return;
}
RCLCPP_INFO(this->get_logger(), "waiting for service to appear...");
}
// Create a request for the LocalizePart service call
auto request = std::make_shared<myworkcell_core::srv::LocalizePart::Request>();
// The base_frame that is passed in is used to fill the request
request->base_frame = base_frame;
using ServiceResponseFuture =
rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedFuture; //holds results of async call
auto response_received_callback = [this](ServiceResponseFuture future) {
auto result = future.get();
RCLCPP_INFO(this->get_logger(), "Part Localized: w: %f, x: %f, y: %f, z: %f",
result->pose.orientation.w,
result->pose.position.x,
result->pose.position.y,
result->pose.position.z);
rclcpp::shutdown();
};
auto future = vision_client_->async_send_request(request, response_received_callback);
// Make sure node doesn't exit using the node interface to spin
rclcpp::spin(rclcpp::Node::get_node_base_interface());
}
private:
//
rclcpp::Client<myworkcell_core::srv::LocalizePart>::SharedPtr vision_client_;
};
int main(int argc, char **argv)
{
// This must be called before anything else ROS-related
rclcpp::init(argc, argv);
// Create the ScanNPlan object and node
auto app = std::make_shared<ScanNPlan>();
// Create client to get parameters
auto parameters_client = std::make_shared<rclcpp::SyncParametersClient>(app);
// String to store the base_frame parameter after getting it from the Node's parameter client
std::string base_frame;
app->declare_parameter("base_frame");
app->get_parameter("base_frame", base_frame);
RCLCPP_INFO(app->get_logger(), "ScanNPlan node has been initialized");
// Call the vision client's LocalizePart service using base_frame as a parameter
app->start(base_frame);
rclcpp::shutdown();
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "defaults.hpp"
#include "tools.hpp"
#include "grid_base.hpp"
#include "grid_tools.hpp"
#include "container.hpp"
namespace gftools {
/** A grid_object_base is a wrapper over container class, that stores data,
* defined on multiple different grids.
*/
template <typename ContainerType, typename ...GridTypes>
class grid_object_base;
template <typename ValueType, typename ... GridTypes>
using grid_object = grid_object_base<container<ValueType, sizeof...(GridTypes)>, GridTypes...>;
template <typename ValueType, typename ... GridTypes>
using grid_object_ref = grid_object_base<container_ref<ValueType, sizeof...(GridTypes)>, GridTypes...>;
template <typename ContainerType, typename ...GridTypes>
class grid_object_base
{
public:
/// A typedef for the container.
typedef ContainerType container_type;
/// A typedef for the values stored in the container.
typedef typename ContainerType::value_type value_type;
/// A typedef for a tuple of grids.
typedef std::tuple<GridTypes...> grid_tuple;
/// Tuple of grids traits.
typedef tools::grid_tuple_traits<grid_tuple> trs;
/// Total number of grids.
static constexpr size_t N = sizeof...(GridTypes);
/// A typedef for a function that gives the analytical value of the object, when it's not stored.
typedef typename tools::GridArgTypeExtractor<value_type, std::tuple<GridTypes...> >::f_type function_type;
/// A typedef for a function that gives the analytical value of the object, when it's not stored.
typedef typename tools::GridPointExtractor<value_type, std::tuple<GridTypes...> >::f_type point_function_type;
/// A typedef for a tuple of grid points.
typedef typename trs::point_tuple point_tuple;
/// A typedef for a tuple of grid point values.
typedef typename trs::arg_tuple arg_tuple;
/// A typedef for an array of grid indices.
typedef typename trs::indices indices_t;
class exPointMismatch : public std::exception { virtual const char* what() const throw() { return "Index mismatch."; }; };
class exIOProblem : public std::exception { virtual const char* what() const throw(){return "IO problem.";} };
class ex_wrong_index : public std::exception { virtual const char* what() const throw(){return "Index out of bounds";}};
public:
/// Grids on which the data is defined.
const std::tuple<GridTypes...> grids_;
/// Cache data dimensions.
const indices_t dims_;
/// Actual data - can be a container (data allocated) or a view (proxy to some other data).
container_type data_;
/// This function returns the value of the object when the point is not in container.
function_type tail_;
// Constructors
/// Constructs a grid object out of a tuple containing various grids.
grid_object_base( const std::tuple<GridTypes...> &grids);
//grid_object_base( const std::tuple<GridTypes...> &grids, ContainerType&& in);
grid_object_base( GridTypes... grids):grid_object_base(std::forward_as_tuple(grids...)){};
/// Constructor of grids and data.
template <typename CType>
grid_object_base( const std::tuple<GridTypes...> &grids, CType& data);
grid_object_base( const std::tuple<GridTypes...> &grids, ContainerType&& data);
/// Copy constructor.
grid_object_base( const grid_object_base<ContainerType, GridTypes...>& rhs);
template <typename CType>
grid_object_base( const grid_object_base<CType, GridTypes...>& rhs);
/// Move constructor.
grid_object_base( grid_object_base<ContainerType, GridTypes...>&& rhs);
// Assignments
grid_object_base& operator= (const grid_object_base & rhs);
template <typename CType>
grid_object_base& operator= (const grid_object_base<CType,GridTypes...> & rhs);
grid_object_base& operator= (grid_object_base && rhs);
grid_object_base& operator= (const value_type & rhs);
// Properties of gridobjects - dimensions, grids, etc
std::tuple<GridTypes...> const& grids() const { return grids_; }
/// Returns an Mth grid in grids_.
template<size_t M = 0>
auto grid() const -> const typename std::tuple_element<M, std::tuple<GridTypes...>>::type&
{ return std::get<M>(grids_); };
size_t size() const { return data_.size(); }
point_tuple points(indices_t in) const { return trs::points(in,grids_); }
arg_tuple get_args(indices_t in) const { return trs::get_args(in, grids_); }
arg_tuple get_args(point_tuple in) const { return trs::get_args(in, grids_); }
indices_t get_indices(point_tuple in) const { return trs::get_indices(in, grids_); }
/// Returns the data_ container.
container_type& data(){return data_;}
container_type const& data() const {return data_;}
function_type& tail(){return tail_;}
// Global operations - reductions, shifts
/// Returns the complex conjugate of this object, if it's complex valued.
grid_object_base<ContainerType, GridTypes...> conj() { return grid_object_base(grids_, data_.conj()); }
/// Returns a norm of difference between two objects.
template <typename CT>
real_type diff (const grid_object_base<CT, GridTypes...> &rhs) const { return data_.diff(rhs.data()); } ;
/// Returns the sum of all elements in the container.
value_type sum() { return data_.sum(); };
/// Returns an object with arguments, shifted by the given values.
template <typename ...ArgTypes>
typename std::enable_if<
(std::is_convertible<std::tuple<typename std::remove_reference<ArgTypes>::type...>, arg_tuple>::value || std::is_convertible<std::tuple<ArgTypes...>, point_tuple>::value),
grid_object<value_type, GridTypes...>>::type shift(ArgTypes... args) const { return this->shift(std::forward_as_tuple(args...)); }
template <typename ...ArgTypes>
typename std::enable_if<
(std::is_convertible<std::tuple<ArgTypes...>, arg_tuple>::value || std::is_same<std::tuple<ArgTypes...>, point_tuple>::value),
grid_object<value_type, GridTypes...>>::type shift(const std::tuple<ArgTypes...>& arg_tuple) const ;
// IO
/// Save the data to the txt file.
void savetxt(const std::string& fname) const;
/// Loads the data to the txt file.
void loadtxt(const std::string& fname, real_type tol = 1e-8);
/// Dumps the object to the stream.
template <typename CT, class ...GridTypes2> friend std::ostream& operator<<(std::ostream& lhs, const grid_object_base<CT,GridTypes2...> &in);
// Access operators
/// Returns element number i, which corresponds to (*_grid)[i].
auto operator[](size_t i)->decltype(data_[i]) { return data_[i]; };
//template <size_t M> value_type& operator[](const std::array<size_t,M>& in);
/// Returns tail_(in).
value_type tail_eval(const arg_tuple& in) const { return tuple_tools::unfold_tuple(tail_, in); }
template <typename ... ArgTypes>
typename std::enable_if<std::is_convertible<std::tuple<ArgTypes...>, arg_tuple>::value, value_type>::type
tail_eval(ArgTypes...in) { return tail_(in...); };
/// Return the value by grid values.
value_type& get(const point_tuple& in) { return data_(get_indices(in)); }
//value_type& operator()(const point_tuple& in) { return data_(get_indices(in)); }
const value_type& operator()(const point_tuple& in) const { return data_(get_indices(in)); }
template <int M=N>
typename std::enable_if<(M>1 ), value_type>::type operator()(arg_tuple in) const
{
try { point_tuple x = trs::find_nearest(in, grids_); return (*this)(x); } // FIXME with expression templates
catch (...) { return this->tail_eval(in); };
// FIXME # warning grid_object::operator() doesn't provide interpolation for D>=2
}
template <int M=N>
typename std::enable_if<(M==1 ), value_type>::type operator()(arg_tuple in) const
{ try { return std::get<0>(grids_).eval(data_, std::get<0>(in)); } catch (...) { return this->tail_eval(in); } }
template <typename ...ArgTypes>
typename std::enable_if<std::is_convertible<std::tuple<ArgTypes...>, point_tuple>::value
, value_type>::type
operator()(ArgTypes... in) const { return (*this)(point_tuple(std::forward_as_tuple(in...))); }
template <typename ...ArgTypes>
typename std::enable_if<!std::is_convertible<std::tuple<ArgTypes...>, point_tuple>::value &&
sizeof...(ArgTypes)!=1 && (sizeof...(ArgTypes)==N)
, value_type>::type
operator()(ArgTypes... in) const { return (*this)(arg_tuple(std::forward_as_tuple(in...))); }
template <typename ArgType>
typename std::enable_if<std::is_same<std::tuple<ArgType>, arg_tuple>::value, value_type>::type
operator()(ArgType in) const { try { return std::get<0>(grids_).eval(data_, in); }
catch (typename std::tuple_element<0, grid_tuple>::type::ex_wrong_index) { return tail_(in); }; }
/*template <typename ArgType>
typename std::enable_if<std::is_same<std::tuple<ArgType>, arg_tuple>::value, value_type>::type
operator()(ArgType in) { return std::get<0>(grids_).eval(data_, in); }
*/
/// Return value of grid_object. eval methods of grids are used, so interpolation is done if provided with grids
// Fill values
/// Fills the container with a provided function.
void fill(const function_type &in);
void fill(const point_function_type &in);
void fill(const std::function<value_type(arg_tuple)>& in) { this->fill(tools::extract_tuple_f(in)); }
void fill(const std::function<value_type(point_tuple)>& in) { this->fill(tools::extract_tuple_f(in)); }
/// A shortcut for fill method.
//template <typename ...ArgTypes> grid_object_base& operator= (const std::function<value_type(ArgTypes...)> &);
/// Same as operator=, but allows for non-equal grids. Slow. Uses analytic function to provide missing values.
template <typename CType2>
grid_object_base& copy_interpolate(const grid_object_base<CType2, GridTypes...> &rhs);
// Math (should be removed to an external algebra class).
grid_object_base& operator*= (const grid_object_base & rhs);
grid_object_base& operator*= (const value_type& rhs);
grid_object_base operator* (const grid_object_base & rhs) const;
grid_object_base operator* (const value_type & rhs) const;
grid_object_base& operator+= (const grid_object_base & rhs);
grid_object_base& operator+= (const value_type& rhs);
grid_object_base operator+ (const grid_object_base & rhs) const;
grid_object_base operator+ (const value_type & rhs) const;
grid_object_base& operator-= (const grid_object_base & rhs);
grid_object_base& operator-= (const value_type& rhs);
grid_object_base operator- (const grid_object_base & rhs) const;
grid_object_base operator- (const value_type & rhs) const;
grid_object_base& operator/= (const grid_object_base & rhs);
grid_object_base& operator/= (const value_type& rhs);
grid_object_base operator/ (const grid_object_base & rhs) const;
grid_object_base operator/ (const value_type & rhs) const;
friend grid_object_base operator* (const value_type & lhs, const grid_object_base & rhs) {return rhs*lhs;};
friend grid_object_base operator+ (const value_type & lhs, const grid_object_base & rhs) {return rhs+lhs;};
friend grid_object_base operator- (const value_type & lhs, const grid_object_base & rhs) {return rhs*(-1.0)+lhs;};
friend grid_object_base operator/ (const value_type & lhs, const grid_object_base & rhs) {grid_object_base out(rhs); out=lhs; return out/rhs;};
};
/*
/// A helper recursive template utility to extract and set data from the container.
template <size_t Nc, typename CT, typename ArgType1, typename ...ArgTypes> struct containerExtractor {
typedef typename CT::value_type value_type;
/// Gets the data by values.
static value_type get(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1, const ArgTypes&... args);
static value_type& get_ref(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1, const ArgTypes&... args);
};
/// Specialization of containerExtractor for 1-dim container.
template <typename CT, typename ArgType1> struct containerExtractor<1,CT,ArgType1> {
typedef typename CT::value_type value_type;
static value_type get(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1);
static value_type get(CT &data, const std::tuple<GridTypes...> &grids, const std::tuple<ArgType1>& arg1);
static value_type& get_ref(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1);
static value_type& get_ref(CT &data, const std::tuple<GridTypes...> &grids, const std::tuple<ArgType1>& arg1);
};
*/
} // end of namespace gftools
#include "grid_object.hxx"
<commit_msg>const operator[] for grid_objects<commit_after>#pragma once
#include "defaults.hpp"
#include "tools.hpp"
#include "grid_base.hpp"
#include "grid_tools.hpp"
#include "container.hpp"
namespace gftools {
/** A grid_object_base is a wrapper over container class, that stores data,
* defined on multiple different grids.
*/
template <typename ContainerType, typename ...GridTypes>
class grid_object_base;
template <typename ValueType, typename ... GridTypes>
using grid_object = grid_object_base<container<ValueType, sizeof...(GridTypes)>, GridTypes...>;
template <typename ValueType, typename ... GridTypes>
using grid_object_ref = grid_object_base<container_ref<ValueType, sizeof...(GridTypes)>, GridTypes...>;
template <typename ContainerType, typename ...GridTypes>
class grid_object_base
{
public:
/// A typedef for the container.
typedef ContainerType container_type;
/// A typedef for the values stored in the container.
typedef typename ContainerType::value_type value_type;
/// A typedef for a tuple of grids.
typedef std::tuple<GridTypes...> grid_tuple;
/// Tuple of grids traits.
typedef tools::grid_tuple_traits<grid_tuple> trs;
/// Total number of grids.
static constexpr size_t N = sizeof...(GridTypes);
/// A typedef for a function that gives the analytical value of the object, when it's not stored.
typedef typename tools::GridArgTypeExtractor<value_type, std::tuple<GridTypes...> >::f_type function_type;
/// A typedef for a function that gives the analytical value of the object, when it's not stored.
typedef typename tools::GridPointExtractor<value_type, std::tuple<GridTypes...> >::f_type point_function_type;
/// A typedef for a tuple of grid points.
typedef typename trs::point_tuple point_tuple;
/// A typedef for a tuple of grid point values.
typedef typename trs::arg_tuple arg_tuple;
/// A typedef for an array of grid indices.
typedef typename trs::indices indices_t;
class exPointMismatch : public std::exception { virtual const char* what() const throw() { return "Index mismatch."; }; };
class exIOProblem : public std::exception { virtual const char* what() const throw(){return "IO problem.";} };
class ex_wrong_index : public std::exception { virtual const char* what() const throw(){return "Index out of bounds";}};
public:
/// Grids on which the data is defined.
const std::tuple<GridTypes...> grids_;
/// Cache data dimensions.
const indices_t dims_;
/// Actual data - can be a container (data allocated) or a view (proxy to some other data).
container_type data_;
/// This function returns the value of the object when the point is not in container.
function_type tail_;
// Constructors
/// Constructs a grid object out of a tuple containing various grids.
grid_object_base( const std::tuple<GridTypes...> &grids);
//grid_object_base( const std::tuple<GridTypes...> &grids, ContainerType&& in);
grid_object_base( GridTypes... grids):grid_object_base(std::forward_as_tuple(grids...)){};
/// Constructor of grids and data.
template <typename CType>
grid_object_base( const std::tuple<GridTypes...> &grids, CType& data);
grid_object_base( const std::tuple<GridTypes...> &grids, ContainerType&& data);
/// Copy constructor.
grid_object_base( const grid_object_base<ContainerType, GridTypes...>& rhs);
template <typename CType>
grid_object_base( const grid_object_base<CType, GridTypes...>& rhs);
/// Move constructor.
grid_object_base( grid_object_base<ContainerType, GridTypes...>&& rhs);
// Assignments
grid_object_base& operator= (const grid_object_base & rhs);
template <typename CType>
grid_object_base& operator= (const grid_object_base<CType,GridTypes...> & rhs);
grid_object_base& operator= (grid_object_base && rhs);
grid_object_base& operator= (const value_type & rhs);
// Properties of gridobjects - dimensions, grids, etc
std::tuple<GridTypes...> const& grids() const { return grids_; }
/// Returns an Mth grid in grids_.
template<size_t M = 0>
auto grid() const -> const typename std::tuple_element<M, std::tuple<GridTypes...>>::type&
{ return std::get<M>(grids_); };
size_t size() const { return data_.size(); }
point_tuple points(indices_t in) const { return trs::points(in,grids_); }
arg_tuple get_args(indices_t in) const { return trs::get_args(in, grids_); }
arg_tuple get_args(point_tuple in) const { return trs::get_args(in, grids_); }
indices_t get_indices(point_tuple in) const { return trs::get_indices(in, grids_); }
/// Returns the data_ container.
container_type& data(){return data_;}
container_type const& data() const {return data_;}
function_type& tail(){return tail_;}
// Global operations - reductions, shifts
/// Returns the complex conjugate of this object, if it's complex valued.
grid_object_base<ContainerType, GridTypes...> conj() { return grid_object_base(grids_, data_.conj()); }
/// Returns a norm of difference between two objects.
template <typename CT>
real_type diff (const grid_object_base<CT, GridTypes...> &rhs) const { return data_.diff(rhs.data()); } ;
/// Returns the sum of all elements in the container.
value_type sum() { return data_.sum(); };
/// Returns an object with arguments, shifted by the given values.
template <typename ...ArgTypes>
typename std::enable_if<
(std::is_convertible<std::tuple<typename std::remove_reference<ArgTypes>::type...>, arg_tuple>::value || std::is_convertible<std::tuple<ArgTypes...>, point_tuple>::value),
grid_object<value_type, GridTypes...>>::type shift(ArgTypes... args) const { return this->shift(std::forward_as_tuple(args...)); }
template <typename ...ArgTypes>
typename std::enable_if<
(std::is_convertible<std::tuple<ArgTypes...>, arg_tuple>::value || std::is_same<std::tuple<ArgTypes...>, point_tuple>::value),
grid_object<value_type, GridTypes...>>::type shift(const std::tuple<ArgTypes...>& arg_tuple) const ;
// IO
/// Save the data to the txt file.
void savetxt(const std::string& fname) const;
/// Loads the data to the txt file.
void loadtxt(const std::string& fname, real_type tol = 1e-8);
/// Dumps the object to the stream.
template <typename CT, class ...GridTypes2> friend std::ostream& operator<<(std::ostream& lhs, const grid_object_base<CT,GridTypes2...> &in);
// Access operators
/// Returns element number i, which corresponds to (*_grid)[i].
auto operator[](size_t i)->decltype(data_[i]) { return data_[i]; };
auto operator[](size_t i) const -> const decltype(data_[i]) { return data_[i]; };
//template <size_t M> value_type& operator[](const std::array<size_t,M>& in);
/// Returns tail_(in).
value_type tail_eval(const arg_tuple& in) const { return tuple_tools::unfold_tuple(tail_, in); }
template <typename ... ArgTypes>
typename std::enable_if<std::is_convertible<std::tuple<ArgTypes...>, arg_tuple>::value, value_type>::type
tail_eval(ArgTypes...in) { return tail_(in...); };
/// Return the value by grid values.
value_type& get(const point_tuple& in) { return data_(get_indices(in)); }
//value_type& operator()(const point_tuple& in) { return data_(get_indices(in)); }
const value_type& operator()(const point_tuple& in) const { return data_(get_indices(in)); }
template <int M=N>
typename std::enable_if<(M>1 ), value_type>::type operator()(arg_tuple in) const
{
try { point_tuple x = trs::find_nearest(in, grids_); return (*this)(x); } // FIXME with expression templates
catch (...) { return this->tail_eval(in); };
// FIXME # warning grid_object::operator() doesn't provide interpolation for D>=2
}
template <int M=N>
typename std::enable_if<(M==1 ), value_type>::type operator()(arg_tuple in) const
{ try { return std::get<0>(grids_).eval(data_, std::get<0>(in)); } catch (...) { return this->tail_eval(in); } }
template <typename ...ArgTypes>
typename std::enable_if<std::is_convertible<std::tuple<ArgTypes...>, point_tuple>::value
, value_type>::type
operator()(ArgTypes... in) const { return (*this)(point_tuple(std::forward_as_tuple(in...))); }
template <typename ...ArgTypes>
typename std::enable_if<!std::is_convertible<std::tuple<ArgTypes...>, point_tuple>::value &&
sizeof...(ArgTypes)!=1 && (sizeof...(ArgTypes)==N)
, value_type>::type
operator()(ArgTypes... in) const { return (*this)(arg_tuple(std::forward_as_tuple(in...))); }
template <typename ArgType>
typename std::enable_if<std::is_same<std::tuple<ArgType>, arg_tuple>::value, value_type>::type
operator()(ArgType in) const { try { return std::get<0>(grids_).eval(data_, in); }
catch (typename std::tuple_element<0, grid_tuple>::type::ex_wrong_index) { return tail_(in); }; }
/*template <typename ArgType>
typename std::enable_if<std::is_same<std::tuple<ArgType>, arg_tuple>::value, value_type>::type
operator()(ArgType in) { return std::get<0>(grids_).eval(data_, in); }
*/
/// Return value of grid_object. eval methods of grids are used, so interpolation is done if provided with grids
// Fill values
/// Fills the container with a provided function.
void fill(const function_type &in);
void fill(const point_function_type &in);
void fill(const std::function<value_type(arg_tuple)>& in) { this->fill(tools::extract_tuple_f(in)); }
void fill(const std::function<value_type(point_tuple)>& in) { this->fill(tools::extract_tuple_f(in)); }
/// A shortcut for fill method.
//template <typename ...ArgTypes> grid_object_base& operator= (const std::function<value_type(ArgTypes...)> &);
/// Same as operator=, but allows for non-equal grids. Slow. Uses analytic function to provide missing values.
template <typename CType2>
grid_object_base& copy_interpolate(const grid_object_base<CType2, GridTypes...> &rhs);
// Math (should be removed to an external algebra class).
grid_object_base& operator*= (const grid_object_base & rhs);
grid_object_base& operator*= (const value_type& rhs);
grid_object_base operator* (const grid_object_base & rhs) const;
grid_object_base operator* (const value_type & rhs) const;
grid_object_base& operator+= (const grid_object_base & rhs);
grid_object_base& operator+= (const value_type& rhs);
grid_object_base operator+ (const grid_object_base & rhs) const;
grid_object_base operator+ (const value_type & rhs) const;
grid_object_base& operator-= (const grid_object_base & rhs);
grid_object_base& operator-= (const value_type& rhs);
grid_object_base operator- (const grid_object_base & rhs) const;
grid_object_base operator- (const value_type & rhs) const;
grid_object_base& operator/= (const grid_object_base & rhs);
grid_object_base& operator/= (const value_type& rhs);
grid_object_base operator/ (const grid_object_base & rhs) const;
grid_object_base operator/ (const value_type & rhs) const;
friend grid_object_base operator* (const value_type & lhs, const grid_object_base & rhs) {return rhs*lhs;};
friend grid_object_base operator+ (const value_type & lhs, const grid_object_base & rhs) {return rhs+lhs;};
friend grid_object_base operator- (const value_type & lhs, const grid_object_base & rhs) {return rhs*(-1.0)+lhs;};
friend grid_object_base operator/ (const value_type & lhs, const grid_object_base & rhs) {grid_object_base out(rhs); out=lhs; return out/rhs;};
};
/*
/// A helper recursive template utility to extract and set data from the container.
template <size_t Nc, typename CT, typename ArgType1, typename ...ArgTypes> struct containerExtractor {
typedef typename CT::value_type value_type;
/// Gets the data by values.
static value_type get(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1, const ArgTypes&... args);
static value_type& get_ref(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1, const ArgTypes&... args);
};
/// Specialization of containerExtractor for 1-dim container.
template <typename CT, typename ArgType1> struct containerExtractor<1,CT,ArgType1> {
typedef typename CT::value_type value_type;
static value_type get(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1);
static value_type get(CT &data, const std::tuple<GridTypes...> &grids, const std::tuple<ArgType1>& arg1);
static value_type& get_ref(CT &data, const std::tuple<GridTypes...> &grids, const ArgType1& arg1);
static value_type& get_ref(CT &data, const std::tuple<GridTypes...> &grids, const std::tuple<ArgType1>& arg1);
};
*/
} // end of namespace gftools
#include "grid_object.hxx"
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/planning_gflags.h"
DEFINE_int32(planning_loop_rate, 5, "Loop rate for planning node");
DEFINE_string(rtk_trajectory_filename, "modules/planning/data/garage.csv",
"Loop rate for planning node");
DEFINE_uint64(backward_trajectory_point_num, 10,
"The number of points to be included in planning trajectory "
"before the matched point");
DEFINE_uint64(rtk_trajectory_forward, 800,
"The number of points to be included in RTK trajectory "
"after the matched point");
DEFINE_double(trajectory_resolution, 0.01,
"The time resolution of "
"output trajectory.");
DEFINE_double(
look_backward_distance, 10,
"look backward this distance when creating reference line from routing");
DEFINE_double(
look_forward_distance, 70,
"look forward this distance when creating reference line from routing");
DEFINE_bool(enable_smooth_reference_line, true,
"enable smooth the map reference line");
DEFINE_int32(max_history_frame_num, 5, "The maximum history frame number");
DEFINE_double(max_collision_distance, 0.1,
"considered as collision if distance (meters) is smaller than or "
"equal to this (meters)");
DEFINE_double(replan_distance_threshold, 5.0,
"The distance threshold of replan");
DEFINE_bool(enable_reference_line_provider_thread, false,
"Enable reference line provider thread.");
DEFINE_double(default_reference_line_width, 4.0,
"Default reference line width");
DEFINE_double(planning_upper_speed_limit, 7.5,
"Maximum speed (m/s) in planning.");
DEFINE_double(planning_distance, 100, "Planning distance");
DEFINE_double(trajectory_time_length, 8.0, "Trajectory time length");
DEFINE_double(trajectory_time_resolution, 0.1,
"Trajectory time resolution in planning");
DEFINE_double(output_trajectory_time_resolution, 0.05,
"Trajectory time resolution when publish");
DEFINE_bool(enable_trajectory_check, false,
"Enable sanity check for planning trajectory.");
DEFINE_double(speed_lower_bound, -0.02, "The lowest speed allowed.");
DEFINE_double(speed_upper_bound, 40.0, "The highest speed allowed.");
DEFINE_double(longitudinal_acceleration_lower_bound, -4.5,
"The lowest longitudinal acceleration allowed.");
DEFINE_double(longitudinal_acceleration_upper_bound, 4.0,
"The highest longitudinal acceleration allowed.");
DEFINE_double(lateral_acceleration_bound, 4.5,
"Bound of lateral acceleration; symmetric for left and right");
DEFINE_double(lateral_jerk_bound, 4.0,
"Bound of lateral jerk; symmetric for left and right");
DEFINE_double(longitudinal_jerk_lower_bound, -4.0,
"The lower bound of longitudinal jerk.");
DEFINE_double(longitudinal_jerk_upper_bound, 4.0,
"The upper bound of longitudinal jerk.");
DEFINE_double(kappa_bound, 1.00, "The bound for vehicle curvature");
// ST Boundary
DEFINE_double(st_max_s, 80, "the maximum s of st boundary");
DEFINE_double(st_max_t, 10, "the maximum t of st boundary");
// Decision Part
DEFINE_double(static_obstacle_speed_threshold, 1.0,
"obstacles are considered as static obstacle if its speed is "
"less than this value (m/s)");
DEFINE_bool(enable_nudge_decision, false, "enable nudge decision");
DEFINE_double(static_decision_ignore_s_range, 3.0,
"threshold for judging nudge in dp path computing decision");
DEFINE_double(static_decision_nudge_l_buffer, 0.5, "l buffer for nudge");
DEFINE_double(stop_distance_obstacle, 10.0,
"stop distance from in-lane obstacle (meters)");
DEFINE_double(stop_distance_destination, 3.0,
"stop distance from destination line");
DEFINE_double(min_driving_width, 2.5,
"minimum road width(meters) for adc to drive through");
DEFINE_double(nudge_distance_obstacle, 0.3,
"minimum distance to nudge a obstacle (meters)");
DEFINE_double(follow_min_distance, 10,
"min follow distance for vehicles/bicycles/moving objects");
DEFINE_double(stop_line_min_distance, 0.0,
"min distance (meters) to stop line for a valid stop");
DEFINE_string(destination_obstacle_id, "DEST",
"obstacle id for converting destination to an obstacle");
DEFINE_int32(virtual_obstacle_perception_id, -1,
"virtual obstacle perception id(a negative int)");
DEFINE_double(virtual_stop_wall_length, 0.1,
"virtual stop wall length (meters)");
DEFINE_double(virtual_stop_wall_width, 3.7, "virtual stop wall width (meters)");
DEFINE_double(virtual_stop_wall_height, 2.0,
"virtual stop wall height (meters)");
// Prediction Part
DEFINE_double(prediction_total_time, 5.0, "Total prediction time");
DEFINE_bool(align_prediction_time, true,
"enable align prediction data based planning time");
// Trajectory
DEFINE_bool(enable_rule_layer, true,
"enable rule for trajectory before model computation");
// Traffic decision
DEFINE_string(planning_config_file,
"modules/planning/conf/planning_config.pb.txt",
"planning config file");
DEFINE_int32(trajectory_point_num_for_debug, 10,
"number of output trajectory points for debugging");
DEFINE_double(decision_valid_stop_range, 0.5,
"The valid stop range in decision.");
DEFINE_bool(enable_record_debug, true,
"True to enable record debug into debug protobuf.");
DEFINE_bool(enable_prediction, true, "True to enable prediction input.");
// QpSt optimizer
DEFINE_bool(enable_slowdown_profile_generator, true,
"True to enable slowdown speed profile generator.");
DEFINE_double(slowdown_speed_threshold, 8.0,
"Only generator slowdown profile when adc speed is lower than "
"this threshold. unit : m/s.");
DEFINE_double(slowdown_profile_deceleration, -1.0,
"The deceleration to generate slowdown profile. unit: m/s^2.");
<commit_msg>planning: disable align_prediction_time to allow rosbag replay works for planning.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/planning/common/planning_gflags.h"
DEFINE_int32(planning_loop_rate, 5, "Loop rate for planning node");
DEFINE_string(rtk_trajectory_filename, "modules/planning/data/garage.csv",
"Loop rate for planning node");
DEFINE_uint64(backward_trajectory_point_num, 10,
"The number of points to be included in planning trajectory "
"before the matched point");
DEFINE_uint64(rtk_trajectory_forward, 800,
"The number of points to be included in RTK trajectory "
"after the matched point");
DEFINE_double(trajectory_resolution, 0.01,
"The time resolution of "
"output trajectory.");
DEFINE_double(
look_backward_distance, 10,
"look backward this distance when creating reference line from routing");
DEFINE_double(
look_forward_distance, 70,
"look forward this distance when creating reference line from routing");
DEFINE_bool(enable_smooth_reference_line, true,
"enable smooth the map reference line");
DEFINE_int32(max_history_frame_num, 5, "The maximum history frame number");
DEFINE_double(max_collision_distance, 0.1,
"considered as collision if distance (meters) is smaller than or "
"equal to this (meters)");
DEFINE_double(replan_distance_threshold, 5.0,
"The distance threshold of replan");
DEFINE_bool(enable_reference_line_provider_thread, false,
"Enable reference line provider thread.");
DEFINE_double(default_reference_line_width, 4.0,
"Default reference line width");
DEFINE_double(planning_upper_speed_limit, 7.5,
"Maximum speed (m/s) in planning.");
DEFINE_double(planning_distance, 100, "Planning distance");
DEFINE_double(trajectory_time_length, 8.0, "Trajectory time length");
DEFINE_double(trajectory_time_resolution, 0.1,
"Trajectory time resolution in planning");
DEFINE_double(output_trajectory_time_resolution, 0.05,
"Trajectory time resolution when publish");
DEFINE_bool(enable_trajectory_check, false,
"Enable sanity check for planning trajectory.");
DEFINE_double(speed_lower_bound, -0.02, "The lowest speed allowed.");
DEFINE_double(speed_upper_bound, 40.0, "The highest speed allowed.");
DEFINE_double(longitudinal_acceleration_lower_bound, -4.5,
"The lowest longitudinal acceleration allowed.");
DEFINE_double(longitudinal_acceleration_upper_bound, 4.0,
"The highest longitudinal acceleration allowed.");
DEFINE_double(lateral_acceleration_bound, 4.5,
"Bound of lateral acceleration; symmetric for left and right");
DEFINE_double(lateral_jerk_bound, 4.0,
"Bound of lateral jerk; symmetric for left and right");
DEFINE_double(longitudinal_jerk_lower_bound, -4.0,
"The lower bound of longitudinal jerk.");
DEFINE_double(longitudinal_jerk_upper_bound, 4.0,
"The upper bound of longitudinal jerk.");
DEFINE_double(kappa_bound, 1.00, "The bound for vehicle curvature");
// ST Boundary
DEFINE_double(st_max_s, 80, "the maximum s of st boundary");
DEFINE_double(st_max_t, 10, "the maximum t of st boundary");
// Decision Part
DEFINE_double(static_obstacle_speed_threshold, 1.0,
"obstacles are considered as static obstacle if its speed is "
"less than this value (m/s)");
DEFINE_bool(enable_nudge_decision, false, "enable nudge decision");
DEFINE_double(static_decision_ignore_s_range, 3.0,
"threshold for judging nudge in dp path computing decision");
DEFINE_double(static_decision_nudge_l_buffer, 0.5, "l buffer for nudge");
DEFINE_double(stop_distance_obstacle, 10.0,
"stop distance from in-lane obstacle (meters)");
DEFINE_double(stop_distance_destination, 3.0,
"stop distance from destination line");
DEFINE_double(min_driving_width, 2.5,
"minimum road width(meters) for adc to drive through");
DEFINE_double(nudge_distance_obstacle, 0.3,
"minimum distance to nudge a obstacle (meters)");
DEFINE_double(follow_min_distance, 10,
"min follow distance for vehicles/bicycles/moving objects");
DEFINE_double(stop_line_min_distance, 0.0,
"min distance (meters) to stop line for a valid stop");
DEFINE_string(destination_obstacle_id, "DEST",
"obstacle id for converting destination to an obstacle");
DEFINE_int32(virtual_obstacle_perception_id, -1,
"virtual obstacle perception id(a negative int)");
DEFINE_double(virtual_stop_wall_length, 0.1,
"virtual stop wall length (meters)");
DEFINE_double(virtual_stop_wall_width, 3.7, "virtual stop wall width (meters)");
DEFINE_double(virtual_stop_wall_height, 2.0,
"virtual stop wall height (meters)");
// Prediction Part
DEFINE_double(prediction_total_time, 5.0, "Total prediction time");
DEFINE_bool(align_prediction_time, false,
"enable align prediction data based planning time");
// Trajectory
DEFINE_bool(enable_rule_layer, true,
"enable rule for trajectory before model computation");
// Traffic decision
DEFINE_string(planning_config_file,
"modules/planning/conf/planning_config.pb.txt",
"planning config file");
DEFINE_int32(trajectory_point_num_for_debug, 10,
"number of output trajectory points for debugging");
DEFINE_double(decision_valid_stop_range, 0.5,
"The valid stop range in decision.");
DEFINE_bool(enable_record_debug, true,
"True to enable record debug into debug protobuf.");
DEFINE_bool(enable_prediction, true, "True to enable prediction input.");
// QpSt optimizer
DEFINE_bool(enable_slowdown_profile_generator, true,
"True to enable slowdown speed profile generator.");
DEFINE_double(slowdown_speed_threshold, 8.0,
"Only generator slowdown profile when adc speed is lower than "
"this threshold. unit : m/s.");
DEFINE_double(slowdown_profile_deceleration, -1.0,
"The deceleration to generate slowdown profile. unit: m/s^2.");
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
void addition(int *sum, int x, int y){
*sum = x + y;
}
int main(){
int x = 4;
int y = 5;
int sum;
addition(&sum, x, y);
cout << "The sum is " << sum << endl;
return 0;
}
<commit_msg>Update S7_Pointer_in_functions.cpp<commit_after>//
// Program Name - S7_Pointer_in_functions.cpp
// Series: GetOnToC++ Step: 7
//
// Purpose: This program illustrates how to and the benefits of pointers in functions
//
// Compile: g++ S7_Pointer_in_functions.cpp -o S7_Pointer_in_functions
// Execute: ./S7_Pointer_in_functions
//
// Created by Narayan Mahadevan on 18/08/13.
//
#include <iostream>
using namespace std;
void addition(int *sum, int x, int y){
*sum = x + y;
}
int main(){
int x = 4;
int y = 5;
int sum;
addition(&sum, x, y);
cout << "The sum is " << sum << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Segment.cpp
*****************************************************************************
* Copyright (C) 2010 - 2011 Klagenfurt University
*
* Created on: Aug 10, 2010
* Authors: Christopher Mueller <[email protected]>
* Christian Timmerer <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#define __STDC_CONSTANT_MACROS
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Segment.h"
#include "Representation.h"
#include "MPD.h"
#include "mp4/AtomsReader.hpp"
#include <cassert>
using namespace dash::mpd;
using namespace dash::http;
ISegment::ISegment(const ICanonicalUrl *parent):
ICanonicalUrl( parent ),
startByte (0),
endByte (0),
startTime (VLC_TS_INVALID),
duration (0)
{
debugName = "Segment";
classId = CLASSID_ISEGMENT;
}
dash::http::Chunk * ISegment::getChunk(const std::string &url)
{
return new (std::nothrow) SegmentChunk(this, url);
}
dash::http::Chunk* ISegment::toChunk(size_t index, Representation *ctxrep)
{
Chunk *chunk;
try
{
chunk = getChunk(getUrlSegment().toString(index, ctxrep));
if (!chunk)
return NULL;
}
catch (int)
{
return NULL;
}
if(startByte != endByte)
{
chunk->setStartByte(startByte);
chunk->setEndByte(endByte);
}
return chunk;
}
bool ISegment::isSingleShot() const
{
return true;
}
void ISegment::done()
{
//Only used for a SegmentTemplate.
}
void ISegment::setByteRange(size_t start, size_t end)
{
startByte = start;
endByte = end;
}
void ISegment::setStartTime(mtime_t ztime)
{
startTime = ztime;
}
mtime_t ISegment::getStartTime() const
{
return startTime;
}
mtime_t ISegment::getDuration() const
{
return duration;
}
void ISegment::setDuration(mtime_t d)
{
duration = d;
}
size_t ISegment::getOffset() const
{
return startByte;
}
std::string ISegment::toString(int indent) const
{
std::stringstream ss;
ss << std::string(indent, ' ') << debugName << " url=" << getUrlSegment().toString();
if(startByte!=endByte)
ss << " @" << startByte << ".." << endByte;
return ss.str();
}
bool ISegment::contains(size_t byte) const
{
if (startByte == endByte)
return false;
return (byte >= startByte &&
(!endByte || byte <= endByte) );
}
int ISegment::getClassId() const
{
return classId;
}
ISegment::SegmentChunk::SegmentChunk(ISegment *segment_, const std::string &url) :
dash::http::Chunk(url)
{
segment = segment_;
}
void ISegment::SegmentChunk::onDownload(void *, size_t)
{
}
Segment::Segment(ICanonicalUrl *parent) :
ISegment(parent)
{
size = -1;
classId = CLASSID_SEGMENT;
}
void Segment::addSubSegment(SubSegment *subsegment)
{
subsegments.push_back(subsegment);
}
Segment::~Segment()
{
std::vector<SubSegment*>::iterator it;
for(it=subsegments.begin();it!=subsegments.end();it++)
delete *it;
}
void Segment::setSourceUrl ( const std::string &url )
{
if ( url.empty() == false )
this->sourceUrl = url;
}
std::string Segment::toString(int indent) const
{
if (subsegments.empty())
{
return ISegment::toString(indent);
}
else
{
std::string ret;
std::vector<SubSegment *>::const_iterator l;
for(l = subsegments.begin(); l != subsegments.end(); l++)
{
ret.append( (*l)->toString(indent + 1) );
}
return ret;
}
}
Url Segment::getUrlSegment() const
{
Url ret = getParentUrlSegment();
if (!sourceUrl.empty())
ret.append(sourceUrl);
return ret;
}
dash::http::Chunk* Segment::toChunk(size_t index, Representation *ctxrep)
{
Chunk *chunk = ISegment::toChunk(index, ctxrep);
if (chunk && ctxrep)
chunk->setBitrate(ctxrep->getBandwidth());
return chunk;
}
std::vector<ISegment*> Segment::subSegments()
{
std::vector<ISegment*> list;
if(!subsegments.empty())
{
std::vector<SubSegment*>::iterator it;
for(it=subsegments.begin();it!=subsegments.end();it++)
list.push_back(*it);
}
else
{
list.push_back(this);
}
return list;
}
InitSegment::InitSegment(ICanonicalUrl *parent) :
Segment(parent)
{
debugName = "InitSegment";
classId = CLASSID_INITSEGMENT;
}
IndexSegment::IndexSegment(ICanonicalUrl *parent) :
Segment(parent)
{
debugName = "IndexSegment";
classId = CLASSID_INDEXSEGMENT;
}
dash::http::Chunk* IndexSegment::toChunk(size_t index, Representation *ctxrep)
{
IndexSegmentChunk *chunk = dynamic_cast<IndexSegmentChunk *>(Segment::toChunk(index, ctxrep));
chunk->setIndexRepresentation(ctxrep);
return chunk;
}
dash::http::Chunk * IndexSegment::getChunk(const std::string &url)
{
return new IndexSegmentChunk(this, url);
}
IndexSegment::IndexSegmentChunk::IndexSegmentChunk(ISegment *segment, const std::string &url)
: SegmentChunk(segment, url)
{
}
void IndexSegment::IndexSegmentChunk::setIndexRepresentation(Representation *rep_)
{
rep = rep_;
}
void IndexSegment::IndexSegmentChunk::onDownload(void *buffer, size_t size)
{
if(!rep)
return;
dash::mp4::AtomsReader br(rep->getMPD()->getVLCObject());
br.parseBlock(buffer, size, rep);
}
SubSegment::SubSegment(Segment *main, size_t start, size_t end) :
ISegment(main), parent(main)
{
setByteRange(start, end);
debugName = "SubSegment";
classId = CLASSID_SUBSEGMENT;
}
Url SubSegment::getUrlSegment() const
{
return getParentUrlSegment();
}
std::vector<ISegment*> SubSegment::subSegments()
{
std::vector<ISegment*> list;
list.push_back(this);
return list;
}
<commit_msg>demux: dash: missing initializer (cid #1260244)<commit_after>/*
* Segment.cpp
*****************************************************************************
* Copyright (C) 2010 - 2011 Klagenfurt University
*
* Created on: Aug 10, 2010
* Authors: Christopher Mueller <[email protected]>
* Christian Timmerer <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#define __STDC_CONSTANT_MACROS
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Segment.h"
#include "Representation.h"
#include "MPD.h"
#include "mp4/AtomsReader.hpp"
#include <cassert>
using namespace dash::mpd;
using namespace dash::http;
ISegment::ISegment(const ICanonicalUrl *parent):
ICanonicalUrl( parent ),
startByte (0),
endByte (0),
startTime (VLC_TS_INVALID),
duration (0)
{
debugName = "Segment";
classId = CLASSID_ISEGMENT;
}
dash::http::Chunk * ISegment::getChunk(const std::string &url)
{
return new (std::nothrow) SegmentChunk(this, url);
}
dash::http::Chunk* ISegment::toChunk(size_t index, Representation *ctxrep)
{
Chunk *chunk;
try
{
chunk = getChunk(getUrlSegment().toString(index, ctxrep));
if (!chunk)
return NULL;
}
catch (int)
{
return NULL;
}
if(startByte != endByte)
{
chunk->setStartByte(startByte);
chunk->setEndByte(endByte);
}
return chunk;
}
bool ISegment::isSingleShot() const
{
return true;
}
void ISegment::done()
{
//Only used for a SegmentTemplate.
}
void ISegment::setByteRange(size_t start, size_t end)
{
startByte = start;
endByte = end;
}
void ISegment::setStartTime(mtime_t ztime)
{
startTime = ztime;
}
mtime_t ISegment::getStartTime() const
{
return startTime;
}
mtime_t ISegment::getDuration() const
{
return duration;
}
void ISegment::setDuration(mtime_t d)
{
duration = d;
}
size_t ISegment::getOffset() const
{
return startByte;
}
std::string ISegment::toString(int indent) const
{
std::stringstream ss;
ss << std::string(indent, ' ') << debugName << " url=" << getUrlSegment().toString();
if(startByte!=endByte)
ss << " @" << startByte << ".." << endByte;
return ss.str();
}
bool ISegment::contains(size_t byte) const
{
if (startByte == endByte)
return false;
return (byte >= startByte &&
(!endByte || byte <= endByte) );
}
int ISegment::getClassId() const
{
return classId;
}
ISegment::SegmentChunk::SegmentChunk(ISegment *segment_, const std::string &url) :
dash::http::Chunk(url)
{
segment = segment_;
}
void ISegment::SegmentChunk::onDownload(void *, size_t)
{
}
Segment::Segment(ICanonicalUrl *parent) :
ISegment(parent)
{
size = -1;
classId = CLASSID_SEGMENT;
}
void Segment::addSubSegment(SubSegment *subsegment)
{
subsegments.push_back(subsegment);
}
Segment::~Segment()
{
std::vector<SubSegment*>::iterator it;
for(it=subsegments.begin();it!=subsegments.end();it++)
delete *it;
}
void Segment::setSourceUrl ( const std::string &url )
{
if ( url.empty() == false )
this->sourceUrl = url;
}
std::string Segment::toString(int indent) const
{
if (subsegments.empty())
{
return ISegment::toString(indent);
}
else
{
std::string ret;
std::vector<SubSegment *>::const_iterator l;
for(l = subsegments.begin(); l != subsegments.end(); l++)
{
ret.append( (*l)->toString(indent + 1) );
}
return ret;
}
}
Url Segment::getUrlSegment() const
{
Url ret = getParentUrlSegment();
if (!sourceUrl.empty())
ret.append(sourceUrl);
return ret;
}
dash::http::Chunk* Segment::toChunk(size_t index, Representation *ctxrep)
{
Chunk *chunk = ISegment::toChunk(index, ctxrep);
if (chunk && ctxrep)
chunk->setBitrate(ctxrep->getBandwidth());
return chunk;
}
std::vector<ISegment*> Segment::subSegments()
{
std::vector<ISegment*> list;
if(!subsegments.empty())
{
std::vector<SubSegment*>::iterator it;
for(it=subsegments.begin();it!=subsegments.end();it++)
list.push_back(*it);
}
else
{
list.push_back(this);
}
return list;
}
InitSegment::InitSegment(ICanonicalUrl *parent) :
Segment(parent)
{
debugName = "InitSegment";
classId = CLASSID_INITSEGMENT;
}
IndexSegment::IndexSegment(ICanonicalUrl *parent) :
Segment(parent)
{
debugName = "IndexSegment";
classId = CLASSID_INDEXSEGMENT;
}
dash::http::Chunk* IndexSegment::toChunk(size_t index, Representation *ctxrep)
{
IndexSegmentChunk *chunk = dynamic_cast<IndexSegmentChunk *>(Segment::toChunk(index, ctxrep));
chunk->setIndexRepresentation(ctxrep);
return chunk;
}
dash::http::Chunk * IndexSegment::getChunk(const std::string &url)
{
return new IndexSegmentChunk(this, url);
}
IndexSegment::IndexSegmentChunk::IndexSegmentChunk(ISegment *segment, const std::string &url)
: SegmentChunk(segment, url)
{
rep = NULL;
}
void IndexSegment::IndexSegmentChunk::setIndexRepresentation(Representation *rep_)
{
rep = rep_;
}
void IndexSegment::IndexSegmentChunk::onDownload(void *buffer, size_t size)
{
if(!rep)
return;
dash::mp4::AtomsReader br(rep->getMPD()->getVLCObject());
br.parseBlock(buffer, size, rep);
}
SubSegment::SubSegment(Segment *main, size_t start, size_t end) :
ISegment(main), parent(main)
{
setByteRange(start, end);
debugName = "SubSegment";
classId = CLASSID_SUBSEGMENT;
}
Url SubSegment::getUrlSegment() const
{
return getParentUrlSegment();
}
std::vector<ISegment*> SubSegment::subSegments()
{
std::vector<ISegment*> list;
list.push_back(this);
return list;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2011, Arvid Norberg, Magnus Jonsson
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/rsa.hpp"
#include "libtorrent/hasher.hpp"
#if defined TORRENT_USE_OPENSSL
extern "C"
{
#include <openssl/rsa.h>
#include <openssl/objects.h> // for NID_sha1
}
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
// convert bytestring to internal representation
// of the private key
RSA* priv = 0;
unsigned char const* key = (unsigned char const*)private_key;
priv = d2i_RSAPrivateKey(&priv, &key, private_len);
if (priv == 0) return -1;
if (RSA_size(priv) > sig_len)
{
RSA_free(priv);
return -1;
}
RSA_sign(NID_sha1, &digest[0], 20, (unsigned char*)signature, (unsigned int*)&sig_len, priv);
RSA_free(priv);
return sig_len;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
// convert bytestring to internal representation
// of the public key
RSA* pub = 0;
unsigned char const* key = (unsigned char const*)public_key;
pub = d2i_RSAPublicKey(&pub, &key, public_len);
if (pub == 0) return false;
int ret = RSA_verify(NID_sha1, &digest[0], 20, (unsigned char*)signature, sig_len, pub);
RSA_free(pub);
return ret;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
RSA* keypair = RSA_generate_key(key_size, 3, 0, 0);
if (keypair == 0) return false;
bool ret = false;
if (RSA_size(keypair) > *public_len) goto getout;
if (RSA_size(keypair) > *private_len) goto getout;
unsigned char* pub = (unsigned char*)public_key;
unsigned char* priv = (unsigned char*)private_key;
*public_len = i2d_RSAPublicKey(keypair, &pub);
*private_len = i2d_RSAPrivateKey(keypair, &priv);
ret = true;
getout:
RSA_free(keypair);
return ret;
}
} // namespace libtorrent
#else
// just stub these out for now, since they're not used anywhere yet
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
return 0;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
return false;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
return false;
}
} // namespace libtorrent
#endif
<commit_msg>fixed build issue<commit_after>/*
Copyright (c) 2011, Arvid Norberg, Magnus Jonsson
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/rsa.hpp"
#include "libtorrent/hasher.hpp"
#if defined TORRENT_USE_OPENSSL
extern "C"
{
#include <openssl/rsa.h>
#include <openssl/objects.h> // for NID_sha1
}
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
// convert bytestring to internal representation
// of the private key
RSA* priv = 0;
unsigned char const* key = (unsigned char const*)private_key;
priv = d2i_RSAPrivateKey(&priv, &key, private_len);
if (priv == 0) return -1;
if (RSA_size(priv) > sig_len)
{
RSA_free(priv);
return -1;
}
RSA_sign(NID_sha1, &digest[0], 20, (unsigned char*)signature, (unsigned int*)&sig_len, priv);
RSA_free(priv);
return sig_len;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
// convert bytestring to internal representation
// of the public key
RSA* pub = 0;
unsigned char const* key = (unsigned char const*)public_key;
pub = d2i_RSAPublicKey(&pub, &key, public_len);
if (pub == 0) return false;
int ret = RSA_verify(NID_sha1, &digest[0], 20, (unsigned char*)signature, sig_len, pub);
RSA_free(pub);
return ret;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
RSA* keypair = RSA_generate_key(key_size, 3, 0, 0);
if (keypair == 0) return false;
bool ret = false;
unsigned char* pub = (unsigned char*)public_key;
unsigned char* priv = (unsigned char*)private_key;
if (RSA_size(keypair) > *public_len) goto getout;
if (RSA_size(keypair) > *private_len) goto getout;
*public_len = i2d_RSAPublicKey(keypair, &pub);
*private_len = i2d_RSAPrivateKey(keypair, &priv);
ret = true;
getout:
RSA_free(keypair);
return ret;
}
} // namespace libtorrent
#else
// just stub these out for now, since they're not used anywhere yet
namespace libtorrent
{
// returns the size of the resulting signature
int sign_rsa(sha1_hash const& digest
, char const* private_key, int private_len
, char* signature, int sig_len)
{
return 0;
}
// returns true if the signature is valid
bool verify_rsa(sha1_hash const& digest
, char const* public_key, int public_len
, char const* signature, int sig_len)
{
return false;
}
bool generate_rsa_keys(char* public_key, int* public_len
, char* private_key, int* private_len, int key_size)
{
return false;
}
} // namespace libtorrent
#endif
<|endoftext|> |
<commit_before>#include <regex>
#include <string.h>
#include "lynxbot.h"
#include "sed.h"
#include "stringparse.h"
struct sedinfo {
char *regex;
char *replace;
int global;
int ignore;
int error;
int errtok;
};
static int parsecmd(struct sedinfo *s, char *cmd);
static void puterr(char *out, size_t max, struct sedinfo *s);
/* sed: perform a basic sed substitution command on input */
int sed(char *s, size_t max, const char *input, const char *sedcmd)
{
char cmd[MAX_MSG];
struct sedinfo sedbuf;
std::regex pattern;
std::smatch match;
strncpy(cmd, sedcmd, MAX_MSG);
if (!parsecmd(&sedbuf, cmd)) {
puterr(s, max, &sedbuf);
return 0;
}
try {
if (sedbuf.ignore)
pattern = std::regex(sedbuf.regex);
else
pattern = std::regex(sedbuf.regex, std::regex::icase);
} catch (std::regex_error) {
_sprintf(out, max, "sed: invalid regex");
return 0;
}
printf("%s\n%s\n%s\n", input, sedbuf.regex, sedbuf.replace);
return 1;
}
#define INVCMD 1
#define UNTERM 2
#define BADOPT 3
/* parsecmd: break up the sed command into its parts */
static int parsecmd(struct sedinfo *s, char *cmd)
{
char *t;
int delim;
s->global = s->ignore = 0;
if (cmd[0] != 's') {
s->error = INVCMD;
s->errtok = cmd[0];
return 0;
}
if (!(delim = cmd[1]) || !*(s->regex = cmd + 2)) {
s->error = UNTERM;
return 0;
}
t = s->regex;
while ((t = strchr(t, delim)) && *(t - 1) == '\\')
shift_l(t - 1);
if (!t) {
s->error = UNTERM;
return 0;
}
*t++ = '\0';
if (!*(s->replace = t)) {
s->error = UNTERM;
return 0;
}
while ((t = strchr(t, delim)) && *(t - 1) == '\\')
shift_l(t - 1);
if (!t) {
s->error = UNTERM;
return 0;
}
*t++ = '\0';
for (; *t; ++t) {
switch (*t) {
case 'g':
s->global = 1;
break;
case 'i':
s->ignore = 1;
break;
default:
s->error = BADOPT;
s->errtok = *t;
return 0;
}
}
return 1;
}
/* puterr: write error string corresponding to s->error to out */
static void puterr(char *out, size_t max, struct sedinfo *s)
{
switch (s->error) {
case INVCMD:
_sprintf(out, max, "sed: invalid command '%c'", s->errtok);
break;
case UNTERM:
_sprintf(out, max, "sed: unterminated 's' command");
break;
case BADOPT:
_sprintf(out, max, "sed: unkown option to 's' command "
"-- '%c'", s->errtok);
break;
default:
break;
}
}
<commit_msg>Changed regex parsing to account for delimeters within brackets<commit_after>#include <regex>
#include <string.h>
#include "lynxbot.h"
#include "sed.h"
#include "stringparse.h"
struct sedinfo {
char *regex;
char *replace;
int global;
int ignore;
int error;
int errtok;
};
static int parsecmd(struct sedinfo *s, char *cmd);
static void puterr(char *out, size_t max, struct sedinfo *s);
static char *readbrackets(char *s);
/* sed: perform a basic sed substitution command on input */
int sed(char *s, size_t max, const char *input, const char *sedcmd)
{
char cmd[MAX_MSG];
struct sedinfo sedbuf;
std::regex pattern;
std::smatch match;
strncpy(cmd, sedcmd, MAX_MSG);
if (!parsecmd(&sedbuf, cmd)) {
puterr(s, max, &sedbuf);
return 0;
}
try {
if (sedbuf.ignore)
pattern = std::regex(sedbuf.regex);
else
pattern = std::regex(sedbuf.regex, std::regex::icase);
} catch (std::regex_error) {
_sprintf(s, max, "sed: invalid regex");
return 0;
}
printf("%s\n%s\n%s\n", input, sedbuf.regex, sedbuf.replace);
return 1;
}
#define INVCMD 1
#define UNTERM 2
#define BADOPT 3
/* parsecmd: break up the sed command into its parts */
static int parsecmd(struct sedinfo *s, char *cmd)
{
char *t;
int delim, type;
s->global = s->ignore = 0;
if (cmd[0] != 's') {
s->error = INVCMD;
s->errtok = cmd[0];
return 0;
}
if (!(delim = cmd[1]) || !*(s->regex = cmd + 2)) {
s->error = UNTERM;
return 0;
}
t = s->regex;
for (t = s->regex; *t; ++t) {
if (*t == '\'' || *t == '"') {
if (!(t = readbrackets(t))) {
s->error = UNTERM;
return 0;
}
} else if (*t == delim) {
if (*(t - 1) != '\\')
break;
shift_l(t - 1);
--t;
}
}
if (!t) {
s->error = UNTERM;
return 0;
}
*t++ = '\0';
if (!*(s->replace = t)) {
s->error = UNTERM;
return 0;
}
while ((t = strchr(t, delim)) && *(t - 1) == '\\')
shift_l(t - 1);
if (!t) {
s->error = UNTERM;
return 0;
}
*t++ = '\0';
for (; *t; ++t) {
switch (*t) {
case 'g':
s->global = 1;
break;
case 'i':
s->ignore = 1;
break;
default:
s->error = BADOPT;
s->errtok = *t;
return 0;
}
}
return 1;
}
/* puterr: write error string corresponding to s->error to out */
static void puterr(char *out, size_t max, struct sedinfo *s)
{
switch (s->error) {
case INVCMD:
_sprintf(out, max, "sed: invalid command '%c'", s->errtok);
break;
case UNTERM:
_sprintf(out, max, "sed: unterminated 's' command");
break;
case BADOPT:
_sprintf(out, max, "sed: unkown option to 's' command "
"-- '%c'", s->errtok);
break;
default:
break;
}
}
static char *readbrackets(char *s)
{
return s;
}
<|endoftext|> |
<commit_before>#ifndef utf8_hh_INCLUDED
#define utf8_hh_INCLUDED
#include <cstddef>
#include "unicode.hh"
namespace Kakoune
{
namespace utf8
{
// returns an iterator to next character first byte
template<typename Iterator>
Iterator next(Iterator it)
{
if (*it++ & 0x80)
while ((*(it) & 0xC0) == 0x80)
++it;
return it;
}
// returns it's parameter if it points to a character first byte,
// or else returns next character first byte
template<typename Iterator>
Iterator finish(Iterator it)
{
while ((*(it) & 0xC0) == 0x80)
++it;
return it;
}
// returns an iterator to the previous character first byte
template<typename Iterator>
Iterator previous(Iterator it)
{
while ((*(--it) & 0xC0) == 0x80)
;
return it;
}
// returns an iterator pointing to the first byte of the
// dth character after (or before if d < 0) the character
// pointed by it
template<typename Iterator, typename Distance>
Iterator advance(Iterator it, Distance d)
{
if (d < 0)
{
while (d++)
it = previous(it);
}
else
{
while (d--)
it = next(it);
}
return it;
}
// returns the character count between begin and end
template<typename Iterator>
size_t distance(Iterator begin, Iterator end)
{
size_t dist = 0;
while (begin != end)
{
if ((*begin++ & 0xC0) != 0x80)
++dist;
}
}
// return true if it points to the first byte of a (either single or
// multibyte) character
template<typename Iterator>
bool is_character_start(Iterator it)
{
return (*it & 0xC0) != 0x80;
}
struct invalid_utf8_sequence{};
// returns the codepoint of the character whose first byte
// is pointed by it
template<typename Iterator>
Codepoint codepoint(Iterator it)
{
// According to rfc3629, UTF-8 allows only up to 4 bytes.
// (21 bits codepoint)
Codepoint cp;
char byte = *it++;
if (not (byte & 0x80)) // 0xxxxxxx
cp = byte;
else if ((byte & 0xE0) == 0xC0) // 110xxxxx
{
cp = ((byte & 0x1F) << 6) | (*it & 0x3F);
}
else if ((byte & 0xF0) == 0xE0) // 1110xxxx
{
cp = ((byte & 0x0F) << 12) | ((*it++ & 0x3F) << 6);
cp |= (*it & 0x3F);
}
else if ((byte & 0xF8) == 0xF0) // 11110xxx
{
cp = ((byte & 0x0F) << 18) | ((*it++ & 0x3F) << 12);
cp |= (*it++ & 0x3F) << 6;
cp |= (*it & 0x3F);
}
else
throw invalid_utf8_sequence{};
}
struct invalid_codepoint{};
template<typename OutputIterator>
void dump(OutputIterator& it, Codepoint cp)
{
if (cp <= 0x7F)
*it++ = cp;
else if (cp <= 0x7FF)
{
*it++ = 0xC0 | (cp >> 6);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0xFFFF)
{
*it++ = 0xE0 | (cp >> 12);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0x10FFFF)
{
*it++ = 0xF0 | (cp >> 18);
*it++ = 0x80 | ((cp >> 12) & 0x3F);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else
throw invalid_codepoint{};
}
}
}
#endif // utf8_hh_INCLUDED
<commit_msg>Actually return something in utf8::codepoint, thanks gcc for using rax<commit_after>#ifndef utf8_hh_INCLUDED
#define utf8_hh_INCLUDED
#include <cstddef>
#include "unicode.hh"
namespace Kakoune
{
namespace utf8
{
// returns an iterator to next character first byte
template<typename Iterator>
Iterator next(Iterator it)
{
if (*it++ & 0x80)
while ((*(it) & 0xC0) == 0x80)
++it;
return it;
}
// returns it's parameter if it points to a character first byte,
// or else returns next character first byte
template<typename Iterator>
Iterator finish(Iterator it)
{
while ((*(it) & 0xC0) == 0x80)
++it;
return it;
}
// returns an iterator to the previous character first byte
template<typename Iterator>
Iterator previous(Iterator it)
{
while ((*(--it) & 0xC0) == 0x80)
;
return it;
}
// returns an iterator pointing to the first byte of the
// dth character after (or before if d < 0) the character
// pointed by it
template<typename Iterator, typename Distance>
Iterator advance(Iterator it, Distance d)
{
if (d < 0)
{
while (d++)
it = previous(it);
}
else
{
while (d--)
it = next(it);
}
return it;
}
// returns the character count between begin and end
template<typename Iterator>
size_t distance(Iterator begin, Iterator end)
{
size_t dist = 0;
while (begin != end)
{
if ((*begin++ & 0xC0) != 0x80)
++dist;
}
}
// return true if it points to the first byte of a (either single or
// multibyte) character
template<typename Iterator>
bool is_character_start(Iterator it)
{
return (*it & 0xC0) != 0x80;
}
struct invalid_utf8_sequence{};
// returns the codepoint of the character whose first byte
// is pointed by it
template<typename Iterator>
Codepoint codepoint(Iterator it)
{
// According to rfc3629, UTF-8 allows only up to 4 bytes.
// (21 bits codepoint)
Codepoint cp;
char byte = *it++;
if (not (byte & 0x80)) // 0xxxxxxx
cp = byte;
else if ((byte & 0xE0) == 0xC0) // 110xxxxx
{
cp = ((byte & 0x1F) << 6) | (*it & 0x3F);
}
else if ((byte & 0xF0) == 0xE0) // 1110xxxx
{
cp = ((byte & 0x0F) << 12) | ((*it++ & 0x3F) << 6);
cp |= (*it & 0x3F);
}
else if ((byte & 0xF8) == 0xF0) // 11110xxx
{
cp = ((byte & 0x0F) << 18) | ((*it++ & 0x3F) << 12);
cp |= (*it++ & 0x3F) << 6;
cp |= (*it & 0x3F);
}
else
throw invalid_utf8_sequence{};
return cp;
}
struct invalid_codepoint{};
template<typename OutputIterator>
void dump(OutputIterator& it, Codepoint cp)
{
if (cp <= 0x7F)
*it++ = cp;
else if (cp <= 0x7FF)
{
*it++ = 0xC0 | (cp >> 6);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0xFFFF)
{
*it++ = 0xE0 | (cp >> 12);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else if (cp <= 0x10FFFF)
{
*it++ = 0xF0 | (cp >> 18);
*it++ = 0x80 | ((cp >> 12) & 0x3F);
*it++ = 0x80 | ((cp >> 6) & 0x3F);
*it++ = 0x80 | (cp & 0x3F);
}
else
throw invalid_codepoint{};
}
}
}
#endif // utf8_hh_INCLUDED
<|endoftext|> |
<commit_before>/* The MIT License (MIT)
*
* Copyright (c) 2014-2017 David Medina and Tim Warburton
*
* 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
*/
#include <map>
#include "occa/tools/misc.hpp"
#include "occa/tools/sys.hpp"
#include "occa/base.hpp"
#include "occa/uva.hpp"
namespace occa {
ptrRangeMap_t uvaMap;
memoryVector_t uvaStaleMemory;
ptrRange_t::ptrRange_t() :
start(NULL),
end(NULL) {}
ptrRange_t::ptrRange_t(void *ptr, const udim_t bytes) :
start((char*) ptr),
end(((char*) ptr) + bytes) {}
ptrRange_t::ptrRange_t(const ptrRange_t &r) :
start(r.start),
end(r.end) {}
ptrRange_t& ptrRange_t::operator = (const ptrRange_t &r) {
start = r.start;
end = r.end;
return *this;
}
bool ptrRange_t::operator == (const ptrRange_t &r) const {
return ((start <= r.start) && (r.start < end));
}
bool ptrRange_t::operator != (const ptrRange_t &r) const {
return ((r.start < start) || (end <= r.start));
}
int operator < (const ptrRange_t &a, const ptrRange_t &b) {
return ((a != b) && (a.start < b.start));
}
uvaPtrInfo_t::uvaPtrInfo_t() :
mem(NULL) {}
uvaPtrInfo_t::uvaPtrInfo_t(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
if (it != uvaMap.end()) {
mem = (it->second);
} else {
mem = (occa::memory_v*) ptr; // Defaults to ptr being a memory_v
}
}
uvaPtrInfo_t::uvaPtrInfo_t(occa::memory_v *mem_) :
mem(mem_) {}
uvaPtrInfo_t::uvaPtrInfo_t(const uvaPtrInfo_t &upi) :
mem(upi.mem) {}
uvaPtrInfo_t& uvaPtrInfo_t::operator = (const uvaPtrInfo_t &upi) {
mem = upi.mem;
return *this;
}
occa::device uvaPtrInfo_t::getDevice() {
return occa::device(mem->dHandle);
}
occa::memory uvaPtrInfo_t::getMemory() {
return occa::memory(mem);
}
occa::memory_v* uvaToMemory(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
return (it == uvaMap.end()) ? NULL : it->second;
}
void startManaging(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem != NULL) {
mem->memInfo |= uvaFlag::isManaged;
}
}
void stopManaging(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem != NULL) {
mem->memInfo &= ~uvaFlag::isManaged;
}
}
void syncToDevice(void *ptr, const udim_t bytes) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem) {
syncMemToDevice(mem, bytes, ptrDiff(mem->uvaPtr, ptr));
}
}
void syncToHost(void *ptr, const udim_t bytes) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem) {
syncMemToHost(mem, bytes, ptrDiff(mem->uvaPtr, ptr));
}
}
void syncMemToDevice(occa::memory_v *mem,
const udim_t bytes,
const udim_t offset) {
if (mem->dHandle->hasSeparateMemorySpace()) {
occa::memory(mem).syncToDevice(bytes, offset);
}
}
void syncMemToHost(occa::memory_v *mem,
const udim_t bytes,
const udim_t offset) {
if (mem->dHandle->hasSeparateMemorySpace()) {
occa::memory(mem).syncToHost(bytes, offset);
}
}
bool needsSync(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
return (mem == NULL) ? false : mem->isStale();
}
void sync(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem != NULL) {
if (mem->inDevice()) {
syncMemToHost(mem);
} else {
syncMemToDevice(mem);
}
}
}
void dontSync(void *ptr) {
removeFromStaleMap(ptr);
}
void removeFromStaleMap(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
if (it == uvaMap.end()) {
return;
}
memory m(it->second);
if (!m.uvaIsStale()) {
return;
}
removeFromStaleMap(m.getMHandle());
}
void removeFromStaleMap(memory_v *mem) {
occa::memory m(mem);
const size_t staleEntries = uvaStaleMemory.size();
for (size_t i = 0; i < staleEntries; ++i) {
if (uvaStaleMemory[i] == mem) {
m.uvaMarkFresh();
uvaStaleMemory.erase(uvaStaleMemory.begin() + i);
break;
}
}
}
void free(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
if ((it != uvaMap.end()) &&
(((void*) it->first.start) != ((void*) it->second))) {
occa::memory(it->second).free();
} else {
::free(ptr);
}
}
}
<commit_msg>[UVA] Set/unset uvaPtr during start/stop managing calls<commit_after>/* The MIT License (MIT)
*
* Copyright (c) 2014-2017 David Medina and Tim Warburton
*
* 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
*/
#include <map>
#include "occa/tools/misc.hpp"
#include "occa/tools/sys.hpp"
#include "occa/base.hpp"
#include "occa/uva.hpp"
namespace occa {
ptrRangeMap_t uvaMap;
memoryVector_t uvaStaleMemory;
ptrRange_t::ptrRange_t() :
start(NULL),
end(NULL) {}
ptrRange_t::ptrRange_t(void *ptr, const udim_t bytes) :
start((char*) ptr),
end(((char*) ptr) + bytes) {}
ptrRange_t::ptrRange_t(const ptrRange_t &r) :
start(r.start),
end(r.end) {}
ptrRange_t& ptrRange_t::operator = (const ptrRange_t &r) {
start = r.start;
end = r.end;
return *this;
}
bool ptrRange_t::operator == (const ptrRange_t &r) const {
return ((start <= r.start) && (r.start < end));
}
bool ptrRange_t::operator != (const ptrRange_t &r) const {
return ((r.start < start) || (end <= r.start));
}
int operator < (const ptrRange_t &a, const ptrRange_t &b) {
return ((a != b) && (a.start < b.start));
}
uvaPtrInfo_t::uvaPtrInfo_t() :
mem(NULL) {}
uvaPtrInfo_t::uvaPtrInfo_t(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
if (it != uvaMap.end()) {
mem = (it->second);
} else {
mem = (occa::memory_v*) ptr; // Defaults to ptr being a memory_v
}
}
uvaPtrInfo_t::uvaPtrInfo_t(occa::memory_v *mem_) :
mem(mem_) {}
uvaPtrInfo_t::uvaPtrInfo_t(const uvaPtrInfo_t &upi) :
mem(upi.mem) {}
uvaPtrInfo_t& uvaPtrInfo_t::operator = (const uvaPtrInfo_t &upi) {
mem = upi.mem;
return *this;
}
occa::device uvaPtrInfo_t::getDevice() {
return occa::device(mem->dHandle);
}
occa::memory uvaPtrInfo_t::getMemory() {
return occa::memory(mem);
}
occa::memory_v* uvaToMemory(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
return (it == uvaMap.end()) ? NULL : it->second;
}
void startManaging(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem != NULL) {
mem->memInfo |= uvaFlag::isManaged;
mem->uvaPtr = (char*) ptr;
}
}
void stopManaging(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem != NULL) {
mem->memInfo &= ~uvaFlag::isManaged;
mem->uvaPtr = NULL;
}
}
void syncToDevice(void *ptr, const udim_t bytes) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem) {
syncMemToDevice(mem, bytes, ptrDiff(mem->uvaPtr, ptr));
}
}
void syncToHost(void *ptr, const udim_t bytes) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem) {
syncMemToHost(mem, bytes, ptrDiff(mem->uvaPtr, ptr));
}
}
void syncMemToDevice(occa::memory_v *mem,
const udim_t bytes,
const udim_t offset) {
if (mem->dHandle->hasSeparateMemorySpace()) {
occa::memory(mem).syncToDevice(bytes, offset);
}
}
void syncMemToHost(occa::memory_v *mem,
const udim_t bytes,
const udim_t offset) {
if (mem->dHandle->hasSeparateMemorySpace()) {
occa::memory(mem).syncToHost(bytes, offset);
}
}
bool needsSync(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
return (mem == NULL) ? false : mem->isStale();
}
void sync(void *ptr) {
occa::memory_v *mem = uvaToMemory(ptr);
if (mem != NULL) {
if (mem->inDevice()) {
syncMemToHost(mem);
} else {
syncMemToDevice(mem);
}
}
}
void dontSync(void *ptr) {
removeFromStaleMap(ptr);
}
void removeFromStaleMap(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
if (it == uvaMap.end()) {
return;
}
memory m(it->second);
if (!m.uvaIsStale()) {
return;
}
removeFromStaleMap(m.getMHandle());
}
void removeFromStaleMap(memory_v *mem) {
occa::memory m(mem);
const size_t staleEntries = uvaStaleMemory.size();
for (size_t i = 0; i < staleEntries; ++i) {
if (uvaStaleMemory[i] == mem) {
m.uvaMarkFresh();
uvaStaleMemory.erase(uvaStaleMemory.begin() + i);
break;
}
}
}
void free(void *ptr) {
ptrRangeMap_t::iterator it = uvaMap.find(ptr);
if ((it != uvaMap.end()) &&
(((void*) it->first.start) != ((void*) it->second))) {
occa::memory(it->second).free();
} else {
::free(ptr);
}
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/geom_util.hpp>
#include <mapnik/feature.hpp>
// boost
#include <boost/utility.hpp>
namespace mapnik
{
struct wkb_reader : boost::noncopyable
{
private:
enum wkbByteOrder {
wkbXDR=0,
wkbNDR=1
};
const char* wkb_;
unsigned size_;
unsigned pos_;
wkbByteOrder byteOrder_;
bool needSwap_;
wkbFormat format_;
public:
enum wkbGeometryType {
wkbPoint=1,
wkbLineString=2,
wkbPolygon=3,
wkbMultiPoint=4,
wkbMultiLineString=5,
wkbMultiPolygon=6,
wkbGeometryCollection=7
};
wkb_reader(const char* wkb,unsigned size,wkbFormat format)
: wkb_(wkb),
size_(size),
pos_(0),
format_(format)
{
switch (format_)
{
case wkbSpatiaLite:
byteOrder_ = (wkbByteOrder) wkb_[1];
pos_ = 39;
break;
case wkbGeneric:
default:
byteOrder_ = (wkbByteOrder) wkb_[0];
pos_ = 1;
break;
}
#ifndef MAPNIK_BIG_ENDIAN
needSwap_=byteOrder_?wkbXDR:wkbNDR;
#else
needSwap_=byteOrder_?wkbNDR:wkbXDR;
#endif
}
~wkb_reader() {}
void read_multi(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint(feature);
break;
case wkbMultiLineString:
read_multilinestring(feature);
break;
case wkbMultiPolygon:
read_multipolygon(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
void read(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint_2(feature);
break;
case wkbMultiLineString:
read_multilinestring_2(feature);
break;
case wkbMultiPolygon:
read_multipolygon_2(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
private:
int read_integer()
{
boost::int32_t n;
if (needSwap_)
{
read_int32_xdr(wkb_+pos_,n);
}
else
{
read_int32_ndr(wkb_+pos_,n);
}
pos_+=4;
return n;
}
double read_double()
{
double d;
if (needSwap_)
{
read_double_xdr(wkb_ + pos_, d);
}
else
{
read_double_ndr(wkb_ + pos_, d);
}
pos_+=8;
return d;
}
void read_coords(CoordinateArray& ar)
{
int size=sizeof(coord<double,2>)*ar.size();
if (!needSwap_)
{
std::memcpy(&ar[0],wkb_+pos_,size);
pos_+=size;
}
else
{
for (unsigned i=0;i<ar.size();++i)
{
read_double_xdr(wkb_ + pos_,ar[i].x);
read_double_xdr(wkb_ + pos_ + 8,ar[i].y);
pos_ += 16;
}
}
}
void read_point(Feature & feature)
{
geometry_type * pt = new geometry_type(Point);
double x = read_double();
double y = read_double();
pt->move_to(x,y);
feature.add_geometry(pt);
}
void read_multipoint(Feature & feature)
{
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
read_point(feature);
}
}
void read_multipoint_2(Feature & feature)
{
geometry_type * pt = new geometry_type(Point);
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
double x = read_double();
double y = read_double();
pt->move_to(x,y);
}
feature.add_geometry(pt);
}
void read_linestring(Feature & feature)
{
geometry_type * line = new geometry_type(LineString);
int num_points=read_integer();
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(num_points);
line->move_to(ar[0].x,ar[0].y);
for (int i=1;i<num_points;++i)
{
line->line_to(ar[i].x,ar[i].y);
}
feature.add_geometry(line);
}
void read_multilinestring(Feature & feature)
{
int num_lines=read_integer();
for (int i=0;i<num_lines;++i)
{
pos_+=5;
read_linestring(feature);
}
}
void read_multilinestring_2(Feature & feature)
{
geometry_type * line = new geometry_type(LineString);
int num_lines=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_lines;++i)
{
pos_+=5;
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(capacity);
line->move_to(ar[0].x,ar[0].y);
for (int i=1;i<num_points;++i)
{
line->line_to(ar[i].x,ar[i].y);
}
}
feature.add_geometry(line);
}
void read_polygon(Feature & feature)
{
geometry_type * poly = new geometry_type(Polygon);
int num_rings=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_rings;++i)
{
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
}
feature.add_geometry(poly);
}
void read_multipolygon(Feature & feature)
{
int num_polys=read_integer();
for (int i=0;i<num_polys;++i)
{
pos_+=5;
read_polygon(feature);
}
}
void read_multipolygon_2(Feature & feature)
{
geometry_type * poly = new geometry_type(Polygon);
int num_polys=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_polys;++i)
{
pos_+=5;
int num_rings=read_integer();
for (int i=0;i<num_rings;++i)
{
int num_points=read_integer();
capacity += num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
poly->line_to(ar[0].x,ar[0].y);
}
}
feature.add_geometry(poly);
}
};
void geometry_utils::from_wkb (Feature & feature,
const char* wkb,
unsigned size,
bool multiple_geometries,
wkbFormat format)
{
wkb_reader reader(wkb,size,format);
if (multiple_geometries)
return reader.read_multi(feature);
else
return reader.read(feature);
}
}
<commit_msg>+ fixed bad errors when parsing wkb<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 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
*
*****************************************************************************/
//$Id: wkb.cpp 19 2005-03-22 13:53:27Z pavlenko $
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/geom_util.hpp>
#include <mapnik/feature.hpp>
// boost
#include <boost/utility.hpp>
namespace mapnik
{
struct wkb_reader : boost::noncopyable
{
private:
enum wkbByteOrder {
wkbXDR=0,
wkbNDR=1
};
const char* wkb_;
unsigned size_;
unsigned pos_;
wkbByteOrder byteOrder_;
bool needSwap_;
wkbFormat format_;
public:
enum wkbGeometryType {
wkbPoint=1,
wkbLineString=2,
wkbPolygon=3,
wkbMultiPoint=4,
wkbMultiLineString=5,
wkbMultiPolygon=6,
wkbGeometryCollection=7
};
wkb_reader(const char* wkb,unsigned size,wkbFormat format)
: wkb_(wkb),
size_(size),
pos_(0),
format_(format)
{
switch (format_)
{
case wkbSpatiaLite:
byteOrder_ = (wkbByteOrder) wkb_[1];
pos_ = 39;
break;
case wkbGeneric:
default:
byteOrder_ = (wkbByteOrder) wkb_[0];
pos_ = 1;
break;
}
#ifndef MAPNIK_BIG_ENDIAN
needSwap_=byteOrder_?wkbXDR:wkbNDR;
#else
needSwap_=byteOrder_?wkbNDR:wkbXDR;
#endif
}
~wkb_reader() {}
void read_multi(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint(feature);
break;
case wkbMultiLineString:
read_multilinestring(feature);
break;
case wkbMultiPolygon:
read_multipolygon(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
void read(Feature & feature)
{
int type=read_integer();
switch (type)
{
case wkbPoint:
read_point(feature);
break;
case wkbLineString:
read_linestring(feature);
break;
case wkbPolygon:
read_polygon(feature);
break;
case wkbMultiPoint:
read_multipoint_2(feature);
break;
case wkbMultiLineString:
read_multilinestring_2(feature);
break;
case wkbMultiPolygon:
read_multipolygon_2(feature);
break;
case wkbGeometryCollection:
break;
default:
break;
}
}
private:
int read_integer()
{
boost::int32_t n;
if (needSwap_)
{
read_int32_xdr(wkb_+pos_,n);
}
else
{
read_int32_ndr(wkb_+pos_,n);
}
pos_+=4;
return n;
}
double read_double()
{
double d;
if (needSwap_)
{
read_double_xdr(wkb_ + pos_, d);
}
else
{
read_double_ndr(wkb_ + pos_, d);
}
pos_+=8;
return d;
}
void read_coords(CoordinateArray& ar)
{
int size=sizeof(coord<double,2>)*ar.size();
if (!needSwap_)
{
std::memcpy(&ar[0],wkb_+pos_,size);
pos_+=size;
}
else
{
for (unsigned i=0;i<ar.size();++i)
{
read_double_xdr(wkb_ + pos_,ar[i].x);
read_double_xdr(wkb_ + pos_ + 8,ar[i].y);
pos_ += 16;
}
}
}
void read_point(Feature & feature)
{
geometry_type * pt = new geometry_type(Point);
double x = read_double();
double y = read_double();
pt->move_to(x,y);
feature.add_geometry(pt);
}
void read_multipoint(Feature & feature)
{
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
read_point(feature);
}
}
void read_multipoint_2(Feature & feature)
{
geometry_type * pt = new geometry_type(Point);
int num_points = read_integer();
for (int i=0;i<num_points;++i)
{
pos_+=5;
double x = read_double();
double y = read_double();
pt->move_to(x,y);
}
feature.add_geometry(pt);
}
void read_linestring(Feature & feature)
{
geometry_type * line = new geometry_type(LineString);
int num_points=read_integer();
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(num_points);
line->move_to(ar[0].x,ar[0].y);
for (int i=1;i<num_points;++i)
{
line->line_to(ar[i].x,ar[i].y);
}
feature.add_geometry(line);
}
void read_multilinestring(Feature & feature)
{
int num_lines=read_integer();
for (int i=0;i<num_lines;++i)
{
pos_+=5;
read_linestring(feature);
}
}
void read_multilinestring_2(Feature & feature)
{
geometry_type * line = new geometry_type(LineString);
int num_lines=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_lines;++i)
{
pos_+=5;
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
line->set_capacity(capacity);
line->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
line->line_to(ar[j].x,ar[j].y);
}
}
feature.add_geometry(line);
}
void read_polygon(Feature & feature)
{
geometry_type * poly = new geometry_type(Polygon);
int num_rings=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_rings;++i)
{
int num_points=read_integer();
capacity+=num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
}
feature.add_geometry(poly);
}
void read_multipolygon(Feature & feature)
{
int num_polys=read_integer();
for (int i=0;i<num_polys;++i)
{
pos_+=5;
read_polygon(feature);
}
}
void read_multipolygon_2(Feature & feature)
{
geometry_type * poly = new geometry_type(Polygon);
int num_polys=read_integer();
unsigned capacity = 0;
for (int i=0;i<num_polys;++i)
{
pos_+=5;
int num_rings=read_integer();
for (int r=0;r<num_rings;++r)
{
int num_points=read_integer();
capacity += num_points;
CoordinateArray ar(num_points);
read_coords(ar);
poly->set_capacity(capacity);
poly->move_to(ar[0].x,ar[0].y);
for (int j=1;j<num_points;++j)
{
poly->line_to(ar[j].x,ar[j].y);
}
poly->line_to(ar[0].x,ar[0].y);
}
}
feature.add_geometry(poly);
}
};
void geometry_utils::from_wkb (Feature & feature,
const char* wkb,
unsigned size,
bool multiple_geometries,
wkbFormat format)
{
wkb_reader reader(wkb,size,format);
if (multiple_geometries)
return reader.read_multi(feature);
else
return reader.read(feature);
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "itksys/SystemTools.hxx"
int main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "Usage : " << argv[0] << " module_path output_script" << std::endl;
return EXIT_FAILURE;
}
std::string module_path(argv[1]);
std::string output_path(argv[2]);
otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);
std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);
otb::Wrapper::Application::Pointer appPtr;
std::ofstream ofs;
ofs.open(output_path.c_str());
for (unsigned int i=0 ; i < appList.size() ; ++i)
{
appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
if (appPtr.IsNull())
{
std::cout << "Error loading application "<< appList[i] << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> keys = appPtr->GetParametersKeys();
ofs << "# completion for application "<< appList[i] << std::endl;
ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
ofs << "{" << std::endl;
ofs << " local cur prev" << std::endl;
ofs << " COMPREPLY=()" << std::endl;
ofs << " _get_comp_words_by_ref cur prev" << std::endl;
ofs << " case \"$cur\" in" << std::endl;
ofs << " -*)" << std::endl;
ofs << " key_list=\"";
for (unsigned int k=0 ; k < keys.size() ; k++ )
{
ofs << "-" << keys[k] << " ";
}
ofs << "\"" << std::endl;
ofs << " COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
ofs << " return 0" << std::endl;
ofs << " ;;" << std::endl;
ofs << " esac" << std::endl;
// detect choice parameters
std::vector<std::string> choiceKeys;
for (unsigned int k=0 ; k < keys.size() ; k++ )
{
if ( appPtr->GetParameterType(keys[k]) == otb::Wrapper::ParameterType_Choice)
{
choiceKeys.push_back(keys[k]);
}
}
if (choiceKeys.size())
{
ofs << " case \"$prev\" in" << std::endl;
for (unsigned int k=0 ; k < choiceKeys.size() ; k++)
{
ofs << " -" << choiceKeys[k] << ")" << std::endl;
ofs << " key_list=\"";
std::vector<std::string> choices = dynamic_cast<otb::Wrapper::ChoiceParameter*>(appPtr->GetParameterByKey(choiceKeys[k]))->GetChoiceKeys();
for (unsigned int j=0 ; j < choices.size() ; j++)
{
ofs << choices[j];
if (j+1 < choices.size() )
{
ofs << " ";
}
}
ofs << "\"" << std::endl;
ofs << " COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
ofs << " ;;" << std::endl;
}
ofs << " esac" << std::endl;
}
ofs << " return 0" << std::endl;
ofs << "}" << std::endl;
ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
}
ofs.close();
return EXIT_SUCCESS;
}
<commit_msg>DOC: document completionGenerator usage<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperParameter.h"
#include "otbWrapperChoiceParameter.h"
#include "itksys/SystemTools.hxx"
/**
* Small executable to :
* - find available application
* - get list of parameters
* - and fill a bash completion script
*
* This script can be sourced to be used, or deployed into a folder such as
* /etc/bash_completion.d
* For choice parameters, the completion will propose the available choices
*/
int main(int argc, char* argv[])
{
if (argc < 3)
{
std::cerr << "Usage : " << argv[0] << " module_path output_script" << std::endl;
return EXIT_FAILURE;
}
std::string module_path(argv[1]);
std::string output_path(argv[2]);
otb::Wrapper::ApplicationRegistry::SetApplicationPath(module_path);
std::vector<std::string> appList = otb::Wrapper::ApplicationRegistry::GetAvailableApplications(false);
otb::Wrapper::Application::Pointer appPtr;
std::ofstream ofs;
ofs.open(output_path.c_str());
for (unsigned int i=0 ; i < appList.size() ; ++i)
{
appPtr = otb::Wrapper::ApplicationRegistry::CreateApplication(appList[i],false);
if (appPtr.IsNull())
{
std::cout << "Error loading application "<< appList[i] << std::endl;
return EXIT_FAILURE;
}
std::vector<std::string> keys = appPtr->GetParametersKeys();
ofs << "# completion for application "<< appList[i] << std::endl;
ofs << "_otbcli_"<<appList[i]<<"()" << std::endl;
ofs << "{" << std::endl;
ofs << " local cur prev" << std::endl;
ofs << " COMPREPLY=()" << std::endl;
ofs << " _get_comp_words_by_ref cur prev" << std::endl;
ofs << " case \"$cur\" in" << std::endl;
ofs << " -*)" << std::endl;
ofs << " key_list=\"";
for (unsigned int k=0 ; k < keys.size() ; k++ )
{
ofs << "-" << keys[k] << " ";
}
ofs << "\"" << std::endl;
ofs << " COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
ofs << " return 0" << std::endl;
ofs << " ;;" << std::endl;
ofs << " esac" << std::endl;
// detect choice parameters
std::vector<std::string> choiceKeys;
for (unsigned int k=0 ; k < keys.size() ; k++ )
{
if ( appPtr->GetParameterType(keys[k]) == otb::Wrapper::ParameterType_Choice)
{
choiceKeys.push_back(keys[k]);
}
}
if (choiceKeys.size())
{
ofs << " case \"$prev\" in" << std::endl;
for (unsigned int k=0 ; k < choiceKeys.size() ; k++)
{
ofs << " -" << choiceKeys[k] << ")" << std::endl;
ofs << " key_list=\"";
std::vector<std::string> choices = dynamic_cast<otb::Wrapper::ChoiceParameter*>(appPtr->GetParameterByKey(choiceKeys[k]))->GetChoiceKeys();
for (unsigned int j=0 ; j < choices.size() ; j++)
{
ofs << choices[j];
if (j+1 < choices.size() )
{
ofs << " ";
}
}
ofs << "\"" << std::endl;
ofs << " COMPREPLY=( $( compgen -W '$key_list' -- $cur) )" << std::endl;
ofs << " ;;" << std::endl;
}
ofs << " esac" << std::endl;
}
ofs << " return 0" << std::endl;
ofs << "}" << std::endl;
ofs << "complete -o default -F _otbcli_" << appList[i] << " otbcli_"<< appList[i] << std::endl;
}
ofs.close();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* DefaultForwardChainerCB.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomutils/AtomUtils.h>
#include <opencog/guile/SchemeSmob.h>
#include <opencog/atoms/bind/BindLink.h>
#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"
using namespace opencog;
DefaultForwardChainerCB::DefaultForwardChainerCB(
AtomSpace* as, source_selection_mode ts_mode /*=TV_FITNESS_BASED*/) :
ForwardChainerCallBack(as)
{
as_ = as;
fcim_ = new ForwardChainInputMatchCB(as);
fcpm_ = new ForwardChainPatternMatchCB(as);
ts_mode_ = ts_mode;
}
DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
delete fcim_;
delete fcpm_;
}
/**
* choose rule based on premises of rule matching the source
* uses temporary atomspace to limit the search space
*
* @param fcmem forward chainer's working memory
* @return a vector of chosen rules
*/
vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
Handle source = fcmem.get_cur_source();
if (source == Handle::UNDEFINED or NodeCast(source))
throw InvalidParamException(TRACE_INFO,
"Needs a source atom of type LINK");
HandleSeq chosen_bindlinks;
if (LinkCast(source)) {
AtomSpace rule_atomspace;
Handle source_cpy = rule_atomspace.addAtom(source);
// Copy rules to the temporary atomspace.
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
rule_atomspace.addAtom(r->get_handle());
}
// Create bindlink with source as an implicant.
PLNCommons pc(&rule_atomspace);
Handle copy = pc.replace_nodes_with_varnode(source_cpy, NODE);
Handle bind_link = pc.create_bindLink(copy, false);
// Pattern match.
BindLinkPtr bl(BindLinkCast(bind_link));
DefaultImplicator imp(&rule_atomspace);
imp.implicand = bl->get_implicand();
imp.set_type_restrictions(bl->get_typemap());
bl->imply(&imp);
// Get matched bindLinks.
HandleSeq matches = imp.result_list;
if (matches.empty()) {
logger().debug(
"No matching BindLink was found.Returning empty vector");
return vector<Rule*> { };
}
HandleSeq bindlinks;
for (Handle hm : matches) {
//get all BindLinks whose part of their premise matches with hm
HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
for (Handle hi : hs) {
if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
bindlinks.push_back(hi);
}
}
}
// Copy handles to main atomspace.
for (Handle h : bindlinks) {
chosen_bindlinks.push_back(as_->addAtom(h));
}
}
// Try to find specialized rules that contain the source node.
if (NodeCast(source)) {
chosen_bindlinks = get_rootlinks(source, as_, BIND_LINK);
}
// Find the rules containing the bindLink in copied_back.
vector<Rule*> matched_rules;
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
r->get_handle()); //xxx not matching
if (it != chosen_bindlinks.end()) {
matched_rules.push_back(r);
}
}
return matched_rules;
}
/**
* Gets all top level links of certain types and subclasses that
* contain @param hsource
*
* @param hsource handle whose top level links are to be searched
* @param as the atomspace in which search is to be done
* @param link_type the root link types to be searched
* @param subclasses a flag that tells to look subclasses of @link_type
*/
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle hsource, AtomSpace* as,
Type link_type,
bool subclasses)
{
auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
PLNCommons pc(as);
HandleSeq chosen_roots;
HandleSeq candidates_roots;
pc.get_root_links(hsource, candidates_roots);
for (Handle hr : candidates_roots) {
bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
== chosen_roots.end();
auto type = as->getType(hr);
bool subtype = (subclasses and classserver().isA(type, link_type));
if (((type == link_type) or subtype) and notexist) {
//make sure matches are actually part of the premise list rather than the output of the bindLink
Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
if (pc.exists_in(hpremise, hsource)) {
chosen_roots.push_back(hr);
}
}
}
return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_premises(FCMemory& fcmem)
{
HandleSeq inputs;
PLNCommons pc(as_);
Handle hsource = fcmem.get_cur_source();
// Get everything associated with the source handle.
UnorderedHandleSet neighbors = get_distant_neighbors(hsource, 2);
// Add all root links of atoms in @param neighbors.
for (auto hn : neighbors) {
if (hn->getType() != VARIABLE_NODE) {
HandleSeq roots;
pc.get_root_links(hn, roots);
for (auto r : roots) {
if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType()
!= BIND_LINK)
inputs.push_back(r);
}
}
}
return inputs;
}
Handle DefaultForwardChainerCB::choose_next_source(FCMemory& fcmem)
{
HandleSeq tlist = fcmem.get_premise_list();
map<Handle, float> tournament_elem;
PLNCommons pc(as_);
Handle hchosen = Handle::UNDEFINED;
for (Handle t : tlist) {
switch (ts_mode_) {
case TV_FITNESS_BASED: {
float fitness = pc.tv_fitness(t);
tournament_elem[t] = fitness;
}
break;
case STI_BASED:
tournament_elem[t] = t->getSTI();
break;
default:
throw RuntimeException(TRACE_INFO,
"Unknown source selection mode.");
break;
}
}
//!Choose a new source that has never been chosen before.
//!xxx FIXME since same handle might be chosen multiple times the following
//!code doesn't guarantee all sources have been exhaustively looked.
for (size_t i = 0; i < tournament_elem.size(); i++) {
Handle hselected = pc.tournament_select(tournament_elem);
if (fcmem.isin_source_list(hselected)) {
continue;
} else {
hchosen = hselected;
break;
}
}
return hchosen;
}
//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
Rule * cur_rule = fcmem.get_cur_rule();
fcpm_->set_fcmem(&fcmem);
BindLinkPtr bl(BindLinkCast(cur_rule->get_handle()));
bl->imply(fcpm_);
HandleSeq product = fcpm_->get_products();
//! Make sure the inferences made are new.
HandleSeq new_product;
for (auto h : product) {
if (not fcmem.isin_premise_list(h))
new_product.push_back(h);
}
return new_product;
}
<commit_msg>Set ForwardChainPatternMatchCB implicand and type restrictions<commit_after>/*
* DefaultForwardChainerCB.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atomutils/AtomUtils.h>
#include <opencog/guile/SchemeSmob.h>
#include <opencog/atoms/bind/BindLink.h>
#include "DefaultForwardChainerCB.h"
#include "PLNCommons.h"
using namespace opencog;
DefaultForwardChainerCB::DefaultForwardChainerCB(
AtomSpace* as, source_selection_mode ts_mode /*=TV_FITNESS_BASED*/) :
ForwardChainerCallBack(as)
{
as_ = as;
fcim_ = new ForwardChainInputMatchCB(as);
fcpm_ = new ForwardChainPatternMatchCB(as);
ts_mode_ = ts_mode;
}
DefaultForwardChainerCB::~DefaultForwardChainerCB()
{
delete fcim_;
delete fcpm_;
}
/**
* choose rule based on premises of rule matching the source
* uses temporary atomspace to limit the search space
*
* @param fcmem forward chainer's working memory
* @return a vector of chosen rules
*/
vector<Rule*> DefaultForwardChainerCB::choose_rule(FCMemory& fcmem)
{
Handle source = fcmem.get_cur_source();
if (source == Handle::UNDEFINED or NodeCast(source))
throw InvalidParamException(TRACE_INFO,
"Needs a source atom of type LINK");
HandleSeq chosen_bindlinks;
if (LinkCast(source)) {
AtomSpace rule_atomspace;
Handle source_cpy = rule_atomspace.addAtom(source);
// Copy rules to the temporary atomspace.
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
rule_atomspace.addAtom(r->get_handle());
}
// Create bindlink with source as an implicant.
PLNCommons pc(&rule_atomspace);
Handle copy = pc.replace_nodes_with_varnode(source_cpy, NODE);
Handle bind_link = pc.create_bindLink(copy, false);
// Pattern match.
BindLinkPtr bl(BindLinkCast(bind_link));
DefaultImplicator imp(&rule_atomspace);
imp.implicand = bl->get_implicand();
imp.set_type_restrictions(bl->get_typemap());
bl->imply(&imp);
// Get matched bindLinks.
HandleSeq matches = imp.result_list;
if (matches.empty()) {
logger().debug(
"No matching BindLink was found.Returning empty vector");
return vector<Rule*> { };
}
HandleSeq bindlinks;
for (Handle hm : matches) {
//get all BindLinks whose part of their premise matches with hm
HandleSeq hs = get_rootlinks(hm, &rule_atomspace, BIND_LINK);
for (Handle hi : hs) {
if (find(bindlinks.begin(), bindlinks.end(), hi) == bindlinks.end()) {
bindlinks.push_back(hi);
}
}
}
// Copy handles to main atomspace.
for (Handle h : bindlinks) {
chosen_bindlinks.push_back(as_->addAtom(h));
}
}
// Try to find specialized rules that contain the source node.
if (NodeCast(source)) {
chosen_bindlinks = get_rootlinks(source, as_, BIND_LINK);
}
// Find the rules containing the bindLink in copied_back.
vector<Rule*> matched_rules;
vector<Rule*> rules = fcmem.get_rules();
for (Rule* r : rules) {
auto it = find(chosen_bindlinks.begin(), chosen_bindlinks.end(),
r->get_handle()); //xxx not matching
if (it != chosen_bindlinks.end()) {
matched_rules.push_back(r);
}
}
return matched_rules;
}
/**
* Gets all top level links of certain types and subclasses that
* contain @param hsource
*
* @param hsource handle whose top level links are to be searched
* @param as the atomspace in which search is to be done
* @param link_type the root link types to be searched
* @param subclasses a flag that tells to look subclasses of @link_type
*/
HandleSeq DefaultForwardChainerCB::get_rootlinks(Handle hsource, AtomSpace* as,
Type link_type,
bool subclasses)
{
auto outgoing = [as](Handle h) {return as->getOutgoing(h);};
PLNCommons pc(as);
HandleSeq chosen_roots;
HandleSeq candidates_roots;
pc.get_root_links(hsource, candidates_roots);
for (Handle hr : candidates_roots) {
bool notexist = find(chosen_roots.begin(), chosen_roots.end(), hr)
== chosen_roots.end();
auto type = as->getType(hr);
bool subtype = (subclasses and classserver().isA(type, link_type));
if (((type == link_type) or subtype) and notexist) {
//make sure matches are actually part of the premise list rather than the output of the bindLink
Handle hpremise = outgoing(outgoing(hr)[1])[0]; //extracting premise from (BindLink((ListLinK..)(ImpLink (premise) (..))))
if (pc.exists_in(hpremise, hsource)) {
chosen_roots.push_back(hr);
}
}
}
return chosen_roots;
}
HandleSeq DefaultForwardChainerCB::choose_premises(FCMemory& fcmem)
{
HandleSeq inputs;
PLNCommons pc(as_);
Handle hsource = fcmem.get_cur_source();
// Get everything associated with the source handle.
UnorderedHandleSet neighbors = get_distant_neighbors(hsource, 2);
// Add all root links of atoms in @param neighbors.
for (auto hn : neighbors) {
if (hn->getType() != VARIABLE_NODE) {
HandleSeq roots;
pc.get_root_links(hn, roots);
for (auto r : roots) {
if (find(inputs.begin(), inputs.end(), r) == inputs.end() and r->getType()
!= BIND_LINK)
inputs.push_back(r);
}
}
}
return inputs;
}
Handle DefaultForwardChainerCB::choose_next_source(FCMemory& fcmem)
{
HandleSeq tlist = fcmem.get_premise_list();
map<Handle, float> tournament_elem;
PLNCommons pc(as_);
Handle hchosen = Handle::UNDEFINED;
for (Handle t : tlist) {
switch (ts_mode_) {
case TV_FITNESS_BASED: {
float fitness = pc.tv_fitness(t);
tournament_elem[t] = fitness;
}
break;
case STI_BASED:
tournament_elem[t] = t->getSTI();
break;
default:
throw RuntimeException(TRACE_INFO,
"Unknown source selection mode.");
break;
}
}
//!Choose a new source that has never been chosen before.
//!xxx FIXME since same handle might be chosen multiple times the following
//!code doesn't guarantee all sources have been exhaustively looked.
for (size_t i = 0; i < tournament_elem.size(); i++) {
Handle hselected = pc.tournament_select(tournament_elem);
if (fcmem.isin_source_list(hselected)) {
continue;
} else {
hchosen = hselected;
break;
}
}
return hchosen;
}
//TODO applier should check on atoms (Inference.matched_atoms when Inference.Rule =Cur_Rule), for mutex rules
HandleSeq DefaultForwardChainerCB::apply_rule(FCMemory& fcmem)
{
Rule * cur_rule = fcmem.get_cur_rule();
fcpm_->set_fcmem(&fcmem);
BindLinkPtr bl(BindLinkCast(cur_rule->get_handle()));
fcpm_->implicand = bl->get_implicand();
fcpm_->set_type_restrictions(bl->get_typemap());
bl->imply(fcpm_);
HandleSeq product = fcpm_->get_products();
//! Make sure the inferences made are new.
HandleSeq new_product;
for (auto h : product) {
if (not fcmem.isin_premise_list(h))
new_product.push_back(h);
}
return new_product;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMSolverCrankNicolson.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include "itkFEMSolverCrankNicolson.h"
#include "FEM/itkFEMLoadNode.h"
#include "FEM/itkFEMLoadElementBase.h"
#include "FEM/itkFEMLoadBCMFC.h"
#include "FEM/itkFEMUtility.h"
#include "FEM/itkFEMObjectFactory.h"
namespace itk {
namespace fem {
void SolverCrankNicolson::InitializeForSolution()
{
m_ls->SetSystemOrder(NGFN+NMFC);
m_ls->SetNumberOfVectors(5);
m_ls->SetNumberOfSolutions(2);
m_ls->SetNumberOfMatrices(2);
m_ls->InitializeMatrix(SumMatrixIndex);
m_ls->InitializeMatrix(DifferenceMatrixIndex);
m_ls->InitializeVector(ForceTIndex);
m_ls->InitializeVector(ForceTMinus1Index);
m_ls->InitializeVector(SolutionTMinus1Index);
m_ls->InitializeVector(DiffMatrixBySolutionTMinus1Index);
m_ls->InitializeSolution(SolutionTIndex);
m_ls->InitializeSolution(TotalSolutionIndex);
}
/*
* Assemble the master stiffness matrix (also apply the MFCs to K)
*/
void SolverCrankNicolson::AssembleKandM()
{
// if no DOFs exist in a system, we have nothing to do
if (NGFN<=0) return;
NMFC=0; // number of MFC in a system
// temporary storage for pointers to LoadBCMFC objects
typedef std::vector<LoadBCMFC::Pointer> MFCArray;
MFCArray mfcLoads;
/*
* Before we can start the assembly procedure, we need to know,
* how many boundary conditions (MFCs) there are in a system.
*/
mfcLoads.clear();
// search for MFC's in Loads array, because they affect the master stiffness matrix
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++) {
if ( LoadBCMFC::Pointer l1=dynamic_cast<LoadBCMFC*>( &(*(*l))) ) {
// store the index of an LoadBCMFC object for later
l1->Index=NMFC;
// store the pointer to a LoadBCMFC object for later
mfcLoads.push_back(l1);
// increase the number of MFC
NMFC++;
}
}
/*
* Now we can assemble the master stiffness matrix
* from element stiffness matrices
*/
InitializeForSolution();
std::cout << "Begin Assembly." << std::endl;
/*
* Step over all elements
*/
for(ElementArray::iterator e=el.begin(); e!=el.end(); e++)
{
vnl_matrix<Float> Ke=(*e)->Ke(); /*Copy the element stiffness matrix for faster access. */
vnl_matrix<Float> Me=(*e)->Me(); /*Copy the element mass matrix for faster access. */
int Ne=(*e)->GetNumberOfDegreesOfFreedom(); /*... same for element DOF */
/* step over all rows in in element matrix */
for(int j=0; j<Ne; j++)
{
/* step over all columns in in element matrix */
for(int k=0; k<Ne; k++)
{
/* error checking. all GFN should be =>0 and <NGFN */
if ( (*e)->GetDegreeOfFreedom(j) < 0 ||
(*e)->GetDegreeOfFreedom(j) >= NGFN ||
(*e)->GetDegreeOfFreedom(k) < 0 ||
(*e)->GetDegreeOfFreedom(k) >= NGFN )
{
throw FEMExceptionSolution(__FILE__,__LINE__,"SolverCrankNicolson::AssembleK()","Illegal GFN!");
}
/* Here we finaly update the corresponding element
* in the master stiffness matrix. We first check if
* element in Ke is zero, to prevent zeros from being
* allocated in sparse matrix.
*/
if ( Ke(j,k)!=Float(0.0) || Me(j,k) != Float(0.0) )
{
// left hand side matrix
Float temp1=Ke(j,k), temp2=Me(j,k);
Float lhsval=(Me(j,k) + m_alpha*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
lhsval, SumMatrixIndex );
//if (j==k) std::cout << temp1 << " " << temp2 << endl;
// right hand side matrix
Float rhsval=(Me(j,k) - (1.-m_alpha)*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
rhsval, DifferenceMatrixIndex );
}
}
}
}
// BUG SHOULD DO THIS ABOVE! FIXME
// M=rho*M;
/* step over all types of BCs */
this->ApplyBC(); // BUG -- are BCs applied appropriately to the problem?
std::cout << "Done Assembling." << std::endl;
}
/*
* Assemble the master force vector
*/
void SolverCrankNicolson::AssembleFforTimeStep(int dim) {
/* if no DOFs exist in a system, we have nothing to do */
if (NGFN<=0) return;
unsigned int i=0;
Float temp=0.0;
AssembleF(dim); // assuming assemblef uses index 0 in vector!
typedef std::map<Element::DegreeOfFreedomIDType,Float> BCTermType;
BCTermType bcterm;
/* Step over all Loads */
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++)
{
Load::Pointer l0=*l;
if ( LoadBC::Pointer l1=dynamic_cast<LoadBC*>(&*l0) )
{
bcterm[ l1->m_element->GetDegreeOfFreedom(l1->m_dof) ]=l1->m_value[dim];
}
} // end for LoadArray::iterator l
// Now set the solution t_minus1 vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
m_ls->SetVectorValue(q->first,0.0,SolutionTMinus1Index); //FIXME?
}
m_ls->MultiplyMatrixVector(DiffMatrixBySolutionTMinus1Index,
DifferenceMatrixIndex,SolutionTMinus1Index);
for (unsigned int index=0; index<NGFN; index++) RecomputeForceVector(index);
// Now set the solution and force vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
Float t1=q->first; Float t2=q->second;
m_ls->SetVectorValue(q->first,q->second,ForceTIndex);
}
}
void SolverCrankNicolson::RecomputeForceVector(unsigned int index)
{//
Float ft = m_ls->GetVectorValue(index,ForceTIndex);
Float ftm1 = m_ls->GetVectorValue(index,ForceTMinus1Index);
Float utm1 = m_ls->GetVectorValue(index,DiffMatrixBySolutionTMinus1Index);
m_ls->SetVectorValue(index , m_deltaT*(m_alpha*ftm1+(1.-m_alpha)*ft)+utm1 , ForceTIndex);
m_ls->SetVectorValue(index ,ft,ForceTMinus1Index); // now set t minus one force vector correctly
}
/*
* Solve for the displacement vector u
*/
void SolverCrankNicolson::Solve()
{
std::cout << " begin solve " << std::endl;
/* FIXME - must verify that this is correct use of wrapper */
/* FIXME Initialize the solution vector */
m_ls->InitializeSolution(SolutionTIndex);
m_ls->Solve();
AddToDisplacements();
}
/*
* Copy solution vector u to the corresponding nodal values, which are
* stored in node objects). This is standard post processing of the solution.
*/
void SolverCrankNicolson::AddToDisplacements()
{
/*
* Copy the resulting displacements from
* solution vector back to node objects.
*/
Float mins=0.0, maxs=0.0;
Float mins2=0.0, maxs2=0.0;
for(int i=0;i<NGFN;i++)
{
Float temp=m_ls->GetSolutionValue(i,SolutionTIndex);
if (temp < mins2 ) mins2=temp;
else if (temp > maxs2 ) maxs2=temp;
// note: set rather than add - i.e. last solution of system not total solution
m_ls->SetVectorValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),SolutionTMinus1Index);
m_ls->AddSolutionValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),TotalSolutionIndex);
temp=m_ls->GetSolutionValue(i,TotalSolutionIndex);
if (temp < mins ) mins=temp;
else if (temp > maxs ) maxs=temp;
}
std::cout << " min cur solution val " << mins2 << endl;
std::cout << " max cur solution val " << maxs2 << endl;
std::cout << " min tot solution val " << mins << endl;
std::cout << " max tot solution val " << maxs << endl;
}
void SolverCrankNicolson::PrintDisplacements()
{
cout << " printing current displacements " << endl;
for(int i=0;i<NGFN;i++)
{
cout << m_ls->GetVectorValue(i,SolutionTMinus1Index) << endl;
}
}
void SolverCrankNicolson::PrintForce()
{
cout << " printing current forces " << endl;
for(int i=0;i<NGFN;i++)
{
cout << m_ls->GetVectorValue(i,ForceTIndex) << endl;
}
}
}} // end namespace itk::fem
<commit_msg>fixed some warning messages<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkFEMSolverCrankNicolson.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include "itkFEMSolverCrankNicolson.h"
#include "FEM/itkFEMLoadNode.h"
#include "FEM/itkFEMLoadElementBase.h"
#include "FEM/itkFEMLoadBCMFC.h"
#include "FEM/itkFEMUtility.h"
#include "FEM/itkFEMObjectFactory.h"
namespace itk {
namespace fem {
void SolverCrankNicolson::InitializeForSolution()
{
m_ls->SetSystemOrder(NGFN+NMFC);
m_ls->SetNumberOfVectors(5);
m_ls->SetNumberOfSolutions(2);
m_ls->SetNumberOfMatrices(2);
m_ls->InitializeMatrix(SumMatrixIndex);
m_ls->InitializeMatrix(DifferenceMatrixIndex);
m_ls->InitializeVector(ForceTIndex);
m_ls->InitializeVector(ForceTMinus1Index);
m_ls->InitializeVector(SolutionTMinus1Index);
m_ls->InitializeVector(DiffMatrixBySolutionTMinus1Index);
m_ls->InitializeSolution(SolutionTIndex);
m_ls->InitializeSolution(TotalSolutionIndex);
}
/*
* Assemble the master stiffness matrix (also apply the MFCs to K)
*/
void SolverCrankNicolson::AssembleKandM()
{
// if no DOFs exist in a system, we have nothing to do
if (NGFN<=0) return;
NMFC=0; // number of MFC in a system
// temporary storage for pointers to LoadBCMFC objects
typedef std::vector<LoadBCMFC::Pointer> MFCArray;
MFCArray mfcLoads;
/*
* Before we can start the assembly procedure, we need to know,
* how many boundary conditions (MFCs) there are in a system.
*/
mfcLoads.clear();
// search for MFC's in Loads array, because they affect the master stiffness matrix
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++) {
if ( LoadBCMFC::Pointer l1=dynamic_cast<LoadBCMFC*>( &(*(*l))) ) {
// store the index of an LoadBCMFC object for later
l1->Index=NMFC;
// store the pointer to a LoadBCMFC object for later
mfcLoads.push_back(l1);
// increase the number of MFC
NMFC++;
}
}
/*
* Now we can assemble the master stiffness matrix
* from element stiffness matrices
*/
InitializeForSolution();
std::cout << "Begin Assembly." << std::endl;
/*
* Step over all elements
*/
for(ElementArray::iterator e=el.begin(); e!=el.end(); e++)
{
vnl_matrix<Float> Ke=(*e)->Ke(); /*Copy the element stiffness matrix for faster access. */
vnl_matrix<Float> Me=(*e)->Me(); /*Copy the element mass matrix for faster access. */
int Ne=(*e)->GetNumberOfDegreesOfFreedom(); /*... same for element DOF */
/* step over all rows in in element matrix */
for(int j=0; j<Ne; j++)
{
/* step over all columns in in element matrix */
for(int k=0; k<Ne; k++)
{
/* error checking. all GFN should be =>0 and <NGFN */
if ( (*e)->GetDegreeOfFreedom(j) >= NGFN ||
(*e)->GetDegreeOfFreedom(k) >= NGFN )
{
throw FEMExceptionSolution(__FILE__,__LINE__,"SolverCrankNicolson::AssembleK()","Illegal GFN!");
}
/* Here we finaly update the corresponding element
* in the master stiffness matrix. We first check if
* element in Ke is zero, to prevent zeros from being
* allocated in sparse matrix.
*/
if ( Ke(j,k)!=Float(0.0) || Me(j,k) != Float(0.0) )
{
// left hand side matrix
Float lhsval=(Me(j,k) + m_alpha*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
lhsval, SumMatrixIndex );
// right hand side matrix
Float rhsval=(Me(j,k) - (1.-m_alpha)*m_deltaT*Ke(j,k));
m_ls->AddMatrixValue( (*e)->GetDegreeOfFreedom(j) ,
(*e)->GetDegreeOfFreedom(k),
rhsval, DifferenceMatrixIndex );
}
}
}
}
// BUG SHOULD DO THIS ABOVE! FIXME
// M=rho*M;
/* step over all types of BCs */
this->ApplyBC(); // BUG -- are BCs applied appropriately to the problem?
std::cout << "Done Assembling." << std::endl;
}
/*
* Assemble the master force vector
*/
void SolverCrankNicolson::AssembleFforTimeStep(int dim) {
/* if no DOFs exist in a system, we have nothing to do */
if (NGFN<=0) return;
AssembleF(dim); // assuming assemblef uses index 0 in vector!
typedef std::map<Element::DegreeOfFreedomIDType,Float> BCTermType;
BCTermType bcterm;
/* Step over all Loads */
for(LoadArray::iterator l=load.begin(); l!=load.end(); l++)
{
Load::Pointer l0=*l;
if ( LoadBC::Pointer l1=dynamic_cast<LoadBC*>(&*l0) )
{
bcterm[ l1->m_element->GetDegreeOfFreedom(l1->m_dof) ]=l1->m_value[dim];
}
} // end for LoadArray::iterator l
// Now set the solution t_minus1 vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
m_ls->SetVectorValue(q->first,0.0,SolutionTMinus1Index); //FIXME?
}
m_ls->MultiplyMatrixVector(DiffMatrixBySolutionTMinus1Index,
DifferenceMatrixIndex,SolutionTMinus1Index);
for (unsigned int index=0; index<NGFN; index++) RecomputeForceVector(index);
// Now set the solution and force vector to fit the BCs
for( BCTermType::iterator q=bcterm.begin(); q!=bcterm.end(); q++)
{
m_ls->SetVectorValue(q->first,q->second,ForceTIndex);
}
}
void SolverCrankNicolson::RecomputeForceVector(unsigned int index)
{//
Float ft = m_ls->GetVectorValue(index,ForceTIndex);
Float ftm1 = m_ls->GetVectorValue(index,ForceTMinus1Index);
Float utm1 = m_ls->GetVectorValue(index,DiffMatrixBySolutionTMinus1Index);
m_ls->SetVectorValue(index , m_deltaT*(m_alpha*ftm1+(1.-m_alpha)*ft)+utm1 , ForceTIndex);
m_ls->SetVectorValue(index ,ft,ForceTMinus1Index); // now set t minus one force vector correctly
}
/*
* Solve for the displacement vector u
*/
void SolverCrankNicolson::Solve()
{
std::cout << " begin solve " << std::endl;
/* FIXME - must verify that this is correct use of wrapper */
/* FIXME Initialize the solution vector */
m_ls->InitializeSolution(SolutionTIndex);
m_ls->Solve();
AddToDisplacements();
}
/*
* Copy solution vector u to the corresponding nodal values, which are
* stored in node objects). This is standard post processing of the solution.
*/
void SolverCrankNicolson::AddToDisplacements()
{
/*
* Copy the resulting displacements from
* solution vector back to node objects.
*/
Float mins=0.0, maxs=0.0;
Float mins2=0.0, maxs2=0.0;
for(unsigned int i=0;i<NGFN;i++)
{
Float temp=m_ls->GetSolutionValue(i,SolutionTIndex);
if (temp < mins2 ) mins2=temp;
else if (temp > maxs2 ) maxs2=temp;
// note: set rather than add - i.e. last solution of system not total solution
m_ls->SetVectorValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),SolutionTMinus1Index);
m_ls->AddSolutionValue(i,m_ls->GetSolutionValue(i,SolutionTIndex),TotalSolutionIndex);
temp=m_ls->GetSolutionValue(i,TotalSolutionIndex);
if (temp < mins ) mins=temp;
else if (temp > maxs ) maxs=temp;
}
std::cout << " min cur solution val " << mins2 << endl;
std::cout << " max cur solution val " << maxs2 << endl;
std::cout << " min tot solution val " << mins << endl;
std::cout << " max tot solution val " << maxs << endl;
}
void SolverCrankNicolson::PrintDisplacements()
{
cout << " printing current displacements " << endl;
for(unsigned int i=0;i<NGFN;i++)
{
cout << m_ls->GetVectorValue(i,SolutionTMinus1Index) << endl;
}
}
void SolverCrankNicolson::PrintForce()
{
cout << " printing current forces " << endl;
for(unsigned int i=0;i<NGFN;i++)
{
cout << m_ls->GetVectorValue(i,ForceTIndex) << endl;
}
}
}} // end namespace itk::fem
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merspecifykitinformation.h"
#include "merconstants.h"
#include "merdevicefactory.h"
#include "mersdkkitinformation.h"
#include <utils/pathchooser.h>
#include <projectexplorer/projectexplorerconstants.h>
using namespace ProjectExplorer;
namespace Mer {
namespace Internal {
MerSpecifyKitInformationWidget::MerSpecifyKitInformationWidget(Kit *k) :
KitConfigWidget(k)
{
m_chooser = new Utils::PathChooser;
m_chooser->setExpectedKind(Utils::PathChooser::File);
m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(k));
connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}
QString MerSpecifyKitInformationWidget::displayName() const
{
return tr("Specify:");
}
QString MerSpecifyKitInformationWidget::toolTip() const
{
return tr("Path for specify tool.");
}
void MerSpecifyKitInformationWidget::refresh()
{
if (!m_ignoreChange)
m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(m_kit));
}
void MerSpecifyKitInformationWidget::makeReadOnly()
{
m_chooser->setEnabled(false);
}
bool MerSpecifyKitInformationWidget::visibleInKit()
{
return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(m_kit));
}
QWidget *MerSpecifyKitInformationWidget::mainWidget() const
{
return m_chooser->lineEdit();
}
QWidget *MerSpecifyKitInformationWidget::buttonWidget() const
{
return m_chooser->buttonAtIndex(0);
}
void MerSpecifyKitInformationWidget::pathWasChanged()
{
m_ignoreChange = true;
MerSpecifyKitInformation::setSpecifyPath(m_kit, m_chooser->fileName());
m_ignoreChange = false;
}
MerSpecifyKitInformation::MerSpecifyKitInformation()
{
setObjectName(QLatin1String("MerSpecifyKitInformation"));
}
Core::Id MerSpecifyKitInformation::dataId() const
{
return Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION);
}
unsigned int MerSpecifyKitInformation::priority() const
{
return 23;
}
QVariant MerSpecifyKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k)
return QString();
}
QList<Task> MerSpecifyKitInformation::validate(const Kit *k) const
{
QList<Task> result;
const Utils::FileName file = MerSpecifyKitInformation::specifyPath(k);
if (!file.toFileInfo().isFile()) {
const QString message = QCoreApplication::translate("MerSdk",
"No valid specify tool found");
return QList<Task>() << Task(Task::Error, message, Utils::FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
}
return result;
}
KitConfigWidget *MerSpecifyKitInformation::createConfigWidget(Kit *k) const
{
return new MerSpecifyKitInformationWidget(k);
}
KitInformation::ItemList MerSpecifyKitInformation::toUserOutput(Kit *k) const
{
return ItemList() << qMakePair(tr("Specify"), specifyPath(k).toUserOutput());
}
Utils::FileName MerSpecifyKitInformation::specifyPath(const Kit *k)
{
if (!k)
return Utils::FileName();
return Utils::FileName::fromString(k->value(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION)).toString());
}
void MerSpecifyKitInformation::setSpecifyPath(Kit *k, const Utils::FileName &v)
{
k->setValue(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION), v.toString());
}
} // Internal
} // Mer
<commit_msg>Jolla: Show specify info in kit page for mer kits only<commit_after>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "merspecifykitinformation.h"
#include "merconstants.h"
#include "merdevicefactory.h"
#include "mersdkkitinformation.h"
#include "mersdkmanager.h"
#include <utils/pathchooser.h>
#include <projectexplorer/projectexplorerconstants.h>
using namespace ProjectExplorer;
namespace Mer {
namespace Internal {
MerSpecifyKitInformationWidget::MerSpecifyKitInformationWidget(Kit *k) :
KitConfigWidget(k)
{
m_chooser = new Utils::PathChooser;
m_chooser->setExpectedKind(Utils::PathChooser::File);
m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(k));
connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}
QString MerSpecifyKitInformationWidget::displayName() const
{
return tr("Specify:");
}
QString MerSpecifyKitInformationWidget::toolTip() const
{
return tr("Path for specify tool.");
}
void MerSpecifyKitInformationWidget::refresh()
{
if (!m_ignoreChange)
m_chooser->setFileName(MerSpecifyKitInformation::specifyPath(m_kit));
}
void MerSpecifyKitInformationWidget::makeReadOnly()
{
m_chooser->setEnabled(false);
}
bool MerSpecifyKitInformationWidget::visibleInKit()
{
return MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(m_kit));
}
QWidget *MerSpecifyKitInformationWidget::mainWidget() const
{
return m_chooser->lineEdit();
}
QWidget *MerSpecifyKitInformationWidget::buttonWidget() const
{
return m_chooser->buttonAtIndex(0);
}
void MerSpecifyKitInformationWidget::pathWasChanged()
{
m_ignoreChange = true;
MerSpecifyKitInformation::setSpecifyPath(m_kit, m_chooser->fileName());
m_ignoreChange = false;
}
MerSpecifyKitInformation::MerSpecifyKitInformation()
{
setObjectName(QLatin1String("MerSpecifyKitInformation"));
}
Core::Id MerSpecifyKitInformation::dataId() const
{
return Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION);
}
unsigned int MerSpecifyKitInformation::priority() const
{
return 23;
}
QVariant MerSpecifyKitInformation::defaultValue(Kit *k) const
{
Q_UNUSED(k)
return QString();
}
QList<Task> MerSpecifyKitInformation::validate(const Kit *k) const
{
QList<Task> result;
const Utils::FileName file = MerSpecifyKitInformation::specifyPath(k);
if (MerSdkManager::isMerKit(k) && !file.toFileInfo().isFile()) {
const QString message = QCoreApplication::translate("MerSdk",
"No valid specify tool found");
return QList<Task>() << Task(Task::Error, message, Utils::FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
}
return result;
}
KitConfigWidget *MerSpecifyKitInformation::createConfigWidget(Kit *k) const
{
return new MerSpecifyKitInformationWidget(k);
}
KitInformation::ItemList MerSpecifyKitInformation::toUserOutput(Kit *k) const
{
if (MerDeviceFactory::canCreate(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(k)))
return ItemList() << qMakePair(tr("Specify"), specifyPath(k).toUserOutput());
else
return ProjectExplorer::KitInformation::ItemList();
}
Utils::FileName MerSpecifyKitInformation::specifyPath(const Kit *k)
{
if (!k)
return Utils::FileName();
return Utils::FileName::fromString(k->value(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION)).toString());
}
void MerSpecifyKitInformation::setSpecifyPath(Kit *k, const Utils::FileName &v)
{
k->setValue(Core::Id(Constants::MER_KIT_SPECIFY_INFORMATION), v.toString());
}
} // Internal
} // Mer
<|endoftext|> |
<commit_before>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "cesdkhandler.h"
#include <QtCore/QFile>
#include <QtCore/QDebug>
#include <QtCore/QXmlStreamReader>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
using ProjectExplorer::Environment;
CeSdkInfo::CeSdkInfo()
: m_major(0), m_minor(0)
{
}
void CeSdkInfo::addToEnvironment(Environment &env)
{
qDebug() << "adding " << name() << "to Environment";
env.set("INCLUDE", m_include);
env.set("LIB", m_lib);
env.prependOrSetPath(m_bin);
qDebug()<<e.toStringList();
}
CeSdkHandler::CeSdkHandler()
{
}
QString CeSdkHandler::platformName(const QString &qtpath)
{
QString platformName;
QString CE_SDK;
QString CE_ARCH;
QFile f(qtpath);
if (f.exists() && f.open(QIODevice::ReadOnly)) {
while (!f.atEnd()) {
QByteArray line = f.readLine();
if (line.startsWith("CE_SDK")) {
int index = line.indexOf('=');
if (index >= 0) {
CE_SDK = line.mid(index + 1).trimmed();
}
} else if (line.startsWith("CE_ARCH")) {
int index = line.indexOf('=');
if (index >= 0) {
CE_ARCH = line.mid(index + 1).trimmed();
}
}
if (!CE_SDK.isEmpty() && !CE_ARCH.isEmpty()) {
platformName = CE_SDK + " (" + CE_ARCH + ")";
break;
}
}
}
return platformName;
}
bool CeSdkHandler::parse(const QString &vsdir)
{
// look at the file at %VCInstallDir%/vcpackages/WCE.VCPlatform.config
// and scan through all installed sdks...
m_list.clear();
VCInstallDir = vsdir + "/VC/";
VSInstallDir = vsdir;
QDir vStudioDir(VCInstallDir);
if (!vStudioDir.cd("vcpackages"))
return false;
QFile configFile(vStudioDir.absoluteFilePath(QLatin1String("WCE.VCPlatform.config")));
qDebug()<<"##";
if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly))
return false;
qDebug()<<"parsing";
QString currentElement;
CeSdkInfo currentItem;
QXmlStreamReader xml(&configFile);
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement()) {
currentElement = xml.name().toString();
if (currentElement == QLatin1String("Platform"))
currentItem = CeSdkInfo();
else if (currentElement == QLatin1String("Directories")) {
QXmlStreamAttributes attr = xml.attributes();
currentItem.m_include = fixPaths(attr.value(QLatin1String("Include")).toString());
currentItem.m_lib = fixPaths(attr.value(QLatin1String("Library")).toString());
currentItem.m_bin = fixPaths(attr.value(QLatin1String("Path")).toString());
}
} else if (xml.isEndElement()) {
if (xml.name().toString() == QLatin1String("Platform"))
m_list.append(currentItem);
} else if (xml.isCharacters() && !xml.isWhitespace()) {
if (currentElement == QLatin1String("PlatformName"))
currentItem.m_name = xml.text().toString();
else if (currentElement == QLatin1String("OSMajorVersion"))
currentItem.m_major = xml.text().toString().toInt();
else if (currentElement == QLatin1String("OSMinorVersion"))
currentItem.m_minor = xml.text().toString().toInt();
}
}
if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
return false;
}
return m_list.size() > 0 ? true : false;
}
CeSdkInfo CeSdkHandler::find(const QString &name)
{
qDebug() << "looking for platform " << name;
for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) {
qDebug() << "...." << it->name();
if (it->name() == name)
return *it;
}
return CeSdkInfo();
}
<commit_msg>Fixes: -Wno-undefined would have saved me.<commit_after>/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
**
** Non-Open Source Usage
**
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt GPL Exception
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
**
***************************************************************************/
#include "cesdkhandler.h"
#include <QtCore/QFile>
#include <QtCore/QDebug>
#include <QtCore/QXmlStreamReader>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
using ProjectExplorer::Environment;
CeSdkInfo::CeSdkInfo()
: m_major(0), m_minor(0)
{
}
void CeSdkInfo::addToEnvironment(Environment &env)
{
qDebug() << "adding " << name() << "to Environment";
env.set("INCLUDE", m_include);
env.set("LIB", m_lib);
env.prependOrSetPath(m_bin);
qDebug()<<env.toStringList();
}
CeSdkHandler::CeSdkHandler()
{
}
QString CeSdkHandler::platformName(const QString &qtpath)
{
QString platformName;
QString CE_SDK;
QString CE_ARCH;
QFile f(qtpath);
if (f.exists() && f.open(QIODevice::ReadOnly)) {
while (!f.atEnd()) {
QByteArray line = f.readLine();
if (line.startsWith("CE_SDK")) {
int index = line.indexOf('=');
if (index >= 0) {
CE_SDK = line.mid(index + 1).trimmed();
}
} else if (line.startsWith("CE_ARCH")) {
int index = line.indexOf('=');
if (index >= 0) {
CE_ARCH = line.mid(index + 1).trimmed();
}
}
if (!CE_SDK.isEmpty() && !CE_ARCH.isEmpty()) {
platformName = CE_SDK + " (" + CE_ARCH + ")";
break;
}
}
}
return platformName;
}
bool CeSdkHandler::parse(const QString &vsdir)
{
// look at the file at %VCInstallDir%/vcpackages/WCE.VCPlatform.config
// and scan through all installed sdks...
m_list.clear();
VCInstallDir = vsdir + "/VC/";
VSInstallDir = vsdir;
QDir vStudioDir(VCInstallDir);
if (!vStudioDir.cd("vcpackages"))
return false;
QFile configFile(vStudioDir.absoluteFilePath(QLatin1String("WCE.VCPlatform.config")));
qDebug()<<"##";
if (!configFile.exists() || !configFile.open(QIODevice::ReadOnly))
return false;
qDebug()<<"parsing";
QString currentElement;
CeSdkInfo currentItem;
QXmlStreamReader xml(&configFile);
while (!xml.atEnd()) {
xml.readNext();
if (xml.isStartElement()) {
currentElement = xml.name().toString();
if (currentElement == QLatin1String("Platform"))
currentItem = CeSdkInfo();
else if (currentElement == QLatin1String("Directories")) {
QXmlStreamAttributes attr = xml.attributes();
currentItem.m_include = fixPaths(attr.value(QLatin1String("Include")).toString());
currentItem.m_lib = fixPaths(attr.value(QLatin1String("Library")).toString());
currentItem.m_bin = fixPaths(attr.value(QLatin1String("Path")).toString());
}
} else if (xml.isEndElement()) {
if (xml.name().toString() == QLatin1String("Platform"))
m_list.append(currentItem);
} else if (xml.isCharacters() && !xml.isWhitespace()) {
if (currentElement == QLatin1String("PlatformName"))
currentItem.m_name = xml.text().toString();
else if (currentElement == QLatin1String("OSMajorVersion"))
currentItem.m_major = xml.text().toString().toInt();
else if (currentElement == QLatin1String("OSMinorVersion"))
currentItem.m_minor = xml.text().toString().toInt();
}
}
if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString();
return false;
}
return m_list.size() > 0 ? true : false;
}
CeSdkInfo CeSdkHandler::find(const QString &name)
{
qDebug() << "looking for platform " << name;
for (QList<CeSdkInfo>::iterator it = m_list.begin(); it != m_list.end(); ++it) {
qDebug() << "...." << it->name();
if (it->name() == name)
return *it;
}
return CeSdkInfo();
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmlproject.h"
#include "qmlprojectfile.h"
#include "qmlprojectmanagerconstants.h"
#include "fileformat/qmlprojectitem.h"
#include "qmlprojectrunconfiguration.h"
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/filewatcher.h>
#include <qmljseditor/qmljsmodelmanagerinterface.h>
#include <QTextStream>
#include <QDeclarativeComponent>
#include <QtDebug>
namespace QmlProjectManager {
QmlProject::QmlProject(Internal::Manager *manager, const QString &fileName)
: m_manager(manager),
m_fileName(fileName),
m_modelManager(ExtensionSystem::PluginManager::instance()->getObject<QmlJSEditor::ModelManagerInterface>()),
m_fileWatcher(new ProjectExplorer::FileWatcher(this)),
m_targetFactory(new Internal::QmlProjectTargetFactory(this))
{
setSupportedTargetIds(QSet<QString>() << QLatin1String(Constants::QML_VIEWER_TARGET_ID));
QFileInfo fileInfo(m_fileName);
m_projectName = fileInfo.completeBaseName();
m_file = new Internal::QmlProjectFile(this, fileName);
m_rootNode = new Internal::QmlProjectNode(this, m_file);
m_fileWatcher->addFile(fileName),
connect(m_fileWatcher, SIGNAL(fileChanged(QString)),
this, SLOT(refreshProjectFile()));
m_manager->registerProject(this);
}
QmlProject::~QmlProject()
{
m_manager->unregisterProject(this);
delete m_rootNode;
}
QDir QmlProject::projectDir() const
{
return QFileInfo(file()->fileName()).dir();
}
QString QmlProject::filesFileName() const
{ return m_fileName; }
void QmlProject::parseProject(RefreshOptions options)
{
if (options & Files) {
if (options & ProjectFile)
delete m_projectItem.data();
if (!m_projectItem) {
QFile file(m_fileName);
if (file.open(QFile::ReadOnly)) {
QDeclarativeComponent *component = new QDeclarativeComponent(&m_engine, this);
component->setData(file.readAll(), QUrl::fromLocalFile(m_fileName));
if (component->isReady()
&& qobject_cast<QmlProjectItem*>(component->create())) {
m_projectItem = qobject_cast<QmlProjectItem*>(component->create());
connect(m_projectItem.data(), SIGNAL(qmlFilesChanged(QSet<QString>, QSet<QString>)),
this, SLOT(refreshFiles(QSet<QString>, QSet<QString>)));
connect(m_projectItem.data(), SIGNAL(importPathsChanged()), this, SLOT(refreshImportPaths()));
refreshImportPaths();
} else {
Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
messageManager->printToOutputPane(tr("Error while loading project file!"));
messageManager->printToOutputPane(component->errorString(), true);
}
}
}
if (m_projectItem) {
m_projectItem.data()->setSourceDirectory(projectDir().path());
m_modelManager->updateSourceFiles(m_projectItem.data()->files(), true);
}
m_rootNode->refresh();
}
if (options & Configuration) {
// update configuration
}
if (options & Files)
emit fileListChanged();
}
void QmlProject::refresh(RefreshOptions options)
{
parseProject(options);
if (options & Files)
m_rootNode->refresh();
}
QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
{
const QDir projectDir(QFileInfo(m_fileName).dir());
QStringList absolutePaths;
foreach (const QString &file, paths) {
QFileInfo fileInfo(projectDir, file);
absolutePaths.append(fileInfo.absoluteFilePath());
}
absolutePaths.removeDuplicates();
return absolutePaths;
}
QStringList QmlProject::files() const
{
QStringList files;
if (m_projectItem) {
files = m_projectItem.data()->files();
} else {
files = m_files;
}
return files;
}
bool QmlProject::validProjectFile() const
{
return !m_projectItem.isNull();
}
QStringList QmlProject::importPaths() const
{
QStringList importPaths;
if (m_projectItem)
importPaths = m_projectItem.data()->importPaths();
return importPaths;
}
bool QmlProject::addFiles(const QStringList &filePaths)
{
QStringList toAdd;
foreach (const QString &filePath, filePaths) {
if (!m_projectItem.data()->matchesFile(filePath))
toAdd << filePaths;
}
return toAdd.isEmpty();
}
void QmlProject::refreshProjectFile()
{
refresh(QmlProject::ProjectFile | Files);
}
void QmlProject::refreshFiles(const QSet<QString> &/*added*/, const QSet<QString> &removed)
{
refresh(Files);
if (!removed.isEmpty())
m_modelManager->removeFiles(removed.toList());
}
void QmlProject::refreshImportPaths()
{
m_modelManager->setProjectImportPaths(importPaths());
}
QString QmlProject::displayName() const
{
return m_projectName;
}
QString QmlProject::id() const
{
return QLatin1String("QmlProjectManager.QmlProject");
}
Core::IFile *QmlProject::file() const
{
return m_file;
}
Internal::Manager *QmlProject::projectManager() const
{
return m_manager;
}
QList<ProjectExplorer::Project *> QmlProject::dependsOn()
{
return QList<Project *>();
}
ProjectExplorer::BuildConfigWidget *QmlProject::createConfigWidget()
{
return 0;
}
QList<ProjectExplorer::BuildConfigWidget*> QmlProject::subConfigWidgets()
{
return QList<ProjectExplorer::BuildConfigWidget*>();
}
Internal::QmlProjectTargetFactory *QmlProject::targetFactory() const
{
return m_targetFactory;
}
Internal::QmlProjectTarget *QmlProject::activeTarget() const
{
return static_cast<Internal::QmlProjectTarget *>(Project::activeTarget());
}
Internal::QmlProjectNode *QmlProject::rootProjectNode() const
{
return m_rootNode;
}
QStringList QmlProject::files(FilesMode) const
{
return files();
}
bool QmlProject::fromMap(const QVariantMap &map)
{
if (!Project::fromMap(map))
return false;
if (targets().isEmpty()) {
Internal::QmlProjectTarget *target(targetFactory()->create(this, QLatin1String(Constants::QML_VIEWER_TARGET_ID)));
addTarget(target);
}
refresh(Everything);
// FIXME workaround to guarantee that run/debug actions are enabled if a valid file exists
QmlProjectRunConfiguration *runConfig = static_cast<QmlProjectRunConfiguration*>(activeTarget()->activeRunConfiguration());
if (runConfig)
runConfig->changeCurrentFile(0);
return true;
}
} // namespace QmlProjectManager
<commit_msg>Fix crash when loading a .qmlproject with a custom run configuration<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmlproject.h"
#include "qmlprojectfile.h"
#include "qmlprojectmanagerconstants.h"
#include "fileformat/qmlprojectitem.h"
#include "qmlprojectrunconfiguration.h"
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/filewatcher.h>
#include <qmljseditor/qmljsmodelmanagerinterface.h>
#include <QTextStream>
#include <QDeclarativeComponent>
#include <QtDebug>
namespace QmlProjectManager {
QmlProject::QmlProject(Internal::Manager *manager, const QString &fileName)
: m_manager(manager),
m_fileName(fileName),
m_modelManager(ExtensionSystem::PluginManager::instance()->getObject<QmlJSEditor::ModelManagerInterface>()),
m_fileWatcher(new ProjectExplorer::FileWatcher(this)),
m_targetFactory(new Internal::QmlProjectTargetFactory(this))
{
setSupportedTargetIds(QSet<QString>() << QLatin1String(Constants::QML_VIEWER_TARGET_ID));
QFileInfo fileInfo(m_fileName);
m_projectName = fileInfo.completeBaseName();
m_file = new Internal::QmlProjectFile(this, fileName);
m_rootNode = new Internal::QmlProjectNode(this, m_file);
m_fileWatcher->addFile(fileName),
connect(m_fileWatcher, SIGNAL(fileChanged(QString)),
this, SLOT(refreshProjectFile()));
m_manager->registerProject(this);
}
QmlProject::~QmlProject()
{
m_manager->unregisterProject(this);
delete m_rootNode;
}
QDir QmlProject::projectDir() const
{
return QFileInfo(file()->fileName()).dir();
}
QString QmlProject::filesFileName() const
{ return m_fileName; }
void QmlProject::parseProject(RefreshOptions options)
{
if (options & Files) {
if (options & ProjectFile)
delete m_projectItem.data();
if (!m_projectItem) {
QFile file(m_fileName);
if (file.open(QFile::ReadOnly)) {
QDeclarativeComponent *component = new QDeclarativeComponent(&m_engine, this);
component->setData(file.readAll(), QUrl::fromLocalFile(m_fileName));
if (component->isReady()
&& qobject_cast<QmlProjectItem*>(component->create())) {
m_projectItem = qobject_cast<QmlProjectItem*>(component->create());
connect(m_projectItem.data(), SIGNAL(qmlFilesChanged(QSet<QString>, QSet<QString>)),
this, SLOT(refreshFiles(QSet<QString>, QSet<QString>)));
connect(m_projectItem.data(), SIGNAL(importPathsChanged()), this, SLOT(refreshImportPaths()));
refreshImportPaths();
} else {
Core::MessageManager *messageManager = Core::ICore::instance()->messageManager();
messageManager->printToOutputPane(tr("Error while loading project file!"));
messageManager->printToOutputPane(component->errorString(), true);
}
}
}
if (m_projectItem) {
m_projectItem.data()->setSourceDirectory(projectDir().path());
m_modelManager->updateSourceFiles(m_projectItem.data()->files(), true);
}
m_rootNode->refresh();
}
if (options & Configuration) {
// update configuration
}
if (options & Files)
emit fileListChanged();
}
void QmlProject::refresh(RefreshOptions options)
{
parseProject(options);
if (options & Files)
m_rootNode->refresh();
}
QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
{
const QDir projectDir(QFileInfo(m_fileName).dir());
QStringList absolutePaths;
foreach (const QString &file, paths) {
QFileInfo fileInfo(projectDir, file);
absolutePaths.append(fileInfo.absoluteFilePath());
}
absolutePaths.removeDuplicates();
return absolutePaths;
}
QStringList QmlProject::files() const
{
QStringList files;
if (m_projectItem) {
files = m_projectItem.data()->files();
} else {
files = m_files;
}
return files;
}
bool QmlProject::validProjectFile() const
{
return !m_projectItem.isNull();
}
QStringList QmlProject::importPaths() const
{
QStringList importPaths;
if (m_projectItem)
importPaths = m_projectItem.data()->importPaths();
return importPaths;
}
bool QmlProject::addFiles(const QStringList &filePaths)
{
QStringList toAdd;
foreach (const QString &filePath, filePaths) {
if (!m_projectItem.data()->matchesFile(filePath))
toAdd << filePaths;
}
return toAdd.isEmpty();
}
void QmlProject::refreshProjectFile()
{
refresh(QmlProject::ProjectFile | Files);
}
void QmlProject::refreshFiles(const QSet<QString> &/*added*/, const QSet<QString> &removed)
{
refresh(Files);
if (!removed.isEmpty())
m_modelManager->removeFiles(removed.toList());
}
void QmlProject::refreshImportPaths()
{
m_modelManager->setProjectImportPaths(importPaths());
}
QString QmlProject::displayName() const
{
return m_projectName;
}
QString QmlProject::id() const
{
return QLatin1String("QmlProjectManager.QmlProject");
}
Core::IFile *QmlProject::file() const
{
return m_file;
}
Internal::Manager *QmlProject::projectManager() const
{
return m_manager;
}
QList<ProjectExplorer::Project *> QmlProject::dependsOn()
{
return QList<Project *>();
}
ProjectExplorer::BuildConfigWidget *QmlProject::createConfigWidget()
{
return 0;
}
QList<ProjectExplorer::BuildConfigWidget*> QmlProject::subConfigWidgets()
{
return QList<ProjectExplorer::BuildConfigWidget*>();
}
Internal::QmlProjectTargetFactory *QmlProject::targetFactory() const
{
return m_targetFactory;
}
Internal::QmlProjectTarget *QmlProject::activeTarget() const
{
return static_cast<Internal::QmlProjectTarget *>(Project::activeTarget());
}
Internal::QmlProjectNode *QmlProject::rootProjectNode() const
{
return m_rootNode;
}
QStringList QmlProject::files(FilesMode) const
{
return files();
}
bool QmlProject::fromMap(const QVariantMap &map)
{
if (!Project::fromMap(map))
return false;
if (targets().isEmpty()) {
Internal::QmlProjectTarget *target(targetFactory()->create(this, QLatin1String(Constants::QML_VIEWER_TARGET_ID)));
addTarget(target);
}
refresh(Everything);
// FIXME workaround to guarantee that run/debug actions are enabled if a valid file exists
QmlProjectRunConfiguration *runConfig = qobject_cast<QmlProjectRunConfiguration*>(activeTarget()->activeRunConfiguration());
if (runConfig)
runConfig->changeCurrentFile(0);
return true;
}
} // namespace QmlProjectManager
<|endoftext|> |
<commit_before>#include "pd_view.h"
#include "pd_backend.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <scintilla/include/Scintilla.h>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct SourceCodeData
{
char filename[4096];
int line;
bool requestFiles;
bool hasFiles;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* readFileFromDisk(const char* file, size_t* size)
{
FILE* f = fopen(file, "rb");
uint8_t* data = 0;
size_t s = 0, t = 0;
*size = 0;
if (!f)
return 0;
// TODO: Use fstat here?
fseek(f, 0, SEEK_END);
long ts = ftell(f);
if (ts < 0)
goto end;
s = (size_t)ts;
data = (uint8_t*)malloc(s + 16);
if (!data)
goto end;
fseek(f, 0, SEEK_SET);
t = fread(data, s, 1, f);
(void)t;
data[s] = 0;
*size = s;
end:
fclose(f);
return data;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
(void)uiFuncs;
SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData));
memset(userData, 0, sizeof(SourceCodeData));
userData->requestFiles = false;
userData->hasFiles = false;
// TODO: Temp testing code
//parseFile(&userData->file, "examples/crashing_native/crash2.c");
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
free(userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setExceptionLocation(PDUI* uiFuncs, PDSCInterface* sourceFuncs, SourceCodeData* data, PDReader* inEvents)
{
const char* filename;
uint32_t line;
// TODO: How to show this? Tell user to switch to disassembly view?
if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound)
return;
if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound)
return;
if (strcmp(filename, data->filename))
{
size_t size = 0;
void* fileData = readFileFromDisk(filename, &size);
printf("reading file to buffer %s\n", filename);
(void)uiFuncs;
PDUI_setTitle(uiFuncs, filename);
if (fileData)
{
PDUI_SCSendCommand(sourceFuncs, SCI_CLEARALL, 0, 0);
PDUI_SCSendCommand(sourceFuncs, SCI_ADDTEXT, size, (intptr_t)fileData);
}
else
{
printf("Sourcecode_plugin: Unable to load %s\n", filename);
}
free(fileData);
strncpy(data->filename, filename, sizeof(data->filename));
data->filename[sizeof(data->filename) - 1] = 0;
}
PDUI_SCSendCommand(sourceFuncs, SCI_GOTOLINE, (uintptr_t)line, 0);
data->line = (int)line;
//if (strcmp(filename, data->filename))
// PDUI_setTitle(uiFuncs, filename);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void updateKeyboard(SourceCodeData* data, PDUI* uiFuncs)
{
(void)data;
(void)uiFuncs;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void toggleBreakpointCurrentLine(SourceCodeData* data, PDWriter* writer)
{
(void)data;
(void)writer;
/*
// TODO: Currenty we don't handly if we set breakpoints on a line we can't
PDWrite_eventBegin(writer, PDEventType_setBreakpoint);
PDWrite_string(writer, "filename", data->file.filename);
PDWrite_u32(writer, "line", (unsigned int)data->cursorPos + 1);
PDWrite_eventEnd(writer);
data->file.lines[data->cursorPos].breakpoint = !data->file.lines[data->cursorPos].breakpoint;
*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
uint32_t event;
(void)uiFuncs;
SourceCodeData* data = (SourceCodeData*)userData;
PDSCInterface* sourceFuncs = uiFuncs->scInputText("test", 800, 700, 0, 0);
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setExceptionLocation:
{
setExceptionLocation(uiFuncs, sourceFuncs, data, inEvents);
data->requestFiles = true;
break;
}
case PDEventType_toggleBreakpointCurrentLine:
{
toggleBreakpointCurrentLine(data, writer);
break;
}
case PDEventType_setSourceFiles:
{
// TODO: Store the files
data->hasFiles = true;
break;
}
}
}
updateKeyboard(data, uiFuncs);
PDUI_SCUpdate(sourceFuncs);
PDUI_SCDraw(sourceFuncs);
//showInUI(data, uiFuncs);
PDWrite_eventBegin(writer, PDEventType_getExceptionLocation);
PDWrite_eventEnd(writer);
if (!data->hasFiles && data->requestFiles)
{
printf("requesting files\n");
PDWrite_eventBegin(writer, PDEventType_getSourceFiles);
PDWrite_eventEnd(writer);
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Source Code View",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
<commit_msg>Test of adding fast open shortcut<commit_after>#include "pd_view.h"
#include "pd_backend.h"
#include "pd_host.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <scintilla/include/Scintilla.h>
static const char* s_pluginName = "Source Code View";
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct SourceCodeData
{
char filename[4096];
int line;
bool requestFiles;
bool hasFiles;
uint32_t fastOpenKey;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDSettingsFuncs* s_settings = 0;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* readFileFromDisk(const char* file, size_t* size)
{
FILE* f = fopen(file, "rb");
uint8_t* data = 0;
size_t s = 0, t = 0;
*size = 0;
if (!f)
return 0;
// TODO: Use fstat here?
fseek(f, 0, SEEK_END);
long ts = ftell(f);
if (ts < 0)
goto end;
s = (size_t)ts;
data = (uint8_t*)malloc(s + 16);
if (!data)
goto end;
fseek(f, 0, SEEK_SET);
t = fread(data, s, 1, f);
(void)t;
data[s] = 0;
*size = s;
end:
fclose(f);
return data;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
(void)serviceFunc;
(void)uiFuncs;
SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData));
memset(userData, 0, sizeof(SourceCodeData));
s_settings = (PDSettingsFuncs*)serviceFunc(PDSETTINGS_GLOBAL);
userData->fastOpenKey = s_settings->getShortcut(s_pluginName, "fast_open");
printf("fastOpenKey 0x%x\n", userData->fastOpenKey);
userData->requestFiles = false;
userData->hasFiles = false;
return userData;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void destroyInstance(void* userData)
{
free(userData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void setExceptionLocation(PDUI* uiFuncs, PDSCInterface* sourceFuncs, SourceCodeData* data, PDReader* inEvents)
{
const char* filename;
uint32_t line;
// TODO: How to show this? Tell user to switch to disassembly view?
if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound)
return;
if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound)
return;
if (strcmp(filename, data->filename))
{
size_t size = 0;
void* fileData = readFileFromDisk(filename, &size);
printf("reading file to buffer %s\n", filename);
(void)uiFuncs;
PDUI_setTitle(uiFuncs, filename);
if (fileData)
{
PDUI_SCSendCommand(sourceFuncs, SCI_CLEARALL, 0, 0);
PDUI_SCSendCommand(sourceFuncs, SCI_ADDTEXT, size, (intptr_t)fileData);
}
else
{
printf("Sourcecode_plugin: Unable to load %s\n", filename);
}
free(fileData);
strncpy(data->filename, filename, sizeof(data->filename));
data->filename[sizeof(data->filename) - 1] = 0;
}
PDUI_SCSendCommand(sourceFuncs, SCI_GOTOLINE, (uintptr_t)line, 0);
data->line = (int)line;
//if (strcmp(filename, data->filename))
// PDUI_setTitle(uiFuncs, filename);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void updateKeyboard(SourceCodeData* data, PDUI* uiFuncs)
{
(void)data;
(void)uiFuncs;
if (uiFuncs->isKeyDownId(data->fastOpenKey, 0))
{
printf("do fast open\n");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void toggleBreakpointCurrentLine(SourceCodeData* data, PDWriter* writer)
{
(void)data;
(void)writer;
/*
// TODO: Currenty we don't handly if we set breakpoints on a line we can't
PDWrite_eventBegin(writer, PDEventType_setBreakpoint);
PDWrite_string(writer, "filename", data->file.filename);
PDWrite_u32(writer, "line", (unsigned int)data->cursorPos + 1);
PDWrite_eventEnd(writer);
data->file.lines[data->cursorPos].breakpoint = !data->file.lines[data->cursorPos].breakpoint;
*/
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
uint32_t event;
(void)uiFuncs;
SourceCodeData* data = (SourceCodeData*)userData;
PDSCInterface* sourceFuncs = uiFuncs->scInputText("test", 800, 700, 0, 0);
while ((event = PDRead_getEvent(inEvents)) != 0)
{
switch (event)
{
case PDEventType_setExceptionLocation:
{
setExceptionLocation(uiFuncs, sourceFuncs, data, inEvents);
data->requestFiles = true;
break;
}
case PDEventType_toggleBreakpointCurrentLine:
{
toggleBreakpointCurrentLine(data, writer);
break;
}
case PDEventType_setSourceFiles:
{
// TODO: Store the files
data->hasFiles = true;
break;
}
}
}
updateKeyboard(data, uiFuncs);
PDUI_SCUpdate(sourceFuncs);
PDUI_SCDraw(sourceFuncs);
//showInUI(data, uiFuncs);
PDWrite_eventBegin(writer, PDEventType_getExceptionLocation);
PDWrite_eventEnd(writer);
if (!data->hasFiles && data->requestFiles)
{
printf("requesting files\n");
PDWrite_eventBegin(writer, PDEventType_getSourceFiles);
PDWrite_eventEnd(writer);
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static PDViewPlugin plugin =
{
"Source Code View",
createInstance,
destroyInstance,
update,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
extern "C"
{
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
{
registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
<|endoftext|> |
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include <gflags/gflags.h>
#include <mutex>
#include "xenia/base/main.h"
#include "xenia/base/math.h"
#include "xenia/base/threading.h"
DEFINE_bool(fast_stdout, false,
"Don't lock around stdout/stderr. May introduce weirdness.");
DEFINE_bool(flush_stdout, true, "Flush stdout after each log line.");
DEFINE_bool(log_filenames, false,
"Log filenames/line numbers in log statements.");
namespace xe {
std::mutex log_lock;
void format_log_line(char* buffer, size_t buffer_count, const char* file_path,
const uint32_t line_number, const char level_char,
const char* fmt, va_list args) {
char* buffer_ptr;
if (FLAGS_log_filenames) {
// Strip out just the filename from the path.
const char* filename = strrchr(file_path, xe::path_separator);
if (filename) {
// Slash - skip over it.
filename++;
} else {
// No slash, entire thing is filename.
filename = file_path;
}
// Format string - add a trailing newline if required.
const char* outfmt = "%c> %.2X %s:%d: ";
buffer_ptr = buffer + snprintf(buffer, buffer_count - 1, outfmt, level_char,
xe::threading::current_thread_id(), filename,
line_number);
} else {
buffer_ptr = buffer;
*(buffer_ptr++) = level_char;
*(buffer_ptr++) = '>';
*(buffer_ptr++) = ' ';
buffer_ptr +=
sprintf(buffer_ptr, "%.4X", xe::threading::current_thread_id());
*(buffer_ptr++) = ' ';
}
// Scribble args into the print buffer.
buffer_ptr = buffer_ptr + vsnprintf(buffer_ptr,
buffer_count - (buffer_ptr - buffer) - 1,
fmt, args);
// Add a trailing newline.
if (buffer_ptr[-1] != '\n') {
buffer_ptr[0] = '\n';
buffer_ptr[1] = 0;
}
}
thread_local char log_buffer[2048];
void log_line(const char* file_path, const uint32_t line_number,
const char level_char, const char* fmt, ...) {
// SCOPE_profile_cpu_i("emu", "log_line");
va_list args;
va_start(args, fmt);
format_log_line(log_buffer, xe::countof(log_buffer), file_path, line_number,
level_char, fmt, args);
va_end(args);
if (!FLAGS_fast_stdout) {
log_lock.lock();
}
#if 0 // defined(OutputDebugString)
OutputDebugStringA(log_buffer);
#else
fprintf(stdout, "%s", log_buffer);
if (FLAGS_flush_stdout) {
fflush(stdout);
}
#endif // OutputDebugString
if (!FLAGS_fast_stdout) {
log_lock.unlock();
}
}
void handle_fatal(const char* file_path, const uint32_t line_number,
const char* fmt, ...) {
char buffer[2048];
va_list args;
va_start(args, fmt);
format_log_line(buffer, xe::countof(buffer), file_path, line_number, 'X', fmt,
args);
va_end(args);
if (!FLAGS_fast_stdout) {
log_lock.lock();
}
#if defined(OutputDebugString)
OutputDebugStringA(buffer);
#else
fprintf(stderr, "%s", buffer);
fflush(stderr);
#endif // OutputDebugString
if (!FLAGS_fast_stdout) {
log_lock.unlock();
}
#if XE_PLATFORM_WIN32
if (!xe::has_console_attached()) {
MessageBoxA(NULL, buffer, "Xenia Error",
MB_OK | MB_ICONERROR | MB_APPLMODAL | MB_SETFOREGROUND);
}
#endif // WIN32
exit(1);
}
} // namespace xe
<commit_msg>Make the log buffer stupid large.<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include <gflags/gflags.h>
#include <mutex>
#include "xenia/base/main.h"
#include "xenia/base/math.h"
#include "xenia/base/threading.h"
DEFINE_bool(fast_stdout, false,
"Don't lock around stdout/stderr. May introduce weirdness.");
DEFINE_bool(flush_stdout, true, "Flush stdout after each log line.");
DEFINE_bool(log_filenames, false,
"Log filenames/line numbers in log statements.");
namespace xe {
std::mutex log_lock;
void format_log_line(char* buffer, size_t buffer_count, const char* file_path,
const uint32_t line_number, const char level_char,
const char* fmt, va_list args) {
char* buffer_ptr;
if (FLAGS_log_filenames) {
// Strip out just the filename from the path.
const char* filename = strrchr(file_path, xe::path_separator);
if (filename) {
// Slash - skip over it.
filename++;
} else {
// No slash, entire thing is filename.
filename = file_path;
}
// Format string - add a trailing newline if required.
const char* outfmt = "%c> %.2X %s:%d: ";
buffer_ptr = buffer + snprintf(buffer, buffer_count - 1, outfmt, level_char,
xe::threading::current_thread_id(), filename,
line_number);
} else {
buffer_ptr = buffer;
*(buffer_ptr++) = level_char;
*(buffer_ptr++) = '>';
*(buffer_ptr++) = ' ';
buffer_ptr +=
sprintf(buffer_ptr, "%.4X", xe::threading::current_thread_id());
*(buffer_ptr++) = ' ';
}
// Scribble args into the print buffer.
buffer_ptr = buffer_ptr + vsnprintf(buffer_ptr,
buffer_count - (buffer_ptr - buffer) - 1,
fmt, args);
// Add a trailing newline.
if (buffer_ptr[-1] != '\n') {
buffer_ptr[0] = '\n';
buffer_ptr[1] = 0;
}
}
thread_local char log_buffer[16 * 1024];
void log_line(const char* file_path, const uint32_t line_number,
const char level_char, const char* fmt, ...) {
// SCOPE_profile_cpu_i("emu", "log_line");
va_list args;
va_start(args, fmt);
format_log_line(log_buffer, xe::countof(log_buffer), file_path, line_number,
level_char, fmt, args);
va_end(args);
if (!FLAGS_fast_stdout) {
log_lock.lock();
}
#if 0 // defined(OutputDebugString)
OutputDebugStringA(log_buffer);
#else
fprintf(stdout, "%s", log_buffer);
if (FLAGS_flush_stdout) {
fflush(stdout);
}
#endif // OutputDebugString
if (!FLAGS_fast_stdout) {
log_lock.unlock();
}
}
void handle_fatal(const char* file_path, const uint32_t line_number,
const char* fmt, ...) {
char buffer[2048];
va_list args;
va_start(args, fmt);
format_log_line(buffer, xe::countof(buffer), file_path, line_number, 'X', fmt,
args);
va_end(args);
if (!FLAGS_fast_stdout) {
log_lock.lock();
}
#if defined(OutputDebugString)
OutputDebugStringA(buffer);
#else
fprintf(stderr, "%s", buffer);
fflush(stderr);
#endif // OutputDebugString
if (!FLAGS_fast_stdout) {
log_lock.unlock();
}
#if XE_PLATFORM_WIN32
if (!xe::has_console_attached()) {
MessageBoxA(NULL, buffer, "Xenia Error",
MB_OK | MB_ICONERROR | MB_APPLMODAL | MB_SETFOREGROUND);
}
#endif // WIN32
exit(1);
}
} // namespace xe
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include "paddle/fluid/memory/detail/system_allocator.h"
#ifdef _WIN32
#include <malloc.h>
#include <windows.h> // VirtualLock/VirtualUnlock
#else
#include <sys/mman.h> // for mlock and munlock
#endif
#include <stdlib.h> // for malloc and free
#include <algorithm> // for std::max
#include "gflags/gflags.h"
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/platform/cpu_info.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/gpu_info.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif
DECLARE_bool(use_pinned_memory);
DECLARE_double(fraction_of_gpu_memory_to_use);
DECLARE_uint64(initial_gpu_memory_in_mb);
DECLARE_uint64(reallocate_gpu_memory_in_mb);
namespace paddle {
namespace memory {
namespace detail {
void* AlignedMalloc(size_t size) {
void* p = nullptr;
size_t alignment = 32ul;
#ifdef PADDLE_WITH_MKLDNN
// refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp
// memory alignment
alignment = 4096ul;
#endif
#ifdef _WIN32
p = _aligned_malloc(size, alignment);
#else
PADDLE_ENFORCE_EQ(posix_memalign(&p, alignment, size), 0, "Alloc %ld error!",
size);
#endif
PADDLE_ENFORCE_NOT_NULL(p, "Fail to allocate CPU memory: size = %d .", size);
return p;
}
void* CPUAllocator::Alloc(size_t* index, size_t size) {
// According to http://www.cplusplus.com/reference/cstdlib/malloc/,
// malloc might not return nullptr if size is zero, but the returned
// pointer shall not be dereferenced -- so we make it nullptr.
if (size <= 0) return nullptr;
*index = 0; // unlock memory
void* p = AlignedMalloc(size);
if (p != nullptr) {
if (FLAGS_use_pinned_memory) {
*index = 1;
#ifdef _WIN32
VirtualLock(p, size);
#else
mlock(p, size); // lock memory
#endif
}
}
return p;
}
void CPUAllocator::Free(void* p, size_t size, size_t index) {
if (p != nullptr && index == 1) {
#ifdef _WIN32
VirtualUnlock(p, size);
#else
munlock(p, size);
#endif
}
#ifdef _WIN32
_aligned_free(p);
#else
free(p);
#endif
}
bool CPUAllocator::UseGpu() const { return false; }
#ifdef PADDLE_WITH_CUDA
void* GPUAllocator::Alloc(size_t* index, size_t size) {
// CUDA documentation doesn't explain if cudaMalloc returns nullptr
// if size is 0. We just make sure it does.
if (size <= 0) return nullptr;
paddle::platform::CUDADeviceGuard guard(gpu_id_);
void* p;
cudaError_t result = cudaMalloc(&p, size);
if (result == cudaSuccess) {
*index = 0;
gpu_alloc_size_ += size;
return p;
} else {
PADDLE_THROW_BAD_ALLOC(
"Cannot malloc " + std::to_string(size / 1024.0 / 1024.0) +
" MB GPU memory. Please shrink "
"FLAGS_fraction_of_gpu_memory_to_use or "
"FLAGS_initial_gpu_memory_in_mb or "
"FLAGS_reallocate_gpu_memory_in_mb"
"environment variable to a lower value. " +
"Current FLAGS_fraction_of_gpu_memory_to_use value is " +
std::to_string(FLAGS_fraction_of_gpu_memory_to_use) +
". Current FLAGS_initial_gpu_memory_in_mb value is " +
std::to_string(FLAGS_initial_gpu_memory_in_mb) +
". Current FLAGS_reallocate_gpu_memory_in_mb value is " +
std::to_string(FLAGS_reallocate_gpu_memory_in_mb));
}
}
void GPUAllocator::Free(void* p, size_t size, size_t index) {
cudaError_t err;
PADDLE_ENFORCE_EQ(index, 0);
PADDLE_ENFORCE_GE(gpu_alloc_size_, size);
gpu_alloc_size_ -= size;
err = cudaFree(p);
// Purposefully allow cudaErrorCudartUnloading, because
// that is returned if you ever call cudaFree after the
// driver has already shutdown. This happens only if the
// process is terminating, in which case we don't care if
// cudaFree succeeds.
if (err != cudaErrorCudartUnloading) {
PADDLE_ENFORCE(err, "cudaFree{Host} failed in GPUAllocator::Free.");
}
}
bool GPUAllocator::UseGpu() const { return true; }
// PINNED memory allows direct DMA transfers by the GPU to and from system
// memory. It’s locked to a physical address.
void* CUDAPinnedAllocator::Alloc(size_t* index, size_t size) {
if (size <= 0) return nullptr;
// NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size
// of host pinned allocation. Allocates too much would reduce
// the amount of memory available to the underlying system for paging.
size_t usable =
paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_;
if (size > usable) {
LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0
<< " MB pinned memory."
<< ", available " << usable / 1024.0 / 1024.0 << " MB";
return nullptr;
}
void* p;
// PINNED memory is visible to all CUDA contexts.
cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable);
if (result == cudaSuccess) {
*index = 1; // PINNED memory
cuda_pinnd_alloc_size_ += size;
return p;
} else {
LOG(WARNING) << "cudaHostAlloc failed.";
return nullptr;
}
return nullptr;
}
void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) {
cudaError_t err;
PADDLE_ENFORCE_EQ(index, 1);
PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_, size);
cuda_pinnd_alloc_size_ -= size;
err = cudaFreeHost(p);
// Purposefully allow cudaErrorCudartUnloading, because
// that is returned if you ever call cudaFreeHost after the
// driver has already shutdown. This happens only if the
// process is terminating, in which case we don't care if
// cudaFreeHost succeeds.
if (err != cudaErrorCudartUnloading) {
PADDLE_ENFORCE(err, "cudaFreeHost failed in GPUPinnedAllocator::Free.");
}
}
bool CUDAPinnedAllocator::UseGpu() const { return false; }
#endif
} // namespace detail
} // namespace memory
} // namespace paddle
<commit_msg>fix typo of allocator, test=develop (#19578)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#define GLOG_NO_ABBREVIATED_SEVERITIES
#include "paddle/fluid/memory/detail/system_allocator.h"
#ifdef _WIN32
#include <malloc.h>
#include <windows.h> // VirtualLock/VirtualUnlock
#else
#include <sys/mman.h> // for mlock and munlock
#endif
#include <stdlib.h> // for malloc and free
#include <algorithm> // for std::max
#include "gflags/gflags.h"
#include "paddle/fluid/memory/allocation/allocator.h"
#include "paddle/fluid/platform/cpu_info.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/gpu_info.h"
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/cuda_device_guard.h"
#endif
DECLARE_bool(use_pinned_memory);
DECLARE_double(fraction_of_gpu_memory_to_use);
DECLARE_uint64(initial_gpu_memory_in_mb);
DECLARE_uint64(reallocate_gpu_memory_in_mb);
namespace paddle {
namespace memory {
namespace detail {
void* AlignedMalloc(size_t size) {
void* p = nullptr;
size_t alignment = 32ul;
#ifdef PADDLE_WITH_MKLDNN
// refer to https://github.com/01org/mkl-dnn/blob/master/include/mkldnn.hpp
// memory alignment
alignment = 4096ul;
#endif
#ifdef _WIN32
p = _aligned_malloc(size, alignment);
#else
PADDLE_ENFORCE_EQ(posix_memalign(&p, alignment, size), 0, "Alloc %ld error!",
size);
#endif
PADDLE_ENFORCE_NOT_NULL(p, "Fail to allocate CPU memory: size = %d .", size);
return p;
}
void* CPUAllocator::Alloc(size_t* index, size_t size) {
// According to http://www.cplusplus.com/reference/cstdlib/malloc/,
// malloc might not return nullptr if size is zero, but the returned
// pointer shall not be dereferenced -- so we make it nullptr.
if (size <= 0) return nullptr;
*index = 0; // unlock memory
void* p = AlignedMalloc(size);
if (p != nullptr) {
if (FLAGS_use_pinned_memory) {
*index = 1;
#ifdef _WIN32
VirtualLock(p, size);
#else
mlock(p, size); // lock memory
#endif
}
}
return p;
}
void CPUAllocator::Free(void* p, size_t size, size_t index) {
if (p != nullptr && index == 1) {
#ifdef _WIN32
VirtualUnlock(p, size);
#else
munlock(p, size);
#endif
}
#ifdef _WIN32
_aligned_free(p);
#else
free(p);
#endif
}
bool CPUAllocator::UseGpu() const { return false; }
#ifdef PADDLE_WITH_CUDA
void* GPUAllocator::Alloc(size_t* index, size_t size) {
// CUDA documentation doesn't explain if cudaMalloc returns nullptr
// if size is 0. We just make sure it does.
if (size <= 0) return nullptr;
paddle::platform::CUDADeviceGuard guard(gpu_id_);
void* p;
cudaError_t result = cudaMalloc(&p, size);
if (result == cudaSuccess) {
*index = 0;
gpu_alloc_size_ += size;
return p;
} else {
PADDLE_THROW_BAD_ALLOC(
"Cannot malloc " + std::to_string(size / 1024.0 / 1024.0) +
" MB GPU memory. Please shrink "
"FLAGS_fraction_of_gpu_memory_to_use or "
"FLAGS_initial_gpu_memory_in_mb or "
"FLAGS_reallocate_gpu_memory_in_mb "
"environment variable to a lower value. " +
"Current FLAGS_fraction_of_gpu_memory_to_use value is " +
std::to_string(FLAGS_fraction_of_gpu_memory_to_use) +
". Current FLAGS_initial_gpu_memory_in_mb value is " +
std::to_string(FLAGS_initial_gpu_memory_in_mb) +
". Current FLAGS_reallocate_gpu_memory_in_mb value is " +
std::to_string(FLAGS_reallocate_gpu_memory_in_mb));
}
}
void GPUAllocator::Free(void* p, size_t size, size_t index) {
cudaError_t err;
PADDLE_ENFORCE_EQ(index, 0);
PADDLE_ENFORCE_GE(gpu_alloc_size_, size);
gpu_alloc_size_ -= size;
err = cudaFree(p);
// Purposefully allow cudaErrorCudartUnloading, because
// that is returned if you ever call cudaFree after the
// driver has already shutdown. This happens only if the
// process is terminating, in which case we don't care if
// cudaFree succeeds.
if (err != cudaErrorCudartUnloading) {
PADDLE_ENFORCE(err, "cudaFree{Host} failed in GPUAllocator::Free.");
}
}
bool GPUAllocator::UseGpu() const { return true; }
// PINNED memory allows direct DMA transfers by the GPU to and from system
// memory. It’s locked to a physical address.
void* CUDAPinnedAllocator::Alloc(size_t* index, size_t size) {
if (size <= 0) return nullptr;
// NOTE: here, we use CUDAPinnedMaxAllocSize as the maximum memory size
// of host pinned allocation. Allocates too much would reduce
// the amount of memory available to the underlying system for paging.
size_t usable =
paddle::platform::CUDAPinnedMaxAllocSize() - cuda_pinnd_alloc_size_;
if (size > usable) {
LOG(WARNING) << "Cannot malloc " << size / 1024.0 / 1024.0
<< " MB pinned memory."
<< ", available " << usable / 1024.0 / 1024.0 << " MB";
return nullptr;
}
void* p;
// PINNED memory is visible to all CUDA contexts.
cudaError_t result = cudaHostAlloc(&p, size, cudaHostAllocPortable);
if (result == cudaSuccess) {
*index = 1; // PINNED memory
cuda_pinnd_alloc_size_ += size;
return p;
} else {
LOG(WARNING) << "cudaHostAlloc failed.";
return nullptr;
}
return nullptr;
}
void CUDAPinnedAllocator::Free(void* p, size_t size, size_t index) {
cudaError_t err;
PADDLE_ENFORCE_EQ(index, 1);
PADDLE_ENFORCE_GE(cuda_pinnd_alloc_size_, size);
cuda_pinnd_alloc_size_ -= size;
err = cudaFreeHost(p);
// Purposefully allow cudaErrorCudartUnloading, because
// that is returned if you ever call cudaFreeHost after the
// driver has already shutdown. This happens only if the
// process is terminating, in which case we don't care if
// cudaFreeHost succeeds.
if (err != cudaErrorCudartUnloading) {
PADDLE_ENFORCE(err, "cudaFreeHost failed in GPUPinnedAllocator::Free.");
}
}
bool CUDAPinnedAllocator::UseGpu() const { return false; }
#endif
} // namespace detail
} // namespace memory
} // namespace paddle
<|endoftext|> |
<commit_before>#include "recordserializer.hh"
#include "registrardb-redis.hh"
#include "common.hh"
#include <algorithm>
#include "configmanager.hh"
#include <hiredis/hiredis.h>
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_wait.h>
#include <memory>
using namespace std;
bool sUseSyslog;
struct DumpListener : public RegistrarDbListener {
private:
su_root_t* root;
private:
void su_break(){
if( root ){
su_root_break(root);
}
}
public:
bool listenerError = false;
public:
DumpListener(su_root_t* _root) : RegistrarDbListener(), root(_root) {}
virtual void onRecordFound(Record *record) {
if (record) cout << *record << endl;
else cout << "No record found" << endl;
su_break();
}
virtual void onError() {
SLOGE << "Connection error, aborting" << endl;
listenerError = true;
su_break();
}
virtual void onInvalid() {
SLOGW << "Invalid" << endl;
listenerError = true;
su_break();
}
};
struct CTArgs {
bool debug;
RedisParameters redis;
string serializer;
string url;
static void usage(const char *app) {
CTArgs args;
cout << app << " -t host[" << args.redis.domain << "] "
<< "-p port[" << args.redis.port << "] "
<< "--debug "
<< "-a auth "
<< "-s serializer[" << args.serializer << "] "
<< "sip_uri " << endl;
}
CTArgs() {
debug = false;
redis.port=6379;
redis.timeout = 2000;
redis.domain = "sip";
serializer = "protobuf";
}
void parse(int argc, char **argv) {
#define EQ0(i, name) (strcmp(name, argv[ i ]) == 0)
#define EQ1(i, name) (strcmp(name, argv[ i ]) == 0 && argc > i)
for (int i = 1; i < argc; ++i) {
if (EQ0(i, "--debug")) {
debug = true;
} else if (EQ0(i, "--help") || EQ0(i, "-h")) {
usage(*argv);
exit(0);
} else if (EQ1(i, "-p")) {
redis.port = atoi(argv[++i]);
} else if (EQ1(i, "-t")) {
redis.domain = argv[++i];
} else if (EQ1(i, "-a")) {
redis.auth = argv[++i];
} else if (EQ1(i, "-s")) {
serializer = argv[++i];
if (serializer != "protobuf" && serializer != "c" && serializer != "json") {
cerr << "invalid serializer : " << serializer << endl;
exit(-1);
}
} else {
url = argv[i++];
if (argc > i) {
cerr << "? arg" << i << " " << argv[i] << endl;
usage(*argv);
exit(-1);
}
}
}
if (url.empty()) {
cerr << "specify aor" << endl;
usage(*argv);
exit(-1);
}
}
};
static void timerfunc(su_root_magic_t *magic, su_timer_t *t, Agent *arg){
arg->idle();
}
int main(int argc, char **argv) {
su_home_t home;
su_root_t* root;
sUseSyslog = false;
shared_ptr<Agent> agent;
CTArgs args; args.parse(argc, argv);
flexisip::log::preinit(sUseSyslog, args.debug);
flexisip::log::initLogs(sUseSyslog, args.debug);
flexisip::log::updateFilter("%Severity% >= debug");
Record::sLineFieldNames = {"line"};
Record::sMaxContacts = 10;
su_home_init(&home);
root = su_root_create(NULL);
agent = make_shared<Agent>(root);
auto serializer = unique_ptr<RecordSerializer>(RecordSerializer::create(args.serializer));
auto registrardb = new RegistrarDbRedisAsync("localhost", root, serializer.get(), args.redis);
auto url = url_format(&home,args.url.c_str());
auto listener = make_shared<DumpListener>(root);
registrardb->fetch(url, listener);
su_timer_t* timer = su_timer_create(su_root_task(root),5000);
if( !listener->listenerError ){
su_timer_set_for_ever(timer,(su_timer_f)timerfunc,agent.get());
su_root_run(root);
}
agent.reset();
su_timer_destroy(timer);
su_root_destroy(root);
su_home_destroy(&home);
}
<commit_msg>Fix class member initialization<commit_after>#include "recordserializer.hh"
#include "registrardb-redis.hh"
#include "common.hh"
#include <algorithm>
#include "configmanager.hh"
#include <hiredis/hiredis.h>
#include <sofia-sip/sip_protos.h>
#include <sofia-sip/su_wait.h>
#include <memory>
using namespace std;
bool sUseSyslog;
struct DumpListener : public RegistrarDbListener {
private:
su_root_t* root;
private:
void su_break(){
if( root ){
su_root_break(root);
}
}
public:
bool listenerError;
public:
DumpListener(su_root_t* _root) : RegistrarDbListener(), root(_root), listenerError(false) {}
virtual void onRecordFound(Record *record) {
if (record) cout << *record << endl;
else cout << "No record found" << endl;
su_break();
}
virtual void onError() {
SLOGE << "Connection error, aborting" << endl;
listenerError = true;
su_break();
}
virtual void onInvalid() {
SLOGW << "Invalid" << endl;
listenerError = true;
su_break();
}
};
struct CTArgs {
bool debug;
RedisParameters redis;
string serializer;
string url;
static void usage(const char *app) {
CTArgs args;
cout << app << " -t host[" << args.redis.domain << "] "
<< "-p port[" << args.redis.port << "] "
<< "--debug "
<< "-a auth "
<< "-s serializer[" << args.serializer << "] "
<< "sip_uri " << endl;
}
CTArgs() {
debug = false;
redis.port=6379;
redis.timeout = 2000;
redis.domain = "sip";
serializer = "protobuf";
}
void parse(int argc, char **argv) {
#define EQ0(i, name) (strcmp(name, argv[ i ]) == 0)
#define EQ1(i, name) (strcmp(name, argv[ i ]) == 0 && argc > i)
for (int i = 1; i < argc; ++i) {
if (EQ0(i, "--debug")) {
debug = true;
} else if (EQ0(i, "--help") || EQ0(i, "-h")) {
usage(*argv);
exit(0);
} else if (EQ1(i, "-p")) {
redis.port = atoi(argv[++i]);
} else if (EQ1(i, "-t")) {
redis.domain = argv[++i];
} else if (EQ1(i, "-a")) {
redis.auth = argv[++i];
} else if (EQ1(i, "-s")) {
serializer = argv[++i];
if (serializer != "protobuf" && serializer != "c" && serializer != "json") {
cerr << "invalid serializer : " << serializer << endl;
exit(-1);
}
} else {
url = argv[i++];
if (argc > i) {
cerr << "? arg" << i << " " << argv[i] << endl;
usage(*argv);
exit(-1);
}
}
}
if (url.empty()) {
cerr << "specify aor" << endl;
usage(*argv);
exit(-1);
}
}
};
static void timerfunc(su_root_magic_t *magic, su_timer_t *t, Agent *arg){
arg->idle();
}
int main(int argc, char **argv) {
su_home_t home;
su_root_t* root;
sUseSyslog = false;
shared_ptr<Agent> agent;
CTArgs args; args.parse(argc, argv);
flexisip::log::preinit(sUseSyslog, args.debug);
flexisip::log::initLogs(sUseSyslog, args.debug);
flexisip::log::updateFilter("%Severity% >= debug");
Record::sLineFieldNames = {"line"};
Record::sMaxContacts = 10;
su_home_init(&home);
root = su_root_create(NULL);
agent = make_shared<Agent>(root);
auto serializer = unique_ptr<RecordSerializer>(RecordSerializer::create(args.serializer));
auto registrardb = new RegistrarDbRedisAsync("localhost", root, serializer.get(), args.redis);
auto url = url_format(&home,args.url.c_str());
auto listener = make_shared<DumpListener>(root);
registrardb->fetch(url, listener);
su_timer_t* timer = su_timer_create(su_root_task(root),5000);
if( !listener->listenerError ){
su_timer_set_for_ever(timer,(su_timer_f)timerfunc,agent.get());
su_root_run(root);
}
agent.reset();
su_timer_destroy(timer);
su_root_destroy(root);
su_home_destroy(&home);
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_FUN_LOG_HPP
#define STAN_MATH_REV_FUN_LOG_HPP
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/fun/abs.hpp>
#include <stan/math/rev/fun/arg.hpp>
#include <stan/math/rev/fun/atan2.hpp>
#include <stan/math/rev/fun/cos.hpp>
#include <stan/math/rev/fun/is_inf.hpp>
#include <stan/math/rev/fun/is_nan.hpp>
#include <stan/math/rev/fun/sqrt.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Return the natural log of the specified variable (cmath).
*
* The derivative is defined by
*
* \f$\frac{d}{dx} \log x = \frac{1}{x}\f$.
*
\f[
\mbox{log}(x) =
\begin{cases}
\textrm{NaN} & \mbox{if } x < 0\\
\ln(x) & \mbox{if } x \geq 0 \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{log}(x)}{\partial x} =
\begin{cases}
\textrm{NaN} & \mbox{if } x < 0\\
\frac{1}{x} & \mbox{if } x\geq 0 \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN}
\end{cases}
\f]
*
* @tparam T Arithmetic or a type inheriting from `EigenBase`.
* @param a Variable whose log is taken.
* @return Natural log of variable.
*/
template <typename T, require_stan_scalar_or_eigen_t<T>* = nullptr>
inline auto log(const var_value<T>& a) {
return make_callback_var(log(a.val()), [a](auto& vi) mutable {
as_array_or_scalar(a.adj())
+= as_array_or_scalar(vi.adj()) / as_array_or_scalar(a.val());
});
}
/**
* Return the natural logarithm (base e) of the specified complex argument.
*
* @param z complex argument
* @return natural logarithm of argument
*/
inline std::complex<var> log(const std::complex<var>& z) {
return internal::complex_log(z);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>fix for apply scalar unary<commit_after>#ifndef STAN_MATH_REV_FUN_LOG_HPP
#define STAN_MATH_REV_FUN_LOG_HPP
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/rev/functor/apply_scalar_unary.hpp>
#include <stan/math/rev/fun/abs.hpp>
#include <stan/math/rev/fun/arg.hpp>
#include <stan/math/rev/fun/atan2.hpp>
#include <stan/math/rev/fun/cos.hpp>
#include <stan/math/rev/fun/is_inf.hpp>
#include <stan/math/rev/fun/is_nan.hpp>
#include <stan/math/rev/fun/sqrt.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Return the natural log of the specified variable (cmath).
*
* The derivative is defined by
*
* \f$\frac{d}{dx} \log x = \frac{1}{x}\f$.
*
\f[
\mbox{log}(x) =
\begin{cases}
\textrm{NaN} & \mbox{if } x < 0\\
\ln(x) & \mbox{if } x \geq 0 \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN}
\end{cases}
\f]
\f[
\frac{\partial\, \mbox{log}(x)}{\partial x} =
\begin{cases}
\textrm{NaN} & \mbox{if } x < 0\\
\frac{1}{x} & \mbox{if } x\geq 0 \\[6pt]
\textrm{NaN} & \mbox{if } x = \textrm{NaN}
\end{cases}
\f]
*
* @tparam T Arithmetic or a type inheriting from `EigenBase`.
* @param a Variable whose log is taken.
* @return Natural log of variable.
*/
template <typename T, require_stan_scalar_or_eigen_t<T>* = nullptr>
inline auto log(const var_value<T>& a) {
return make_callback_var(log(a.val()), [a](auto& vi) mutable {
as_array_or_scalar(a.adj())
+= as_array_or_scalar(vi.adj()) / as_array_or_scalar(a.val());
});
}
/**
* Return the natural logarithm (base e) of the specified complex argument.
*
* @param z complex argument
* @return natural logarithm of argument
*/
inline std::complex<var> log(const std::complex<var>& z) {
return internal::complex_log(z);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: applicat.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: fme $ $Date: 2001-08-16 09:14:25 $
*
* 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 APPLICAT_HXX
#define APPLICAT_HXX
class SvxErrorHandler;
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
/**************************************************************************/
/*
**
** MACRO DEFINITION
**
**/
#define SMDLL 1
#define APPLICATIONNAME "smath3"
/**************************************************************************/
/*
**
** CLASS DEFINITION
**
**/
#ifdef WIN
#define RELEASE "WIN304"
#endif
#ifdef PM2
#define RELEASE "PM304"
#endif
#ifdef MAC
#define RELEASE "MAC304"
#endif
#ifdef WNT
#define RELEASE "WNT304"
#endif
#ifdef UNX
#define RELEASE "UNX304"
#endif
#ifndef SMDLL
class SmResId : public ResId
{
public:
SmResId(USHORT nId) :
ResId(nId)
{
}
};
#endif
#ifndef _DLL_
class SmDLL;
class SmApplicat: public SfxApplication
{
protected:
SvxErrorHandler *pSvxErrorHandler;
virtual void OpenClients();
// initialization / deinitialization
virtual void Init();
virtual void Exit();
public:
void Main();
SmApplicat() :
SfxApplication("iso")
{
}
};
#endif
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.456); FILE MERGED 2005/09/05 17:37:21 rt 1.3.456.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: applicat.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 14:57:06 $
*
* 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 APPLICAT_HXX
#define APPLICAT_HXX
class SvxErrorHandler;
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
/**************************************************************************/
/*
**
** MACRO DEFINITION
**
**/
#define SMDLL 1
#define APPLICATIONNAME "smath3"
/**************************************************************************/
/*
**
** CLASS DEFINITION
**
**/
#ifdef WIN
#define RELEASE "WIN304"
#endif
#ifdef PM2
#define RELEASE "PM304"
#endif
#ifdef MAC
#define RELEASE "MAC304"
#endif
#ifdef WNT
#define RELEASE "WNT304"
#endif
#ifdef UNX
#define RELEASE "UNX304"
#endif
#ifndef SMDLL
class SmResId : public ResId
{
public:
SmResId(USHORT nId) :
ResId(nId)
{
}
};
#endif
#ifndef _DLL_
class SmDLL;
class SmApplicat: public SfxApplication
{
protected:
SvxErrorHandler *pSvxErrorHandler;
virtual void OpenClients();
// initialization / deinitialization
virtual void Init();
virtual void Exit();
public:
void Main();
SmApplicat() :
SfxApplication("iso")
{
}
};
#endif
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef APPLICAT_HXX
#define APPLICAT_HXX
class SvxErrorHandler;
#include <sfx2/app.hxx>
/**************************************************************************/
/*
**
** MACRO DEFINITION
**
**/
#define SMDLL 1
#define APPLICATIONNAME "smath3"
/**************************************************************************/
/*
**
** CLASS DEFINITION
**
**/
#ifdef PM2
#define RELEASE "PM304"
#endif
#ifdef WNT
#define RELEASE "WNT304"
#endif
#ifdef UNX
#define RELEASE "UNX304"
#endif
#ifndef SMDLL
class SmResId : public ResId
{
public:
SmResId(USHORT nId) :
ResId(nId)
{
}
};
#endif
#ifndef _DLL_
class SmDLL;
class SmApplicat: public SfxApplication
{
protected:
SvxErrorHandler *pSvxErrorHandler;
virtual void OpenClients();
// initialization / deinitialization
virtual void Init();
virtual void Exit();
public:
void Main();
SmApplicat() :
SfxApplication("iso")
{
}
};
#endif
#endif
<commit_msg>CWS gnumake3: some more fixes for windows and svx; remove superfluous code in starmath that still used old _DLL_ define<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef APPLICAT_HXX
#define APPLICAT_HXX
class SvxErrorHandler;
#include <sfx2/app.hxx>
/**************************************************************************/
/*
**
** MACRO DEFINITION
**
**/
#define SMDLL 1
#define APPLICATIONNAME "smath3"
/**************************************************************************/
/*
**
** CLASS DEFINITION
**
**/
#ifdef PM2
#define RELEASE "PM304"
#endif
#ifdef WNT
#define RELEASE "WNT304"
#endif
#ifdef UNX
#define RELEASE "UNX304"
#endif
#ifndef SMDLL
class SmResId : public ResId
{
public:
SmResId(USHORT nId) :
ResId(nId)
{
}
};
#endif
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: document.hxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: rt $ $Date: 2003-09-19 08:51:11 $
*
* 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 DOCUMENT_HXX
#define DOCUMENT_HXX
#define SMDLL 1
#ifndef _SVSTOR_HXX //autogen
#include <so3/svstor.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFX_INTERNO_HXX //autogen
#include <sfx2/interno.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif
class SmNode;
class SmSymSetManager;
class SfxPrinter;
class Printer;
#ifndef SO2_DECL_SVSTORAGESTREAM_DEFINED
#define SO2_DECL_SVSTORAGESTREAM_DEFINED
SO2_DECL_REF(SvStorageStream)
#endif
#define HINT_DATACHANGED 1004
#define SM30BIDENT ((ULONG)0x534D3033L)
#define SM30IDENT ((ULONG)0x30334d53L)
#define SM304AIDENT ((ULONG)0x34303330L)
#define SM30VERSION ((ULONG)0x00010000L)
#define SM50VERSION ((ULONG)0x00010001L) //Unterschied zur SM30VERSION ist
//der neue Border im Format.
#define FRMIDENT ((ULONG)0x03031963L)
#define FRMVERSION ((ULONG)0x00010001L)
#define STAROFFICE_XML "StarOffice XML (Math)"
#define MATHML_XML "MathML XML (Math)"
/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
* ==========================================================================
*
* Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
* das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
* grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
* einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
* im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
* Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
* (etwa waehrend des Paints).
* Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
* oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
* fuer die der Access auch Friend der DocShell ist.
*/
class SmDocShell;
class EditEngine;
class EditEngineItemPool;
class SmPrinterAccess
{
Printer* pPrinter;
OutputDevice* pRefDev;
public:
SmPrinterAccess( SmDocShell &rDocShell );
~SmPrinterAccess();
Printer* GetPrinter() { return pPrinter; }
OutputDevice* GetRefDev() { return pRefDev; }
};
////////////////////////////////////////////////////////////
class SmDocShell : public SfxObjectShell, public SfxInPlaceObject,
public SfxListener
{
friend class SmPrinterAccess;
String aText;
SmFormat aFormat;
SmParser aInterpreter;
SvStorageStreamRef aDocStream;
String aAccText;
SmSymSetManager *pSymSetMgr;
SmNode *pTree;
SvInPlaceMenuBar *pMenuBar;
SfxMenuBarManager *pMenuMgr;
SfxItemPool *pEditEngineItemPool;
EditEngine *pEditEngine;
SfxPrinter *pPrinter; //Siehe Kommentar zum SmPrinter Access!
Printer *pTmpPrinter; //ebenfalls
long nLeftBorder,
nRightBorder,
nTopBorder,
nBottomBorder;
USHORT nModifyCount;
BOOL bIsFormulaArranged;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType);
void RestartFocusTimer ();
BOOL Try3x( SvStorage *pStor, StreamMode eMode);
BOOL Try2x( SvStorage *pStor, StreamMode eMode);
BOOL WriteAsMathType3( SfxMedium& );
virtual void Draw(OutputDevice *pDevice,
const JobSetup & rSetup,
USHORT nAspect = ASPECT_CONTENT);
virtual void FillClass(SvGlobalName* pClassName,
ULONG* pFormat,
String* pAppName,
String* pFullTypeName,
String* pShortTypeName,
long nFileFormat = SOFFICE_FILEFORMAT_CURRENT) const;
virtual BOOL SetData( const String& rData );
virtual ULONG GetMiscStatus() const;
virtual void OnDocumentPrinterChanged( Printer * );
virtual BOOL InitNew(SvStorage *);
virtual BOOL Load(SvStorage *);
virtual BOOL Insert(SvStorage *);
void ImplSave( SvStorageStreamRef xStrm );
virtual BOOL Save();
virtual BOOL SaveAs( SvStorage *pNewStor );
virtual BOOL ConvertTo( SfxMedium &rMedium );
virtual BOOL SaveCompleted( SvStorage *pNewStor );
virtual void HandsOff();
Printer *GetPrt();
OutputDevice* GetRefDev();
// used to convert the formula text between different office versions
void ConvertText( String &rText, SmConvert eConv );
BOOL IsFormulaArranged() const { return bIsFormulaArranged; }
void SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }
void ArrangeFormula();
virtual BOOL ConvertFrom(SfxMedium &rMedium);
BOOL InsertFrom(SfxMedium &rMedium);
BOOL ImportSM20File(SvStream *pStream);
void UpdateText();
public:
TYPEINFO();
SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1);
SFX_DECL_OBJECTFACTORY(SmDocShell);
SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
virtual ~SmDocShell();
void LoadSymbols();
void SaveSymbols();
//Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
//und fuer die Kommunikation mit dem SFX!
//Alle internen Verwendungen des Printers sollten ausschlieslich uber
//den SmPrinterAccess funktionieren.
BOOL HasPrinter() { return 0 != pPrinter; }
SfxPrinter *GetPrinter() { GetPrt(); return pPrinter; }
void SetPrinter( SfxPrinter * );
const String &GetTitle() const;
const String &GetComment() const;
void SetText(const String& rBuffer);
String& GetText() { return (aText); }
void SetFormat(SmFormat& rFormat);
SmFormat& GetFormat() { return (aFormat); }
void Parse();
SmParser & GetParser() { return aInterpreter; }
const SmNode * GetFormulaTree() const { return pTree; }
void SetFormulaTree(SmNode *&rTree) { pTree = rTree; }
String GetAccessibleText();
EditEngine & GetEditEngine();
SfxItemPool & GetEditEngineItemPool();
SmSymSetManager & GetSymSetManager();
const SmSymSetManager & GetSymSetManager() const
{
return ((SmDocShell *) this)->GetSymSetManager();
}
void Draw(OutputDevice &rDev, Point &rPosition);
Size GetSize();
void Resize();
virtual SfxUndoManager *GetUndoManager ();
virtual SfxItemPool& GetPool();
void Execute( SfxRequest& rReq );
void GetState(SfxItemSet &);
virtual void SetVisArea (const Rectangle & rVisArea);
virtual void UIActivate (BOOL bActivate);
virtual void SetModified(BOOL bModified);
};
#endif
<commit_msg>INTEGRATION: CWS mav09 (1.18.74); FILE MERGED 2004/08/12 17:09:38 mav 1.18.74.5: #i27773# introduce version back 2004/04/29 11:05:05 mba 1.18.74.4: #i27773#: remove so3 2004/04/14 13:24:37 mba 1.18.74.3: #i27773#: remove so3; new storage API 2004/04/14 12:45:30 mba 1.18.74.2: #i27773#: remove so3; new storage API 2004/04/14 12:29:40 mba 1.18.74.1: #i27773#: remove so3; new storage API<commit_after>/*************************************************************************
*
* $RCSfile: document.hxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: kz $ $Date: 2004-10-04 18:02:50 $
*
* 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 DOCUMENT_HXX
#define DOCUMENT_HXX
#define SMDLL 1
#ifndef _SOT_STORAGE_HXX
#include <sot/storage.hxx>
#endif
#ifndef _SOT_SOTREF_HXX //autogen
#include <sot/sotref.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXLSTNER_HXX //autogen
#include <svtools/lstner.hxx>
#endif
#ifndef _SFX_OBJFAC_HXX //autogen
#include <sfx2/docfac.hxx>
#endif
#ifndef _SV_VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _FORMAT_HXX
#include "format.hxx"
#endif
#ifndef PARSE_HXX
#include "parse.hxx"
#endif
#ifndef SMMOD_HXX
#include "smmod.hxx"
#endif
#include <vcl/jobset.hxx>
class SmNode;
class SmSymSetManager;
class SfxPrinter;
class Printer;
#define HINT_DATACHANGED 1004
#define SM30BIDENT ((ULONG)0x534D3033L)
#define SM30IDENT ((ULONG)0x30334d53L)
#define SM304AIDENT ((ULONG)0x34303330L)
#define SM30VERSION ((ULONG)0x00010000L)
#define SM50VERSION ((ULONG)0x00010001L) //Unterschied zur SM30VERSION ist
//der neue Border im Format.
#define FRMIDENT ((ULONG)0x03031963L)
#define FRMVERSION ((ULONG)0x00010001L)
#define STAROFFICE_XML "StarOffice XML (Math)"
#define MATHML_XML "MathML XML (Math)"
/* Zugriff auf den Drucker sollte ausschliesslich ueber diese Klasse erfolgen
* ==========================================================================
*
* Der Drucker kann dem Dokument oder auch dem OLE-Container gehoeren. Wenn
* das Dokument also eine OLE-Dokument ist, so gehoert der Drucker auch
* grundsaetzlich dem Container. Der Container arbeitet aber eventuell mit
* einer anderen MapUnit als der Server. Der Drucker wird bezueglich des MapMode
* im Konstruktor entsprechend eingestellt und im Destruktor wieder restauriert.
* Das bedingt natuerlich, das diese Klasse immer nur kurze Zeit existieren darf
* (etwa waehrend des Paints).
* Die Kontrolle darueber ob der Drucker selbst angelegt, vom Server besorgt
* oder dann auch NULL ist, uebernimmt die DocShell in der Methode GetPrt(),
* fuer die der Access auch Friend der DocShell ist.
*/
class SmDocShell;
class EditEngine;
class EditEngineItemPool;
class SmPrinterAccess
{
Printer* pPrinter;
OutputDevice* pRefDev;
public:
SmPrinterAccess( SmDocShell &rDocShell );
~SmPrinterAccess();
Printer* GetPrinter() { return pPrinter; }
OutputDevice* GetRefDev() { return pRefDev; }
};
////////////////////////////////////////////////////////////
class SmDocShell : public SfxObjectShell, public SfxListener
{
friend class SmPrinterAccess;
String aText;
SmFormat aFormat;
SmParser aInterpreter;
String aAccText;
SmSymSetManager *pSymSetMgr;
SmNode *pTree;
SfxMenuBarManager *pMenuMgr;
SfxItemPool *pEditEngineItemPool;
EditEngine *pEditEngine;
SfxPrinter *pPrinter; //Siehe Kommentar zum SmPrinter Access!
Printer *pTmpPrinter; //ebenfalls
long nLeftBorder,
nRightBorder,
nTopBorder,
nBottomBorder;
USHORT nModifyCount;
BOOL bIsFormulaArranged;
virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType);
void RestartFocusTimer ();
BOOL Try3x( SvStorage *pStor, StreamMode eMode);
BOOL Try2x( SvStorage *pStor, StreamMode eMode);
BOOL WriteAsMathType3( SfxMedium& );
virtual void Draw(OutputDevice *pDevice,
const JobSetup & rSetup,
USHORT nAspect = ASPECT_CONTENT);
virtual void FillClass(SvGlobalName* pClassName,
ULONG* pFormat,
String* pAppName,
String* pFullTypeName,
String* pShortTypeName,
sal_Int32 nFileFormat ) const;
virtual BOOL SetData( const String& rData );
virtual ULONG GetMiscStatus() const;
virtual void OnDocumentPrinterChanged( Printer * );
virtual sal_Bool InitNew( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL Load( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL Insert( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
void ImplSave( SvStorageStreamRef xStrm );
virtual BOOL Save();
virtual BOOL SaveAs( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
virtual BOOL ConvertTo( SfxMedium &rMedium );
virtual BOOL SaveCompleted( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage );
Printer *GetPrt();
OutputDevice* GetRefDev();
// used to convert the formula text between different office versions
void ConvertText( String &rText, SmConvert eConv );
BOOL IsFormulaArranged() const { return bIsFormulaArranged; }
void SetFormulaArranged(BOOL bVal) { bIsFormulaArranged = bVal; }
void ArrangeFormula();
virtual BOOL ConvertFrom(SfxMedium &rMedium);
BOOL InsertFrom(SfxMedium &rMedium);
BOOL ImportSM20File(SvStream *pStream);
void UpdateText();
public:
TYPEINFO();
SFX_DECL_INTERFACE(SFX_INTERFACE_SMA_START+1);
SFX_DECL_OBJECTFACTORY();
SmDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
virtual ~SmDocShell();
void LoadSymbols();
void SaveSymbols();
//Zugriff fuer die View. Diese Zugriffe sind nur fuer den nicht OLE-Fall!
//und fuer die Kommunikation mit dem SFX!
//Alle internen Verwendungen des Printers sollten ausschlieslich uber
//den SmPrinterAccess funktionieren.
BOOL HasPrinter() { return 0 != pPrinter; }
SfxPrinter *GetPrinter() { GetPrt(); return pPrinter; }
void SetPrinter( SfxPrinter * );
const String &GetTitle() const;
const String &GetComment() const;
void SetText(const String& rBuffer);
String& GetText() { return (aText); }
void SetFormat(SmFormat& rFormat);
SmFormat& GetFormat() { return (aFormat); }
void Parse();
SmParser & GetParser() { return aInterpreter; }
const SmNode * GetFormulaTree() const { return pTree; }
void SetFormulaTree(SmNode *&rTree) { pTree = rTree; }
String GetAccessibleText();
EditEngine & GetEditEngine();
SfxItemPool & GetEditEngineItemPool();
SmSymSetManager & GetSymSetManager();
const SmSymSetManager & GetSymSetManager() const
{
return ((SmDocShell *) this)->GetSymSetManager();
}
void Draw(OutputDevice &rDev, Point &rPosition);
Size GetSize();
void Resize();
virtual SfxUndoManager *GetUndoManager ();
virtual SfxItemPool& GetPool();
void Execute( SfxRequest& rReq );
void GetState(SfxItemSet &);
virtual void SetVisArea (const Rectangle & rVisArea);
virtual void UIActivate (BOOL bActivate);
virtual void SetModified(BOOL bModified);
};
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2013 CoDyCo Project
* Author: Silvio Traversaro
* website: http://www.codyco.eu
*/
#include "kdl_codyco/treepartition.hpp"
#include <kdl/joint.hpp>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
#include "kdl_codyco/utils.hpp"
#include "kdl_codyco/config.h"
namespace KDL {
namespace CoDyCo {
/*
int TreePart::getLocalPartIndex(const std::string part_name)
{
std::map<std::string,int>::const_iterator it_si = name_map.find(part_name);
if( it_si == name_map.end() ) { return -1; }
int part_id = it_si->second;
std::map<int,int>::const_iterator it_ii = ID_map.find(part_id);
if( it_ii == ID_map.end() ) { return -1; }
int part_local_index = it_ii->second;
return part_local_index;
}*/
TreePart::TreePart(): part_id(-1), part_name("TreePartError"), dof_id(0), links_id(0)
{
}
TreePart::TreePart(int _part_id, std::string _part_name): part_id(_part_id), part_name(_part_name), dof_id(0), links_id(0)
{
}
TreePart::TreePart(int _part_id, std::string _part_name, std::vector<int> _dof_id, std::vector<int> _links_id): part_id(_part_id), part_name(_part_name), dof_id(_dof_id), links_id(_links_id)
{
}
TreePart::~TreePart()
{
}
TreePart& TreePart::operator=(const TreePart& x)
{
if ( this != &x ) {
this->part_id = x.part_id;
this->part_name = x.part_name;
this->dof_id = x.dof_id;
this->links_id = x.links_id;
}
return *this;
}
int TreePart::getNrOfLinks() const
{
return links_id.size();
}
int TreePart::getNrOfDOFs() const
{
return dof_id.size();
}
std::string TreePart::getPartName() const
{
return part_name;
}
int TreePart::getPartID() const
{
return part_id;
}
std::string TreePart::toString() const
{
std::stringstream ss;
ss << "TreePart: " << part_id << " " << part_name << std::endl;
ss << "Links: " << std::endl;
for(int link = 0; link < getNrOfLinks(); link++ ) {
ss << "Local link " << link << " is global link " << links_id[link] << std::endl;
}
ss << "Joints: " << std::endl;
for(int joint = 0; joint < getNrOfDOFs(); joint++ ) {
ss << "Local dof id " << joint << " is global dof " << dof_id[joint] << std::endl;
}
return ss.str();
}
TreePartition::TreePartition()
{
}
TreePartition::~TreePartition()
{
}
TreePartition::TreePartition(const Tree & tree)
{
int nrOfDOFs = tree.getNrOfJoints();
int nrOfLinks = tree.getNrOfSegments();
TreePart tree_part(0,"default_part");
SegmentMap::const_iterator root = tree.getRootSegment();
/** \todo remove this assumption */
assert(GetTreeElementChildren(root->second).size() != 0);
// SegmentMap::const_iterator root_child = root->second.children[0];
//This should be coherent with the behaviour of UndirectedTree
if( !isBaseLinkFake(tree) )
{
nrOfLinks++;
}
for(int i=0; i <nrOfDOFs; i++ )
{
tree_part.addDOF(i);
}
for(int i=0; i <nrOfLinks; i++ )
{
tree_part.addLink(i);
}
addPart(tree_part);
}
bool TreePartition::addPart(TreePart & tree_part)
{
int part_index = parts.size();
parts.push_back(tree_part);
ID_map.insert(std::make_pair(tree_part.getPartID(),part_index));
name_map.insert(std::make_pair(tree_part.getPartName(),part_index));
return true;
}
TreePart TreePartition::getPart(int id) const
{
int local_index;
std::map<int,int>::const_iterator it = ID_map.find(id);
if( it == ID_map.end() ) {
return TreePart();
}
local_index = it->second;
return parts[local_index];
}
TreePart TreePartition::getPart(const std::string & part_name) const
{
int local_index;
std::map<std::string,int>::const_iterator it = name_map.find(part_name);
if( it == name_map.end() ) {
return TreePart();
}
local_index = it->second;
return parts[local_index];
}
int TreePartition::getPartIDfromPartName(const std::string & part_name) const
{
int local_index;
std::map<std::string,int>::const_iterator it = name_map.find(part_name);
if( it == name_map.end() ) {
return -1;
}
local_index = it->second;
return parts[local_index].getPartID();
}
int TreePartition::getPartIDfromLink(int link_id) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
if( parts[i].getGlobalLinkIndex(j) == link_id ) {
return parts[i].getPartID();
}
}
}
return -1;
}
int TreePartition::getPartIDfromDOF(int dof_id) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
if( parts[i].getGlobalDOFIndex(j) == dof_id ) {
return parts[i].getPartID();
}
}
}
return -1;
}
int TreePartition::getGlobalLinkIndex(int part_ID, int local_link_index) const
{
int local_index;
std::map<int,int>::const_iterator it = ID_map.find(part_ID);
if( it == ID_map.end() ) {
return -1;
}
local_index = it->second;
if( local_link_index >= parts[local_index].getNrOfLinks() || local_link_index < 0 ) return -2;
return parts[local_index].getGlobalLinkIndex(local_link_index);
}
int TreePartition::getGlobalDOFIndex(int part_ID, int local_DOF_index) const
{
int local_index;
std::map<int,int>::const_iterator it = ID_map.find(part_ID);
if( it == ID_map.end() ) {
return -1;
}
local_index = it->second;
return parts[local_index].getGlobalDOFIndex(local_DOF_index);
}
int TreePartition::getLocalLinkIndex(int global_link_index) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
if( parts[i].getGlobalLinkIndex(j) == global_link_index ) {
return j;
}
}
}
return -1;
}
int TreePartition::getLocalDOFIndex(int global_dof_index) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
if( parts[i].getGlobalDOFIndex(j) == global_dof_index) {
return j;
}
}
}
return -1;
}
/**
* Check if the TreePartition is a valid partition for the
* given Tree (and optionally the given TreeSerialization )
*
*/
bool TreePartition::is_consistent(const Tree & tree ) const
{
return is_consistent(tree,TreeSerialization(tree));
}
bool TreePartition::is_consistent(const Tree & tree, TreeSerialization tree_serialization) const
{
if( !tree_serialization.is_consistent(tree) ) return false;
int total_links = 0;
for(int i=0; i < (int)parts.size(); i++ ) {
TreePart part = parts[i];
if( part.getNrOfLinks() <= 0 ) return false;
total_links += part.getNrOfLinks();
}
if( total_links != (int)tree.getNrOfSegments() ) return false;
if( ID_map.size() != parts.size() ) { return false; }
if( name_map.size() != parts.size() ) { return false; }
/**
* \todo add link/joint id level serialization
*/
return true;
}
/**
* \todo add efficient way of returning vector<int>
*
*/
std::vector<int> TreePartition::getPartLinkIDs(const std::string & part_name) const
{
//\todo error checking
TreePart part = getPart(part_name);
return part.getLinkIDs();
}
/**
* \todo add efficient way of returning vector<int>
*
*/
std::vector<int> TreePartition::getPartDOFIDs(const std::string & part_name) const
{
std::vector<int> ret;
#ifndef NDEBUG
//std::cout << "getPartDOFIDs(" << part_name <<")" << std::endl;
#endif
TreePart part = getPart(part_name);
ret = part.getDOFIDs();
#ifndef NDEBUG
//std::cout << part.toString() << std::endl;
//std::cout << "has " << ret.size() << " DOFs " << std::endl;
#endif
return ret;
}
std::string TreePartition::toString() const
{
std::stringstream ss;
for(int i=0; i < (int)parts.size(); i++ ) {
ss << parts[i].toString() << std::endl;
int part_id = parts[i].getPartID();
std::map<int,int>::const_iterator it = ID_map.find(part_id);
int local_vector_index = it->second;
ss << "Part with ID " << parts[i].getPartID() << " has index in local part vector" << local_vector_index << std::endl;
}
return ss.str();
}
}
}
<commit_msg>Added assertion in treepartition method<commit_after>/**
* Copyright (C) 2013 CoDyCo Project
* Author: Silvio Traversaro
* website: http://www.codyco.eu
*/
#include "kdl_codyco/treepartition.hpp"
#include <kdl/joint.hpp>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <sstream>
#include "kdl_codyco/utils.hpp"
#include "kdl_codyco/config.h"
namespace KDL {
namespace CoDyCo {
/*
int TreePart::getLocalPartIndex(const std::string part_name)
{
std::map<std::string,int>::const_iterator it_si = name_map.find(part_name);
if( it_si == name_map.end() ) { return -1; }
int part_id = it_si->second;
std::map<int,int>::const_iterator it_ii = ID_map.find(part_id);
if( it_ii == ID_map.end() ) { return -1; }
int part_local_index = it_ii->second;
return part_local_index;
}*/
TreePart::TreePart(): part_id(-1), part_name("TreePartError"), dof_id(0), links_id(0)
{
}
TreePart::TreePart(int _part_id, std::string _part_name): part_id(_part_id), part_name(_part_name), dof_id(0), links_id(0)
{
}
TreePart::TreePart(int _part_id, std::string _part_name, std::vector<int> _dof_id, std::vector<int> _links_id): part_id(_part_id), part_name(_part_name), dof_id(_dof_id), links_id(_links_id)
{
}
TreePart::~TreePart()
{
}
TreePart& TreePart::operator=(const TreePart& x)
{
if ( this != &x ) {
this->part_id = x.part_id;
this->part_name = x.part_name;
this->dof_id = x.dof_id;
this->links_id = x.links_id;
}
return *this;
}
int TreePart::getNrOfLinks() const
{
return links_id.size();
}
int TreePart::getNrOfDOFs() const
{
return dof_id.size();
}
std::string TreePart::getPartName() const
{
return part_name;
}
int TreePart::getPartID() const
{
return part_id;
}
std::string TreePart::toString() const
{
std::stringstream ss;
ss << "TreePart: " << part_id << " " << part_name << std::endl;
ss << "Links: " << std::endl;
for(int link = 0; link < getNrOfLinks(); link++ ) {
ss << "Local link " << link << " is global link " << links_id[link] << std::endl;
}
ss << "Joints: " << std::endl;
for(int joint = 0; joint < getNrOfDOFs(); joint++ ) {
ss << "Local dof id " << joint << " is global dof " << dof_id[joint] << std::endl;
}
return ss.str();
}
TreePartition::TreePartition()
{
}
TreePartition::~TreePartition()
{
}
TreePartition::TreePartition(const Tree & tree)
{
int nrOfDOFs = tree.getNrOfJoints();
int nrOfLinks = tree.getNrOfSegments();
TreePart tree_part(0,"default_part");
SegmentMap::const_iterator root = tree.getRootSegment();
/** \todo remove this assumption */
assert(GetTreeElementChildren(root->second).size() != 0);
// SegmentMap::const_iterator root_child = root->second.children[0];
//This should be coherent with the behaviour of UndirectedTree
if( !isBaseLinkFake(tree) )
{
nrOfLinks++;
}
for(int i=0; i <nrOfDOFs; i++ )
{
tree_part.addDOF(i);
}
for(int i=0; i <nrOfLinks; i++ )
{
tree_part.addLink(i);
}
addPart(tree_part);
}
bool TreePartition::addPart(TreePart & tree_part)
{
int part_index = parts.size();
parts.push_back(tree_part);
ID_map.insert(std::make_pair(tree_part.getPartID(),part_index));
name_map.insert(std::make_pair(tree_part.getPartName(),part_index));
return true;
}
TreePart TreePartition::getPart(int id) const
{
int local_index;
std::map<int,int>::const_iterator it = ID_map.find(id);
if( it == ID_map.end() ) {
return TreePart();
}
local_index = it->second;
return parts[local_index];
}
TreePart TreePartition::getPart(const std::string & part_name) const
{
int local_index;
std::map<std::string,int>::const_iterator it = name_map.find(part_name);
if( it == name_map.end() ) {
return TreePart();
}
local_index = it->second;
return parts[local_index];
}
int TreePartition::getPartIDfromPartName(const std::string & part_name) const
{
int local_index;
std::map<std::string,int>::const_iterator it = name_map.find(part_name);
if( it == name_map.end() ) {
return -1;
}
local_index = it->second;
return parts[local_index].getPartID();
}
int TreePartition::getPartIDfromLink(int link_id) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
if( parts[i].getGlobalLinkIndex(j) == link_id ) {
return parts[i].getPartID();
}
}
}
return -1;
}
int TreePartition::getPartIDfromDOF(int dof_id) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
if( parts[i].getGlobalDOFIndex(j) == dof_id ) {
return parts[i].getPartID();
}
}
}
return -1;
}
int TreePartition::getGlobalLinkIndex(int part_ID, int local_link_index) const
{
int local_index;
std::map<int,int>::const_iterator it = ID_map.find(part_ID);
if( it == ID_map.end() ) {
return -1;
}
local_index = it->second;
if( local_link_index >= parts[local_index].getNrOfLinks() || local_link_index < 0 ) return -2;
return parts[local_index].getGlobalLinkIndex(local_link_index);
}
int TreePartition::getGlobalDOFIndex(int part_ID, int local_DOF_index) const
{
int local_index;
assert(ID_map.size() == parts.size());
std::map<int,int>::const_iterator it = ID_map.find(part_ID);
if( it == ID_map.end() ) {
return -1;
}
local_index = it->second;
return parts[local_index].getGlobalDOFIndex(local_DOF_index);
}
int TreePartition::getLocalLinkIndex(int global_link_index) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfLinks(); j++ ) {
if( parts[i].getGlobalLinkIndex(j) == global_link_index ) {
return j;
}
}
}
return -1;
}
int TreePartition::getLocalDOFIndex(int global_dof_index) const
{
for(int i=0; i < (int)parts.size(); i++ ) {
for( int j=0; j < parts[i].getNrOfDOFs(); j++ ) {
if( parts[i].getGlobalDOFIndex(j) == global_dof_index) {
return j;
}
}
}
return -1;
}
/**
* Check if the TreePartition is a valid partition for the
* given Tree (and optionally the given TreeSerialization )
*
*/
bool TreePartition::is_consistent(const Tree & tree ) const
{
return is_consistent(tree,TreeSerialization(tree));
}
bool TreePartition::is_consistent(const Tree & tree, TreeSerialization tree_serialization) const
{
if( !tree_serialization.is_consistent(tree) ) return false;
int total_links = 0;
for(int i=0; i < (int)parts.size(); i++ ) {
TreePart part = parts[i];
if( part.getNrOfLinks() <= 0 ) return false;
total_links += part.getNrOfLinks();
}
if( total_links != (int)tree.getNrOfSegments() ) return false;
if( ID_map.size() != parts.size() ) { return false; }
if( name_map.size() != parts.size() ) { return false; }
/**
* \todo add link/joint id level serialization
*/
return true;
}
/**
* \todo add efficient way of returning vector<int>
*
*/
std::vector<int> TreePartition::getPartLinkIDs(const std::string & part_name) const
{
//\todo error checking
TreePart part = getPart(part_name);
return part.getLinkIDs();
}
/**
* \todo add efficient way of returning vector<int>
*
*/
std::vector<int> TreePartition::getPartDOFIDs(const std::string & part_name) const
{
std::vector<int> ret;
#ifndef NDEBUG
//std::cout << "getPartDOFIDs(" << part_name <<")" << std::endl;
#endif
TreePart part = getPart(part_name);
ret = part.getDOFIDs();
#ifndef NDEBUG
//std::cout << part.toString() << std::endl;
//std::cout << "has " << ret.size() << " DOFs " << std::endl;
#endif
return ret;
}
std::string TreePartition::toString() const
{
std::stringstream ss;
for(int i=0; i < (int)parts.size(); i++ ) {
ss << parts[i].toString() << std::endl;
int part_id = parts[i].getPartID();
std::map<int,int>::const_iterator it = ID_map.find(part_id);
int local_vector_index = it->second;
ss << "Part with ID " << parts[i].getPartID() << " has index in local part vector" << local_vector_index << std::endl;
}
return ss.str();
}
}
}
<|endoftext|> |
<commit_before>
#include <ctype.h>
#include <iostream>
#include <boost/regex.hpp>
#include "storage/Devices/MdImpl.h"
#include "storage/Holders/MdUser.h"
#include "storage/Devicegraph.h"
#include "storage/Action.h"
#include "storage/Storage.h"
#include "storage/Environment.h"
#include "storage/SystemInfo/SystemInfo.h"
#include "storage/Utils/Exception.h"
#include "storage/Utils/Enum.h"
#include "storage/Utils/StorageTmpl.h"
#include "storage/Utils/StorageTypes.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Utils/StorageTmpl.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Md>::classname = "Md";
Md::Impl::Impl(const xmlNode* node)
: Partitionable::Impl(node)
{
string tmp;
if (getChildValue(node, "md-level", tmp))
md_level = toValueWithFallback(tmp, RAID0);
if (getChildValue(node, "md-parity", tmp))
md_parity = toValueWithFallback(tmp, PAR_DEFAULT);
getChildValue(node, "chunk-size-k", chunk_size_k);
}
void
Md::Impl::set_md_level(MdType md_level)
{
// TODO calculate size_k
Impl::md_level = md_level;
}
void
Md::Impl::set_chunk_size_k(unsigned long chunk_size_k)
{
// TODO calculate size_k
Impl::chunk_size_k = chunk_size_k;
}
bool
Md::Impl::is_valid_name(const string& name)
{
static boost::regex name_regex(DEVDIR "/md[0-9]+", boost::regex_constants::extended);
return boost::regex_match(name, name_regex);
}
vector<string>
Md::Impl::probe_mds(SystemInfo& systeminfo)
{
vector<string> ret;
for (const string& short_name : systeminfo.getDir(SYSFSDIR "/block"))
{
string name = DEVDIR "/" + short_name;
if (!is_valid_name(name))
continue;
ret.push_back(name);
}
return ret;
}
void
Md::Impl::probe(Devicegraph* probed, SystemInfo& systeminfo)
{
Partitionable::Impl::probe(systeminfo);
string tmp = get_name().substr(strlen(DEVDIR "/"));
ProcMdstat::Entry entry;
if (!systeminfo.getProcMdstat().getEntry(tmp, entry))
{
// TODO
throw;
}
md_level = entry.md_level;
md_parity = entry.md_parity;
chunk_size_k = entry.chunk_size_k;
for (const string& device : entry.devices)
{
BlkDevice* blk_device = BlkDevice::find(probed, device);
MdUser* md_user = MdUser::create(probed, blk_device, get_device());
md_user->set_spare(false);
}
for (const string& device : entry.spares)
{
BlkDevice* blk_device = BlkDevice::find(probed, device);
MdUser* md_user = MdUser::create(probed, blk_device, get_device());
md_user->set_spare(true);
}
}
void
Md::Impl::save(xmlNode* node) const
{
Partitionable::Impl::save(node);
setChildValue(node, "md-level", toString(md_level));
setChildValueIf(node, "md-parity", toString(md_parity), md_parity != PAR_DEFAULT);
setChildValueIf(node, "chunk-size-k", chunk_size_k, chunk_size_k != 0);
}
MdUser*
Md::Impl::add_device(BlkDevice* blk_device)
{
if (blk_device->num_children() != 0)
ST_THROW(WrongNumberOfChildren(blk_device->num_children(), 0));
// TODO calculate size_k
// TODO set partition id?
return MdUser::create(get_devicegraph(), blk_device, get_device());
}
vector<BlkDevice*>
Md::Impl::get_devices()
{
Devicegraph::Impl& devicegraph = get_devicegraph()->get_impl();
Devicegraph::Impl::vertex_descriptor vertex = get_vertex();
return devicegraph.filter_devices_of_type<BlkDevice>(devicegraph.parents(vertex));
}
vector<const BlkDevice*>
Md::Impl::get_devices() const
{
const Devicegraph::Impl& devicegraph = get_devicegraph()->get_impl();
Devicegraph::Impl::vertex_descriptor vertex = get_vertex();
return devicegraph.filter_devices_of_type<const BlkDevice>(devicegraph.parents(vertex));
}
unsigned int
Md::Impl::get_number() const
{
string::size_type pos = get_name().find_last_not_of("0123456789");
if (pos == string::npos || pos == get_name().size() - 1)
ST_THROW(Exception("md name has no number"));
return atoi(get_name().substr(pos + 1).c_str());
}
bool
Md::Impl::equal(const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
if (!Partitionable::Impl::equal(rhs))
return false;
return md_level == rhs.md_level && md_parity == rhs.md_parity &&
chunk_size_k == rhs.chunk_size_k;
}
void
Md::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
Partitionable::Impl::log_diff(log, rhs);
storage::log_diff_enum(log, "md-level", md_level, rhs.md_level);
storage::log_diff_enum(log, "md-parity", md_parity, rhs.md_parity);
storage::log_diff(log, "chunk-size-k", chunk_size_k, rhs.chunk_size_k);
}
void
Md::Impl::print(std::ostream& out) const
{
Partitionable::Impl::print(out);
out << " md-level:" << toString(get_md_level());
out << " md-parity:" << toString(get_md_parity());
out << " chunk-size-k:" << get_chunk_size_k();
}
void
Md::Impl::process_udev_ids(vector<string>& udev_ids) const
{
partition(udev_ids.begin(), udev_ids.end(), string_starts_with("md-uuid-"));
}
Text
Md::Impl::do_create_text(bool doing) const
{
return sformat(_("Create MD RAID %1$s (%2$s)"), get_displayname().c_str(),
get_size_string().c_str());
}
void
Md::Impl::do_create() const
{
string cmd_line = MDADMBIN " --create " + quote(get_name()) + " --run --level=" +
boost::to_lower_copy(toString(md_level), locale::classic()) + " -e 1.0 --homehost=any";
if (md_level == RAID1 || md_level == RAID5 || md_level == RAID6 || md_level == RAID10)
cmd_line += " -b internal";
if (chunk_size_k > 0)
cmd_line += " --chunk=" + to_string(chunk_size_k);
if (md_parity != PAR_DEFAULT)
cmd_line += " --parity=" + toString(md_parity);
vector<string> devices;
vector<string> spares;
for (const BlkDevice* blk_device : get_devices())
{
bool spare = false;
// TODO add get_out_holder that throws if num_children != 1, like get_single_child_of_type
for (const Holder* out_holder : blk_device->get_out_holders())
{
if (to_md_user(out_holder)->is_spare())
{
spare = true;
break;
}
}
if (!spare)
devices.push_back(blk_device->get_name());
else
spares.push_back(blk_device->get_name());
}
cmd_line += " --raid-devices=" + to_string(devices.size());
if (!spares.empty())
cmd_line += " --spare-devices=" + to_string(spares.size());
cmd_line += " " + quote(devices) + " " + quote(spares);
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("create md raid failed"));
}
Text
Md::Impl::do_delete_text(bool doing) const
{
return sformat(_("Delete MD RAID %1$s (%2$s)"), get_displayname().c_str(),
get_size_string().c_str());
}
void
Md::Impl::do_delete() const
{
// TODO split into deactivate and delete?
string cmd_line = MDADMBIN " --stop " + quote(get_name());
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("delete md raid failed"));
for (const BlkDevice* blk_device : get_devices())
{
blk_device->get_impl().wipe_device();
}
}
bool
compare_by_number(const Md* lhs, const Md* rhs)
{
return lhs->get_number() < rhs->get_number();
};
}
<commit_msg>- added TODO note<commit_after>
#include <ctype.h>
#include <iostream>
#include <boost/regex.hpp>
#include "storage/Devices/MdImpl.h"
#include "storage/Holders/MdUser.h"
#include "storage/Devicegraph.h"
#include "storage/Action.h"
#include "storage/Storage.h"
#include "storage/Environment.h"
#include "storage/SystemInfo/SystemInfo.h"
#include "storage/Utils/Exception.h"
#include "storage/Utils/Enum.h"
#include "storage/Utils/StorageTmpl.h"
#include "storage/Utils/StorageTypes.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Utils/StorageTmpl.h"
namespace storage
{
using namespace std;
const char* DeviceTraits<Md>::classname = "Md";
Md::Impl::Impl(const xmlNode* node)
: Partitionable::Impl(node)
{
string tmp;
if (getChildValue(node, "md-level", tmp))
md_level = toValueWithFallback(tmp, RAID0);
if (getChildValue(node, "md-parity", tmp))
md_parity = toValueWithFallback(tmp, PAR_DEFAULT);
getChildValue(node, "chunk-size-k", chunk_size_k);
}
void
Md::Impl::set_md_level(MdType md_level)
{
// TODO calculate size_k
Impl::md_level = md_level;
}
void
Md::Impl::set_chunk_size_k(unsigned long chunk_size_k)
{
// TODO calculate size_k
Impl::chunk_size_k = chunk_size_k;
}
bool
Md::Impl::is_valid_name(const string& name)
{
static boost::regex name_regex(DEVDIR "/md[0-9]+", boost::regex_constants::extended);
return boost::regex_match(name, name_regex);
}
vector<string>
Md::Impl::probe_mds(SystemInfo& systeminfo)
{
vector<string> ret;
for (const string& short_name : systeminfo.getDir(SYSFSDIR "/block"))
{
string name = DEVDIR "/" + short_name;
if (!is_valid_name(name))
continue;
ret.push_back(name);
}
return ret;
}
void
Md::Impl::probe(Devicegraph* probed, SystemInfo& systeminfo)
{
Partitionable::Impl::probe(systeminfo);
string tmp = get_name().substr(strlen(DEVDIR "/"));
ProcMdstat::Entry entry;
if (!systeminfo.getProcMdstat().getEntry(tmp, entry))
{
// TODO
throw;
}
md_level = entry.md_level;
md_parity = entry.md_parity;
chunk_size_k = entry.chunk_size_k;
for (const string& device : entry.devices)
{
BlkDevice* blk_device = BlkDevice::find(probed, device);
MdUser* md_user = MdUser::create(probed, blk_device, get_device());
md_user->set_spare(false);
}
for (const string& device : entry.spares)
{
BlkDevice* blk_device = BlkDevice::find(probed, device);
MdUser* md_user = MdUser::create(probed, blk_device, get_device());
md_user->set_spare(true);
}
}
void
Md::Impl::save(xmlNode* node) const
{
Partitionable::Impl::save(node);
setChildValue(node, "md-level", toString(md_level));
setChildValueIf(node, "md-parity", toString(md_parity), md_parity != PAR_DEFAULT);
setChildValueIf(node, "chunk-size-k", chunk_size_k, chunk_size_k != 0);
}
MdUser*
Md::Impl::add_device(BlkDevice* blk_device)
{
if (blk_device->num_children() != 0)
ST_THROW(WrongNumberOfChildren(blk_device->num_children(), 0));
// TODO calculate size_k
// TODO set partition id?
return MdUser::create(get_devicegraph(), blk_device, get_device());
}
vector<BlkDevice*>
Md::Impl::get_devices()
{
Devicegraph::Impl& devicegraph = get_devicegraph()->get_impl();
Devicegraph::Impl::vertex_descriptor vertex = get_vertex();
// TODO sorting
return devicegraph.filter_devices_of_type<BlkDevice>(devicegraph.parents(vertex));
}
vector<const BlkDevice*>
Md::Impl::get_devices() const
{
const Devicegraph::Impl& devicegraph = get_devicegraph()->get_impl();
Devicegraph::Impl::vertex_descriptor vertex = get_vertex();
// TODO sorting
return devicegraph.filter_devices_of_type<const BlkDevice>(devicegraph.parents(vertex));
}
unsigned int
Md::Impl::get_number() const
{
string::size_type pos = get_name().find_last_not_of("0123456789");
if (pos == string::npos || pos == get_name().size() - 1)
ST_THROW(Exception("md name has no number"));
return atoi(get_name().substr(pos + 1).c_str());
}
bool
Md::Impl::equal(const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
if (!Partitionable::Impl::equal(rhs))
return false;
return md_level == rhs.md_level && md_parity == rhs.md_parity &&
chunk_size_k == rhs.chunk_size_k;
}
void
Md::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const
{
const Impl& rhs = dynamic_cast<const Impl&>(rhs_base);
Partitionable::Impl::log_diff(log, rhs);
storage::log_diff_enum(log, "md-level", md_level, rhs.md_level);
storage::log_diff_enum(log, "md-parity", md_parity, rhs.md_parity);
storage::log_diff(log, "chunk-size-k", chunk_size_k, rhs.chunk_size_k);
}
void
Md::Impl::print(std::ostream& out) const
{
Partitionable::Impl::print(out);
out << " md-level:" << toString(get_md_level());
out << " md-parity:" << toString(get_md_parity());
out << " chunk-size-k:" << get_chunk_size_k();
}
void
Md::Impl::process_udev_ids(vector<string>& udev_ids) const
{
partition(udev_ids.begin(), udev_ids.end(), string_starts_with("md-uuid-"));
}
Text
Md::Impl::do_create_text(bool doing) const
{
return sformat(_("Create MD RAID %1$s (%2$s)"), get_displayname().c_str(),
get_size_string().c_str());
}
void
Md::Impl::do_create() const
{
string cmd_line = MDADMBIN " --create " + quote(get_name()) + " --run --level=" +
boost::to_lower_copy(toString(md_level), locale::classic()) + " -e 1.0 --homehost=any";
if (md_level == RAID1 || md_level == RAID5 || md_level == RAID6 || md_level == RAID10)
cmd_line += " -b internal";
if (chunk_size_k > 0)
cmd_line += " --chunk=" + to_string(chunk_size_k);
if (md_parity != PAR_DEFAULT)
cmd_line += " --parity=" + toString(md_parity);
vector<string> devices;
vector<string> spares;
for (const BlkDevice* blk_device : get_devices())
{
bool spare = false;
// TODO add get_out_holder that throws if num_children != 1, like get_single_child_of_type
for (const Holder* out_holder : blk_device->get_out_holders())
{
if (to_md_user(out_holder)->is_spare())
{
spare = true;
break;
}
}
if (!spare)
devices.push_back(blk_device->get_name());
else
spares.push_back(blk_device->get_name());
}
cmd_line += " --raid-devices=" + to_string(devices.size());
if (!spares.empty())
cmd_line += " --spare-devices=" + to_string(spares.size());
cmd_line += " " + quote(devices) + " " + quote(spares);
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("create md raid failed"));
}
Text
Md::Impl::do_delete_text(bool doing) const
{
return sformat(_("Delete MD RAID %1$s (%2$s)"), get_displayname().c_str(),
get_size_string().c_str());
}
void
Md::Impl::do_delete() const
{
// TODO split into deactivate and delete?
string cmd_line = MDADMBIN " --stop " + quote(get_name());
cout << cmd_line << endl;
SystemCmd cmd(cmd_line);
if (cmd.retcode() != 0)
ST_THROW(Exception("delete md raid failed"));
for (const BlkDevice* blk_device : get_devices())
{
blk_device->get_impl().wipe_device();
}
}
bool
compare_by_number(const Md* lhs, const Md* rhs)
{
return lhs->get_number() < rhs->get_number();
};
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) [2004-2009] Novell, Inc.
* Copyright (c) 2018 SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* 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, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include "storage/Utils/LoggerImpl.h"
#include "storage/Utils/LockImpl.h"
#include "storage/Utils/ExceptionImpl.h"
#include "storage/Utils/StorageTmpl.h"
#define LOCK_DIR "/run/libstorage-ng"
namespace storage
{
vector<const Lock*> Lock::locks;
int Lock::fd = -1;
Lock::Lock(bool read_only, bool disable)
: read_only(read_only), disabled(disable)
{
if (disabled)
return;
y2mil("getting " << (read_only ? "read-only" : "read-write") << " lock");
if (locks.empty())
{
// If there are no locks within the same process try to take the
// system-wide lock.
if (mkdir(LOCK_DIR, 0755) == -1 && errno != EEXIST)
{
y2err("creating directory for lock-file failed: " << strerror(errno));
}
fd = open(LOCK_DIR "/lock", (read_only ? O_RDONLY : O_WRONLY) | O_CREAT | O_CLOEXEC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if (fd < 0)
{
// Opening lock-file failed.
y2err("opening lock-file failed: " << strerror(errno));
ST_THROW(LockException(0));
}
struct flock lock;
memset(&lock, 0, sizeof(lock));
lock.l_type = (read_only ? F_RDLCK : F_WRLCK);
lock.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &lock) < 0)
{
switch (errno)
{
case EACCES:
case EAGAIN:
// Another process has a lock. Between the two fcntl
// calls the lock of the other process could be
// release. In that case we don't get the pid (and it is
// still 0).
fcntl(fd, F_GETLK, &lock);
close(fd);
y2err("locked by process " << lock.l_pid);
ST_THROW(LockException(lock.l_pid));
default:
// Some other error.
close(fd);
y2err("getting lock failed: " << strerror(errno));
ST_THROW(LockException(0));
}
}
}
else
{
// If there are locks within the same process check if a further
// lock is allowed.
if (read_only)
{
// no read-write lock of the process allowed
if (any_of(locks.begin(), locks.end(), [](const Lock* tmp) { return !tmp->read_only; }))
{
y2err("read-write lock by same process exists");
ST_THROW(LockException(-2));
}
}
else
{
// no other lock of the process allowed
y2err("lock by same process exists");
ST_THROW(LockException(-2));
}
}
// Add this lock to the list of locks in the same process.
locks.push_back(this);
y2mil("lock succeeded");
}
Lock::~Lock() noexcept
{
if (disabled)
return;
// Remove this lock from the list of locks in the same process.
erase(locks, this);
if (locks.empty())
{
// If this process has no further locks release the system-wide
// lock.
close(fd);
fd = -1;
// Do not bother deleting lock-file. Likelihood of race conditions
// is to high.
}
}
}
<commit_msg>Create lock with proper permissions (bsc#1059972)<commit_after>/*
* Copyright (c) [2004-2009] Novell, Inc.
* Copyright (c) 2018 SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* 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, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include "storage/Utils/LoggerImpl.h"
#include "storage/Utils/LockImpl.h"
#include "storage/Utils/ExceptionImpl.h"
#include "storage/Utils/StorageTmpl.h"
#define LOCK_DIR "/run/libstorage-ng"
namespace storage
{
vector<const Lock*> Lock::locks;
int Lock::fd = -1;
Lock::Lock(bool read_only, bool disable)
: read_only(read_only), disabled(disable)
{
if (disabled)
return;
y2mil("getting " << (read_only ? "read-only" : "read-write") << " lock");
if (locks.empty())
{
// If there are no locks within the same process try to take the
// system-wide lock.
if (mkdir(LOCK_DIR, 0755) == -1 && errno != EEXIST)
{
y2err("creating directory for lock-file failed: " << strerror(errno));
}
fd = open(LOCK_DIR "/lock", (read_only ? O_RDONLY : O_WRONLY) | O_CREAT | O_CLOEXEC, 0600);
if (fd < 0)
{
// Opening lock-file failed.
y2err("opening lock-file failed: " << strerror(errno));
ST_THROW(LockException(0));
}
struct flock lock;
memset(&lock, 0, sizeof(lock));
lock.l_type = (read_only ? F_RDLCK : F_WRLCK);
lock.l_whence = SEEK_SET;
if (fcntl(fd, F_SETLK, &lock) < 0)
{
switch (errno)
{
case EACCES:
case EAGAIN:
// Another process has a lock. Between the two fcntl
// calls the lock of the other process could be
// release. In that case we don't get the pid (and it is
// still 0).
fcntl(fd, F_GETLK, &lock);
close(fd);
y2err("locked by process " << lock.l_pid);
ST_THROW(LockException(lock.l_pid));
default:
// Some other error.
close(fd);
y2err("getting lock failed: " << strerror(errno));
ST_THROW(LockException(0));
}
}
}
else
{
// If there are locks within the same process check if a further
// lock is allowed.
if (read_only)
{
// no read-write lock of the process allowed
if (any_of(locks.begin(), locks.end(), [](const Lock* tmp) { return !tmp->read_only; }))
{
y2err("read-write lock by same process exists");
ST_THROW(LockException(-2));
}
}
else
{
// no other lock of the process allowed
y2err("lock by same process exists");
ST_THROW(LockException(-2));
}
}
// Add this lock to the list of locks in the same process.
locks.push_back(this);
y2mil("lock succeeded");
}
Lock::~Lock() noexcept
{
if (disabled)
return;
// Remove this lock from the list of locks in the same process.
erase(locks, this);
if (locks.empty())
{
// If this process has no further locks release the system-wide
// lock.
close(fd);
fd = -1;
// Do not bother deleting lock-file. Likelihood of race conditions
// is to high.
}
}
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "helpwindow.h"
#include "utils.h"
#include "ui_mainwindow.h"
#ifdef Q_WS_WIN
#include <windows.h>
#endif
#include <QApplication>
#include <QCloseEvent>
#include <QDebug>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDir>
#include <QHelpEngine>
#include <QMessageBox>
#include <QSettings>
#include <QTemporaryFile>
#include <QUrl>
#define OPENCOR_HOMEPAGE "http://opencor.sourceforge.net/"
#define OPENCOR_HELP_HOMEPAGE QUrl("qthelp://world.opencor/doc/index.html")
#define SETTINGS_INSTITUTION "World"
#define SETTINGS_GENERAL_LOCALE "General_Locale"
#define SETTINGS_GENERAL_GEOMETRY "General_Geometry"
#define SETTINGS_GENERAL_STATE "General_State"
#define SETTINGS_HELPWINDOW_ZOOMLEVEL "HelpWindow_ZoomLevel"
MainWindow::MainWindow(QWidget *pParent) :
QMainWindow(pParent),
mUi(new Ui::MainWindow)
{
// Set up the GUI
mUi->setupUi(this);
// Set the name of the main window to that of the application
setWindowTitle(qApp->applicationName());
// Some basic signals/events for some actions
connect(mUi->actionExit, SIGNAL(triggered(bool)),
this, SLOT(close()));
connect(mUi->actionResetAll, SIGNAL(triggered(bool)),
this, SLOT(resetAll()));
// Signals/events for showing/hiding the various toolbars
connect(mUi->actionHelpToolbar, SIGNAL(triggered(bool)),
mUi->helpToolbar, SLOT(setVisible(bool)));
connect(mUi->helpToolbar->toggleViewAction(), SIGNAL(toggled(bool)),
mUi->actionHelpToolbar, SLOT(setChecked(bool)));
// Extract the help files
QTemporaryFile tempDir;
tempDir.open(); // Note: this is required to get a 'valid' temporary
tempDir.close(); // directory name...
mTempDirName = tempDir.fileName().append(".dir");
QDir().mkdir(mTempDirName);
QString applicationBaseName(QFileInfo(qApp->applicationFilePath()).baseName());
mQchFileName = mTempDirName+QDir::separator()+applicationBaseName+".qch";
mQhcFileName = mTempDirName+QDir::separator()+applicationBaseName+".qhc";
saveResourceAs(":qchFile", mQchFileName);
saveResourceAs(":qhcFile", mQhcFileName);
// Set up the help engine
mHelpEngine = new QHelpEngine(mQhcFileName);
mHelpEngine->setupData();
// Help window
mHelpWindow = new HelpWindow(mHelpEngine, OPENCOR_HELP_HOMEPAGE);
connect(mUi->actionHelp, SIGNAL(triggered(bool)),
mHelpWindow, SLOT(setVisible(bool)));
connect(mHelpWindow, SIGNAL(visibilityChanged(bool)),
mUi->actionHelp, SLOT(setChecked(bool)));
// Default user settings
resetAll(false);
// Retrieve our default settings
loadSettings();
// Update the GUI, which may have changed (e.g. hidden toolbar) as a result
// of loading OpenCOR's settings
updateGUI();
}
MainWindow::~MainWindow()
{
// Delete some internal objects
delete mHelpEngine;
delete mUi;
// Delete the help files
QFile(mQchFileName).remove();
QFile(mQhcFileName).remove();
QDir().rmdir(mTempDirName);
}
void MainWindow::closeEvent(QCloseEvent *pEvent)
{
// Keep track of our default settings
// Note: it must be done here, as opposed to the destructor, otherwise some
// settings (e.g. docked windows) won't be properly saved
saveSettings();
pEvent->accept();
}
void MainWindow::singleAppMsgRcvd(const QString&)
{
// We have just received a message from another instance of OpenCOR, so
// bring ourselves to the foreground
// Note: one would normally use activateWindow(), but depending on the
// operating system it may or not bring OpenCOR to the foreground,
// so... instead we do what follows, depending on the operating
// system...
#ifdef Q_WS_WIN
// Retrieve OpenCOR's window Id
WId mwWinId = winId();
// Restore OpenCOR, should it be minimized
if (IsIconic(mwWinId))
SendMessage(mwWinId, WM_SYSCOMMAND, SC_RESTORE, 0);
// Bring OpenCOR to the foreground
DWORD foregroundThreadPId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
DWORD mwThreadPId = GetWindowThreadProcessId(mwWinId, NULL);
if (foregroundThreadPId != mwThreadPId)
{
// OpenCOR's thread process Id is not that of the foreground window, so
// attach the foreground thread to OpenCOR's, set OpenCOR to the
// foreground, and detach the foreground thread from OpenCOR's
AttachThreadInput(foregroundThreadPId, mwThreadPId, true);
SetForegroundWindow(mwWinId);
AttachThreadInput(foregroundThreadPId, mwThreadPId, false);
}
else
// OpenCOR's thread process Id is that of the foreground window, so
// just set OpenCOR to the foreground
SetForegroundWindow(mwWinId);
// Note: under Windows, to use activateWindow() will only highlight the
// application in the taskbar, since under Windows no application
// should be allowed to bring itself to the foreground when another
// application is already in the foreground. Fair enough, but it
// happens that, here, the user wants OpenCOR to be brought to the
// foreground, hence the above code to get the effect we are after...
#else
// Do what one should normally do and which works fine under Mac OS X
activateWindow();
#ifdef Q_WS_X11
raise();
// Note: under Linux, to use activateWindow() may or not give the
// expected result. The above code is supposed to make sure that
// OpenCOR gets brought to the foreground, but that itsn't the
// case under Ubuntu at least (it works when you want to open a
// second instance of OpenCOR, but not thereafter!)...
#endif
#endif
// Now, we must handle the arguments that were passed to us
// TODO: handle the arguments passed to the 'official' instance of OpenCOR
}
void MainWindow::loadSettings()
{
QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());
// Retrieve the language to be used by OpenCOR, with a default just in case
setLocale(settings.value(SETTINGS_GENERAL_LOCALE, QLocale::system().name()).toString());
// Retrieve the geometry of the main window
restoreGeometry(settings.value(SETTINGS_GENERAL_GEOMETRY).toByteArray());
// Retrieve the state of the main window
restoreState(settings.value(SETTINGS_GENERAL_STATE).toByteArray());
// Retrieve the zoom level for the help widget, with a default value just
// in case
mHelpWindow->setZoomLevel(settings.value(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->defaultZoomLevel()).toInt());
}
void MainWindow::saveSettings()
{
QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());
// Keep track of the language to be used by OpenCOR
settings.setValue(SETTINGS_GENERAL_LOCALE, mLocale);
// Keep track of the geometry of the main window
settings.setValue(SETTINGS_GENERAL_GEOMETRY, saveGeometry());
// Keep track of the state of the main window
settings.setValue(SETTINGS_GENERAL_STATE, saveState());
// Keep track of the text size multiplier for the help widget
settings.setValue(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->zoomLevel());
}
void MainWindow::setLocale(const QString& pLocale)
{
if (pLocale != mLocale)
{
mLocale = pLocale;
// Specify the language to be used by OpenCOR
// qApp->removeTranslator(qtTranslator);
// qtTranslator->load("qt_"+pLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
// qApp->installTranslator(qtTranslator);
// qApp->removeTranslator(appTranslator);
// appTranslator->load(":app_"+pLocale);
// qApp->installTranslator(appTranslator);
}
// Update the checked menu item
// Note: it has to be done every single time, since selecting a menu item
// will automatically toggle its checked status, so...
mUi->actionEnglish->setChecked(pLocale.startsWith("en"));
mUi->actionFrench->setChecked(pLocale.startsWith("fr"));
}
void MainWindow::notYetImplemented(const QString& pMsg)
{
// Display a warning message about a particular feature having not yet been
// implemented
QMessageBox::warning(this, qApp->applicationName(), pMsg+tr(" has not yet been implemented..."),
QMessageBox::Ok, QMessageBox::Ok);
}
void MainWindow::on_actionEnglish_triggered()
{
// Select English as the language used by OpenCOR
setLocale("en");
}
void MainWindow::on_actionFrench_triggered()
{
// Select French as the language used by OpenCOR
setLocale("fr");
}
void MainWindow::updateGUI()
{
// Update the checked status of the toolbars menu items
mUi->actionHelpToolbar->setChecked(mUi->helpToolbar->isVisible());
}
void MainWindow::on_actionHomepage_triggered()
{
// Look up the OpenCOR home page
QDesktopServices::openUrl(QUrl(OPENCOR_HOMEPAGE));
}
void MainWindow::on_actionAbout_triggered()
{
QMessageBox::about(this, qApp->applicationName(),
QString("")+
"<CENTER>"+
"<H1><B>"+qApp->applicationName()+" "+qApp->applicationVersion()+"</B></H1>"+
"<H3><I>"+getOsName()+"</I></H3>"+
"</CENTER>"+
"<BR>"+
"<A HREF = \""+QString(OPENCOR_HOMEPAGE)+"\">"+qApp->applicationName()+"</A> "+tr("is a cross-platform <A HREF = \"http://www.cellml.org/\">CellML</A>-based modelling environment which can be used to organise, edit, simulate and analyse CellML files.")+"<BR><BR>"+
qApp->applicationName()+" "+tr("is written in C++, using the <A HREF = \"http://qt.nokia.com/\">Qt framework</A>, and is not currently released under any particular license, but this is due to change in the near future."));
}
void MainWindow::resetAll(const bool& pClearUserSettings)
{
// Default language to be used by OpenCOR
setLocale(QLocale::system().name());
// Default size and position of both the main and help windows
const double mainRatio = 3.0/5.0;
const double helpRatio = 1.0/3.0;
const double spaceRatio = 1.0/45.0;
const double horizSpace = spaceRatio*qApp->desktop()->width();
const double vertSpace = 2.0*spaceRatio*qApp->desktop()->height();
mHelpWindow->setVisible(false); // By default
addDockWidget(Qt::RightDockWidgetArea, mHelpWindow);
// Note: the above is only required so that the help window can then be
// docked to the main window, should the user want to do that.
// Indeed, to make the help window float is not sufficient, so...
mHelpWindow->setFloating(true);
resize(QSize(mainRatio*qApp->desktop()->width(), mainRatio*qApp->desktop()->height()));
mHelpWindow->resize(helpRatio*qApp->desktop()->width(), size().height());
move(QPoint(horizSpace, vertSpace));
mHelpWindow->move(QPoint(qApp->desktop()->width()-mHelpWindow->size().width()-horizSpace, vertSpace));
// Default settings for the help widget
mHelpWindow->resetAll();
// Default visibility and location of the various toolbars
this->addToolBar(Qt::TopToolBarArea, mUi->helpToolbar);
mUi->helpToolbar->setVisible(true);
// Clear all the user settings, if required
if (pClearUserSettings)
QSettings(SETTINGS_INSTITUTION, qApp->applicationName()).clear();
}
<commit_msg>Updated the about box.<commit_after>#include "mainwindow.h"
#include "helpwindow.h"
#include "utils.h"
#include "ui_mainwindow.h"
#ifdef Q_WS_WIN
#include <windows.h>
#endif
#include <QApplication>
#include <QCloseEvent>
#include <QDebug>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QDir>
#include <QHelpEngine>
#include <QMessageBox>
#include <QSettings>
#include <QTemporaryFile>
#include <QUrl>
#define OPENCOR_HOMEPAGE "http://opencor.sourceforge.net/"
#define OPENCOR_HELP_HOMEPAGE QUrl("qthelp://world.opencor/doc/index.html")
#define SETTINGS_INSTITUTION "World"
#define SETTINGS_GENERAL_LOCALE "General_Locale"
#define SETTINGS_GENERAL_GEOMETRY "General_Geometry"
#define SETTINGS_GENERAL_STATE "General_State"
#define SETTINGS_HELPWINDOW_ZOOMLEVEL "HelpWindow_ZoomLevel"
MainWindow::MainWindow(QWidget *pParent) :
QMainWindow(pParent),
mUi(new Ui::MainWindow)
{
// Set up the GUI
mUi->setupUi(this);
// Set the name of the main window to that of the application
setWindowTitle(qApp->applicationName());
// Some basic signals/events for some actions
connect(mUi->actionExit, SIGNAL(triggered(bool)),
this, SLOT(close()));
connect(mUi->actionResetAll, SIGNAL(triggered(bool)),
this, SLOT(resetAll()));
// Signals/events for showing/hiding the various toolbars
connect(mUi->actionHelpToolbar, SIGNAL(triggered(bool)),
mUi->helpToolbar, SLOT(setVisible(bool)));
connect(mUi->helpToolbar->toggleViewAction(), SIGNAL(toggled(bool)),
mUi->actionHelpToolbar, SLOT(setChecked(bool)));
// Extract the help files
QTemporaryFile tempDir;
tempDir.open(); // Note: this is required to get a 'valid' temporary
tempDir.close(); // directory name...
mTempDirName = tempDir.fileName().append(".dir");
QDir().mkdir(mTempDirName);
QString applicationBaseName(QFileInfo(qApp->applicationFilePath()).baseName());
mQchFileName = mTempDirName+QDir::separator()+applicationBaseName+".qch";
mQhcFileName = mTempDirName+QDir::separator()+applicationBaseName+".qhc";
saveResourceAs(":qchFile", mQchFileName);
saveResourceAs(":qhcFile", mQhcFileName);
// Set up the help engine
mHelpEngine = new QHelpEngine(mQhcFileName);
mHelpEngine->setupData();
// Help window
mHelpWindow = new HelpWindow(mHelpEngine, OPENCOR_HELP_HOMEPAGE);
connect(mUi->actionHelp, SIGNAL(triggered(bool)),
mHelpWindow, SLOT(setVisible(bool)));
connect(mHelpWindow, SIGNAL(visibilityChanged(bool)),
mUi->actionHelp, SLOT(setChecked(bool)));
// Default user settings
resetAll(false);
// Retrieve our default settings
loadSettings();
// Update the GUI, which may have changed (e.g. hidden toolbar) as a result
// of loading OpenCOR's settings
updateGUI();
}
MainWindow::~MainWindow()
{
// Delete some internal objects
delete mHelpEngine;
delete mUi;
// Delete the help files
QFile(mQchFileName).remove();
QFile(mQhcFileName).remove();
QDir().rmdir(mTempDirName);
}
void MainWindow::closeEvent(QCloseEvent *pEvent)
{
// Keep track of our default settings
// Note: it must be done here, as opposed to the destructor, otherwise some
// settings (e.g. docked windows) won't be properly saved
saveSettings();
pEvent->accept();
}
void MainWindow::singleAppMsgRcvd(const QString&)
{
// We have just received a message from another instance of OpenCOR, so
// bring ourselves to the foreground
// Note: one would normally use activateWindow(), but depending on the
// operating system it may or not bring OpenCOR to the foreground,
// so... instead we do what follows, depending on the operating
// system...
#ifdef Q_WS_WIN
// Retrieve OpenCOR's window Id
WId mwWinId = winId();
// Restore OpenCOR, should it be minimized
if (IsIconic(mwWinId))
SendMessage(mwWinId, WM_SYSCOMMAND, SC_RESTORE, 0);
// Bring OpenCOR to the foreground
DWORD foregroundThreadPId = GetWindowThreadProcessId(GetForegroundWindow(), NULL);
DWORD mwThreadPId = GetWindowThreadProcessId(mwWinId, NULL);
if (foregroundThreadPId != mwThreadPId)
{
// OpenCOR's thread process Id is not that of the foreground window, so
// attach the foreground thread to OpenCOR's, set OpenCOR to the
// foreground, and detach the foreground thread from OpenCOR's
AttachThreadInput(foregroundThreadPId, mwThreadPId, true);
SetForegroundWindow(mwWinId);
AttachThreadInput(foregroundThreadPId, mwThreadPId, false);
}
else
// OpenCOR's thread process Id is that of the foreground window, so
// just set OpenCOR to the foreground
SetForegroundWindow(mwWinId);
// Note: under Windows, to use activateWindow() will only highlight the
// application in the taskbar, since under Windows no application
// should be allowed to bring itself to the foreground when another
// application is already in the foreground. Fair enough, but it
// happens that, here, the user wants OpenCOR to be brought to the
// foreground, hence the above code to get the effect we are after...
#else
// Do what one should normally do and which works fine under Mac OS X
activateWindow();
#ifdef Q_WS_X11
raise();
// Note: under Linux, to use activateWindow() may or not give the
// expected result. The above code is supposed to make sure that
// OpenCOR gets brought to the foreground, but that itsn't the
// case under Ubuntu at least (it works when you want to open a
// second instance of OpenCOR, but not thereafter!)...
#endif
#endif
// Now, we must handle the arguments that were passed to us
// TODO: handle the arguments passed to the 'official' instance of OpenCOR
}
void MainWindow::loadSettings()
{
QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());
// Retrieve the language to be used by OpenCOR, with a default just in case
setLocale(settings.value(SETTINGS_GENERAL_LOCALE, QLocale::system().name()).toString());
// Retrieve the geometry of the main window
restoreGeometry(settings.value(SETTINGS_GENERAL_GEOMETRY).toByteArray());
// Retrieve the state of the main window
restoreState(settings.value(SETTINGS_GENERAL_STATE).toByteArray());
// Retrieve the zoom level for the help widget, with a default value just
// in case
mHelpWindow->setZoomLevel(settings.value(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->defaultZoomLevel()).toInt());
}
void MainWindow::saveSettings()
{
QSettings settings(SETTINGS_INSTITUTION, qApp->applicationName());
// Keep track of the language to be used by OpenCOR
settings.setValue(SETTINGS_GENERAL_LOCALE, mLocale);
// Keep track of the geometry of the main window
settings.setValue(SETTINGS_GENERAL_GEOMETRY, saveGeometry());
// Keep track of the state of the main window
settings.setValue(SETTINGS_GENERAL_STATE, saveState());
// Keep track of the text size multiplier for the help widget
settings.setValue(SETTINGS_HELPWINDOW_ZOOMLEVEL, mHelpWindow->zoomLevel());
}
void MainWindow::setLocale(const QString& pLocale)
{
if (pLocale != mLocale)
{
mLocale = pLocale;
// Specify the language to be used by OpenCOR
// qApp->removeTranslator(qtTranslator);
// qtTranslator->load("qt_"+pLocale, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
// qApp->installTranslator(qtTranslator);
// qApp->removeTranslator(appTranslator);
// appTranslator->load(":app_"+pLocale);
// qApp->installTranslator(appTranslator);
}
// Update the checked menu item
// Note: it has to be done every single time, since selecting a menu item
// will automatically toggle its checked status, so...
mUi->actionEnglish->setChecked(pLocale.startsWith("en"));
mUi->actionFrench->setChecked(pLocale.startsWith("fr"));
}
void MainWindow::notYetImplemented(const QString& pMsg)
{
// Display a warning message about a particular feature having not yet been
// implemented
QMessageBox::warning(this, qApp->applicationName(), pMsg+tr(" has not yet been implemented..."),
QMessageBox::Ok, QMessageBox::Ok);
}
void MainWindow::on_actionEnglish_triggered()
{
// Select English as the language used by OpenCOR
setLocale("en");
}
void MainWindow::on_actionFrench_triggered()
{
// Select French as the language used by OpenCOR
setLocale("fr");
}
void MainWindow::updateGUI()
{
// Update the checked status of the toolbars menu items
mUi->actionHelpToolbar->setChecked(mUi->helpToolbar->isVisible());
}
void MainWindow::on_actionHomepage_triggered()
{
// Look up the OpenCOR home page
QDesktopServices::openUrl(QUrl(OPENCOR_HOMEPAGE));
}
void MainWindow::on_actionAbout_triggered()
{
QMessageBox::about(this, qApp->applicationName(),
QString("")+
"<CENTER>"+
"<H1><B>"+qApp->applicationName()+" "+qApp->applicationVersion()+"</B></H1>"+
"<H3><I>"+getOsName()+"</I></H3>"+
"</CENTER>"+
"<BR>"+
"<A HREF = \""+QString(OPENCOR_HOMEPAGE)+"\">"+qApp->applicationName()+"</A> "+tr("is a cross-platform <A HREF = \"http://www.cellml.org/\">CellML</A>-based modelling environment which can be used to organise, edit, simulate and analyse CellML files."));
}
void MainWindow::resetAll(const bool& pClearUserSettings)
{
// Default language to be used by OpenCOR
setLocale(QLocale::system().name());
// Default size and position of both the main and help windows
const double mainRatio = 3.0/5.0;
const double helpRatio = 1.0/3.0;
const double spaceRatio = 1.0/45.0;
const double horizSpace = spaceRatio*qApp->desktop()->width();
const double vertSpace = 2.0*spaceRatio*qApp->desktop()->height();
mHelpWindow->setVisible(false); // By default
addDockWidget(Qt::RightDockWidgetArea, mHelpWindow);
// Note: the above is only required so that the help window can then be
// docked to the main window, should the user want to do that.
// Indeed, to make the help window float is not sufficient, so...
mHelpWindow->setFloating(true);
resize(QSize(mainRatio*qApp->desktop()->width(), mainRatio*qApp->desktop()->height()));
mHelpWindow->resize(helpRatio*qApp->desktop()->width(), size().height());
move(QPoint(horizSpace, vertSpace));
mHelpWindow->move(QPoint(qApp->desktop()->width()-mHelpWindow->size().width()-horizSpace, vertSpace));
// Default settings for the help widget
mHelpWindow->resetAll();
// Default visibility and location of the various toolbars
this->addToolBar(Qt::TopToolBarArea, mUi->helpToolbar);
mUi->helpToolbar->setVisible(true);
// Clear all the user settings, if required
if (pClearUserSettings)
QSettings(SETTINGS_INSTITUTION, qApp->applicationName()).clear();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth 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.
*
* VapourSynth 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 VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QWaitCondition>
#include <QtCore/QFile>
#include <QtCore/QMap>
#include "VSScript.h"
#include "VSHelper.h"
#ifdef _WIN32
static inline QString nativeToQString(const wchar_t *str) {
return QString::fromWCharArray(str);
}
#else
static inline QString nativeToQString(const char *str) {
return QString::fromLocal8Bit(str);
}
#endif
const VSAPI *vsapi = NULL;
VSScript *se = NULL;
VSNodeRef *node = NULL;
FILE *outFile = NULL;
int requests = 0;
int index = 0;
int outputFrames = 0;
int requestedFrames = 0;
int completedFrames = 0;
int totalFrames = 0;
int numPlanes = 0;
bool y4m = false;
bool outputError = false;
bool showInfo = false;
QMap<int, const VSFrameRef *> reorderMap;
QString errorMessage;
QWaitCondition condition;
QMutex mutex;
void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) {
completedFrames++;
if (f) {
reorderMap.insert(n, f);
while (reorderMap.contains(outputFrames)) {
const VSFrameRef *frame = reorderMap.take(outputFrames);
if (!outputError) {
if (y4m) {
if (!fwrite("FRAME\n", 6, 1, outFile)) {
errorMessage = "Error: fwrite() call failed";
totalFrames = requestedFrames;
outputError = true;
}
}
if (!outputError) {
const VSFormat *fi = vsapi->getFrameFormat(frame);
for (int p = 0; p < fi->numPlanes; p++) {
int stride = vsapi->getStride(frame, p);
const uint8_t *readPtr = vsapi->getReadPtr(frame, p);
int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample;
int height = vsapi->getFrameHeight(frame, p);
for (int y = 0; y < height; y++) {
if (!fwrite(readPtr, rowSize, 1, outFile)) {
errorMessage = "Error: fwrite() call failed";
totalFrames = requestedFrames;
outputError = true;
p = 100; // break out of the outer loop
break;
}
readPtr += stride;
}
}
}
}
vsapi->freeFrame(frame);
outputFrames++;
}
} else {
outputError = true;
totalFrames = requestedFrames;
if (errorMsg)
errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg);
else
errorMessage = QString("Error: Failed to retrieve frame ") + n;
}
if (requestedFrames < totalFrames) {
vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL);
requestedFrames++;
}
if (totalFrames == completedFrames) {
QMutexLocker lock(&mutex);
condition.wakeOne();
}
}
bool outputNode() {
if (requests < 1) {
const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore());
requests = info->numThreads;
}
const VSVideoInfo *vi = vsapi->getVideoInfo(node);
totalFrames = vi->numFrames;
if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) {
errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips";
fprintf(stderr, "%s", errorMessage.toUtf8().constData());
return true;
}
QString y4mFormat;
QString numBits;
if (y4m) {
if (vi->format->colorFamily == cmGray) {
y4mFormat = "mono";
if (vi->format->bitsPerSample > 8)
y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample);
} else if (vi->format->colorFamily == cmYUV) {
if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1)
y4mFormat = "420";
else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0)
y4mFormat = "422";
else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0)
y4mFormat = "444";
else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2)
y4mFormat = "410";
else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0)
y4mFormat = "411";
else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1)
y4mFormat = "440";
else {
fprintf(stderr, "No y4m identifier exists for current format");
return true;
}
if (vi->format->bitsPerSample > 8)
y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample);
} else {
fprintf(stderr, "No y4m identifier exists for current format");
return true;
}
}
if (!y4mFormat.isEmpty())
y4mFormat = "C" + y4mFormat + " ";
QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum) + ":" + QString::number(vi->fpsDen) + " Ip A0:0\n";
QByteArray rawHeader = header.toUtf8();
if (y4m) {
if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) {
errorMessage = "Error: fwrite() call failed";
fprintf(stderr, "%s", errorMessage.toUtf8().constData());
outputError = true;
return outputError;
}
}
QMutexLocker lock(&mutex);
int intitalRequestSize = std::min(requests, totalFrames);
requestedFrames = intitalRequestSize;
for (int n = 0; n < intitalRequestSize; n++)
vsapi->getFrameAsync(n, node, frameDoneCallback, NULL);
condition.wait(&mutex);
if (outputError) {
fprintf(stderr, "%s", errorMessage.toUtf8().constData());
}
return outputError;
}
const char *colorFamilyToString(int colorFamily) {
switch (colorFamily) {
case cmGray: return "Gray";
case cmRGB: return "RGB";
case cmYUV: return "YUV";
case cmYCoCg: return "YCoCg";
case cmCompat: return "Compat";
}
return "";
}
// fixme, only allow info without output
#ifdef _WIN32
int wmain(int argc, wchar_t **argv) {
#else
int main(int argc, char **argv) {
#endif
if (argc < 3) {
fprintf(stderr, "VSPipe usage:\n");
fprintf(stderr, "Show script info: vspipe script.vpy - -info\n");
fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n");
fprintf(stderr, "Write to file: vspipe script.vpy <outFile> [options]\n");
fprintf(stderr, "Available options:\n");
fprintf(stderr, "Select output index: -index N\n");
fprintf(stderr, "Set number of concurrent frame requests: -requests N\n");
fprintf(stderr, "Add YUV4MPEG headers: -y4m\n");
fprintf(stderr, "Show video info: -info (overrides other options)\n");
return 1;
}
QFile scriptFile(nativeToQString(argv[1]));
if (!scriptFile.open(QIODevice::ReadOnly)) {
fprintf(stderr, "Failed to to open script file for reading\n");
return 1;
}
if (scriptFile.size() > 1024*1024*16) {
fprintf(stderr, "Script files bigger than 16MB not allowed\n");
return 1;
}
QByteArray scriptData = scriptFile.readAll();
scriptFile.close();
if (scriptData.isEmpty()) {
fprintf(stderr, "Failed to read script file or file is empty\n");
return 1;
}
QString outputFilename = nativeToQString(argv[2]);
if (outputFilename == "-") {
outFile = stdout;
} else {
#ifdef _WIN32
outFile = _wfopen(outputFilename.toStdWString().c_str(), L"wb");
#else
outfile = fopen(outputFilename.toLocal8Bit(), "wb");
#endif
if (!outFile) {
fprintf(stderr, "Failed to open output for writing\n");
return 1;
}
}
for (int arg = 3; arg < argc; arg++) {
QString argString = nativeToQString(argv[arg]);
if (argString == "-y4m") {
y4m = true;
} else if (argString == "-info") {
showInfo = true;
} else if (argString == "-index") {
bool ok = false;
if (argc <= arg + 1) {
fprintf(stderr, "No index number specified");
return 1;
}
QString numString = nativeToQString(argv[arg+1]);
index = numString.toInt(&ok);
if (!ok) {
fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
return 1;
}
arg++;
} else if (argString == "-requests") {
bool ok = false;
if (argc <= arg + 1) {
fprintf(stderr, "No request number specified");
return 1;
}
QString numString = nativeToQString(argv[arg+1]);
requests = numString.toInt(&ok);
if (!ok) {
fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
return 1;
}
arg++;
} else {
fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData());
return 1;
}
}
if (!vseval_init()) {
fprintf(stderr, "Failed to initialize VapourSynth environment\n");
return 1;
}
vsapi = vseval_getVSApi();
if (!vsapi) {
fprintf(stderr, "Failed to get VapourSynth API pointer\n");
vseval_finalize();
return 1;
}
if (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) {
fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se));
vseval_freeScript(se);
vseval_finalize();
return 1;
}
node = vseval_getOutput(se, index);
if (!node) {
fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n");
vseval_freeScript(se);
vseval_finalize();
return 1;
}
bool error = false;
const VSVideoInfo *vi = vsapi->getVideoInfo(node);
if (showInfo) {
fprintf(outFile, "Width: %d\n", vi->width);
fprintf(outFile, "Height: %d\n", vi->height);
fprintf(outFile, "Frames: %d\n", vi->numFrames);
fprintf(outFile, "FPS: %d/%d\n", vi->fpsNum, vi->fpsDen);
if (vi->format) {
fprintf(outFile, "Format Name: %s\n", vi->format->name);
fprintf(outFile, "Color Family: %s\n", colorFamilyToString(vi->format->colorFamily));
fprintf(outFile, "Bits: %d\n", vi->format->bitsPerSample);
fprintf(outFile, "SubSampling W: %d\n", vi->format->subSamplingW);
fprintf(outFile, "SubSampling H: %d\n", vi->format->subSamplingH);
} else {
printf("Format Name: Variable\n");
}
} else {
if (!isConstantFormat(vi) || vi->numFrames == 0) {
fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n");
vseval_freeScript(se);
vseval_finalize();
return 1;
}
error = outputNode();
}
fflush(outFile);
vseval_freeScript(se);
vseval_finalize();
return error;
}
<commit_msg>Fix info output in vspipe<commit_after>/*
* Copyright (c) 2013 Fredrik Mellbin
*
* This file is part of VapourSynth.
*
* VapourSynth 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.
*
* VapourSynth 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 VapourSynth; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QWaitCondition>
#include <QtCore/QFile>
#include <QtCore/QMap>
#include "VSScript.h"
#include "VSHelper.h"
#ifdef _WIN32
static inline QString nativeToQString(const wchar_t *str) {
return QString::fromWCharArray(str);
}
#else
static inline QString nativeToQString(const char *str) {
return QString::fromLocal8Bit(str);
}
#endif
const VSAPI *vsapi = NULL;
VSScript *se = NULL;
VSNodeRef *node = NULL;
FILE *outFile = NULL;
int requests = 0;
int index = 0;
int outputFrames = 0;
int requestedFrames = 0;
int completedFrames = 0;
int totalFrames = 0;
int numPlanes = 0;
bool y4m = false;
bool outputError = false;
bool showInfo = false;
QMap<int, const VSFrameRef *> reorderMap;
QString errorMessage;
QWaitCondition condition;
QMutex mutex;
void VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) {
completedFrames++;
if (f) {
reorderMap.insert(n, f);
while (reorderMap.contains(outputFrames)) {
const VSFrameRef *frame = reorderMap.take(outputFrames);
if (!outputError) {
if (y4m) {
if (!fwrite("FRAME\n", 6, 1, outFile)) {
errorMessage = "Error: fwrite() call failed";
totalFrames = requestedFrames;
outputError = true;
}
}
if (!outputError) {
const VSFormat *fi = vsapi->getFrameFormat(frame);
for (int p = 0; p < fi->numPlanes; p++) {
int stride = vsapi->getStride(frame, p);
const uint8_t *readPtr = vsapi->getReadPtr(frame, p);
int rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample;
int height = vsapi->getFrameHeight(frame, p);
for (int y = 0; y < height; y++) {
if (!fwrite(readPtr, rowSize, 1, outFile)) {
errorMessage = "Error: fwrite() call failed";
totalFrames = requestedFrames;
outputError = true;
p = 100; // break out of the outer loop
break;
}
readPtr += stride;
}
}
}
}
vsapi->freeFrame(frame);
outputFrames++;
}
} else {
outputError = true;
totalFrames = requestedFrames;
if (errorMsg)
errorMessage = QString("Error: Failed to retrieve frame ") + n + QString(" with error: ") + QString::fromUtf8(errorMsg);
else
errorMessage = QString("Error: Failed to retrieve frame ") + n;
}
if (requestedFrames < totalFrames) {
vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL);
requestedFrames++;
}
if (totalFrames == completedFrames) {
QMutexLocker lock(&mutex);
condition.wakeOne();
}
}
bool outputNode() {
if (requests < 1) {
const VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore());
requests = info->numThreads;
}
const VSVideoInfo *vi = vsapi->getVideoInfo(node);
totalFrames = vi->numFrames;
if (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) {
errorMessage = "Error: Can only apply y4m headers to YUV and Gray format clips";
fprintf(stderr, "%s", errorMessage.toUtf8().constData());
return true;
}
QString y4mFormat;
QString numBits;
if (y4m) {
if (vi->format->colorFamily == cmGray) {
y4mFormat = "mono";
if (vi->format->bitsPerSample > 8)
y4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample);
} else if (vi->format->colorFamily == cmYUV) {
if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1)
y4mFormat = "420";
else if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0)
y4mFormat = "422";
else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0)
y4mFormat = "444";
else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2)
y4mFormat = "410";
else if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0)
y4mFormat = "411";
else if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1)
y4mFormat = "440";
else {
fprintf(stderr, "No y4m identifier exists for current format");
return true;
}
if (vi->format->bitsPerSample > 8)
y4mFormat = y4mFormat + "p" + QString::number(vi->format->bitsPerSample);
} else {
fprintf(stderr, "No y4m identifier exists for current format");
return true;
}
}
if (!y4mFormat.isEmpty())
y4mFormat = "C" + y4mFormat + " ";
QString header = "YUV4MPEG2 " + y4mFormat + "W" + QString::number(vi->width) + " H" + QString::number(vi->height) + " F" + QString::number(vi->fpsNum) + ":" + QString::number(vi->fpsDen) + " Ip A0:0\n";
QByteArray rawHeader = header.toUtf8();
if (y4m) {
if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) {
errorMessage = "Error: fwrite() call failed";
fprintf(stderr, "%s", errorMessage.toUtf8().constData());
outputError = true;
return outputError;
}
}
QMutexLocker lock(&mutex);
int intitalRequestSize = std::min(requests, totalFrames);
requestedFrames = intitalRequestSize;
for (int n = 0; n < intitalRequestSize; n++)
vsapi->getFrameAsync(n, node, frameDoneCallback, NULL);
condition.wait(&mutex);
if (outputError) {
fprintf(stderr, "%s", errorMessage.toUtf8().constData());
}
return outputError;
}
const char *colorFamilyToString(int colorFamily) {
switch (colorFamily) {
case cmGray: return "Gray";
case cmRGB: return "RGB";
case cmYUV: return "YUV";
case cmYCoCg: return "YCoCg";
case cmCompat: return "Compat";
}
return "";
}
// fixme, only allow info without output
#ifdef _WIN32
int wmain(int argc, wchar_t **argv) {
#else
int main(int argc, char **argv) {
#endif
if (argc < 3) {
fprintf(stderr, "VSPipe usage:\n");
fprintf(stderr, "Show script info: vspipe script.vpy - -info\n");
fprintf(stderr, "Write to stdout: vspipe script.vpy - [options]\n");
fprintf(stderr, "Write to file: vspipe script.vpy <outFile> [options]\n");
fprintf(stderr, "Available options:\n");
fprintf(stderr, "Select output index: -index N\n");
fprintf(stderr, "Set number of concurrent frame requests: -requests N\n");
fprintf(stderr, "Add YUV4MPEG headers: -y4m\n");
fprintf(stderr, "Show video info: -info (overrides other options)\n");
return 1;
}
QFile scriptFile(nativeToQString(argv[1]));
if (!scriptFile.open(QIODevice::ReadOnly)) {
fprintf(stderr, "Failed to to open script file for reading\n");
return 1;
}
if (scriptFile.size() > 1024*1024*16) {
fprintf(stderr, "Script files bigger than 16MB not allowed\n");
return 1;
}
QByteArray scriptData = scriptFile.readAll();
scriptFile.close();
if (scriptData.isEmpty()) {
fprintf(stderr, "Failed to read script file or file is empty\n");
return 1;
}
QString outputFilename = nativeToQString(argv[2]);
if (outputFilename == "-") {
outFile = stdout;
} else {
#ifdef _WIN32
outFile = _wfopen(outputFilename.toStdWString().c_str(), L"wb");
#else
outfile = fopen(outputFilename.toLocal8Bit(), "wb");
#endif
if (!outFile) {
fprintf(stderr, "Failed to open output for writing\n");
return 1;
}
}
for (int arg = 3; arg < argc; arg++) {
QString argString = nativeToQString(argv[arg]);
if (argString == "-y4m") {
y4m = true;
} else if (argString == "-info") {
showInfo = true;
} else if (argString == "-index") {
bool ok = false;
if (argc <= arg + 1) {
fprintf(stderr, "No index number specified");
return 1;
}
QString numString = nativeToQString(argv[arg+1]);
index = numString.toInt(&ok);
if (!ok) {
fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
return 1;
}
arg++;
} else if (argString == "-requests") {
bool ok = false;
if (argc <= arg + 1) {
fprintf(stderr, "No request number specified");
return 1;
}
QString numString = nativeToQString(argv[arg+1]);
requests = numString.toInt(&ok);
if (!ok) {
fprintf(stderr, "Couldn't convert %s to an integer", numString.toUtf8().constData());
return 1;
}
arg++;
} else {
fprintf(stderr, "Unknown argument: %s\n", argString.toUtf8().constData());
return 1;
}
}
if (!vseval_init()) {
fprintf(stderr, "Failed to initialize VapourSynth environment\n");
return 1;
}
vsapi = vseval_getVSApi();
if (!vsapi) {
fprintf(stderr, "Failed to get VapourSynth API pointer\n");
vseval_finalize();
return 1;
}
if (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) {
fprintf(stderr, "Script evaluation failed:\n%s", vseval_getError(se));
vseval_freeScript(se);
vseval_finalize();
return 1;
}
node = vseval_getOutput(se, index);
if (!node) {
fprintf(stderr, "Failed to retrieve output node. Invalid index specified?\n");
vseval_freeScript(se);
vseval_finalize();
return 1;
}
bool error = false;
const VSVideoInfo *vi = vsapi->getVideoInfo(node);
if (showInfo) {
fprintf(outFile, "Width: %d\n", vi->width);
fprintf(outFile, "Height: %d\n", vi->height);
fprintf(outFile, "Frames: %d\n", vi->numFrames);
fprintf(outFile, "FPS: %d/%d\n", vi->fpsNum, vi->fpsDen);
if (vi->format) {
fprintf(outFile, "Format Name: %s\n", vi->format->name);
fprintf(outFile, "Color Family: %s\n", colorFamilyToString(vi->format->colorFamily));
fprintf(outFile, "Bits: %d\n", vi->format->bitsPerSample);
fprintf(outFile, "SubSampling W: %d\n", vi->format->subSamplingW);
fprintf(outFile, "SubSampling H: %d\n", vi->format->subSamplingH);
} else {
fprintf(outFile, "Format Name: Variable\n");
}
} else {
if (!isConstantFormat(vi) || vi->numFrames == 0) {
fprintf(stderr, "Cannot output clips with varying dimensions or unknown length\n");
vseval_freeScript(se);
vseval_finalize();
return 1;
}
error = outputNode();
}
fflush(outFile);
vseval_freeScript(se);
vseval_finalize();
return error;
}
<|endoftext|> |
<commit_before>#include "windowManager.h"
#ifdef WIN32
#include "dynamicLibrary.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "graphics/opengl.h"
#include "Updatable.h"
#include "Renderable.h"
#include "collisionable.h"
#include "postProcessManager.h"
#include "input.h"
#include <glm/gtc/type_ptr.hpp>
#include <cmath>
#include <SDL.h>
PVector<Window> Window::all_windows;
void* Window::gl_context = nullptr;
Window::Window(glm::vec2 virtual_size, bool fullscreen, RenderChain* render_chain, int fsaa)
: minimal_virtual_size(virtual_size), current_virtual_size(virtual_size), render_chain(render_chain), fullscreen(fullscreen), fsaa(fsaa)
{
srand(static_cast<int32_t>(time(nullptr)));
#ifdef _WIN32
//On Vista or newer windows, let the OS know we are DPI aware, so we won't have odd scaling issues.
auto user32 = DynamicLibrary::open("USER32.DLL");
if (user32)
{
auto SetProcessDPIAware = user32->getFunction<BOOL(WINAPI *)(void)>("SetProcessDPIAware");
if (SetProcessDPIAware)
SetProcessDPIAware();
}
#endif
create();
sp::initOpenGL();
all_windows.push_back(this);
}
Window::~Window()
{
}
void Window::render()
{
//#warning SDL2 TODO
/*
if (InputHandler::keyboardIsPressed(sf::Keyboard::Return) && (sf::Keyboard::isKeyPressed(sf::Keyboard::LAlt) || sf::Keyboard::isKeyPressed(sf::Keyboard::RAlt)))
{
setFullscreen(!isFullscreen());
}
*/
SDL_GL_MakeCurrent(static_cast<SDL_Window*>(window), gl_context);
int w, h;
SDL_GL_GetDrawableSize(static_cast<SDL_Window*>(window), &w, &h);
glViewport(0, 0, w, h);
// Clear the window
glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Call the first item of the rendering chain.
sp::RenderTarget target{current_virtual_size, {w, h}};
render_chain->render(target);
target.finish();
// Display things on screen
SDL_GL_SwapWindow(static_cast<SDL_Window*>(window));
}
void Window::setFullscreen(bool new_fullscreen)
{
if (fullscreen == new_fullscreen)
return;
fullscreen = new_fullscreen;
create();
}
void Window::setFSAA(int new_fsaa)
{
if (fsaa == new_fsaa)
return;
fsaa = new_fsaa;
create();
}
void Window::setTitle(string title)
{
SDL_SetWindowTitle(static_cast<SDL_Window*>(window), title.c_str());
}
glm::vec2 Window::mapPixelToCoords(const glm::ivec2 point) const
{
int w, h;
SDL_GetWindowSize(static_cast<SDL_Window*>(window), &w, &h);
float x = float(point.x) / float(w) * float(current_virtual_size.x);
float y = float(point.y) / float(h) * float(current_virtual_size.y);
return glm::vec2(x, y);
}
glm::ivec2 Window::mapCoordsToPixel(const glm::vec2 point) const
{
int w, h;
SDL_GetWindowSize(static_cast<SDL_Window*>(window), &w, &h);
float x = float(point.x) * float(w) / float(current_virtual_size.x);
float y = float(point.y) * float(h) / float(current_virtual_size.y);
return glm::ivec2(x, y);
}
void Window::create()
{
if (window) return;
// Create the window of the application
auto windowWidth = static_cast<int>(minimal_virtual_size.x);
auto windowHeight = static_cast<int>(minimal_virtual_size.y);
SDL_Rect rect;
SDL_GetDisplayBounds(0, &rect);
if (fullscreen)
{
windowWidth = rect.w;
windowHeight = rect.h;
}else{
int scale = 2;
while(windowWidth * scale < int(rect.w) && windowHeight * scale < int(rect.h))
scale += 1;
windowWidth *= scale - 1;
windowHeight *= scale - 1;
while(windowWidth >= int(rect.w) || windowHeight >= int(rect.h) - 100)
{
windowWidth = static_cast<int>(std::floor(windowWidth * 0.9f));
windowHeight = static_cast<int>(std::floor(windowHeight * 0.9f));
}
}
#if defined(ANDROID)
constexpr auto context_profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
constexpr auto context_profile_minor_version = 0;
#else
constexpr auto context_profile_mask = SDL_GL_CONTEXT_PROFILE_CORE;
constexpr auto context_profile_minor_version = 1;
#endif
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, context_profile_mask);
#if defined(DEBUG)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, context_profile_minor_version);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
if (fullscreen)
flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, flags);
if (!gl_context)
gl_context = SDL_GL_CreateContext(static_cast<SDL_Window*>(window));
if (SDL_GL_SetSwapInterval(-1))
SDL_GL_SetSwapInterval(1);
setupView();
}
void Window::handleEvent(const SDL_Event& event)
{
switch(event.type)
{
case SDL_MOUSEBUTTONDOWN:
{
sp::io::Pointer::Button button = sp::io::Pointer::Button::Unknown;
switch(event.button.button)
{
case SDL_BUTTON_LEFT: button = sp::io::Pointer::Button::Left; break;
case SDL_BUTTON_MIDDLE: button = sp::io::Pointer::Button::Middle; break;
case SDL_BUTTON_RIGHT: button = sp::io::Pointer::Button::Right; break;
default: break;
}
mouse_button_down_mask |= 1 << int(event.button.button);
render_chain->onPointerDown(button, mapPixelToCoords({event.button.x, event.button.y}), sp::io::Pointer::mouse);
}
break;
case SDL_MOUSEMOTION:
if (mouse_button_down_mask)
render_chain->onPointerDrag(mapPixelToCoords({event.motion.x, event.motion.y}), sp::io::Pointer::mouse);
else
render_chain->onPointerMove(mapPixelToCoords({event.motion.x, event.motion.y}), sp::io::Pointer::mouse);
break;
case SDL_MOUSEBUTTONUP:
mouse_button_down_mask &=~(1 << int(event.button.button));
if (!mouse_button_down_mask)
{
render_chain->onPointerUp(mapPixelToCoords({event.button.x, event.button.y}), sp::io::Pointer::mouse);
render_chain->onPointerMove(mapPixelToCoords({event.button.x, event.button.y}), sp::io::Pointer::mouse);
}
break;
case SDL_FINGERDOWN:
render_chain->onPointerDown(sp::io::Pointer::Button::Touch, {event.tfinger.x * current_virtual_size.x, event.tfinger.y * current_virtual_size.y}, event.tfinger.fingerId);
break;
case SDL_FINGERMOTION:
render_chain->onPointerDrag({event.tfinger.x * current_virtual_size.x, event.tfinger.y * current_virtual_size.y}, event.tfinger.fingerId);
break;
case SDL_FINGERUP:
render_chain->onPointerUp({event.tfinger.x * current_virtual_size.x, event.tfinger.y * current_virtual_size.y}, event.tfinger.fingerId);
break;
case SDL_TEXTINPUT:
render_chain->onTextInput(event.text.text);
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_KP_4:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_LEFT:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordLeftWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordLeft);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::LeftWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Left);
break;
case SDLK_KP_6:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_RIGHT:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordRightWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordRight);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::RightWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Right);
break;
case SDLK_KP_8:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_UP:
if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::UpWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Up);
break;
case SDLK_KP_2:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_DOWN:
if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::DownWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Down);
break;
case SDLK_KP_7:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_HOME:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextStartWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextStart);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::LineStartWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::LineStart);
break;
case SDLK_KP_1:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_END:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextEndWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextEnd);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::LineEndWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::LineEnd);
break;
case SDLK_KP_PERIOD:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_DELETE:
render_chain->onTextInput(sp::TextInputEvent::Delete);
break;
case SDLK_BACKSPACE:
render_chain->onTextInput(sp::TextInputEvent::Backspace);
break;
case SDLK_KP_ENTER:
case SDLK_RETURN:
render_chain->onTextInput(sp::TextInputEvent::Return);
break;
case SDLK_TAB:
case SDLK_KP_TAB:
if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::Unindent);
else
render_chain->onTextInput(sp::TextInputEvent::Indent);
break;
case SDLK_a:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::SelectAll);
break;
case SDLK_c:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::Copy);
break;
case SDLK_v:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::Paste);
break;
case SDLK_x:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::Cut);
break;
}
break;
case SDL_WINDOWEVENT:
switch(event.window.event)
{
case SDL_WINDOWEVENT_LEAVE:
if (!SDL_GetMouseState(nullptr, nullptr))
{
render_chain->onPointerLeave(-1);
}
break;
case SDL_WINDOWEVENT_CLOSE:
//close();
break;
case SDL_WINDOWEVENT_RESIZED:
setupView();
break;
}
break;
case SDL_QUIT:
//close();
break;
default:
break;
}
}
void Window::setupView()
{
int w, h;
SDL_GetWindowSize(static_cast<SDL_Window*>(window), &w, &h);
glm::vec2 window_size{w, h};
current_virtual_size = minimal_virtual_size;
if (window_size.x / window_size.y > current_virtual_size.x / current_virtual_size.y)
{
current_virtual_size.x = current_virtual_size.y / window_size.y * window_size.x;
}else{
current_virtual_size.y = current_virtual_size.x / window_size.x * window_size.y;
}
}
<commit_msg>Fix fullscreen toggle, and put each window on a different monitor if available.<commit_after>#include "windowManager.h"
#ifdef WIN32
#include "dynamicLibrary.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include "graphics/opengl.h"
#include "Updatable.h"
#include "Renderable.h"
#include "collisionable.h"
#include "postProcessManager.h"
#include "input.h"
#include <glm/gtc/type_ptr.hpp>
#include <cmath>
#include <SDL.h>
PVector<Window> Window::all_windows;
void* Window::gl_context = nullptr;
Window::Window(glm::vec2 virtual_size, bool fullscreen, RenderChain* render_chain, int fsaa)
: minimal_virtual_size(virtual_size), current_virtual_size(virtual_size), render_chain(render_chain), fullscreen(fullscreen), fsaa(fsaa)
{
srand(static_cast<int32_t>(time(nullptr)));
#ifdef _WIN32
//On Vista or newer windows, let the OS know we are DPI aware, so we won't have odd scaling issues.
auto user32 = DynamicLibrary::open("USER32.DLL");
if (user32)
{
auto SetProcessDPIAware = user32->getFunction<BOOL(WINAPI *)(void)>("SetProcessDPIAware");
if (SetProcessDPIAware)
SetProcessDPIAware();
}
#endif
create();
sp::initOpenGL();
all_windows.push_back(this);
}
Window::~Window()
{
}
void Window::render()
{
//#warning SDL2 TODO
/*
if (InputHandler::keyboardIsPressed(sf::Keyboard::Return) && (sf::Keyboard::isKeyPressed(sf::Keyboard::LAlt) || sf::Keyboard::isKeyPressed(sf::Keyboard::RAlt)))
{
setFullscreen(!isFullscreen());
}
*/
SDL_GL_MakeCurrent(static_cast<SDL_Window*>(window), gl_context);
int w, h;
SDL_GL_GetDrawableSize(static_cast<SDL_Window*>(window), &w, &h);
glViewport(0, 0, w, h);
// Clear the window
glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Call the first item of the rendering chain.
sp::RenderTarget target{current_virtual_size, {w, h}};
render_chain->render(target);
target.finish();
// Display things on screen
SDL_GL_SwapWindow(static_cast<SDL_Window*>(window));
}
void Window::setFullscreen(bool new_fullscreen)
{
if (fullscreen == new_fullscreen)
return;
fullscreen = new_fullscreen;
SDL_SetWindowFullscreen(static_cast<SDL_Window*>(window), fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0);
setupView();
}
void Window::setFSAA(int new_fsaa)
{
if (fsaa == new_fsaa)
return;
fsaa = new_fsaa;
create();
}
void Window::setTitle(string title)
{
SDL_SetWindowTitle(static_cast<SDL_Window*>(window), title.c_str());
}
glm::vec2 Window::mapPixelToCoords(const glm::ivec2 point) const
{
int w, h;
SDL_GetWindowSize(static_cast<SDL_Window*>(window), &w, &h);
float x = float(point.x) / float(w) * float(current_virtual_size.x);
float y = float(point.y) / float(h) * float(current_virtual_size.y);
return glm::vec2(x, y);
}
glm::ivec2 Window::mapCoordsToPixel(const glm::vec2 point) const
{
int w, h;
SDL_GetWindowSize(static_cast<SDL_Window*>(window), &w, &h);
float x = float(point.x) * float(w) / float(current_virtual_size.x);
float y = float(point.y) * float(h) / float(current_virtual_size.y);
return glm::ivec2(x, y);
}
void Window::create()
{
if (window) return;
int display_nr = 0;
for(auto w : all_windows)
{
if (w == this)
break;
display_nr ++;
}
// Create the window of the application
auto windowWidth = static_cast<int>(minimal_virtual_size.x);
auto windowHeight = static_cast<int>(minimal_virtual_size.y);
SDL_Rect rect;
if (SDL_GetDisplayBounds(display_nr, &rect))
{
display_nr = 0;
SDL_GetDisplayBounds(display_nr, &rect);
}
int scale = 2;
while(windowWidth * scale < int(rect.w) && windowHeight * scale < int(rect.h))
scale += 1;
windowWidth *= scale - 1;
windowHeight *= scale - 1;
while(windowWidth >= int(rect.w) || windowHeight >= int(rect.h) - 100)
{
windowWidth = static_cast<int>(std::floor(windowWidth * 0.9f));
windowHeight = static_cast<int>(std::floor(windowHeight * 0.9f));
}
#if defined(ANDROID)
constexpr auto context_profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
constexpr auto context_profile_minor_version = 0;
#else
constexpr auto context_profile_mask = SDL_GL_CONTEXT_PROFILE_CORE;
constexpr auto context_profile_minor_version = 1;
#endif
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, context_profile_mask);
#if defined(DEBUG)
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
#endif
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, context_profile_minor_version);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
if (fullscreen)
flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
window = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED_DISPLAY(display_nr), SDL_WINDOWPOS_CENTERED_DISPLAY(display_nr), windowWidth, windowHeight, flags);
if (!gl_context)
gl_context = SDL_GL_CreateContext(static_cast<SDL_Window*>(window));
if (SDL_GL_SetSwapInterval(-1))
SDL_GL_SetSwapInterval(1);
setupView();
}
void Window::handleEvent(const SDL_Event& event)
{
switch(event.type)
{
case SDL_MOUSEBUTTONDOWN:
{
sp::io::Pointer::Button button = sp::io::Pointer::Button::Unknown;
switch(event.button.button)
{
case SDL_BUTTON_LEFT: button = sp::io::Pointer::Button::Left; break;
case SDL_BUTTON_MIDDLE: button = sp::io::Pointer::Button::Middle; break;
case SDL_BUTTON_RIGHT: button = sp::io::Pointer::Button::Right; break;
default: break;
}
mouse_button_down_mask |= 1 << int(event.button.button);
render_chain->onPointerDown(button, mapPixelToCoords({event.button.x, event.button.y}), sp::io::Pointer::mouse);
}
break;
case SDL_MOUSEMOTION:
if (mouse_button_down_mask)
render_chain->onPointerDrag(mapPixelToCoords({event.motion.x, event.motion.y}), sp::io::Pointer::mouse);
else
render_chain->onPointerMove(mapPixelToCoords({event.motion.x, event.motion.y}), sp::io::Pointer::mouse);
break;
case SDL_MOUSEBUTTONUP:
mouse_button_down_mask &=~(1 << int(event.button.button));
if (!mouse_button_down_mask)
{
render_chain->onPointerUp(mapPixelToCoords({event.button.x, event.button.y}), sp::io::Pointer::mouse);
render_chain->onPointerMove(mapPixelToCoords({event.button.x, event.button.y}), sp::io::Pointer::mouse);
}
break;
case SDL_FINGERDOWN:
render_chain->onPointerDown(sp::io::Pointer::Button::Touch, {event.tfinger.x * current_virtual_size.x, event.tfinger.y * current_virtual_size.y}, event.tfinger.fingerId);
break;
case SDL_FINGERMOTION:
render_chain->onPointerDrag({event.tfinger.x * current_virtual_size.x, event.tfinger.y * current_virtual_size.y}, event.tfinger.fingerId);
break;
case SDL_FINGERUP:
render_chain->onPointerUp({event.tfinger.x * current_virtual_size.x, event.tfinger.y * current_virtual_size.y}, event.tfinger.fingerId);
break;
case SDL_TEXTINPUT:
render_chain->onTextInput(event.text.text);
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_KP_4:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_LEFT:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordLeftWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordLeft);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::LeftWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Left);
break;
case SDLK_KP_6:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_RIGHT:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordRightWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::WordRight);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::RightWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Right);
break;
case SDLK_KP_8:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_UP:
if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::UpWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Up);
break;
case SDLK_KP_2:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_DOWN:
if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::DownWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::Down);
break;
case SDLK_KP_7:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_HOME:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextStartWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextStart);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::LineStartWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::LineStart);
break;
case SDLK_KP_1:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_END:
if (event.key.keysym.mod & KMOD_SHIFT && event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextEndWithSelection);
else if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::TextEnd);
else if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::LineEndWithSelection);
else
render_chain->onTextInput(sp::TextInputEvent::LineEnd);
break;
case SDLK_KP_PERIOD:
if (event.key.keysym.mod & KMOD_NUM)
break;
//fallthrough
case SDLK_DELETE:
render_chain->onTextInput(sp::TextInputEvent::Delete);
break;
case SDLK_BACKSPACE:
render_chain->onTextInput(sp::TextInputEvent::Backspace);
break;
case SDLK_KP_ENTER:
case SDLK_RETURN:
render_chain->onTextInput(sp::TextInputEvent::Return);
break;
case SDLK_TAB:
case SDLK_KP_TAB:
if (event.key.keysym.mod & KMOD_SHIFT)
render_chain->onTextInput(sp::TextInputEvent::Unindent);
else
render_chain->onTextInput(sp::TextInputEvent::Indent);
break;
case SDLK_a:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::SelectAll);
break;
case SDLK_c:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::Copy);
break;
case SDLK_v:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::Paste);
break;
case SDLK_x:
if (event.key.keysym.mod & KMOD_CTRL)
render_chain->onTextInput(sp::TextInputEvent::Cut);
break;
}
break;
case SDL_WINDOWEVENT:
switch(event.window.event)
{
case SDL_WINDOWEVENT_LEAVE:
if (!SDL_GetMouseState(nullptr, nullptr))
{
render_chain->onPointerLeave(-1);
}
break;
case SDL_WINDOWEVENT_CLOSE:
//close();
break;
case SDL_WINDOWEVENT_RESIZED:
setupView();
break;
}
break;
case SDL_QUIT:
//close();
break;
default:
break;
}
}
void Window::setupView()
{
int w, h;
SDL_GetWindowSize(static_cast<SDL_Window*>(window), &w, &h);
glm::vec2 window_size{w, h};
current_virtual_size = minimal_virtual_size;
if (window_size.x / window_size.y > current_virtual_size.x / current_virtual_size.y)
{
current_virtual_size.x = current_virtual_size.y / window_size.y * window_size.x;
}else{
current_virtual_size.y = current_virtual_size.x / window_size.x * window_size.y;
}
}
<|endoftext|> |
<commit_before>/**
* ZNC Mailer Module
*
* A ZNC Module that uses the Unix mail command to send mentions and private
* messages to an email address when you are not connected to ZNC.
*
* Copyright (c) 2011 Dougal Matthews
* Licensed under the MIT license
*/
#include <main.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <Modules.h>
#include <IRCSock.h>
#include <User.h>
#include <Nick.h>
#include <Chan.h>
class CMailerTimer: public CTimer {
public:
CMailerTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CMailerTimer() {}
protected:
virtual void RunJob();
};
class CMailer : public CModule {
protected:
CUser *ConnectedUser;
list<CString> MessagesList;
CString NotificationSubject;
CString NotificationEmail;
unsigned int MaxNotifications;
bool DebugMode;
public:
MODCONSTRUCTOR(CMailer) {
ConnectedUser = GetUser();
DebugMode = false;
NotificationSubject = "IRC Notification";
}
virtual ~CMailer() {}
void DebugPrint(string sMessage){
if (DebugMode){
PutModule(sMessage);
}
}
virtual bool OnLoad(const CString& sArgs, CString& sErrorMsg) {
AddTimer(new CMailerTimer(this, 1200, 0, "Mail", "Send emails every 20 mins."));
MaxNotifications = 50;
PutModule("Please tell me what email address you want notifications to be sent to with 'email <address>'");
VCString tokens;
int token_count = sArgs.Split(" ", tokens, false);
if (token_count < 1)
{
return true;
}
CString action = tokens[0].AsLower();
if (action == "debug"){
PutModule("DEBUG ON");
DebugMode = true;
}
return true;
}
virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {
Handle(Nick, Channel.GetName(), sMessage);
return CONTINUE;
}
virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) {
Handle(Nick, "PRIVATE", sMessage);
return CONTINUE;
}
void OnModCommand(const CString& command)
{
VCString tokens;
int token_count = command.Split(" ", tokens, false);
if (token_count < 1)
{
return;
}
CString action = tokens[0].AsLower();
if (action == "email"){
if (token_count < 2)
{
PutModule("Email: " + NotificationEmail);
PutModule("Usage: email <email address>");
return;
}
NotificationEmail = tokens[1].AsLower();
PutModule("email address set");
} else if (action == "subject"){
if (token_count < 2)
{
PutModule("Subject: " + NotificationSubject);
PutModule("Usage: subject <email subject>");
return;
}
NotificationSubject = tokens[1].AsLower();
PutModule("email subject set.");
} else if (action == "help") {
PutModule("View the documentation at...");
} else {
if (!DebugMode){
PutModule("Error: invalid command, try `help`");
}
}
DebugCommands(command);
}
void DebugCommands(const CString& command){
if (!DebugMode){
return;
}
VCString tokens;
int token_count = command.Split(" ", tokens, false);
if (token_count < 1)
{
return;
}
CString action = tokens[0].AsLower();
if (action == "testemail"){
CString message;
message = "This is a testing email.";
Send(message);
} else if (action == "testfull"){
CString message = "Testing";
MessagesList.push_front(message);
BatchSend();
} else if (action == "testshowqueue"){
list<CString>::iterator it;
CString message;
for ( it=MessagesList.begin() ; it != MessagesList.end(); it++ ){
DebugPrint(*it);
}
} else if (action == "testbatchsend"){
BatchSend();
}
}
void Handle(CNick& Nick, const CString& location, CString& sMessage){
if (SendNotification(Nick, sMessage) || location == "PRIVATE"){
CString message = "<" + location + ":" + Nick.GetNick() + "> " + sMessage + "\n\n";
MessagesList.push_front(message);
DebugPrint("Added message...");
DebugPrint(message);
if (MessagesList.size() > MaxNotifications){
MessagesList.pop_back();
}
}
}
bool SendNotification(CNick& Nick, CString& sMessage){
// Don't send notifications if DebugMode is off and the ConnectedUser is not attached.
if (!DebugMode && ConnectedUser->IsUserAttached()){
return false;
}
CString UserNick = ConnectedUser->GetNick().AsLower();
size_t found = sMessage.AsLower().find(UserNick);
if (found!=string::npos){
return true;
} else {
return false;
}
}
void BatchSend(){
if (!DebugMode && ConnectedUser->IsUserAttached()){
return;
}
list<CString>::iterator it;
CString message;
if (MessagesList.size() <= 0){
return;
}
for ( it=MessagesList.begin() ; it != MessagesList.end(); it++ ){
message = message + *it;
}
Send(message);
MessagesList.erase(MessagesList.begin(),MessagesList.end());
}
void Send(CString& sMessage){
CString command;
command = "mail -s '" + NotificationSubject + "' " + NotificationEmail;
if (DebugMode){
DebugPrint(command);
}
DebugPrint("Sending");
FILE *email= popen(command.c_str(), "w");
if (!email){
PutModule("Problems with mail command.");
return;
}
fprintf(email, "%s", (char*) sMessage.c_str());
pclose(email);
DebugPrint(sMessage);
DebugPrint("Sent");
}
};
void CMailerTimer::RunJob(){
CMailer *p = (CMailer *)m_pModule;
p->BatchSend();
}
MODULEDEFS(CMailer, "To be used to send mentions as an email")
<commit_msg>Reverse the batch processing, to make sure the messages are in chronological order with oldest at the bottom.<commit_after>/**
* ZNC Mailer Module
*
* A ZNC Module that uses the Unix mail command to send mentions and private
* messages to an email address when you are not connected to ZNC.
*
* Copyright (c) 2011 Dougal Matthews
* Licensed under the MIT license
*/
#include <main.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <Modules.h>
#include <IRCSock.h>
#include <User.h>
#include <Nick.h>
#include <Chan.h>
class CMailerTimer: public CTimer {
public:
CMailerTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
virtual ~CMailerTimer() {}
protected:
virtual void RunJob();
};
class CMailer : public CModule {
protected:
CUser *ConnectedUser;
list<CString> MessagesList;
CString NotificationSubject;
CString NotificationEmail;
unsigned int MaxNotifications;
bool DebugMode;
public:
MODCONSTRUCTOR(CMailer) {
ConnectedUser = GetUser();
DebugMode = false;
NotificationSubject = "IRC Notification";
}
virtual ~CMailer() {}
void DebugPrint(string sMessage){
if (DebugMode){
PutModule(sMessage);
}
}
virtual bool OnLoad(const CString& sArgs, CString& sErrorMsg) {
AddTimer(new CMailerTimer(this, 1200, 0, "Mail", "Send emails every 20 mins."));
MaxNotifications = 50;
PutModule("Please tell me what email address you want notifications to be sent to with 'email <address>'");
VCString tokens;
int token_count = sArgs.Split(" ", tokens, false);
if (token_count < 1)
{
return true;
}
CString action = tokens[0].AsLower();
if (action == "debug"){
PutModule("DEBUG ON");
DebugMode = true;
}
return true;
}
virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {
Handle(Nick, Channel.GetName(), sMessage);
return CONTINUE;
}
virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) {
Handle(Nick, "PRIVATE", sMessage);
return CONTINUE;
}
void OnModCommand(const CString& command)
{
VCString tokens;
int token_count = command.Split(" ", tokens, false);
if (token_count < 1)
{
return;
}
CString action = tokens[0].AsLower();
if (action == "email"){
if (token_count < 2)
{
PutModule("Email: " + NotificationEmail);
PutModule("Usage: email <email address>");
return;
}
NotificationEmail = tokens[1].AsLower();
PutModule("email address set");
} else if (action == "subject"){
if (token_count < 2)
{
PutModule("Subject: " + NotificationSubject);
PutModule("Usage: subject <email subject>");
return;
}
NotificationSubject = tokens[1].AsLower();
PutModule("email subject set.");
} else if (action == "help") {
PutModule("View the documentation at...");
} else {
if (!DebugMode){
PutModule("Error: invalid command, try `help`");
}
}
DebugCommands(command);
}
void DebugCommands(const CString& command){
if (!DebugMode){
return;
}
VCString tokens;
int token_count = command.Split(" ", tokens, false);
if (token_count < 1)
{
return;
}
CString action = tokens[0].AsLower();
if (action == "testemail"){
CString message;
message = "This is a testing email.";
Send(message);
} else if (action == "testfull"){
CString message = "Testing";
MessagesList.push_front(message);
BatchSend();
} else if (action == "testshowqueue"){
list<CString>::iterator it;
CString message;
for ( it=MessagesList.begin() ; it != MessagesList.end(); it++ ){
DebugPrint(*it);
}
} else if (action == "testbatchsend"){
BatchSend();
}
}
void Handle(CNick& Nick, const CString& location, CString& sMessage){
if (SendNotification(Nick, sMessage) || location == "PRIVATE"){
CString message = "<" + location + ":" + Nick.GetNick() + "> " + sMessage + "\n\n";
MessagesList.push_front(message);
DebugPrint("Added message...");
DebugPrint(message);
if (MessagesList.size() > MaxNotifications){
MessagesList.pop_back();
}
}
}
bool SendNotification(CNick& Nick, CString& sMessage){
// Don't send notifications if DebugMode is off and the ConnectedUser is not attached.
if (!DebugMode && ConnectedUser->IsUserAttached()){
return false;
}
CString UserNick = ConnectedUser->GetNick().AsLower();
size_t found = sMessage.AsLower().find(UserNick);
if (found!=string::npos){
return true;
} else {
return false;
}
}
void BatchSend(){
if (!DebugMode && ConnectedUser->IsUserAttached()){
return;
}
list<CString>::iterator it;
CString message;
if (MessagesList.size() <= 0){
return;
}
for ( it=MessagesList.end() ; it != MessagesList.begin(); it-- ){
message = message + *it;
}
Send(message);
MessagesList.erase(MessagesList.begin(),MessagesList.end());
}
void Send(CString& sMessage){
CString command;
command = "mail -s '" + NotificationSubject + "' " + NotificationEmail;
if (DebugMode){
DebugPrint(command);
}
DebugPrint("Sending");
FILE *email= popen(command.c_str(), "w");
if (!email){
PutModule("Problems with mail command.");
return;
}
fprintf(email, "%s", (char*) sMessage.c_str());
pclose(email);
DebugPrint(sMessage);
DebugPrint("Sent");
}
};
void CMailerTimer::RunJob(){
CMailer *p = (CMailer *)m_pModule;
p->BatchSend();
}
MODULEDEFS(CMailer, "To be used to send mentions as an email")
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/program_options.hpp>
#include <plasp/sas/Description.h>
#include <plasp/sas/TranslatorASP.h>
int main(int argc, char **argv)
{
namespace po = boost::program_options;
po::options_description description("Allowed options");
description.add_options()
("help,h", "Display this help message.")
("version,v", "Display version information.")
("input,i", po::value<std::string>(), "Specify the SAS input file.");
po::positional_options_description positionalOptionsDescription;
positionalOptionsDescription.add("input", -1);
po::variables_map variablesMap;
const auto printHelp =
[&]()
{
std::cout << "Usage: plasp file [options]" << std::endl;
std::cout << "Translate PDDL instances to ASP facts." << std::endl << std::endl;
std::cout << description;
};
try
{
po::store(po::command_line_parser(argc, argv)
.options(description)
.positional(positionalOptionsDescription)
.run(),
variablesMap);
po::notify(variablesMap);
}
catch (const po::error &e)
{
std::cerr << "Error: " << e.what() << std::endl << std::endl;
printHelp();
return EXIT_FAILURE;
}
if (variablesMap.count("help"))
{
printHelp();
return EXIT_SUCCESS;
}
if (variablesMap.count("version"))
{
std::cout << "plasp version 3.0.0" << std::endl;
return EXIT_SUCCESS;
}
if (!variablesMap.count("input"))
{
std::cerr << "Error: No input file specified" << std::endl << std::endl;
printHelp();
return EXIT_FAILURE;
}
try
{
const auto sasDescription = plasp::sas::Description::fromFile(variablesMap["input"].as<std::string>());
const auto sasTranslator = plasp::sas::TranslatorASP(sasDescription);
sasTranslator.translate(std::cout);
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl << std::endl;
printHelp();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Added support for input from std::cin.<commit_after>#include <iostream>
#include <boost/program_options.hpp>
#include <plasp/sas/Description.h>
#include <plasp/sas/TranslatorASP.h>
int main(int argc, char **argv)
{
namespace po = boost::program_options;
po::options_description description("Allowed options");
description.add_options()
("help,h", "Display this help message.")
("version,v", "Display version information.")
("input,i", po::value<std::string>(), "Specify the SAS input file.");
po::positional_options_description positionalOptionsDescription;
positionalOptionsDescription.add("input", -1);
po::variables_map variablesMap;
const auto printHelp =
[&]()
{
std::cout << "Usage: plasp file [options]" << std::endl;
std::cout << "Translate PDDL instances to ASP facts." << std::endl << std::endl;
std::cout << description;
};
try
{
po::store(po::command_line_parser(argc, argv)
.options(description)
.positional(positionalOptionsDescription)
.run(),
variablesMap);
po::notify(variablesMap);
}
catch (const po::error &e)
{
std::cerr << "Error: " << e.what() << std::endl << std::endl;
printHelp();
return EXIT_FAILURE;
}
if (variablesMap.count("help"))
{
printHelp();
return EXIT_SUCCESS;
}
if (variablesMap.count("version"))
{
std::cout << "plasp version 3.0.0" << std::endl;
return EXIT_SUCCESS;
}
try
{
const auto sasDescription = variablesMap.count("input")
? plasp::sas::Description::fromFile(variablesMap["input"].as<std::string>())
: plasp::sas::Description::fromStream(std::cin);
const auto sasTranslator = plasp::sas::TranslatorASP(sasDescription);
sasTranslator.translate(std::cout);
}
catch (const std::exception &e)
{
std::cerr << "Error: " << e.what() << std::endl << std::endl;
printHelp();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Multi-aligner
#include "malign.h"
using namespace std;
/*
* MAligner
*/
MAligner::MAligner(int nseq, char** seqs, char** names){
global_matrix = (dp_matrix*) malloc(sizeof(dp_matrix));
global_matrix->matrix = NULL;
global_matrix->size = 0;
for( int ii = 0; ii < nseq; ++ii ){
MAlignerEntry *en = new MAlignerEntry(names[ii], seqs[ii], global_matrix);
entries.insert(pair<string,MAlignerEntry*>(string(seqs[ii]),en));
}
}
MAligner::~MAligner(){
if( global_matrix->matrix != NULL ){
free(global_matrix->matrix);
}
free(global_matrix);
}
priority_queue<MAlignerEntry*> MAligner::align(char* input){
queue<MAlignerEntry*> robin;
map<string, MAlignerEntry*>::iterator entry_itr;
int len = strlen(input);
for( entry_itr = entries.begin(); entry_itr != entries.end(); entry_itr++ ){
MAlignerEntry *e = (*entry_itr).second;
e->initialize(input, len);
robin.push(e);
}
return this->roundRobin(robin);
}
priority_queue<MAlignerEntry*> MAligner::alignWith(char* input, int nnames, char** names){
queue<MAlignerEntry*> robin;
int len = strlen(input);
map<string,MAlignerEntry*>::iterator search_itr;
for( int ii = 0; ii < nnames ; ++ii ){
search_itr = entries.find(string(names[ii]));
if( search_itr != entries.end() ){
(*search_itr).second->initialize(input, len);
robin.push( (*search_itr).second );
}
}
return this->roundRobin(robin);
}
priority_queue<MAlignerEntry*> MAligner::roundRobin(queue<MAlignerEntry*> robin){
priority_queue<MAlignerEntry*> results;
int bestLowerBound = MINVAL;
while( !robin.empty() ){
MAlignerEntry *mae = robin.front();
robin.pop();
if( mae->upperBound() > bestLowerBound ){
mae->step();
if( mae->lowerBound() > bestLowerBound ){
bestLowerBound = mae->lowerBound();
}
if( mae->upperBound() >= bestLowerBound
&& !mae->isAligned() ){
robin.push(mae);
}
}
if( mae->isAligned() ){
results.push(mae);
}
}
return results;
}
bool MAligner::initialize(char* input){
map<string, MAlignerEntry*>::iterator entry_itr;
int len = strlen(input);
for( entry_itr = entries.begin() ; entry_itr != entries.end() ; entry_itr++ ){
(*entry_itr).second->initialize(input, len);
}
return true;
}
/*
* MAlignerEntry
*/
MAlignerEntry::MAlignerEntry(const char *nm, const char *seq, dp_matrix *dp){
this->name = (char*) malloc(strlen(nm) + 1);
this->refSequence = (char*) malloc(strlen(seq) + 1);
this->testSequence = NULL;
strcpy(this->name, nm);
strcpy(this->refSequence, seq);
this->ref_length = strlen(this->refSequence);
this->dpm = dp;
this->num_rows = NULL;
this->num_cols = NULL; // initialize this when we load it with a sequence
this->uBound = MINVAL;
this->lBound = MINVAL;
this->matrix_size = MINVAL;
this->gap = -1;
this->match = 1;
this->mismatch = -1;
this->initialized = false;
this->setLowerBound(0,0,0);
this->setUpperBound(0,0,0);
}
MAlignerEntry::~MAlignerEntry(){
free(this->name);
free(this->refSequence);
}
bool MAlignerEntry::isAligned() {
return aligned;
}
const bool MAlignerEntry::operator< (MAlignerEntry& entry){
return this->getScore() > entry.getScore();
}
const bool MAlignerEntry::operator> (MAlignerEntry& entry){
return this->getScore() < entry.getScore();
}
int MAlignerEntry::getScore(){
return score;
}
int MAlignerEntry::upperBound(){
return this->uBound;
}
int MAlignerEntry::lowerBound(){
return this->lBound;
}
int MAlignerEntry::setUpperBound(int x, int y, int score){
if( !this->initialized ){ return MINVAL; }
int d = min(this->num_cols - x, this->num_rows - y); // get the maximum score along the diagonal
int h = max(this->num_cols - x - d, this->num_rows - y - d);
assert(h >= 0);
this->uBound = score + d * this->match - h * this->gap;
return uBound;
}
int MAlignerEntry::setLowerBound(int x, int y, int score){
if( !this->initialized ){ return MINVAL; }
int perimeter = (this->num_cols - x) + (this->num_rows - y);
int mismatchPath = min(this->num_cols - x, this->num_rows - y);
int mismatchPerimeter =
max(this->num_cols - x - mismatchPath, this->num_rows - y - mismatchPath);
/*
assert(perimeter >= 0);
assert(mismatchPath >= 0);
assert(mismatchPerimeter >= 0);
*/
int perimeterScore = perimeter * this->gap;
int mismatchScore = mismatchPath * this->mismatch + mismatchPerimeter * this->gap;
this->lBound = score + max(perimeterScore, mismatchScore);
return lBound;
}
int MAlignerEntry::grow(bool growLeft, bool growRight){
if( growLeft ){
this->left = min(this->left * 2, this->num_cols / 2);
}
if( growRight ){
this->right = min(this->right * 2, this->num_cols / 2);
}
int l = this->left;
int r = this->right;
int d = this->num_rows - this->num_cols;
this->matrix_size =
this->num_rows
* (l + r + 1)
- (l * (l + 1) / 2)
- (r * (r + 1) / 2)
- (r * d)
- (d * (d+1) / 2); // account for left hand overflow and the diagonal
printf("diff: %d Left: %d Right: %d Rows: %d Cols: %d Size: %d\n", d, l, r, this->num_rows, this->num_cols, this->matrix_size);
// Ask for a bigger scratch space if we need it
if(this->dpm->size < this->matrix_size ){
free(this->dpm->matrix);
this->dpm->matrix = (int*) malloc(sizeof(int) * this->matrix_size);
this->dpm->size = this->matrix_size;
}
return this->matrix_size;
}
bool MAlignerEntry::initialize(const char* testSeq, int len=0){
this->test_length = strlen(testSeq);
//printf("Initialized entry with '%s' and length %d...\n", testSeq, len);
this->testSequence = (char*) malloc(this->test_length + 1);
strcpy(this->testSequence, testSeq);
// test will be the row
if( this->test_length > this->ref_length ) {
this->row_seq = this->testSequence;
this->num_rows = this->test_length;
this->col_seq = this->refSequence;
this->num_cols = this->ref_length;
// reference will be the row
} else {
this->row_seq = this->refSequence;
this->num_rows = this->ref_length;
this->col_seq = this->testSequence;
this->num_cols = this->test_length;
}
this->initialized = true;
this->left = (this->num_cols < this->num_rows ? this->num_rows - this->num_cols : 1);
this->right = 1;
this->aligned = false;
grow(false, false);
return true;
}
int MAlignerEntry::align(){
if( !this->initialized ) { return MINVAL; }
while( !this->isAligned() ){
this->step();
}
return getScore();
}
bool MAlignerEntry::step(){
int num_rows = this->num_rows;
int num_cols = this->num_cols;
int *prevRow = NULL;
int *thisRow = this->dpm->matrix;
bool boundary = false;
const int left = this->left;
const int right = this->right;
int ii = 0;
for(int y = 0; y < num_rows; ++y ){
int start = (y >= left ? y - left : 0 );
int stop = (num_cols < y + right + 1 ? num_cols : y + right + 1);
int lmax = MINVAL;
int rmax = MINVAL;
int line_max = MINVAL;
int max_x, max_y;
int rowOffset = 0;
// This offset is necessary for the cases where the lefthand side of
// the search window falls outside of the DP matrix.
// By doing this we can avoid any sort of zany offset garbage.
if( start == 0 ){
prevRow = prevRow - 1;
}
for( int x = start ; x < stop; ++x){
assert( (ii > 0 && !(x == 0 && y == 0)) || ii == 0 );
// add a matrix entry
int t = this->scoreDP(x, y, rowOffset, prevRow, thisRow);
// we need to know if we've run into a boundary
if( x == start && x > 0){ lmax = t; }
if( x == stop - 1 && x < num_cols - 1){ rmax = t; }
if( t > line_max ){
line_max = t;
max_x = x;
max_y = y;
}
++rowOffset;
++ii;
}
prevRow = thisRow;
thisRow = thisRow + rowOffset; //TODO off by one?
// if we've hit a boundary, short circuit our way out of the loop
// and increase the boundary sizes
if( num_cols > y + right + 1 ){
bool grow_left = false;
bool grow_right = false;
if( line_max == lmax
&& this->left != this->num_cols / 2 ){
boundary = true;
grow_left = true;
}
if( line_max == rmax
&& this->right != this->num_cols / 2){
boundary = true;
grow_right = true;
}
if( boundary ){
this->grow(grow_left, grow_right);
this->setUpperBound(max_x, max_y, line_max);
this->setLowerBound(max_x, max_y, line_max);
return MINVAL;
}
}
}
int s = this->dpm->matrix[ii - 1];
if( !boundary ){
this->aligned = true;
this->score = s;
return s;
}
return MINVAL;
}
int MAlignerEntry::scoreDP(
int x,
int y,
int rowOffset,
int *prevRow,
int *thisRow) {
int leftVal = MINVAL;
int upVal = MINVAL;
int upleftVal = this->gap * x + this->gap * y;
const char* row_seq = this->row_seq;
const char* col_seq = this->col_seq;
if(rowOffset > 0 ){
leftVal = thisRow[rowOffset - 1] + this->gap;
} else {
leftVal = MINVAL;
}
if(y > 0 && x > 0){
upleftVal = prevRow[rowOffset] + (row_seq[y] == col_seq[x] ? this->match : this->mismatch );
} else {
upleftVal = upleftVal + (row_seq[y] == col_seq[x] ? this->match : this->mismatch);
}
if((y > 0)
&& ( prevRow + rowOffset + 1 < thisRow )){
upVal = prevRow[rowOffset + 1] + this->gap;
} else {
upVal = MINVAL;
}
thisRow[rowOffset] = max(upleftVal, max(leftVal, upVal));
//printf("<%p, %p, %p> [x:%d y:%d] %d (%p)\n", upVal, leftVal, upleftVal, x, y, *(thisRow + rowOffset), (thisRow + rowOffset));
return thisRow[rowOffset];
}
int main(int argc, char** argv){
dp_matrix *dpm = (dp_matrix*) malloc(sizeof(dp_matrix));
dpm->matrix = NULL;
dpm->size = 0;
MAlignerEntry *aligner = new MAlignerEntry(string("Sample").c_str(), string("ABCDEFGHIJKL").c_str(), dpm);
aligner->initialize(string("ABCDEFGHIJKLMNOP").c_str());
aligner->align();
printf("%d\n", aligner->getScore());
//aligner->initialize(string("XXXXXXXXXXXX").c_str());
//aligner->align();
//aligner->initialize(string("XXXXXXX").c_str());
//aligner->align();
//aligner->initialize(string("ABCDEFG").c_str());
//aligner->align();
delete aligner;
return 0;
}
<commit_msg>Upper and lower bounds are set on completed alignment. Better Multi-aligner destructor.<commit_after>// Multi-aligner
#include "malign.h"
using namespace std;
/*
* MAligner
*/
MAligner::MAligner(int nseq, char** seqs, char** names){
global_matrix = (dp_matrix*) malloc(sizeof(dp_matrix));
global_matrix->matrix = NULL;
global_matrix->size = 0;
for( int ii = 0; ii < nseq; ++ii ){
MAlignerEntry *en = new MAlignerEntry(names[ii], seqs[ii], global_matrix);
entries.insert(pair<string,MAlignerEntry*>(string(seqs[ii]),en));
}
}
MAligner::~MAligner(){
list<MAlignerEntry*>::iterator entry_itr;
for( entry_itr = this->entries->begin() ; entry_itr != this->entries->end(); entry_itr++ ){
delete (*entry_itr);
}
if( global_matrix->matrix != NULL ){
free(global_matrix->matrix);
}
free(global_matrix);
}
priority_queue<MAlignerEntry*> MAligner::align(char* input){
queue<MAlignerEntry*> robin;
map<string, MAlignerEntry*>::iterator entry_itr;
int len = strlen(input);
for( entry_itr = entries.begin(); entry_itr != entries.end(); entry_itr++ ){
MAlignerEntry *e = (*entry_itr).second;
e->initialize(input, len);
robin.push(e);
}
return this->roundRobin(robin);
}
priority_queue<MAlignerEntry*> MAligner::alignWith(char* input, int nnames, char** names){
queue<MAlignerEntry*> robin;
int len = strlen(input);
map<string,MAlignerEntry*>::iterator search_itr;
for( int ii = 0; ii < nnames ; ++ii ){
search_itr = entries.find(string(names[ii]));
if( search_itr != entries.end() ){
(*search_itr).second->initialize(input, len);
robin.push( (*search_itr).second );
}
}
return this->roundRobin(robin);
}
priority_queue<MAlignerEntry*> MAligner::roundRobin(queue<MAlignerEntry*> robin){
priority_queue<MAlignerEntry*> results;
int bestLowerBound = MINVAL;
while( !robin.empty() ){
MAlignerEntry *mae = robin.front();
robin.pop();
if( mae->upperBound() > bestLowerBound ){
mae->step();
if( mae->lowerBound() > bestLowerBound ){
bestLowerBound = mae->lowerBound();
}
if( mae->upperBound() >= bestLowerBound
&& !mae->isAligned() ){
robin.push(mae);
}
}
if( mae->isAligned() ){
results.push(mae);
}
}
return results;
}
bool MAligner::initialize(char* input){
map<string, MAlignerEntry*>::iterator entry_itr;
int len = strlen(input);
for( entry_itr = entries.begin() ; entry_itr != entries.end() ; entry_itr++ ){
(*entry_itr).second->initialize(input, len);
}
return true;
}
/*
* MAlignerEntry
*/
MAlignerEntry::MAlignerEntry(const char *nm, const char *seq, dp_matrix *dp){
// copy the reference into place
this->name = (char*) malloc(strlen(nm) + 1);
this->refSequence = (char*) malloc(strlen(seq) + 1);
this->testSequence = NULL;
strcpy(this->name, nm);
strcpy(this->refSequence, seq);
this->ref_length = strlen(this->refSequence);
this->dpm = dp;
this->num_rows = NULL;
this->num_cols = NULL; // initialize this when we load it with a sequence
this->uBound = MINVAL;
this->lBound = MINVAL;
this->matrix_size = MINVAL;
this->gap = -1;
this->match = 1;
this->mismatch = -1;
this->initialized = false;
this->setLowerBound(0,0,0);
this->setUpperBound(0,0,0);
}
MAlignerEntry::~MAlignerEntry(){
free(this->name);
free(this->refSequence);
if( this->testSequence ){ free(this->testSequence); }
}
bool MAlignerEntry::isAligned() {
return aligned;
}
const bool MAlignerEntry::operator< (MAlignerEntry& entry){
return this->getScore() > entry.getScore();
}
const bool MAlignerEntry::operator> (MAlignerEntry& entry){
return this->getScore() < entry.getScore();
}
int MAlignerEntry::getScore(){
return score;
}
int MAlignerEntry::upperBound(){
return this->uBound;
}
int MAlignerEntry::lowerBound(){
return this->lBound;
}
int MAlignerEntry::setUpperBound(int x, int y, int score){
if( !this->initialized ){ return MINVAL; }
int d = min(this->num_cols - x, this->num_rows - y); // get the maximum score along the diagonal
int h = max(this->num_cols - x - d, this->num_rows - y - d);
assert(h >= 0);
this->uBound = score + d * this->match - h * this->gap;
return uBound;
}
int MAlignerEntry::setLowerBound(int x, int y, int score){
if( !this->initialized ){ return MINVAL; }
int perimeter = (this->num_cols - x) + (this->num_rows - y);
int mismatchPath = min(this->num_cols - x, this->num_rows - y);
int mismatchPerimeter =
max(this->num_cols - x - mismatchPath, this->num_rows - y - mismatchPath);
/*
assert(perimeter >= 0);
assert(mismatchPath >= 0);
assert(mismatchPerimeter >= 0);
*/
int perimeterScore = perimeter * this->gap;
int mismatchScore = mismatchPath * this->mismatch + mismatchPerimeter * this->gap;
this->lBound = score + max(perimeterScore, mismatchScore);
return lBound;
}
int MAlignerEntry::grow(bool growLeft, bool growRight){
if( growLeft ){
this->left = min(this->left * 2, this->num_cols / 2);
}
if( growRight ){
this->right = min(this->right * 2, this->num_cols / 2);
}
int l = this->left;
int r = this->right;
int d = this->num_rows - this->num_cols;
this->matrix_size =
this->num_rows
* (l + r + 1)
- (l * (l + 1) / 2)
- (r * (r + 1) / 2)
- (r * d)
- (d * (d+1) / 2); // account for left hand overflow and the diagonal
printf("diff: %d Left: %d Right: %d Rows: %d Cols: %d Size: %d\n", d, l, r, this->num_rows, this->num_cols, this->matrix_size);
// Ask for a bigger scratch space if we need it
if(this->dpm->size < this->matrix_size ){
free(this->dpm->matrix);
this->dpm->matrix = (int*) malloc(sizeof(int) * this->matrix_size);
this->dpm->size = this->matrix_size;
}
return this->matrix_size;
}
bool MAlignerEntry::initialize(const char* testSeq, int len=0){
this->test_length = strlen(testSeq);
//printf("Initialized entry with '%s' and length %d...\n", testSeq, len);
this->testSequence = (char*) malloc(this->test_length + 1);
strcpy(this->testSequence, testSeq);
// test will be the row
if( this->test_length > this->ref_length ) {
this->row_seq = this->testSequence;
this->num_rows = this->test_length;
this->col_seq = this->refSequence;
this->num_cols = this->ref_length;
// reference will be the row
} else {
this->row_seq = this->refSequence;
this->num_rows = this->ref_length;
this->col_seq = this->testSequence;
this->num_cols = this->test_length;
}
this->initialized = true;
this->left = (this->num_cols < this->num_rows ? this->num_rows - this->num_cols : 1);
this->right = 1;
this->aligned = false;
grow(false, false);
return true;
}
int MAlignerEntry::align(){
if( !this->initialized ) { return MINVAL; }
while( !this->isAligned() ){
this->step();
}
return getScore();
}
bool MAlignerEntry::step(){
int num_rows = this->num_rows;
int num_cols = this->num_cols;
int *prevRow = NULL;
int *thisRow = this->dpm->matrix;
bool boundary = false;
const int left = this->left;
const int right = this->right;
int ii = 0;
for(int y = 0; y < num_rows; ++y ){
int start = (y >= left ? y - left : 0 );
int stop = (num_cols < y + right + 1 ? num_cols : y + right + 1);
int lmax = MINVAL;
int rmax = MINVAL;
int line_max = MINVAL;
int max_x, max_y;
int rowOffset = 0;
// This offset is necessary for the cases where the lefthand side of
// the search window falls outside of the DP matrix.
// By doing this we can avoid any sort of zany offset garbage.
if( start == 0 ){
prevRow = prevRow - 1;
}
for( int x = start ; x < stop; ++x){
assert( (ii > 0 && !(x == 0 && y == 0)) || ii == 0 );
// add a matrix entry
int t = this->scoreDP(x, y, rowOffset, prevRow, thisRow);
// we need to know if we've run into a boundary
if( x == start && x > 0){ lmax = t; }
if( x == stop - 1 && x < num_cols - 1){ rmax = t; }
if( t > line_max ){
line_max = t;
max_x = x;
max_y = y;
}
++rowOffset;
++ii;
}
prevRow = thisRow;
thisRow = thisRow + rowOffset; //TODO off by one?
// if we've hit a boundary, short circuit our way out of the loop
// and increase the boundary sizes
if( num_cols > y + right + 1 ){
bool grow_left = false;
bool grow_right = false;
if( line_max == lmax
&& this->left != this->num_cols / 2 ){
boundary = true;
grow_left = true;
}
if( line_max == rmax
&& this->right != this->num_cols / 2){
boundary = true;
grow_right = true;
}
if( boundary ){
this->grow(grow_left, grow_right);
this->setUpperBound(max_x, max_y, line_max);
this->setLowerBound(max_x, max_y, line_max);
return MINVAL;
}
}
}
int s = this->dpm->matrix[ii - 1];
if( !boundary ){
this->aligned = true;
this->score = s;
this->uBound = s;
this->lBound = s;
return s;
}
return MINVAL;
}
int MAlignerEntry::scoreDP(
int x,
int y,
int rowOffset,
int *prevRow,
int *thisRow) {
int leftVal = MINVAL;
int upVal = MINVAL;
int upleftVal = this->gap * x + this->gap * y;
const char* row_seq = this->row_seq;
const char* col_seq = this->col_seq;
if(rowOffset > 0 ){
leftVal = thisRow[rowOffset - 1] + this->gap;
} else {
leftVal = MINVAL;
}
if(y > 0 && x > 0){
upleftVal = prevRow[rowOffset] + (row_seq[y] == col_seq[x] ? this->match : this->mismatch );
} else {
upleftVal = upleftVal + (row_seq[y] == col_seq[x] ? this->match : this->mismatch);
}
if((y > 0)
&& ( prevRow + rowOffset + 1 < thisRow )){
upVal = prevRow[rowOffset + 1] + this->gap;
} else {
upVal = MINVAL;
}
thisRow[rowOffset] = max(upleftVal, max(leftVal, upVal));
//printf("<%p, %p, %p> [x:%d y:%d] %d (%p)\n", upVal, leftVal, upleftVal, x, y, *(thisRow + rowOffset), (thisRow + rowOffset));
return thisRow[rowOffset];
}
int main(int argc, char** argv){
dp_matrix *dpm = (dp_matrix*) malloc(sizeof(dp_matrix));
dpm->matrix = NULL;
dpm->size = 0;
MAlignerEntry *aligner = new MAlignerEntry(string("Sample").c_str(), string("ABCDEFGHIJKL").c_str(), dpm);
aligner->initialize(string("XXXXXXXXXXXXXXXXXXX").c_str());
aligner->align();
printf("%d (%d,%d)\n", aligner->getScore(), aligner->lowerBound(), aligner->upperBound());
//aligner->initialize(string("XXXXXXXXXXXX").c_str());
//aligner->align();
//aligner->initialize(string("XXXXXXX").c_str());
//aligner->align();
//aligner->initialize(string("ABCDEFG").c_str());
//aligner->align();
delete aligner;
return 0;
}
<|endoftext|> |
<commit_before>// $Id: fourth_error_estimators.C,v 1.5 2005-06-11 03:59:18 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm> // for std::fill
#include <math.h> // for sqrt
// Local Includes
#include "libmesh_common.h"
#include "fourth_error_estimators.h"
#include "dof_map.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "mesh.h"
#include "system.h"
//-----------------------------------------------------------------
// ErrorEstimator implementations
#ifndef ENABLE_SECOND_DERIVATIVES
void LaplacianErrorEstimator::estimate_error (const System&,
std::vector<float>&)
{
std::cerr << "ERROR: This functionalitry requires second-derivative support!"
<< std::endl;
error();
}
#else // defined (ENABLE_SECOND_DERIVATIVES)
void LaplacianErrorEstimator::estimate_error (const System& system,
std::vector<float>& error_per_cell)
{
START_LOG("laplacian_jump()", "LaplacianErrorEstimator");
/*
- e & f are global element ids
Case (1.) Elements are at the same level, e<f
Compute the laplacian jump on the face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | |
| | f |
| | |
| e |---> n |
| | |
| | |
----------------------
Case (2.) The neighbor is at a higher level.
Compute the laplacian jump on e's face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | | |
| | e |---> n |
| | | |
|-----------| f |
| | | |
| | | |
| | | |
----------------------
*/
// The current mesh
const Mesh& mesh = system.get_mesh();
// The dimensionality of the mesh
const unsigned int dim = mesh.mesh_dimension();
// The number of variables in the system
const unsigned int n_vars = system.n_vars();
// The DofMap for this system
const DofMap& dof_map = system.get_dof_map();
// Resize the error_per_cell vector to be
// the number of elements, initialize it to 0.
error_per_cell.resize (mesh.n_elem());
std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);
// Check for a valid component_mask
if (!component_mask.empty())
if (component_mask.size() != n_vars)
{
std::cerr << "ERROR: component_mask is the wrong size:"
<< std::endl
<< " component_mask.size()=" << component_mask.size()
<< std::endl
<< " n_vars=" << n_vars
<< std::endl;
error();
}
// Loop over all the variables in the system
for (unsigned int var=0; var<n_vars; var++)
{
// Possibly skip this variable
if (!component_mask.empty())
if (component_mask[var] == false) continue;
// The type of finite element to use for this variable
const FEType& fe_type = dof_map.variable_type (var);
// Finite element objects for the same face from
// different sides
AutoPtr<FEBase> fe_e (FEBase::build (dim, fe_type));
AutoPtr<FEBase> fe_f (FEBase::build (dim, fe_type));
// Build an appropriate Clough-Tocher quadrature rule
QClough qrule (dim-1, fe_type.default_quadrature_order());
// Tell the finite element for element e about the quadrature
// rule. The finite element for element f need not know about it
fe_e->attach_quadrature_rule (&qrule);
// By convention we will always do the integration
// on the face of element e. Get its Jacobian values, etc..
const std::vector<Real>& JxW_face = fe_e->get_JxW();
const std::vector<Point>& qface_point = fe_e->get_xyz();
// const std::vector<Point>& face_normals = fe_e->get_normals();
// The quadrature points on element f. These will be computed
// from the quadrature points on element e.
std::vector<Point> qp_f;
// The shape function second derivatives on elements e & f
const std::vector<std::vector<RealTensor> > & d2phi_e =
fe_e->get_d2phi();
const std::vector<std::vector<RealTensor> > & d2phi_f =
fe_f->get_d2phi();
// The global DOF indices for elements e & f
std::vector<unsigned int> dof_indices_e;
std::vector<unsigned int> dof_indices_f;
// Iterate over all the active elements in the mesh
// that live on this processor.
MeshBase::const_element_iterator elem_it =
mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end =
mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
// e is necessarily an active element on the local processor
const Elem* e = *elem_it;
const unsigned int e_id = e->id();
// Loop over the neighbors of element e
for (unsigned int n_e=0; n_e<e->n_neighbors(); n_e++)
if (e->neighbor(n_e) != NULL) // e is not on the boundary
{
const Elem* f = e->neighbor(n_e);
const unsigned int f_id = f->id();
if ( //-------------------------------------
((f->active()) &&
(f->level() == e->level()) &&
(e_id < f_id)) // Case 1.
|| //-------------------------------------
(f->level() < e->level()) // Case 2.
) //-------------------------------------
{
// Update the shape functions on side s_e of
// element e
fe_e->reinit (e, n_e);
// Build the side
AutoPtr<Elem> side (e->build_side(n_e));
// Get the maximum h for this side
const Real h = side->hmax();
// Get the DOF indices for the two elements
dof_map.dof_indices (e, dof_indices_e, var);
dof_map.dof_indices (f, dof_indices_f, var);
// The number of DOFS on each element
const unsigned int n_dofs_e = dof_indices_e.size();
const unsigned int n_dofs_f = dof_indices_f.size();
// The number of quadrature points
const unsigned int n_qp = qrule.n_points();
// Find the location of the quadrature points
// on element f
FEInterface::inverse_map (dim, fe_type, f,
qface_point, qp_f);
// Compute the shape functions on element f
// at the quadrature points of element e
fe_f->reinit (f, &qp_f);
// The error contribution from this face
Real error = 1.e-10;
// loop over the integration points on the face
for (unsigned int qp=0; qp<n_qp; qp++)
{
// The solution laplacian from each element
Number lap_e = 0., lap_f = 0.;
// Compute the solution laplacian on element e
for (unsigned int i=0; i<n_dofs_e; i++)
{
lap_e += d2phi_e[i][qp](0,0) *
system.current_solution(dof_indices_e[i]);
lap_e += d2phi_e[i][qp](1,1) *
system.current_solution(dof_indices_e[i]);
}
// Compute the solution gradient on element f
for (unsigned int i=0; i<n_dofs_f; i++)
{
lap_f += d2phi_f[i][qp](0,0) *
system.current_solution(dof_indices_f[i]);
lap_f += d2phi_f[i][qp](1,1) *
system.current_solution(dof_indices_f[i]);
}
// The flux jump at the face
const Number jump = lap_e - lap_f;
// The flux jump squared
#ifndef USE_COMPLEX_NUMBERS
const Real jump2 = jump*jump;
#else
const Real jump2 = std::norm(jump);
#endif
// Integrate the error on the face
error += JxW_face[qp]*h*jump2;
} // End quadrature point loop
// Add the error contribution to elements e & f
error_per_cell[e_id] += error;
error_per_cell[f_id] += error;
}
} // if (e->neigbor(n_e) != NULL)
} // End loop over active local elements
} // End loop over variables
// Each processor has now computed the error contribuions
// for its local elements. We need to sum the vector
// and then take the square-root of each component. Note
// that we only need to sum if we are running on multiple
// processors, and we only need to take the square-root
// if the value is nonzero. There will in general be many
// zeros for the inactive elements.
// First sum the vector
this->reduce_error(error_per_cell);
// Compute the square-root of each component.
for (unsigned int i=0; i<error_per_cell.size(); i++)
if (error_per_cell[i] != 0.)
error_per_cell[i] = sqrt(error_per_cell[i]);
STOP_LOG("laplacian_jump()", "LaplacianErrorEstimator");
}
#endif // defined (ENABLE_SECOND_DERIVATIVES)
<commit_msg>Changed component_mask to component_scale.<commit_after>// $Id: fourth_error_estimators.C,v 1.6 2005-06-14 00:14:56 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2004 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <algorithm> // for std::fill
#include <math.h> // for sqrt
// Local Includes
#include "libmesh_common.h"
#include "fourth_error_estimators.h"
#include "dof_map.h"
#include "fe.h"
#include "fe_interface.h"
#include "quadrature_clough.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "mesh.h"
#include "system.h"
//-----------------------------------------------------------------
// ErrorEstimator implementations
#ifndef ENABLE_SECOND_DERIVATIVES
void LaplacianErrorEstimator::estimate_error (const System&,
std::vector<float>&)
{
std::cerr << "ERROR: This functionalitry requires second-derivative support!"
<< std::endl;
error();
}
#else // defined (ENABLE_SECOND_DERIVATIVES)
void LaplacianErrorEstimator::estimate_error (const System& system,
std::vector<float>& error_per_cell)
{
START_LOG("laplacian_jump()", "LaplacianErrorEstimator");
/*
- e & f are global element ids
Case (1.) Elements are at the same level, e<f
Compute the laplacian jump on the face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | |
| | f |
| | |
| e |---> n |
| | |
| | |
----------------------
Case (2.) The neighbor is at a higher level.
Compute the laplacian jump on e's face and
add it as a contribution to error_per_cell[e]
and error_per_cell[f]
----------------------
| | | |
| | e |---> n |
| | | |
|-----------| f |
| | | |
| | | |
| | | |
----------------------
*/
// The current mesh
const Mesh& mesh = system.get_mesh();
// The dimensionality of the mesh
const unsigned int dim = mesh.mesh_dimension();
// The number of variables in the system
const unsigned int n_vars = system.n_vars();
// The DofMap for this system
const DofMap& dof_map = system.get_dof_map();
// Resize the error_per_cell vector to be
// the number of elements, initialize it to 0.
error_per_cell.resize (mesh.n_elem());
std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);
// Check for a valid component_mask
if (!component_scale.empty())
{
if (component_scale.size() != n_vars)
{
std::cerr << "ERROR: component_scale is the wrong size:"
<< std::endl
<< " component_scale.size()=" << component_scale.size()
<< std::endl
<< " n_vars=" << n_vars
<< std::endl;
error();
}
}
else
{
// No specified scaling. Scale all variables by one.
component_scale.resize (n_vars);
std::fill (component_scale.begin(), component_scale.end(), 1.0);
}
// Loop over all the variables in the system
for (unsigned int var=0; var<n_vars; var++)
{
// Possibly skip this variable
if (!component_scale.empty())
if (component_scale[var] == false) continue;
// The type of finite element to use for this variable
const FEType& fe_type = dof_map.variable_type (var);
// Finite element objects for the same face from
// different sides
AutoPtr<FEBase> fe_e (FEBase::build (dim, fe_type));
AutoPtr<FEBase> fe_f (FEBase::build (dim, fe_type));
// Build an appropriate Clough-Tocher quadrature rule
QClough qrule (dim-1, fe_type.default_quadrature_order());
// Tell the finite element for element e about the quadrature
// rule. The finite element for element f need not know about it
fe_e->attach_quadrature_rule (&qrule);
// By convention we will always do the integration
// on the face of element e. Get its Jacobian values, etc..
const std::vector<Real>& JxW_face = fe_e->get_JxW();
const std::vector<Point>& qface_point = fe_e->get_xyz();
// const std::vector<Point>& face_normals = fe_e->get_normals();
// The quadrature points on element f. These will be computed
// from the quadrature points on element e.
std::vector<Point> qp_f;
// The shape function second derivatives on elements e & f
const std::vector<std::vector<RealTensor> > & d2phi_e =
fe_e->get_d2phi();
const std::vector<std::vector<RealTensor> > & d2phi_f =
fe_f->get_d2phi();
// The global DOF indices for elements e & f
std::vector<unsigned int> dof_indices_e;
std::vector<unsigned int> dof_indices_f;
// Iterate over all the active elements in the mesh
// that live on this processor.
MeshBase::const_element_iterator elem_it =
mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end =
mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
// e is necessarily an active element on the local processor
const Elem* e = *elem_it;
const unsigned int e_id = e->id();
// Loop over the neighbors of element e
for (unsigned int n_e=0; n_e<e->n_neighbors(); n_e++)
if (e->neighbor(n_e) != NULL) // e is not on the boundary
{
const Elem* f = e->neighbor(n_e);
const unsigned int f_id = f->id();
if ( //-------------------------------------
((f->active()) &&
(f->level() == e->level()) &&
(e_id < f_id)) // Case 1.
|| //-------------------------------------
(f->level() < e->level()) // Case 2.
) //-------------------------------------
{
// Update the shape functions on side s_e of
// element e
fe_e->reinit (e, n_e);
// Build the side
AutoPtr<Elem> side (e->build_side(n_e));
// Get the maximum h for this side
const Real h = side->hmax();
// Get the DOF indices for the two elements
dof_map.dof_indices (e, dof_indices_e, var);
dof_map.dof_indices (f, dof_indices_f, var);
// The number of DOFS on each element
const unsigned int n_dofs_e = dof_indices_e.size();
const unsigned int n_dofs_f = dof_indices_f.size();
// The number of quadrature points
const unsigned int n_qp = qrule.n_points();
// Find the location of the quadrature points
// on element f
FEInterface::inverse_map (dim, fe_type, f,
qface_point, qp_f);
// Compute the shape functions on element f
// at the quadrature points of element e
fe_f->reinit (f, &qp_f);
// The error contribution from this face
Real error = 1.e-10;
// loop over the integration points on the face
for (unsigned int qp=0; qp<n_qp; qp++)
{
// The solution laplacian from each element
Number lap_e = 0., lap_f = 0.;
// Compute the solution laplacian on element e
for (unsigned int i=0; i<n_dofs_e; i++)
{
lap_e += d2phi_e[i][qp](0,0) *
system.current_solution(dof_indices_e[i]);
lap_e += d2phi_e[i][qp](1,1) *
system.current_solution(dof_indices_e[i]);
}
// Compute the solution gradient on element f
for (unsigned int i=0; i<n_dofs_f; i++)
{
lap_f += d2phi_f[i][qp](0,0) *
system.current_solution(dof_indices_f[i]);
lap_f += d2phi_f[i][qp](1,1) *
system.current_solution(dof_indices_f[i]);
}
// The flux jump at the face
const Number jump = lap_e - lap_f;
// The flux jump squared
#ifndef USE_COMPLEX_NUMBERS
const Real jump2 = jump*jump;
#else
const Real jump2 = std::norm(jump);
#endif
// Integrate the error on the face
error += JxW_face[qp]*h*jump2;
} // End quadrature point loop
// Add the error contribution to elements e & f
error_per_cell[e_id] += error;
error_per_cell[f_id] += error;
}
} // if (e->neigbor(n_e) != NULL)
} // End loop over active local elements
} // End loop over variables
// Each processor has now computed the error contribuions
// for its local elements. We need to sum the vector
// and then take the square-root of each component. Note
// that we only need to sum if we are running on multiple
// processors, and we only need to take the square-root
// if the value is nonzero. There will in general be many
// zeros for the inactive elements.
// First sum the vector
this->reduce_error(error_per_cell);
// Compute the square-root of each component.
for (unsigned int i=0; i<error_per_cell.size(); i++)
if (error_per_cell[i] != 0.)
error_per_cell[i] = sqrt(error_per_cell[i]);
STOP_LOG("laplacian_jump()", "LaplacianErrorEstimator");
}
#endif // defined (ENABLE_SECOND_DERIVATIVES)
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/url_request/url_request_job_manager.h"
#include "build/build_config.h"
#include "base/string_util.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_about_job.h"
#include "net/url_request/url_request_error_job.h"
#if defined(OS_WIN)
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_ftp_job.h"
#else
// TODO(playmobil): Implement on non-windows platforms.
#endif
#include "net/url_request/url_request_http_job.h"
#include "net/url_request/url_request_view_cache_job.h"
// The built-in set of protocol factories
namespace {
struct SchemeToFactory {
const char* scheme;
URLRequest::ProtocolFactory* factory;
};
} // namespace
static const SchemeToFactory kBuiltinFactories[] = {
{ "http", URLRequestHttpJob::Factory },
{ "https", URLRequestHttpJob::Factory },
#if defined(OS_WIN)
{ "file", URLRequestFileJob::Factory },
{ "ftp", URLRequestFtpJob::Factory },
#else
// TODO(playmobil): Implement on non-windows platforms.
#endif
{ "about", URLRequestAboutJob::Factory },
{ "view-cache", URLRequestViewCacheJob::Factory },
};
URLRequestJobManager::URLRequestJobManager() {
#ifndef NDEBUG
allowed_thread_ = 0;
allowed_thread_initialized_ = false;
#endif
}
URLRequestJob* URLRequestJobManager::CreateJob(URLRequest* request) const {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
// If we are given an invalid URL, then don't even try to inspect the scheme.
if (!request->url().is_valid())
return new URLRequestErrorJob(request, net::ERR_INVALID_URL);
const std::string& scheme = request->url().scheme(); // already lowercase
// We do this here to avoid asking interceptors about unsupported schemes.
if (!SupportsScheme(scheme))
return new URLRequestErrorJob(request, net::ERR_UNKNOWN_URL_SCHEME);
// THREAD-SAFETY NOTICE:
// We do not need to acquire the lock here since we are only reading our
// data structures. They should only be modified on the current thread.
// See if the request should be intercepted.
if (!(request->load_flags() & net::LOAD_DISABLE_INTERCEPT)) {
InterceptorList::const_iterator i;
for (i = interceptors_.begin(); i != interceptors_.end(); ++i) {
URLRequestJob* job = (*i)->MaybeIntercept(request);
if (job)
return job;
}
}
// See if the request should be handled by a registered protocol factory.
// If the registered factory returns null, then we want to fall-back to the
// built-in protocol factory.
FactoryMap::const_iterator i = factories_.find(scheme);
if (i != factories_.end()) {
URLRequestJob* job = i->second(request, scheme);
if (job)
return job;
}
// See if the request should be handled by a built-in protocol factory.
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) {
if (scheme == kBuiltinFactories[i].scheme) {
URLRequestJob* job = (kBuiltinFactories[i].factory)(request, scheme);
DCHECK(job); // The built-in factories are not expected to fail!
return job;
}
}
// If we reached here, then it means that a registered protocol factory
// wasn't interested in handling the URL. That is fairly unexpected, and we
// don't know have a specific error to report here :-(
return new URLRequestErrorJob(request, net::ERR_FAILED);
}
bool URLRequestJobManager::SupportsScheme(const std::string& scheme) const {
// The set of registered factories may change on another thread.
{
AutoLock locked(lock_);
if (factories_.find(scheme) != factories_.end())
return true;
}
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i)
if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme))
return true;
return false;
}
URLRequest::ProtocolFactory* URLRequestJobManager::RegisterProtocolFactory(
const std::string& scheme,
URLRequest::ProtocolFactory* factory) {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
AutoLock locked(lock_);
URLRequest::ProtocolFactory* old_factory;
FactoryMap::iterator i = factories_.find(scheme);
if (i != factories_.end()) {
old_factory = i->second;
} else {
old_factory = NULL;
}
if (factory) {
factories_[scheme] = factory;
} else if (i != factories_.end()) { // uninstall any old one
factories_.erase(i);
}
return old_factory;
}
void URLRequestJobManager::RegisterRequestInterceptor(
URLRequest::Interceptor* interceptor) {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
AutoLock locked(lock_);
DCHECK(std::find(interceptors_.begin(), interceptors_.end(), interceptor) ==
interceptors_.end());
interceptors_.push_back(interceptor);
}
void URLRequestJobManager::UnregisterRequestInterceptor(
URLRequest::Interceptor* interceptor) {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
AutoLock locked(lock_);
InterceptorList::iterator i =
std::find(interceptors_.begin(), interceptors_.end(), interceptor);
DCHECK(i != interceptors_.end());
interceptors_.erase(i);
}
<commit_msg>fix build bustage due to missing header<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/url_request/url_request_job_manager.h"
#include <algorithm>
#include "build/build_config.h"
#include "base/string_util.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_about_job.h"
#include "net/url_request/url_request_error_job.h"
#if defined(OS_WIN)
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_ftp_job.h"
#else
// TODO(playmobil): Implement on non-windows platforms.
#endif
#include "net/url_request/url_request_http_job.h"
#include "net/url_request/url_request_view_cache_job.h"
// The built-in set of protocol factories
namespace {
struct SchemeToFactory {
const char* scheme;
URLRequest::ProtocolFactory* factory;
};
} // namespace
static const SchemeToFactory kBuiltinFactories[] = {
{ "http", URLRequestHttpJob::Factory },
{ "https", URLRequestHttpJob::Factory },
#if defined(OS_WIN)
{ "file", URLRequestFileJob::Factory },
{ "ftp", URLRequestFtpJob::Factory },
#else
// TODO(playmobil): Implement on non-windows platforms.
#endif
{ "about", URLRequestAboutJob::Factory },
{ "view-cache", URLRequestViewCacheJob::Factory },
};
URLRequestJobManager::URLRequestJobManager() {
#ifndef NDEBUG
allowed_thread_ = 0;
allowed_thread_initialized_ = false;
#endif
}
URLRequestJob* URLRequestJobManager::CreateJob(URLRequest* request) const {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
// If we are given an invalid URL, then don't even try to inspect the scheme.
if (!request->url().is_valid())
return new URLRequestErrorJob(request, net::ERR_INVALID_URL);
const std::string& scheme = request->url().scheme(); // already lowercase
// We do this here to avoid asking interceptors about unsupported schemes.
if (!SupportsScheme(scheme))
return new URLRequestErrorJob(request, net::ERR_UNKNOWN_URL_SCHEME);
// THREAD-SAFETY NOTICE:
// We do not need to acquire the lock here since we are only reading our
// data structures. They should only be modified on the current thread.
// See if the request should be intercepted.
if (!(request->load_flags() & net::LOAD_DISABLE_INTERCEPT)) {
InterceptorList::const_iterator i;
for (i = interceptors_.begin(); i != interceptors_.end(); ++i) {
URLRequestJob* job = (*i)->MaybeIntercept(request);
if (job)
return job;
}
}
// See if the request should be handled by a registered protocol factory.
// If the registered factory returns null, then we want to fall-back to the
// built-in protocol factory.
FactoryMap::const_iterator i = factories_.find(scheme);
if (i != factories_.end()) {
URLRequestJob* job = i->second(request, scheme);
if (job)
return job;
}
// See if the request should be handled by a built-in protocol factory.
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) {
if (scheme == kBuiltinFactories[i].scheme) {
URLRequestJob* job = (kBuiltinFactories[i].factory)(request, scheme);
DCHECK(job); // The built-in factories are not expected to fail!
return job;
}
}
// If we reached here, then it means that a registered protocol factory
// wasn't interested in handling the URL. That is fairly unexpected, and we
// don't know have a specific error to report here :-(
return new URLRequestErrorJob(request, net::ERR_FAILED);
}
bool URLRequestJobManager::SupportsScheme(const std::string& scheme) const {
// The set of registered factories may change on another thread.
{
AutoLock locked(lock_);
if (factories_.find(scheme) != factories_.end())
return true;
}
for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i)
if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme))
return true;
return false;
}
URLRequest::ProtocolFactory* URLRequestJobManager::RegisterProtocolFactory(
const std::string& scheme,
URLRequest::ProtocolFactory* factory) {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
AutoLock locked(lock_);
URLRequest::ProtocolFactory* old_factory;
FactoryMap::iterator i = factories_.find(scheme);
if (i != factories_.end()) {
old_factory = i->second;
} else {
old_factory = NULL;
}
if (factory) {
factories_[scheme] = factory;
} else if (i != factories_.end()) { // uninstall any old one
factories_.erase(i);
}
return old_factory;
}
void URLRequestJobManager::RegisterRequestInterceptor(
URLRequest::Interceptor* interceptor) {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
AutoLock locked(lock_);
DCHECK(std::find(interceptors_.begin(), interceptors_.end(), interceptor) ==
interceptors_.end());
interceptors_.push_back(interceptor);
}
void URLRequestJobManager::UnregisterRequestInterceptor(
URLRequest::Interceptor* interceptor) {
#ifndef NDEBUG
DCHECK(IsAllowedThread());
#endif
AutoLock locked(lock_);
InterceptorList::iterator i =
std::find(interceptors_.begin(), interceptors_.end(), interceptor);
DCHECK(i != interceptors_.end());
interceptors_.erase(i);
}
<|endoftext|> |
<commit_before>/*
* module_param_cache.cpp
*
* Created on: 19 Jul 2012
* Author: andreas
*/
#include "planner_modules_pr2/module_param_cache.h"
std::string ModuleParamCache::baseNamespace = "/tfd_modules/cache";
ModuleParamCache::ModuleParamCache()
{
node = NULL;
}
void ModuleParamCache::initialize(const std::string& moduleNamespace, ros::NodeHandle* node)
{
this->node = node;
this->baseNamespace = baseNamespace;
keyPrefix = baseNamespace + "/" + moduleNamespace + "/";
}
ModuleParamCache::~ModuleParamCache()
{
}
void ModuleParamCache::clearAll()
{
ros::NodeHandle s_node = ros::NodeHandle();
if (s_node.hasParam(baseNamespace))
{
s_node.deleteParam(baseNamespace);
}
}
void ModuleParamCache::set(const std::string& key, double value)
{
ROS_INFO("[cache]: writing to cache: %s -> %f", key.c_str(), value);
node->setParam(keyPrefix + key, value);
}
bool ModuleParamCache::get(const std::string& key, double& value) const
{
ROS_INFO("[cache]: lookup in cache: %s -> %f", key.c_str(), value);
return node->getParamCached(keyPrefix + key, value);
}
<commit_msg>planner_modules_pr2: removed debug messages from module param cache<commit_after>/*
* module_param_cache.cpp
*
* Created on: 19 Jul 2012
* Author: andreas
*/
#include "planner_modules_pr2/module_param_cache.h"
std::string ModuleParamCache::baseNamespace = "/tfd_modules/cache";
ModuleParamCache::ModuleParamCache()
{
node = NULL;
}
void ModuleParamCache::initialize(const std::string& moduleNamespace, ros::NodeHandle* node)
{
this->node = node;
this->baseNamespace = baseNamespace;
keyPrefix = baseNamespace + "/" + moduleNamespace + "/";
}
ModuleParamCache::~ModuleParamCache()
{
}
void ModuleParamCache::clearAll()
{
ros::NodeHandle s_node = ros::NodeHandle();
if (s_node.hasParam(baseNamespace))
{
s_node.deleteParam(baseNamespace);
}
}
void ModuleParamCache::set(const std::string& key, double value)
{
// ROS_INFO("[cache]: writing to cache: %s -> %f", key.c_str(), value);
node->setParam(keyPrefix + key, value);
}
bool ModuleParamCache::get(const std::string& key, double& value) const
{
// ROS_INFO("[cache]: lookup in cache: %s -> %f", key.c_str(), value);
return node->getParamCached(keyPrefix + key, value);
}
<|endoftext|> |
<commit_before>#pragma once
#include "node.hpp"
#include "type.hpp"
#include "ctype.hpp"
namespace backend {
class copier
: public no_op_visitor<std::shared_ptr<node> >
{
protected:
//If you know you're not going to do any rewriting at deeper
//levels of the AST, just grab the pointer from the node
template<typename Node>
result_type get_node_ptr(const Node &n) {
return std::const_pointer_cast<node>(n.shared_from_this());
}
template<typename Type>
std::shared_ptr<type_t> get_type_ptr(const Type &n) {
return std::const_pointer_cast<type_t>(n.shared_from_this());
}
template<typename Ctype>
std::shared_ptr<ctype::type_t> get_ctype_ptr(const Ctype &n) {
return std::const_pointer_cast<ctype::type_t>(n.shared_from_this());
}
public:
using backend::no_op_visitor<std::shared_ptr<node> >::operator();
virtual result_type operator()(const literal& n) {
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new literal(n.id(), t, ct));
}
virtual result_type operator()(const name &n) {
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new name(n.id(), t, ct));
}
virtual result_type operator()(const tuple &n) {
std::vector<std::shared_ptr<expression> > n_values;
for(auto i = n.begin(); i != n.end(); i++) {
auto n_i = std::static_pointer_cast<expression>(boost::apply_visitor(*this, *i));
n_values.push_back(n_i);
}
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new tuple(std::move(n_values), t, ct));
}
virtual result_type operator()(const apply &n) {
auto n_fn = std::static_pointer_cast<name>(boost::apply_visitor(*this, n.fn()));
auto n_args = std::static_pointer_cast<tuple>((*this)(n.args()));
return result_type(new apply(n_fn, n_args));
}
virtual result_type operator()(const lambda &n) {
auto n_args = std::static_pointer_cast<tuple>((*this)(n.args()));
auto n_body = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.body()));
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new lambda(n_args, n_body, t, ct));
}
virtual result_type operator()(const closure &n) {
return result_type(new closure());
}
virtual result_type operator()(const conditional &n) {
return result_type(new conditional());
}
virtual result_type operator()(const ret &n) {
auto n_val = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.val()));
return result_type(new ret(n_val));
}
virtual result_type operator()(const bind &n) {
auto n_lhs = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.lhs()));
auto n_rhs = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.rhs()));
return result_type(new bind(n_lhs, n_rhs));
}
virtual result_type operator()(const call &n) {
auto n_sub = std::static_pointer_cast<apply>(boost::apply_visitor(*this, n.sub()));
return result_type(new call(n_sub));
}
virtual result_type operator()(const procedure &n) {
auto n_id = std::static_pointer_cast<name>((*this)(n.id()));
auto n_args = std::static_pointer_cast<tuple>((*this)(n.args()));
auto n_stmts = std::static_pointer_cast<suite>((*this)(n.stmts()));
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new procedure(n_id, n_args, n_stmts, t, ct));
}
virtual result_type operator()(const suite &n) {
std::vector<std::shared_ptr<statement> > n_stmts;
for(auto i = n.begin(); i != n.end(); i++) {
auto n_stmt = std::static_pointer_cast<statement>(boost::apply_visitor(*this, *i));
n_stmts.push_back(n_stmt);
}
return result_type(new suite(std::move(n_stmts)));
}
virtual result_type operator()(const structure &n) {
auto n_id = std::static_pointer_cast<name>((*this)(n.id()));
auto n_stmts = std::static_pointer_cast<suite>((*this)(n.stmts()));
return result_type(new structure(n_id, n_stmts));
}
virtual result_type operator()(const templated_name &n) {
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
auto n_args = std::static_pointer_cast<ctype::tuple_t>(
get_ctype_ptr(n.template_types()));
return result_type(new templated_name(n.id(), n_args, t, ct));
}
virtual result_type operator()(const include &n) {
std::shared_ptr<name> id = std::static_pointer_cast<name>(
boost::apply_visitor(*this, n.id()));
return result_type(new include(id));
}
};
}
<commit_msg>Reuse AST nodes when possible.<commit_after>#pragma once
#include "node.hpp"
#include "type.hpp"
#include "ctype.hpp"
namespace backend {
class copier
: public no_op_visitor<std::shared_ptr<node> >
{
protected:
//If you know you're not going to do any rewriting at deeper
//levels of the AST, just grab the pointer from the node
template<typename Node>
result_type get_node_ptr(const Node &n) {
return std::const_pointer_cast<node>(n.shared_from_this());
}
template<typename Type>
std::shared_ptr<type_t> get_type_ptr(const Type &n) {
return std::const_pointer_cast<type_t>(n.shared_from_this());
}
template<typename Ctype>
std::shared_ptr<ctype::type_t> get_ctype_ptr(const Ctype &n) {
return std::const_pointer_cast<ctype::type_t>(n.shared_from_this());
}
bool m_match;
void start_match() {
m_match = true;
}
template<typename T, typename U>
inline void update_match(const T& t, const U& u) {
m_match = m_match && (t == get_node_ptr(u));
}
bool is_match() {
return m_match;
}
public:
using backend::no_op_visitor<std::shared_ptr<node> >::operator();
virtual result_type operator()(const literal& n) {
return get_node_ptr(n);
}
virtual result_type operator()(const name &n) {
return get_node_ptr(n);
}
virtual result_type operator()(const tuple &n) {
start_match();
std::vector<std::shared_ptr<expression> > n_values;
for(auto i = n.begin(); i != n.end(); i++) {
auto n_i = std::static_pointer_cast<expression>(boost::apply_visitor(*this, *i));
update_match(n_i, *i);
n_values.push_back(n_i);
}
if (is_match())
return get_node_ptr(n);
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new tuple(std::move(n_values), t, ct));
}
virtual result_type operator()(const apply &n) {
auto n_fn = std::static_pointer_cast<name>(boost::apply_visitor(*this, n.fn()));
auto n_args = std::static_pointer_cast<tuple>((*this)(n.args()));
start_match();
update_match(n_fn, n.fn());
update_match(n_args, n.args());
if (is_match())
return get_node_ptr(n);
return result_type(new apply(n_fn, n_args));
}
virtual result_type operator()(const lambda &n) {
auto n_args = std::static_pointer_cast<tuple>((*this)(n.args()));
auto n_body = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.body()));
start_match();
update_match(n_args, n.args());
update_match(n_body, n.body());
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new lambda(n_args, n_body, t, ct));
}
virtual result_type operator()(const closure &n) {
return result_type(new closure());
}
virtual result_type operator()(const conditional &n) {
return result_type(new conditional());
}
virtual result_type operator()(const ret &n) {
auto n_val = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.val()));
start_match();
update_match(n_val, n.val());
if (is_match())
return get_node_ptr(n);
return result_type(new ret(n_val));
}
virtual result_type operator()(const bind &n) {
auto n_lhs = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.lhs()));
auto n_rhs = std::static_pointer_cast<expression>(boost::apply_visitor(*this, n.rhs()));
start_match();
update_match(n_lhs, n.lhs());
update_match(n_rhs, n.rhs());
if (is_match())
return get_node_ptr(n);
return result_type(new bind(n_lhs, n_rhs));
}
virtual result_type operator()(const call &n) {
auto n_sub = std::static_pointer_cast<apply>(boost::apply_visitor(*this, n.sub()));
start_match();
update_match(n_sub, n.sub());
if (is_match())
return get_node_ptr(n);
return result_type(new call(n_sub));
}
virtual result_type operator()(const procedure &n) {
auto n_id = std::static_pointer_cast<name>((*this)(n.id()));
auto n_args = std::static_pointer_cast<tuple>((*this)(n.args()));
auto n_stmts = std::static_pointer_cast<suite>((*this)(n.stmts()));
start_match();
update_match(n_id, n.id());
update_match(n_args, n.args());
update_match(n_stmts, n.stmts());
if (is_match())
return get_node_ptr(n);
std::shared_ptr<type_t> t = get_type_ptr(n.type());
std::shared_ptr<ctype::type_t> ct = get_ctype_ptr(n.ctype());
return result_type(new procedure(n_id, n_args, n_stmts, t, ct));
}
virtual result_type operator()(const suite &n) {
start_match();
std::vector<std::shared_ptr<statement> > n_stmts;
for(auto i = n.begin(); i != n.end(); i++) {
auto n_stmt = std::static_pointer_cast<statement>(boost::apply_visitor(*this, *i));
update_match(n_stmt, *i);
n_stmts.push_back(n_stmt);
}
if (is_match())
return get_node_ptr(n);
return result_type(new suite(std::move(n_stmts)));
}
virtual result_type operator()(const structure &n) {
auto n_id = std::static_pointer_cast<name>((*this)(n.id()));
auto n_stmts = std::static_pointer_cast<suite>((*this)(n.stmts()));
start_match();
update_match(n_id, n.id());
update_match(n_stmts, n.stmts());
if (is_match())
return get_node_ptr(n);
return result_type(new structure(n_id, n_stmts));
}
virtual result_type operator()(const templated_name &n) {
return get_node_ptr(n);
}
virtual result_type operator()(const include &n) {
return get_node_ptr(n);
}
};
}
<|endoftext|> |
<commit_before>/*
* Clever language
* Copyright (c) 2010 Clever 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 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.
*
* $Id: parser.y 67 2010-12-22 18:55:54Z felipensp $
*/
#include <cstdlib>
#include <iostream>
#include "opcodes.h"
#include "vm.h"
namespace clever {
/*
* Destroy the opcodes data
*/
VM::~VM(void) {
OpcodeList::iterator it = m_opcodes->begin();
while (it < m_opcodes->end()) {
if ((*it)->get_op1()) {
(*it)->get_op1()->delRef();
}
if ((*it)->get_op2()) {
(*it)->get_op2()->delRef();
}
if ((*it)->get_result()) {
(*it)->get_result()->delRef();
}
delete *it;
++it;
}
}
/*
* Displays an error message
*/
void VM::error(const char* message) const {
std::cout << "Runtime error: " << message << std::endl;
exit(1);
}
/*
* Execute the collected opcodes
*/
void VM::run(void) {
OpcodeList::iterator it = m_opcodes->begin();
m_symbols.pushVarMap(SymbolTable::var_map());
while (it < m_opcodes->end()) {
Opcode* opcode = *it;
(this->*((*it)->get_handler()))(*it);
++it;
}
m_symbols.popVarMap();
}
/*
* echo statemenet
*/
void VM::echo_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
std::cout << op1->toString() << std::endl;
}
/*
* x + y
*/
void VM::plus_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2) && op1->hasSameType(op2)) {
switch (op1->get_type()) {
case Value::STRING:
opcode->get_result()->set_value(new ConstantValue(CSTRING(op1->getString() + op2->getString())));
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() + op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
/*
* x / y
*/
void VM::div_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2) && op1->hasSameType(op2)) {
switch (op1->get_type()) {
case Value::STRING:
error("Operation not allow in strings!");
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() / op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
/*
* x - y
*/
void VM::minus_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2) && op1->hasSameType(op2)) {
switch (op1->get_type()) {
case Value::STRING:
error("Operation not allow in strings!");
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() - op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
/*
* x * y
*/
void VM::mult_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2) && op1->hasSameType(op2)) {
switch (op1->get_type()) {
case Value::STRING:
error("Operation not allow in strings!");
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() * op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
void VM::new_scope_handler(CLEVER_VM_HANDLER_ARGS) {
m_symbols.pushVarMap(SymbolTable::var_map());
}
void VM::end_scope_handler(CLEVER_VM_HANDLER_ARGS) {
m_symbols.popVarMap();
}
void VM::var_decl_handler(CLEVER_VM_HANDLER_ARGS) {
Value* value = opcode->get_op2();
value->addRef();
m_symbols.register_var(opcode->get_op1()->toString(), value);
}
} // clever
<commit_msg>- Added runtime typemismatch checking<commit_after>/*
* Clever language
* Copyright (c) 2010 Clever 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 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.
*
* $Id: parser.y 67 2010-12-22 18:55:54Z felipensp $
*/
#include <cstdlib>
#include <iostream>
#include "opcodes.h"
#include "vm.h"
namespace clever {
/*
* Destroy the opcodes data
*/
VM::~VM(void) {
OpcodeList::iterator it = m_opcodes->begin();
while (it < m_opcodes->end()) {
if ((*it)->get_op1()) {
(*it)->get_op1()->delRef();
}
if ((*it)->get_op2()) {
(*it)->get_op2()->delRef();
}
if ((*it)->get_result()) {
(*it)->get_result()->delRef();
}
delete *it;
++it;
}
}
/*
* Displays an error message
*/
void VM::error(const char* message) const {
std::cout << "Runtime error: " << message << std::endl;
exit(1);
}
/*
* Execute the collected opcodes
*/
void VM::run(void) {
OpcodeList::iterator it = m_opcodes->begin();
m_symbols.pushVarMap(SymbolTable::var_map());
while (it < m_opcodes->end()) {
Opcode* opcode = *it;
(this->*((*it)->get_handler()))(*it);
++it;
}
m_symbols.popVarMap();
}
/*
* echo statemenet
*/
void VM::echo_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
std::cout << op1->toString() << std::endl;
}
/*
* x + y
*/
void VM::plus_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2)) {
if (!op1->hasSameType(op2)) {
error("Type mismatch!");
}
switch (op1->get_type()) {
case Value::STRING:
opcode->get_result()->set_value(new ConstantValue(CSTRING(op1->getString() + op2->getString())));
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() + op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
/*
* x / y
*/
void VM::div_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2)) {
if (!op1->hasSameType(op2)) {
error("Type mismatch!");
}
switch (op1->get_type()) {
case Value::STRING:
error("Operation not allow in strings!");
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() / op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
/*
* x - y
*/
void VM::minus_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2)) {
if (!op1->hasSameType(op2)) {
error("Type mismatch!");
}
switch (op1->get_type()) {
case Value::STRING:
error("Operation not allow in strings!");
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() - op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
/*
* x * y
*/
void VM::mult_handler(CLEVER_VM_HANDLER_ARGS) {
Value* op1 = getValue(opcode->get_op1());
Value* op2 = getValue(opcode->get_op2());
if (op1->isConst() && op1->hasSameKind(op2)) {
if (!op1->hasSameType(op2)) {
error("Type mismatch!");
}
switch (op1->get_type()) {
case Value::STRING:
error("Operation not allow in strings!");
break;
case Value::INTEGER:
opcode->get_result()->set_value(new ConstantValue(op1->getInteger() * op2->getInteger()));
break;
case Value::DOUBLE:
opcode->get_result()->set_value(new ConstantValue(op1->getDouble() + op2->getDouble()));
break;
}
}
}
void VM::new_scope_handler(CLEVER_VM_HANDLER_ARGS) {
m_symbols.pushVarMap(SymbolTable::var_map());
}
void VM::end_scope_handler(CLEVER_VM_HANDLER_ARGS) {
m_symbols.popVarMap();
}
void VM::var_decl_handler(CLEVER_VM_HANDLER_ARGS) {
Value* value = opcode->get_op2();
value->addRef();
m_symbols.register_var(opcode->get_op1()->toString(), value);
}
} // clever
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: options.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:12:45 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include /*MSVC trouble: <cstring>*/ <string.h>
#ifndef _IDLC_OPTIONS_HXX_
#include <idlc/options.hxx>
#endif
using namespace rtl;
Options::Options(): m_stdin(false)
{
}
Options::~Options()
{
}
sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile)
throw( IllegalArgument )
{
sal_Bool ret = sal_True;
sal_uInt16 i=0;
if (!bCmdFile)
{
bCmdFile = sal_True;
m_program = av[0];
if (ac < 2)
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
}
i = 1;
} else
{
i = 0;
}
char *s=NULL;
for (i; i < ac; i++)
{
if (av[i][0] == '-')
{
switch (av[i][1])
{
case 'O':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-O', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
m_options["-O"] = OString(s);
break;
case 'I':
{
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-I', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
OString inc(s);
if ( inc.indexOf(';') > 0 )
{
OString tmp(s);
sal_Int32 nIndex = 0;
inc = OString();
do inc = inc + " -I" + tmp.getToken( 0, ';', nIndex ); while( nIndex != -1 );
} else
inc = OString("-I") + s;
if (m_options.count("-I") > 0)
{
OString tmp(m_options["-I"]);
tmp = tmp + " " + inc;
m_options["-I"] = tmp;
} else
{
m_options["-I"] = inc;
}
}
break;
case 'D':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-D', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i];
}
if (m_options.count("-D") > 0)
{
OString tmp(m_options["-D"]);
tmp = tmp + " " + s;
m_options["-D"] = tmp;
} else
m_options["-D"] = OString(s);
break;
case 'C':
if (av[i][2] != '\0')
{
throw IllegalArgument(OString(av[i]) + ", please check your input");
}
if (m_options.count("-C") == 0)
m_options["-C"] = OString(av[i]);
break;
case 'c':
if (av[i][2] == 'i' && av[i][3] == 'd' && av[i][4] == '\0')
{
if (m_options.count("-cid") == 0)
m_options["-cid"] = OString(av[i]);
} else
throw IllegalArgument(OString(av[i]) + ", please check your input");
break;
case 'w':
if (av[i][2] == 'e' && av[i][3] == '\0') {
if (m_options.count("-we") == 0)
m_options["-we"] = OString(av[i]);
} else {
if (av[i][2] == '\0') {
if (m_options.count("-w") == 0)
m_options["-w"] = OString(av[i]);
} else
throw IllegalArgument(OString(av[i]) + ", please check your input");
}
break;
case 'h':
case '?':
if (av[i][2] != '\0')
{
throw IllegalArgument(OString(av[i]) + ", please check your input");
} else
{
fprintf(stdout, "%s", prepareHelp().getStr());
exit(0);
}
break;
case 's':
if (/*MSVC trouble: std::*/strcmp(&av[i][2], "tdin") == 0)
{
m_stdin = true;
break;
}
// fall through
default:
throw IllegalArgument("the option is unknown" + OString(av[i]));
break;
}
} else
{
if (av[i][0] == '@')
{
FILE* cmdFile = fopen(av[i]+1, "r");
if( cmdFile == NULL )
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
} else
{
int rargc=0;
char* rargv[512];
char buffer[512];
while ( fscanf(cmdFile, "%s", buffer) != EOF )
{
rargv[rargc]= strdup(buffer);
rargc++;
}
fclose(cmdFile);
ret = initOptions(rargc, rargv, bCmdFile);
long ii = 0;
for (ii=0; ii < rargc; ii++)
{
free(rargv[ii]);
}
}
} else
{
OString name(av[i]);
name = name.toAsciiLowerCase();
if ( name.lastIndexOf(".idl") != (name.getLength() - 4) )
{
throw IllegalArgument("'" + OString(av[i]) +
"' is not a valid input file, only '*.idl' files will be accepted");
}
m_inputFiles.push_back(av[i]);
}
}
}
return ret;
}
OString Options::prepareHelp()
{
OString help("\nusing: ");
help += m_program
+ " [-options] <file_1> ... <file_n> | @<filename> | -stdin\n";
help += " <file_n> = file_n specifies one or more idl files.\n";
help += " Only files with the extension '.idl' are valid.\n";
help += " @<filename> = filename specifies the name of a command file.\n";
help += " -stdin = read idl file from standard input.\n";
help += " Options:\n";
help += " -O<path> = path specifies the output directory.\n";
help += " The generated output is a registry file with\n";
help += " the same name as the idl input file (or 'stdin'\n";
help += " for -stdin).\n";
help += " -I<path> = path specifies a directory where include\n";
help += " files will be searched by the preprocessor.\n";
help += " Multiple directories can be combined with ';'.\n";
help += " -D<name> = name defines a macro for the preprocessor.\n";
help += " -C = generate complete type information, including\n";
help += " documentation.\n";
help += " -cid = check if identifiers fulfill the UNO naming\n";
help += " requirements.\n";
help += " -w = display warning messages.\n";
help += " -we = treat warnings as errors.\n";
help += " -h|-? = print this help message and exit.\n";
help += prepareVersion();
return help;
}
OString Options::prepareVersion()
{
OString version("\nSun Microsystems (R) ");
version += m_program + " Version 1.1\n\n";
return version;
}
const OString& Options::getProgramName() const
{
return m_program;
}
sal_uInt16 Options::getNumberOfOptions() const
{
return (sal_uInt16)(m_options.size());
}
sal_Bool Options::isValid(const OString& option)
{
return (m_options.count(option) > 0);
}
const OString Options::getOption(const OString& option)
throw( IllegalArgument )
{
const OString ret;
if (m_options.count(option) > 0)
{
return m_options[option];
} else
{
throw IllegalArgument("Option is not valid or currently not set.");
}
return ret;
}
const OptionMap& Options::getOptions()
{
return m_options;
}
<commit_msg>INTEGRATION: CWS jscpp1 (1.10.24); FILE MERGED 2005/08/09 11:47:09 jsc 1.10.24.1: #i52596# improve reading command line option<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: options.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-10-17 13:20:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include /*MSVC trouble: <cstring>*/ <string.h>
#ifndef _IDLC_OPTIONS_HXX_
#include <idlc/options.hxx>
#endif
using namespace rtl;
Options::Options(): m_stdin(false)
{
}
Options::~Options()
{
}
sal_Bool Options::initOptions(int ac, char* av[], sal_Bool bCmdFile)
throw( IllegalArgument )
{
sal_Bool ret = sal_True;
sal_uInt16 i=0;
if (!bCmdFile)
{
bCmdFile = sal_True;
m_program = av[0];
if (ac < 2)
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
}
i = 1;
} else
{
i = 0;
}
char *s=NULL;
for (i; i < ac; i++)
{
if (av[i][0] == '-')
{
switch (av[i][1])
{
case 'O':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-O', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
m_options["-O"] = OString(s);
break;
case 'I':
{
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-I', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i] + 2;
}
OString inc(s);
if ( inc.indexOf(';') > 0 )
{
OString tmp(s);
sal_Int32 nIndex = 0;
inc = OString();
do inc = inc + " -I" + tmp.getToken( 0, ';', nIndex ); while( nIndex != -1 );
} else
inc = OString("-I") + s;
if (m_options.count("-I") > 0)
{
OString tmp(m_options["-I"]);
tmp = tmp + " " + inc;
m_options["-I"] = tmp;
} else
{
m_options["-I"] = inc;
}
}
break;
case 'D':
if (av[i][2] == '\0')
{
if (i < ac - 1 && av[i+1][0] != '-')
{
i++;
s = av[i];
} else
{
OString tmp("'-D', please check");
if (i <= ac - 1)
{
tmp += " your input '" + OString(av[i+1]) + "'";
}
throw IllegalArgument(tmp);
}
} else
{
s = av[i];
}
if (m_options.count("-D") > 0)
{
OString tmp(m_options["-D"]);
tmp = tmp + " " + s;
m_options["-D"] = tmp;
} else
m_options["-D"] = OString(s);
break;
case 'C':
if (av[i][2] != '\0')
{
throw IllegalArgument(OString(av[i]) + ", please check your input");
}
if (m_options.count("-C") == 0)
m_options["-C"] = OString(av[i]);
break;
case 'c':
if (av[i][2] == 'i' && av[i][3] == 'd' && av[i][4] == '\0')
{
if (m_options.count("-cid") == 0)
m_options["-cid"] = OString(av[i]);
} else
throw IllegalArgument(OString(av[i]) + ", please check your input");
break;
case 'w':
if (av[i][2] == 'e' && av[i][3] == '\0') {
if (m_options.count("-we") == 0)
m_options["-we"] = OString(av[i]);
} else {
if (av[i][2] == '\0') {
if (m_options.count("-w") == 0)
m_options["-w"] = OString(av[i]);
} else
throw IllegalArgument(OString(av[i]) + ", please check your input");
}
break;
case 'h':
case '?':
if (av[i][2] != '\0')
{
throw IllegalArgument(OString(av[i]) + ", please check your input");
} else
{
fprintf(stdout, "%s", prepareHelp().getStr());
exit(0);
}
break;
case 's':
if (/*MSVC trouble: std::*/strcmp(&av[i][2], "tdin") == 0)
{
m_stdin = true;
break;
}
// fall through
default:
throw IllegalArgument("the option is unknown" + OString(av[i]));
break;
}
} else
{
if (av[i][0] == '@')
{
FILE* cmdFile = fopen(av[i]+1, "r");
if( cmdFile == NULL )
{
fprintf(stderr, "%s", prepareHelp().getStr());
ret = sal_False;
} else
{
int rargc=0;
char* rargv[512];
char buffer[512];
int i=0;
int found = 0;
char c;
while ( fscanf(cmdFile, "%c", &c) != EOF )
{
if (c=='\"') {
if (found) {
found=0;
} else {
found=1;
continue;
}
} else {
if (c!=13 && c!=10) {
if (found || c!=' ') {
buffer[i++]=c;
continue;
}
}
if (i==0)
continue;
}
buffer[i]='\0';
found=0;
i=0;
rargv[rargc]= strdup(buffer);
rargc++;
}
fclose(cmdFile);
ret = initOptions(rargc, rargv, bCmdFile);
long ii = 0;
for (ii=0; ii < rargc; ii++)
{
free(rargv[ii]);
}
}
} else
{
OString name(av[i]);
name = name.toAsciiLowerCase();
if ( name.lastIndexOf(".idl") != (name.getLength() - 4) )
{
throw IllegalArgument("'" + OString(av[i]) +
"' is not a valid input file, only '*.idl' files will be accepted");
}
m_inputFiles.push_back(av[i]);
}
}
}
return ret;
}
OString Options::prepareHelp()
{
OString help("\nusing: ");
help += m_program
+ " [-options] <file_1> ... <file_n> | @<filename> | -stdin\n";
help += " <file_n> = file_n specifies one or more idl files.\n";
help += " Only files with the extension '.idl' are valid.\n";
help += " @<filename> = filename specifies the name of a command file.\n";
help += " -stdin = read idl file from standard input.\n";
help += " Options:\n";
help += " -O<path> = path specifies the output directory.\n";
help += " The generated output is a registry file with\n";
help += " the same name as the idl input file (or 'stdin'\n";
help += " for -stdin).\n";
help += " -I<path> = path specifies a directory where include\n";
help += " files will be searched by the preprocessor.\n";
help += " Multiple directories can be combined with ';'.\n";
help += " -D<name> = name defines a macro for the preprocessor.\n";
help += " -C = generate complete type information, including\n";
help += " documentation.\n";
help += " -cid = check if identifiers fulfill the UNO naming\n";
help += " requirements.\n";
help += " -w = display warning messages.\n";
help += " -we = treat warnings as errors.\n";
help += " -h|-? = print this help message and exit.\n";
help += prepareVersion();
return help;
}
OString Options::prepareVersion()
{
OString version("\nSun Microsystems (R) ");
version += m_program + " Version 1.1\n\n";
return version;
}
const OString& Options::getProgramName() const
{
return m_program;
}
sal_uInt16 Options::getNumberOfOptions() const
{
return (sal_uInt16)(m_options.size());
}
sal_Bool Options::isValid(const OString& option)
{
return (m_options.count(option) > 0);
}
const OString Options::getOption(const OString& option)
throw( IllegalArgument )
{
const OString ret;
if (m_options.count(option) > 0)
{
return m_options[option];
} else
{
throw IllegalArgument("Option is not valid or currently not set.");
}
return ret;
}
const OptionMap& Options::getOptions()
{
return m_options;
}
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "common/RhoPort.h"
#include "ext/rho/rhoruby.h"
extern "C" {
void mapview_create(rho_param *p)
{
//TODO: mapview_create
}
void mapview_close()
{
//TODO: mapview_close
}
VALUE mapview_state_started()
{
//TODO: mapview_state_started
return rho_ruby_create_boolean(0);
}
double mapview_state_center_lat()
{
//TODO: mapview_state_center_lat
return 0.;
}
double mapview_state_center_lon()
{
//TODO: mapview_state_center_lon
return 0.;
}
} //extern "C"
<commit_msg>fixed linkage bug<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* 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.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
#include "common/RhoPort.h"
#include "ext/rho/rhoruby.h"
extern "C" {
void mapview_create(rho_param *p)
{
//TODO: mapview_create
}
void mapview_close()
{
//TODO: mapview_close
}
VALUE mapview_state_started()
{
//TODO: mapview_state_started
return rho_ruby_create_boolean(0);
}
double mapview_state_center_lat()
{
//TODO: mapview_state_center_lat
return 0.;
}
double mapview_state_center_lon()
{
//TODO: mapview_state_center_lon
return 0.;
}
void mapview_set_file_caching_enable(int enable)
{
}
} //extern "C"
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/* Author: Luis G. Torres, Ioan Sucan */
#include "ompl/base/OptimizationObjective.h"
#include "ompl/geometric/PathGeometric.h"
#include "ompl/tools/config/MagicConstants.h"
#include "ompl/base/goals/GoalRegion.h"
#include <limits>
ompl::base::OptimizationObjective::OptimizationObjective(const SpaceInformationPtr &si) :
si_(si),
threshold_(0.0)
{
}
const std::string& ompl::base::OptimizationObjective::getDescription() const
{
return description_;
}
bool ompl::base::OptimizationObjective::isSatisfied(Cost c) const
{
return this->isCostBetterThan(c, threshold_);
}
ompl::base::Cost ompl::base::OptimizationObjective::getCostThreshold() const
{
return threshold_;
}
void ompl::base::OptimizationObjective::setCostThreshold(Cost c)
{
threshold_ = c;
}
bool ompl::base::OptimizationObjective::isCostBetterThan(Cost c1, Cost c2) const
{
return c1.value() + magic::BETTER_PATH_COST_MARGIN < c2.value();
}
bool ompl::base::OptimizationObjective::isCostEquivalentTo(Cost c1, Cost c2) const
{
//If c1 is not better than c2, and c2 is not better than c1, then they are equal
return !isCostBetterThan(c1,c2) && !isCostBetterThan(c2,c1);
bool ompl::base::OptimizationObjective::isFinite(Cost cost) const
{
return isCostBetterThan(cost, infiniteCost());
}
ompl::base::Cost ompl::base::OptimizationObjective::betterCost(Cost c1, Cost c2) const
{
return isCostBetterThan(c1, c2) ? c1 : c2;
}
ompl::base::Cost ompl::base::OptimizationObjective::combineCosts(Cost c1, Cost c2) const
{
return Cost(c1.value() + c2.value());
}
ompl::base::Cost ompl::base::OptimizationObjective::identityCost() const
{
return Cost(0.0);
}
ompl::base::Cost ompl::base::OptimizationObjective::infiniteCost() const
{
return Cost(std::numeric_limits<double>::infinity());
}
ompl::base::Cost ompl::base::OptimizationObjective::initialCost(const State *s) const
{
return identityCost();
}
ompl::base::Cost ompl::base::OptimizationObjective::terminalCost(const State *s) const
{
return identityCost();
}
bool ompl::base::OptimizationObjective::isSymmetric() const
{
return si_->getStateSpace()->hasSymmetricInterpolate();
}
ompl::base::Cost ompl::base::OptimizationObjective::averageStateCost(unsigned int numStates) const
{
StateSamplerPtr ss = si_->allocStateSampler();
State *state = si_->allocState();
Cost totalCost(this->identityCost());
for (unsigned int i = 0 ; i < numStates ; ++i)
{
ss->sampleUniform(state);
totalCost = this->combineCosts(totalCost, this->stateCost(state));
}
si_->freeState(state);
return Cost(totalCost.value() / (double)numStates);
}
void ompl::base::OptimizationObjective::setCostToGoHeuristic(const CostToGoHeuristic& costToGo)
{
costToGoFn_ = costToGo;
}
bool ompl::base::OptimizationObjective::hasCostToGoHeuristic() const
{
return static_cast<bool>(costToGoFn_);
}
ompl::base::Cost ompl::base::OptimizationObjective::costToGo(const State *state, const Goal *goal) const
{
if (hasCostToGoHeuristic())
return costToGoFn_(state, goal);
else
return this->identityCost(); // assumes that identity < all costs
}
ompl::base::Cost ompl::base::OptimizationObjective::motionCostHeuristic(const State *s1, const State *s2) const
{
return this->identityCost(); // assumes that identity < all costs
}
const ompl::base::SpaceInformationPtr& ompl::base::OptimizationObjective::getSpaceInformation() const
{
return si_;
}
ompl::base::Cost ompl::base::goalRegionCostToGo(const State *state, const Goal *goal)
{
const GoalRegion *goalRegion = goal->as<GoalRegion>();
// Ensures that all states within the goal region's threshold to
// have a cost-to-go of exactly zero.
return Cost(std::max(goalRegion->distanceGoal(state) - goalRegion->getThreshold(),
0.0));
}
ompl::base::MultiOptimizationObjective::MultiOptimizationObjective(const SpaceInformationPtr &si) :
OptimizationObjective(si),
locked_(false)
{
}
ompl::base::MultiOptimizationObjective::Component::
Component(const OptimizationObjectivePtr& obj, double weight) :
objective(obj), weight(weight)
{
}
void ompl::base::MultiOptimizationObjective::addObjective(const OptimizationObjectivePtr& objective,
double weight)
{
if (locked_)
{
throw Exception("This optimization objective is locked. No further objectives can be added.");
}
else
components_.push_back(Component(objective, weight));
}
std::size_t ompl::base::MultiOptimizationObjective::getObjectiveCount() const
{
return components_.size();
}
const ompl::base::OptimizationObjectivePtr& ompl::base::MultiOptimizationObjective::getObjective(unsigned int idx) const
{
if (components_.size() > idx)
return components_[idx].objective;
else
throw Exception("Objective index does not exist.");
}
double ompl::base::MultiOptimizationObjective::getObjectiveWeight(unsigned int idx) const
{
if (components_.size() > idx)
return components_[idx].weight;
else
throw Exception("Objective index does not exist.");
}
void ompl::base::MultiOptimizationObjective::setObjectiveWeight(unsigned int idx,
double weight)
{
if (components_.size() > idx)
components_[idx].weight = weight;
else
throw Exception("Objecitve index does not exist.");
}
void ompl::base::MultiOptimizationObjective::lock()
{
locked_ = true;
}
bool ompl::base::MultiOptimizationObjective::isLocked() const
{
return locked_;
}
ompl::base::Cost ompl::base::MultiOptimizationObjective::stateCost(const State *s) const
{
Cost c = this->identityCost();
for (std::vector<Component>::const_iterator comp = components_.begin();
comp != components_.end();
++comp)
{
c = Cost(c.value() + comp->weight * (comp->objective->stateCost(s).value()));
}
return c;
}
ompl::base::Cost ompl::base::MultiOptimizationObjective::motionCost(const State *s1,
const State *s2) const
{
Cost c = this->identityCost();
for (std::vector<Component>::const_iterator comp = components_.begin();
comp != components_.end();
++comp)
{
c = Cost(c.value() + comp->weight * (comp->objective->motionCost(s1, s2).value()));
}
return c;
}
ompl::base::OptimizationObjectivePtr ompl::base::operator+(const OptimizationObjectivePtr &a,
const OptimizationObjectivePtr &b)
{
std::vector<MultiOptimizationObjective::Component> components;
if (a)
{
if (MultiOptimizationObjective *mult = dynamic_cast<MultiOptimizationObjective*>(a.get()))
{
for (std::size_t i = 0; i < mult->getObjectiveCount(); ++i)
{
components.push_back(MultiOptimizationObjective::
Component(mult->getObjective(i),
mult->getObjectiveWeight(i)));
}
}
else
components.push_back(MultiOptimizationObjective::Component(a, 1.0));
}
if (b)
{
if (MultiOptimizationObjective *mult = dynamic_cast<MultiOptimizationObjective*>(b.get()))
{
for (std::size_t i = 0; i < mult->getObjectiveCount(); ++i)
{
components.push_back(MultiOptimizationObjective::Component(mult->getObjective(i),
mult->getObjectiveWeight(i)));
}
}
else
components.push_back(MultiOptimizationObjective::Component(b, 1.0));
}
MultiOptimizationObjective *multObj = new MultiOptimizationObjective(a->getSpaceInformation());
for (std::vector<MultiOptimizationObjective::Component>::const_iterator comp = components.begin();
comp != components.end();
++comp)
{
multObj->addObjective(comp->objective, comp->weight);
}
return OptimizationObjectivePtr(multObj);
}
ompl::base::OptimizationObjectivePtr ompl::base::operator*(double weight,
const OptimizationObjectivePtr &a)
{
std::vector<MultiOptimizationObjective::Component> components;
if (a)
{
if (MultiOptimizationObjective *mult = dynamic_cast<MultiOptimizationObjective*>(a.get()))
{
for (std::size_t i = 0; i < mult->getObjectiveCount(); ++i)
{
components.push_back(MultiOptimizationObjective
::Component(mult->getObjective(i),
weight * mult->getObjectiveWeight(i)));
}
}
else
components.push_back(MultiOptimizationObjective::Component(a, weight));
}
MultiOptimizationObjective *multObj = new MultiOptimizationObjective(a->getSpaceInformation());
for (std::vector<MultiOptimizationObjective::Component>::const_iterator comp = components.begin();
comp != components.end();
++comp)
{
multObj->addObjective(comp->objective, comp->weight);
}
return OptimizationObjectivePtr(multObj);
}
ompl::base::OptimizationObjectivePtr ompl::base::operator*(const OptimizationObjectivePtr &a,
double weight)
{
return weight * a;
}
<commit_msg>Typo.<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage 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.
*********************************************************************/
/* Author: Luis G. Torres, Ioan Sucan */
#include "ompl/base/OptimizationObjective.h"
#include "ompl/geometric/PathGeometric.h"
#include "ompl/tools/config/MagicConstants.h"
#include "ompl/base/goals/GoalRegion.h"
#include <limits>
ompl::base::OptimizationObjective::OptimizationObjective(const SpaceInformationPtr &si) :
si_(si),
threshold_(0.0)
{
}
const std::string& ompl::base::OptimizationObjective::getDescription() const
{
return description_;
}
bool ompl::base::OptimizationObjective::isSatisfied(Cost c) const
{
return this->isCostBetterThan(c, threshold_);
}
ompl::base::Cost ompl::base::OptimizationObjective::getCostThreshold() const
{
return threshold_;
}
void ompl::base::OptimizationObjective::setCostThreshold(Cost c)
{
threshold_ = c;
}
bool ompl::base::OptimizationObjective::isCostBetterThan(Cost c1, Cost c2) const
{
return c1.value() + magic::BETTER_PATH_COST_MARGIN < c2.value();
}
bool ompl::base::OptimizationObjective::isCostEquivalentTo(Cost c1, Cost c2) const
{
//If c1 is not better than c2, and c2 is not better than c1, then they are equal
return !isCostBetterThan(c1,c2) && !isCostBetterThan(c2,c1);
}
bool ompl::base::OptimizationObjective::isFinite(Cost cost) const
{
return isCostBetterThan(cost, infiniteCost());
}
ompl::base::Cost ompl::base::OptimizationObjective::betterCost(Cost c1, Cost c2) const
{
return isCostBetterThan(c1, c2) ? c1 : c2;
}
ompl::base::Cost ompl::base::OptimizationObjective::combineCosts(Cost c1, Cost c2) const
{
return Cost(c1.value() + c2.value());
}
ompl::base::Cost ompl::base::OptimizationObjective::identityCost() const
{
return Cost(0.0);
}
ompl::base::Cost ompl::base::OptimizationObjective::infiniteCost() const
{
return Cost(std::numeric_limits<double>::infinity());
}
ompl::base::Cost ompl::base::OptimizationObjective::initialCost(const State *s) const
{
return identityCost();
}
ompl::base::Cost ompl::base::OptimizationObjective::terminalCost(const State *s) const
{
return identityCost();
}
bool ompl::base::OptimizationObjective::isSymmetric() const
{
return si_->getStateSpace()->hasSymmetricInterpolate();
}
ompl::base::Cost ompl::base::OptimizationObjective::averageStateCost(unsigned int numStates) const
{
StateSamplerPtr ss = si_->allocStateSampler();
State *state = si_->allocState();
Cost totalCost(this->identityCost());
for (unsigned int i = 0 ; i < numStates ; ++i)
{
ss->sampleUniform(state);
totalCost = this->combineCosts(totalCost, this->stateCost(state));
}
si_->freeState(state);
return Cost(totalCost.value() / (double)numStates);
}
void ompl::base::OptimizationObjective::setCostToGoHeuristic(const CostToGoHeuristic& costToGo)
{
costToGoFn_ = costToGo;
}
bool ompl::base::OptimizationObjective::hasCostToGoHeuristic() const
{
return static_cast<bool>(costToGoFn_);
}
ompl::base::Cost ompl::base::OptimizationObjective::costToGo(const State *state, const Goal *goal) const
{
if (hasCostToGoHeuristic())
return costToGoFn_(state, goal);
else
return this->identityCost(); // assumes that identity < all costs
}
ompl::base::Cost ompl::base::OptimizationObjective::motionCostHeuristic(const State *s1, const State *s2) const
{
return this->identityCost(); // assumes that identity < all costs
}
const ompl::base::SpaceInformationPtr& ompl::base::OptimizationObjective::getSpaceInformation() const
{
return si_;
}
ompl::base::Cost ompl::base::goalRegionCostToGo(const State *state, const Goal *goal)
{
const GoalRegion *goalRegion = goal->as<GoalRegion>();
// Ensures that all states within the goal region's threshold to
// have a cost-to-go of exactly zero.
return Cost(std::max(goalRegion->distanceGoal(state) - goalRegion->getThreshold(),
0.0));
}
ompl::base::MultiOptimizationObjective::MultiOptimizationObjective(const SpaceInformationPtr &si) :
OptimizationObjective(si),
locked_(false)
{
}
ompl::base::MultiOptimizationObjective::Component::
Component(const OptimizationObjectivePtr& obj, double weight) :
objective(obj), weight(weight)
{
}
void ompl::base::MultiOptimizationObjective::addObjective(const OptimizationObjectivePtr& objective,
double weight)
{
if (locked_)
{
throw Exception("This optimization objective is locked. No further objectives can be added.");
}
else
components_.push_back(Component(objective, weight));
}
std::size_t ompl::base::MultiOptimizationObjective::getObjectiveCount() const
{
return components_.size();
}
const ompl::base::OptimizationObjectivePtr& ompl::base::MultiOptimizationObjective::getObjective(unsigned int idx) const
{
if (components_.size() > idx)
return components_[idx].objective;
else
throw Exception("Objective index does not exist.");
}
double ompl::base::MultiOptimizationObjective::getObjectiveWeight(unsigned int idx) const
{
if (components_.size() > idx)
return components_[idx].weight;
else
throw Exception("Objective index does not exist.");
}
void ompl::base::MultiOptimizationObjective::setObjectiveWeight(unsigned int idx,
double weight)
{
if (components_.size() > idx)
components_[idx].weight = weight;
else
throw Exception("Objecitve index does not exist.");
}
void ompl::base::MultiOptimizationObjective::lock()
{
locked_ = true;
}
bool ompl::base::MultiOptimizationObjective::isLocked() const
{
return locked_;
}
ompl::base::Cost ompl::base::MultiOptimizationObjective::stateCost(const State *s) const
{
Cost c = this->identityCost();
for (std::vector<Component>::const_iterator comp = components_.begin();
comp != components_.end();
++comp)
{
c = Cost(c.value() + comp->weight * (comp->objective->stateCost(s).value()));
}
return c;
}
ompl::base::Cost ompl::base::MultiOptimizationObjective::motionCost(const State *s1,
const State *s2) const
{
Cost c = this->identityCost();
for (std::vector<Component>::const_iterator comp = components_.begin();
comp != components_.end();
++comp)
{
c = Cost(c.value() + comp->weight * (comp->objective->motionCost(s1, s2).value()));
}
return c;
}
ompl::base::OptimizationObjectivePtr ompl::base::operator+(const OptimizationObjectivePtr &a,
const OptimizationObjectivePtr &b)
{
std::vector<MultiOptimizationObjective::Component> components;
if (a)
{
if (MultiOptimizationObjective *mult = dynamic_cast<MultiOptimizationObjective*>(a.get()))
{
for (std::size_t i = 0; i < mult->getObjectiveCount(); ++i)
{
components.push_back(MultiOptimizationObjective::
Component(mult->getObjective(i),
mult->getObjectiveWeight(i)));
}
}
else
components.push_back(MultiOptimizationObjective::Component(a, 1.0));
}
if (b)
{
if (MultiOptimizationObjective *mult = dynamic_cast<MultiOptimizationObjective*>(b.get()))
{
for (std::size_t i = 0; i < mult->getObjectiveCount(); ++i)
{
components.push_back(MultiOptimizationObjective::Component(mult->getObjective(i),
mult->getObjectiveWeight(i)));
}
}
else
components.push_back(MultiOptimizationObjective::Component(b, 1.0));
}
MultiOptimizationObjective *multObj = new MultiOptimizationObjective(a->getSpaceInformation());
for (std::vector<MultiOptimizationObjective::Component>::const_iterator comp = components.begin();
comp != components.end();
++comp)
{
multObj->addObjective(comp->objective, comp->weight);
}
return OptimizationObjectivePtr(multObj);
}
ompl::base::OptimizationObjectivePtr ompl::base::operator*(double weight,
const OptimizationObjectivePtr &a)
{
std::vector<MultiOptimizationObjective::Component> components;
if (a)
{
if (MultiOptimizationObjective *mult = dynamic_cast<MultiOptimizationObjective*>(a.get()))
{
for (std::size_t i = 0; i < mult->getObjectiveCount(); ++i)
{
components.push_back(MultiOptimizationObjective
::Component(mult->getObjective(i),
weight * mult->getObjectiveWeight(i)));
}
}
else
components.push_back(MultiOptimizationObjective::Component(a, weight));
}
MultiOptimizationObjective *multObj = new MultiOptimizationObjective(a->getSpaceInformation());
for (std::vector<MultiOptimizationObjective::Component>::const_iterator comp = components.begin();
comp != components.end();
++comp)
{
multObj->addObjective(comp->objective, comp->weight);
}
return OptimizationObjectivePtr(multObj);
}
ompl::base::OptimizationObjectivePtr ompl::base::operator*(const OptimizationObjectivePtr &a,
double weight)
{
return weight * a;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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://qt.nokia.com/contact.
**
**************************************************************************/
#include "texteditorplugin.h"
#include "findinfiles.h"
#include "findincurrentfile.h"
#include "fontsettings.h"
#include "linenumberfilter.h"
#include "texteditorconstants.h"
#include "texteditorsettings.h"
#include "textfilewizard.h"
#include "plaintexteditorfactory.h"
#include "plaintexteditor.h"
#include "storagesettings.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/editormanager/editormanager.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/texteditoractionhandler.h>
#include <find/searchresultwindow.h>
#include <utils/qtcassert.h>
#include <QtCore/QtPlugin>
#include <QtGui/QMainWindow>
#include <QtGui/QShortcut>
using namespace TextEditor;
using namespace TextEditor::Internal;
TextEditorPlugin *TextEditorPlugin::m_instance = 0;
TextEditorPlugin::TextEditorPlugin()
: m_settings(0),
m_wizard(0),
m_editorFactory(0),
m_lineNumberFilter(0),
m_searchResultWindow(0)
{
QTC_ASSERT(!m_instance, return);
m_instance = this;
}
TextEditorPlugin::~TextEditorPlugin()
{
m_instance = 0;
}
TextEditorPlugin *TextEditorPlugin::instance()
{
return m_instance;
}
// ExtensionSystem::PluginInterface
bool TextEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
if (!Core::ICore::instance()->mimeDatabase()->addMimeTypes(QLatin1String(":/texteditor/TextEditor.mimetypes.xml"), errorMessage))
return false;
Core::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
wizardParameters.setDescription(tr("Creates a text file (.txt)."));
wizardParameters.setName(tr("Text File"));
wizardParameters.setCategory(QLatin1String("O.General"));
wizardParameters.setTrCategory(tr("General"));
m_wizard = new TextFileWizard(QLatin1String(TextEditor::Constants::C_TEXTEDITOR_MIMETYPE_TEXT),
QLatin1String(Core::Constants::K_DEFAULT_TEXT_EDITOR),
QLatin1String("text$"),
wizardParameters);
// Add text file wizard
addAutoReleasedObject(m_wizard);
m_settings = new TextEditorSettings(this);
// Add plain text editor factory
m_editorFactory = new PlainTextEditorFactory;
addAutoReleasedObject(m_editorFactory);
// Goto line functionality for quick open
Core::ICore *core = Core::ICore::instance();
m_lineNumberFilter = new LineNumberFilter;
addAutoReleasedObject(m_lineNumberFilter);
int contextId = core->uniqueIDManager()->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR);
QList<int> context = QList<int>() << contextId;
Core::ActionManager *am = core->actionManager();
// Add shortcut for invoking automatic completion
QShortcut *completionShortcut = new QShortcut(core->mainWindow());
completionShortcut->setWhatsThis(tr("Triggers a completion in this scope"));
// Make sure the shortcut still works when the completion widget is active
completionShortcut->setContext(Qt::ApplicationShortcut);
Core::Command *command = am->registerShortcut(completionShortcut, Constants::COMPLETE_THIS, context);
#ifndef Q_WS_MAC
command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Space")));
#else
command->setDefaultKeySequence(QKeySequence(tr("Meta+Space")));
#endif
connect(completionShortcut, SIGNAL(activated()), this, SLOT(invokeCompletion()));
// Add shortcut for invoking quick fix options
QShortcut *quickFixShortcut = new QShortcut(core->mainWindow());
quickFixShortcut->setWhatsThis(tr("Triggers a quick fix in this scope"));
// Make sure the shortcut still works when the quick fix widget is active
quickFixShortcut->setContext(Qt::ApplicationShortcut);
Core::Command *quickFixCommand = am->registerShortcut(quickFixShortcut, Constants::QUICKFIX_THIS, context);
quickFixCommand->setDefaultKeySequence(QKeySequence(tr("Alt+Return")));
connect(quickFixShortcut, SIGNAL(activated()), this, SLOT(invokeQuickFix()));
return true;
}
void TextEditorPlugin::extensionsInitialized()
{
m_editorFactory->actionHandler()->initializeActions();
m_searchResultWindow = ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>();
connect(m_settings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
this, SLOT(updateSearchResultsFont(TextEditor::FontSettings)));
updateSearchResultsFont(m_settings->fontSettings());
addAutoReleasedObject(new FindInFiles(
ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>()));
addAutoReleasedObject(new FindInCurrentFile(
ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>()));
}
void TextEditorPlugin::initializeEditor(PlainTextEditor *editor)
{
// common actions
m_editorFactory->actionHandler()->setupActions(editor);
TextEditorSettings::instance()->initializeEditor(editor);
}
void TextEditorPlugin::invokeCompletion()
{
Core::IEditor *iface = Core::EditorManager::instance()->currentEditor();
ITextEditor *editor = qobject_cast<ITextEditor *>(iface);
if (editor)
editor->triggerCompletions();
}
void TextEditorPlugin::invokeQuickFix()
{
Core::IEditor *iface = Core::EditorManager::instance()->currentEditor();
ITextEditor *editor = qobject_cast<ITextEditor *>(iface);
if (editor)
editor->triggerQuickFix();
}
void TextEditorPlugin::updateSearchResultsFont(const FontSettings &settings)
{
if (m_searchResultWindow)
m_searchResultWindow->setTextEditorFont(QFont(settings.family(), settings.fontSize()));
}
Q_EXPORT_PLUGIN(TextEditorPlugin)
<commit_msg>zoom the search results as well (regression fix)<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** 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://qt.nokia.com/contact.
**
**************************************************************************/
#include "texteditorplugin.h"
#include "findinfiles.h"
#include "findincurrentfile.h"
#include "fontsettings.h"
#include "linenumberfilter.h"
#include "texteditorconstants.h"
#include "texteditorsettings.h"
#include "textfilewizard.h"
#include "plaintexteditorfactory.h"
#include "plaintexteditor.h"
#include "storagesettings.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/uniqueidmanager.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/editormanager/editormanager.h>
#include <extensionsystem/pluginmanager.h>
#include <texteditor/texteditoractionhandler.h>
#include <find/searchresultwindow.h>
#include <utils/qtcassert.h>
#include <QtCore/QtPlugin>
#include <QtGui/QMainWindow>
#include <QtGui/QShortcut>
using namespace TextEditor;
using namespace TextEditor::Internal;
TextEditorPlugin *TextEditorPlugin::m_instance = 0;
TextEditorPlugin::TextEditorPlugin()
: m_settings(0),
m_wizard(0),
m_editorFactory(0),
m_lineNumberFilter(0),
m_searchResultWindow(0)
{
QTC_ASSERT(!m_instance, return);
m_instance = this;
}
TextEditorPlugin::~TextEditorPlugin()
{
m_instance = 0;
}
TextEditorPlugin *TextEditorPlugin::instance()
{
return m_instance;
}
// ExtensionSystem::PluginInterface
bool TextEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
if (!Core::ICore::instance()->mimeDatabase()->addMimeTypes(QLatin1String(":/texteditor/TextEditor.mimetypes.xml"), errorMessage))
return false;
Core::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
wizardParameters.setDescription(tr("Creates a text file (.txt)."));
wizardParameters.setName(tr("Text File"));
wizardParameters.setCategory(QLatin1String("O.General"));
wizardParameters.setTrCategory(tr("General"));
m_wizard = new TextFileWizard(QLatin1String(TextEditor::Constants::C_TEXTEDITOR_MIMETYPE_TEXT),
QLatin1String(Core::Constants::K_DEFAULT_TEXT_EDITOR),
QLatin1String("text$"),
wizardParameters);
// Add text file wizard
addAutoReleasedObject(m_wizard);
m_settings = new TextEditorSettings(this);
// Add plain text editor factory
m_editorFactory = new PlainTextEditorFactory;
addAutoReleasedObject(m_editorFactory);
// Goto line functionality for quick open
Core::ICore *core = Core::ICore::instance();
m_lineNumberFilter = new LineNumberFilter;
addAutoReleasedObject(m_lineNumberFilter);
int contextId = core->uniqueIDManager()->uniqueIdentifier(TextEditor::Constants::C_TEXTEDITOR);
QList<int> context = QList<int>() << contextId;
Core::ActionManager *am = core->actionManager();
// Add shortcut for invoking automatic completion
QShortcut *completionShortcut = new QShortcut(core->mainWindow());
completionShortcut->setWhatsThis(tr("Triggers a completion in this scope"));
// Make sure the shortcut still works when the completion widget is active
completionShortcut->setContext(Qt::ApplicationShortcut);
Core::Command *command = am->registerShortcut(completionShortcut, Constants::COMPLETE_THIS, context);
#ifndef Q_WS_MAC
command->setDefaultKeySequence(QKeySequence(tr("Ctrl+Space")));
#else
command->setDefaultKeySequence(QKeySequence(tr("Meta+Space")));
#endif
connect(completionShortcut, SIGNAL(activated()), this, SLOT(invokeCompletion()));
// Add shortcut for invoking quick fix options
QShortcut *quickFixShortcut = new QShortcut(core->mainWindow());
quickFixShortcut->setWhatsThis(tr("Triggers a quick fix in this scope"));
// Make sure the shortcut still works when the quick fix widget is active
quickFixShortcut->setContext(Qt::ApplicationShortcut);
Core::Command *quickFixCommand = am->registerShortcut(quickFixShortcut, Constants::QUICKFIX_THIS, context);
quickFixCommand->setDefaultKeySequence(QKeySequence(tr("Alt+Return")));
connect(quickFixShortcut, SIGNAL(activated()), this, SLOT(invokeQuickFix()));
return true;
}
void TextEditorPlugin::extensionsInitialized()
{
m_editorFactory->actionHandler()->initializeActions();
m_searchResultWindow = ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>();
connect(m_settings, SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
this, SLOT(updateSearchResultsFont(TextEditor::FontSettings)));
updateSearchResultsFont(m_settings->fontSettings());
addAutoReleasedObject(new FindInFiles(
ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>()));
addAutoReleasedObject(new FindInCurrentFile(
ExtensionSystem::PluginManager::instance()->getObject<Find::SearchResultWindow>()));
}
void TextEditorPlugin::initializeEditor(PlainTextEditor *editor)
{
// common actions
m_editorFactory->actionHandler()->setupActions(editor);
TextEditorSettings::instance()->initializeEditor(editor);
}
void TextEditorPlugin::invokeCompletion()
{
Core::IEditor *iface = Core::EditorManager::instance()->currentEditor();
ITextEditor *editor = qobject_cast<ITextEditor *>(iface);
if (editor)
editor->triggerCompletions();
}
void TextEditorPlugin::invokeQuickFix()
{
Core::IEditor *iface = Core::EditorManager::instance()->currentEditor();
ITextEditor *editor = qobject_cast<ITextEditor *>(iface);
if (editor)
editor->triggerQuickFix();
}
void TextEditorPlugin::updateSearchResultsFont(const FontSettings &settings)
{
if (m_searchResultWindow)
m_searchResultWindow->setTextEditorFont(QFont(settings.family(),
settings.fontSize() * settings.fontZoom() / 100));
}
Q_EXPORT_PLUGIN(TextEditorPlugin)
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
// TestCameraBBox.h
#include <gtest/gtest.h>
#include <test/Helpers.h>
#include <vw/Cartography/CameraBBox.h>
#include <vw/Camera/PinholeModel.h>
using namespace vw;
using namespace vw::cartography;
using namespace vw::test;
using namespace vw::camera;
// Must have protobuf to be able to read camera
#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1
class CameraBBoxTest : public ::testing::Test {
protected:
virtual void SetUp() {
apollo = boost::shared_ptr<CameraModel>(new PinholeModel("apollo.pinhole"));
moon.set_well_known_geogcs("D_MOON");
}
boost::shared_ptr<CameraModel> apollo;
GeoReference moon;
};
TEST_F( CameraBBoxTest, GeospatialIntersectDatum ) {
for ( unsigned i = 0; i < 10; i++ ) {
Vector2 input_image( rand()%4096, rand()%4096 );
bool did_intersect;
Vector2 lonlat =
geospatial_intersect( input_image, moon,
apollo, 1, did_intersect );
ASSERT_TRUE( did_intersect );
double radius = moon.datum().radius( lonlat[0], lonlat[1] );
EXPECT_NEAR( radius, 1737400, 1e-3 );
Vector3 llr( lonlat[0], lonlat[1], 0 );
Vector3 ecef = moon.datum().geodetic_to_cartesian(llr);
Vector3 llr2 = moon.datum().cartesian_to_geodetic(ecef);
EXPECT_VECTOR_NEAR( llr2, llr, 1e-4 );
Vector2 retrn_image = apollo->point_to_pixel( ecef );
EXPECT_VECTOR_NEAR( retrn_image, input_image, 1e-3 );
}
}
TEST_F( CameraBBoxTest, CameraBBoxDatum ) {
float scale; // degrees per pixel
BBox2 image_bbox = camera_bbox( moon, apollo, 4096, 4096, scale );
EXPECT_VECTOR_NEAR( image_bbox.min(), Vector2(86,-1), 2 );
EXPECT_VECTOR_NEAR( image_bbox.max(), Vector2(95,7), 2 );
EXPECT_NEAR( scale, (95-86.)/sqrt(4096*4096*2), 1e-3 ); // Cam is rotated
}
TEST_F( CameraBBoxTest, CameraBBoxDEM ) {
ImageView<float> DEM(20,20); // DEM covering lat {10,-10} long {80,100}
for ( uint i = 0; i < 20; i++ )
for ( uint j = 0; j <20; j++ )
DEM(i,j) = 1000 - 10*(pow(10.-i,2.)+pow(10.-j,2));
Matrix<double> geotrans = vw::math::identity_matrix<3>();
geotrans(0,2) = 80;
geotrans(1,1) = -1;
geotrans(1,2) = 10;
moon.set_transform(geotrans);
BBox2 image_bbox = camera_bbox( DEM, moon, apollo, 4096, 4096 );
EXPECT_VECTOR_NEAR( image_bbox.min(), Vector2(87,0), 2 );
EXPECT_VECTOR_NEAR( image_bbox.max(), Vector2(94,6), 2 );
}
#endif
<commit_msg>needs a TEST_SRCDIR<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
// TestCameraBBox.h
#include <gtest/gtest.h>
#include <test/Helpers.h>
#include <vw/Cartography/CameraBBox.h>
#include <vw/Camera/PinholeModel.h>
using namespace vw;
using namespace vw::cartography;
using namespace vw::test;
using namespace vw::camera;
// Must have protobuf to be able to read camera
#if defined(VW_HAVE_PKG_PROTOBUF) && VW_HAVE_PKG_PROTOBUF==1
class CameraBBoxTest : public ::testing::Test {
protected:
virtual void SetUp() {
apollo = boost::shared_ptr<CameraModel>(new PinholeModel(TEST_SRCDIR"/apollo.pinhole"));
moon.set_well_known_geogcs("D_MOON");
}
boost::shared_ptr<CameraModel> apollo;
GeoReference moon;
};
TEST_F( CameraBBoxTest, GeospatialIntersectDatum ) {
for ( unsigned i = 0; i < 10; i++ ) {
Vector2 input_image( rand()%4096, rand()%4096 );
bool did_intersect;
Vector2 lonlat =
geospatial_intersect( input_image, moon,
apollo, 1, did_intersect );
ASSERT_TRUE( did_intersect );
double radius = moon.datum().radius( lonlat[0], lonlat[1] );
EXPECT_NEAR( radius, 1737400, 1e-3 );
Vector3 llr( lonlat[0], lonlat[1], 0 );
Vector3 ecef = moon.datum().geodetic_to_cartesian(llr);
Vector3 llr2 = moon.datum().cartesian_to_geodetic(ecef);
EXPECT_VECTOR_NEAR( llr2, llr, 1e-4 );
Vector2 retrn_image = apollo->point_to_pixel( ecef );
EXPECT_VECTOR_NEAR( retrn_image, input_image, 1e-3 );
}
}
TEST_F( CameraBBoxTest, CameraBBoxDatum ) {
float scale; // degrees per pixel
BBox2 image_bbox = camera_bbox( moon, apollo, 4096, 4096, scale );
EXPECT_VECTOR_NEAR( image_bbox.min(), Vector2(86,-1), 2 );
EXPECT_VECTOR_NEAR( image_bbox.max(), Vector2(95,7), 2 );
EXPECT_NEAR( scale, (95-86.)/sqrt(4096*4096*2), 1e-3 ); // Cam is rotated
}
TEST_F( CameraBBoxTest, CameraBBoxDEM ) {
ImageView<float> DEM(20,20); // DEM covering lat {10,-10} long {80,100}
for ( uint i = 0; i < 20; i++ )
for ( uint j = 0; j <20; j++ )
DEM(i,j) = 1000 - 10*(pow(10.-i,2.)+pow(10.-j,2));
Matrix<double> geotrans = vw::math::identity_matrix<3>();
geotrans(0,2) = 80;
geotrans(1,1) = -1;
geotrans(1,2) = 10;
moon.set_transform(geotrans);
BBox2 image_bbox = camera_bbox( DEM, moon, apollo, 4096, 4096 );
EXPECT_VECTOR_NEAR( image_bbox.min(), Vector2(87,0), 2 );
EXPECT_VECTOR_NEAR( image_bbox.max(), Vector2(94,6), 2 );
}
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. 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.
*/
/* HIT_START
* BUILD: %t %s ../test_common.cpp EXCLUDE_HIP_PLATFORM nvcc
* RUN: %t
* HIT_END
*/
#include <thread>
#include <cassert>
#include <cstdio>
#include "hip/hip_runtime.h"
#include "hip/device_functions.h"
#include "test_common.h"
#define HIP_ASSERT(x) (assert((x)==hipSuccess))
__host__ void fence_system() {
std::atomic_thread_fence(std::memory_order_seq_cst);
}
__device__ void fence_system() {
__threadfence_system();
}
__host__ __device__ void round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) {
for (int i = 0; i < num_iter; i++) {
while(*flag%num_dev != id)
fence_system(); // invalid the cache for read
(*data)++;
fence_system(); // make sure the store to data is sequenced before the store to flag
(*flag)++;
fence_system(); // invalid the cache to flush out flag
}
}
__global__ void gpu_round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) {
round_robin(id, num_dev, num_iter, data, flag);
}
int main() {
int num_gpus = 0;
HIP_ASSERT(hipGetDeviceCount(&num_gpus));
if (num_gpus == 0) {
passed();
return 0;
}
volatile int* data;
HIP_ASSERT(hipHostMalloc(&data, sizeof(int), hipHostMallocCoherent));
constexpr int init_data = 1000;
*data = init_data;
volatile int* flag;
HIP_ASSERT(hipHostMalloc(&flag, sizeof(int), hipHostMallocCoherent));
*flag = 0;
// number of rounds per device
constexpr int num_iter = 1000;
// one CPU thread + 1 kernel/GPU
const int num_dev = num_gpus + 1;
int next_id = 0;
std::vector<std::thread> threads;
// create a CPU thread for the round_robin
threads.push_back(std::thread(round_robin, next_id++, num_dev, num_iter, data, flag));
// run one thread per GPU
dim3 dim_block(1,1,1);
dim3 dim_grid(1,1,1);
// launch one kernel per device for the round robin
for (; next_id < num_dev; ++next_id) {
threads.push_back(std::thread([=]() {
HIP_ASSERT(hipSetDevice(next_id-1));
hipLaunchKernelGGL(gpu_round_robin, dim_grid, dim_block, 0, 0x0
, next_id, num_dev, num_iter, data, flag);
HIP_ASSERT(hipDeviceSynchronize());
}));
}
for (auto& t : threads) {
t.join();
}
int expected_data = init_data + num_dev * num_iter;
int expected_flag = num_dev * num_iter;
bool passed = *data == expected_data
&& *flag == expected_flag;
HIP_ASSERT(hipHostFree((void*)data));
HIP_ASSERT(hipHostFree((void*)flag));
if (passed) {
passed();
}
else {
failed("Failed Verification!\n");
}
return 0;
}
<commit_msg>add C++11 compilation flags and minor bug fixes<commit_after>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. 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.
*/
/* HIT_START
* BUILD: %t %s ../test_common.cpp -std=c++11
* RUN: %t
* HIT_END
*/
#include <vector>
#include <atomic>
#include <thread>
#include <cassert>
#include <cstdio>
#include "hip/hip_runtime.h"
#include "hip/device_functions.h"
#include "test_common.h"
#define HIP_ASSERT(x) (assert((x)==hipSuccess))
__host__ __device__ void fence_system() {
#ifdef __HIP_DEVICE_COMPILE__
__threadfence_system();
#else
std::atomic_thread_fence(std::memory_order_seq_cst);
#endif
}
__host__ __device__ void round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) {
for (int i = 0; i < num_iter; i++) {
while(*flag%num_dev != id)
fence_system(); // invalid the cache for read
(*data)++;
fence_system(); // make sure the store to data is sequenced before the store to flag
(*flag)++;
fence_system(); // invalid the cache to flush out flag
}
}
__global__ void gpu_round_robin(const int id, const int num_dev, const int num_iter, volatile int* data, volatile int* flag) {
round_robin(id, num_dev, num_iter, data, flag);
}
int main() {
int num_gpus = 0;
HIP_ASSERT(hipGetDeviceCount(&num_gpus));
if (num_gpus == 0) {
passed();
return 0;
}
volatile int* data;
HIP_ASSERT(hipHostMalloc(&data, sizeof(int), hipHostMallocCoherent));
constexpr int init_data = 1000;
*data = init_data;
volatile int* flag;
HIP_ASSERT(hipHostMalloc(&flag, sizeof(int), hipHostMallocCoherent));
*flag = 0;
// number of rounds per device
constexpr int num_iter = 1000;
// one CPU thread + 1 kernel/GPU
const int num_dev = num_gpus + 1;
int next_id = 0;
std::vector<std::thread> threads;
// create a CPU thread for the round_robin
threads.push_back(std::thread(round_robin, next_id++, num_dev, num_iter, data, flag));
// run one thread per GPU
dim3 dim_block(1,1,1);
dim3 dim_grid(1,1,1);
// launch one kernel per device for the round robin
for (; next_id < num_dev; ++next_id) {
threads.push_back(std::thread([=]() {
HIP_ASSERT(hipSetDevice(next_id-1));
hipLaunchKernelGGL(gpu_round_robin, dim_grid, dim_block, 0, 0x0
, next_id, num_dev, num_iter, data, flag);
HIP_ASSERT(hipDeviceSynchronize());
}));
}
for (auto& t : threads) {
t.join();
}
int expected_data = init_data + num_dev * num_iter;
int expected_flag = num_dev * num_iter;
bool passed = *data == expected_data
&& *flag == expected_flag;
HIP_ASSERT(hipHostFree((void*)data));
HIP_ASSERT(hipHostFree((void*)flag));
if (passed) {
passed();
}
else {
failed("Failed Verification!\n");
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <SDL.h>
#include "res_path.h"
/*
* Lesson 1: Hello World!
*/
int main(int, char**){
//First we need to start up SDL, and make sure it went ok
if (SDL_Init(SDL_INIT_VIDEO) != 0){
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
//Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
//Make sure creating our window went ok
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
return 1;
}
//Create a renderer that will draw to the window, -1 specifies that we want to load whichever
//video driver supports the flags we're passing
//Flags: SDL_RENDERER_ACCELERATED: We want to use hardware accelerated rendering
//SDL_RENDERER_PRESENTVSYNC: We want the renderer's present function (update screen) to be
//synchornized with the monitor's refresh rate
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr){
SDL_DestroyWindow(win);
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
//SDL 2.0 now uses textures to draw things but SDL_LoadBMP returns a surface
//this lets us choose when to upload or remove textures from the GPU
std::string imagePath = getResourcePath("Lesson1") + "hello.bmp";
SDL_Surface *bmp = SDL_LoadBMP(imagePath.c_str());
if (bmp == nullptr){
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
//To use a hardware accelerated texture for rendering we can create one from
//the surface we loaded
SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
//We no longer need the surface
SDL_FreeSurface(bmp);
if (tex == nullptr){
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
//A sleepy rendering loop, wait for 3 seconds and render and present the screen each time
for (int i = 0; i < 3; ++i){
//First clear the renderer
SDL_RenderClear(ren);
//Draw the texture
SDL_RenderCopy(ren, tex, NULL, NULL);
//Update the screen
SDL_RenderPresent(ren);
//Take a quick break after all that hard work
SDL_Delay(1000);
}
//Clean up our objects and quit
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
<commit_msg>Fixed typo<commit_after>#include <iostream>
#include <SDL.h>
#include "res_path.h"
/*
* Lesson 1: Hello World!
*/
int main(int, char**){
//First we need to start up SDL, and make sure it went ok
if (SDL_Init(SDL_INIT_VIDEO) != 0){
std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
return 1;
}
//Now create a window with title "Hello World" at 100, 100 on the screen with w:640 h:480 and show it
SDL_Window *win = SDL_CreateWindow("Hello World!", 100, 100, 640, 480, SDL_WINDOW_SHOWN);
//Make sure creating our window went ok
if (win == nullptr){
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
return 1;
}
//Create a renderer that will draw to the window, -1 specifies that we want to load whichever
//video driver supports the flags we're passing
//Flags: SDL_RENDERER_ACCELERATED: We want to use hardware accelerated rendering
//SDL_RENDERER_PRESENTVSYNC: We want the renderer's present function (update screen) to be
//synchronized with the monitor's refresh rate
SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (ren == nullptr){
SDL_DestroyWindow(win);
std::cout << "SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
//SDL 2.0 now uses textures to draw things but SDL_LoadBMP returns a surface
//this lets us choose when to upload or remove textures from the GPU
std::string imagePath = getResourcePath("Lesson1") + "hello.bmp";
SDL_Surface *bmp = SDL_LoadBMP(imagePath.c_str());
if (bmp == nullptr){
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
std::cout << "SDL_LoadBMP Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
//To use a hardware accelerated texture for rendering we can create one from
//the surface we loaded
SDL_Texture *tex = SDL_CreateTextureFromSurface(ren, bmp);
//We no longer need the surface
SDL_FreeSurface(bmp);
if (tex == nullptr){
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
std::cout << "SDL_CreateTextureFromSurface Error: " << SDL_GetError() << std::endl;
SDL_Quit();
return 1;
}
//A sleepy rendering loop, wait for 3 seconds and render and present the screen each time
for (int i = 0; i < 3; ++i){
//First clear the renderer
SDL_RenderClear(ren);
//Draw the texture
SDL_RenderCopy(ren, tex, NULL, NULL);
//Update the screen
SDL_RenderPresent(ren);
//Take a quick break after all that hard work
SDL_Delay(1000);
}
//Clean up our objects and quit
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(ren);
SDL_DestroyWindow(win);
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#if defined(_MSC_VER)
#include <SDL.h>
#include <SDL_image.h>
#elif defined(__clang__)
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
#else
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#endif
/*
* Lesson 5: Clipping Sprite Sheets
*/
//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
/**
* Log an SDL error with some error message to the output stream of our choice
* @param os The output stream to write the message too
* @param msg The error message to write, format will be msg error: SDL_GetError()
*/
void logSDLError(std::ostream &os, const std::string &msg){
os << msg << " error: " << SDL_GetError() << std::endl;
}
/**
* Loads an image into a texture on the rendering device
* @param file The image file to load
* @param ren The renderer to load the texture onto
* @return the loaded texture, or nullptr if something went wrong.
*/
SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){
SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
if (texture == nullptr)
logSDLError(std::cout, "LoadTexture");
return texture;
}
/**
* Draw an SDL_Texture to an SDL_Renderer at some destination rect
* taking a clip of the texture if desired
* @param tex The source texture we want to draw
* @param rend The renderer we want to draw too
* @param dst The destination rectangle to render the texture too
* @param clip The sub-section of the texture to draw (clipping rect)
* default of nullptr draws the entire texture
*/
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr){
SDL_RenderCopy(ren, tex, clip, &dst);
}
/**
* Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
* the texture's width and height and taking a clip of the texture if desired
* If a clip is passed, the clip's width and height will be used instead of the texture's
* @param tex The source texture we want to draw
* @param rend The renderer we want to draw too
* @param x The x coordinate to draw too
* @param y The y coordinate to draw too
* @param clip The sub-section of the texture to draw (clipping rect)
* default of nullptr draws the entire texture
*/
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr){
SDL_Rect dst;
dst.x = x;
dst.y = y;
if (clip != nullptr){
dst.w = clip->w;
dst.h = clip->h;
}
else
SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);
renderTexture(tex, ren, dst, clip);
}
int main(int argc, char** argv){
//Start up SDL and make sure it went ok
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
logSDLError(std::cout, "SDL_Init");
return 1;
}
//Setup our window and renderer
SDL_Window *window = SDL_CreateWindow("Lesson 5", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == nullptr){
logSDLError(std::cout, "CreateWindow");
return 2;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
logSDLError(std::cout, "CreateRenderer");
return 3;
}
SDL_Texture *image = loadTexture("../res/Lesson5/image.png", renderer);
if (image == nullptr)
return 4;
//iW and iH are the clip width and height
//We'll be drawing only clips so get a center position for the w/h of a clip
int iW = 100, iH = 100;
int x = SCREEN_WIDTH / 2 - iW / 2;
int y = SCREEN_HEIGHT / 2 - iH / 2;
//Setup the clips for our image
SDL_Rect clips[4];
//Since our clips our uniform in size we can generate a list of their
//positions using some math (the specifics of this are covered in the lesson)
int column = 0;
for (int i = 0; i < 4; ++i){
if (i != 0 && i % 2 == 0)
++column;
clips[i].x = column * iW;
clips[i].y = i % 2 * iH;
clips[i].w = iW;
clips[i].h = iH;
}
//Specify a default clip to start with
int useClip = 0;
SDL_Event e;
bool quit = false;
while (!quit){
//Event Polling
while (SDL_PollEvent(&e)){
//If user closes he window
if (e.type == SDL_QUIT)
quit = true;
//Use number input to select which clip should be drawn
if (e.type == SDL_KEYDOWN){
switch (e.key.keysym.sym){
case SDLK_1:
useClip = 0;
break;
case SDLK_2:
useClip = 1;
break;
case SDLK_3:
useClip = 2;
break;
case SDLK_4:
useClip = 3;
break;
case SDLK_ESCAPE:
quit = true;
break;
default:
break;
}
}
}
//Rendering
SDL_RenderClear(renderer);
//Draw the image
renderTexture(image, renderer, x, y, &clips[useClip]);
//Update the screen
SDL_RenderPresent(renderer);
}
//Clean up
SDL_DestroyTexture(image);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 0;
}
<commit_msg>Use a better method for computing the clip positions<commit_after>#include <string>
#include <iostream>
#if defined(_MSC_VER)
#include <SDL.h>
#include <SDL_image.h>
#elif defined(__clang__)
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>
#else
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#endif
/*
* Lesson 5: Clipping Sprite Sheets
*/
//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
/**
* Log an SDL error with some error message to the output stream of our choice
* @param os The output stream to write the message too
* @param msg The error message to write, format will be msg error: SDL_GetError()
*/
void logSDLError(std::ostream &os, const std::string &msg){
os << msg << " error: " << SDL_GetError() << std::endl;
}
/**
* Loads an image into a texture on the rendering device
* @param file The image file to load
* @param ren The renderer to load the texture onto
* @return the loaded texture, or nullptr if something went wrong.
*/
SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){
SDL_Texture *texture = IMG_LoadTexture(ren, file.c_str());
if (texture == nullptr)
logSDLError(std::cout, "LoadTexture");
return texture;
}
/**
* Draw an SDL_Texture to an SDL_Renderer at some destination rect
* taking a clip of the texture if desired
* @param tex The source texture we want to draw
* @param rend The renderer we want to draw too
* @param dst The destination rectangle to render the texture too
* @param clip The sub-section of the texture to draw (clipping rect)
* default of nullptr draws the entire texture
*/
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, SDL_Rect dst, SDL_Rect *clip = nullptr){
SDL_RenderCopy(ren, tex, clip, &dst);
}
/**
* Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving
* the texture's width and height and taking a clip of the texture if desired
* If a clip is passed, the clip's width and height will be used instead of the texture's
* @param tex The source texture we want to draw
* @param rend The renderer we want to draw too
* @param x The x coordinate to draw too
* @param y The y coordinate to draw too
* @param clip The sub-section of the texture to draw (clipping rect)
* default of nullptr draws the entire texture
*/
void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, SDL_Rect *clip = nullptr){
SDL_Rect dst;
dst.x = x;
dst.y = y;
if (clip != nullptr){
dst.w = clip->w;
dst.h = clip->h;
}
else
SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h);
renderTexture(tex, ren, dst, clip);
}
int main(int argc, char** argv){
//Start up SDL and make sure it went ok
if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
logSDLError(std::cout, "SDL_Init");
return 1;
}
//Setup our window and renderer
SDL_Window *window = SDL_CreateWindow("Lesson 5", SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (window == nullptr){
logSDLError(std::cout, "CreateWindow");
return 2;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
logSDLError(std::cout, "CreateRenderer");
return 3;
}
SDL_Texture *image = loadTexture("../res/Lesson5/image.png", renderer);
if (image == nullptr)
return 4;
//iW and iH are the clip width and height
//We'll be drawing only clips so get a center position for the w/h of a clip
int iW = 100, iH = 100;
int x = SCREEN_WIDTH / 2 - iW / 2;
int y = SCREEN_HEIGHT / 2 - iH / 2;
//Setup the clips for our image
SDL_Rect clips[4];
//Since our clips our uniform in size we can generate a list of their
//positions using some math (the specifics of this are covered in the lesson)
for (int i = 0; i < 4; ++i){
clips[i].x = i / 2 * iW;
clips[i].y = i % 2 * iH;
clips[i].w = iW;
clips[i].h = iH;
}
//Specify a default clip to start with
int useClip = 0;
SDL_Event e;
bool quit = false;
while (!quit){
//Event Polling
while (SDL_PollEvent(&e)){
//If user closes he window
if (e.type == SDL_QUIT)
quit = true;
//Use number input to select which clip should be drawn
if (e.type == SDL_KEYDOWN){
switch (e.key.keysym.sym){
case SDLK_1:
useClip = 0;
break;
case SDLK_2:
useClip = 1;
break;
case SDLK_3:
useClip = 2;
break;
case SDLK_4:
useClip = 3;
break;
case SDLK_ESCAPE:
quit = true;
break;
default:
break;
}
}
}
//Rendering
SDL_RenderClear(renderer);
//Draw the image
renderTexture(image, renderer, x, y, &clips[useClip]);
//Update the screen
SDL_RenderPresent(renderer);
}
//Clean up
SDL_DestroyTexture(image);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
IMG_Quit();
SDL_Quit();
return 0;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
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 "OgreVolumeMeshBuilder.h"
#include <limits.h>
#include "OgreHardwareBufferManager.h"
#include "OgreManualObject.h"
#include "OgreMeshManager.h"
namespace Ogre {
namespace Volume {
bool operator==(Vertex const& a, Vertex const& b)
{
return a.x == b.x &&
a.y == b.y &&
a.z == b.z &&
a.nX == b.nX &&
a.nY == b.nY &&
a.nZ == b.nZ;
}
//-----------------------------------------------------------------------
bool operator<(const Vertex& a, const Vertex& b)
{
return memcmp(&a, &b, sizeof(Ogre::Volume::Vertex)) < 0;
}
//-----------------------------------------------------------------------
const unsigned short MeshBuilder::MAIN_BINDING = 0;
//-----------------------------------------------------------------------
MeshBuilder::MeshBuilder(void) : mBoxInit(false)
{
}
//-----------------------------------------------------------------------
size_t MeshBuilder::generateBuffers(RenderOperation &operation)
{
// Early out if nothing to do.
if (mIndices.size() == 0)
{
return 0;
}
// Prepare vertex buffer
operation.operationType = RenderOperation::OT_TRIANGLE_LIST;
operation.vertexData = OGRE_NEW VertexData();
operation.vertexData->vertexCount = mVertices.size();
operation.vertexData->vertexStart = 0;
VertexDeclaration *decl = operation.vertexData->vertexDeclaration;
VertexBufferBinding *bind = operation.vertexData->vertexBufferBinding;
size_t offset = 0;
// Add vertex-positions to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
offset += VertexElement::getTypeSize(VET_FLOAT3);
// Add vertex-normals to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING),
operation.vertexData->vertexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
bind->setBinding(0, vbuf);
float* vertices = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
VecVertex::const_iterator endVertices = mVertices.end();
for (VecVertex::const_iterator iter = mVertices.begin(); iter != endVertices; ++iter)
{
*vertices++ = (float)iter->x;
*vertices++ = (float)iter->y;
*vertices++ = (float)iter->z;
*vertices++ = (float)iter->nX;
*vertices++ = (float)iter->nY;
*vertices++ = (float)iter->nZ;
}
vbuf->unlock();
// Get Indexarray
operation.indexData = OGRE_NEW IndexData();
operation.indexData->indexCount = mIndices.size();
operation.indexData->indexStart = 0;
VecIndices::const_iterator endIndices = mIndices.end();
if (operation.indexData->indexCount > USHRT_MAX)
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_32BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned int* indices = static_cast<unsigned int*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
else
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_16BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned short* indices = static_cast<unsigned short*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = (unsigned short)*iter;
}
}
operation.indexData->indexBuffer->unlock();
return mIndices.size() / 3;
}
//-----------------------------------------------------------------------
AxisAlignedBox MeshBuilder::getBoundingBox(void)
{
return mBox;
}
//-----------------------------------------------------------------------
Entity* MeshBuilder::generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material)
{
ManualObject* manual = sceneManager->createManualObject();
manual->begin(material, RenderOperation::OT_TRIANGLE_LIST);
for (VecVertex::const_iterator iter = mVertices.begin(); iter != mVertices.end(); ++iter)
{
manual->position(Vector3(iter->x, iter->y, iter->z));
manual->normal(Vector3(iter->nX, iter->nY, iter->nZ));
}
for (VecIndices::const_iterator iter = mIndices.begin(); iter != mIndices.end(); ++iter)
{
manual->index(*iter);
}
manual->end();
StringUtil::StrStreamType meshName;
meshName << name << "ManualObject";
MeshManager::getSingleton().remove(meshName.str());
manual->convertToMesh(meshName.str());
return sceneManager->createEntity(name, meshName.str());
}
//-----------------------------------------------------------------------
void MeshBuilder::executeCallback(MeshBuilderCallback *callback) const
{
callback->trianglesReady(mVertices, mIndices);
}
}
}<commit_msg>Volume Rendering: micro cleanup<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2012 Torus Knot Software Ltd
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 "OgreVolumeMeshBuilder.h"
#include <limits.h>
#include "OgreHardwareBufferManager.h"
#include "OgreManualObject.h"
#include "OgreMeshManager.h"
namespace Ogre {
namespace Volume {
bool operator==(Vertex const& a, Vertex const& b)
{
return a.x == b.x &&
a.y == b.y &&
a.z == b.z &&
a.nX == b.nX &&
a.nY == b.nY &&
a.nZ == b.nZ;
}
//-----------------------------------------------------------------------
bool operator<(const Vertex& a, const Vertex& b)
{
return memcmp(&a, &b, sizeof(Vertex)) < 0;
}
//-----------------------------------------------------------------------
const unsigned short MeshBuilder::MAIN_BINDING = 0;
//-----------------------------------------------------------------------
MeshBuilder::MeshBuilder(void) : mBoxInit(false)
{
}
//-----------------------------------------------------------------------
size_t MeshBuilder::generateBuffers(RenderOperation &operation)
{
// Early out if nothing to do.
if (mIndices.size() == 0)
{
return 0;
}
// Prepare vertex buffer
operation.operationType = RenderOperation::OT_TRIANGLE_LIST;
operation.vertexData = OGRE_NEW VertexData();
operation.vertexData->vertexCount = mVertices.size();
operation.vertexData->vertexStart = 0;
VertexDeclaration *decl = operation.vertexData->vertexDeclaration;
VertexBufferBinding *bind = operation.vertexData->vertexBufferBinding;
size_t offset = 0;
// Add vertex-positions to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_POSITION);
offset += VertexElement::getTypeSize(VET_FLOAT3);
// Add vertex-normals to the buffer
decl->addElement(0, offset, VET_FLOAT3, VES_NORMAL);
offset += VertexElement::getTypeSize(VET_FLOAT3);
HardwareVertexBufferSharedPtr vbuf = HardwareBufferManager::getSingleton().createVertexBuffer(
decl->getVertexSize(MAIN_BINDING),
operation.vertexData->vertexCount,
HardwareBuffer::HBU_STATIC_WRITE_ONLY);
bind->setBinding(0, vbuf);
float* vertices = static_cast<float*>(vbuf->lock(HardwareBuffer::HBL_DISCARD));
VecVertex::const_iterator endVertices = mVertices.end();
for (VecVertex::const_iterator iter = mVertices.begin(); iter != endVertices; ++iter)
{
*vertices++ = (float)iter->x;
*vertices++ = (float)iter->y;
*vertices++ = (float)iter->z;
*vertices++ = (float)iter->nX;
*vertices++ = (float)iter->nY;
*vertices++ = (float)iter->nZ;
}
vbuf->unlock();
// Get Indexarray
operation.indexData = OGRE_NEW IndexData();
operation.indexData->indexCount = mIndices.size();
operation.indexData->indexStart = 0;
VecIndices::const_iterator endIndices = mIndices.end();
if (operation.indexData->indexCount > USHRT_MAX)
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_32BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned int* indices = static_cast<unsigned int*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = *iter;
}
}
else
{
operation.indexData->indexBuffer =
HardwareBufferManager::getSingleton().createIndexBuffer(
HardwareIndexBuffer::IT_16BIT,
operation.indexData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY);
unsigned short* indices = static_cast<unsigned short*>(
operation.indexData->indexBuffer->lock(0,
operation.indexData->indexBuffer->getSizeInBytes(),
HardwareBuffer::HBL_DISCARD));
for (VecIndices::const_iterator iter = mIndices.begin(); iter != endIndices; ++iter)
{
*indices++ = (unsigned short)*iter;
}
}
operation.indexData->indexBuffer->unlock();
return mIndices.size() / 3;
}
//-----------------------------------------------------------------------
AxisAlignedBox MeshBuilder::getBoundingBox(void)
{
return mBox;
}
//-----------------------------------------------------------------------
Entity* MeshBuilder::generateWithManualObject(SceneManager *sceneManager, const String &name, const String &material)
{
ManualObject* manual = sceneManager->createManualObject();
manual->begin(material, RenderOperation::OT_TRIANGLE_LIST);
for (VecVertex::const_iterator iter = mVertices.begin(); iter != mVertices.end(); ++iter)
{
manual->position(Vector3(iter->x, iter->y, iter->z));
manual->normal(Vector3(iter->nX, iter->nY, iter->nZ));
}
for (VecIndices::const_iterator iter = mIndices.begin(); iter != mIndices.end(); ++iter)
{
manual->index(*iter);
}
manual->end();
StringUtil::StrStreamType meshName;
meshName << name << "ManualObject";
MeshManager::getSingleton().remove(meshName.str());
manual->convertToMesh(meshName.str());
return sceneManager->createEntity(name, meshName.str());
}
//-----------------------------------------------------------------------
void MeshBuilder::executeCallback(MeshBuilderCallback *callback) const
{
callback->trianglesReady(mVertices, mIndices);
}
}
}<|endoftext|> |
<commit_before><commit_msg>cast to pointer to pointer, not just pointer. (confused yet?)<commit_after><|endoftext|> |
<commit_before>#include "kerberos_context.h"
Persistent<FunctionTemplate> KerberosContext::constructor_template;
KerberosContext::KerberosContext() : ObjectWrap() {
}
KerberosContext::~KerberosContext() {
}
KerberosContext* KerberosContext::New() {
NanScope();
Local<Object> obj = NanNew(constructor_template)->GetFunction()->NewInstance();
KerberosContext *kerberos_context = ObjectWrap::Unwrap<KerberosContext>(obj);
return kerberos_context;
}
NAN_METHOD(KerberosContext::New) {
NanScope();
// Create code object
KerberosContext *kerberos_context = new KerberosContext();
// Wrap it
kerberos_context->Wrap(args.This());
// Return the object
NanReturnValue(args.This());
}
void KerberosContext::Initialize(v8::Handle<v8::Object> target) {
// Grab the scope of the call from Node
NanScope();
// Define a new function template
// Local<FunctionTemplate> t = NanNew<FunctionTemplate>(New);
Local<FunctionTemplate> t = NanNew<v8::FunctionTemplate>(static_cast<NAN_METHOD((*))>(New));
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew<String>("KerberosContext"));
// Get prototype
Local<ObjectTemplate> proto = t->PrototypeTemplate();
// Getter for the response
proto->SetAccessor(NanNew<String>("response"), KerberosContext::ResponseGetter);
// Getter for the username - server side only
proto->SetAccessor(NanNew<String>("username"), KerberosContext::UsernameGetter);
// Getter for the targetname - server side only
proto->SetAccessor(NanNew<String>("targetname"), KerberosContext::TargetnameGetter);
// Set persistent
NanAssignPersistent(constructor_template, t);
// Set the symbol
target->ForceSet(NanNew<String>("KerberosContext"), t->GetFunction());
}
// Response Setter / Getter
NAN_GETTER(KerberosContext::ResponseGetter) {
NanScope();
gss_client_state *client_state;
gss_server_state *server_state;
// Unpack the object
KerberosContext *context = ObjectWrap::Unwrap<KerberosContext>(args.This());
// Let's grab the two possible responses
client_state = context->state;
server_state = context->server_state;
// the non-NULL provides a response string, which could be NULL, otherwise NULL.
char *response = client_state != NULL ? client_state->response :
server_state != NULL ? server_state->response : NULL;
if(response == NULL) {
NanReturnValue(NanNull());
} else {
// Return the response
NanReturnValue(NanNew<String>(response));
}
}
// username Getter
NAN_GETTER(KerberosContext::UsernameGetter) {
NanScope();
// Unpack the object
KerberosContext *context = ObjectWrap::Unwrap<KerberosContext>(args.This());
gss_client_state *client_state = context->state;
gss_server_state *server_state = context->server_state;
// the non-NULL provides a response string, which could be NULL, otherwise NULL.
char *username = client_state != NULL ? client_state->username :
server_state != NULL ? server_state->username : NULL;
if(username == NULL) {
NanReturnValue(NanNull());
} else {
NanReturnValue(NanNew<String>(username));
}
}
// targetname Getter - server side only
NAN_GETTER(KerberosContext::TargetnameGetter) {
NanScope();
// Unpack the object
KerberosContext *context = ObjectWrap::Unwrap<KerberosContext>(args.This());
gss_server_state *server_state = context->server_state;
// the non-NULL provides a response string, which could be NULL, otherwise NULL.
char *targetname = server_state != NULL ? server_state->targetname : NULL;
if(targetname == NULL) {
NanReturnValue(NanNull());
} else {
NanReturnValue(NanNew<String>(targetname));
}
}
<commit_msg>that property is server or client side<commit_after>#include "kerberos_context.h"
Persistent<FunctionTemplate> KerberosContext::constructor_template;
KerberosContext::KerberosContext() : ObjectWrap() {
}
KerberosContext::~KerberosContext() {
}
KerberosContext* KerberosContext::New() {
NanScope();
Local<Object> obj = NanNew(constructor_template)->GetFunction()->NewInstance();
KerberosContext *kerberos_context = ObjectWrap::Unwrap<KerberosContext>(obj);
return kerberos_context;
}
NAN_METHOD(KerberosContext::New) {
NanScope();
// Create code object
KerberosContext *kerberos_context = new KerberosContext();
// Wrap it
kerberos_context->Wrap(args.This());
// Return the object
NanReturnValue(args.This());
}
void KerberosContext::Initialize(v8::Handle<v8::Object> target) {
// Grab the scope of the call from Node
NanScope();
// Define a new function template
// Local<FunctionTemplate> t = NanNew<FunctionTemplate>(New);
Local<FunctionTemplate> t = NanNew<v8::FunctionTemplate>(static_cast<NAN_METHOD((*))>(New));
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew<String>("KerberosContext"));
// Get prototype
Local<ObjectTemplate> proto = t->PrototypeTemplate();
// Getter for the response
proto->SetAccessor(NanNew<String>("response"), KerberosContext::ResponseGetter);
// Getter for the username
proto->SetAccessor(NanNew<String>("username"), KerberosContext::UsernameGetter);
// Getter for the targetname - server side only
proto->SetAccessor(NanNew<String>("targetname"), KerberosContext::TargetnameGetter);
// Set persistent
NanAssignPersistent(constructor_template, t);
// Set the symbol
target->ForceSet(NanNew<String>("KerberosContext"), t->GetFunction());
}
// Response Setter / Getter
NAN_GETTER(KerberosContext::ResponseGetter) {
NanScope();
gss_client_state *client_state;
gss_server_state *server_state;
// Unpack the object
KerberosContext *context = ObjectWrap::Unwrap<KerberosContext>(args.This());
// Let's grab the two possible responses
client_state = context->state;
server_state = context->server_state;
// the non-NULL provides a response string, which could be NULL, otherwise NULL.
char *response = client_state != NULL ? client_state->response :
server_state != NULL ? server_state->response : NULL;
if(response == NULL) {
NanReturnValue(NanNull());
} else {
// Return the response
NanReturnValue(NanNew<String>(response));
}
}
// username Getter
NAN_GETTER(KerberosContext::UsernameGetter) {
NanScope();
// Unpack the object
KerberosContext *context = ObjectWrap::Unwrap<KerberosContext>(args.This());
gss_client_state *client_state = context->state;
gss_server_state *server_state = context->server_state;
// the non-NULL provides a response string, which could be NULL, otherwise NULL.
char *username = client_state != NULL ? client_state->username :
server_state != NULL ? server_state->username : NULL;
if(username == NULL) {
NanReturnValue(NanNull());
} else {
NanReturnValue(NanNew<String>(username));
}
}
// targetname Getter - server side only
NAN_GETTER(KerberosContext::TargetnameGetter) {
NanScope();
// Unpack the object
KerberosContext *context = ObjectWrap::Unwrap<KerberosContext>(args.This());
gss_server_state *server_state = context->server_state;
// the non-NULL provides a response string, which could be NULL, otherwise NULL.
char *targetname = server_state != NULL ? server_state->targetname : NULL;
if(targetname == NULL) {
NanReturnValue(NanNull());
} else {
NanReturnValue(NanNew<String>(targetname));
}
}
<|endoftext|> |
<commit_before>#include "androidretracer.h"
#include "androiddevicedialog.h"
#include "thumbnail.h"
#include "image/image.hpp"
#include "trace_profiler.hpp"
#include <QHostAddress>
#include <QJsonDocument>
#include <QSettings>
#include <QTime>
typedef QLatin1String _;
static QLatin1String packageName("apitrace.github.io.eglretrace");
static QLatin1String activityName("/.RetraceActivity");
AndroidRetracer::AndroidRetracer(QObject *parent)
: Retracer(parent),
m_stdoutPort(52341),
m_stderrPort(52342)
{
connect(&m_androidUtils, SIGNAL(statusMessage(QString)),
SIGNAL(statusMessage(QString)));
}
void AndroidRetracer::setAndroidFileName(const QString &fileName)
{
m_androdiFileName = fileName;
}
static int extractPidFromChunk(const QByteArray &chunk, int from)
{
int pos1 = chunk.indexOf(' ', from);
if (pos1 == -1)
return -1;
while (chunk[pos1] == ' ')
++pos1;
int pos3 = chunk.indexOf(' ', pos1);
int pid = chunk.mid(pos1, pos3 - pos1).toInt();
return pid;
}
static int extractPid(const QByteArray &psOutput)
{
static const QByteArray needle("apitrace.github.io.eglretrace\r");
const int to = psOutput.indexOf(needle);
if (to == -1)
return -1;
const int from = psOutput.lastIndexOf('\n', to);
if (from == -1)
return -1;
return extractPidFromChunk(psOutput, from);
}
static QByteArray readLine(QTcpSocket &sock)
{
while (!sock.canReadLine() && sock.waitForReadyRead());
if (sock.state() != QAbstractSocket::ConnectedState)
return QByteArray();
return sock.readLine();
}
static bool read(QTcpSocket &sock, char *ptr, qint64 sz)
{
do {
qint64 readBytes = sock.read(ptr, sz);
ptr += readBytes;
sz -= readBytes;
} while(sz && sock.waitForReadyRead());
return sz == 0;
}
void AndroidRetracer::run()
{
m_androidUtils.reloadAdb();
QString errorStr;
bool setupRet;
QMetaObject::invokeMethod(this, "setup", Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, setupRet),
Q_ARG(QString *, &errorStr));
if (!setupRet) {
emit finished(errorStr);
return;
}
if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("am") << _("start") << _("-n") << packageName + activityName)) {
emit finished(tr("Can't start apitrace application"));
return;
}
QByteArray which;
if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("readlink") << _("$(which ps)") , &which)) {
emit finished(tr("Can't start adb"));
return;
}
bool isBusyBox = which.startsWith("busybox");
QStringList psArgs;
psArgs << _("shell") << _("ps");
if (isBusyBox)
psArgs << _("-w");
qint64 processPID;
bool wasStarted = false;
QTime startTime;
startTime.start();
QTcpSocket stdoutSocket;
QTcpSocket stderrSocket;
ImageHash thumbnails;
QVariantMap parsedJson;
trace::Profile* profile = isProfiling() ? new trace::Profile() : NULL;
QList<ApiTraceError> errors;
QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
QString msg = QLatin1String("Replay finished!");
QByteArray jsonBuffer;
QByteArray outputBuffer;
bool keepGoing = true;
while(keepGoing) {
if (!wasStarted || startTime.elapsed() > 1000) {
QByteArray psOut;
m_androidUtils.runAdb(psArgs, &psOut);
processPID = extractPid(psOut);
if (wasStarted)
startTime.restart();
}
if (processPID == -1) {
if (wasStarted) {
break;
} else {
if (startTime.elapsed() > 3000) { // wait 3 seconds to start
emit finished(tr("Unable to start retrace on device."));
return;
}
}
msleep(100);
continue;
}
// we have a valid pid, it means the application started
if (!wasStarted) {
// connect the sockets
int tries = 0;
do {
stdoutSocket.connectToHost(QHostAddress::LocalHost, m_stdoutPort);
} while (!stdoutSocket.waitForConnected(100) && ++tries < 10);
if (stdoutSocket.state() != QAbstractSocket::ConnectedState) {
emit finished(tr("Can't connect to stdout socket."));
return;
}
// Android doesn't suport GPU and PPD profiling (at leats not on my devices)
//setProfiling(false, isProfilingCpu(), false);
QString args = (retraceArguments() << m_androdiFileName).join(" ") + _("\n");
stdoutSocket.write(args.toUtf8());
if (!stdoutSocket.waitForBytesWritten()) {
emit finished(tr("Can't send params."));
return;
}
stderrSocket.connectToHost(QHostAddress::LocalHost, m_stderrPort);
stderrSocket.waitForConnected(100);
if (stderrSocket.state() != QAbstractSocket::ConnectedState) {
emit finished(tr("Can't connect to stderr socket."));
return;
}
wasStarted = true;
}
// We are going to read both channels at the same time
// read stdout channel
if (stdoutSocket.waitForReadyRead(100)) {
if (captureState())
jsonBuffer.append(stdoutSocket.readAll());
else if (captureThumbnails()) {
// read one image
image::PNMInfo info;
QByteArray header;
int headerLines = 3; // assume no optional comment line
for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
QByteArray line = readLine(stdoutSocket);
if (line.isEmpty()) {
keepGoing = false;
break;
}
header += line;
// if header actually contains optional comment line, ...
if (headerLine == 1 && line[0] == '#') {
++headerLines;
}
}
const char *headerEnd = image::readPNMHeader(header.constData(), header.size(), info);
// if invalid PNM header was encountered, ...
if (headerEnd == NULL ||
info.channelType != image::TYPE_UNORM8) {
qDebug() << "error: invalid snapshot stream encountered";
keepGoing = false;
break;
}
unsigned channels = info.channels;
unsigned width = info.width;
unsigned height = info.height;
// qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";
QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);
int rowBytes = channels * width;
for (int y = 0; y < height; ++y) {
unsigned char *scanLine = snapshot.scanLine(y);
if (!read(stdoutSocket, (char *) scanLine, rowBytes)) {
keepGoing = false;
break;
}
}
QImage thumb = thumbnail(snapshot);
thumbnails.insert(info.commentNumber, thumb);
} else if (isProfiling()) {
QByteArray line = readLine(stdoutSocket);
if (line.isEmpty()) {
keepGoing = false;
break;
}
line.append('\0');
trace::Profiler::parseLine(line.constData(), profile);
} else {
outputBuffer.append(stdoutSocket.readAll());
}
}
// read stderr channel
if (stderrSocket.waitForReadyRead(5) && stderrSocket.canReadLine()) {
QString line = stderrSocket.readLine();
if (regexp.indexIn(line) != -1) {
ApiTraceError error;
error.callIndex = regexp.cap(1).toInt();
error.type = regexp.cap(2);
error.message = regexp.cap(3);
errors.append(error);
} else if (!errors.isEmpty()) {
// Probably a multiligne message
ApiTraceError &previous = errors.last();
if (line.endsWith("\n")) {
line.chop(1);
}
previous.message.append('\n');
previous.message.append(line);
}
}
}
if (outputBuffer.size() < 80)
msg = outputBuffer;
if (captureState()) {
QJsonParseError error;
QJsonDocument jsonDoc =
QJsonDocument::fromJson(jsonBuffer, &error);
if (error.error != QJsonParseError::NoError)
msg = error.errorString();
parsedJson = jsonDoc.toVariant().toMap();
ApiTraceState *state = new ApiTraceState(parsedJson);
emit foundState(state);
}
if (captureThumbnails() && !thumbnails.isEmpty()) {
emit foundThumbnails(thumbnails);
}
if (isProfiling() && profile) {
emit foundProfile(profile);
}
if (!errors.isEmpty()) {
emit retraceErrors(errors);
}
emit finished(msg);
}
bool AndroidRetracer::setup(QString *error)
{
m_androidUtils.reloadAdb();
if (m_androidUtils.serialNumber().isEmpty()) {
*error = tr("No device selected");
return false;
}
// forward adbPorts
QSettings s;
s.beginGroup(_("android"));
m_stdoutPort = s.value(_("stdoutPort"), m_stdoutPort).toInt();
m_stderrPort = s.value(_("stderrPort"), m_stderrPort).toInt();
s.endGroup();
if (!m_androidUtils.runAdb(QStringList(_("forward"))
<< QString::fromLatin1("tcp:%1").arg(m_stdoutPort)
<< _("localabstract:apitrace.github.io.eglretrace.stdout"))) {
*error = tr("Can't forward ports");
return false;
}
if (!m_androidUtils.runAdb(QStringList(_("forward"))
<< QString::fromLatin1("tcp:%1").arg(m_stderrPort)
<< _("localabstract:apitrace.github.io.eglretrace.stderr"))) {
*error = tr("Can't forward ports");
return false;
}
return true;
}
<commit_msg>gui: Try to un-break android retracer.<commit_after>#include "androidretracer.h"
#include "androiddevicedialog.h"
#include "thumbnail.h"
#include "image/image.hpp"
#include "trace_profiler.hpp"
#include <QHostAddress>
#include <QSettings>
#include <QTime>
#include <QBuffer>
#include "qubjson.h"
typedef QLatin1String _;
static QLatin1String packageName("apitrace.github.io.eglretrace");
static QLatin1String activityName("/.RetraceActivity");
AndroidRetracer::AndroidRetracer(QObject *parent)
: Retracer(parent),
m_stdoutPort(52341),
m_stderrPort(52342)
{
connect(&m_androidUtils, SIGNAL(statusMessage(QString)),
SIGNAL(statusMessage(QString)));
}
void AndroidRetracer::setAndroidFileName(const QString &fileName)
{
m_androdiFileName = fileName;
}
static int extractPidFromChunk(const QByteArray &chunk, int from)
{
int pos1 = chunk.indexOf(' ', from);
if (pos1 == -1)
return -1;
while (chunk[pos1] == ' ')
++pos1;
int pos3 = chunk.indexOf(' ', pos1);
int pid = chunk.mid(pos1, pos3 - pos1).toInt();
return pid;
}
static int extractPid(const QByteArray &psOutput)
{
static const QByteArray needle("apitrace.github.io.eglretrace\r");
const int to = psOutput.indexOf(needle);
if (to == -1)
return -1;
const int from = psOutput.lastIndexOf('\n', to);
if (from == -1)
return -1;
return extractPidFromChunk(psOutput, from);
}
static QByteArray readLine(QTcpSocket &sock)
{
while (!sock.canReadLine() && sock.waitForReadyRead());
if (sock.state() != QAbstractSocket::ConnectedState)
return QByteArray();
return sock.readLine();
}
static bool read(QTcpSocket &sock, char *ptr, qint64 sz)
{
do {
qint64 readBytes = sock.read(ptr, sz);
ptr += readBytes;
sz -= readBytes;
} while(sz && sock.waitForReadyRead());
return sz == 0;
}
void AndroidRetracer::run()
{
m_androidUtils.reloadAdb();
QString errorStr;
bool setupRet;
QMetaObject::invokeMethod(this, "setup", Qt::BlockingQueuedConnection,
Q_RETURN_ARG(bool, setupRet),
Q_ARG(QString *, &errorStr));
if (!setupRet) {
emit finished(errorStr);
return;
}
if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("am") << _("start") << _("-n") << packageName + activityName)) {
emit finished(tr("Can't start apitrace application"));
return;
}
QByteArray which;
if (!m_androidUtils.runAdb(QStringList() << _("shell") << _("readlink") << _("$(which ps)") , &which)) {
emit finished(tr("Can't start adb"));
return;
}
bool isBusyBox = which.startsWith("busybox");
QStringList psArgs;
psArgs << _("shell") << _("ps");
if (isBusyBox)
psArgs << _("-w");
qint64 processPID;
bool wasStarted = false;
QTime startTime;
startTime.start();
QTcpSocket stdoutSocket;
QTcpSocket stderrSocket;
ImageHash thumbnails;
QVariantMap parsedJson;
trace::Profile* profile = isProfiling() ? new trace::Profile() : NULL;
QList<ApiTraceError> errors;
QRegExp regexp("(^\\d+): +(\\b\\w+\\b): ([^\\r\\n]+)[\\r\\n]*$");
QString msg = QLatin1String("Replay finished!");
QByteArray ubjsonBuffer;
QByteArray outputBuffer;
bool keepGoing = true;
while(keepGoing) {
if (!wasStarted || startTime.elapsed() > 1000) {
QByteArray psOut;
m_androidUtils.runAdb(psArgs, &psOut);
processPID = extractPid(psOut);
if (wasStarted)
startTime.restart();
}
if (processPID == -1) {
if (wasStarted) {
break;
} else {
if (startTime.elapsed() > 3000) { // wait 3 seconds to start
emit finished(tr("Unable to start retrace on device."));
return;
}
}
msleep(100);
continue;
}
// we have a valid pid, it means the application started
if (!wasStarted) {
// connect the sockets
int tries = 0;
do {
stdoutSocket.connectToHost(QHostAddress::LocalHost, m_stdoutPort);
} while (!stdoutSocket.waitForConnected(100) && ++tries < 10);
if (stdoutSocket.state() != QAbstractSocket::ConnectedState) {
emit finished(tr("Can't connect to stdout socket."));
return;
}
// Android doesn't suport GPU and PPD profiling (at leats not on my devices)
//setProfiling(false, isProfilingCpu(), false);
QString args = (retraceArguments() << m_androdiFileName).join(" ") + _("\n");
stdoutSocket.write(args.toUtf8());
if (!stdoutSocket.waitForBytesWritten()) {
emit finished(tr("Can't send params."));
return;
}
stderrSocket.connectToHost(QHostAddress::LocalHost, m_stderrPort);
stderrSocket.waitForConnected(100);
if (stderrSocket.state() != QAbstractSocket::ConnectedState) {
emit finished(tr("Can't connect to stderr socket."));
return;
}
wasStarted = true;
}
// We are going to read both channels at the same time
// read stdout channel
if (stdoutSocket.waitForReadyRead(100)) {
if (captureState())
ubjsonBuffer.append(stdoutSocket.readAll());
else if (captureThumbnails()) {
// read one image
image::PNMInfo info;
QByteArray header;
int headerLines = 3; // assume no optional comment line
for (int headerLine = 0; headerLine < headerLines; ++headerLine) {
QByteArray line = readLine(stdoutSocket);
if (line.isEmpty()) {
keepGoing = false;
break;
}
header += line;
// if header actually contains optional comment line, ...
if (headerLine == 1 && line[0] == '#') {
++headerLines;
}
}
const char *headerEnd = image::readPNMHeader(header.constData(), header.size(), info);
// if invalid PNM header was encountered, ...
if (headerEnd == NULL ||
info.channelType != image::TYPE_UNORM8) {
qDebug() << "error: invalid snapshot stream encountered";
keepGoing = false;
break;
}
unsigned channels = info.channels;
unsigned width = info.width;
unsigned height = info.height;
// qDebug() << "channels: " << channels << ", width: " << width << ", height: " << height";
QImage snapshot = QImage(width, height, channels == 1 ? QImage::Format_Mono : QImage::Format_RGB888);
int rowBytes = channels * width;
for (int y = 0; y < height; ++y) {
unsigned char *scanLine = snapshot.scanLine(y);
if (!read(stdoutSocket, (char *) scanLine, rowBytes)) {
keepGoing = false;
break;
}
}
QImage thumb = thumbnail(snapshot);
thumbnails.insert(info.commentNumber, thumb);
} else if (isProfiling()) {
QByteArray line = readLine(stdoutSocket);
if (line.isEmpty()) {
keepGoing = false;
break;
}
line.append('\0');
trace::Profiler::parseLine(line.constData(), profile);
} else {
outputBuffer.append(stdoutSocket.readAll());
}
}
// read stderr channel
if (stderrSocket.waitForReadyRead(5) && stderrSocket.canReadLine()) {
QString line = stderrSocket.readLine();
if (regexp.indexIn(line) != -1) {
ApiTraceError error;
error.callIndex = regexp.cap(1).toInt();
error.type = regexp.cap(2);
error.message = regexp.cap(3);
errors.append(error);
} else if (!errors.isEmpty()) {
// Probably a multiligne message
ApiTraceError &previous = errors.last();
if (line.endsWith("\n")) {
line.chop(1);
}
previous.message.append('\n');
previous.message.append(line);
}
}
}
if (outputBuffer.size() < 80)
msg = outputBuffer;
if (captureState()) {
QBuffer io(&ubjsonBuffer);
io.open(QIODevice::ReadOnly);
parsedJson = decodeUBJSONObject(&io).toMap();
ApiTraceState *state = new ApiTraceState(parsedJson);
emit foundState(state);
}
if (captureThumbnails() && !thumbnails.isEmpty()) {
emit foundThumbnails(thumbnails);
}
if (isProfiling() && profile) {
emit foundProfile(profile);
}
if (!errors.isEmpty()) {
emit retraceErrors(errors);
}
emit finished(msg);
}
bool AndroidRetracer::setup(QString *error)
{
m_androidUtils.reloadAdb();
if (m_androidUtils.serialNumber().isEmpty()) {
*error = tr("No device selected");
return false;
}
// forward adbPorts
QSettings s;
s.beginGroup(_("android"));
m_stdoutPort = s.value(_("stdoutPort"), m_stdoutPort).toInt();
m_stderrPort = s.value(_("stderrPort"), m_stderrPort).toInt();
s.endGroup();
if (!m_androidUtils.runAdb(QStringList(_("forward"))
<< QString::fromLatin1("tcp:%1").arg(m_stdoutPort)
<< _("localabstract:apitrace.github.io.eglretrace.stdout"))) {
*error = tr("Can't forward ports");
return false;
}
if (!m_androidUtils.runAdb(QStringList(_("forward"))
<< QString::fromLatin1("tcp:%1").arg(m_stderrPort)
<< _("localabstract:apitrace.github.io.eglretrace.stderr"))) {
*error = tr("Can't forward ports");
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/*
* $Id: XMReceiverMediaPatch.cpp,v 1.30 2007/02/13 12:57:52 hfriederich Exp $
*
* Copyright (c) 2005-2007 XMeeting Project ("http://xmeeting.sf.net").
* All rights reserved.
* Copyright (c) 2005-2007 Hannes Friederich. All rights reserved.
*/
#include "XMReceiverMediaPatch.h"
#include <opal/mediastrm.h>
#include <opal/mediacmd.h>
#include "XMMediaFormats.h"
#include "XMMediaStream.h"
#include "XMCallbackBridge.h"
#include "XMAudioTester.h"
#define XM_PACKET_POOL_GRANULARITY 8
#define XM_FRAME_BUFFER_SIZE 352*288*4
XMReceiverMediaPatch::XMReceiverMediaPatch(OpalMediaStream & src)
: OpalMediaPatch(src)
{
packetReassembler = NULL;
}
XMReceiverMediaPatch::~XMReceiverMediaPatch()
{
}
void XMReceiverMediaPatch::Start()
{
// quit any running audio test if needed
XMAudioTester::Stop();
OpalMediaPatch::Start();
}
void XMReceiverMediaPatch::Main()
{
///////////////////////////////////////////////////////////////////////////////////////////////
// The receiving algorithm tries to achieve best-possible data integrity and builds upon
// the following assumptions:
//
// 1) The chance for packets actually being lost/dropped is very small
// 2) The chance of packets being delayed across timestamp boundaries is much smaller than
// the chance of packets being reordered within the same timestamp (the same video frame)
//
// First, the frames will be read and put into a sorted linked list with ascending sequence
// numbers. If a packet group is complete, the packet payloads are copied together and the
// resulting frame is sent to the XMMediaReceiver class for decompression and display.
// A packet group is considered to be complete IF
//
// a) The first packet has the next ascending sequence number to the sequence number of the
// last packet of the previous packet group or the packet contains the beginning of a
// coded frame (picture start codes in H.261 / H.263) AND
// b) The sequence numbers of the packets in the list are ascending with no sequence number
// missing AND
// c) The last packet has the marker bit set
//
// This algorithm makes it possible to process packets of a packet group even if they arrive
// after the last packet of the packet group with the marker bit set. This works well if
// assumptions 1) and 2) are true.
//
// If a packet group is incomplete and the first packet of the next packet group arrives
// (indicated by a different timestamp), the incomplete packet group is either dropped
// or processed, depending on the codec being used. If the incomplete packet group is
// processed, the processing happens delayed since the first packet of the next packet
// group arrived, leading to inconstant display intervals. As long as assumption 1)
// is met, this is not a big drawback.
//
// If either packets are missing or the decompression of the frame fails, an
// fast update request is being sent to the remote party.
///////////////////////////////////////////////////////////////////////////////////////////////
// Allocating a pool of XMRTPPacket instances to reduce
// buffer allocation overhead.
// The pool size increases in steps of 8 packets with an initial size of 8 packets.
// These 8 packets are allocated initially.
// The packets 9-xx are allocated on demand
unsigned allocatedPackets = XM_PACKET_POOL_GRANULARITY;
XMRTPPacket **packets = (XMRTPPacket **)malloc(allocatedPackets * sizeof(XMRTPPacket *));
unsigned packetIndex = 0;
for(unsigned i = 0; i < allocatedPackets; i++)
{
packets[i] = new XMRTPPacket(source.GetDataSize());
}
// make sure the RTP session does NOT ignore out of order packets
OpalRTPMediaStream & rtpStream = (OpalRTPMediaStream &)source;
rtpStream.GetRtpSession().SetIgnoreOutOfOrderPackets(FALSE);
BYTE *frameBuffer = (BYTE *)malloc(sizeof(BYTE) * XM_FRAME_BUFFER_SIZE);
// Read the first packet
BOOL firstReadSuccesful = source.ReadPacket(*(packets[0]));
// Access the media format
const OpalMediaFormat & mediaFormat = source.GetMediaFormat();
if(firstReadSuccesful == TRUE)
{
// Tell the media receiver to prepare processing packets
XMCodecIdentifier codecIdentifier = _XMGetMediaFormatCodec(mediaFormat);
unsigned sessionID = 2;
RTP_DataFrame::PayloadTypes payloadType = packets[0]->GetPayloadType();
// initialize the packet processing variables
DWORD currentTimestamp = packets[0]->GetTimestamp();
WORD firstSeqNrOfPacketGroup = 0;
XMRTPPacket *firstPacketOfPacketGroup = NULL;
XMRTPPacket *lastPacketOfPacketGroup = NULL;
switch(codecIdentifier)
{
case XMCodecIdentifier_H261:
packetReassembler = new XMH261RTPPacketReassembler();
break;
case XMCodecIdentifier_H263:
if(_XMGetIsRFC2429(mediaFormat) || mediaFormat == XM_MEDIA_FORMAT_H263PLUS)
{
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
else
{
int result = _XMDetermineH263PacketizationScheme(packets[0]->GetPayloadPtr(), packets[0]->GetPayloadSize());
if(result == 0)
{
// cannot determine. Last hope is to look at the payload code
if(payloadType == RTP_DataFrame::H263)
{
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
}
else
{
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
}
else if(result == 1)
{
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
}
else
{
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
}
break;
case XMCodecIdentifier_H264:
packetReassembler = new XMH264RTPPacketReassembler();
break;
default:
break;
}
_XMStartMediaReceiving(sessionID, codecIdentifier);
// loop to receive packets and process them
do {
inUse.Wait();
BOOL processingSuccessful = TRUE;
unsigned numberOfPacketsToRelease = 0;
XMRTPPacket *packet = packets[packetIndex];
packet->next = NULL;
packet->prev = NULL;
// processing the packet
DWORD timestamp = packet->GetTimestamp();
WORD sequenceNumber = packet->GetSequenceNumber();
// take into account that the timestamp might wrap around
if(timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31))
{
// This packet group is already processed
// By changing the sequenceNumber parameter,
// we can adjust the expected beginning of
// the current packet group.
if(firstSeqNrOfPacketGroup <= sequenceNumber)
{
firstSeqNrOfPacketGroup = sequenceNumber + 1;
}
}
else
{
// also take into account that the timestamp might wrap around
if(timestamp > currentTimestamp || (timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31)))
{
if(firstPacketOfPacketGroup != NULL)
{
// Try to process the old packet although not complete
BOOL result = TRUE;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyIncompletePacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if(result == TRUE)
{
_XMProcessFrame(sessionID, frameBuffer, frameBufferSize);
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
processingSuccessful = FALSE;
PTRACE(1, "XMeetingReceiverMediaPatch\tIncomplete old packet group");
// There are (packetIndex + 1) packets in the buffer, but only the last one
// ist still needed
numberOfPacketsToRelease = packetIndex;
}
currentTimestamp = timestamp;
}
if(lastPacketOfPacketGroup != NULL)
{
XMRTPPacket *previousPacket = lastPacketOfPacketGroup;
do {
WORD previousSequenceNumber = previousPacket->GetSequenceNumber();
// take into account that the sequence number might wrap around
if(sequenceNumber > previousSequenceNumber ||
(sequenceNumber < previousSequenceNumber && (previousSequenceNumber - sequenceNumber) > (0x01 << 15)))
{
// ordering is correct, insert at this point
packet->next = previousPacket->next;
previousPacket->next = packet;
packet->prev = previousPacket;
if(previousPacket == lastPacketOfPacketGroup)
{
lastPacketOfPacketGroup = packet;
}
break;
}
else if(sequenceNumber == previousSequenceNumber)
{
break;
}
if(previousPacket == firstPacketOfPacketGroup)
{
// inserting this packet at the beginning of
// the packet group
packet->next = previousPacket;
previousPacket->prev = packet;
firstPacketOfPacketGroup = packet;
break;
}
previousPacket = previousPacket->prev;
} while(TRUE);
}
else
{
firstPacketOfPacketGroup = packet;
lastPacketOfPacketGroup = packet;
}
}
/////////////////////////////////////////////////////////
// checking whether the packet group is complete or not
/////////////////////////////////////////////////////////
BOOL packetGroupIsComplete = FALSE;
WORD expectedSequenceNumber = firstSeqNrOfPacketGroup;
XMRTPPacket *thePacket = firstPacketOfPacketGroup;
BOOL isFirstPacket = FALSE;
if(expectedSequenceNumber == thePacket->GetSequenceNumber())
{
isFirstPacket = TRUE;
}
else
{
// the sequence number is not the expected one. Try to analyze
// the bitstream to determine whether this is the first packet
// of a packet group or not
isFirstPacket = packetReassembler->IsFirstPacketOfFrame(thePacket);
}
if(isFirstPacket == TRUE)
{
expectedSequenceNumber = thePacket->GetSequenceNumber();
do {
if(expectedSequenceNumber != thePacket->GetSequenceNumber())
{
break;
}
expectedSequenceNumber++;
if(thePacket->next == NULL)
{
// no more packets in the packet group.
// If the marker bit is set, we're complete
if(thePacket->GetMarker() == TRUE)
{
packetGroupIsComplete = TRUE;
}
break;
}
thePacket = thePacket->next;
} while(TRUE);
}
/////////////////////////////////////////////////////
// If the packet group is complete, copy the packets
// into a frame and send it to the XMMediaReceiver
// system.
/////////////////////////////////////////////////////
if(packetGroupIsComplete == TRUE)
{
BOOL result = TRUE;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyPacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if(result == TRUE)
{
result = _XMProcessFrame(sessionID, frameBuffer, frameBufferSize);
if(result == FALSE)
{
PTRACE(1, "XMeetingReceiverMediaPatch\tDecompression of the frame failed");
processingSuccessful = FALSE;
}
}
else
{
PTRACE(1, "XMeetingReceiverMediaPatch\tCould not copy packets into frame buffer");
processingSuccessful = FALSE;
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
// Release all packets in the pool
numberOfPacketsToRelease = packetIndex + 1;
}
if(processingSuccessful == FALSE)
{
IssueVideoUpdatePictureCommand();
processingSuccessful = TRUE;
}
// Of not all packets can be released, the remaining packets are
// put at the beginning of the packet pool.
if(numberOfPacketsToRelease != 0)
{
unsigned i;
for(i = 0; i < (packetIndex + 1 - numberOfPacketsToRelease); i++)
{
// swapping the remaining frames
XMRTPPacket *packet = packets[i];
packets[i] = packets[i + numberOfPacketsToRelease];
packets[i + numberOfPacketsToRelease] = packet;
}
packetIndex = packetIndex + 1 - numberOfPacketsToRelease;
}
else
{
// increment the packetIndex, allocate a new XMRTPPacket if needed.
// Also increase the size of the packet pool if required
packetIndex++;
if(packetIndex == allocatedPackets)
{
if(allocatedPackets % XM_PACKET_POOL_GRANULARITY == 0)
{
packets = (XMRTPPacket **)realloc(packets, (allocatedPackets + XM_PACKET_POOL_GRANULARITY) * sizeof(XMRTPPacket *));
}
packets[packetIndex] = new XMRTPPacket(source.GetDataSize());
allocatedPackets++;
}
}
// check for loop termination conditions
PINDEX len = sinks.GetSize();
inUse.Signal();
if(len == 0)
{
break;
}
} while(source.ReadPacket(*(packets[packetIndex])) == TRUE);
// End the media processing
_XMStopMediaReceiving(sessionID);
}
// release the used RTP_DataFrames
for(unsigned i = 0; i < allocatedPackets; i++)
{
XMRTPPacket *dataFrame = packets[i];
delete dataFrame;
}
free(packets);
free(frameBuffer);
if(packetReassembler != NULL)
{
free(packetReassembler);
}
}
void XMReceiverMediaPatch::IssueVideoUpdatePictureCommand()
{
OpalVideoUpdatePicture command = OpalVideoUpdatePicture(-1, -1, -1);
sinks[0].stream->ExecuteCommand(command);
}
<commit_msg>Prevent sending fast update picture commands if there is no sink stream<commit_after>/*
* $Id: XMReceiverMediaPatch.cpp,v 1.31 2007/02/16 14:13:51 hfriederich Exp $
*
* Copyright (c) 2005-2007 XMeeting Project ("http://xmeeting.sf.net").
* All rights reserved.
* Copyright (c) 2005-2007 Hannes Friederich. All rights reserved.
*/
#include "XMReceiverMediaPatch.h"
#include <opal/mediastrm.h>
#include <opal/mediacmd.h>
#include "XMMediaFormats.h"
#include "XMMediaStream.h"
#include "XMCallbackBridge.h"
#include "XMAudioTester.h"
#define XM_PACKET_POOL_GRANULARITY 8
#define XM_FRAME_BUFFER_SIZE 352*288*4
XMReceiverMediaPatch::XMReceiverMediaPatch(OpalMediaStream & src)
: OpalMediaPatch(src)
{
packetReassembler = NULL;
}
XMReceiverMediaPatch::~XMReceiverMediaPatch()
{
}
void XMReceiverMediaPatch::Start()
{
// quit any running audio test if needed
XMAudioTester::Stop();
OpalMediaPatch::Start();
}
void XMReceiverMediaPatch::Main()
{
///////////////////////////////////////////////////////////////////////////////////////////////
// The receiving algorithm tries to achieve best-possible data integrity and builds upon
// the following assumptions:
//
// 1) The chance for packets actually being lost/dropped is very small
// 2) The chance of packets being delayed across timestamp boundaries is much smaller than
// the chance of packets being reordered within the same timestamp (the same video frame)
//
// First, the frames will be read and put into a sorted linked list with ascending sequence
// numbers. If a packet group is complete, the packet payloads are copied together and the
// resulting frame is sent to the XMMediaReceiver class for decompression and display.
// A packet group is considered to be complete IF
//
// a) The first packet has the next ascending sequence number to the sequence number of the
// last packet of the previous packet group or the packet contains the beginning of a
// coded frame (picture start codes in H.261 / H.263) AND
// b) The sequence numbers of the packets in the list are ascending with no sequence number
// missing AND
// c) The last packet has the marker bit set
//
// This algorithm makes it possible to process packets of a packet group even if they arrive
// after the last packet of the packet group with the marker bit set. This works well if
// assumptions 1) and 2) are true.
//
// If a packet group is incomplete and the first packet of the next packet group arrives
// (indicated by a different timestamp), the incomplete packet group is either dropped
// or processed, depending on the codec being used. If the incomplete packet group is
// processed, the processing happens delayed since the first packet of the next packet
// group arrived, leading to inconstant display intervals. As long as assumption 1)
// is met, this is not a big drawback.
//
// If either packets are missing or the decompression of the frame fails, an
// fast update request is being sent to the remote party.
///////////////////////////////////////////////////////////////////////////////////////////////
// Allocating a pool of XMRTPPacket instances to reduce
// buffer allocation overhead.
// The pool size increases in steps of 8 packets with an initial size of 8 packets.
// These 8 packets are allocated initially.
// The packets 9-xx are allocated on demand
unsigned allocatedPackets = XM_PACKET_POOL_GRANULARITY;
XMRTPPacket **packets = (XMRTPPacket **)malloc(allocatedPackets * sizeof(XMRTPPacket *));
unsigned packetIndex = 0;
for(unsigned i = 0; i < allocatedPackets; i++)
{
packets[i] = new XMRTPPacket(source.GetDataSize());
}
// make sure the RTP session does NOT ignore out of order packets
OpalRTPMediaStream & rtpStream = (OpalRTPMediaStream &)source;
rtpStream.GetRtpSession().SetIgnoreOutOfOrderPackets(FALSE);
BYTE *frameBuffer = (BYTE *)malloc(sizeof(BYTE) * XM_FRAME_BUFFER_SIZE);
// Read the first packet
BOOL firstReadSuccesful = source.ReadPacket(*(packets[0]));
// Access the media format
const OpalMediaFormat & mediaFormat = source.GetMediaFormat();
if(firstReadSuccesful == TRUE)
{
// Tell the media receiver to prepare processing packets
XMCodecIdentifier codecIdentifier = _XMGetMediaFormatCodec(mediaFormat);
unsigned sessionID = 2;
RTP_DataFrame::PayloadTypes payloadType = packets[0]->GetPayloadType();
// initialize the packet processing variables
DWORD currentTimestamp = packets[0]->GetTimestamp();
WORD firstSeqNrOfPacketGroup = 0;
XMRTPPacket *firstPacketOfPacketGroup = NULL;
XMRTPPacket *lastPacketOfPacketGroup = NULL;
switch(codecIdentifier)
{
case XMCodecIdentifier_H261:
packetReassembler = new XMH261RTPPacketReassembler();
break;
case XMCodecIdentifier_H263:
if(_XMGetIsRFC2429(mediaFormat) || mediaFormat == XM_MEDIA_FORMAT_H263PLUS)
{
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
else
{
int result = _XMDetermineH263PacketizationScheme(packets[0]->GetPayloadPtr(), packets[0]->GetPayloadSize());
if(result == 0)
{
// cannot determine. Last hope is to look at the payload code
if(payloadType == RTP_DataFrame::H263)
{
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
}
else
{
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
}
else if(result == 1)
{
cout << "Receiving RFC2190" << endl;
packetReassembler = new XMH263RTPPacketReassembler();
}
else
{
cout << "Receiving RFC2429" << endl;
packetReassembler = new XMH263PlusRTPPacketReassembler();
}
}
break;
case XMCodecIdentifier_H264:
packetReassembler = new XMH264RTPPacketReassembler();
break;
default:
break;
}
_XMStartMediaReceiving(sessionID, codecIdentifier);
// loop to receive packets and process them
do {
inUse.Wait();
BOOL processingSuccessful = TRUE;
unsigned numberOfPacketsToRelease = 0;
XMRTPPacket *packet = packets[packetIndex];
packet->next = NULL;
packet->prev = NULL;
// processing the packet
DWORD timestamp = packet->GetTimestamp();
WORD sequenceNumber = packet->GetSequenceNumber();
// take into account that the timestamp might wrap around
if(timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31))
{
// This packet group is already processed
// By changing the sequenceNumber parameter,
// we can adjust the expected beginning of
// the current packet group.
if(firstSeqNrOfPacketGroup <= sequenceNumber)
{
firstSeqNrOfPacketGroup = sequenceNumber + 1;
}
}
else
{
// also take into account that the timestamp might wrap around
if(timestamp > currentTimestamp || (timestamp < currentTimestamp && (currentTimestamp - timestamp) > (0x01 << 31)))
{
if(firstPacketOfPacketGroup != NULL)
{
// Try to process the old packet although not complete
BOOL result = TRUE;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyIncompletePacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if(result == TRUE)
{
_XMProcessFrame(sessionID, frameBuffer, frameBufferSize);
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
processingSuccessful = FALSE;
PTRACE(1, "XMeetingReceiverMediaPatch\tIncomplete old packet group");
// There are (packetIndex + 1) packets in the buffer, but only the last one
// ist still needed
numberOfPacketsToRelease = packetIndex;
}
currentTimestamp = timestamp;
}
if(lastPacketOfPacketGroup != NULL)
{
XMRTPPacket *previousPacket = lastPacketOfPacketGroup;
do {
WORD previousSequenceNumber = previousPacket->GetSequenceNumber();
// take into account that the sequence number might wrap around
if(sequenceNumber > previousSequenceNumber ||
(sequenceNumber < previousSequenceNumber && (previousSequenceNumber - sequenceNumber) > (0x01 << 15)))
{
// ordering is correct, insert at this point
packet->next = previousPacket->next;
previousPacket->next = packet;
packet->prev = previousPacket;
if(previousPacket == lastPacketOfPacketGroup)
{
lastPacketOfPacketGroup = packet;
}
break;
}
else if(sequenceNumber == previousSequenceNumber)
{
break;
}
if(previousPacket == firstPacketOfPacketGroup)
{
// inserting this packet at the beginning of
// the packet group
packet->next = previousPacket;
previousPacket->prev = packet;
firstPacketOfPacketGroup = packet;
break;
}
previousPacket = previousPacket->prev;
} while(TRUE);
}
else
{
firstPacketOfPacketGroup = packet;
lastPacketOfPacketGroup = packet;
}
}
/////////////////////////////////////////////////////////
// checking whether the packet group is complete or not
/////////////////////////////////////////////////////////
BOOL packetGroupIsComplete = FALSE;
WORD expectedSequenceNumber = firstSeqNrOfPacketGroup;
XMRTPPacket *thePacket = firstPacketOfPacketGroup;
BOOL isFirstPacket = FALSE;
if(expectedSequenceNumber == thePacket->GetSequenceNumber())
{
isFirstPacket = TRUE;
}
else
{
// the sequence number is not the expected one. Try to analyze
// the bitstream to determine whether this is the first packet
// of a packet group or not
isFirstPacket = packetReassembler->IsFirstPacketOfFrame(thePacket);
}
if(isFirstPacket == TRUE)
{
expectedSequenceNumber = thePacket->GetSequenceNumber();
do {
if(expectedSequenceNumber != thePacket->GetSequenceNumber())
{
break;
}
expectedSequenceNumber++;
if(thePacket->next == NULL)
{
// no more packets in the packet group.
// If the marker bit is set, we're complete
if(thePacket->GetMarker() == TRUE)
{
packetGroupIsComplete = TRUE;
}
break;
}
thePacket = thePacket->next;
} while(TRUE);
}
/////////////////////////////////////////////////////
// If the packet group is complete, copy the packets
// into a frame and send it to the XMMediaReceiver
// system.
/////////////////////////////////////////////////////
if(packetGroupIsComplete == TRUE)
{
BOOL result = TRUE;
PINDEX frameBufferSize = 0;
result = packetReassembler->CopyPacketsIntoFrameBuffer(firstPacketOfPacketGroup, frameBuffer, &frameBufferSize);
if(result == TRUE)
{
result = _XMProcessFrame(sessionID, frameBuffer, frameBufferSize);
if(result == FALSE)
{
PTRACE(1, "XMeetingReceiverMediaPatch\tDecompression of the frame failed");
processingSuccessful = FALSE;
}
}
else
{
PTRACE(1, "XMeetingReceiverMediaPatch\tCould not copy packets into frame buffer");
processingSuccessful = FALSE;
}
firstSeqNrOfPacketGroup = lastPacketOfPacketGroup->GetSequenceNumber() + 1;
firstPacketOfPacketGroup = NULL;
lastPacketOfPacketGroup = NULL;
// Release all packets in the pool
numberOfPacketsToRelease = packetIndex + 1;
}
if(processingSuccessful == FALSE)
{
IssueVideoUpdatePictureCommand();
processingSuccessful = TRUE;
}
// Of not all packets can be released, the remaining packets are
// put at the beginning of the packet pool.
if(numberOfPacketsToRelease != 0)
{
unsigned i;
for(i = 0; i < (packetIndex + 1 - numberOfPacketsToRelease); i++)
{
// swapping the remaining frames
XMRTPPacket *packet = packets[i];
packets[i] = packets[i + numberOfPacketsToRelease];
packets[i + numberOfPacketsToRelease] = packet;
}
packetIndex = packetIndex + 1 - numberOfPacketsToRelease;
}
else
{
// increment the packetIndex, allocate a new XMRTPPacket if needed.
// Also increase the size of the packet pool if required
packetIndex++;
if(packetIndex == allocatedPackets)
{
if(allocatedPackets % XM_PACKET_POOL_GRANULARITY == 0)
{
packets = (XMRTPPacket **)realloc(packets, (allocatedPackets + XM_PACKET_POOL_GRANULARITY) * sizeof(XMRTPPacket *));
}
packets[packetIndex] = new XMRTPPacket(source.GetDataSize());
allocatedPackets++;
}
}
// check for loop termination conditions
PINDEX len = sinks.GetSize();
inUse.Signal();
if(len == 0)
{
break;
}
} while(source.ReadPacket(*(packets[packetIndex])) == TRUE);
// End the media processing
_XMStopMediaReceiving(sessionID);
}
// release the used RTP_DataFrames
for(unsigned i = 0; i < allocatedPackets; i++)
{
XMRTPPacket *dataFrame = packets[i];
delete dataFrame;
}
free(packets);
free(frameBuffer);
if(packetReassembler != NULL)
{
free(packetReassembler);
}
}
void XMReceiverMediaPatch::IssueVideoUpdatePictureCommand()
{
if(sinks.GetSize() == 0) {
return;
}
OpalVideoUpdatePicture command = OpalVideoUpdatePicture(-1, -1, -1);
sinks[0].stream->ExecuteCommand(command);
}
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(1)
class Solution {
public:
string reverseVowels(string s) {
for (int i = 0, j = s.length() - 1; i < j;) {
if (is_vowel(tolower(s[i])) &&
is_vowel(tolower(s[j]))) {
swap(s[i++], s[j--]);
} else if (!is_vowel(tolower(s[i]))) {
++i;
} else {
--j;
}
}
return s;
}
private:
const string vowels_ = "aeiou";
bool is_vowel(char a){
return vowels_.find(a) != string::npos;
}
};
<commit_msg>Update reverse-vowels-of-a-string.cpp<commit_after>// Time: O(n)
// Space: O(1)
class Solution {
public:
string reverseVowels(string s) {
for (int i = 0, j = s.length() - 1; i < j;) {
if (!is_vowel(tolower(s[i]))) {
++i;
} else if (!is_vowel(tolower(s[j]))) {
--j;
} else {
swap(s[i++], s[j--]);
}
}
return s;
}
private:
const string vowels_ = "aeiou";
bool is_vowel(char a){
return vowels_.find(a) != string::npos;
}
};
<|endoftext|> |
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2015 Taras Kushnir <[email protected]>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <QDir>
#include <QtQml>
#include <QFile>
#include <QtDebug>
#include <QUuid>
#include <QDateTime>
#include <QSettings>
#include <QTextStream>
#include <QQmlContext>
#include <QApplication>
#include <QStandardPaths>
#include <QQmlApplicationEngine>
//-------------------------------------
#include "SpellCheck/spellchecksuggestionmodel.h"
#include "Models/filteredartitemsproxymodel.h"
#include "Suggestion/suggestionqueryengine.h"
#include "Conectivity/analyticsuserevent.h"
#include "SpellCheck/spellcheckerservice.h"
#include "Models/recentdirectoriesmodel.h"
#include "Suggestion/keywordssuggestor.h"
#include "Models/combinedartworksmodel.h"
#include "Conectivity/telemetryservice.h"
#include "Helpers/globalimageprovider.h"
#include "Models/uploadinforepository.h"
#include "Helpers/backupsaverservice.h"
#include "Helpers/helpersqmlwrapper.h"
#include "Encryption/secretsmanager.h"
#include "Models/artworksrepository.h"
#include "Helpers/settingsprovider.h"
#include "UndoRedo/undoredomanager.h"
#include "Helpers/clipboardhelper.h"
#include "Commands/commandmanager.h"
#include "Suggestion/locallibrary.h"
#include "Models/artworkuploader.h"
#include "Models/warningsmanager.h"
#include "Helpers/loggingworker.h"
#include "Helpers/updateservice.h"
#include "Models/artitemsmodel.h"
#include "Models/settingsmodel.h"
#include "Models/iptcprovider.h"
#include "Helpers/appsettings.h"
#include "Models/ziparchiver.h"
#include "Helpers/constants.h"
#include "Encryption/aes-qt.h"
#include "Helpers/runguard.h"
#include "Models/logsmodel.h"
#include "Helpers/logger.h"
#include "Common/version.h"
#include "Common/defines.h"
#ifdef WITH_LOGS
void myMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
Q_UNUSED(context);
QString txt;
switch (type) {
case QtDebugMsg:
txt = QString("Debug: %1").arg(msg);
break;
case QtWarningMsg:
txt = QString("Warning: %1").arg(msg);
break;
case QtCriticalMsg:
txt = QString("Critical: %1").arg(msg);
break;
case QtFatalMsg:
txt = QString("Fatal: %1").arg(msg);
break;
}
QString logLine = QString("%1 - %2")
.arg(QDateTime::currentDateTimeUtc().toString("dd.MM.yyyy hh:mm:ss.zzz"))
.arg(txt);
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.log(logLine);
if (type == QtFatalMsg) {
abort();
}
}
#endif
#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)
void initQSettings() {
QCoreApplication::setOrganizationName(Constants::ORGANIZATION_NAME);
QCoreApplication::setOrganizationDomain(Constants::ORGANIZATION_DOMAIN);
QCoreApplication::setApplicationName(Constants::APPLICATION_NAME);
QString appVersion(STRINGIZE(BUILDNUMBER));
QCoreApplication::setApplicationVersion(STRINGIZE(XPIKS_VERSION)" "STRINGIZE(XPIKS_VERSION_SUFFIX)" - " + appVersion.left(10));
}
void ensureUserIdExists(Helpers::AppSettings *settings) {
QLatin1String userIdKey = QLatin1String(Constants::USER_AGENT_ID);
if (!settings->contains(userIdKey)) {
QUuid uuid = QUuid::createUuid();
settings->setValue(userIdKey, uuid.toString());
}
}
int main(int argc, char *argv[]) {
Helpers::RunGuard guard("xpiks");
if (!guard.tryToRun()) {
std::cerr << "Xpiks is already running";
return -1;
}
initQSettings();
Helpers::AppSettings appSettings;
ensureUserIdExists(&appSettings);
Suggestion::LocalLibrary localLibrary;
QString appDataPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
if (!appDataPath.isEmpty()) {
QDir appDataDir(appDataPath);
QString logFilePath = appDataDir.filePath(Constants::LOG_FILENAME);
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.setLogFilePath(logFilePath);
QString libraryFilePath = appDataDir.filePath(Constants::LIBRARY_FILENAME);
localLibrary.setLibraryPath(libraryFilePath);
}
Models::LogsModel logsModel;
logsModel.startLogging();
#ifdef WITH_LOGS
QString logFileDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
if (!logFileDir.isEmpty()) {
QDir dir(logFileDir);
if (!dir.exists()) {
bool created = QDir().mkpath(logFileDir);
Q_UNUSED(created);
}
}
qInstallMessageHandler(myMessageHandler);
qDebug() << "Log started";
#endif
QApplication app(argc, argv);
localLibrary.loadLibraryAsync();
QString userId = appSettings.value(QLatin1String(Constants::USER_AGENT_ID)).toString();
userId.remove(QRegExp("[{}-]."));
Models::ArtworksRepository artworkRepository;
Models::ArtItemsModel artItemsModel;
Models::CombinedArtworksModel combinedArtworksModel;
Models::IptcProvider iptcProvider;
iptcProvider.setLocalLibrary(&localLibrary);
Models::UploadInfoRepository uploadInfoRepository;
Models::WarningsManager warningsManager;
Models::SettingsModel settingsModel;
settingsModel.readAllValues();
Encryption::SecretsManager secretsManager;
UndoRedo::UndoRedoManager undoRedoManager;
Models::ZipArchiver zipArchiver;
Suggestion::KeywordsSuggestor keywordsSuggestor;
keywordsSuggestor.setLocalLibrary(&localLibrary);
Models::FilteredArtItemsProxyModel filteredArtItemsModel;
filteredArtItemsModel.setSourceModel(&artItemsModel);
Models::RecentDirectoriesModel recentDirectorieModel;
Models::ArtworkUploader artworkUploader(settingsModel.getMaxParallelUploads());
SpellCheck::SpellCheckerService spellCheckerService;
SpellCheck::SpellCheckSuggestionModel spellCheckSuggestionModel;
Helpers::BackupSaverService metadataSaverService;
Helpers::UpdateService updateService;
const QString reportingEndpoint = QLatin1String("cc39a47f60e1ed812e2403b33678dd1c529f1cc43f66494998ec478a4d13496269a3dfa01f882941766dba246c76b12b2a0308e20afd84371c41cf513260f8eb8b71f8c472cafb1abf712c071938ec0791bbf769ab9625c3b64827f511fa3fbb");
QString endpoint = Encryption::decodeText(reportingEndpoint, "reporting");
Conectivity::TelemetryService telemetryService(userId, endpoint);
Commands::CommandManager commandManager;
commandManager.InjectDependency(&artworkRepository);
commandManager.InjectDependency(&artItemsModel);
commandManager.InjectDependency(&filteredArtItemsModel);
commandManager.InjectDependency(&combinedArtworksModel);
commandManager.InjectDependency(&iptcProvider);
commandManager.InjectDependency(&artworkUploader);
commandManager.InjectDependency(&uploadInfoRepository);
commandManager.InjectDependency(&warningsManager);
commandManager.InjectDependency(&secretsManager);
commandManager.InjectDependency(&undoRedoManager);
commandManager.InjectDependency(&zipArchiver);
commandManager.InjectDependency(&keywordsSuggestor);
commandManager.InjectDependency(&settingsModel);
commandManager.InjectDependency(&recentDirectorieModel);
commandManager.InjectDependency(&spellCheckerService);
commandManager.InjectDependency(&spellCheckSuggestionModel);
commandManager.InjectDependency(&metadataSaverService);
commandManager.InjectDependency(&telemetryService);
commandManager.InjectDependency(&updateService);
// other initializations
secretsManager.setMasterPasswordHash(appSettings.value(Constants::MASTER_PASSWORD_HASH, "").toString());
uploadInfoRepository.initFromString(appSettings.value(Constants::UPLOAD_HOSTS, "").toString());
recentDirectorieModel.deserializeFromSettings(appSettings.value(Constants::RECENT_DIRECTORIES, "").toString());
Helpers::SettingsProvider::getInstance().setSettingsModelInstance(&settingsModel);
commandManager.connectEntitiesSignalsSlots();
qmlRegisterType<Helpers::ClipboardHelper>("xpiks", 1, 0, "ClipboardHelper");
QQmlApplicationEngine engine;
Helpers::GlobalImageProvider *globalProvider = new Helpers::GlobalImageProvider(QQmlImageProviderBase::Image);
Helpers::HelpersQmlWrapper helpersQmlWrapper(&commandManager);
QQmlContext *rootContext = engine.rootContext();
rootContext->setContextProperty("artItemsModel", &artItemsModel);
rootContext->setContextProperty("artworkRepository", &artworkRepository);
rootContext->setContextProperty("combinedArtworks", &combinedArtworksModel);
rootContext->setContextProperty("appSettings", &appSettings);
rootContext->setContextProperty("iptcProvider", &iptcProvider);
rootContext->setContextProperty("artworkUploader", &artworkUploader);
rootContext->setContextProperty("uploadInfos", &uploadInfoRepository);
rootContext->setContextProperty("logsModel", &logsModel);
rootContext->setContextProperty("warningsManager", &warningsManager);
rootContext->setContextProperty("secretsManager", &secretsManager);
rootContext->setContextProperty("undoRedoManager", &undoRedoManager);
rootContext->setContextProperty("zipArchiver", &zipArchiver);
rootContext->setContextProperty("keywordsSuggestor", &keywordsSuggestor);
rootContext->setContextProperty("settingsModel", &settingsModel);
rootContext->setContextProperty("filteredArtItemsModel", &filteredArtItemsModel);
rootContext->setContextProperty("helpersWrapper", &helpersQmlWrapper);
rootContext->setContextProperty("recentDirectories", &recentDirectorieModel);
rootContext->setContextProperty("updateService", &updateService);
rootContext->setContextProperty("spellCheckerService", &spellCheckerService);
rootContext->setContextProperty("spellCheckSuggestionModel", &spellCheckSuggestionModel);
engine.addImageProvider("global", globalProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
#ifdef QT_DEBUG
if (argc > 1) {
QStringList pathes;
for (int i = 1; i < argc; ++i) {
pathes.append(QString(argv[i]));
}
commandManager.addInitialArtworks(pathes);
}
#endif
return app.exec();
}
<commit_msg>Minor fix for Release build for qt 5.5<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2015 Taras Kushnir <[email protected]>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <QDir>
#include <QtQml>
#include <QFile>
#include <QtDebug>
#include <QUuid>
#include <QDateTime>
#include <QSettings>
#include <QTextStream>
#include <QQmlContext>
#include <QApplication>
#include <QStandardPaths>
#include <QQmlApplicationEngine>
//-------------------------------------
#include "SpellCheck/spellchecksuggestionmodel.h"
#include "Models/filteredartitemsproxymodel.h"
#include "Suggestion/suggestionqueryengine.h"
#include "Conectivity/analyticsuserevent.h"
#include "SpellCheck/spellcheckerservice.h"
#include "Models/recentdirectoriesmodel.h"
#include "Suggestion/keywordssuggestor.h"
#include "Models/combinedartworksmodel.h"
#include "Conectivity/telemetryservice.h"
#include "Helpers/globalimageprovider.h"
#include "Models/uploadinforepository.h"
#include "Helpers/backupsaverservice.h"
#include "Helpers/helpersqmlwrapper.h"
#include "Encryption/secretsmanager.h"
#include "Models/artworksrepository.h"
#include "Helpers/settingsprovider.h"
#include "UndoRedo/undoredomanager.h"
#include "Helpers/clipboardhelper.h"
#include "Commands/commandmanager.h"
#include "Suggestion/locallibrary.h"
#include "Models/artworkuploader.h"
#include "Models/warningsmanager.h"
#include "Helpers/loggingworker.h"
#include "Helpers/updateservice.h"
#include "Models/artitemsmodel.h"
#include "Models/settingsmodel.h"
#include "Models/iptcprovider.h"
#include "Helpers/appsettings.h"
#include "Models/ziparchiver.h"
#include "Helpers/constants.h"
#include "Encryption/aes-qt.h"
#include "Helpers/runguard.h"
#include "Models/logsmodel.h"
#include "Helpers/logger.h"
#include "Common/version.h"
#include "Common/defines.h"
#ifdef WITH_LOGS
void myMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
Q_UNUSED(context);
QString txt;
switch (type) {
case QtDebugMsg:
txt = QString("Debug: %1").arg(msg);
break;
case QtWarningMsg:
txt = QString("Warning: %1").arg(msg);
break;
case QtCriticalMsg:
txt = QString("Critical: %1").arg(msg);
break;
case QtFatalMsg:
txt = QString("Fatal: %1").arg(msg);
break;
case QtInfoMsg:
txt = QString("Info: %1").arg(msg);
break;
}
QString logLine = QString("%1 - %2")
.arg(QDateTime::currentDateTimeUtc().toString("dd.MM.yyyy hh:mm:ss.zzz"))
.arg(txt);
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.log(logLine);
if (type == QtFatalMsg) {
abort();
}
}
#endif
#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)
void initQSettings() {
QCoreApplication::setOrganizationName(Constants::ORGANIZATION_NAME);
QCoreApplication::setOrganizationDomain(Constants::ORGANIZATION_DOMAIN);
QCoreApplication::setApplicationName(Constants::APPLICATION_NAME);
QString appVersion(STRINGIZE(BUILDNUMBER));
QCoreApplication::setApplicationVersion(STRINGIZE(XPIKS_VERSION)" "STRINGIZE(XPIKS_VERSION_SUFFIX)" - " + appVersion.left(10));
}
void ensureUserIdExists(Helpers::AppSettings *settings) {
QLatin1String userIdKey = QLatin1String(Constants::USER_AGENT_ID);
if (!settings->contains(userIdKey)) {
QUuid uuid = QUuid::createUuid();
settings->setValue(userIdKey, uuid.toString());
}
}
int main(int argc, char *argv[]) {
Helpers::RunGuard guard("xpiks");
if (!guard.tryToRun()) {
std::cerr << "Xpiks is already running";
return -1;
}
initQSettings();
Helpers::AppSettings appSettings;
ensureUserIdExists(&appSettings);
Suggestion::LocalLibrary localLibrary;
QString appDataPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
if (!appDataPath.isEmpty()) {
QDir appDataDir(appDataPath);
QString logFilePath = appDataDir.filePath(Constants::LOG_FILENAME);
Helpers::Logger &logger = Helpers::Logger::getInstance();
logger.setLogFilePath(logFilePath);
QString libraryFilePath = appDataDir.filePath(Constants::LIBRARY_FILENAME);
localLibrary.setLibraryPath(libraryFilePath);
}
Models::LogsModel logsModel;
logsModel.startLogging();
#ifdef WITH_LOGS
QString logFileDir = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
if (!logFileDir.isEmpty()) {
QDir dir(logFileDir);
if (!dir.exists()) {
bool created = QDir().mkpath(logFileDir);
Q_UNUSED(created);
}
}
qInstallMessageHandler(myMessageHandler);
qDebug() << "Log started";
#endif
QApplication app(argc, argv);
localLibrary.loadLibraryAsync();
QString userId = appSettings.value(QLatin1String(Constants::USER_AGENT_ID)).toString();
userId.remove(QRegExp("[{}-]."));
Models::ArtworksRepository artworkRepository;
Models::ArtItemsModel artItemsModel;
Models::CombinedArtworksModel combinedArtworksModel;
Models::IptcProvider iptcProvider;
iptcProvider.setLocalLibrary(&localLibrary);
Models::UploadInfoRepository uploadInfoRepository;
Models::WarningsManager warningsManager;
Models::SettingsModel settingsModel;
settingsModel.readAllValues();
Encryption::SecretsManager secretsManager;
UndoRedo::UndoRedoManager undoRedoManager;
Models::ZipArchiver zipArchiver;
Suggestion::KeywordsSuggestor keywordsSuggestor;
keywordsSuggestor.setLocalLibrary(&localLibrary);
Models::FilteredArtItemsProxyModel filteredArtItemsModel;
filteredArtItemsModel.setSourceModel(&artItemsModel);
Models::RecentDirectoriesModel recentDirectorieModel;
Models::ArtworkUploader artworkUploader(settingsModel.getMaxParallelUploads());
SpellCheck::SpellCheckerService spellCheckerService;
SpellCheck::SpellCheckSuggestionModel spellCheckSuggestionModel;
Helpers::BackupSaverService metadataSaverService;
Helpers::UpdateService updateService;
const QString reportingEndpoint = QLatin1String("cc39a47f60e1ed812e2403b33678dd1c529f1cc43f66494998ec478a4d13496269a3dfa01f882941766dba246c76b12b2a0308e20afd84371c41cf513260f8eb8b71f8c472cafb1abf712c071938ec0791bbf769ab9625c3b64827f511fa3fbb");
QString endpoint = Encryption::decodeText(reportingEndpoint, "reporting");
Conectivity::TelemetryService telemetryService(userId, endpoint);
Commands::CommandManager commandManager;
commandManager.InjectDependency(&artworkRepository);
commandManager.InjectDependency(&artItemsModel);
commandManager.InjectDependency(&filteredArtItemsModel);
commandManager.InjectDependency(&combinedArtworksModel);
commandManager.InjectDependency(&iptcProvider);
commandManager.InjectDependency(&artworkUploader);
commandManager.InjectDependency(&uploadInfoRepository);
commandManager.InjectDependency(&warningsManager);
commandManager.InjectDependency(&secretsManager);
commandManager.InjectDependency(&undoRedoManager);
commandManager.InjectDependency(&zipArchiver);
commandManager.InjectDependency(&keywordsSuggestor);
commandManager.InjectDependency(&settingsModel);
commandManager.InjectDependency(&recentDirectorieModel);
commandManager.InjectDependency(&spellCheckerService);
commandManager.InjectDependency(&spellCheckSuggestionModel);
commandManager.InjectDependency(&metadataSaverService);
commandManager.InjectDependency(&telemetryService);
commandManager.InjectDependency(&updateService);
// other initializations
secretsManager.setMasterPasswordHash(appSettings.value(Constants::MASTER_PASSWORD_HASH, "").toString());
uploadInfoRepository.initFromString(appSettings.value(Constants::UPLOAD_HOSTS, "").toString());
recentDirectorieModel.deserializeFromSettings(appSettings.value(Constants::RECENT_DIRECTORIES, "").toString());
Helpers::SettingsProvider::getInstance().setSettingsModelInstance(&settingsModel);
commandManager.connectEntitiesSignalsSlots();
qmlRegisterType<Helpers::ClipboardHelper>("xpiks", 1, 0, "ClipboardHelper");
QQmlApplicationEngine engine;
Helpers::GlobalImageProvider *globalProvider = new Helpers::GlobalImageProvider(QQmlImageProviderBase::Image);
Helpers::HelpersQmlWrapper helpersQmlWrapper(&commandManager);
QQmlContext *rootContext = engine.rootContext();
rootContext->setContextProperty("artItemsModel", &artItemsModel);
rootContext->setContextProperty("artworkRepository", &artworkRepository);
rootContext->setContextProperty("combinedArtworks", &combinedArtworksModel);
rootContext->setContextProperty("appSettings", &appSettings);
rootContext->setContextProperty("iptcProvider", &iptcProvider);
rootContext->setContextProperty("artworkUploader", &artworkUploader);
rootContext->setContextProperty("uploadInfos", &uploadInfoRepository);
rootContext->setContextProperty("logsModel", &logsModel);
rootContext->setContextProperty("warningsManager", &warningsManager);
rootContext->setContextProperty("secretsManager", &secretsManager);
rootContext->setContextProperty("undoRedoManager", &undoRedoManager);
rootContext->setContextProperty("zipArchiver", &zipArchiver);
rootContext->setContextProperty("keywordsSuggestor", &keywordsSuggestor);
rootContext->setContextProperty("settingsModel", &settingsModel);
rootContext->setContextProperty("filteredArtItemsModel", &filteredArtItemsModel);
rootContext->setContextProperty("helpersWrapper", &helpersQmlWrapper);
rootContext->setContextProperty("recentDirectories", &recentDirectorieModel);
rootContext->setContextProperty("updateService", &updateService);
rootContext->setContextProperty("spellCheckerService", &spellCheckerService);
rootContext->setContextProperty("spellCheckSuggestionModel", &spellCheckSuggestionModel);
engine.addImageProvider("global", globalProvider);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
#ifdef QT_DEBUG
if (argc > 1) {
QStringList pathes;
for (int i = 1; i < argc; ++i) {
pathes.append(QString(argv[i]));
}
commandManager.addInitialArtworks(pathes);
}
#endif
return app.exec();
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* Copyright (c) 2012 */
/* Linas Vepstas <[email protected]> */
/* All rights reserved */
/* */
/*************************************************************************/
/// This file provides a unit test for the operation of the viterbi parser.
#include <stdlib.h>
#include <iostream>
#include <link-grammar/link-includes.h>
#include "read-dict.h"
#include "parser.h"
using namespace std;
using namespace link_grammar::viterbi;
#define Lynk link_grammar::viterbi::Link
#define ANODE(TYPE,NAME) (new Node(TYPE,NAME))
#define ALINK1(TYPE,A) (new Lynk(TYPE, A))
#define ALINK2(TYPE,A,B) (new Lynk(TYPE, A,B))
#define ALINK3(TYPE,A,B,C) (new Lynk(TYPE, A,B,C))
int total_tests = 0;
// ==================================================================
// A simple hello test; several different dictionaries
// should give exactly the same output. The input sentence
// is just one word, it should connect to the left-wall in
// just one way.
bool test_hello(const char *id, const char *dict_str)
{
total_tests++;
Dictionary dict = dictionary_create_from_utf8(dict_str);
// print_dictionary_data(dict);
Parser parser(dict);
parser.streamin("Hello");
// This is the expected output, no matter what the
// dictionary may be.
Lynk* ans =
ALINK1(SET,
ALINK3(LING,
ANODE(LING_TYPE, "Wd"),
ALINK2(WORD_DISJ,
ANODE(WORD, "LEFT-WALL"),
ANODE(CONNECTOR, "Wd+")
),
ALINK2(WORD_DISJ,
ANODE(WORD, "Hello"),
ANODE(CONNECTOR, "Wd-")
)
)
);
Lynk* output = parser.get_output_set();
if (not (ans->operator==(output)))
{
cout << "Error: test failure on test " << id << endl;
cout << "=== Expecting:\n" << ans << endl;
cout << "=== Got:\n" << output << endl;
return false;
}
Lynk* final_state = parser.get_state();
if (0 != final_state->get_arity())
{
cout << "Error: test failure on test " << id << endl;
cout << "Expecting the final state to be the empty set, but found:\n"
<< final_state << endl;
return false;
}
cout<<"PASS: test_hello(" << id << ") " << endl;
return true;
}
bool test_simplest()
{
return test_hello ("test_simplest",
"LEFT-WALL: Wd+;"
"Hello: Wd-;"
);
}
bool test_simple_left_disj()
{
return test_hello ("simple left disj",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: Wd-;"
);
}
bool test_simple_optional_left_cset()
{
return test_hello ("optional left cset",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {CP+} & {Xx+} & {RW+ or Xp+};"
"Hello: Wd-;"
);
}
bool test_simple_right_disj()
{
return test_hello ("simple right disj",
"LEFT-WALL: Wd+;"
"Hello: Wd- or Wi-;"
);
}
bool test_simple_optional()
{
return test_hello ("optionals in both csets",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {CP+} & {Xx+} & {RW+ or Xp+};"
"Hello: Wd- or Xi- or (Xj- & {A+ or B+});"
);
}
bool test_simple_onereq()
{
return test_hello ("one required link (simple)",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: Wd- & {A+} & {B+} & {C+};"
);
}
bool test_simple_zeroreq()
{
return test_hello ("zero required links (simple)",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: {Wd-} & {A+} & {B+} & {C+};"
);
}
int ntest_simple()
{
size_t num_failures = 0;
if (!test_simplest()) num_failures++;
if (!test_simple_left_disj()) num_failures++;
if (!test_simple_optional_left_cset()) num_failures++;
if (!test_simple_right_disj()) num_failures++;
if (!test_simple_optional()) num_failures++;
if (!test_simple_onereq()) num_failures++;
if (!test_simple_zeroreq()) num_failures++;
return num_failures;
}
// ==================================================================
// A test of two alternative parses of a sentence with single word in it.
// Expect to get back a set with two alternative parses, each parse is
// assigned a probability of 1/2.
bool test_alternative(const char *id, const char *dict_str)
{
total_tests++;
Dictionary dict = dictionary_create_from_utf8(dict_str);
// print_dictionary_data(dict);
Parser parser(dict);
parser.streamin("Hello");
Lynk* ans =
ALINK2(SET,
ALINK3(LING,
ANODE(LING_TYPE, "Wd"),
ALINK2(WORD_DISJ,
ANODE(WORD, "LEFT-WALL"),
ANODE(CONNECTOR, "Wd+")
),
ALINK2(WORD_DISJ,
ANODE(WORD, "Hello"),
ANODE(CONNECTOR, "Wd-")
)
),
ALINK3(LING,
ANODE(LING_TYPE, "Wi"),
ALINK2(WORD_DISJ,
ANODE(WORD, "LEFT-WALL"),
ANODE(CONNECTOR, "Wi+")
),
ALINK2(WORD_DISJ,
ANODE(WORD, "Hello"),
ANODE(CONNECTOR, "Wi-")
)
)
);
Lynk* output = parser.get_output_set();
if (not (ans->operator==(output)))
{
cout << "Error: test failure on test " << id << endl;
cout << "=== Expecting:\n" << ans << endl;
cout << "=== Got:\n" << output << endl;
return false;
}
Lynk* final_state = parser.get_state();
if (0 != final_state->get_arity())
{
cout << "Error: test failure on test " << id << endl;
cout << "Expecting the final state to be the empty set, but found:\n"
<< final_state << endl;
return false;
}
cout<<"PASS: test_alternative(" << id << ") " << endl;
return true;
}
bool test_two_alts()
{
return test_alternative("two alternatives",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: Wd- or Wi-;"
);
}
bool test_two_opts()
{
return test_alternative("two alts plus opts",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or Wi- or (Xj- & {A+ or B+});"
);
}
bool test_two_one_opts()
{
return test_alternative("two alt, or one opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or {Wi-} or (Xj- & {A+ or B+});"
);
}
bool test_two_all_opts()
{
return test_alternative("two alts, or all opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: {Wd-} or {Wi-} or (Xj- & {A+ or B+});"
);
}
bool test_two_and_opts()
{
return test_alternative("two alts, and an opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or (Wi- & {Xj- & {A+ or B+}} & {C+});"
);
}
bool test_two_and_no_opts()
{
return test_alternative("two alt, and all opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or ({Wi-} & {Xj- & {A+ or B+}} & {C+});"
);
}
bool test_two_and_excess()
{
return test_alternative("two alt, and excess reqs",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or (Wi- & Xj- & {A+ or B+} & {C+}) or Wi-;"
);
}
int ntest_two()
{
size_t num_failures = 0;
if (!test_two_alts()) num_failures++;
if (!test_two_opts()) num_failures++;
if (!test_two_one_opts()) num_failures++;
if (!test_two_all_opts()) num_failures++;
if (!test_two_and_opts()) num_failures++;
if (!test_two_and_no_opts()) num_failures++;
if (!test_two_and_excess()) num_failures++;
return num_failures;
}
// ==================================================================
bool test_simple_state(const char *id, const char *dict_str)
{
total_tests++;
Dictionary dict = dictionary_create_from_utf8(dict_str);
// print_dictionary_data(dict);
Parser parser(dict);
// Expecting more words to follow, so a non-trivial state.
parser.streamin("this");
Lynk* output = parser.get_output_set();
if (output)
{
cout << "Error: test failure on test " << id << endl;
cout << "Expecting no output, but found:\n"
<< output << endl;
return false;
}
Lynk* ans =
ALINK1(SET,
ALINK2(SEQ,
ALINK2(WORD_CSET,
ANODE(WORD, "this"),
ANODE(CONNECTOR, "Ss*b+")
),
ALINK2(WORD_CSET,
ANODE(WORD, "LEFT-WALL"),
ALINK3(OR,
ANODE(CONNECTOR, "Wd+"),
ANODE(CONNECTOR, "Wi+"),
ANODE(CONNECTOR, "Wq+")
)
)
)
);
Lynk* state = parser.get_state();
if (not (ans->operator==(state)))
{
cout << "Error: test failure on test " << id << endl;
cout << "=== Expecting state:\n" << ans << endl;
cout << "=== Got state:\n" << state << endl;
return false;
}
return true;
}
bool test_first_state()
{
return test_simple_state("first state",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"this: Ss*b+;"
);
}
// ==================================================================
int
main(int argc, char *argv[])
{
size_t num_failures = 0;
num_failures += ntest_simple();
num_failures += ntest_two();
if (!test_first_state()) num_failures++;
if (num_failures)
{
cout << "Test failures = " << num_failures
<< " out of " << total_tests
<< " total." << endl;
exit(1);
}
cout << "All " << total_tests
<< " tests pass." << endl;
exit (0);
}
<commit_msg>Add new failing test<commit_after>/*************************************************************************/
/* Copyright (c) 2012 */
/* Linas Vepstas <[email protected]> */
/* All rights reserved */
/* */
/*************************************************************************/
/// This file provides a unit test for the operation of the viterbi parser.
#include <stdlib.h>
#include <iostream>
#include <link-grammar/link-includes.h>
#include "read-dict.h"
#include "parser.h"
using namespace std;
using namespace link_grammar::viterbi;
#define Lynk link_grammar::viterbi::Link
#define ANODE(TYPE,NAME) (new Node(TYPE,NAME))
#define ALINK1(TYPE,A) (new Lynk(TYPE, A))
#define ALINK2(TYPE,A,B) (new Lynk(TYPE, A,B))
#define ALINK3(TYPE,A,B,C) (new Lynk(TYPE, A,B,C))
int total_tests = 0;
// ==================================================================
// A simple hello test; several different dictionaries
// should give exactly the same output. The input sentence
// is just one word, it should connect to the left-wall in
// just one way.
bool test_hello(const char *id, const char *dict_str)
{
total_tests++;
Dictionary dict = dictionary_create_from_utf8(dict_str);
// print_dictionary_data(dict);
Parser parser(dict);
parser.streamin("Hello");
// This is the expected output, no matter what the
// dictionary may be.
Lynk* ans =
ALINK1(SET,
ALINK3(LING,
ANODE(LING_TYPE, "Wd"),
ALINK2(WORD_DISJ,
ANODE(WORD, "LEFT-WALL"),
ANODE(CONNECTOR, "Wd+")
),
ALINK2(WORD_DISJ,
ANODE(WORD, "Hello"),
ANODE(CONNECTOR, "Wd-")
)
)
);
Lynk* output = parser.get_output_set();
if (not (ans->operator==(output)))
{
cout << "Error: test failure on test " << id << endl;
cout << "=== Expecting:\n" << ans << endl;
cout << "=== Got:\n" << output << endl;
return false;
}
Lynk* final_state = parser.get_state();
if (0 != final_state->get_arity())
{
cout << "Error: test failure on test " << id << endl;
cout << "Expecting the final state to be the empty set, but found:\n"
<< final_state << endl;
return false;
}
cout<<"PASS: test_hello(" << id << ") " << endl;
return true;
}
bool test_simplest()
{
return test_hello ("test_simplest",
"LEFT-WALL: Wd+;"
"Hello: Wd-;"
);
}
bool test_simple_left_disj()
{
return test_hello ("simple left disj",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: Wd-;"
);
}
bool test_simple_optional_left_cset()
{
return test_hello ("optional left cset",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {CP+} & {Xx+} & {RW+ or Xp+};"
"Hello: Wd-;"
);
}
bool test_simple_right_disj()
{
return test_hello ("simple right disj",
"LEFT-WALL: Wd+;"
"Hello: Wd- or Wi-;"
);
}
bool test_simple_optional()
{
return test_hello ("optionals in both csets",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {CP+} & {Xx+} & {RW+ or Xp+};"
"Hello: Wd- or Xi- or (Xj- & {A+ or B+});"
);
}
bool test_simple_onereq()
{
return test_hello ("one required link (simple)",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: Wd- & {A+} & {B+} & {C+};"
);
}
bool test_simple_zeroreq()
{
return test_hello ("zero required links (simple)",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: {Wd-} & {A+} & {B+} & {C+};"
);
}
int ntest_simple()
{
size_t num_failures = 0;
if (!test_simplest()) num_failures++;
if (!test_simple_left_disj()) num_failures++;
if (!test_simple_optional_left_cset()) num_failures++;
if (!test_simple_right_disj()) num_failures++;
if (!test_simple_optional()) num_failures++;
if (!test_simple_onereq()) num_failures++;
if (!test_simple_zeroreq()) num_failures++;
return num_failures;
}
// ==================================================================
// A test of two alternative parses of a sentence with single word in it.
// Expect to get back a set with two alternative parses, each parse is
// assigned a probability of 1/2.
bool test_alternative(const char *id, const char *dict_str)
{
total_tests++;
Dictionary dict = dictionary_create_from_utf8(dict_str);
// print_dictionary_data(dict);
Parser parser(dict);
parser.streamin("Hello");
Lynk* ans =
ALINK2(SET,
ALINK3(LING,
ANODE(LING_TYPE, "Wd"),
ALINK2(WORD_DISJ,
ANODE(WORD, "LEFT-WALL"),
ANODE(CONNECTOR, "Wd+")
),
ALINK2(WORD_DISJ,
ANODE(WORD, "Hello"),
ANODE(CONNECTOR, "Wd-")
)
),
ALINK3(LING,
ANODE(LING_TYPE, "Wi"),
ALINK2(WORD_DISJ,
ANODE(WORD, "LEFT-WALL"),
ANODE(CONNECTOR, "Wi+")
),
ALINK2(WORD_DISJ,
ANODE(WORD, "Hello"),
ANODE(CONNECTOR, "Wi-")
)
)
);
Lynk* output = parser.get_output_set();
if (not (ans->operator==(output)))
{
cout << "Error: test failure on test " << id << endl;
cout << "=== Expecting:\n" << ans << endl;
cout << "=== Got:\n" << output << endl;
return false;
}
Lynk* final_state = parser.get_state();
if (0 != final_state->get_arity())
{
cout << "Error: test failure on test " << id << endl;
cout << "Expecting the final state to be the empty set, but found:\n"
<< final_state << endl;
return false;
}
cout<<"PASS: test_alternative(" << id << ") " << endl;
return true;
}
bool test_two_alts()
{
return test_alternative("two alternatives",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"Hello: Wd- or Wi-;"
);
}
bool test_two_opts()
{
return test_alternative("two alts plus opts",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or Wi- or (Xj- & {A+ or B+});"
);
}
bool test_two_one_opts()
{
return test_alternative("two alt, or one opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or {Wi-} or (Xj- & {A+ or B+});"
);
}
bool test_two_all_opts()
{
return test_alternative("two alts, or all opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: {Wd-} or {Wi-} or (Xj- & {A+ or B+});"
);
}
bool test_two_and_opts()
{
return test_alternative("two alts, and an opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or (Wi- & {Xj- & {A+ or B+}} & {C+});"
);
}
bool test_two_and_no_opts()
{
return test_alternative("two alt, and all opt",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or ({Wi-} & {Xj- & {A+ or B+}} & {C+});"
);
}
bool test_two_and_excess()
{
return test_alternative("two alt, and excess reqs",
"LEFT-WALL: (Wd+ or Wi+ or Wq+) & {A+};"
"Hello: Wd- or (Wi- & Xj- & {A+ or B+} & {C+}) or Wi-;"
);
}
int ntest_two()
{
size_t num_failures = 0;
if (!test_two_alts()) num_failures++;
if (!test_two_opts()) num_failures++;
if (!test_two_one_opts()) num_failures++;
if (!test_two_all_opts()) num_failures++;
if (!test_two_and_opts()) num_failures++;
if (!test_two_and_no_opts()) num_failures++;
if (!test_two_and_excess()) num_failures++;
return num_failures;
}
// ==================================================================
bool test_simple_state(const char *id, const char *dict_str)
{
total_tests++;
Dictionary dict = dictionary_create_from_utf8(dict_str);
// print_dictionary_data(dict);
Parser parser(dict);
// Expecting more words to follow, so a non-trivial state.
parser.streamin("this");
Lynk* output = parser.get_output_set();
if (output)
{
cout << "Error: test failure on test " << id << endl;
cout << "Expecting no output, but found:\n"
<< output << endl;
return false;
}
Lynk* ans =
ALINK1(SET,
ALINK2(SEQ,
ALINK2(WORD_CSET,
ANODE(WORD, "this"),
ANODE(CONNECTOR, "Ss*b+")
),
ALINK2(WORD_CSET,
ANODE(WORD, "LEFT-WALL"),
ALINK3(OR,
ANODE(CONNECTOR, "Wd+"),
ANODE(CONNECTOR, "Wi+"),
ANODE(CONNECTOR, "Wq+")
)
)
)
);
Lynk* state = parser.get_state();
if (not (ans->operator==(state)))
{
cout << "Error: test failure on test " << id << endl;
cout << "=== Expecting state:\n" << ans << endl;
cout << "=== Got state:\n" << state << endl;
return false;
}
return true;
}
bool test_first_state()
{
return test_simple_state("first state",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"this: Ss*b+;"
);
}
bool test_first_opt_lefty()
{
return test_simple_state("first state, left-going optional",
"LEFT-WALL: Wd+ or Wi+ or Wq+;"
"this: Ss*b+ and {Xi-};"
);
}
// ==================================================================
int
main(int argc, char *argv[])
{
size_t num_failures = 0;
num_failures += ntest_simple();
num_failures += ntest_two();
if (!test_first_state()) num_failures++;
if (!test_first_opt_lefty()) num_failures++;
if (num_failures)
{
cout << "Test failures = " << num_failures
<< " out of " << total_tests
<< " total." << endl;
exit(1);
}
cout << "All " << total_tests
<< " tests pass." << endl;
exit (0);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQtChartSeriesOptions.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#ifdef _MSC_VER
// Disable warnings that Qt headers give.
#pragma warning(disable:4127)
#endif
#include "vtkQtChartSeriesOptions.h"
#include "vtkQtChartSeriesColors.h"
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions::vtkQtChartSeriesOptions(QObject* parentObject)
:QObject(parentObject)
{
this->InitializeDefaults();
}
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions::vtkQtChartSeriesOptions(
const vtkQtChartSeriesOptions &other)
: QObject(), Data(other.Data), Defaults(other.Defaults)
{
this->InitializeDefaults();
}
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions::~vtkQtChartSeriesOptions()
{
}
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions &vtkQtChartSeriesOptions::operator=(
const vtkQtChartSeriesOptions &other)
{
this->Defaults = other.Defaults;
this->Data = other.Data;
return *this;
}
//----------------------------------------------------------------------------
vtkQtChartSeriesColors *vtkQtChartSeriesOptions::getSeriesColors() const
{
return qobject_cast<vtkQtChartSeriesColors*>(
this->getGenericOption(COLORS).value<QObject*>());
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::setSeriesColors(vtkQtChartSeriesColors *colors)
{
this->setGenericOption(COLORS, colors);
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::setGenericOption(
vtkQtChartSeriesOptions::OptionType type, const QVariant& value)
{
QMap<OptionType, QVariant>::const_iterator iter = this->Data.find(type);
if (iter == this->Data.end() || iter.value() != value)
{
// we call getGenericOption() since we need to take into consideration the
// default value as well before firing the dataChanged() signal. This is
// essential since the chart layers may do some non-idempotent operations
// that can cause amazing issues when this signal is fired when no data has
// really changed.
QVariant oldValue = this->getGenericOption(type);
this->Data[type] = value;
if (oldValue != value)
{
emit this->dataChanged(type, value, oldValue);
}
}
}
//----------------------------------------------------------------------------
QVariant vtkQtChartSeriesOptions::getGenericOption(
vtkQtChartSeriesOptions::OptionType type) const
{
if (this->Data.contains(type))
{
return this->Data[type];
}
else if (this->Defaults.contains(type))
{
return this->Defaults[type];
}
return QVariant();
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::setDefaultOption(
OptionType type, const QVariant& value)
{
QMap<OptionType, QVariant>::const_iterator iter = this->Defaults.find(type);
if (iter == this->Defaults.end() || iter.value() != value)
{
QVariant oldValue = this->getGenericOption(type);
this->Defaults[type] = value;
if (this->getGenericOption(type) != oldValue)
{
emit this->dataChanged(type, value, oldValue);
}
}
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::InitializeDefaults()
{
this->Defaults[VISIBLE] = true;
this->Defaults[PEN] = QPen(Qt::red);
this->Defaults[BRUSH] = QBrush(Qt::red);
this->Defaults[COLORS]= (vtkQtChartSeriesColors*)NULL;
this->Defaults[AXES_CORNER] = vtkQtChartLayer::BottomLeft;
this->Defaults[MARKER_STYLE] = vtkQtPointMarker::NoMarker;
this->Defaults[MARKER_SIZE] = QSizeF(5, 5);
}
<commit_msg>COMP: fixed compiler error with Qt 4.5<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkQtChartSeriesOptions.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*-------------------------------------------------------------------------
Copyright 2008 Sandia Corporation.
Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------*/
#ifdef _MSC_VER
// Disable warnings that Qt headers give.
#pragma warning(disable:4127)
#endif
#include "vtkQtChartSeriesOptions.h"
#include "vtkQtChartSeriesColors.h"
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions::vtkQtChartSeriesOptions(QObject* parentObject)
:QObject(parentObject)
{
this->InitializeDefaults();
}
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions::vtkQtChartSeriesOptions(
const vtkQtChartSeriesOptions &other)
: QObject(), Data(other.Data), Defaults(other.Defaults)
{
this->InitializeDefaults();
}
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions::~vtkQtChartSeriesOptions()
{
}
//----------------------------------------------------------------------------
vtkQtChartSeriesOptions &vtkQtChartSeriesOptions::operator=(
const vtkQtChartSeriesOptions &other)
{
this->Defaults = other.Defaults;
this->Data = other.Data;
return *this;
}
//----------------------------------------------------------------------------
vtkQtChartSeriesColors *vtkQtChartSeriesOptions::getSeriesColors() const
{
return qobject_cast<vtkQtChartSeriesColors*>(
this->getGenericOption(COLORS).value<QObject*>());
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::setSeriesColors(vtkQtChartSeriesColors *colors)
{
this->setGenericOption(COLORS, colors);
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::setGenericOption(
vtkQtChartSeriesOptions::OptionType type, const QVariant& value)
{
QMap<OptionType, QVariant>::const_iterator iter = this->Data.find(type);
if (iter == this->Data.end() || iter.value() != value)
{
// we call getGenericOption() since we need to take into consideration the
// default value as well before firing the dataChanged() signal. This is
// essential since the chart layers may do some non-idempotent operations
// that can cause amazing issues when this signal is fired when no data has
// really changed.
QVariant oldValue = this->getGenericOption(type);
this->Data[type] = value;
if (oldValue != value)
{
emit this->dataChanged(type, value, oldValue);
}
}
}
//----------------------------------------------------------------------------
QVariant vtkQtChartSeriesOptions::getGenericOption(
vtkQtChartSeriesOptions::OptionType type) const
{
if (this->Data.contains(type))
{
return this->Data[type];
}
else if (this->Defaults.contains(type))
{
return this->Defaults[type];
}
return QVariant();
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::setDefaultOption(
OptionType type, const QVariant& value)
{
QMap<OptionType, QVariant>::const_iterator iter = this->Defaults.find(type);
if (iter == this->Defaults.end() || iter.value() != value)
{
QVariant oldValue = this->getGenericOption(type);
this->Defaults[type] = value;
if (this->getGenericOption(type) != oldValue)
{
emit this->dataChanged(type, value, oldValue);
}
}
}
//----------------------------------------------------------------------------
void vtkQtChartSeriesOptions::InitializeDefaults()
{
this->Defaults[VISIBLE] = true;
this->Defaults[PEN] = QPen(Qt::red);
this->Defaults[BRUSH] = QBrush(Qt::red);
this->Defaults[COLORS]= 0;
this->Defaults[AXES_CORNER] = vtkQtChartLayer::BottomLeft;
this->Defaults[MARKER_STYLE] = vtkQtPointMarker::NoMarker;
this->Defaults[MARKER_SIZE] = QSizeF(5, 5);
}
<|endoftext|> |
<commit_before>#pragma once
#include "meta/enable_if.hpp"
#include "range.hpp"
#include <algorithm>
#include <array>
#include <functional>
namespace frea {
template <class MT>
class Random {
private:
using MT_t = MT;
MT_t _mt;
template <class T>
using Lim = std::numeric_limits<T>;
template <class T>
struct Dist_Int {
using uniform_t = std::uniform_int_distribution<T>;
constexpr static Range<T> DefaultRange{Lim<T>::lowest(), Lim<T>::max()},
NumericRange = DefaultRange;
};
template <class T>
struct Dist_Float {
using uniform_t = std::uniform_real_distribution<T>;
constexpr static Range<T> DefaultRange{T(0), T(1)},
NumericRange{Lim<T>::lowest()/2, Lim<T>::max()/2};
};
template <class T, ENABLE_IF((std::is_integral<T>{}))>
static Dist_Int<T> DetectDist();
template <class T, ENABLE_IF((std::is_floating_point<T>{}))>
static Dist_Float<T> DetectDist();
template <class T>
using Dist_t = decltype(DetectDist<T>());
public:
template <class T>
class RObj {
private:
Random& _rd;
const Range<T> _range;
public:
RObj(Random& rd, const Range<T>& r):
_rd(rd),
_range(r)
{}
RObj(const RObj&) = default;
//! 実行時範囲指定
auto operator ()(const Range<T>& r) const {
return _rd.template getUniform<T>(r);
}
//! デフォルト範囲指定
auto operator ()() const {
return (*this)(_range);
}
};
public:
Random(MT_t mt) noexcept: _mt(std::move(mt)) {}
Random(const Random&) = delete;
Random(Random&& t) noexcept {
*this = std::move(t);
}
Random& operator = (Random&& t) noexcept {
swap(t);
return *this;
}
void swap(Random& t) noexcept {
std::swap(_mt, t._mt);
}
MT_t& refMt() noexcept {
return _mt;
}
//! 一様分布
/*! floating-pointの場合は0から1の乱数
integerの場合は範囲指定なしnumeric_limits<T>::min() -> max()の乱数 */
template <class T>
T getUniform() {
constexpr auto R = Dist_t<T>::DefaultRange;
return getUniform<T>(R);
}
//! 一様分布
/*! 数値として取り得る値の範囲 */
template <class T>
T getUniformNR() {
constexpr auto R = Dist_t<T>::NumericRange;
return getUniform<T>(R);
}
//! 指定範囲の一様分布(in range)
template <class T>
T getUniform(const Range<T>& range) {
return typename Dist_t<T>::uniform_t(range.from, range.to)(_mt);
}
//! 一様分布を返すファンクタを作成
template <class T>
auto getUniformF(const Range<T>& r) noexcept {
return RObj<T>(*this, r);
}
//! 一様分布を返すファンクタを作成
template <class T>
auto getUniformF() noexcept {
constexpr auto R = Dist_t<T>::DefaultRange;
return RObj<T>(*this, R);
}
//! 指定範囲の一様分布(vmax)
template <class T>
T getUniformMax(const T& vmax) {
return getUniform<T>({Lim<T>::lowest(), vmax});
}
//! 指定範囲の一様分布(vmin)
template <class T>
T getUniformMin(const T& vmin) {
return getUniform<T>({vmin, Lim<T>::max()});
}
template <std::size_t NumSeed>
static Random<MT_t> Make() {
std::random_device rnd;
std::array<std::seed_seq::result_type, NumSeed> seed;
std::generate(seed.begin(), seed.end(), std::ref(rnd));
std::seed_seq seq(seed.begin(), seed.end());
return std::move(Random<MT_t>(MT_t{seq}));
}
};
using RandomMT = Random<std::mt19937>;
using RandomMT64 = Random<std::mt19937_64>;
}
<commit_msg>Random: デフォルトの値範囲を1種類に固定<commit_after>#pragma once
#include "meta/enable_if.hpp"
#include "range.hpp"
#include <algorithm>
#include <array>
#include <functional>
namespace frea {
template <class MT>
class Random {
private:
using MT_t = MT;
MT_t _mt;
template <class T>
using Lim = std::numeric_limits<T>;
template <class T>
struct Dist_Int {
using uniform_t = std::uniform_int_distribution<T>;
constexpr static Range<T> NumericRange{Lim<T>::lowest(), Lim<T>::max()};
};
template <class T>
struct Dist_Float {
using uniform_t = std::uniform_real_distribution<T>;
constexpr static Range<T> NumericRange{Lim<T>::lowest()/2, Lim<T>::max()/2};
};
template <class T, ENABLE_IF((std::is_integral<T>{}))>
static Dist_Int<T> DetectDist();
template <class T, ENABLE_IF((std::is_floating_point<T>{}))>
static Dist_Float<T> DetectDist();
template <class T>
using Dist_t = decltype(DetectDist<T>());
public:
template <class T>
class RObj {
private:
Random& _rd;
const Range<T> _range;
public:
RObj(Random& rd, const Range<T>& r):
_rd(rd),
_range(r)
{}
RObj(const RObj&) = default;
//! 実行時範囲指定
auto operator ()(const Range<T>& r) const {
return _rd.template getUniform<T>(r);
}
//! デフォルト範囲指定
auto operator ()() const {
return (*this)(_range);
}
};
public:
Random(MT_t mt) noexcept: _mt(std::move(mt)) {}
Random(const Random&) = delete;
Random(Random&& t) noexcept {
*this = std::move(t);
}
Random& operator = (Random&& t) noexcept {
swap(t);
return *this;
}
void swap(Random& t) noexcept {
std::swap(_mt, t._mt);
}
MT_t& refMt() noexcept {
return _mt;
}
//! 一様分布
/*! 範囲がnumeric_limits<T>::lowest() -> max()の乱数 */
template <class T>
T getUniform() {
constexpr auto R = Dist_t<T>::NumericRange;
return getUniform<T>(R);
}
//! 指定範囲の一様分布(in range)
template <class T>
T getUniform(const Range<T>& range) {
return typename Dist_t<T>::uniform_t(range.from, range.to)(_mt);
}
//! 一様分布を返すファンクタを作成
template <class T>
auto getUniformF(const Range<T>& r) noexcept {
return RObj<T>(*this, r);
}
//! 一様分布を返すファンクタを作成
template <class T>
auto getUniformF() noexcept {
constexpr auto R = Dist_t<T>::NumericRange;
return RObj<T>(*this, R);
}
//! 指定範囲の一様分布(vmax)
template <class T>
T getUniformMax(const T& vmax) {
return getUniform<T>({Lim<T>::lowest(), vmax});
}
//! 指定範囲の一様分布(vmin)
template <class T>
T getUniformMin(const T& vmin) {
return getUniform<T>({vmin, Lim<T>::max()});
}
template <std::size_t NumSeed>
static Random<MT_t> Make() {
std::random_device rnd;
std::array<std::seed_seq::result_type, NumSeed> seed;
std::generate(seed.begin(), seed.end(), std::ref(rnd));
std::seed_seq seq(seed.begin(), seed.end());
return std::move(Random<MT_t>(MT_t{seq}));
}
};
using RandomMT = Random<std::mt19937>;
using RandomMT64 = Random<std::mt19937_64>;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2010, 2011 Esrille 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.
*/
#include "ViewCSSImp.h"
#include <org/w3c/dom/Text.h>
#include <org/w3c/dom/Comment.h>
#include <new>
#include <boost/bind.hpp>
#include "CSSStyleRuleImp.h"
#include "CSSStyleDeclarationImp.h"
#include "CSSStyleSheetImp.h"
#include "DocumentImp.h"
#include "Box.h"
#include "StackingContext.h"
#include "Test.util.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
namespace {
bool isReplacedElement(Element& element)
{
std::u16string tag = element.getLocalName(); // TODO: Check HTML namespace
if (tag == u"img" || tag == u"iframe" || tag == u"video") // TODO: more tags to come...
return true;
return false;
}
}
ViewCSSImp::ViewCSSImp(DocumentWindowPtr window, css::CSSStyleSheet defaultStyleSheet) :
window(window),
defaultStyleSheet(defaultStyleSheet),
stackingContexts(0),
hovered(0),
dpi(96),
mutationListener(boost::bind(&ViewCSSImp::handleMutation, this, _1))
{
setMediumFontSize(16);
getDocument().addEventListener(u"DOMAttrModified", &mutationListener);
}
ViewCSSImp::~ViewCSSImp()
{
getDocument().removeEventListener(u"DOMAttrModified", &mutationListener);
}
Box* ViewCSSImp::boxFromPoint(int x, int y)
{
if (!boxTree)
return 0;
if (Box* target = boxTree.get()->boxFromPoint(x, y))
return target;
return boxTree.get();
}
bool ViewCSSImp::isHovered(Node node)
{
for (Node i = hovered; i; i = i.getParentNode()) {
if (node == i)
return true;
}
return false;
}
void ViewCSSImp::handleMutation(events::Event event)
{
if (boxTree)
boxTree->setFlags(1);
}
void ViewCSSImp::findDeclarations(DeclarationSet& set, Element element, css::CSSRuleList list)
{
if (!list)
return;
unsigned int size = list.getLength();
for (unsigned int i = 0; i < size; ++i) {
css::CSSRule rule = list.getElement(i);
if (CSSStyleRuleImp* imp = dynamic_cast<CSSStyleRuleImp*>(rule.self())) {
CSSSelector* selector = imp->match(element, this);
if (!selector)
continue;
unsigned pseudoElementID = 0;
if (CSSPseudoElementSelector* pseudo = selector->getPseudoElement())
pseudoElementID = pseudo->getID();
PrioritizedDeclaration decl(imp->getLastSpecificity(), dynamic_cast<CSSStyleDeclarationImp*>(imp->getStyle().self()), pseudoElementID);
set.insert(decl);
}
}
}
void ViewCSSImp::render()
{
if (boxTree)
boxTree->render(this);
}
void ViewCSSImp::cascade()
{
map.clear();
delete stackingContexts;
stackingContexts = 0;
cascade(getDocument(), 0);
printComputedValues(getDocument(), this); // for debug
}
void ViewCSSImp::cascade(Node node, CSSStyleDeclarationImp* parentStyle)
{
CSSStyleDeclarationImp* style = 0;
if (node.getNodeType() == Node::ELEMENT_NODE) {
Element element = interface_cast<Element>(node);
style = new(std::nothrow) CSSStyleDeclarationImp;
if (!style) {
map.erase(element);
return; // TODO: error
}
map[element] = style;
DeclarationSet set;
findDeclarations(set, element, defaultStyleSheet.getCssRules());
for (auto i = set.begin(); i != set.end(); ++i) {
if (CSSStyleDeclarationImp* pseudo = style->createPseudoElementStyle((*i).pseudoElementID))
pseudo->specify((*i).decl);
}
set.clear();
stylesheets::StyleSheetList styleSheets = element.getOwnerDocument().getStyleSheets();
for (unsigned i = 0; i < styleSheets.getLength(); ++i) {
stylesheets::StyleSheet sheet = styleSheets.getElement(i);
if (CSSStyleSheetImp* imp = dynamic_cast<CSSStyleSheetImp*>(sheet.self()))
findDeclarations(set, element, imp->getCssRules());
}
for (auto i = set.begin(); i != set.end(); ++i) {
if (CSSStyleDeclarationImp* pseudo = style->createPseudoElementStyle((*i).pseudoElementID))
pseudo->specify((*i).decl);
}
for (auto i = set.begin(); i != set.end(); ++i) {
if (CSSStyleDeclarationImp* pseudo = style->createPseudoElementStyle((*i).pseudoElementID))
pseudo->specifyImportant((*i).decl);
}
set.clear();
// TODO: process user normal declarations and user important declarations
if (html::HTMLElement htmlElement = interface_cast<html::HTMLElement>(element)) { // TODO: type check
if (css::CSSStyleDeclaration decl = htmlElement.getStyle())
style->specify(static_cast<CSSStyleDeclarationImp*>(decl.self()));
}
style->compute(this, parentStyle, element);
}
for (Node child = node.getFirstChild(); child; child = child.getNextSibling())
cascade(child, style);
}
// In this step, neither inline-level boxes nor line boxes are generated.
// Those will be generated later by layOut().
BlockLevelBox* ViewCSSImp::layOutBlockBoxes(Node node, BlockLevelBox* parentBox, BlockLevelBox* siblingBox, CSSStyleDeclarationImp* style)
{
BlockLevelBox* newBox = 0;
switch (node.getNodeType()) {
case Node::TEXT_NODE:
newBox = layOutBlockBoxes(interface_cast<Text>(node), parentBox, siblingBox, style);
break;
case Node::ELEMENT_NODE:
newBox = layOutBlockBoxes(interface_cast<Element>(node), parentBox, siblingBox, style);
break;
case Node::DOCUMENT_NODE:
// Iterate over from back to front to process run-in boxes
for (Node child = node.getLastChild(); child; child = child.getPreviousSibling()) {
if (BlockLevelBox* box = layOutBlockBoxes(child, parentBox, newBox, style))
newBox = box;
}
break;
default:
break;
}
return newBox;
}
BlockLevelBox* ViewCSSImp::layOutBlockBoxes(Text text, BlockLevelBox* parentBox, BlockLevelBox* siblingBox, CSSStyleDeclarationImp* style)
{
if (!parentBox || !style)
return 0;
if (!parentBox->hasChildBoxes()) {
parentBox->insertInline(text);
return 0;
}
if (!parentBox->hasAnonymousBox()) {
// cf. http://www.w3.org/TR/CSS2/visuren.html#anonymous
// White space content that would subsequently be collapsed
// away according to the 'white-space' property does not
// generate any anonymous inline boxes.
std::u16string data;
bool whiteSpace = true;
switch (style->whiteSpace.getValue()) {
case CSSWhiteSpaceValueImp::Normal:
case CSSWhiteSpaceValueImp::Nowrap:
case CSSWhiteSpaceValueImp::PreLine:
data = text.getData(); // TODO: make this faster
for (auto i = data.begin(); i != data.end(); ++i) {
if (!isSpace(*i)) {
whiteSpace = false;
break;
}
}
if (whiteSpace)
return 0;
break;
}
}
if (BlockLevelBox* anonymousBox = parentBox->getAnonymousBox()) {
anonymousBox->insertInline(text);
return anonymousBox;
}
return 0;
}
BlockLevelBox* ViewCSSImp::layOutBlockBoxes(Element element, BlockLevelBox* parentBox, BlockLevelBox* siblingBox, CSSStyleDeclarationImp* style, bool asBlock)
{
style = map[element].get();
if (!style || style->display.isNone())
return 0;
bool runIn = style->display.isRunIn();
BlockLevelBox* currentBox = parentBox;
BlockLevelBox* childBox = 0;
if (style->isFloat() || style->isAbsolutelyPositioned()) {
currentBox = new(std::nothrow) BlockLevelBox(element, style);
if (!currentBox)
return 0; // TODO: error
if (!currentBox->establishFormattingContext())
return 0; // TODO: error
style->addBox(currentBox);
// Do not insert currentBox into parentBox
} else if (style->isBlockLevel() || runIn || asBlock) {
// Create a temporary block-level box for the run-in box, too.
if (parentBox && parentBox->hasInline()) {
if (!parentBox->getAnonymousBox())
return 0;
assert(!parentBox->hasInline());
}
currentBox = new(std::nothrow) BlockLevelBox(element, style);
if (!currentBox)
return 0;
style->addBox(currentBox);
if (parentBox) {
if (Box* first = parentBox->getFirstChild())
parentBox->insertBefore(currentBox, first);
else
parentBox->appendChild(currentBox);
} else
runIn = false;
// Establish a new formatting context?
if (!parentBox || style->isFlowRoot()) {
if (!currentBox->establishFormattingContext())
return 0; // TODO error
}
} else if (style->isInlineBlock() || isReplacedElement(element)) {
assert(currentBox);
if (!currentBox->hasChildBoxes())
currentBox->insertInline(element);
else if (BlockLevelBox* anonymousBox = currentBox->getAnonymousBox()) {
anonymousBox->insertInline(element);
return anonymousBox;
}
return currentBox;
}
if (CSSStyleDeclarationImp* afterStyle = style->getPseudoElementStyle(CSSPseudoElementSelector::After)) {
afterStyle->compute(this, style, element);
if (Element after = afterStyle->content.eval(getDocument(), element)) {
map[after] = afterStyle;
if (BlockLevelBox* box = layOutBlockBoxes(after, currentBox, childBox, style))
childBox = box;
}
}
// Iterate over from back to front to process run-in boxes
for (Node child = element.getLastChild(); child; child = child.getPreviousSibling()) {
if (BlockLevelBox* box = layOutBlockBoxes(child, currentBox, childBox, style))
childBox = box;
}
if (runIn && !currentBox->hasChildBoxes() && siblingBox) {
assert(siblingBox->getBoxType() == Box::BLOCK_LEVEL_BOX);
siblingBox->spliceInline(currentBox);
parentBox->removeChild(currentBox);
delete currentBox;
currentBox = 0;
}
if (CSSStyleDeclarationImp* beforeStyle = style->getPseudoElementStyle(CSSPseudoElementSelector::Before)) {
beforeStyle->compute(this, style, element);
if (Element before = beforeStyle->content.eval(getDocument(), element)) {
map[before] = beforeStyle;
if (BlockLevelBox* box = layOutBlockBoxes(before, currentBox, childBox, style))
childBox = box;
}
}
if (!currentBox)
currentBox = childBox;
else if (currentBox == parentBox)
currentBox = 0;
else if (currentBox->isFloat() || currentBox->isAbsolutelyPositioned()) {
floatMap[element] = currentBox;
if (parentBox) {
if (!parentBox->hasChildBoxes())
parentBox->insertInline(element);
else if (BlockLevelBox* anonymousBox = parentBox->getAnonymousBox()) {
anonymousBox->insertInline(element);
return anonymousBox;
}
}
}
return currentBox;
}
// Lay out a tree box block-level boxes
BlockLevelBox* ViewCSSImp::layOutBlockBoxes()
{
floatMap.clear();
boxTree = layOutBlockBoxes(getDocument(), 0, 0, 0);
return boxTree.get();
}
BlockLevelBox* ViewCSSImp::layOut()
{
layOutBlockBoxes();
if (!boxTree)
return 0;
// Expand line boxes and inline-level boxes in each block-level box
boxTree->layOut(this, 0);
// Lay out absolute boxes.
// Since absolute boxes could be created by layOutAbsolute() itself,
// we cannot simply iterate over floatMap.
// TODO: refine the code
std::map<Node, BlockLevelBoxPtr> tmp;
while (!floatMap.empty()) {
auto i = floatMap.begin();
BlockLevelBoxPtr box = i->second;
if (box->isAbsolutelyPositioned())
box->layOutAbsolute(this, i->first);
tmp.insert(*i);
floatMap.erase(i);
}
floatMap.swap(tmp);
if (stackingContexts) {
stackingContexts->eval();
stackingContexts->dump();
}
return boxTree.get();
}
BlockLevelBox* ViewCSSImp::dump()
{
boxTree->dump(this);
return boxTree.get();
}
CSSStyleDeclarationImp* ViewCSSImp::getStyle(Element elt, Nullable<std::u16string> pseudoElt)
{
auto i = map.find(elt);
if (i == map.end())
return 0;
CSSStyleDeclarationImp* style = i->second.get();
if (!pseudoElt.hasValue() || pseudoElt.value().length() == 0)
return style;
return style->getPseudoElementStyle(pseudoElt.value());
}
// ViewCSS
css::CSSStyleDeclaration ViewCSSImp::getComputedStyle(Element elt, Nullable<std::u16string> pseudoElt) {
return getStyle(elt, pseudoElt);
}
}}}} // org::w3c::dom::bootstrap
<commit_msg>(ViewCSSImp::layOutBlockBoxes) : Fix to process the run-in box after placing the pseudo-elements.<commit_after>/*
* Copyright 2010, 2011 Esrille 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.
*/
#include "ViewCSSImp.h"
#include <org/w3c/dom/Text.h>
#include <org/w3c/dom/Comment.h>
#include <new>
#include <boost/bind.hpp>
#include "CSSStyleRuleImp.h"
#include "CSSStyleDeclarationImp.h"
#include "CSSStyleSheetImp.h"
#include "DocumentImp.h"
#include "Box.h"
#include "StackingContext.h"
#include "Test.util.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
namespace {
bool isReplacedElement(Element& element)
{
std::u16string tag = element.getLocalName(); // TODO: Check HTML namespace
if (tag == u"img" || tag == u"iframe" || tag == u"video") // TODO: more tags to come...
return true;
return false;
}
}
ViewCSSImp::ViewCSSImp(DocumentWindowPtr window, css::CSSStyleSheet defaultStyleSheet) :
window(window),
defaultStyleSheet(defaultStyleSheet),
stackingContexts(0),
hovered(0),
dpi(96),
mutationListener(boost::bind(&ViewCSSImp::handleMutation, this, _1))
{
setMediumFontSize(16);
getDocument().addEventListener(u"DOMAttrModified", &mutationListener);
}
ViewCSSImp::~ViewCSSImp()
{
getDocument().removeEventListener(u"DOMAttrModified", &mutationListener);
}
Box* ViewCSSImp::boxFromPoint(int x, int y)
{
if (!boxTree)
return 0;
if (Box* target = boxTree.get()->boxFromPoint(x, y))
return target;
return boxTree.get();
}
bool ViewCSSImp::isHovered(Node node)
{
for (Node i = hovered; i; i = i.getParentNode()) {
if (node == i)
return true;
}
return false;
}
void ViewCSSImp::handleMutation(events::Event event)
{
if (boxTree)
boxTree->setFlags(1);
}
void ViewCSSImp::findDeclarations(DeclarationSet& set, Element element, css::CSSRuleList list)
{
if (!list)
return;
unsigned int size = list.getLength();
for (unsigned int i = 0; i < size; ++i) {
css::CSSRule rule = list.getElement(i);
if (CSSStyleRuleImp* imp = dynamic_cast<CSSStyleRuleImp*>(rule.self())) {
CSSSelector* selector = imp->match(element, this);
if (!selector)
continue;
unsigned pseudoElementID = 0;
if (CSSPseudoElementSelector* pseudo = selector->getPseudoElement())
pseudoElementID = pseudo->getID();
PrioritizedDeclaration decl(imp->getLastSpecificity(), dynamic_cast<CSSStyleDeclarationImp*>(imp->getStyle().self()), pseudoElementID);
set.insert(decl);
}
}
}
void ViewCSSImp::render()
{
if (boxTree)
boxTree->render(this);
}
void ViewCSSImp::cascade()
{
map.clear();
delete stackingContexts;
stackingContexts = 0;
cascade(getDocument(), 0);
printComputedValues(getDocument(), this); // for debug
}
void ViewCSSImp::cascade(Node node, CSSStyleDeclarationImp* parentStyle)
{
CSSStyleDeclarationImp* style = 0;
if (node.getNodeType() == Node::ELEMENT_NODE) {
Element element = interface_cast<Element>(node);
style = new(std::nothrow) CSSStyleDeclarationImp;
if (!style) {
map.erase(element);
return; // TODO: error
}
map[element] = style;
DeclarationSet set;
findDeclarations(set, element, defaultStyleSheet.getCssRules());
for (auto i = set.begin(); i != set.end(); ++i) {
if (CSSStyleDeclarationImp* pseudo = style->createPseudoElementStyle((*i).pseudoElementID))
pseudo->specify((*i).decl);
}
set.clear();
stylesheets::StyleSheetList styleSheets = element.getOwnerDocument().getStyleSheets();
for (unsigned i = 0; i < styleSheets.getLength(); ++i) {
stylesheets::StyleSheet sheet = styleSheets.getElement(i);
if (CSSStyleSheetImp* imp = dynamic_cast<CSSStyleSheetImp*>(sheet.self()))
findDeclarations(set, element, imp->getCssRules());
}
for (auto i = set.begin(); i != set.end(); ++i) {
if (CSSStyleDeclarationImp* pseudo = style->createPseudoElementStyle((*i).pseudoElementID))
pseudo->specify((*i).decl);
}
for (auto i = set.begin(); i != set.end(); ++i) {
if (CSSStyleDeclarationImp* pseudo = style->createPseudoElementStyle((*i).pseudoElementID))
pseudo->specifyImportant((*i).decl);
}
set.clear();
// TODO: process user normal declarations and user important declarations
if (html::HTMLElement htmlElement = interface_cast<html::HTMLElement>(element)) { // TODO: type check
if (css::CSSStyleDeclaration decl = htmlElement.getStyle())
style->specify(static_cast<CSSStyleDeclarationImp*>(decl.self()));
}
style->compute(this, parentStyle, element);
}
for (Node child = node.getFirstChild(); child; child = child.getNextSibling())
cascade(child, style);
}
// In this step, neither inline-level boxes nor line boxes are generated.
// Those will be generated later by layOut().
BlockLevelBox* ViewCSSImp::layOutBlockBoxes(Node node, BlockLevelBox* parentBox, BlockLevelBox* siblingBox, CSSStyleDeclarationImp* style)
{
BlockLevelBox* newBox = 0;
switch (node.getNodeType()) {
case Node::TEXT_NODE:
newBox = layOutBlockBoxes(interface_cast<Text>(node), parentBox, siblingBox, style);
break;
case Node::ELEMENT_NODE:
newBox = layOutBlockBoxes(interface_cast<Element>(node), parentBox, siblingBox, style);
break;
case Node::DOCUMENT_NODE:
// Iterate over from back to front to process run-in boxes
for (Node child = node.getLastChild(); child; child = child.getPreviousSibling()) {
if (BlockLevelBox* box = layOutBlockBoxes(child, parentBox, newBox, style))
newBox = box;
}
break;
default:
break;
}
return newBox;
}
BlockLevelBox* ViewCSSImp::layOutBlockBoxes(Text text, BlockLevelBox* parentBox, BlockLevelBox* siblingBox, CSSStyleDeclarationImp* style)
{
if (!parentBox || !style)
return 0;
if (!parentBox->hasChildBoxes()) {
parentBox->insertInline(text);
return 0;
}
if (!parentBox->hasAnonymousBox()) {
// cf. http://www.w3.org/TR/CSS2/visuren.html#anonymous
// White space content that would subsequently be collapsed
// away according to the 'white-space' property does not
// generate any anonymous inline boxes.
std::u16string data;
bool whiteSpace = true;
switch (style->whiteSpace.getValue()) {
case CSSWhiteSpaceValueImp::Normal:
case CSSWhiteSpaceValueImp::Nowrap:
case CSSWhiteSpaceValueImp::PreLine:
data = text.getData(); // TODO: make this faster
for (auto i = data.begin(); i != data.end(); ++i) {
if (!isSpace(*i)) {
whiteSpace = false;
break;
}
}
if (whiteSpace)
return 0;
break;
}
}
if (BlockLevelBox* anonymousBox = parentBox->getAnonymousBox()) {
anonymousBox->insertInline(text);
return anonymousBox;
}
return 0;
}
BlockLevelBox* ViewCSSImp::layOutBlockBoxes(Element element, BlockLevelBox* parentBox, BlockLevelBox* siblingBox, CSSStyleDeclarationImp* style, bool asBlock)
{
style = map[element].get();
if (!style || style->display.isNone())
return 0;
bool runIn = style->display.isRunIn();
BlockLevelBox* currentBox = parentBox;
BlockLevelBox* childBox = 0;
if (style->isFloat() || style->isAbsolutelyPositioned()) {
currentBox = new(std::nothrow) BlockLevelBox(element, style);
if (!currentBox)
return 0; // TODO: error
if (!currentBox->establishFormattingContext())
return 0; // TODO: error
style->addBox(currentBox);
// Do not insert currentBox into parentBox
} else if (style->isBlockLevel() || runIn || asBlock) {
// Create a temporary block-level box for the run-in box, too.
if (parentBox && parentBox->hasInline()) {
if (!parentBox->getAnonymousBox())
return 0;
assert(!parentBox->hasInline());
}
currentBox = new(std::nothrow) BlockLevelBox(element, style);
if (!currentBox)
return 0;
style->addBox(currentBox);
if (parentBox) {
if (Box* first = parentBox->getFirstChild())
parentBox->insertBefore(currentBox, first);
else
parentBox->appendChild(currentBox);
} else
runIn = false;
// Establish a new formatting context?
if (!parentBox || style->isFlowRoot()) {
if (!currentBox->establishFormattingContext())
return 0; // TODO error
}
} else if (style->isInlineBlock() || isReplacedElement(element)) {
assert(currentBox);
if (!currentBox->hasChildBoxes())
currentBox->insertInline(element);
else if (BlockLevelBox* anonymousBox = currentBox->getAnonymousBox()) {
anonymousBox->insertInline(element);
return anonymousBox;
}
return currentBox;
}
if (CSSStyleDeclarationImp* afterStyle = style->getPseudoElementStyle(CSSPseudoElementSelector::After)) {
afterStyle->compute(this, style, element);
if (Element after = afterStyle->content.eval(getDocument(), element)) {
map[after] = afterStyle;
if (BlockLevelBox* box = layOutBlockBoxes(after, currentBox, childBox, style))
childBox = box;
}
}
// Iterate over from back to front to process run-in boxes
for (Node child = element.getLastChild(); child; child = child.getPreviousSibling()) {
if (BlockLevelBox* box = layOutBlockBoxes(child, currentBox, childBox, style))
childBox = box;
}
if (CSSStyleDeclarationImp* beforeStyle = style->getPseudoElementStyle(CSSPseudoElementSelector::Before)) {
beforeStyle->compute(this, style, element);
if (Element before = beforeStyle->content.eval(getDocument(), element)) {
map[before] = beforeStyle;
if (BlockLevelBox* box = layOutBlockBoxes(before, currentBox, childBox, style))
childBox = box;
}
}
// cf. http://www.w3.org/TR/2010/WD-CSS2-20101207/generate.html#before-after-content
if (runIn && !currentBox->hasChildBoxes() && siblingBox) {
assert(siblingBox->getBoxType() == Box::BLOCK_LEVEL_BOX);
siblingBox->spliceInline(currentBox);
parentBox->removeChild(currentBox);
delete currentBox;
currentBox = 0;
}
if (!currentBox)
currentBox = childBox;
else if (currentBox == parentBox)
currentBox = 0;
else if (currentBox->isFloat() || currentBox->isAbsolutelyPositioned()) {
floatMap[element] = currentBox;
if (parentBox) {
if (!parentBox->hasChildBoxes())
parentBox->insertInline(element);
else if (BlockLevelBox* anonymousBox = parentBox->getAnonymousBox()) {
anonymousBox->insertInline(element);
return anonymousBox;
}
}
}
return currentBox;
}
// Lay out a tree box block-level boxes
BlockLevelBox* ViewCSSImp::layOutBlockBoxes()
{
floatMap.clear();
boxTree = layOutBlockBoxes(getDocument(), 0, 0, 0);
return boxTree.get();
}
BlockLevelBox* ViewCSSImp::layOut()
{
layOutBlockBoxes();
if (!boxTree)
return 0;
// Expand line boxes and inline-level boxes in each block-level box
boxTree->layOut(this, 0);
// Lay out absolute boxes.
// Since absolute boxes could be created by layOutAbsolute() itself,
// we cannot simply iterate over floatMap.
// TODO: refine the code
std::map<Node, BlockLevelBoxPtr> tmp;
while (!floatMap.empty()) {
auto i = floatMap.begin();
BlockLevelBoxPtr box = i->second;
if (box->isAbsolutelyPositioned())
box->layOutAbsolute(this, i->first);
tmp.insert(*i);
floatMap.erase(i);
}
floatMap.swap(tmp);
if (stackingContexts) {
stackingContexts->eval();
stackingContexts->dump();
}
return boxTree.get();
}
BlockLevelBox* ViewCSSImp::dump()
{
boxTree->dump(this);
return boxTree.get();
}
CSSStyleDeclarationImp* ViewCSSImp::getStyle(Element elt, Nullable<std::u16string> pseudoElt)
{
auto i = map.find(elt);
if (i == map.end())
return 0;
CSSStyleDeclarationImp* style = i->second.get();
if (!pseudoElt.hasValue() || pseudoElt.value().length() == 0)
return style;
return style->getPseudoElementStyle(pseudoElt.value());
}
// ViewCSS
css::CSSStyleDeclaration ViewCSSImp::getComputedStyle(Element elt, Nullable<std::u16string> pseudoElt) {
return getStyle(elt, pseudoElt);
}
}}}} // org::w3c::dom::bootstrap
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <ocidl.h>
#include <commdlg.h>
#include <string>
#include "base/scoped_ptr.h"
#include "printing/printing_test.h"
#include "printing/printing_context.h"
#include "printing/printing_context_win.h"
#include "printing/print_settings.h"
#include "testing/gtest/include/gtest/gtest.h"
// This test is automatically disabled if no printer is available.
class PrintingContextTest : public PrintingTest<testing::Test> {
public:
void PrintSettingsCallback(printing::PrintingContext::Result result) {
result_ = result;
}
protected:
printing::PrintingContext::Result result() const { return result_; }
private:
printing::PrintingContext::Result result_;
};
// This is a fake PrintDlgEx implementation that sets the right fields in
// |lppd| to trigger a bug in older revisions of PrintingContext.
HRESULT WINAPI PrintDlgExMock(LPPRINTDLGEX lppd) {
// The interesting bits:
// Pretend the user hit print
lppd->dwResultAction = PD_RESULT_PRINT;
// Pretend the page range is 1-5, but since lppd->Flags does not have
// PD_SELECTION set, this really shouldn't matter.
lppd->nPageRanges = 1;
lppd->lpPageRanges = new PRINTPAGERANGE[1];
lppd->lpPageRanges[0].nFromPage = 1;
lppd->lpPageRanges[0].nToPage = 5;
// Painful paperwork.
std::wstring printer_name = PrintingContextTest::GetDefaultPrinter();
HANDLE printer;
if (!OpenPrinter(const_cast<wchar_t*>(printer_name.c_str()), &printer, NULL))
return E_FAIL;
scoped_array<uint8> buffer;
DEVMODE* dev_mode = NULL;
PRINTER_INFO_2* info_2 = NULL;
printing::PrintingContextWin::GetPrinterHelper(printer, 2, &buffer);
if (buffer.get()) {
info_2 = reinterpret_cast<PRINTER_INFO_2*>(buffer.get());
if (info_2->pDevMode != NULL)
dev_mode = info_2->pDevMode;
}
if (!dev_mode)
return E_FAIL;
if (!printing::PrintingContextWin::AllocateContext(printer_name, dev_mode,
&lppd->hDC)) {
return E_FAIL;
}
size_t dev_mode_size = dev_mode->dmSize + dev_mode->dmDriverExtra;
lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, dev_mode_size);
if (!lppd->hDevMode)
return E_FAIL;
void* dev_mode_ptr = GlobalLock(lppd->hDevMode);
if (!dev_mode_ptr)
return E_FAIL;
memcpy(dev_mode_ptr, dev_mode, dev_mode_size);
GlobalUnlock(lppd->hDevMode);
size_t driver_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pDriverName);
size_t printer_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPrinterName);
size_t port_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPortName);
size_t dev_names_size = sizeof(DEVNAMES) + driver_size + printer_size +
port_size;
lppd->hDevNames = GlobalAlloc(GHND, dev_names_size);
if (!lppd->hDevNames)
return E_FAIL;
void* dev_names_ptr = GlobalLock(lppd->hDevNames);
if (!dev_names_ptr)
return E_FAIL;
DEVNAMES* dev_names = reinterpret_cast<DEVNAMES*>(dev_names_ptr);
dev_names->wDefault = 1;
dev_names->wDriverOffset = sizeof(DEVNAMES);
memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDriverOffset,
info_2->pDriverName, driver_size);
dev_names->wDeviceOffset = dev_names->wDriverOffset + driver_size;
memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDeviceOffset,
info_2->pPrinterName, printer_size);
dev_names->wOutputOffset = dev_names->wDeviceOffset + printer_size;
memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wOutputOffset,
info_2->pPortName, port_size);
GlobalUnlock(lppd->hDevNames);
return S_OK;
}
TEST_F(PrintingContextTest, Base) {
printing::PrintSettings settings;
settings.set_device_name(GetDefaultPrinter());
// Initialize it.
scoped_ptr<printing::PrintingContext> context(
printing::PrintingContext::Create());
EXPECT_EQ(printing::PrintingContext::OK, context->InitWithSettings(settings));
// The print may lie to use and may not support world transformation.
// Verify right now.
XFORM random_matrix = { 1, 0.1f, 0, 1.5f, 0, 1 };
EXPECT_TRUE(SetWorldTransform(context->context(), &random_matrix));
EXPECT_TRUE(ModifyWorldTransform(context->context(), NULL, MWT_IDENTITY));
}
// http://crbug.com/61499
TEST_F(PrintingContextTest, FLAKY_PrintAll) {
printing::PrintingContextWin context;
context.SetPrintDialog(&PrintDlgExMock);
context.AskUserForSettings(
NULL,
123,
false,
NewCallback(static_cast<PrintingContextTest*>(this),
&PrintingContextTest::PrintSettingsCallback));
ASSERT_EQ(printing::PrintingContext::OK, result());
printing::PrintSettings settings = context.settings();
EXPECT_EQ(settings.ranges.size(), 0);
}
<commit_msg>Disable PrintingContextTest.Base on win<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <ocidl.h>
#include <commdlg.h>
#include <string>
#include "base/scoped_ptr.h"
#include "printing/printing_test.h"
#include "printing/printing_context.h"
#include "printing/printing_context_win.h"
#include "printing/print_settings.h"
#include "testing/gtest/include/gtest/gtest.h"
// This test is automatically disabled if no printer is available.
class PrintingContextTest : public PrintingTest<testing::Test> {
public:
void PrintSettingsCallback(printing::PrintingContext::Result result) {
result_ = result;
}
protected:
printing::PrintingContext::Result result() const { return result_; }
private:
printing::PrintingContext::Result result_;
};
// This is a fake PrintDlgEx implementation that sets the right fields in
// |lppd| to trigger a bug in older revisions of PrintingContext.
HRESULT WINAPI PrintDlgExMock(LPPRINTDLGEX lppd) {
// The interesting bits:
// Pretend the user hit print
lppd->dwResultAction = PD_RESULT_PRINT;
// Pretend the page range is 1-5, but since lppd->Flags does not have
// PD_SELECTION set, this really shouldn't matter.
lppd->nPageRanges = 1;
lppd->lpPageRanges = new PRINTPAGERANGE[1];
lppd->lpPageRanges[0].nFromPage = 1;
lppd->lpPageRanges[0].nToPage = 5;
// Painful paperwork.
std::wstring printer_name = PrintingContextTest::GetDefaultPrinter();
HANDLE printer;
if (!OpenPrinter(const_cast<wchar_t*>(printer_name.c_str()), &printer, NULL))
return E_FAIL;
scoped_array<uint8> buffer;
DEVMODE* dev_mode = NULL;
PRINTER_INFO_2* info_2 = NULL;
printing::PrintingContextWin::GetPrinterHelper(printer, 2, &buffer);
if (buffer.get()) {
info_2 = reinterpret_cast<PRINTER_INFO_2*>(buffer.get());
if (info_2->pDevMode != NULL)
dev_mode = info_2->pDevMode;
}
if (!dev_mode)
return E_FAIL;
if (!printing::PrintingContextWin::AllocateContext(printer_name, dev_mode,
&lppd->hDC)) {
return E_FAIL;
}
size_t dev_mode_size = dev_mode->dmSize + dev_mode->dmDriverExtra;
lppd->hDevMode = GlobalAlloc(GMEM_MOVEABLE, dev_mode_size);
if (!lppd->hDevMode)
return E_FAIL;
void* dev_mode_ptr = GlobalLock(lppd->hDevMode);
if (!dev_mode_ptr)
return E_FAIL;
memcpy(dev_mode_ptr, dev_mode, dev_mode_size);
GlobalUnlock(lppd->hDevMode);
size_t driver_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pDriverName);
size_t printer_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPrinterName);
size_t port_size = 2 + sizeof(wchar_t) * lstrlen(info_2->pPortName);
size_t dev_names_size = sizeof(DEVNAMES) + driver_size + printer_size +
port_size;
lppd->hDevNames = GlobalAlloc(GHND, dev_names_size);
if (!lppd->hDevNames)
return E_FAIL;
void* dev_names_ptr = GlobalLock(lppd->hDevNames);
if (!dev_names_ptr)
return E_FAIL;
DEVNAMES* dev_names = reinterpret_cast<DEVNAMES*>(dev_names_ptr);
dev_names->wDefault = 1;
dev_names->wDriverOffset = sizeof(DEVNAMES);
memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDriverOffset,
info_2->pDriverName, driver_size);
dev_names->wDeviceOffset = dev_names->wDriverOffset + driver_size;
memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wDeviceOffset,
info_2->pPrinterName, printer_size);
dev_names->wOutputOffset = dev_names->wDeviceOffset + printer_size;
memcpy(reinterpret_cast<uint8*>(dev_names_ptr) + dev_names->wOutputOffset,
info_2->pPortName, port_size);
GlobalUnlock(lppd->hDevNames);
return S_OK;
}
// crbug.com/61509
TEST_F(PrintingContextTest, FLAKY_Base) {
printing::PrintSettings settings;
settings.set_device_name(GetDefaultPrinter());
// Initialize it.
scoped_ptr<printing::PrintingContext> context(
printing::PrintingContext::Create());
EXPECT_EQ(printing::PrintingContext::OK, context->InitWithSettings(settings));
// The print may lie to use and may not support world transformation.
// Verify right now.
XFORM random_matrix = { 1, 0.1f, 0, 1.5f, 0, 1 };
EXPECT_TRUE(SetWorldTransform(context->context(), &random_matrix));
EXPECT_TRUE(ModifyWorldTransform(context->context(), NULL, MWT_IDENTITY));
}
// http://crbug.com/61499
TEST_F(PrintingContextTest, FLAKY_PrintAll) {
printing::PrintingContextWin context;
context.SetPrintDialog(&PrintDlgExMock);
context.AskUserForSettings(
NULL,
123,
false,
NewCallback(static_cast<PrintingContextTest*>(this),
&PrintingContextTest::PrintSettingsCallback));
ASSERT_EQ(printing::PrintingContext::OK, result());
printing::PrintSettings settings = context.settings();
EXPECT_EQ(settings.ranges.size(), 0);
}
<|endoftext|> |
<commit_before>// Copyright 2010 Google
// 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 <algorithm>
#include <vector>
#include "base/callback.h"
#include "base/util.h"
#include "graph/graph.h"
namespace operations_research {
namespace {
// TODO(user) : rewrite this algorithm without the recursivity.
void Search(ResultCallback2<bool, int, int>* const graph,
ResultCallback1<bool, const vector<int>&>* const callback,
int* input_candidates,
int input_size,
int input_candidate_size,
vector<int>* actual,
bool* stop) {
vector<int> actual_candidates(input_candidate_size);
int pre_increment = 0;
int pivot = 0;
int actual_candidate_size;
int actual_size;
int start = 0;
int index = input_candidate_size;
// Find Pivot.
for (int i = 0; i < input_candidate_size && index != 0; ++i) {
int p = input_candidates[i];
int count = 0;
int position = 0;
// Count disconnections.
for (int j = input_size; j < input_candidate_size && count < index; ++j) {
if (!graph->Run(p, input_candidates[j])) {
count++;
// Save position of potential candidate.
position = j;
}
}
// Test new minimum.
if (count < index) {
pivot = p;
index = count;
if (i < input_size) {
start = position;
} else {
start = i;
// pre increment obvious candidate.
pre_increment = 1;
}
}
}
// If fixed point initially chosen from candidates then
// number of diconnections will be preincreased by one
// Backtracking step for all nodes in the candidate list CD.
for (int nod = index + pre_increment; nod >= 1; nod--) {
// Swap.
int selected = input_candidates[start];
input_candidates[start] = input_candidates[input_size];
input_candidates[input_size] = selected;
// Fill new set "not".
actual_candidate_size = 0;
for (int i = 0; i < input_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_candidate_size++] = input_candidates[i];
}
}
// Fill new set "candidates".
actual_size = actual_candidate_size;
for (int i = input_size + 1; i < input_candidate_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_size++] = input_candidates[i];
}
}
// Add to "actual relevant nodes".
actual->push_back(selected);
// We have found a maximum clique.
if (actual_size == 0) {
*stop = callback->Run(*actual);
} else {
if (actual_candidate_size < actual_size) {
Search(graph, callback, actual_candidates.data(),
actual_candidate_size, actual_size, actual, stop);
if (*stop) {
return;
}
}
}
// move node from MD to ND
// Remove from compsub
actual->pop_back();
// Add to "nod"
input_size++;
if (nod > 1) {
// Select a candidate disgraph to the fixed point
start = input_size;
while (graph->Run(pivot, input_candidates[start])) {
start++;
}
}
// end selection
}
}
#if defined(_MSC_VER)
// The following class defines a hash function for arcs
class IntPairHasher : public stdext::hash_compare <Arc> {
public:
size_t operator() (const pair<int, int>& a) const {
uint64 x = a.first;
uint64 y = GG_ULONGLONG(0xe08c1d668b756f82);
uint64 z = a.second;
mix(x, y, z);
return z;
}
bool operator() (const pair<int, int>& a1, const pair<int, int>& a2) const {
return a1.first < a2.first ||
(a1.first == a2.first && a1.second < a2.second);
}
};
#endif
class FindAndEliminate {
public:
FindAndEliminate(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback)
: graph_(graph), node_count_(node_count), callback_(callback) {}
bool GraphCallback(int node1, int node2) {
if (visited_.find(make_pair(std::min(node1, node2),
std::max(node1, node2))) != visited_.end()) {
return false;
}
return graph_->Run(node1, node2);
}
bool SolutionCallback(const vector<int>& solution) {
const int size = solution.size();
if (size > 1) {
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
visited_.insert(make_pair(std::min(solution[i], solution[j]),
std::max(solution[i], solution[j])));
}
}
callback_->Run(solution);
}
return false;
}
private:
ResultCallback2<bool, int, int>* const graph_;
int node_count_;
ResultCallback1<bool, const vector<int>&>* const callback_;
#if defined(_MSC_VER)
hash_set<pair<int, int>, IntPairHasher> visited_;
#else
hash_set<pair<int, int> > visited_;
#endif
};
} // namespace
// This method implements the 'version2' of the Bron-Kerbosch
// algorithm to find all maximal cliques in a undirected graph.
void FindCliques(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(graph, callback, initial_candidates.get(), 0, node_count, &actual,
&stop);
}
void CoverArcsByCliques(
ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
FindAndEliminate cache(graph, node_count, callback);
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > cached_graph(
NewPermanentCallback(&cache, &FindAndEliminate::GraphCallback));
scoped_ptr<ResultCallback1<bool, const vector<int>&> >cached_callback(
NewPermanentCallback(&cache, &FindAndEliminate::SolutionCallback));
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(cached_graph.get(), cached_callback.get(),
initial_candidates.get(), 0,
node_count, &actual, &stop);
}
} // namespace operations_research
<commit_msg>fix visual studio compilation<commit_after>// Copyright 2010 Google
// 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 <algorithm>
#include <vector>
#include "base/callback.h"
#include "base/util.h"
#include "graph/graph.h"
namespace operations_research {
namespace {
// TODO(user) : rewrite this algorithm without the recursivity.
void Search(ResultCallback2<bool, int, int>* const graph,
ResultCallback1<bool, const vector<int>&>* const callback,
int* input_candidates,
int input_size,
int input_candidate_size,
vector<int>* actual,
bool* stop) {
vector<int> actual_candidates(input_candidate_size);
int pre_increment = 0;
int pivot = 0;
int actual_candidate_size;
int actual_size;
int start = 0;
int index = input_candidate_size;
// Find Pivot.
for (int i = 0; i < input_candidate_size && index != 0; ++i) {
int p = input_candidates[i];
int count = 0;
int position = 0;
// Count disconnections.
for (int j = input_size; j < input_candidate_size && count < index; ++j) {
if (!graph->Run(p, input_candidates[j])) {
count++;
// Save position of potential candidate.
position = j;
}
}
// Test new minimum.
if (count < index) {
pivot = p;
index = count;
if (i < input_size) {
start = position;
} else {
start = i;
// pre increment obvious candidate.
pre_increment = 1;
}
}
}
// If fixed point initially chosen from candidates then
// number of diconnections will be preincreased by one
// Backtracking step for all nodes in the candidate list CD.
for (int nod = index + pre_increment; nod >= 1; nod--) {
// Swap.
int selected = input_candidates[start];
input_candidates[start] = input_candidates[input_size];
input_candidates[input_size] = selected;
// Fill new set "not".
actual_candidate_size = 0;
for (int i = 0; i < input_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_candidate_size++] = input_candidates[i];
}
}
// Fill new set "candidates".
actual_size = actual_candidate_size;
for (int i = input_size + 1; i < input_candidate_size; ++i) {
if (graph->Run(selected, input_candidates[i])) {
actual_candidates[actual_size++] = input_candidates[i];
}
}
// Add to "actual relevant nodes".
actual->push_back(selected);
// We have found a maximum clique.
if (actual_size == 0) {
*stop = callback->Run(*actual);
} else {
if (actual_candidate_size < actual_size) {
Search(graph, callback, actual_candidates.data(),
actual_candidate_size, actual_size, actual, stop);
if (*stop) {
return;
}
}
}
// move node from MD to ND
// Remove from compsub
actual->pop_back();
// Add to "nod"
input_size++;
if (nod > 1) {
// Select a candidate disgraph to the fixed point
start = input_size;
while (graph->Run(pivot, input_candidates[start])) {
start++;
}
}
// end selection
}
}
#if defined(_MSC_VER)
// The following class defines a hash function for arcs
class IntPairHasher : public stdext::hash_compare <pair<int, int> > {
public:
size_t operator() (const pair<int, int>& a) const {
uint64 x = a.first;
uint64 y = GG_ULONGLONG(0xe08c1d668b756f82);
uint64 z = a.second;
mix(x, y, z);
return z;
}
bool operator() (const pair<int, int>& a1, const pair<int, int>& a2) const {
return a1.first < a2.first ||
(a1.first == a2.first && a1.second < a2.second);
}
};
#endif
class FindAndEliminate {
public:
FindAndEliminate(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback)
: graph_(graph), node_count_(node_count), callback_(callback) {}
bool GraphCallback(int node1, int node2) {
if (visited_.find(make_pair(std::min(node1, node2),
std::max(node1, node2))) != visited_.end()) {
return false;
}
return graph_->Run(node1, node2);
}
bool SolutionCallback(const vector<int>& solution) {
const int size = solution.size();
if (size > 1) {
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
visited_.insert(make_pair(std::min(solution[i], solution[j]),
std::max(solution[i], solution[j])));
}
}
callback_->Run(solution);
}
return false;
}
private:
ResultCallback2<bool, int, int>* const graph_;
int node_count_;
ResultCallback1<bool, const vector<int>&>* const callback_;
#if defined(_MSC_VER)
hash_set<pair<int, int>, IntPairHasher> visited_;
#else
hash_set<pair<int, int> > visited_;
#endif
};
} // namespace
// This method implements the 'version2' of the Bron-Kerbosch
// algorithm to find all maximal cliques in a undirected graph.
void FindCliques(ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(graph, callback, initial_candidates.get(), 0, node_count, &actual,
&stop);
}
void CoverArcsByCliques(
ResultCallback2<bool, int, int>* const graph,
int node_count,
ResultCallback1<bool, const vector<int>&>* const callback) {
graph->CheckIsRepeatable();
callback->CheckIsRepeatable();
scoped_ptr<ResultCallback2<bool, int, int> > graph_deleter(graph);
scoped_ptr<ResultCallback1<bool, const vector<int>&> > callback_deleter(
callback);
FindAndEliminate cache(graph, node_count, callback);
scoped_array<int> initial_candidates(new int[node_count]);
vector<int> actual;
scoped_ptr<ResultCallback2<bool, int, int> > cached_graph(
NewPermanentCallback(&cache, &FindAndEliminate::GraphCallback));
scoped_ptr<ResultCallback1<bool, const vector<int>&> >cached_callback(
NewPermanentCallback(&cache, &FindAndEliminate::SolutionCallback));
for (int c = 0; c < node_count; ++c) {
initial_candidates[c] = c;
}
bool stop = false;
Search(cached_graph.get(), cached_callback.get(),
initial_candidates.get(), 0,
node_count, &actual, &stop);
}
} // namespace operations_research
<|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 "ppapi/cpp/var.h"
#include <string.h>
#include <algorithm>
#include "ppapi/c/pp_var.h"
#include "ppapi/c/ppb_var.h"
#include "ppapi/cpp/logging.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/scriptable_object.h"
// Defining sprintf
#include <stdio.h>
#if defined(_MSC_VER)
# define snprintf _snprintf_s
#endif
// Defining PRId32
#if defined(_WIN64)
# define PRId32 "I64d"
#elif defined(_WIN32)
# define PRId32 "ld"
#else
# include <inttypes.h>
#endif
namespace {
DeviceFuncs<PPB_Var> ppb_var_f(PPB_VAR_INTERFACE);
// Technically you can call AddRef and Release on any Var, but it may involve
// cross-process calls depending on the plugin. This is an optimization so we
// only do refcounting on the necessary objects.
inline bool NeedsRefcounting(const PP_Var& var) {
return var.type == PP_VARTYPE_STRING || var.type == PP_VARTYPE_OBJECT;
}
} // namespace
namespace pp {
Var::Var() {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
Var::Var(Null) {
var_.type = PP_VARTYPE_NULL;
needs_release_ = false;
}
Var::Var(bool b) {
var_.type = PP_VARTYPE_BOOL;
var_.value.as_bool = b;
needs_release_ = false;
}
Var::Var(int32_t i) {
var_.type = PP_VARTYPE_INT32;
var_.value.as_int = i;
needs_release_ = false;
}
Var::Var(double d) {
var_.type = PP_VARTYPE_DOUBLE;
var_.value.as_double = d;
needs_release_ = false;
}
Var::Var(const char* str) {
if (ppb_var_f) {
var_ = ppb_var_f->VarFromUtf8(str, static_cast<uint32_t>(strlen(str)));
needs_release_ = true;
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
}
Var::Var(const std::string& str) {
if (ppb_var_f) {
var_ = ppb_var_f->VarFromUtf8(str.c_str(),
static_cast<uint32_t>(str.size()));
needs_release_ = true;
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
}
Var::Var(ScriptableObject* object) {
if (ppb_var_f) {
var_ = ppb_var_f->CreateObject(object->GetClass(), object);
needs_release_ = true;
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
}
Var::Var(const Var& other) {
var_ = other.var_;
if (NeedsRefcounting(var_) && other.needs_release_) {
if (ppb_var_f) {
needs_release_ = true;
ppb_var_f->AddRef(var_);
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
} else {
needs_release_ = false;
}
}
Var::~Var() {
if (needs_release_ && ppb_var_f)
ppb_var_f->Release(var_);
}
Var& Var::operator=(const Var& other) {
// Use the copy constructor to make a copy, then swap into that. This makes
// sure we call the correct init and destruct for everything, without actually
// needing to write the refcounting code here.
Var copy(other);
swap(copy);
return *this;
}
void Var::swap(Var& other) {
std::swap(var_, other.var_);
std::swap(needs_release_, other.needs_release_);
}
bool Var::AsBool() const {
if (!is_bool()) {
PP_NOTREACHED();
return false;
}
return var_.value.as_bool;
}
int32_t Var::AsInt() const {
if (is_int())
return var_.value.as_int;
if (is_double())
return static_cast<int>(var_.value.as_double);
PP_NOTREACHED();
return 0;
}
double Var::AsDouble() const {
if (is_double())
return var_.value.as_double;
if (is_int())
return static_cast<double>(var_.value.as_int);
PP_NOTREACHED();
return 0.0;
}
std::string Var::AsString() const {
if (!is_string()) {
PP_NOTREACHED();
return std::string();
}
if (!ppb_var_f)
return std::string();
uint32_t len;
const char* str = ppb_var_f->VarToUtf8(var_, &len);
return std::string(str, len);
}
bool Var::HasProperty(const Var& name, Var* exception) const {
if (!ppb_var_f)
return false;
return ppb_var_f->HasProperty(var_, name.var_, OutException(exception));
}
Var Var::GetProperty(const Var& name, Var* exception) const {
if (!ppb_var_f)
return Var();
return Var(PassRef(), ppb_var_f->GetProperty(var_, name.var_,
OutException(exception)));
}
void Var::GetAllPropertyNames(std::vector<Var>* properties,
Var* exception) const {
if (!ppb_var_f)
return;
PP_Var* props = NULL;
uint32_t prop_count = 0;
ppb_var_f->GetAllPropertyNames(var_, &prop_count, &props,
OutException(exception));
if (!prop_count)
return;
properties->resize(prop_count);
for (uint32_t i = 0; i < prop_count; ++i) {
Var temp(PassRef(), props[i]);
(*properties)[i].swap(temp);
}
Module::Get()->core()->MemFree(props);
}
void Var::SetProperty(const Var& name, const Var& value, Var* exception) {
if (!ppb_var_f)
return;
ppb_var_f->SetProperty(var_, name.var_, value.var_, OutException(exception));
}
void Var::RemoveProperty(const Var& name, Var* exception) {
if (!ppb_var_f)
return;
ppb_var_f->RemoveProperty(var_, name.var_, OutException(exception));
}
Var Var::Call(const Var& method_name, uint32_t argc, Var* argv,
Var* exception) {
if (!ppb_var_f)
return Var();
if (argc > 0) {
std::vector<PP_Var> args;
args.reserve(argc);
for (size_t i = 0; i < argc; i++)
args.push_back(argv[i].var_);
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_,
argc, &args[0],
OutException(exception)));
} else {
// Don't try to get the address of a vector if it's empty.
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 0, NULL,
OutException(exception)));
}
}
Var Var::Construct(uint32_t argc, Var* argv, Var* exception) const {
if (!ppb_var_f)
return Var();
if (argc > 0) {
std::vector<PP_Var> args;
args.reserve(argc);
for (size_t i = 0; i < argc; i++)
args.push_back(argv[i].var_);
return Var(PassRef(), ppb_var_f->Construct(var_, argc, &args[0],
OutException(exception)));
} else {
// Don't try to get the address of a vector if it's empty.
return Var(PassRef(), ppb_var_f->Construct(var_, 0, NULL,
OutException(exception)));
}
}
Var Var::Call(const Var& method_name, const Var& arg1, Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[1] = {arg1.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 1, args,
OutException(exception)));
}
Var Var::Call(const Var& method_name, const Var& arg1, const Var& arg2,
Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[2] = {arg1.var_, arg2.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 2, args,
OutException(exception)));
}
Var Var::Call(const Var& method_name, const Var& arg1, const Var& arg2,
const Var& arg3, Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[3] = {arg1.var_, arg2.var_, arg3.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 3, args,
OutException(exception)));
}
Var Var::Call(const Var& method_name, const Var& arg1, const Var& arg2,
const Var& arg3, const Var& arg4, Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[4] = {arg1.var_, arg2.var_, arg3.var_, arg4.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 4, args,
OutException(exception)));
}
std::string Var::DebugString() const {
char buf[256];
if (is_void())
snprintf(buf, sizeof(buf), "Var<VOID>");
else if (is_null())
snprintf(buf, sizeof(buf), "Var<NULL>");
else if (is_bool())
snprintf(buf, sizeof(buf), AsBool() ? "Var<true>" : "Var<false>");
else if (is_int())
snprintf(buf, sizeof(buf), "Var<%"PRId32">", AsInt());
else if (is_double())
snprintf(buf, sizeof(buf), "Var<%f>", AsDouble());
else if (is_string())
snprintf(buf, sizeof(buf), "Var<'%s'>", AsString().c_str());
else if (is_object())
snprintf(buf, sizeof(buf), "Var<OBJECT>");
return buf;
}
} // namespace pp
<commit_msg>Fix snprintf comment.<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 "ppapi/cpp/var.h"
#include <string.h>
#include <algorithm>
#include "ppapi/c/pp_var.h"
#include "ppapi/c/ppb_var.h"
#include "ppapi/cpp/logging.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/module_impl.h"
#include "ppapi/cpp/scriptable_object.h"
// Defining snprintf
#include <stdio.h>
#if defined(_MSC_VER)
# define snprintf _snprintf_s
#endif
// Defining PRId32
#if defined(_WIN64)
# define PRId32 "I64d"
#elif defined(_WIN32)
# define PRId32 "ld"
#else
# include <inttypes.h>
#endif
namespace {
DeviceFuncs<PPB_Var> ppb_var_f(PPB_VAR_INTERFACE);
// Technically you can call AddRef and Release on any Var, but it may involve
// cross-process calls depending on the plugin. This is an optimization so we
// only do refcounting on the necessary objects.
inline bool NeedsRefcounting(const PP_Var& var) {
return var.type == PP_VARTYPE_STRING || var.type == PP_VARTYPE_OBJECT;
}
} // namespace
namespace pp {
Var::Var() {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
Var::Var(Null) {
var_.type = PP_VARTYPE_NULL;
needs_release_ = false;
}
Var::Var(bool b) {
var_.type = PP_VARTYPE_BOOL;
var_.value.as_bool = b;
needs_release_ = false;
}
Var::Var(int32_t i) {
var_.type = PP_VARTYPE_INT32;
var_.value.as_int = i;
needs_release_ = false;
}
Var::Var(double d) {
var_.type = PP_VARTYPE_DOUBLE;
var_.value.as_double = d;
needs_release_ = false;
}
Var::Var(const char* str) {
if (ppb_var_f) {
var_ = ppb_var_f->VarFromUtf8(str, static_cast<uint32_t>(strlen(str)));
needs_release_ = true;
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
}
Var::Var(const std::string& str) {
if (ppb_var_f) {
var_ = ppb_var_f->VarFromUtf8(str.c_str(),
static_cast<uint32_t>(str.size()));
needs_release_ = true;
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
}
Var::Var(ScriptableObject* object) {
if (ppb_var_f) {
var_ = ppb_var_f->CreateObject(object->GetClass(), object);
needs_release_ = true;
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
}
Var::Var(const Var& other) {
var_ = other.var_;
if (NeedsRefcounting(var_) && other.needs_release_) {
if (ppb_var_f) {
needs_release_ = true;
ppb_var_f->AddRef(var_);
} else {
var_.type = PP_VARTYPE_VOID;
needs_release_ = false;
}
} else {
needs_release_ = false;
}
}
Var::~Var() {
if (needs_release_ && ppb_var_f)
ppb_var_f->Release(var_);
}
Var& Var::operator=(const Var& other) {
// Use the copy constructor to make a copy, then swap into that. This makes
// sure we call the correct init and destruct for everything, without actually
// needing to write the refcounting code here.
Var copy(other);
swap(copy);
return *this;
}
void Var::swap(Var& other) {
std::swap(var_, other.var_);
std::swap(needs_release_, other.needs_release_);
}
bool Var::AsBool() const {
if (!is_bool()) {
PP_NOTREACHED();
return false;
}
return var_.value.as_bool;
}
int32_t Var::AsInt() const {
if (is_int())
return var_.value.as_int;
if (is_double())
return static_cast<int>(var_.value.as_double);
PP_NOTREACHED();
return 0;
}
double Var::AsDouble() const {
if (is_double())
return var_.value.as_double;
if (is_int())
return static_cast<double>(var_.value.as_int);
PP_NOTREACHED();
return 0.0;
}
std::string Var::AsString() const {
if (!is_string()) {
PP_NOTREACHED();
return std::string();
}
if (!ppb_var_f)
return std::string();
uint32_t len;
const char* str = ppb_var_f->VarToUtf8(var_, &len);
return std::string(str, len);
}
bool Var::HasProperty(const Var& name, Var* exception) const {
if (!ppb_var_f)
return false;
return ppb_var_f->HasProperty(var_, name.var_, OutException(exception));
}
Var Var::GetProperty(const Var& name, Var* exception) const {
if (!ppb_var_f)
return Var();
return Var(PassRef(), ppb_var_f->GetProperty(var_, name.var_,
OutException(exception)));
}
void Var::GetAllPropertyNames(std::vector<Var>* properties,
Var* exception) const {
if (!ppb_var_f)
return;
PP_Var* props = NULL;
uint32_t prop_count = 0;
ppb_var_f->GetAllPropertyNames(var_, &prop_count, &props,
OutException(exception));
if (!prop_count)
return;
properties->resize(prop_count);
for (uint32_t i = 0; i < prop_count; ++i) {
Var temp(PassRef(), props[i]);
(*properties)[i].swap(temp);
}
Module::Get()->core()->MemFree(props);
}
void Var::SetProperty(const Var& name, const Var& value, Var* exception) {
if (!ppb_var_f)
return;
ppb_var_f->SetProperty(var_, name.var_, value.var_, OutException(exception));
}
void Var::RemoveProperty(const Var& name, Var* exception) {
if (!ppb_var_f)
return;
ppb_var_f->RemoveProperty(var_, name.var_, OutException(exception));
}
Var Var::Call(const Var& method_name, uint32_t argc, Var* argv,
Var* exception) {
if (!ppb_var_f)
return Var();
if (argc > 0) {
std::vector<PP_Var> args;
args.reserve(argc);
for (size_t i = 0; i < argc; i++)
args.push_back(argv[i].var_);
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_,
argc, &args[0],
OutException(exception)));
} else {
// Don't try to get the address of a vector if it's empty.
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 0, NULL,
OutException(exception)));
}
}
Var Var::Construct(uint32_t argc, Var* argv, Var* exception) const {
if (!ppb_var_f)
return Var();
if (argc > 0) {
std::vector<PP_Var> args;
args.reserve(argc);
for (size_t i = 0; i < argc; i++)
args.push_back(argv[i].var_);
return Var(PassRef(), ppb_var_f->Construct(var_, argc, &args[0],
OutException(exception)));
} else {
// Don't try to get the address of a vector if it's empty.
return Var(PassRef(), ppb_var_f->Construct(var_, 0, NULL,
OutException(exception)));
}
}
Var Var::Call(const Var& method_name, const Var& arg1, Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[1] = {arg1.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 1, args,
OutException(exception)));
}
Var Var::Call(const Var& method_name, const Var& arg1, const Var& arg2,
Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[2] = {arg1.var_, arg2.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 2, args,
OutException(exception)));
}
Var Var::Call(const Var& method_name, const Var& arg1, const Var& arg2,
const Var& arg3, Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[3] = {arg1.var_, arg2.var_, arg3.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 3, args,
OutException(exception)));
}
Var Var::Call(const Var& method_name, const Var& arg1, const Var& arg2,
const Var& arg3, const Var& arg4, Var* exception) {
if (!ppb_var_f)
return Var();
PP_Var args[4] = {arg1.var_, arg2.var_, arg3.var_, arg4.var_};
return Var(PassRef(), ppb_var_f->Call(var_, method_name.var_, 4, args,
OutException(exception)));
}
std::string Var::DebugString() const {
char buf[256];
if (is_void())
snprintf(buf, sizeof(buf), "Var<VOID>");
else if (is_null())
snprintf(buf, sizeof(buf), "Var<NULL>");
else if (is_bool())
snprintf(buf, sizeof(buf), AsBool() ? "Var<true>" : "Var<false>");
else if (is_int())
snprintf(buf, sizeof(buf), "Var<%"PRId32">", AsInt());
else if (is_double())
snprintf(buf, sizeof(buf), "Var<%f>", AsDouble());
else if (is_string())
snprintf(buf, sizeof(buf), "Var<'%s'>", AsString().c_str());
else if (is_object())
snprintf(buf, sizeof(buf), "Var<OBJECT>");
return buf;
}
} // namespace pp
<|endoftext|> |
<commit_before><commit_msg>plugins: jsAPI: comment out debug messages in eventCallback<commit_after><|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Till Adam <[email protected]>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>
#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <qurl.h>
#include <qfile.h>
#include <qdir.h>
namespace {
class Formatter : public KMail::Interface::BodyPartFormatter {
public:
Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const {
if ( !writer ) return Ok;
const QString diff = bodyPart->asText();
if ( diff.isEmpty() ) return AsIcon;
QString addedLineStyle = QString::fromLatin1(
"style=\""
"padding-left: 4px; "
"font-family: monospace; "
//"border-right: #000 dashed 1px; "
"color: green;\"");
QString fileAddStyle( "style=\"font-weight: bold; font-family: monospace; color: green; \"" );
QString removedLineStyle = QString::fromLatin1(
"style=\""
"padding-left: 4px; "
"font-family: monospace; "
"color: red;\"");
QString fileRemoveStyle( "style=\"font-weight: bold; font-family: monospace; color: red ;\"" );
QString tableStyle = QString::fromLatin1(
"style=\""
"border: dashed 1px; "
"margin: 0em;\"");
QString sepStyle( "style=\"color: black; font-weight: bold; font-family: monospace; \"" );
QString chunkStyle( "style=\"color: blue; font-family: monospace; \"" );
QString regularStyle( "style=\"font-family: monospace;\"" );
QString html = "<br><div align=\"center\">";
html += "<table " + tableStyle +">";
QStringList lines = QStringList::split( '\n', diff, true );
for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
QString line( *it );
QString style;
if ( line.length() > 0 ) {
if ( line.startsWith( "+++" ) ) {
style = fileAddStyle;
} else if ( line.startsWith( "---" ) ) {
style = fileRemoveStyle;
} else if ( line.startsWith( "+" ) || line.startsWith( ">" ) ) {
style = addedLineStyle;
} else if ( line.startsWith( "-" ) || line.startsWith( "<" ) ) {
style = removedLineStyle;
} else if ( line.startsWith( "==") ) {
style = sepStyle;
} else if ( line.startsWith( "@@" ) ) {
style = chunkStyle;
} else {
style = regularStyle;
}
}
html += "<tr><td " + style + ">" + line + "</td></tr>";
}
html += "</table></div>";
writer->queue( html );
return Ok;
}
};
class Plugin : public KMail::Interface::BodyPartFormatterPlugin {
public:
const KMail::Interface::BodyPartFormatter * bodyPartFormatter( int idx ) const {
return idx == 0 ? new Formatter() : 0 ;
}
const char * type( int idx ) const {
return idx == 0 ? "text" : 0 ;
}
const char * subtype( int idx ) const {
return idx == 0 ? "x-diff" : 0 ;
}
const KMail::Interface::BodyPartURLHandler * urlHandler( int ) const { return 0; }
};
}
extern "C"
KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_xdiff_create_bodypart_formatter_plugin() {
return new Plugin();
}
<commit_msg>Quote strings that are used in html.<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Till Adam <[email protected]>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>
#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <qurl.h>
#include <qfile.h>
#include <qdir.h>
#include <qstylesheet.h>
namespace {
class Formatter : public KMail::Interface::BodyPartFormatter {
public:
Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const {
if ( !writer ) return Ok;
const QString diff = bodyPart->asText();
if ( diff.isEmpty() ) return AsIcon;
QString addedLineStyle = QString::fromLatin1(
"style=\""
"padding-left: 4px; "
"font-family: monospace; "
//"border-right: #000 dashed 1px; "
"color: green;\"");
QString fileAddStyle( "style=\"font-weight: bold; font-family: monospace; color: green; \"" );
QString removedLineStyle = QString::fromLatin1(
"style=\""
"padding-left: 4px; "
"font-family: monospace; "
"color: red;\"");
QString fileRemoveStyle( "style=\"font-weight: bold; font-family: monospace; color: red ;\"" );
QString tableStyle = QString::fromLatin1(
"style=\""
"border: dashed 1px; "
"margin: 0em;\"");
QString sepStyle( "style=\"color: black; font-weight: bold; font-family: monospace; \"" );
QString chunkStyle( "style=\"color: blue; font-family: monospace; \"" );
QString regularStyle( "style=\"font-family: monospace;\"" );
QString html = "<br><div align=\"center\">";
html += "<table " + tableStyle +">";
QStringList lines = QStringList::split( '\n', diff, true );
for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
QString line( QStyleSheet::escape( *it ) );
QString style;
if ( line.length() > 0 ) {
if ( line.startsWith( "+++" ) ) {
style = fileAddStyle;
} else if ( line.startsWith( "---" ) ) {
style = fileRemoveStyle;
} else if ( line.startsWith( "+" ) || line.startsWith( ">" ) ) {
style = addedLineStyle;
} else if ( line.startsWith( "-" ) || line.startsWith( "<" ) ) {
style = removedLineStyle;
} else if ( line.startsWith( "==") ) {
style = sepStyle;
} else if ( line.startsWith( "@@" ) ) {
style = chunkStyle;
} else {
style = regularStyle;
}
}
html += "<tr><td " + style + ">" + line + "</td></tr>";
}
html += "</table></div>";
writer->queue( html );
return Ok;
}
};
class Plugin : public KMail::Interface::BodyPartFormatterPlugin {
public:
const KMail::Interface::BodyPartFormatter * bodyPartFormatter( int idx ) const {
return idx == 0 ? new Formatter() : 0 ;
}
const char * type( int idx ) const {
return idx == 0 ? "text" : 0 ;
}
const char * subtype( int idx ) const {
return idx == 0 ? "x-diff" : 0 ;
}
const KMail::Interface::BodyPartURLHandler * urlHandler( int ) const { return 0; }
};
}
extern "C"
KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_xdiff_create_bodypart_formatter_plugin() {
return new Plugin();
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.2 1999/11/17 22:36:41 rahulj
* Code works with ICU transcoding service
*
* Revision 1.1.1.1 1999/11/09 01:06:07 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:33 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/TranscodingException.hpp>
#include "ICUTransService.hpp"
#include <string.h>
#include <uloc.h>
#include <unicode.h>
#include <ucnv.h>
#include <ustring.h>
// ---------------------------------------------------------------------------
// ICUTransService: Public, static methods
// ---------------------------------------------------------------------------
void ICUTransService::setICUPath(const char* const pathToSet)
{
uloc_setDataDirectory(pathToSet);
}
// ---------------------------------------------------------------------------
// ICUTransService: Constructors and Destructor
// ---------------------------------------------------------------------------
ICUTransService::ICUTransService()
{
}
ICUTransService::~ICUTransService()
{
}
// ---------------------------------------------------------------------------
// ICUTransService: The virtual transcoding service API
// ---------------------------------------------------------------------------
int ICUTransService::compareIString(const XMLCh* const comp1
, const XMLCh* const comp2)
{
const XMLCh* psz1 = comp1;
const XMLCh* psz2 = comp2;
unsigned int curCount = 0;
while (true)
{
// If an inequality, then return the difference
if (Unicode::toUpperCase(*psz1) != Unicode::toUpperCase(*psz2))
return int(*psz1) - int(*psz2);
// If either has ended, then they both ended, so equal
if (!*psz1 || !*psz2)
break;
// Move upwards for the next round
psz1++;
psz2++;
}
return 0;
}
int ICUTransService::compareNIString(const XMLCh* const comp1
, const XMLCh* const comp2
, const unsigned int maxChars)
{
const XMLCh* psz1 = comp1;
const XMLCh* psz2 = comp2;
unsigned int curCount = 0;
while (true)
{
// If an inequality, then return difference
if (Unicode::toUpperCase(*psz1) != Unicode::toUpperCase(*psz2))
return int(*psz1) - int(*psz2);
// If either ended, then both ended, so equal
if (!*psz1 || !*psz2)
break;
// Move upwards to next chars
psz1++;
psz2++;
//
// Bump the count of chars done. If it equals the count then we
// are equal for the requested count, so break out and return
// equal.
//
curCount++;
if (maxChars == curCount)
break;
}
return 0;
}
bool ICUTransService::isSpace(const XMLCh toCheck) const
{
return (Unicode::isSpaceChar(toCheck) != 0);
}
XMLTranscoder* ICUTransService::makeNewDefTranscoder()
{
//
// Try to create a default converter. If it fails, return a null pointer
// which will basically cause the system to give up because we really can't
// do anything without one.
//
UErrorCode uerr = U_ZERO_ERROR;
UConverter* converter = ucnv_open(NULL, &uerr);
if (!converter)
return 0;
// That went ok, so create an ICU transcoder wrapper and return it
return new ICUTranscoder(converter, 0);
}
XMLTranscoder*
ICUTransService::makeNewTranscoderFor( const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize)
{
UErrorCode uerr = U_ZERO_ERROR;
UConverter* converter = ucnv_openU(encodingName, &uerr);
if (!converter)
{
resValue = XMLTransService::UnsupportedEncoding;
return 0;
}
return new ICUTranscoder(converter, blockSize);
}
// ---------------------------------------------------------------------------
// ICUTranscoder: Constructors and Destructor
// ---------------------------------------------------------------------------
ICUTranscoder::ICUTranscoder( UConverter* const toAdopt
, const unsigned int blockSize) :
fCharOfsBuf(0)
, fConverter(toAdopt)
{
// There won't be a block size if this is for a default transcoder
if (blockSize)
fCharOfsBuf = new long[blockSize];
}
ICUTranscoder::~ICUTranscoder()
{
delete [] fCharOfsBuf;
// If there is a converter, ask ICU to clean it up
if (fConverter)
{
// <TBD> Does this actually delete the structure???
ucnv_close(fConverter);
fConverter = 0;
}
}
// ---------------------------------------------------------------------------
// ICUTranscoder: The virtual transcoder API
// ---------------------------------------------------------------------------
unsigned int ICUTranscoder::calcRequiredSize(const XMLCh* const srcText)
{
if (!srcText)
return 0;
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const int32_t targetCap = ucnv_fromUChars
(
fConverter
, 0
, 0
, srcText
, &err
);
if (err != U_BUFFER_OVERFLOW_ERROR)
return 0;
return (unsigned int)targetCap;
}
unsigned int ICUTranscoder::calcRequiredSize(const char* const srcText)
{
if (!srcText)
return 0;
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const int32_t targetCap = ucnv_toUChars
(
fConverter
, 0
, 0
, srcText
, strlen(srcText)
, &err
);
if (err != U_BUFFER_OVERFLOW_ERROR)
return 0;
// Subtract one since it includes the terminator space
return (unsigned int)(targetCap - 1);
}
XMLCh ICUTranscoder::transcodeOne( const char* const srcData
, const unsigned int srcBytes
, unsigned int& bytesEaten)
{
// Check for stupid stuff
if (!srcBytes)
return 0;
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const char* startSrc = srcData;
const XMLCh chRet = ucnv_getNextUChar
(
fConverter
, &startSrc
, (srcData + srcBytes) - 1
, &err
);
// Bail out if an error
if (U_FAILURE(err))
return 0;
// Calculate the bytes eaten and return the char
bytesEaten = startSrc - srcData;
return chRet;
}
char* ICUTranscoder::transcode(const XMLCh* const toTranscode)
{
char* retBuf = 0;
// Check for a couple of special cases
if (!toTranscode)
return 0;
if (!*toTranscode)
{
retBuf = new char[1];
retBuf[0] = 0;
return retBuf;
}
XMLMutexLock lockConverter(&fMutex);
// Caculate a return buffer size not too big, but less likely to overflow
int32_t targetLen = (int32_t)(u_strlen(toTranscode) * 1.25);
// Allocate the return buffer
retBuf = new char[targetLen + 1];
//Convert the Unicode string to char* using Intl stuff
UErrorCode err = U_ZERO_ERROR;
int32_t targetCap = ucnv_fromUChars
(
fConverter
, retBuf
, targetLen + 1
, toTranscode
, &err
);
// If targetLen is not enough then buffer overflow might occur
if (err == U_BUFFER_OVERFLOW_ERROR)
{
// Reset the error, delete the old buffer, allocate a new one, and try again
err = U_ZERO_ERROR;
delete [] retBuf;
retBuf = new char[targetCap];
targetCap = ucnv_fromUChars(fConverter, retBuf, targetCap, toTranscode, &err);
}
if (U_FAILURE(err))
{
delete [] retBuf;
return 0;
}
// Cap it off and return
retBuf[targetCap] = 0;
return retBuf;
}
bool ICUTranscoder::transcode( const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxChars)
{
// Watch for a few psycho corner cases
if (!toTranscode || !maxChars)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
int32_t targetCap;
targetCap = ucnv_fromUChars(fConverter, toFill, maxChars + 1, toTranscode, &err);
if (U_FAILURE(err))
return false;
return true;
}
XMLCh* ICUTranscoder::transcode(const char* const toTranscode)
{
// Watch for a few pyscho corner cases
if (!toTranscode)
return 0;
XMLCh* retVal = 0;
if (!*toTranscode)
{
retVal = new XMLCh[1];
retVal[0] = 0;
return retVal;
}
XMLMutexLock lockConverter(&fMutex);
//
// Get the length of the string to transcode. The Unicode string will
// almost always be no more chars than were in the source, so this is
// the best guess as to the storage needed.
//
const int32_t srcLen = (int32_t)strlen(toTranscode);
//
// Here we don't know what the target length will be so use 0 and expect
// an BUFFER_OVERFLOW_ERROR in which case it'd get resolved by the
// correct capacity value.
//
UErrorCode err = U_ZERO_ERROR;
int32_t targetCap;
targetCap = ucnv_toUChars
(
fConverter
, 0
, 0
, toTranscode
, srcLen
, &err
);
if (err != U_BUFFER_OVERFLOW_ERROR)
return 0;
err = U_ZERO_ERROR;
retVal = new XMLCh[targetCap];
ucnv_toUChars
(
fConverter
, retVal
, targetCap
, toTranscode
, srcLen
, &err
);
if (U_FAILURE(err))
return 0;
return retVal;
}
bool ICUTranscoder::transcode( const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars)
{
// Check for a couple of psycho corner cases
if (!toTranscode || !maxChars)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const int32_t srcLen = (int32_t)strlen(toTranscode);
ucnv_toUChars
(
fConverter
, toFill
, maxChars + 1
, toTranscode
, srcLen
, &err
);
if (U_FAILURE(err))
return false;
return true;
}
unsigned int
ICUTranscoder::transcodeXML(const char* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten)
{
//
// If the input encoding uses fixed size characters, we can use a
// simpler, faster approach to computing the character sizes to be
// returned in the charSizes array.
//
const int maxCharSize = ucnv_getMaxCharSize(fConverter);
const int minCharSize = ucnv_getMinCharSize(fConverter);
//
// Set up pointers to the source and destination buffers.
//
UChar* startTarget = toFill;
const char* startSrc = srcData;
const char* endSrc = srcData + srcCount;
//
// Transoode the buffer. Buffer overflow errors are normal, occuring
// when the raw input buffer holds more characters than will fit
// in the Unicode output buffer.
//
UErrorCode err = U_ZERO_ERROR;
ucnv_toUnicode
(
fConverter
, &startTarget
, toFill + maxChars
, &startSrc
, endSrc
, 0
, false
, &err
);
if ((err != U_ZERO_ERROR) && (err != U_INDEX_OUTOFBOUNDS_ERROR))
ThrowXML(TranscodingException, XML4CExcepts::Trans_CouldNotXCodeXMLData);
// Calculate the bytes eaten and store in caller's param
bytesEaten = startSrc - srcData;
// Return the chars we put into the target buffer
return startTarget - toFill;
}
<commit_msg>Now works with ICU 1.3.1<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/**
* $Log$
* Revision 1.3 1999/11/18 20:16:52 abagchi
* Now works with ICU 1.3.1
*
* Revision 1.2 1999/11/17 22:36:41 rahulj
* Code works with ICU transcoding service
*
* Revision 1.1.1.1 1999/11/09 01:06:07 twl
* Initial checkin
*
* Revision 1.3 1999/11/08 20:45:33 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/TranscodingException.hpp>
#include "ICUTransService.hpp"
#include <string.h>
#include <uloc.h>
#include <unicode.h>
#include <ucnv.h>
#include <ustring.h>
// ---------------------------------------------------------------------------
// ICUTransService: Public, static methods
// ---------------------------------------------------------------------------
void ICUTransService::setICUPath(const char* const pathToSet)
{
uloc_setDataDirectory(pathToSet);
}
// ---------------------------------------------------------------------------
// ICUTransService: Constructors and Destructor
// ---------------------------------------------------------------------------
ICUTransService::ICUTransService()
{
}
ICUTransService::~ICUTransService()
{
}
// ---------------------------------------------------------------------------
// ICUTransService: The virtual transcoding service API
// ---------------------------------------------------------------------------
int ICUTransService::compareIString(const XMLCh* const comp1
, const XMLCh* const comp2)
{
const XMLCh* psz1 = comp1;
const XMLCh* psz2 = comp2;
unsigned int curCount = 0;
while (true)
{
// If an inequality, then return the difference
if (Unicode::toUpperCase(*psz1) != Unicode::toUpperCase(*psz2))
return int(*psz1) - int(*psz2);
// If either has ended, then they both ended, so equal
if (!*psz1 || !*psz2)
break;
// Move upwards for the next round
psz1++;
psz2++;
}
return 0;
}
int ICUTransService::compareNIString(const XMLCh* const comp1
, const XMLCh* const comp2
, const unsigned int maxChars)
{
const XMLCh* psz1 = comp1;
const XMLCh* psz2 = comp2;
unsigned int curCount = 0;
while (true)
{
// If an inequality, then return difference
if (Unicode::toUpperCase(*psz1) != Unicode::toUpperCase(*psz2))
return int(*psz1) - int(*psz2);
// If either ended, then both ended, so equal
if (!*psz1 || !*psz2)
break;
// Move upwards to next chars
psz1++;
psz2++;
//
// Bump the count of chars done. If it equals the count then we
// are equal for the requested count, so break out and return
// equal.
//
curCount++;
if (maxChars == curCount)
break;
}
return 0;
}
bool ICUTransService::isSpace(const XMLCh toCheck) const
{
return (Unicode::isSpaceChar(toCheck) != 0);
}
XMLTranscoder* ICUTransService::makeNewDefTranscoder()
{
//
// Try to create a default converter. If it fails, return a null pointer
// which will basically cause the system to give up because we really can't
// do anything without one.
//
UErrorCode uerr = U_ZERO_ERROR;
UConverter* converter = ucnv_open(NULL, &uerr);
if (!converter)
return 0;
// That went ok, so create an ICU transcoder wrapper and return it
return new ICUTranscoder(converter, 0);
}
XMLTranscoder*
ICUTransService::makeNewTranscoderFor( const XMLCh* const encodingName
, XMLTransService::Codes& resValue
, const unsigned int blockSize)
{
UErrorCode uerr = U_ZERO_ERROR;
UConverter* converter = ucnv_openU(encodingName, &uerr);
if (!converter)
{
resValue = XMLTransService::UnsupportedEncoding;
return 0;
}
return new ICUTranscoder(converter, blockSize);
}
// ---------------------------------------------------------------------------
// ICUTranscoder: Constructors and Destructor
// ---------------------------------------------------------------------------
ICUTranscoder::ICUTranscoder( UConverter* const toAdopt
, const unsigned int blockSize) :
fCharOfsBuf(0)
, fConverter(toAdopt)
{
// There won't be a block size if this is for a default transcoder
if (blockSize)
fCharOfsBuf = new long[blockSize];
}
ICUTranscoder::~ICUTranscoder()
{
delete [] fCharOfsBuf;
// If there is a converter, ask ICU to clean it up
if (fConverter)
{
// <TBD> Does this actually delete the structure???
ucnv_close(fConverter);
fConverter = 0;
}
}
// ---------------------------------------------------------------------------
// ICUTranscoder: The virtual transcoder API
// ---------------------------------------------------------------------------
unsigned int ICUTranscoder::calcRequiredSize(const XMLCh* const srcText)
{
if (!srcText)
return 0;
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const int32_t targetCap = ucnv_fromUChars
(
fConverter
, 0
, 0
, srcText
, &err
);
if (err != U_BUFFER_OVERFLOW_ERROR)
return 0;
return (unsigned int)targetCap;
}
unsigned int ICUTranscoder::calcRequiredSize(const char* const srcText)
{
if (!srcText)
return 0;
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const int32_t targetCap = ucnv_toUChars
(
fConverter
, 0
, 0
, srcText
, strlen(srcText)
, &err
);
if (err != U_BUFFER_OVERFLOW_ERROR)
return 0;
// Subtract one since it includes the terminator space
return (unsigned int)(targetCap - 1);
}
XMLCh ICUTranscoder::transcodeOne( const char* const srcData
, const unsigned int srcBytes
, unsigned int& bytesEaten)
{
// Check for stupid stuff
if (!srcBytes)
return 0;
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const char* startSrc = srcData;
const XMLCh chRet = ucnv_getNextUChar
(
fConverter
, &startSrc
, (srcData + srcBytes) - 1
, &err
);
// Bail out if an error
if (U_FAILURE(err))
return 0;
// Calculate the bytes eaten and return the char
bytesEaten = startSrc - srcData;
return chRet;
}
char* ICUTranscoder::transcode(const XMLCh* const toTranscode)
{
char* retBuf = 0;
// Check for a couple of special cases
if (!toTranscode)
return 0;
if (!*toTranscode)
{
retBuf = new char[1];
retBuf[0] = 0;
return retBuf;
}
XMLMutexLock lockConverter(&fMutex);
// Caculate a return buffer size not too big, but less likely to overflow
int32_t targetLen = (int32_t)(u_strlen(toTranscode) * 1.25);
// Allocate the return buffer
retBuf = new char[targetLen + 1];
//Convert the Unicode string to char* using Intl stuff
UErrorCode err = U_ZERO_ERROR;
int32_t targetCap = ucnv_fromUChars
(
fConverter
, retBuf
, targetLen + 1
, toTranscode
, &err
);
// If targetLen is not enough then buffer overflow might occur
if (err == U_BUFFER_OVERFLOW_ERROR)
{
// Reset the error, delete the old buffer, allocate a new one, and try again
err = U_ZERO_ERROR;
delete [] retBuf;
retBuf = new char[targetCap];
targetCap = ucnv_fromUChars(fConverter, retBuf, targetCap, toTranscode, &err);
}
if (U_FAILURE(err))
{
delete [] retBuf;
return 0;
}
// Cap it off and return
retBuf[targetCap] = 0;
return retBuf;
}
bool ICUTranscoder::transcode( const XMLCh* const toTranscode
, char* const toFill
, const unsigned int maxChars)
{
// Watch for a few psycho corner cases
if (!toTranscode || !maxChars)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
int32_t targetCap;
targetCap = ucnv_fromUChars(fConverter, toFill, maxChars + 1, toTranscode, &err);
if (U_FAILURE(err))
return false;
return true;
}
XMLCh* ICUTranscoder::transcode(const char* const toTranscode)
{
// Watch for a few pyscho corner cases
if (!toTranscode)
return 0;
XMLCh* retVal = 0;
if (!*toTranscode)
{
retVal = new XMLCh[1];
retVal[0] = 0;
return retVal;
}
XMLMutexLock lockConverter(&fMutex);
//
// Get the length of the string to transcode. The Unicode string will
// almost always be no more chars than were in the source, so this is
// the best guess as to the storage needed.
//
const int32_t srcLen = (int32_t)strlen(toTranscode);
//
// Here we don't know what the target length will be so use 0 and expect
// an U_BUFFER_OVERFLOW_ERROR in which case it'd get resolved by the
// correct capacity value.
//
UErrorCode err = U_ZERO_ERROR;
int32_t targetCap;
targetCap = ucnv_toUChars
(
fConverter
, 0
, 0
, toTranscode
, srcLen
, &err
);
if (err != U_BUFFER_OVERFLOW_ERROR)
return 0;
err = U_ZERO_ERROR;
retVal = new XMLCh[targetCap];
ucnv_toUChars
(
fConverter
, retVal
, targetCap
, toTranscode
, srcLen
, &err
);
if (U_FAILURE(err))
return 0;
return retVal;
}
bool ICUTranscoder::transcode( const char* const toTranscode
, XMLCh* const toFill
, const unsigned int maxChars)
{
// Check for a couple of psycho corner cases
if (!toTranscode || !maxChars)
{
toFill[0] = 0;
return true;
}
if (!*toTranscode)
{
toFill[0] = 0;
return true;
}
XMLMutexLock lockConverter(&fMutex);
UErrorCode err = U_ZERO_ERROR;
const int32_t srcLen = (int32_t)strlen(toTranscode);
ucnv_toUChars
(
fConverter
, toFill
, maxChars + 1
, toTranscode
, srcLen
, &err
);
if (U_FAILURE(err))
return false;
return true;
}
unsigned int
ICUTranscoder::transcodeXML(const char* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten)
{
//
// If the input encoding uses fixed size characters, we can use a
// simpler, faster approach to computing the character sizes to be
// returned in the charSizes array.
//
const int maxCharSize = ucnv_getMaxCharSize(fConverter);
const int minCharSize = ucnv_getMinCharSize(fConverter);
//
// Set up pointers to the source and destination buffers.
//
UChar* startTarget = toFill;
const char* startSrc = srcData;
const char* endSrc = srcData + srcCount;
//
// Transoode the buffer. Buffer overflow errors are normal, occuring
// when the raw input buffer holds more characters than will fit
// in the Unicode output buffer.
//
UErrorCode err = U_ZERO_ERROR;
ucnv_toUnicode
(
fConverter
, &startTarget
, toFill + maxChars
, &startSrc
, endSrc
, 0
, false
, &err
);
if ((err != U_ZERO_ERROR) && (err != U_INDEX_OUTOFBOUNDS_ERROR))
ThrowXML(TranscodingException, XML4CExcepts::Trans_CouldNotXCodeXMLData);
// Calculate the bytes eaten and store in caller's param
bytesEaten = startSrc - srcData;
// Return the chars we put into the target buffer
return startTarget - toFill;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <base/parse_object.h>
#include <ifmap/ifmap_link.h>
#include <ifmap/ifmap_table.h>
#include <vnc_cfg_types.h>
#include <cmn/agent_cmn.h>
#include <cmn/agent.h>
#include <init/agent_param.h>
#include <cmn/agent_db.h>
#include <cfg/cfg_init.h>
#include <cfg/cfg_interface_listener.h>
#include <cfg/cfg_interface.h>
#include <oper/agent_types.h>
#include <oper/interface_common.h>
#include <oper/vm.h>
#include <oper/vn.h>
#include <oper/mirror_table.h>
#include <oper/config_manager.h>
using namespace std;
using namespace boost::uuids;
using namespace autogen;
void InterfaceCfgClient::Notify(DBTablePartBase *partition, DBEntryBase *e) {
CfgIntEntry *entry = static_cast<CfgIntEntry *>(e);
Agent *agent = Agent::GetInstance();
if (entry->IsDeleted()) {
VmInterface::Delete(agent->interface_table(),
entry->GetUuid(), VmInterface::INSTANCE_MSG);
} else {
uint16_t tx_vlan_id = VmInterface::kInvalidVlanId;
uint16_t rx_vlan_id = VmInterface::kInvalidVlanId;
string port = Agent::NullString();
Interface::Transport transport = Interface::TRANSPORT_ETHERNET;
if (agent->params()->isVmwareMode()) {
tx_vlan_id = entry->tx_vlan_id();
rx_vlan_id = entry->rx_vlan_id();
port = agent->params()->vmware_physical_port();
transport = Interface::TRANSPORT_VIRTUAL;
}
if (agent->vrouter_on_nic_mode() == true ||
agent->vrouter_on_host_dpdk() == true) {
transport = Interface::TRANSPORT_PMD;
}
VmInterface::NovaAdd(agent->interface_table(), entry->GetUuid(),
entry->GetIfname(), entry->ip_addr().to_v4(),
entry->GetMacAddr(), entry->vm_name(),
entry->vm_project_uuid(), tx_vlan_id, rx_vlan_id,
port, entry->ip6_addr(), transport);
FetchInterfaceData(entry->GetUuid());
}
}
void InterfaceCfgClient::FetchInterfaceData(const uuid if_uuid) const {
IFMapNode *node = UuidToIFNode(if_uuid);
if (node != NULL) {
DBRequest req;
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
if (agent_cfg_->agent()->interface_table()->IFNodeToReq(node,
req, const_cast<uuid&>(if_uuid))) {
agent_cfg_->agent()->interface_table()->Enqueue(&req);
}
}
}
void InterfaceCfgClient::RouteTableNotify(DBTablePartBase *partition,
DBEntryBase *e) {
IFMapNode *node = static_cast<IFMapNode *>(e);
if (node->IsDeleted()) {
return;
}
//Trigger change on all interface entries
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
for (DBGraphVertex::adjacency_iterator iter =
node->begin(table->GetGraph());
iter != node->end(table->GetGraph()); ++iter) {
if (iter->IsDeleted()) {
continue;
}
IFMapNode *adj_node = static_cast<IFMapNode *>(iter.operator->());
if (Agent::GetInstance()->config_manager()->SkipNode(adj_node)) {
continue;
}
if (adj_node->table() ==
Agent::GetInstance()->cfg()->cfg_vm_interface_table()) {
DBRequest req;
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
boost::uuids::uuid id;
agent_cfg_->agent()->interface_table()->IFNodeToUuid(adj_node, id);
if (agent_cfg_->agent()->interface_table()->IFNodeToReq(adj_node,
req, id)) {
agent_cfg_->agent()->interface_table()->Enqueue(&req);
}
}
}
}
void InterfaceCfgClient::CfgNotify(DBTablePartBase *partition, DBEntryBase *e) {
IFMapNode *node = static_cast<IFMapNode *>(e);
CfgState *state = static_cast<CfgState *>(e->GetState(partition->parent(), cfg_listener_id_));
if (node->IsDeleted()) {
if (state) {
VirtualMachineInterface *cfg =
static_cast <VirtualMachineInterface *> (node->GetObject());
assert(cfg);
autogen::IdPermsType id_perms = cfg->id_perms();
boost::uuids::uuid u;
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, u);
uuid_ifnode_tree_.erase(u);
node->ClearState(partition->parent(), cfg_listener_id_);
delete state;
}
} else {
VirtualMachineInterface *cfg =
static_cast <VirtualMachineInterface *> (node->GetObject());
if (cfg == NULL) {
return;
}
autogen::IdPermsType id_perms = cfg->id_perms();
boost::uuids::uuid u;
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, u);
// We have observed that control node gives a node withoug uuid first
// followed by subsequent changes that give uuid.
// Ignore if UUID is not yet present
if (u == nil_uuid()) {
return;
}
if (state == NULL) {
uuid_ifnode_tree_.insert(UuidIFNodePair(u, node));
state = new CfgState();
state->seen_ = true;
node->SetState(partition->parent(), cfg_listener_id_, state);
}
}
}
IFMapNode *InterfaceCfgClient::UuidToIFNode(const uuid &u) const {
UuidToIFNodeTree::const_iterator it;
it = uuid_ifnode_tree_.find(u);
if (it == uuid_ifnode_tree_.end()) {
return NULL;
}
return it->second;
}
void InterfaceCfgClient::Init() {
DBTableBase *table = agent_cfg_->agent()->interface_config_table();
table->Register(boost::bind(&InterfaceCfgClient::Notify, this, _1, _2));
// Register with config DB table for vm-port UUID to IFNode mapping
DBTableBase *cfg_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"virtual-machine-interface");
assert(cfg_db);
cfg_listener_id_ = cfg_db->Register
(boost::bind(&InterfaceCfgClient::CfgNotify, this, _1, _2));
// Register with config DB table for static route table changes
DBTableBase *cfg_route_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"interface-route-table");
assert(cfg_route_db);
cfg_route_table_listener_id_ = cfg_route_db->Register
(boost::bind(&InterfaceCfgClient::RouteTableNotify, this, _1, _2));
}
void InterfaceCfgClient::Shutdown() {
IFMapTable *cfg_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"virtual-machine-interface");
DBTable::DBStateClear(cfg_db, cfg_listener_id_);
cfg_db->Unregister(cfg_listener_id_);
DBTableBase *cfg_route_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"interface-route-table");
cfg_route_db->Unregister(cfg_route_table_listener_id_);
}
<commit_msg>* Set transport type as ethernet if its a namespace interface Closes-bug:#1519731<commit_after>/*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <base/parse_object.h>
#include <ifmap/ifmap_link.h>
#include <ifmap/ifmap_table.h>
#include <vnc_cfg_types.h>
#include <cmn/agent_cmn.h>
#include <cmn/agent.h>
#include <init/agent_param.h>
#include <cmn/agent_db.h>
#include <cfg/cfg_init.h>
#include <cfg/cfg_interface_listener.h>
#include <cfg/cfg_interface.h>
#include <oper/agent_types.h>
#include <oper/interface_common.h>
#include <oper/vm.h>
#include <oper/vn.h>
#include <oper/mirror_table.h>
#include <oper/config_manager.h>
using namespace std;
using namespace boost::uuids;
using namespace autogen;
void InterfaceCfgClient::Notify(DBTablePartBase *partition, DBEntryBase *e) {
CfgIntEntry *entry = static_cast<CfgIntEntry *>(e);
Agent *agent = Agent::GetInstance();
if (entry->IsDeleted()) {
VmInterface::Delete(agent->interface_table(),
entry->GetUuid(), VmInterface::INSTANCE_MSG);
} else {
uint16_t tx_vlan_id = VmInterface::kInvalidVlanId;
uint16_t rx_vlan_id = VmInterface::kInvalidVlanId;
string port = Agent::NullString();
Interface::Transport transport = Interface::TRANSPORT_ETHERNET;
if (agent->params()->isVmwareMode()) {
tx_vlan_id = entry->tx_vlan_id();
rx_vlan_id = entry->rx_vlan_id();
port = agent->params()->vmware_physical_port();
transport = Interface::TRANSPORT_VIRTUAL;
}
if ((agent->vrouter_on_nic_mode() == true ||
agent->vrouter_on_host_dpdk() == true) &&
entry->port_type() == CfgIntEntry::CfgIntVMPort) {
transport = Interface::TRANSPORT_PMD;
}
VmInterface::NovaAdd(agent->interface_table(), entry->GetUuid(),
entry->GetIfname(), entry->ip_addr().to_v4(),
entry->GetMacAddr(), entry->vm_name(),
entry->vm_project_uuid(), tx_vlan_id, rx_vlan_id,
port, entry->ip6_addr(), transport);
FetchInterfaceData(entry->GetUuid());
}
}
void InterfaceCfgClient::FetchInterfaceData(const uuid if_uuid) const {
IFMapNode *node = UuidToIFNode(if_uuid);
if (node != NULL) {
DBRequest req;
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
if (agent_cfg_->agent()->interface_table()->IFNodeToReq(node,
req, const_cast<uuid&>(if_uuid))) {
agent_cfg_->agent()->interface_table()->Enqueue(&req);
}
}
}
void InterfaceCfgClient::RouteTableNotify(DBTablePartBase *partition,
DBEntryBase *e) {
IFMapNode *node = static_cast<IFMapNode *>(e);
if (node->IsDeleted()) {
return;
}
//Trigger change on all interface entries
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
for (DBGraphVertex::adjacency_iterator iter =
node->begin(table->GetGraph());
iter != node->end(table->GetGraph()); ++iter) {
if (iter->IsDeleted()) {
continue;
}
IFMapNode *adj_node = static_cast<IFMapNode *>(iter.operator->());
if (Agent::GetInstance()->config_manager()->SkipNode(adj_node)) {
continue;
}
if (adj_node->table() ==
Agent::GetInstance()->cfg()->cfg_vm_interface_table()) {
DBRequest req;
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
boost::uuids::uuid id;
agent_cfg_->agent()->interface_table()->IFNodeToUuid(adj_node, id);
if (agent_cfg_->agent()->interface_table()->IFNodeToReq(adj_node,
req, id)) {
agent_cfg_->agent()->interface_table()->Enqueue(&req);
}
}
}
}
void InterfaceCfgClient::CfgNotify(DBTablePartBase *partition, DBEntryBase *e) {
IFMapNode *node = static_cast<IFMapNode *>(e);
CfgState *state = static_cast<CfgState *>(e->GetState(partition->parent(), cfg_listener_id_));
if (node->IsDeleted()) {
if (state) {
VirtualMachineInterface *cfg =
static_cast <VirtualMachineInterface *> (node->GetObject());
assert(cfg);
autogen::IdPermsType id_perms = cfg->id_perms();
boost::uuids::uuid u;
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, u);
uuid_ifnode_tree_.erase(u);
node->ClearState(partition->parent(), cfg_listener_id_);
delete state;
}
} else {
VirtualMachineInterface *cfg =
static_cast <VirtualMachineInterface *> (node->GetObject());
if (cfg == NULL) {
return;
}
autogen::IdPermsType id_perms = cfg->id_perms();
boost::uuids::uuid u;
CfgUuidSet(id_perms.uuid.uuid_mslong, id_perms.uuid.uuid_lslong, u);
// We have observed that control node gives a node withoug uuid first
// followed by subsequent changes that give uuid.
// Ignore if UUID is not yet present
if (u == nil_uuid()) {
return;
}
if (state == NULL) {
uuid_ifnode_tree_.insert(UuidIFNodePair(u, node));
state = new CfgState();
state->seen_ = true;
node->SetState(partition->parent(), cfg_listener_id_, state);
}
}
}
IFMapNode *InterfaceCfgClient::UuidToIFNode(const uuid &u) const {
UuidToIFNodeTree::const_iterator it;
it = uuid_ifnode_tree_.find(u);
if (it == uuid_ifnode_tree_.end()) {
return NULL;
}
return it->second;
}
void InterfaceCfgClient::Init() {
DBTableBase *table = agent_cfg_->agent()->interface_config_table();
table->Register(boost::bind(&InterfaceCfgClient::Notify, this, _1, _2));
// Register with config DB table for vm-port UUID to IFNode mapping
DBTableBase *cfg_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"virtual-machine-interface");
assert(cfg_db);
cfg_listener_id_ = cfg_db->Register
(boost::bind(&InterfaceCfgClient::CfgNotify, this, _1, _2));
// Register with config DB table for static route table changes
DBTableBase *cfg_route_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"interface-route-table");
assert(cfg_route_db);
cfg_route_table_listener_id_ = cfg_route_db->Register
(boost::bind(&InterfaceCfgClient::RouteTableNotify, this, _1, _2));
}
void InterfaceCfgClient::Shutdown() {
IFMapTable *cfg_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"virtual-machine-interface");
DBTable::DBStateClear(cfg_db, cfg_listener_id_);
cfg_db->Unregister(cfg_listener_id_);
DBTableBase *cfg_route_db = IFMapTable::FindTable(agent_cfg_->agent()->db(),
"interface-route-table");
cfg_route_db->Unregister(cfg_route_table_listener_id_);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id$
*/
//////////////////////////////////////////////////////////////////////
// DOMNodeIteratorImpl.cpp: implementation of the DOMNodeIteratorImpl class.
//
//////////////////////////////////////////////////////////////////////
#include "DOMNodeIteratorImpl.hpp"
#include "DOMDocumentImpl.hpp"
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
DOMNodeIteratorImpl::DOMNodeIteratorImpl (DOMDocument* doc,
DOMNode* root,
unsigned long whatToShow,
DOMNodeFilter* nodeFilter,
bool expandEntityRef)
: fRoot(root),
fDocument(doc),
fWhatToShow(whatToShow),
fNodeFilter(nodeFilter),
fExpandEntityReferences(expandEntityRef),
fDetached(false),
fCurrentNode(0),
fForward(true)
{
}
DOMNodeIteratorImpl::DOMNodeIteratorImpl ( const DOMNodeIteratorImpl& toCopy)
: fRoot(toCopy.fRoot),
fDocument(toCopy.fDocument),
fWhatToShow(toCopy.fWhatToShow),
fNodeFilter(toCopy.fNodeFilter),
fExpandEntityReferences(toCopy.fExpandEntityReferences),
fDetached(toCopy.fDetached),
fCurrentNode(toCopy.fCurrentNode),
fForward(toCopy.fForward)
{
}
DOMNodeIteratorImpl& DOMNodeIteratorImpl::operator= (const DOMNodeIteratorImpl& other) {
fRoot = other.fRoot;
fCurrentNode = other.fRoot;
fWhatToShow = other.fWhatToShow;
fNodeFilter = other.fNodeFilter;
fForward = other.fForward;
fDetached = other.fDetached;
fExpandEntityReferences = other.fExpandEntityReferences;
fDocument = other.fDocument;
return *this;
}
DOMNodeIteratorImpl::~DOMNodeIteratorImpl ()
{
fDetached = false;
}
void DOMNodeIteratorImpl::detach ()
{
fDetached = true;
((DOMDocumentImpl *)fDocument)->removeNodeIterator(this);
}
DOMNode* DOMNodeIteratorImpl::getRoot() {
return fRoot;
}
// Implementation Note: Note that the iterator looks at whatToShow
// and filter values at each call, and therefore one _could_ add
// setters for these values and alter them while iterating!
/** Return the whatToShow value */
unsigned long DOMNodeIteratorImpl::getWhatToShow () {
return fWhatToShow;
}
/** Return the filter */
DOMNodeFilter* DOMNodeIteratorImpl::getFilter () {
return fNodeFilter;
}
/** Get the expandEntity reference flag. */
bool DOMNodeIteratorImpl::getExpandEntityReferences()
{
return fExpandEntityReferences;
}
/** Return the next DOMNode* in the Iterator. The node is the next node in
* depth-first order which also passes the filter, and whatToShow.
* A 0 return means either that
*/
DOMNode* DOMNodeIteratorImpl::nextNode () {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
// if root is 0 there is no next node->
if (!fRoot)
return 0;
DOMNode* aNextNode = fCurrentNode;
bool accepted = false; // the next node has not been accepted.
while (!accepted) {
// if last direction is not forward, repeat node->
if (!fForward && (aNextNode != 0)) {
//System.out.println("nextNode():!fForward:"+fCurrentNode.getNodeName());
aNextNode = fCurrentNode;
} else {
// else get the next node via depth-first
aNextNode = nextNode(aNextNode, true);
}
fForward = true; //REVIST: should direction be set forward before 0 check?
// nothing in the list. return 0.
if (!aNextNode) return 0;
// does node pass the filters and whatToShow?
accepted = acceptNode(aNextNode);
if (accepted) {
// if so, then the node is the current node->
fCurrentNode = aNextNode;
return fCurrentNode;
}
}
// no nodes, or no accepted nodes.
return 0;
}
/** Return the previous Node in the Iterator. The node is the next node in
* _backwards_ depth-first order which also passes the filter, and whatToShow.
*/
DOMNode* DOMNodeIteratorImpl::previousNode () {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
// if the root is 0, or the current node is 0, return 0.
if (!fRoot || !fCurrentNode) return 0;
DOMNode* aPreviousNode = fCurrentNode;
bool accepted = false;
while (!accepted) {
if (fForward && (aPreviousNode != 0)) {
//repeat last node->
aPreviousNode = fCurrentNode;
} else {
// get previous node in backwards depth first order.
aPreviousNode = previousNode(aPreviousNode);
}
// we are going backwards
fForward = false;
// if the new previous node is 0, we're at head or past the root,
// so return 0.
if (!aPreviousNode) return 0;
// check if node passes filters and whatToShow.
accepted = acceptNode(aPreviousNode);
if (accepted) {
// if accepted, update the current node, and return it.
fCurrentNode = aPreviousNode;
return fCurrentNode;
}
}
// there are no nodes?
return 0;
}
/** The node is accepted if it passes the whatToShow and the filter. */
bool DOMNodeIteratorImpl::acceptNode (DOMNode* node) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
if (fNodeFilter == 0) {
return ((fWhatToShow & (1 << (node->getNodeType() - 1))) != 0);
} else {
return ((fWhatToShow & (1 << (node->getNodeType() - 1))) != 0)
&& fNodeFilter->acceptNode(node) == DOMNodeFilter::FILTER_ACCEPT;
}
}
/** Return node, if matches or any parent if matches. */
DOMNode* DOMNodeIteratorImpl::matchNodeOrParent (DOMNode* node) {
for (DOMNode* n = fCurrentNode; n != fRoot; n = n->getParentNode()) {
if (node == n) return n;
}
return 0;
}
/** The method nextNode(DOMNode, bool) returns the next node
* from the actual DOM tree.
*
* The bool visitChildren determines whether to visit the children.
* The result is the nextNode.
*/
DOMNode* DOMNodeIteratorImpl::nextNode (DOMNode* node, bool visitChildren) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
if (!node) return fRoot;
DOMNode* result = 0;
// only check children if we visit children.
if (visitChildren) {
//if hasChildren, return 1st child.
if (node->hasChildNodes()) {
result = node->getFirstChild();
return result;
}
}
// if hasSibling, return sibling
if (node != fRoot) {
result = node->getNextSibling();
if (result != 0) return result;
// return parent's 1st sibling.
DOMNode* parent = node->getParentNode();
while ((parent != 0) && parent != fRoot) {
result = parent->getNextSibling();
if (result != 0) {
return result;
} else {
parent = parent->getParentNode();
}
} // while (parent != 0 && parent != fRoot) {
}
// end of list, return 0
return 0;
}
/** The method previousNode(DOMNode) returns the previous node
* from the actual DOM tree.
*/
DOMNode* DOMNodeIteratorImpl::previousNode (DOMNode* node) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
DOMNode* result = 0;
// if we're at the root, return 0.
if (node == fRoot)
return 0;
// get sibling
result = node->getPreviousSibling();
if (!result) {
//if 1st sibling, return parent
result = node->getParentNode();
return result;
}
// if sibling has children, keep getting last child of child.
if (result->hasChildNodes()) {
while (result->hasChildNodes()) {
result = result->getLastChild();
}
}
return result;
}
/** Fix-up the iterator on a remove. Called by DOM or otherwise,
* before an actual DOM remove.
*/
void DOMNodeIteratorImpl::removeNode (DOMNode* node) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
// Implementation note: Fix-up means setting the current node properly
// after a remove.
if (!node) return;
DOMNode* deleted = matchNodeOrParent(node);
if (!deleted) return;
if (fForward) {
fCurrentNode = previousNode(deleted);
} else
// if (!fForward)
{
DOMNode* next = nextNode(deleted, false);
if (next != 0) {
// normal case: there _are_ nodes following this in the iterator.
fCurrentNode = next;
} else {
// the last node in the iterator is to be removed,
// so we set the current node to be the previous one.
fCurrentNode = previousNode(deleted);
fForward = true;
}
}
}
void DOMNodeIteratorImpl::release()
{
detach();
// for performance reason, do not recycle pointer
// chance that this is allocated again and again is not usual
}
XERCES_CPP_NAMESPACE_END
<commit_msg>Take into account the fExpandEntityReferences setting [jira# 1303]<commit_after>/*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id$
*/
//////////////////////////////////////////////////////////////////////
// DOMNodeIteratorImpl.cpp: implementation of the DOMNodeIteratorImpl class.
//
//////////////////////////////////////////////////////////////////////
#include "DOMNodeIteratorImpl.hpp"
#include "DOMDocumentImpl.hpp"
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
DOMNodeIteratorImpl::DOMNodeIteratorImpl (DOMDocument* doc,
DOMNode* root,
unsigned long whatToShow,
DOMNodeFilter* nodeFilter,
bool expandEntityRef)
: fRoot(root),
fDocument(doc),
fWhatToShow(whatToShow),
fNodeFilter(nodeFilter),
fExpandEntityReferences(expandEntityRef),
fDetached(false),
fCurrentNode(0),
fForward(true)
{
}
DOMNodeIteratorImpl::DOMNodeIteratorImpl ( const DOMNodeIteratorImpl& toCopy)
: fRoot(toCopy.fRoot),
fDocument(toCopy.fDocument),
fWhatToShow(toCopy.fWhatToShow),
fNodeFilter(toCopy.fNodeFilter),
fExpandEntityReferences(toCopy.fExpandEntityReferences),
fDetached(toCopy.fDetached),
fCurrentNode(toCopy.fCurrentNode),
fForward(toCopy.fForward)
{
}
DOMNodeIteratorImpl& DOMNodeIteratorImpl::operator= (const DOMNodeIteratorImpl& other) {
fRoot = other.fRoot;
fCurrentNode = other.fRoot;
fWhatToShow = other.fWhatToShow;
fNodeFilter = other.fNodeFilter;
fForward = other.fForward;
fDetached = other.fDetached;
fExpandEntityReferences = other.fExpandEntityReferences;
fDocument = other.fDocument;
return *this;
}
DOMNodeIteratorImpl::~DOMNodeIteratorImpl ()
{
fDetached = false;
}
void DOMNodeIteratorImpl::detach ()
{
fDetached = true;
((DOMDocumentImpl *)fDocument)->removeNodeIterator(this);
}
DOMNode* DOMNodeIteratorImpl::getRoot() {
return fRoot;
}
// Implementation Note: Note that the iterator looks at whatToShow
// and filter values at each call, and therefore one _could_ add
// setters for these values and alter them while iterating!
/** Return the whatToShow value */
unsigned long DOMNodeIteratorImpl::getWhatToShow () {
return fWhatToShow;
}
/** Return the filter */
DOMNodeFilter* DOMNodeIteratorImpl::getFilter () {
return fNodeFilter;
}
/** Get the expandEntity reference flag. */
bool DOMNodeIteratorImpl::getExpandEntityReferences()
{
return fExpandEntityReferences;
}
/** Return the next DOMNode* in the Iterator. The node is the next node in
* depth-first order which also passes the filter, and whatToShow.
* A 0 return means either that
*/
DOMNode* DOMNodeIteratorImpl::nextNode () {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
// if root is 0 there is no next node->
if (!fRoot)
return 0;
DOMNode* aNextNode = fCurrentNode;
bool accepted = false; // the next node has not been accepted.
while (!accepted) {
// if last direction is not forward, repeat node->
if (!fForward && (aNextNode != 0)) {
//System.out.println("nextNode():!fForward:"+fCurrentNode.getNodeName());
aNextNode = fCurrentNode;
} else {
// else get the next node via depth-first
aNextNode = nextNode(aNextNode, true);
}
fForward = true; //REVIST: should direction be set forward before 0 check?
// nothing in the list. return 0.
if (!aNextNode) return 0;
// does node pass the filters and whatToShow?
accepted = acceptNode(aNextNode);
if (accepted) {
// if so, then the node is the current node->
fCurrentNode = aNextNode;
return fCurrentNode;
}
}
// no nodes, or no accepted nodes.
return 0;
}
/** Return the previous Node in the Iterator. The node is the next node in
* _backwards_ depth-first order which also passes the filter, and whatToShow.
*/
DOMNode* DOMNodeIteratorImpl::previousNode () {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
// if the root is 0, or the current node is 0, return 0.
if (!fRoot || !fCurrentNode) return 0;
DOMNode* aPreviousNode = fCurrentNode;
bool accepted = false;
while (!accepted) {
if (fForward && (aPreviousNode != 0)) {
//repeat last node->
aPreviousNode = fCurrentNode;
} else {
// get previous node in backwards depth first order.
aPreviousNode = previousNode(aPreviousNode);
}
// we are going backwards
fForward = false;
// if the new previous node is 0, we're at head or past the root,
// so return 0.
if (!aPreviousNode) return 0;
// check if node passes filters and whatToShow.
accepted = acceptNode(aPreviousNode);
if (accepted) {
// if accepted, update the current node, and return it.
fCurrentNode = aPreviousNode;
return fCurrentNode;
}
}
// there are no nodes?
return 0;
}
/** The node is accepted if it passes the whatToShow and the filter. */
bool DOMNodeIteratorImpl::acceptNode (DOMNode* node) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
if (fNodeFilter == 0) {
return ((fWhatToShow & (1 << (node->getNodeType() - 1))) != 0);
} else {
return ((fWhatToShow & (1 << (node->getNodeType() - 1))) != 0)
&& fNodeFilter->acceptNode(node) == DOMNodeFilter::FILTER_ACCEPT;
}
}
/** Return node, if matches or any parent if matches. */
DOMNode* DOMNodeIteratorImpl::matchNodeOrParent (DOMNode* node) {
for (DOMNode* n = fCurrentNode; n != fRoot; n = n->getParentNode()) {
if (node == n) return n;
}
return 0;
}
/** The method nextNode(DOMNode, bool) returns the next node
* from the actual DOM tree.
*
* The bool visitChildren determines whether to visit the children.
* The result is the nextNode.
*/
DOMNode* DOMNodeIteratorImpl::nextNode (DOMNode* node, bool visitChildren) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
if (!node) return fRoot;
DOMNode* result = 0;
// only check children if we visit children.
if (visitChildren) {
//if hasChildren, return 1st child.
if ((fExpandEntityReferences || node->getNodeType()!=DOMNode::ENTITY_REFERENCE_NODE) &&
node->hasChildNodes()) {
result = node->getFirstChild();
return result;
}
}
// if hasSibling, return sibling
if (node != fRoot) {
result = node->getNextSibling();
if (result != 0) return result;
// return parent's 1st sibling.
DOMNode* parent = node->getParentNode();
while ((parent != 0) && parent != fRoot) {
result = parent->getNextSibling();
if (result != 0) {
return result;
} else {
parent = parent->getParentNode();
}
} // while (parent != 0 && parent != fRoot) {
}
// end of list, return 0
return 0;
}
/** The method previousNode(DOMNode) returns the previous node
* from the actual DOM tree.
*/
DOMNode* DOMNodeIteratorImpl::previousNode (DOMNode* node) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
DOMNode* result = 0;
// if we're at the root, return 0.
if (node == fRoot)
return 0;
// get sibling
result = node->getPreviousSibling();
if (!result) {
//if 1st sibling, return parent
result = node->getParentNode();
return result;
}
// if sibling has children, keep getting last child of child.
if (result->hasChildNodes()) {
while ((fExpandEntityReferences || result->getNodeType()!=DOMNode::ENTITY_REFERENCE_NODE) &&
result->hasChildNodes()) {
result = result->getLastChild();
}
}
return result;
}
/** Fix-up the iterator on a remove. Called by DOM or otherwise,
* before an actual DOM remove.
*/
void DOMNodeIteratorImpl::removeNode (DOMNode* node) {
if (fDetached)
throw DOMException(DOMException::INVALID_STATE_ERR, 0, GetDOMNodeIteratorMemoryManager);
// Implementation note: Fix-up means setting the current node properly
// after a remove.
if (!node) return;
DOMNode* deleted = matchNodeOrParent(node);
if (!deleted) return;
if (fForward) {
fCurrentNode = previousNode(deleted);
} else
// if (!fForward)
{
DOMNode* next = nextNode(deleted, false);
if (next != 0) {
// normal case: there _are_ nodes following this in the iterator.
fCurrentNode = next;
} else {
// the last node in the iterator is to be removed,
// so we set the current node to be the previous one.
fCurrentNode = previousNode(deleted);
fForward = true;
}
}
}
void DOMNodeIteratorImpl::release()
{
detach();
// for performance reason, do not recycle pointer
// chance that this is allocated again and again is not usual
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.