text
stringlengths 54
60.6k
|
---|
<commit_before>/**
This is a tool shipped by 'Aleph - A Library for Exploring Persistent
Homology'.
Its purpose is to calculate zero-dimensional persistence diagrams of
spectra. This is supposed to yield a simple feature descriptor which
in turn might be used in machine learning pipepline.
Input: filename
Output: persistence diagram
The persistence diagram represents the superlevel set filtration of
the input data. This permits us to quantify the number of maxima in
a data set.
Original author: Bastian Rieck
*/
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/ConnectedComponents.hh>
#include <aleph/topology/io/FlexSpectrum.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <algorithm>
#include <iostream>
#include <fstream> // FIXME: remove or make output configurable...
#include <string>
#include <tuple>
#include <cassert>
using DataType = unsigned;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
int main( int argc, char** argv )
{
if( argc <= 1 )
return -1;
std::string input = argv[1];
// Parse input -------------------------------------------------------
std::cerr << "* Reading '" << input << "'...";
SimplicialComplex K;
aleph::topology::io::FlexSpectrumReader reader;
reader( input, K );
std::cerr << "finished\n";
// Calculate persistent homology -------------------------------------
std::cerr << "* Calculating persistent homology...";
using PersistencePairing = aleph::PersistencePairing<VertexType>;
using Traits = aleph::traits::PersistencePairingCalculation<PersistencePairing>;
auto&& tuple
= aleph::calculateZeroDimensionalPersistenceDiagram<Simplex, Traits>( K );
std::cerr << "finished\n";
// Output ------------------------------------------------------------
auto&& D = std::get<0>( tuple );
auto&& pairing = std::get<1>( tuple );
assert( D.dimension() == 0 );
assert( D.betti() == 1 );
D.removeDiagonal();
// This ensures that the global maximum is paired with the global
// minimum of the persistence diagram. This is valid because each
// function has finite support and is bounded from below.
std::transform( D.begin(), D.end(), D.begin(),
[] ( const PersistenceDiagram::Point& p )
{
// TODO: we should check whether zero is really the smallest
// value
if( p.isUnpaired() )
return PersistenceDiagram::Point( p.x(), DataType() );
else
return PersistenceDiagram::Point( p );
}
);
std::cout << D << "\n";
// Transform input data (experimental) -------------------------------
auto&& map = reader.getIndexToValueMap();
std::map<double, double> transformedFunction;
for( auto&& pair : pairing )
{
auto&& creator = pair.first;
auto&& destroyer = pair.second;
auto&& sigma = K.at( creator );
auto&& tau = destroyer < K.size() ? K.at( destroyer ) : Simplex( {0,1}, DataType() );
assert( sigma.dimension() == 0 );
assert( tau.dimension() == 1 );
auto persistence = std::abs( double( sigma.data() ) - double( tau.data() ) );
auto x = map.at( sigma[0] );
transformedFunction[ x ] = persistence;
}
std::ofstream out( "/tmp/F.txt" );
for( auto&& pair : transformedFunction )
out << pair.first << "\t" << pair.second << "\n";
}
<commit_msg>Improved support for other options<commit_after>/**
This is a tool shipped by 'Aleph - A Library for Exploring Persistent
Homology'.
Its purpose is to calculate zero-dimensional persistence diagrams of
spectra. This is supposed to yield a simple feature descriptor which
in turn might be used in machine learning pipepline.
Input: filename
Output: persistence diagram
The persistence diagram represents the superlevel set filtration of
the input data. This permits us to quantify the number of maxima in
a data set.
Original author: Bastian Rieck
*/
#include <aleph/persistenceDiagrams/PersistenceDiagram.hh>
#include <aleph/persistentHomology/Calculation.hh>
#include <aleph/persistentHomology/ConnectedComponents.hh>
#include <aleph/topology/io/FlexSpectrum.hh>
#include <aleph/topology/Simplex.hh>
#include <aleph/topology/SimplicialComplex.hh>
#include <algorithm>
#include <iostream>
#include <fstream> // FIXME: remove or make output configurable...
#include <string>
#include <tuple>
#include <cassert>
#include <cmath>
#include <getopt.h>
using DataType = unsigned;
using VertexType = unsigned;
using Simplex = aleph::topology::Simplex<DataType, VertexType>;
using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>;
using PersistenceDiagram = aleph::PersistenceDiagram<DataType>;
int main( int argc, char** argv )
{
bool normalize = false;
std::string mode = "diagram";
{
static option commandLineOptions[] =
{
{ "mode" , required_argument, nullptr, 'm' },
{ "normalize", no_argument , nullptr, 'n' },
{ nullptr , 0 , nullptr, 0 }
};
int option = 0;
while( ( option = getopt_long( argc, argv, "m:n", commandLineOptions, nullptr ) ) != -1 )
{
switch( option )
{
case 'm':
mode = optarg;
break;
case 'n':
normalize = true;
break;
}
}
}
if( ( argc - optind ) < 1 )
return -1;
std::string input = argv[optind++];
// Parse input -------------------------------------------------------
std::cerr << "* Reading '" << input << "'...";
SimplicialComplex K;
aleph::topology::io::FlexSpectrumReader reader;
if( normalize )
reader.normalize( true );
reader( input, K );
std::cerr << "finished\n";
// Calculate persistent homology -------------------------------------
std::cerr << "* Calculating persistent homology...";
using PersistencePairing = aleph::PersistencePairing<VertexType>;
using Traits = aleph::traits::PersistencePairingCalculation<PersistencePairing>;
auto&& tuple
= aleph::calculateZeroDimensionalPersistenceDiagram<Simplex, Traits>( K );
std::cerr << "finished\n";
// Output ------------------------------------------------------------
auto&& D = std::get<0>( tuple );
auto&& pairing = std::get<1>( tuple );
assert( D.dimension() == 0 );
assert( D.betti() == 1 );
D.removeDiagonal();
// This ensures that the global maximum is paired with the global
// minimum of the persistence diagram. This is valid because each
// function has finite support and is bounded from below.
std::transform( D.begin(), D.end(), D.begin(),
[] ( const PersistenceDiagram::Point& p )
{
// TODO: we should check whether zero is really the smallest
// value
if( p.isUnpaired() )
return PersistenceDiagram::Point( p.x(), DataType() );
else
return PersistenceDiagram::Point( p );
}
);
std::cout << D << "\n";
// Transform input data (experimental) -------------------------------
auto&& map = reader.getIndexToValueMap();
std::map<double, double> transformedFunction;
for( auto&& pair : pairing )
{
auto&& creator = pair.first;
auto&& destroyer = pair.second;
auto&& sigma = K.at( creator );
auto&& tau = destroyer < K.size() ? K.at( destroyer ) : Simplex( {0,1}, DataType() );
assert( sigma.dimension() == 0 );
assert( tau.dimension() == 1 );
auto persistence = std::abs( double( sigma.data() ) - double( tau.data() ) );
auto x = map.at( sigma[0] );
transformedFunction[ x ] = persistence;
}
std::ofstream out( "/tmp/F.txt" );
for( auto&& pair : transformedFunction )
out << pair.first << "\t" << pair.second << "\n";
}
<|endoftext|> |
<commit_before>#include "binary_io.hpp"
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const std::string& s)
{
stream << s.length();
stream.put(s.c_str(), s.length() * sizeof(char));
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, std::string& s)
{
size_t len;
stream >> len;
s.resize(len);
stream.get(&s[0], len * sizeof(char));
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const SubstitutionModel& sm)
{
stream << sm.base_freqs();
stream << sm.subst_rates();
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const Model& m)
{
// if (m.param_mode(PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER) != ParamValue::undefined)
stream << m.brlen_scaler();
// if (m.param_mode(PLLMOD_OPT_PARAM_PINV) != ParamValue::undefined)
stream << m.pinv();
stream << m.num_ratecats();
if (m.num_ratecats() > 1)
{
stream << m.ratehet_mode();
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
stream << m.alpha();
stream << m.ratecat_weights();
stream << m.ratecat_rates();
}
/* store subst model parameters only if they were estimated */
if (m.param_mode(PLLMOD_OPT_PARAM_FREQUENCIES) == ParamValue::ML ||
m.param_mode(PLLMOD_OPT_PARAM_SUBST_RATES) == ParamValue::ML)
{
stream << m.num_submodels();
for (size_t i = 0; i < m.num_submodels(); ++i)
{
stream << m.submodel(i);
}
}
return stream;
}
static bool save_modparam(const Model& m, ModelBinaryFmt fmt, unsigned int param)
{
auto pmode = m.param_mode(param);
switch (pmode)
{
case ParamValue::model:
case ParamValue::undefined:
return false;
case ParamValue::user:
return (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::def);
case ParamValue::empirical:
return (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::params);
case ParamValue::ML:
return (fmt != ModelBinaryFmt::def);
default:
assert(0);
}
return true;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, std::tuple<const Model&, ModelBinaryFmt> bm)
{
auto m = std::get<0>(bm);
auto fmt = std::get<1>(bm);
stream << fmt;
if (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::def)
{
auto s = m.to_string(false);
stream << s;
}
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER))
stream << m.brlen_scaler();
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_PINV))
stream << m.pinv();
if (m.num_ratecats() > 1)
{
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_ALPHA))
stream << m.alpha();
}
else
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_RATE_WEIGHTS))
stream << m.ratecat_weights();
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREE_RATES))
stream << m.ratecat_rates();
}
}
for (size_t i = 0; i < m.num_submodels(); ++i)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREQUENCIES))
stream << m.submodel(i).base_freqs();
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_SUBST_RATES))
stream << m.submodel(i).subst_rates();
}
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, Model& m)
{
// if (m.param_mode(PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER) != ParamValue::undefined)
m.brlen_scaler(stream.get<double>());
// if (m.param_mode(PLLMOD_OPT_PARAM_PINV) != ParamValue::undefined)
m.pinv(stream.get<double>());
auto num_ratecats = stream.get<unsigned int>();
assert(num_ratecats == m.num_ratecats());
if (m.num_ratecats() > 1)
{
auto ratehet_mode = stream.get<unsigned int>();
assert(ratehet_mode == m.ratehet_mode());
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
m.alpha(stream.get<double>());
m.ratecat_weights(stream.get<doubleVector>());
m.ratecat_rates(stream.get<doubleVector>());
}
if (m.param_mode(PLLMOD_OPT_PARAM_FREQUENCIES) == ParamValue::ML ||
m.param_mode(PLLMOD_OPT_PARAM_SUBST_RATES) == ParamValue::ML)
{
auto num_submodels = stream.get<unsigned int>();
assert(num_submodels == m.num_submodels());
for (size_t i = 0; i < m.num_submodels(); ++i)
{
m.base_freqs(i, stream.get<doubleVector>());
m.subst_rates(i, stream.get<doubleVector>());
}
}
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, std::tuple<Model&, ModelBinaryFmt> bm)
{
auto& m = std::get<0>(bm);
auto fmt = std::get<1>(bm);
if (stream.get<ModelBinaryFmt>() != fmt)
throw std::runtime_error("Invalid binary model format!");
if (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::def)
{
std::string s = stream.get<std::string>();
// printf("\n%s\n", s.c_str());
m = Model(DataType::autodetect, s);
}
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER))
m.brlen_scaler(stream.get<double>());
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_PINV))
m.pinv(stream.get<double>());
if (m.num_ratecats() > 1)
{
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_ALPHA))
m.alpha(stream.get<double>());
}
else
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_RATE_WEIGHTS))
m.ratecat_weights(stream.get<doubleVector>());
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREE_RATES))
m.ratecat_rates(stream.get<doubleVector>());
}
}
for (size_t i = 0; i < m.num_submodels(); ++i)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREQUENCIES))
m.base_freqs(i, stream.get<doubleVector>());
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_SUBST_RATES))
m.subst_rates(i, stream.get<doubleVector>());
}
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const TreeCollection& c)
{
stream << c.size();
for (const auto tree: c)
stream << tree.first << tree.second;
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, TreeCollection& c)
{
auto size = stream.get<size_t>();
for (size_t i = 0; i < size; ++i)
{
auto score = stream.get<double>();
c.push_back(score, stream.get<TreeTopology>());
}
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const MSA& m)
{
stream << m.size();
stream << m.length();
stream << m.weights();
for (size_t i = 0; i < m.size(); ++i)
{
auto seq = m.at(i);
assert(seq.length() == m.length());
stream.write(seq.c_str(), m.length());
}
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, MSA& m)
{
auto taxa_count = stream.get<size_t>();
auto pat_count = stream.get<size_t>();
m = MSA(pat_count);
m.weights(stream.get<WeightVector>());
std::string seq(pat_count, 0);
for (size_t i = 0; i < taxa_count; ++i)
{
stream.read(&seq[0], pat_count);
m.append(seq);
}
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const PartitionStats& ps)
{
stream << ps.site_count;
stream << ps.pattern_count;
stream << ps.inv_count;
stream << ps.gap_prop;
stream << ps.emp_base_freqs;
stream << ps.emp_subst_rates;
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, PartitionStats& ps)
{
stream >> ps.site_count;
stream >> ps.pattern_count;
stream >> ps.inv_count;
stream >> ps.gap_prop;
stream >> ps.emp_base_freqs;
stream >> ps.emp_subst_rates;
return stream;
}
<commit_msg>fix bug in binary MSA writing (failed to save models with equal params)<commit_after>#include "binary_io.hpp"
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const std::string& s)
{
stream << s.length();
stream.put(s.c_str(), s.length() * sizeof(char));
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, std::string& s)
{
size_t len;
stream >> len;
s.resize(len);
stream.get(&s[0], len * sizeof(char));
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const SubstitutionModel& sm)
{
stream << sm.base_freqs();
stream << sm.subst_rates();
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const Model& m)
{
// if (m.param_mode(PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER) != ParamValue::undefined)
stream << m.brlen_scaler();
// if (m.param_mode(PLLMOD_OPT_PARAM_PINV) != ParamValue::undefined)
stream << m.pinv();
stream << m.num_ratecats();
if (m.num_ratecats() > 1)
{
stream << m.ratehet_mode();
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
stream << m.alpha();
stream << m.ratecat_weights();
stream << m.ratecat_rates();
}
/* store subst model parameters only if they were estimated */
if (m.param_mode(PLLMOD_OPT_PARAM_FREQUENCIES) == ParamValue::ML ||
m.param_mode(PLLMOD_OPT_PARAM_SUBST_RATES) == ParamValue::ML)
{
stream << m.num_submodels();
for (size_t i = 0; i < m.num_submodels(); ++i)
{
stream << m.submodel(i);
}
}
return stream;
}
static bool save_modparam(const Model& m, ModelBinaryFmt fmt, unsigned int param)
{
auto pmode = m.param_mode(param);
switch (pmode)
{
case ParamValue::model:
case ParamValue::equal:
case ParamValue::undefined:
return false;
case ParamValue::user:
return (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::def);
case ParamValue::empirical:
return (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::params);
case ParamValue::ML:
return (fmt != ModelBinaryFmt::def);
default:
assert(0);
}
return true;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, std::tuple<const Model&, ModelBinaryFmt> bm)
{
auto m = std::get<0>(bm);
auto fmt = std::get<1>(bm);
stream << fmt;
if (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::def)
{
auto s = m.to_string(false);
stream << s;
}
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER))
stream << m.brlen_scaler();
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_PINV))
stream << m.pinv();
if (m.num_ratecats() > 1)
{
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_ALPHA))
stream << m.alpha();
}
else
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_RATE_WEIGHTS))
stream << m.ratecat_weights();
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREE_RATES))
stream << m.ratecat_rates();
}
}
for (size_t i = 0; i < m.num_submodels(); ++i)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREQUENCIES))
stream << m.submodel(i).base_freqs();
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_SUBST_RATES))
stream << m.submodel(i).subst_rates();
}
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, Model& m)
{
// if (m.param_mode(PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER) != ParamValue::undefined)
m.brlen_scaler(stream.get<double>());
// if (m.param_mode(PLLMOD_OPT_PARAM_PINV) != ParamValue::undefined)
m.pinv(stream.get<double>());
auto num_ratecats = stream.get<unsigned int>();
assert(num_ratecats == m.num_ratecats());
if (m.num_ratecats() > 1)
{
auto ratehet_mode = stream.get<unsigned int>();
assert(ratehet_mode == m.ratehet_mode());
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
m.alpha(stream.get<double>());
m.ratecat_weights(stream.get<doubleVector>());
m.ratecat_rates(stream.get<doubleVector>());
}
if (m.param_mode(PLLMOD_OPT_PARAM_FREQUENCIES) == ParamValue::ML ||
m.param_mode(PLLMOD_OPT_PARAM_SUBST_RATES) == ParamValue::ML)
{
auto num_submodels = stream.get<unsigned int>();
assert(num_submodels == m.num_submodels());
for (size_t i = 0; i < m.num_submodels(); ++i)
{
m.base_freqs(i, stream.get<doubleVector>());
m.subst_rates(i, stream.get<doubleVector>());
}
}
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, std::tuple<Model&, ModelBinaryFmt> bm)
{
auto& m = std::get<0>(bm);
auto fmt = std::get<1>(bm);
if (stream.get<ModelBinaryFmt>() != fmt)
throw std::runtime_error("Invalid binary model format!");
if (fmt == ModelBinaryFmt::full || fmt == ModelBinaryFmt::def)
{
std::string s = stream.get<std::string>();
// printf("\n%s\n", s.c_str());
m = Model(DataType::autodetect, s);
}
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_BRANCH_LEN_SCALER))
m.brlen_scaler(stream.get<double>());
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_PINV))
m.pinv(stream.get<double>());
if (m.num_ratecats() > 1)
{
if (m.ratehet_mode() == PLLMOD_UTIL_MIXTYPE_GAMMA)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_ALPHA))
m.alpha(stream.get<double>());
}
else
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_RATE_WEIGHTS))
m.ratecat_weights(stream.get<doubleVector>());
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREE_RATES))
m.ratecat_rates(stream.get<doubleVector>());
}
}
for (size_t i = 0; i < m.num_submodels(); ++i)
{
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_FREQUENCIES))
m.base_freqs(i, stream.get<doubleVector>());
if (save_modparam(m, fmt, PLLMOD_OPT_PARAM_SUBST_RATES))
m.subst_rates(i, stream.get<doubleVector>());
}
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const TreeCollection& c)
{
stream << c.size();
for (const auto tree: c)
stream << tree.first << tree.second;
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, TreeCollection& c)
{
auto size = stream.get<size_t>();
for (size_t i = 0; i < size; ++i)
{
auto score = stream.get<double>();
c.push_back(score, stream.get<TreeTopology>());
}
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const MSA& m)
{
stream << m.size();
stream << m.length();
stream << m.weights();
for (size_t i = 0; i < m.size(); ++i)
{
auto seq = m.at(i);
assert(seq.length() == m.length());
stream.write(seq.c_str(), m.length());
}
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, MSA& m)
{
auto taxa_count = stream.get<size_t>();
auto pat_count = stream.get<size_t>();
m = MSA(pat_count);
m.weights(stream.get<WeightVector>());
std::string seq(pat_count, 0);
for (size_t i = 0; i < taxa_count; ++i)
{
stream.read(&seq[0], pat_count);
m.append(seq);
}
return stream;
}
BasicBinaryStream& operator<<(BasicBinaryStream& stream, const PartitionStats& ps)
{
stream << ps.site_count;
stream << ps.pattern_count;
stream << ps.inv_count;
stream << ps.gap_prop;
stream << ps.emp_base_freqs;
stream << ps.emp_subst_rates;
return stream;
}
BasicBinaryStream& operator>>(BasicBinaryStream& stream, PartitionStats& ps)
{
stream >> ps.site_count;
stream >> ps.pattern_count;
stream >> ps.inv_count;
stream >> ps.gap_prop;
stream >> ps.emp_base_freqs;
stream >> ps.emp_subst_rates;
return stream;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 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 the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "browserapplication.h"
#include "bookmarks.h"
#include "browsermainwindow.h"
#include "cookiejar.h"
#include "downloadmanager.h"
#include "history.h"
#include "networkaccessmanager.h"
#include "tabwidget.h"
#include "webview.h"
#include <QtCore/QBuffer>
#include <QtCore/QDir>
#include <QtCore/QLibraryInfo>
#include <QtCore/QSettings>
#include <QtCore/QTextStream>
#include <QtCore/QTranslator>
#include <QtGui/QDesktopServices>
#include <QtGui/QFileOpenEvent>
#include <QtGui/QMessageBox>
#include <QtNetwork/QLocalServer>
#include <QtNetwork/QLocalSocket>
#include <QtNetwork/QNetworkProxy>
#include <QtNetwork/QSslSocket>
#include <QtWebKit/QWebSettings>
#include <QtCore/QDebug>
DownloadManager *BrowserApplication::s_downloadManager = 0;
HistoryManager *BrowserApplication::s_historyManager = 0;
NetworkAccessManager *BrowserApplication::s_networkAccessManager = 0;
BookmarksManager *BrowserApplication::s_bookmarksManager = 0;
BrowserApplication::BrowserApplication(int &argc, char **argv)
: QApplication(argc, argv)
, m_localServer(0)
{
QCoreApplication::setOrganizationName(QLatin1String("Trolltech"));
QCoreApplication::setApplicationName(QLatin1String("demobrowser"));
QCoreApplication::setApplicationVersion(QLatin1String("0.1"));
#ifdef Q_WS_QWS
// Use a different server name for QWS so we can run an X11
// browser and a QWS browser in parallel on the same machine for
// debugging
QString serverName = QCoreApplication::applicationName() + QLatin1String("_qws");
#else
QString serverName = QCoreApplication::applicationName();
#endif
QLocalSocket socket;
socket.connectToServer(serverName);
if (socket.waitForConnected(500)) {
QTextStream stream(&socket);
QStringList args = QCoreApplication::arguments();
if (args.count() > 1)
stream << args.last();
else
stream << QString();
stream.flush();
socket.waitForBytesWritten();
return;
}
#if defined(Q_WS_MAC)
QApplication::setQuitOnLastWindowClosed(false);
#else
QApplication::setQuitOnLastWindowClosed(true);
#endif
m_localServer = new QLocalServer(this);
connect(m_localServer, SIGNAL(newConnection()),
this, SLOT(newLocalSocketConnection()));
if (!m_localServer->listen(serverName)) {
if (m_localServer->serverError() == QAbstractSocket::AddressInUseError
&& QFile::exists(m_localServer->serverName())) {
QFile::remove(m_localServer->serverName());
m_localServer->listen(serverName);
}
}
#ifndef QT_NO_OPENSSL
if (!QSslSocket::supportsSsl()) {
QMessageBox::information(0, "Demo Browser",
"This system does not support OpenSSL. SSL websites will not be available.");
}
#endif
QDesktopServices::setUrlHandler(QLatin1String("http"), this, "openUrl");
QString localSysName = QLocale::system().name();
installTranslator(QLatin1String("qt_") + localSysName);
QSettings settings;
settings.beginGroup(QLatin1String("sessions"));
m_lastSession = settings.value(QLatin1String("lastSession")).toByteArray();
settings.endGroup();
#if defined(Q_WS_MAC)
connect(this, SIGNAL(lastWindowClosed()),
this, SLOT(lastWindowClosed()));
#endif
QTimer::singleShot(0, this, SLOT(postLaunch()));
}
BrowserApplication::~BrowserApplication()
{
delete s_downloadManager;
for (int i = 0; i < m_mainWindows.size(); ++i) {
BrowserMainWindow *window = m_mainWindows.at(i);
delete window;
}
delete s_networkAccessManager;
delete s_bookmarksManager;
}
#if defined(Q_WS_MAC)
void BrowserApplication::lastWindowClosed()
{
clean();
BrowserMainWindow *mw = new BrowserMainWindow;
mw->slotHome();
m_mainWindows.prepend(mw);
}
#endif
BrowserApplication *BrowserApplication::instance()
{
return (static_cast<BrowserApplication *>(QCoreApplication::instance()));
}
#if defined(Q_WS_MAC)
#include <QtGui/QMessageBox>
void BrowserApplication::quitBrowser()
{
clean();
int tabCount = 0;
for (int i = 0; i < m_mainWindows.count(); ++i) {
tabCount =+ m_mainWindows.at(i)->tabWidget()->count();
}
if (tabCount > 1) {
int ret = QMessageBox::warning(mainWindow(), QString(),
tr("There are %1 windows and %2 tabs open\n"
"Do you want to quit anyway?").arg(m_mainWindows.count()).arg(tabCount),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ret == QMessageBox::No)
return;
}
exit(0);
}
#endif
/*!
Any actions that can be delayed until the window is visible
*/
void BrowserApplication::postLaunch()
{
QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
if (directory.isEmpty())
directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
QWebSettings::setIconDatabasePath(directory);
setWindowIcon(QIcon(QLatin1String(":browser.svg")));
loadSettings();
// newMainWindow() needs to be called in main() for this to happen
if (m_mainWindows.count() > 0) {
QStringList args = QCoreApplication::arguments();
if (args.count() > 1)
mainWindow()->loadPage(args.last());
else
mainWindow()->slotHome();
}
BrowserApplication::historyManager();
}
void BrowserApplication::loadSettings()
{
QSettings settings;
settings.beginGroup(QLatin1String("websettings"));
QWebSettings *defaultSettings = QWebSettings::globalSettings();
QString standardFontFamily = defaultSettings->fontFamily(QWebSettings::StandardFont);
int standardFontSize = defaultSettings->fontSize(QWebSettings::DefaultFontSize);
QFont standardFont = QFont(standardFontFamily, standardFontSize);
standardFont = qVariantValue<QFont>(settings.value(QLatin1String("standardFont"), standardFont));
defaultSettings->setFontFamily(QWebSettings::StandardFont, standardFont.family());
defaultSettings->setFontSize(QWebSettings::DefaultFontSize, standardFont.pointSize());
QString fixedFontFamily = defaultSettings->fontFamily(QWebSettings::FixedFont);
int fixedFontSize = defaultSettings->fontSize(QWebSettings::DefaultFixedFontSize);
QFont fixedFont = QFont(fixedFontFamily, fixedFontSize);
fixedFont = qVariantValue<QFont>(settings.value(QLatin1String("fixedFont"), fixedFont));
defaultSettings->setFontFamily(QWebSettings::FixedFont, fixedFont.family());
defaultSettings->setFontSize(QWebSettings::DefaultFixedFontSize, fixedFont.pointSize());
defaultSettings->setAttribute(QWebSettings::JavascriptEnabled, settings.value(QLatin1String("enableJavascript"), true).toBool());
defaultSettings->setAttribute(QWebSettings::PluginsEnabled, settings.value(QLatin1String("enablePlugins"), true).toBool());
QUrl url = settings.value(QLatin1String("userStyleSheet")).toUrl();
defaultSettings->setUserStyleSheetUrl(url);
settings.endGroup();
}
QList<BrowserMainWindow*> BrowserApplication::mainWindows()
{
clean();
QList<BrowserMainWindow*> list;
for (int i = 0; i < m_mainWindows.count(); ++i)
list.append(m_mainWindows.at(i));
return list;
}
void BrowserApplication::clean()
{
// cleanup any deleted main windows first
for (int i = m_mainWindows.count() - 1; i >= 0; --i)
if (m_mainWindows.at(i).isNull())
m_mainWindows.removeAt(i);
}
void BrowserApplication::saveSession()
{
QWebSettings *globalSettings = QWebSettings::globalSettings();
if (globalSettings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
return;
clean();
QSettings settings;
settings.beginGroup(QLatin1String("sessions"));
QByteArray data;
QBuffer buffer(&data);
QDataStream stream(&buffer);
buffer.open(QIODevice::ReadWrite);
stream << m_mainWindows.count();
for (int i = 0; i < m_mainWindows.count(); ++i)
stream << m_mainWindows.at(i)->saveState();
settings.setValue(QLatin1String("lastSession"), data);
settings.endGroup();
}
bool BrowserApplication::canRestoreSession() const
{
return !m_lastSession.isEmpty();
}
void BrowserApplication::restoreLastSession()
{
QList<QByteArray> windows;
QBuffer buffer(&m_lastSession);
QDataStream stream(&buffer);
buffer.open(QIODevice::ReadOnly);
int windowCount;
stream >> windowCount;
for (int i = 0; i < windowCount; ++i) {
QByteArray windowState;
stream >> windowState;
windows.append(windowState);
}
for (int i = 0; i < windows.count(); ++i) {
BrowserMainWindow *newWindow = 0;
if (m_mainWindows.count() == 1
&& mainWindow()->tabWidget()->count() == 1
&& mainWindow()->currentTab()->url() == QUrl()) {
newWindow = mainWindow();
} else {
newWindow = newMainWindow();
}
newWindow->restoreState(windows.at(i));
}
}
bool BrowserApplication::isTheOnlyBrowser() const
{
return (m_localServer != 0);
}
void BrowserApplication::installTranslator(const QString &name)
{
QTranslator *translator = new QTranslator(this);
translator->load(name, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
QApplication::installTranslator(translator);
}
#if defined(Q_WS_MAC)
bool BrowserApplication::event(QEvent* event)
{
switch (event->type()) {
case QEvent::ApplicationActivate: {
clean();
if (!m_mainWindows.isEmpty()) {
BrowserMainWindow *mw = mainWindow();
if (mw && !mw->isMinimized()) {
mainWindow()->show();
}
return true;
}
}
case QEvent::FileOpen:
if (!m_mainWindows.isEmpty()) {
mainWindow()->loadPage(static_cast<QFileOpenEvent *>(event)->file());
return true;
}
default:
break;
}
return QApplication::event(event);
}
#endif
void BrowserApplication::openUrl(const QUrl &url)
{
mainWindow()->loadPage(url.toString());
}
BrowserMainWindow *BrowserApplication::newMainWindow()
{
BrowserMainWindow *browser = new BrowserMainWindow();
m_mainWindows.prepend(browser);
browser->show();
return browser;
}
BrowserMainWindow *BrowserApplication::mainWindow()
{
clean();
if (m_mainWindows.isEmpty())
newMainWindow();
return m_mainWindows[0];
}
void BrowserApplication::newLocalSocketConnection()
{
QLocalSocket *socket = m_localServer->nextPendingConnection();
if (!socket)
return;
socket->waitForReadyRead(1000);
QTextStream stream(socket);
QString url;
stream >> url;
if (!url.isEmpty()) {
QSettings settings;
settings.beginGroup(QLatin1String("general"));
int openLinksIn = settings.value(QLatin1String("openLinksIn"), 0).toInt();
settings.endGroup();
if (openLinksIn == 1)
newMainWindow();
else
mainWindow()->tabWidget()->newTab();
openUrl(url);
}
delete socket;
mainWindow()->raise();
mainWindow()->activateWindow();
}
CookieJar *BrowserApplication::cookieJar()
{
return (CookieJar*)networkAccessManager()->cookieJar();
}
DownloadManager *BrowserApplication::downloadManager()
{
if (!s_downloadManager) {
s_downloadManager = new DownloadManager();
}
return s_downloadManager;
}
NetworkAccessManager *BrowserApplication::networkAccessManager()
{
if (!s_networkAccessManager) {
s_networkAccessManager = new NetworkAccessManager();
s_networkAccessManager->setCookieJar(new CookieJar);
}
return s_networkAccessManager;
}
HistoryManager *BrowserApplication::historyManager()
{
if (!s_historyManager) {
s_historyManager = new HistoryManager();
QWebHistoryInterface::setDefaultInterface(s_historyManager);
}
return s_historyManager;
}
BookmarksManager *BrowserApplication::bookmarksManager()
{
if (!s_bookmarksManager) {
s_bookmarksManager = new BookmarksManager;
}
return s_bookmarksManager;
}
QIcon BrowserApplication::icon(const QUrl &url) const
{
QIcon icon = QWebSettings::iconForUrl(url);
if (!icon.isNull())
return icon.pixmap(16, 16);
if (m_defaultIcon.isNull())
m_defaultIcon = QIcon(QLatin1String(":defaulticon.png"));
return m_defaultIcon.pixmap(16, 16);
}
<commit_msg>Fix initialization of the HTML 5 offline storage.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 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 the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "browserapplication.h"
#include "bookmarks.h"
#include "browsermainwindow.h"
#include "cookiejar.h"
#include "downloadmanager.h"
#include "history.h"
#include "networkaccessmanager.h"
#include "tabwidget.h"
#include "webview.h"
#include <QtCore/QBuffer>
#include <QtCore/QDir>
#include <QtCore/QLibraryInfo>
#include <QtCore/QSettings>
#include <QtCore/QTextStream>
#include <QtCore/QTranslator>
#include <QtGui/QDesktopServices>
#include <QtGui/QFileOpenEvent>
#include <QtGui/QMessageBox>
#include <QtNetwork/QLocalServer>
#include <QtNetwork/QLocalSocket>
#include <QtNetwork/QNetworkProxy>
#include <QtNetwork/QSslSocket>
#include <QtWebKit/QWebSettings>
#include <QtCore/QDebug>
DownloadManager *BrowserApplication::s_downloadManager = 0;
HistoryManager *BrowserApplication::s_historyManager = 0;
NetworkAccessManager *BrowserApplication::s_networkAccessManager = 0;
BookmarksManager *BrowserApplication::s_bookmarksManager = 0;
BrowserApplication::BrowserApplication(int &argc, char **argv)
: QApplication(argc, argv)
, m_localServer(0)
{
QCoreApplication::setOrganizationName(QLatin1String("Trolltech"));
QCoreApplication::setApplicationName(QLatin1String("demobrowser"));
QCoreApplication::setApplicationVersion(QLatin1String("0.1"));
#ifdef Q_WS_QWS
// Use a different server name for QWS so we can run an X11
// browser and a QWS browser in parallel on the same machine for
// debugging
QString serverName = QCoreApplication::applicationName() + QLatin1String("_qws");
#else
QString serverName = QCoreApplication::applicationName();
#endif
QLocalSocket socket;
socket.connectToServer(serverName);
if (socket.waitForConnected(500)) {
QTextStream stream(&socket);
QStringList args = QCoreApplication::arguments();
if (args.count() > 1)
stream << args.last();
else
stream << QString();
stream.flush();
socket.waitForBytesWritten();
return;
}
#if defined(Q_WS_MAC)
QApplication::setQuitOnLastWindowClosed(false);
#else
QApplication::setQuitOnLastWindowClosed(true);
#endif
m_localServer = new QLocalServer(this);
connect(m_localServer, SIGNAL(newConnection()),
this, SLOT(newLocalSocketConnection()));
if (!m_localServer->listen(serverName)) {
if (m_localServer->serverError() == QAbstractSocket::AddressInUseError
&& QFile::exists(m_localServer->serverName())) {
QFile::remove(m_localServer->serverName());
m_localServer->listen(serverName);
}
}
#ifndef QT_NO_OPENSSL
if (!QSslSocket::supportsSsl()) {
QMessageBox::information(0, "Demo Browser",
"This system does not support OpenSSL. SSL websites will not be available.");
}
#endif
QDesktopServices::setUrlHandler(QLatin1String("http"), this, "openUrl");
QString localSysName = QLocale::system().name();
installTranslator(QLatin1String("qt_") + localSysName);
QSettings settings;
settings.beginGroup(QLatin1String("sessions"));
m_lastSession = settings.value(QLatin1String("lastSession")).toByteArray();
settings.endGroup();
#if defined(Q_WS_MAC)
connect(this, SIGNAL(lastWindowClosed()),
this, SLOT(lastWindowClosed()));
#endif
QTimer::singleShot(0, this, SLOT(postLaunch()));
}
BrowserApplication::~BrowserApplication()
{
delete s_downloadManager;
for (int i = 0; i < m_mainWindows.size(); ++i) {
BrowserMainWindow *window = m_mainWindows.at(i);
delete window;
}
delete s_networkAccessManager;
delete s_bookmarksManager;
}
#if defined(Q_WS_MAC)
void BrowserApplication::lastWindowClosed()
{
clean();
BrowserMainWindow *mw = new BrowserMainWindow;
mw->slotHome();
m_mainWindows.prepend(mw);
}
#endif
BrowserApplication *BrowserApplication::instance()
{
return (static_cast<BrowserApplication *>(QCoreApplication::instance()));
}
#if defined(Q_WS_MAC)
#include <QtGui/QMessageBox>
void BrowserApplication::quitBrowser()
{
clean();
int tabCount = 0;
for (int i = 0; i < m_mainWindows.count(); ++i) {
tabCount =+ m_mainWindows.at(i)->tabWidget()->count();
}
if (tabCount > 1) {
int ret = QMessageBox::warning(mainWindow(), QString(),
tr("There are %1 windows and %2 tabs open\n"
"Do you want to quit anyway?").arg(m_mainWindows.count()).arg(tabCount),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ret == QMessageBox::No)
return;
}
exit(0);
}
#endif
/*!
Any actions that can be delayed until the window is visible
*/
void BrowserApplication::postLaunch()
{
QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
if (directory.isEmpty())
directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
QWebSettings::setIconDatabasePath(directory);
QWebSettings::setOfflineStoragePath(directory);
setWindowIcon(QIcon(QLatin1String(":browser.svg")));
loadSettings();
// newMainWindow() needs to be called in main() for this to happen
if (m_mainWindows.count() > 0) {
QStringList args = QCoreApplication::arguments();
if (args.count() > 1)
mainWindow()->loadPage(args.last());
else
mainWindow()->slotHome();
}
BrowserApplication::historyManager();
}
void BrowserApplication::loadSettings()
{
QSettings settings;
settings.beginGroup(QLatin1String("websettings"));
QWebSettings *defaultSettings = QWebSettings::globalSettings();
QString standardFontFamily = defaultSettings->fontFamily(QWebSettings::StandardFont);
int standardFontSize = defaultSettings->fontSize(QWebSettings::DefaultFontSize);
QFont standardFont = QFont(standardFontFamily, standardFontSize);
standardFont = qVariantValue<QFont>(settings.value(QLatin1String("standardFont"), standardFont));
defaultSettings->setFontFamily(QWebSettings::StandardFont, standardFont.family());
defaultSettings->setFontSize(QWebSettings::DefaultFontSize, standardFont.pointSize());
QString fixedFontFamily = defaultSettings->fontFamily(QWebSettings::FixedFont);
int fixedFontSize = defaultSettings->fontSize(QWebSettings::DefaultFixedFontSize);
QFont fixedFont = QFont(fixedFontFamily, fixedFontSize);
fixedFont = qVariantValue<QFont>(settings.value(QLatin1String("fixedFont"), fixedFont));
defaultSettings->setFontFamily(QWebSettings::FixedFont, fixedFont.family());
defaultSettings->setFontSize(QWebSettings::DefaultFixedFontSize, fixedFont.pointSize());
defaultSettings->setAttribute(QWebSettings::JavascriptEnabled, settings.value(QLatin1String("enableJavascript"), true).toBool());
defaultSettings->setAttribute(QWebSettings::PluginsEnabled, settings.value(QLatin1String("enablePlugins"), true).toBool());
QUrl url = settings.value(QLatin1String("userStyleSheet")).toUrl();
defaultSettings->setUserStyleSheetUrl(url);
settings.endGroup();
}
QList<BrowserMainWindow*> BrowserApplication::mainWindows()
{
clean();
QList<BrowserMainWindow*> list;
for (int i = 0; i < m_mainWindows.count(); ++i)
list.append(m_mainWindows.at(i));
return list;
}
void BrowserApplication::clean()
{
// cleanup any deleted main windows first
for (int i = m_mainWindows.count() - 1; i >= 0; --i)
if (m_mainWindows.at(i).isNull())
m_mainWindows.removeAt(i);
}
void BrowserApplication::saveSession()
{
QWebSettings *globalSettings = QWebSettings::globalSettings();
if (globalSettings->testAttribute(QWebSettings::PrivateBrowsingEnabled))
return;
clean();
QSettings settings;
settings.beginGroup(QLatin1String("sessions"));
QByteArray data;
QBuffer buffer(&data);
QDataStream stream(&buffer);
buffer.open(QIODevice::ReadWrite);
stream << m_mainWindows.count();
for (int i = 0; i < m_mainWindows.count(); ++i)
stream << m_mainWindows.at(i)->saveState();
settings.setValue(QLatin1String("lastSession"), data);
settings.endGroup();
}
bool BrowserApplication::canRestoreSession() const
{
return !m_lastSession.isEmpty();
}
void BrowserApplication::restoreLastSession()
{
QList<QByteArray> windows;
QBuffer buffer(&m_lastSession);
QDataStream stream(&buffer);
buffer.open(QIODevice::ReadOnly);
int windowCount;
stream >> windowCount;
for (int i = 0; i < windowCount; ++i) {
QByteArray windowState;
stream >> windowState;
windows.append(windowState);
}
for (int i = 0; i < windows.count(); ++i) {
BrowserMainWindow *newWindow = 0;
if (m_mainWindows.count() == 1
&& mainWindow()->tabWidget()->count() == 1
&& mainWindow()->currentTab()->url() == QUrl()) {
newWindow = mainWindow();
} else {
newWindow = newMainWindow();
}
newWindow->restoreState(windows.at(i));
}
}
bool BrowserApplication::isTheOnlyBrowser() const
{
return (m_localServer != 0);
}
void BrowserApplication::installTranslator(const QString &name)
{
QTranslator *translator = new QTranslator(this);
translator->load(name, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
QApplication::installTranslator(translator);
}
#if defined(Q_WS_MAC)
bool BrowserApplication::event(QEvent* event)
{
switch (event->type()) {
case QEvent::ApplicationActivate: {
clean();
if (!m_mainWindows.isEmpty()) {
BrowserMainWindow *mw = mainWindow();
if (mw && !mw->isMinimized()) {
mainWindow()->show();
}
return true;
}
}
case QEvent::FileOpen:
if (!m_mainWindows.isEmpty()) {
mainWindow()->loadPage(static_cast<QFileOpenEvent *>(event)->file());
return true;
}
default:
break;
}
return QApplication::event(event);
}
#endif
void BrowserApplication::openUrl(const QUrl &url)
{
mainWindow()->loadPage(url.toString());
}
BrowserMainWindow *BrowserApplication::newMainWindow()
{
BrowserMainWindow *browser = new BrowserMainWindow();
m_mainWindows.prepend(browser);
browser->show();
return browser;
}
BrowserMainWindow *BrowserApplication::mainWindow()
{
clean();
if (m_mainWindows.isEmpty())
newMainWindow();
return m_mainWindows[0];
}
void BrowserApplication::newLocalSocketConnection()
{
QLocalSocket *socket = m_localServer->nextPendingConnection();
if (!socket)
return;
socket->waitForReadyRead(1000);
QTextStream stream(socket);
QString url;
stream >> url;
if (!url.isEmpty()) {
QSettings settings;
settings.beginGroup(QLatin1String("general"));
int openLinksIn = settings.value(QLatin1String("openLinksIn"), 0).toInt();
settings.endGroup();
if (openLinksIn == 1)
newMainWindow();
else
mainWindow()->tabWidget()->newTab();
openUrl(url);
}
delete socket;
mainWindow()->raise();
mainWindow()->activateWindow();
}
CookieJar *BrowserApplication::cookieJar()
{
return (CookieJar*)networkAccessManager()->cookieJar();
}
DownloadManager *BrowserApplication::downloadManager()
{
if (!s_downloadManager) {
s_downloadManager = new DownloadManager();
}
return s_downloadManager;
}
NetworkAccessManager *BrowserApplication::networkAccessManager()
{
if (!s_networkAccessManager) {
s_networkAccessManager = new NetworkAccessManager();
s_networkAccessManager->setCookieJar(new CookieJar);
}
return s_networkAccessManager;
}
HistoryManager *BrowserApplication::historyManager()
{
if (!s_historyManager) {
s_historyManager = new HistoryManager();
QWebHistoryInterface::setDefaultInterface(s_historyManager);
}
return s_historyManager;
}
BookmarksManager *BrowserApplication::bookmarksManager()
{
if (!s_bookmarksManager) {
s_bookmarksManager = new BookmarksManager;
}
return s_bookmarksManager;
}
QIcon BrowserApplication::icon(const QUrl &url) const
{
QIcon icon = QWebSettings::iconForUrl(url);
if (!icon.isNull())
return icon.pixmap(16, 16);
if (m_defaultIcon.isNull())
m_defaultIcon = QIcon(QLatin1String(":defaulticon.png"));
return m_defaultIcon.pixmap(16, 16);
}
<|endoftext|> |
<commit_before>
#include "journal/player.hpp"
#include <list>
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"
namespace principia {
namespace journal {
void BM_PlayForReal(benchmark::State& state) {
while (state.KeepRunning()) {
Player player(
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20180311-192733)");
int count = 0;
while (player.Play(count)) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0)
<< count << " journal entries replayed";
}
}
}
BENCHMARK(BM_PlayForReal);
class PlayerTest : public ::testing::Test {
protected:
PlayerTest()
: test_info_(testing::UnitTest::GetInstance()->current_test_info()),
test_case_name_(test_info_->test_case_name()),
test_name_(test_info_->name()),
plugin_(interface::principia__NewPlugin("MJD0", "MJD0", 0)) {}
template<typename Profile>
bool RunIfAppropriate(serialization::Method const& method_in,
serialization::Method const& method_out_return,
Player& player) {
return player.RunIfAppropriate<Profile>(method_in, method_out_return);
}
::testing::TestInfo const* const test_info_;
std::string const test_case_name_;
std::string const test_name_;
std::unique_ptr<ksp_plugin::Plugin> plugin_;
};
TEST_F(PlayerTest, PlayTiny) {
{
Recorder* const r(new Recorder(test_name_ + ".journal.hex"));
Recorder::Activate(r);
{
Method<NewPlugin> m({"MJD1", "MJD2", 3});
m.Return(plugin_.get());
}
{
const ksp_plugin::Plugin* plugin = plugin_.get();
Method<DeletePlugin> m({&plugin}, {&plugin});
m.Return();
}
Recorder::Deactivate();
}
Player player(test_name_ + ".journal.hex");
// Replay the journal.
int count = 0;
while (player.Play(count)) {
++count;
}
EXPECT_EQ(3, count);
}
TEST_F(PlayerTest, DISABLED_SECULAR_Benchmarks) {
benchmark::RunSpecifiedBenchmarks();
}
TEST_F(PlayerTest, DISABLED_SECULAR_Debug) {
google::LogToStderr();
// An example of how journaling may be used for debugging. You must set
// |path| and fill the |method_in| and |method_out_return| protocol buffers.
std::string path =
R"(P:\Public Mockingbird\Principia\Crashes\2922\JOURNAL.20210312-215639)"; // NOLINT
Player player(path);
int count = 0;
while (player.Play(count)) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0) << count
<< " journal entries replayed";
}
LOG(ERROR) << count << " journal entries in total";
LOG(ERROR) << "Last successful method in:\n"
<< player.last_method_in().DebugString();
LOG(ERROR) << "Last successful method out/return: \n"
<< player.last_method_out_return().DebugString();
#if 1
serialization::Method method_in;
{
auto* extension = method_in.MutableExtension(
serialization::FreeVesselsAndPartsAndCollectPileUps::extension);
auto* in = extension->mutable_in();
in->set_plugin(2718550096736);
in->set_delta_t(0.02);
}
serialization::Method method_out_return;
{
auto* extension = method_out_return.MutableExtension(
serialization::FreeVesselsAndPartsAndCollectPileUps::extension);
}
LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString();
CHECK(RunIfAppropriate<FreeVesselsAndPartsAndCollectPileUps>(
method_in, method_out_return, player));
#endif
}
} // namespace journal
} // namespace principia
<commit_msg>More verbose logging.<commit_after>
#include "journal/player.hpp"
#include <list>
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"
namespace principia {
namespace journal {
void BM_PlayForReal(benchmark::State& state) {
while (state.KeepRunning()) {
Player player(
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20180311-192733)");
int count = 0;
while (player.Play(count)) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0)
<< count << " journal entries replayed";
}
}
}
BENCHMARK(BM_PlayForReal);
class PlayerTest : public ::testing::Test {
protected:
PlayerTest()
: test_info_(testing::UnitTest::GetInstance()->current_test_info()),
test_case_name_(test_info_->test_case_name()),
test_name_(test_info_->name()),
plugin_(interface::principia__NewPlugin("MJD0", "MJD0", 0)) {}
template<typename Profile>
bool RunIfAppropriate(serialization::Method const& method_in,
serialization::Method const& method_out_return,
Player& player) {
return player.RunIfAppropriate<Profile>(method_in, method_out_return);
}
::testing::TestInfo const* const test_info_;
std::string const test_case_name_;
std::string const test_name_;
std::unique_ptr<ksp_plugin::Plugin> plugin_;
};
TEST_F(PlayerTest, PlayTiny) {
{
Recorder* const r(new Recorder(test_name_ + ".journal.hex"));
Recorder::Activate(r);
{
Method<NewPlugin> m({"MJD1", "MJD2", 3});
m.Return(plugin_.get());
}
{
const ksp_plugin::Plugin* plugin = plugin_.get();
Method<DeletePlugin> m({&plugin}, {&plugin});
m.Return();
}
Recorder::Deactivate();
}
Player player(test_name_ + ".journal.hex");
// Replay the journal.
int count = 0;
while (player.Play(count)) {
++count;
}
EXPECT_EQ(3, count);
}
TEST_F(PlayerTest, DISABLED_SECULAR_Benchmarks) {
benchmark::RunSpecifiedBenchmarks();
}
TEST_F(PlayerTest, DISABLED_SECULAR_Debug) {
// An example of how journaling may be used for debugging. You must set
// |path| and fill the |method_in| and |method_out_return| protocol buffers.
std::string path =
R"(P:\Public Mockingbird\Principia\Crashes\2922\JOURNAL.20210312-215639)"; // NOLINT
Player player(path);
int count = 0;
while (player.Play(count)) {
++count;
// Reset logging after each method so as to output all messages irrespective
// of what the game did.
google::LogToStderr();
LOG_IF(ERROR, (count % 100'000) == 0) << count
<< " journal entries replayed";
}
LOG(ERROR) << count << " journal entries in total";
LOG(ERROR) << "Last successful method in:\n"
<< player.last_method_in().DebugString();
LOG(ERROR) << "Last successful method out/return: \n"
<< player.last_method_out_return().DebugString();
#if 1
serialization::Method method_in;
{
auto* extension = method_in.MutableExtension(
serialization::FreeVesselsAndPartsAndCollectPileUps::extension);
auto* in = extension->mutable_in();
in->set_plugin(2718550096736);
in->set_delta_t(0.02);
}
serialization::Method method_out_return;
{
auto* extension = method_out_return.MutableExtension(
serialization::FreeVesselsAndPartsAndCollectPileUps::extension);
}
LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString();
CHECK(RunIfAppropriate<FreeVesselsAndPartsAndCollectPileUps>(
method_in, method_out_return, player));
#endif
}
} // namespace journal
} // namespace principia
<|endoftext|> |
<commit_before>#include <karl/storage.hpp>
#include <karl/util/guard.hpp>
namespace supermarx
{
storage::storage(std::string const& embedded_dir)
{
const char *server_options[] = \
{"test", "--innodb=OFF", "-h", embedded_dir.c_str(), NULL};
int num_options = (sizeof(server_options)/sizeof(char*)) - 1;
mysql_library_init(num_options, const_cast<char**>(server_options), NULL);
{
auto db = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo());
auto result = db->select_query("show databases");
bool found_karl = false;
while(result){
if(result.get<std::string>("Database") == "karl"){
found_karl = true;
}
result.next();
}
if(!found_karl){
db->execute("create database karl");
}
}
database = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo("karl"));
update_database_schema();
prepare_statements();
}
storage::storage(const std::string &host, const std::string &user, const std::string &password, const std::string& db)
: database(std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo(host, 3306, user, password, db)))
, prepared_statements()
{
update_database_schema();
prepare_statements();
}
storage::~storage()
{
prepared_statements.clear();
database.reset();
mysql_library_end();
}
void storage::lock_products_read()
{
// LibRUSQL does not support grabbing a specific connection (yet), do not lock for now
//database->query("lock tables product read");
}
void
storage::lock_products_write()
{
// LibRUSQL does not support grabbing a specific connection (yet), do not lock for now
//database->query("lock tables product write");
}
void storage::unlock_all()
{
// LibRUSQL does not support grabbing a specific connection (yet), do not lock for now
//database->query("unlock tables");
}
boost::optional<id_t> storage::find_product_unsafe(std::string const& identifier, id_t supermarket_id)
{
auto& qselect = *prepared_statements.at(statement::get_product_by_identifier);
qselect.execute(identifier, supermarket_id);
id_t product_id;
qselect.bind_results(product_id);
if(qselect.fetch())
return product_id;
return boost::none;
}
boost::optional<std::pair<id_t, product>> storage::fetch_last_productdetails_unsafe(id_t product_id)
{
auto& qolder = *prepared_statements.at(statement::get_last_productdetails_by_product);
qolder.execute(product_id);
id_t id;
product p;
std::string raw_discount_condition, raw_valid_on, raw_retrieved_on;
qolder.bind_results(id, p.identifier, p.name, p.orig_price, p.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);
if(!qolder.fetch())
return boost::none;
p.discount_condition = to_condition(raw_discount_condition);
p.valid_on = to_date(raw_valid_on);
p.retrieved_on = to_datetime(raw_retrieved_on);
return std::make_pair(id, p);
}
id_t storage::find_add_product(std::string const& identifier, id_t supermarket_id)
{
{
lock_products_read();
guard unlocker([&]() {
unlock_all();
});
auto product_id = find_product_unsafe(identifier, supermarket_id);
if(product_id)
return product_id.get();
}
{
lock_products_write();
guard unlocker([&]() {
unlock_all();
});
auto product_id = find_product_unsafe(identifier, supermarket_id);
if(product_id)
return product_id.get();
auto& qinsert = *prepared_statements.at(statement::add_product);
qinsert.execute(identifier, supermarket_id);
return qinsert.insert_id();
}
}
void storage::register_productdetailsrecord(id_t productdetails_id, datetime retrieved_on)
{
auto& q = *prepared_statements.at(statement::add_productdetailsrecord);
q.execute(productdetails_id, to_string(retrieved_on));
}
void storage::add_product(product const& p, id_t supermarket_id)
{
id_t product_id = find_add_product(p.identifier, supermarket_id);
// TODO Does not need locks, but does require a transaction
// Check if an older version of the product exactly matches what we've got
auto p_old_opt_kvp = fetch_last_productdetails_unsafe(product_id);
if(p_old_opt_kvp)
{
product const& p_old = p_old_opt_kvp->second;
bool similar = (
p.discount_condition == p_old.discount_condition &&
p.name == p_old.name &&
p.orig_price == p_old.orig_price &&
p.price == p_old.price
);
if(similar)
{
register_productdetailsrecord(p_old_opt_kvp->first, p.retrieved_on);
return;
}
else
{
auto& qinvalidate = *prepared_statements.at(statement::invalidate_productdetails);
qinvalidate.execute(to_string(p.valid_on), product_id);
}
}
//TODO check if a newer entry is already entered. Perhaps invalidate that entry in such a case.
auto& qadd = *prepared_statements.at(statement::add_productdetails);
qadd.execute(product_id, p.name, p.orig_price, p.price, to_string(p.discount_condition), to_string(p.valid_on), to_string(p.retrieved_on));
id_t productdetails_id = qadd.insert_id();
std::cerr << "Inserted new productdetails " << productdetails_id << " for product " << p.identifier << " [" << product_id << ']' << std::endl;
register_productdetailsrecord(productdetails_id, p.retrieved_on);
}
std::vector<product> storage::get_products_by_name(std::string const& name, id_t supermarket_id)
{
lock_products_read();
guard unlocker([&]() {
unlock_all();
});
rusql::PreparedStatement& query = *prepared_statements.at(statement::get_last_productdetails_by_name);
query.execute(std::string("%") + name + "%", supermarket_id);
std::vector<product> products;
product row;
std::string raw_discount_condition, raw_valid_on, raw_retrieved_on;
query.bind_results(row.identifier, row.name, row.orig_price, row.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);
while(query.fetch())
{
row.discount_condition = to_condition(raw_discount_condition);
row.valid_on = to_date(raw_valid_on);
row.retrieved_on = to_datetime(raw_retrieved_on);
products.push_back(row);
}
return products;
}
void storage::update_database_schema()
{
bool product_found = false;
bool productdetails_found = false;
bool productdetailsrecord_found = false;
bool supermarket_found = false;
auto result = database->select_query("show tables");
while(result)
{
std::string tablename = result.get<std::string>(0);
if(tablename == "product")
product_found = true;
else if(tablename == "productdetails")
productdetails_found = true;
else if(tablename == "productdetailsrecord")
productdetailsrecord_found = true;
else if(tablename == "supermarket")
supermarket_found = true;
result.next();
}
if(!product_found)
database->execute(std::string() +
"create table `product` ("+
"`id` int(11) unsigned not null auto_increment,"+
"`identifier` varchar(1024) not null,"+
"`supermarket_id` int(11) unsigned null,"+
"primary key (`id`),"+
"key `supermarket_id` (`supermarket_id`)"+
") character set utf8 collate utf8_bin");
if(!productdetails_found)
database->execute(std::string() +
"create table `productdetails` (" +
"`id` int(10) unsigned not null auto_increment," +
"`product_id` int(10) unsigned not null," +
"`name` varchar(1024) character set utf8 not null," +
"`orig_price` int not null," +
"`price` int not null," +
"`discount_condition` enum('ALWAYS','AT_TWO','AT_THREE') not null," +
"`valid_on` date not null," +
"`valid_until` date," +
"`retrieved_on` datetime not null," +
"primary key (`id`)," +
"key `product_id` (`product_id`)" +
") character set utf8 collate utf8_bin");
if(!productdetailsrecord_found)
database->execute(std::string() +
"create table `productdetailsrecord` (" +
"`id` int(10) unsigned not null auto_increment," +
"`productdetails_id` int(10) unsigned not null," +
"`retrieved_on` datetime not null," +
"primary key (`id`)," +
"key `productdetails_id` (`productdetails_id`)" +
") character set utf8 collate utf8_bin");
if(!supermarket_found)
database->execute(std::string() +
"create table `supermarket` (" +
"`id` int(11) unsigned not null auto_increment," +
"`name` varchar(1024) not null," +
"primary key (`id`)" +
") character set utf8 collate utf8_bin");
}
void storage::prepare_statements()
{
auto create_statement =
[&](statement const& s, std::string const& query)
{
prepared_statements[s] = std::make_shared<rusql::PreparedStatement>(database->prepare(query));
};
database->query("SET NAMES 'utf8'");
database->query("SET CHARACTER SET utf8");
create_statement(statement::add_product, "insert into product (identifier, supermarket_id) values (?, ?)");
create_statement(statement::get_product_by_identifier, "select product.id from product where product.identifier = ? and product.supermarket_id = ?");
create_statement(statement::add_productdetails, "insert into productdetails (product_id, name, orig_price, price, discount_condition, valid_on, valid_until, retrieved_on) values(?, ?, ?, ?, ?, ?, NULL, ?)");
create_statement(statement::add_productdetailsrecord, "insert into productdetailsrecord (productdetails_id, retrieved_on) values(?, ?)");
create_statement(statement::get_last_productdetails_by_product, "select productdetails.id, product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.product_id = ? AND productdetails.valid_until is NULL");
create_statement(statement::get_last_productdetails_by_name, "select product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.name like ? collate utf8_general_ci AND productdetails.valid_until is NULL AND product.supermarket_id = ?");
create_statement(statement::invalidate_productdetails, "update productdetails set productdetails.valid_until = ? where productdetails.valid_until is null and productdetails.product_id = ?");
}
}
<commit_msg>Restored collation in storage<commit_after>#include <karl/storage.hpp>
#include <karl/util/guard.hpp>
namespace supermarx
{
storage::storage(std::string const& embedded_dir)
{
const char *server_options[] = \
{"test", "--innodb=OFF", "-h", embedded_dir.c_str(), NULL};
int num_options = (sizeof(server_options)/sizeof(char*)) - 1;
mysql_library_init(num_options, const_cast<char**>(server_options), NULL);
{
auto db = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo());
auto result = db->select_query("show databases");
bool found_karl = false;
while(result){
if(result.get<std::string>("Database") == "karl"){
found_karl = true;
}
result.next();
}
if(!found_karl){
db->execute("create database karl");
}
}
database = std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo("karl"));
update_database_schema();
prepare_statements();
}
storage::storage(const std::string &host, const std::string &user, const std::string &password, const std::string& db)
: database(std::make_shared<rusql::Database>(rusql::Database::ConstructionInfo(host, 3306, user, password, db)))
, prepared_statements()
{
update_database_schema();
prepare_statements();
}
storage::~storage()
{
prepared_statements.clear();
database.reset();
mysql_library_end();
}
void storage::lock_products_read()
{
// LibRUSQL does not support grabbing a specific connection (yet), do not lock for now
//database->query("lock tables product read");
}
void
storage::lock_products_write()
{
// LibRUSQL does not support grabbing a specific connection (yet), do not lock for now
//database->query("lock tables product write");
}
void storage::unlock_all()
{
// LibRUSQL does not support grabbing a specific connection (yet), do not lock for now
//database->query("unlock tables");
}
boost::optional<id_t> storage::find_product_unsafe(std::string const& identifier, id_t supermarket_id)
{
auto& qselect = *prepared_statements.at(statement::get_product_by_identifier);
qselect.execute(identifier, supermarket_id);
id_t product_id;
qselect.bind_results(product_id);
if(qselect.fetch())
return product_id;
return boost::none;
}
boost::optional<std::pair<id_t, product>> storage::fetch_last_productdetails_unsafe(id_t product_id)
{
auto& qolder = *prepared_statements.at(statement::get_last_productdetails_by_product);
qolder.execute(product_id);
id_t id;
product p;
std::string raw_discount_condition, raw_valid_on, raw_retrieved_on;
qolder.bind_results(id, p.identifier, p.name, p.orig_price, p.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);
if(!qolder.fetch())
return boost::none;
p.discount_condition = to_condition(raw_discount_condition);
p.valid_on = to_date(raw_valid_on);
p.retrieved_on = to_datetime(raw_retrieved_on);
return std::make_pair(id, p);
}
id_t storage::find_add_product(std::string const& identifier, id_t supermarket_id)
{
{
lock_products_read();
guard unlocker([&]() {
unlock_all();
});
auto product_id = find_product_unsafe(identifier, supermarket_id);
if(product_id)
return product_id.get();
}
{
lock_products_write();
guard unlocker([&]() {
unlock_all();
});
auto product_id = find_product_unsafe(identifier, supermarket_id);
if(product_id)
return product_id.get();
auto& qinsert = *prepared_statements.at(statement::add_product);
qinsert.execute(identifier, supermarket_id);
return qinsert.insert_id();
}
}
void storage::register_productdetailsrecord(id_t productdetails_id, datetime retrieved_on)
{
auto& q = *prepared_statements.at(statement::add_productdetailsrecord);
q.execute(productdetails_id, to_string(retrieved_on));
}
void storage::add_product(product const& p, id_t supermarket_id)
{
id_t product_id = find_add_product(p.identifier, supermarket_id);
// TODO Does not need locks, but does require a transaction
// Check if an older version of the product exactly matches what we've got
auto p_old_opt_kvp = fetch_last_productdetails_unsafe(product_id);
if(p_old_opt_kvp)
{
product const& p_old = p_old_opt_kvp->second;
bool similar = (
p.discount_condition == p_old.discount_condition &&
p.name == p_old.name &&
p.orig_price == p_old.orig_price &&
p.price == p_old.price
);
if(similar)
{
register_productdetailsrecord(p_old_opt_kvp->first, p.retrieved_on);
return;
}
else
{
auto& qinvalidate = *prepared_statements.at(statement::invalidate_productdetails);
qinvalidate.execute(to_string(p.valid_on), product_id);
}
}
//TODO check if a newer entry is already entered. Perhaps invalidate that entry in such a case.
auto& qadd = *prepared_statements.at(statement::add_productdetails);
qadd.execute(product_id, p.name, p.orig_price, p.price, to_string(p.discount_condition), to_string(p.valid_on), to_string(p.retrieved_on));
id_t productdetails_id = qadd.insert_id();
std::cerr << "Inserted new productdetails " << productdetails_id << " for product " << p.identifier << " [" << product_id << ']' << std::endl;
register_productdetailsrecord(productdetails_id, p.retrieved_on);
}
std::vector<product> storage::get_products_by_name(std::string const& name, id_t supermarket_id)
{
lock_products_read();
guard unlocker([&]() {
unlock_all();
});
rusql::PreparedStatement& query = *prepared_statements.at(statement::get_last_productdetails_by_name);
query.execute(std::string("%") + name + "%", supermarket_id);
std::vector<product> products;
product row;
std::string raw_discount_condition, raw_valid_on, raw_retrieved_on;
query.bind_results(row.identifier, row.name, row.orig_price, row.price, raw_discount_condition, raw_valid_on, raw_retrieved_on);
while(query.fetch())
{
row.discount_condition = to_condition(raw_discount_condition);
row.valid_on = to_date(raw_valid_on);
row.retrieved_on = to_datetime(raw_retrieved_on);
products.push_back(row);
}
return products;
}
void storage::update_database_schema()
{
bool product_found = false;
bool productdetails_found = false;
bool productdetailsrecord_found = false;
bool supermarket_found = false;
auto result = database->select_query("show tables");
while(result)
{
std::string tablename = result.get<std::string>(0);
if(tablename == "product")
product_found = true;
else if(tablename == "productdetails")
productdetails_found = true;
else if(tablename == "productdetailsrecord")
productdetailsrecord_found = true;
else if(tablename == "supermarket")
supermarket_found = true;
result.next();
}
if(!product_found)
database->execute(std::string() +
"create table `product` ("+
"`id` int(11) unsigned not null auto_increment,"+
"`identifier` varchar(1024) not null,"+
"`supermarket_id` int(11) unsigned null,"+
"primary key (`id`),"+
"key `supermarket_id` (`supermarket_id`)"+
") character set utf8 collate utf8_bin");
if(!productdetails_found)
database->execute(std::string() +
"create table `productdetails` (" +
"`id` int(10) unsigned not null auto_increment," +
"`product_id` int(10) unsigned not null," +
"`name` varchar(1024) character set utf8 not null," +
"`orig_price` int not null," +
"`price` int not null," +
"`discount_condition` enum('ALWAYS','AT_TWO','AT_THREE') not null," +
"`valid_on` date not null," +
"`valid_until` date," +
"`retrieved_on` datetime not null," +
"primary key (`id`)," +
"key `product_id` (`product_id`)" +
") character set utf8 collate utf8_bin");
if(!productdetailsrecord_found)
database->execute(std::string() +
"create table `productdetailsrecord` (" +
"`id` int(10) unsigned not null auto_increment," +
"`productdetails_id` int(10) unsigned not null," +
"`retrieved_on` datetime not null," +
"primary key (`id`)," +
"key `productdetails_id` (`productdetails_id`)" +
") character set utf8 collate utf8_bin");
if(!supermarket_found)
database->execute(std::string() +
"create table `supermarket` (" +
"`id` int(11) unsigned not null auto_increment," +
"`name` varchar(1024) not null," +
"primary key (`id`)" +
") character set utf8 collate utf8_bin");
}
void storage::prepare_statements()
{
auto create_statement =
[&](statement const& s, std::string const& query)
{
prepared_statements[s] = std::make_shared<rusql::PreparedStatement>(database->prepare(query));
};
database->query("SET NAMES 'utf8'");
database->query("SET CHARACTER SET utf8");
create_statement(statement::add_product, "insert into product (identifier, supermarket_id) values (?, ?)");
create_statement(statement::get_product_by_identifier, "select product.id from product where product.identifier = ? and product.supermarket_id = ?");
create_statement(statement::add_productdetails, "insert into productdetails (product_id, name, orig_price, price, discount_condition, valid_on, valid_until, retrieved_on) values(?, ?, ?, ?, ?, ?, NULL, ?)");
create_statement(statement::add_productdetailsrecord, "insert into productdetailsrecord (productdetails_id, retrieved_on) values(?, ?)");
create_statement(statement::get_last_productdetails_by_product, "select productdetails.id, product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.product_id = ? AND productdetails.valid_until is NULL");
create_statement(statement::get_last_productdetails_by_name, "select product.identifier, productdetails.name, productdetails.orig_price, productdetails.price, productdetails.discount_condition, productdetails.valid_on, productdetails.retrieved_on from product inner join productdetails on (product.id = productdetails.product_id) where productdetails.name like ? AND productdetails.valid_until is NULL AND product.supermarket_id = ?");
create_statement(statement::invalidate_productdetails, "update productdetails set productdetails.valid_until = ? where productdetails.valid_until is null and productdetails.product_id = ?");
}
}
<|endoftext|> |
<commit_before>#include <clang-c/Index.h>
#include <cstdio>
#include <array>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
const std::string indentation(indent_spaces, ' ');
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
// function signature, forwarding call arguments, optional return
// keyword, and function name
std::vector<std::array<std::string, 4>> member_functions;
bool printed_headers;
const char* filename;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
for (unsigned int i = 0; i < tokens.second; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data & data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void print_lines (const client_data & data,
const char** lines,
std::size_t num_lines)
{
for (unsigned int i = 0; i < num_lines; ++i) {
if (lines[i])
std::cout << indent(data) << indentation << lines[i] << "\n";
else
std::cout << "\n";
}
}
void print_headers (client_data & data)
{
if (data.printed_headers)
return;
std::cout << "#include <algorithm>\n"
<< "#include <functional>\n"
<< "#include <memory>\n"
<< "#include <type_traits>\n"
<< "#include <utility>\n"
<< "\n";
data.printed_headers = true;
}
void open_struct (const client_data & data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
const std::string struct_name =
clang_getCString(clang_getCursorSpelling(data.current_struct));
const std::string ctor_0 =
struct_name + " () = default;";
const std::string ctor_1 =
struct_name + " (T_T__ value) :";
const std::string ctor_2 =
struct_name + " (any_printable && rhs) noexcept = default;";
const std::string ctor_3 =
struct_name + " & operator= (T_T__ value)";
const std::string ctor_4 =
struct_name + " & operator= (any_printable && rhs) noexcept = default;";
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
ctor_0.c_str(),
0,
"template <typename T_T__>",
ctor_1.c_str(),
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T_T__>::type>",
" >(std::forward<T_T__>(value))",
" )",
"{}",
0,
ctor_2.c_str(),
0,
"template <typename T_T__>",
ctor_3.c_str(),
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T_T__>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));",
" return *this;",
"}",
0,
ctor_4.c_str()
};
print_lines(data,
public_interface,
sizeof(public_interface) / sizeof(const char*));
}
void close_struct (const client_data & data)
{
std::cout << "\n"
<< indent(data) << "private:\n";
const char* handle_base_preamble[] = {
0,
"struct handle_base",
"{",
" virtual ~handle_base () {}",
" virtual std::shared_ptr<handle_base> close () const = 0;",
0
};
print_lines(data,
handle_base_preamble,
sizeof(handle_base_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << indent(data) << indentation << indentation
<< "virtual " << member[0] << " = 0;\n";
}
const char* handle_preamble[] = {
0,
"};",
0,
"template <typename T_T__>",
"struct handle :",
" handle_base",
"{",
" template <typename T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" std::is_reference<U_U__>::value",
" >::type* = 0) :",
" value_ (value)",
" {}",
0,
" template <typename U_U__ = T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" !std::is_reference<U_U__>::value,",
" int",
" >::type* = 0) noexcept :",
" value_ (std::move(value))",
" {}",
0,
" virtual std::shared_ptr<handle_base> clone () const",
" { return std::make_shared<handle>(value_); }"
};
print_lines(data,
handle_preamble,
sizeof(handle_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << "\n"
<< indent(data) << indentation << indentation
<< "virtual " << member[0] << "\n"
<< indent(data) << indentation << indentation
<< "{ " << member[2] << "value_." << member[3]
<< "( " << member[1] << " ); }\n";
}
const char* handle_postamble[] = {
0,
" T_T__ value_;",
"};",
0,
"template <typename T_T__>",
"struct handle<std::reference_wrapper<T_T__>> :",
" handle<T_T__ &>",
"{",
" handle (std::reference_wrapper<T_T__> ref) :",
" handle<T_T__ &> (ref.get())",
" {}",
"};",
0,
"const handle_base & read () const",
"{ return *handle_; }",
0,
"handle_base & write ()",
"{",
" if (!handle_.unique())",
" handle_ = handle_->clone();",
" return *handle_;",
"}",
0,
"std::shared_ptr<handle_base> handle_;"
};
print_lines(data,
handle_postamble,
sizeof(handle_postamble) / sizeof(const char*));
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function (const client_data & data, CXCursor cursor)
{
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data)
<< data.member_functions.back()[0];
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << data.member_functions.back()[2]
<< "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( " << data.member_functions.back()[1] << " ); }\n";
}
void open_namespace (const client_data & data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data & data)
{ std::cout << "\n" << indent(data) << "}\n"; }
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data & data = *static_cast<client_data*>(data_);
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!data.current_namespaces.empty() &&
!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
data.member_functions.clear();
}
CXSourceLocation location = clang_getCursorLocation(cursor);
const bool from_main_file = clang_Location_isFromMainFile(location);
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
if (from_main_file) {
print_headers(data);
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
}
return CXChildVisit_Recurse;
} else if (!from_main_file) {
return CXChildVisit_Continue;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
print_headers(data);
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
const std::string open_brace = "{";
const std::string semicolon = ";";
std::string str;
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling =
clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
str += " ";
str += c_str;
}
std::string args;
const int num_args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < num_args; ++i) {
if (i)
args += ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
args += clang_getCString(clang_getCursorSpelling(arg_cursor));
}
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ?
"" :
"return ";
const char* function_name =
clang_getCString(clang_getCursorSpelling(cursor));
free_tokens(data.tu, tokens);
data.member_functions.push_back({str, args, return_str, function_name});
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_DetailedPreprocessingRecord
);
const char* filename =
clang_getCString(clang_getTranslationUnitSpelling(tu));
client_data data = {tu, {}, clang_getNullCursor(), {}, false, filename};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<commit_msg>Preserve #includes from the original file.<commit_after>#include <clang-c/Index.h>
#include <cstdio>
#include <array>
#include <iostream>
#include <vector>
namespace {
const unsigned int indent_spaces = 4;
const std::string indentation(indent_spaces, ' ');
}
CXCursor tu_cursor;
struct client_data
{
CXTranslationUnit tu;
std::vector<CXCursor> current_namespaces;
CXCursor current_struct;
// function signature, forwarding call arguments, optional return
// keyword, and function name
std::vector<std::array<std::string, 4>> member_functions;
bool printed_headers;
const char* filename;
};
std::pair<CXToken*, unsigned int>
get_tokens (CXTranslationUnit tu, CXCursor cursor)
{
CXSourceRange range = clang_getCursorExtent(cursor);
CXSourceLocation start = clang_getRangeStart(range);
CXSourceLocation end = clang_getRangeEnd(range);
unsigned int start_offset, end_offset;
std::pair<CXToken*, unsigned int> retval(0, 0);
clang_tokenize(tu, range, &retval.first, &retval.second);
return retval;
}
void
free_tokens (CXTranslationUnit tu, std::pair<CXToken*, unsigned int> tokens)
{ clang_disposeTokens(tu, tokens.first, tokens.second); }
void print_tokens (CXTranslationUnit tu, CXCursor cursor, bool elide_final_token)
{
std::pair<CXToken*, unsigned int> tokens = get_tokens(tu, cursor);
const unsigned int num_tokens =
tokens.second && elide_final_token ? tokens.second - 1 : tokens.second;
for (unsigned int i = 0; i < num_tokens; ++i) {
if (i)
std::cout << " ";
CXString spelling = clang_getTokenSpelling(tu, tokens.first[i]);
std::cout << clang_getCString(spelling);
}
std::cout << "\n";
free_tokens(tu, tokens);
}
bool struct_kind (CXCursorKind kind)
{
switch (kind) {
case CXCursor_ClassDecl:
case CXCursor_StructDecl:
case CXCursor_ClassTemplate:
case CXCursor_ClassTemplatePartialSpecialization:
return true;
}
return false;
}
std::string indent (const client_data & data)
{
std::size_t size = data.current_namespaces.size();
return std::string(size * indent_spaces, ' ');
}
void print_lines (const client_data & data,
const char** lines,
std::size_t num_lines)
{
for (unsigned int i = 0; i < num_lines; ++i) {
if (lines[i])
std::cout << indent(data) << indentation << lines[i] << "\n";
else
std::cout << "\n";
}
}
void print_headers (client_data & data)
{
if (data.printed_headers)
return;
std::cout << "#include <algorithm>\n"
<< "#include <functional>\n"
<< "#include <memory>\n"
<< "#include <type_traits>\n"
<< "#include <utility>\n"
<< "\n";
data.printed_headers = true;
}
void open_struct (const client_data & data, CXCursor struct_cursor)
{
std::pair<CXToken*, unsigned int> tokens =
get_tokens(data.tu, struct_cursor);
std::cout << "\n" << indent(data);
const std::string open_brace = "{";
const std::string struct_ = "struct";
const std::string class_ = "class";
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling = clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace)
break;
if (c_str == struct_ || c_str == class_) {
std::cout << "\n" << indent(data);
} else if (i) {
std::cout << " ";
}
std::cout << c_str;
}
free_tokens(data.tu, tokens);
const std::string struct_name =
clang_getCString(clang_getCursorSpelling(data.current_struct));
const std::string ctor_0 =
struct_name + " () = default;";
const std::string ctor_1 =
struct_name + " (T_T__ value) :";
const std::string ctor_2 =
struct_name + " (any_printable && rhs) noexcept = default;";
const std::string ctor_3 =
struct_name + " & operator= (T_T__ value)";
const std::string ctor_4 =
struct_name + " & operator= (any_printable && rhs) noexcept = default;";
std::cout << "\n"
<< indent(data) << "{\n"
<< indent(data) << "public:\n";
const char* public_interface[] = {
0,
ctor_0.c_str(),
0,
"template <typename T_T__>",
ctor_1.c_str(),
" handle_ (",
" std::make_shared<",
" handle<typename std::remove_reference<T_T__>::type>",
" >(std::forward<T_T__>(value))",
" )",
"{}",
0,
ctor_2.c_str(),
0,
"template <typename T_T__>",
ctor_3.c_str(),
"{",
" if (handle_.unique())",
" *handle_ = std::forward<T_T__>(value);",
" else if (!handle_)",
" handle_ = std::make_shared<T_T__>(std::forward<T_T__>(value));",
" return *this;",
"}",
0,
ctor_4.c_str()
};
print_lines(data,
public_interface,
sizeof(public_interface) / sizeof(const char*));
}
void close_struct (const client_data & data)
{
std::cout << "\n"
<< indent(data) << "private:\n";
const char* handle_base_preamble[] = {
0,
"struct handle_base",
"{",
" virtual ~handle_base () {}",
" virtual std::shared_ptr<handle_base> close () const = 0;",
0
};
print_lines(data,
handle_base_preamble,
sizeof(handle_base_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << indent(data) << indentation << indentation
<< "virtual " << member[0] << " = 0;\n";
}
const char* handle_preamble[] = {
0,
"};",
0,
"template <typename T_T__>",
"struct handle :",
" handle_base",
"{",
" template <typename T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" std::is_reference<U_U__>::value",
" >::type* = 0) :",
" value_ (value)",
" {}",
0,
" template <typename U_U__ = T_T__>",
" handle (T_T__ value,",
" typename std::enable_if<",
" !std::is_reference<U_U__>::value,",
" int",
" >::type* = 0) noexcept :",
" value_ (std::move(value))",
" {}",
0,
" virtual std::shared_ptr<handle_base> clone () const",
" { return std::make_shared<handle>(value_); }"
};
print_lines(data,
handle_preamble,
sizeof(handle_preamble) / sizeof(const char*));
for (auto & member : data.member_functions) {
std::cout << "\n"
<< indent(data) << indentation << indentation
<< "virtual " << member[0] << "\n"
<< indent(data) << indentation << indentation
<< "{ " << member[2] << "value_." << member[3]
<< "( " << member[1] << " ); }\n";
}
const char* handle_postamble[] = {
0,
" T_T__ value_;",
"};",
0,
"template <typename T_T__>",
"struct handle<std::reference_wrapper<T_T__>> :",
" handle<T_T__ &>",
"{",
" handle (std::reference_wrapper<T_T__> ref) :",
" handle<T_T__ &> (ref.get())",
" {}",
"};",
0,
"const handle_base & read () const",
"{ return *handle_; }",
0,
"handle_base & write ()",
"{",
" if (!handle_.unique())",
" handle_ = handle_->clone();",
" return *handle_;",
"}",
0,
"std::shared_ptr<handle_base> handle_;"
};
print_lines(data,
handle_postamble,
sizeof(handle_postamble) / sizeof(const char*));
std::cout << "\n"
<< indent(data) << "};\n";
}
void print_member_function (const client_data & data, CXCursor cursor)
{
std::cout << "\n"
<< std::string(indent_spaces, ' ') << indent(data)
<< data.member_functions.back()[0];
std::cout << "\n" << std::string(indent_spaces, ' ') << indent(data)
<< "{ assert(handle_); " << data.member_functions.back()[2]
<< "handle_->"
<< clang_getCString(clang_getCursorSpelling(cursor))
<< "( " << data.member_functions.back()[1] << " ); }\n";
}
void open_namespace (const client_data & data, CXCursor namespace_)
{
std::cout
<< "\n"
<< indent(data)
<< "namespace "
<< clang_getCString(clang_getCursorSpelling(namespace_))
<< " {";
}
void close_namespace (const client_data & data)
{ std::cout << "\n" << indent(data) << "}\n"; }
CXChildVisitResult
visitor (CXCursor cursor, CXCursor parent, CXClientData data_)
{
client_data & data = *static_cast<client_data*>(data_);
CXCursor null_cursor = clang_getNullCursor();
// close open namespaces we have left
CXCursor enclosing_namespace = parent;
while (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) != CXCursor_Namespace) {
enclosing_namespace =
clang_getCursorSemanticParent(enclosing_namespace);
}
if (!clang_equalCursors(enclosing_namespace, tu_cursor) &&
clang_getCursorKind(enclosing_namespace) == CXCursor_Namespace) {
while (!data.current_namespaces.empty() &&
!clang_equalCursors(enclosing_namespace,
data.current_namespaces.back())) {
data.current_namespaces.pop_back();
close_namespace(data);
}
}
// close open struct if we have left it
CXCursor enclosing_struct = parent;
while (!clang_equalCursors(enclosing_struct, tu_cursor) &&
!struct_kind(clang_getCursorKind(enclosing_struct))) {
enclosing_struct = clang_getCursorSemanticParent(enclosing_struct);
}
if (!clang_Cursor_isNull(data.current_struct) &&
!clang_equalCursors(enclosing_struct, data.current_struct)) {
data.current_struct = null_cursor;
close_struct(data);
data.member_functions.clear();
}
CXSourceLocation location = clang_getCursorLocation(cursor);
const bool from_main_file = clang_Location_isFromMainFile(location);
CXCursorKind kind = clang_getCursorKind(cursor);
if (kind == CXCursor_Namespace) {
if (from_main_file) {
print_headers(data);
open_namespace(data, cursor);
data.current_namespaces.push_back(cursor);
}
return CXChildVisit_Recurse;
} else if (!from_main_file) {
return CXChildVisit_Continue;
} else if (struct_kind(kind)) {
if (clang_Cursor_isNull(data.current_struct)) {
print_headers(data);
data.current_struct = cursor;
open_struct(data, cursor);
return CXChildVisit_Recurse;
}
} else if (kind == CXCursor_CXXMethod) {
std::pair<CXToken*, unsigned int> tokens = get_tokens(data.tu, cursor);
const std::string open_brace = "{";
const std::string semicolon = ";";
std::string str;
for (unsigned int i = 0; i < tokens.second; ++i) {
CXString spelling =
clang_getTokenSpelling(data.tu, tokens.first[i]);
const char* c_str = clang_getCString(spelling);
if (c_str == open_brace || c_str == semicolon)
break;
if (i)
str += " ";
str += c_str;
}
std::string args;
const int num_args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < num_args; ++i) {
if (i)
args += ", ";
CXCursor arg_cursor = clang_Cursor_getArgument(cursor, i);
args += clang_getCString(clang_getCursorSpelling(arg_cursor));
}
const char* return_str =
clang_getCursorResultType(cursor).kind == CXType_Void ?
"" :
"return ";
const char* function_name =
clang_getCString(clang_getCursorSpelling(cursor));
free_tokens(data.tu, tokens);
data.member_functions.push_back({str, args, return_str, function_name});
print_member_function(data, cursor);
}
return CXChildVisit_Continue;
}
CXVisitorResult visit_includes (void * context, CXCursor cursor, CXSourceRange range)
{
print_tokens(static_cast<CXTranslationUnit>(context), cursor, true);
return CXVisit_Continue;
}
int main (int argc, char* argv[])
{
CXIndex index = clang_createIndex(0, 1);
CXTranslationUnit tu = clang_parseTranslationUnit(
index,
0,
argv,
argc,
0,
0,
CXTranslationUnit_DetailedPreprocessingRecord
);
const char* filename =
clang_getCString(clang_getTranslationUnitSpelling(tu));
CXFile file = clang_getFile(tu, filename);
CXCursorAndRangeVisitor visitor_ = {tu, visit_includes};
clang_findIncludesInFile(tu, file, visitor_);
std::cout << "\n";
client_data data = {tu, {}, clang_getNullCursor(), {}, false, filename};
tu_cursor = clang_getTranslationUnitCursor(tu);
clang_visitChildren(tu_cursor, visitor, &data);
if (!clang_Cursor_isNull(data.current_struct))
close_struct(data);
while (!data.current_namespaces.empty()) {
data.current_namespaces.pop_back();
close_namespace(data);
}
clang_disposeTranslationUnit(tu);
clang_disposeIndex(index);
return 0;
}
<|endoftext|> |
<commit_before>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <limits>
#include <string>
TEST(ErrorHandlingMat, CheckLess_Matrix) {
using stan::math::check_less;
const char* function = "check_less";
double x;
double high;
Eigen::Matrix<double, Eigen::Dynamic, 1> x_vec;
Eigen::Matrix<double, Eigen::Dynamic, 1> high_vec;
x_vec.resize(3);
high_vec.resize(3);
// x_vec, high
x_vec << -5, 0, 5;
high = 10;
EXPECT_NO_THROW(check_less(function, "x", x_vec, high));
x_vec << -5, 0, 5;
high = std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_less(function, "x", x_vec, high));
x_vec << -5, 0, 5;
high = 5;
EXPECT_THROW(check_less(function, "x", x_vec, high), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high = 5;
EXPECT_THROW(check_less(function, "x", x_vec, high), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high = std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x_vec, high), std::domain_error);
// x_vec, high_vec
x_vec << -5, 0, 5;
high_vec << 0, 5, 10;
EXPECT_NO_THROW(check_less(function, "x", x_vec, high_vec));
x_vec << -5, 0, 5;
high_vec << std::numeric_limits<double>::infinity(), 10, 10;
EXPECT_NO_THROW(check_less(function, "x", x_vec, high_vec));
x_vec << -5, 0, 5;
high_vec << 10, 10, 5;
EXPECT_THROW(check_less(function, "x", x_vec, high_vec), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high_vec << 10, 10, 10;
EXPECT_THROW(check_less(function, "x", x_vec, high_vec), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high_vec << 10, 10, std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x_vec, high_vec), std::domain_error);
// x, high_vec
x = -100;
high_vec << 0, 5, 10;
EXPECT_NO_THROW(check_less(function, "x", x, high_vec));
x = 10;
high_vec << 100, 200, std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_less(function, "x", x, high_vec));
x = 5;
high_vec << 100, 200, 5;
EXPECT_THROW(check_less(function, "x", x, high_vec), std::domain_error);
x = std::numeric_limits<double>::infinity();
high_vec << 10, 20, 30;
EXPECT_THROW(check_less(function, "x", x, high_vec), std::domain_error);
x = std::numeric_limits<double>::infinity();
high_vec << std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x, high_vec), std::domain_error);
}
TEST(ErrorHandlingMat, CheckLess_Matrix_one_indexed_message) {
using stan::math::check_less;
const char* function = "check_less";
double x;
double high;
Eigen::Matrix<double, Eigen::Dynamic, 1> x_vec;
Eigen::Matrix<double, Eigen::Dynamic, 1> high_vec;
x_vec.resize(3);
high_vec.resize(3);
std::string message;
// x_vec, high
x_vec << -5, 0, 5;
high = 5;
try {
check_less(function, "x", x_vec, high);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_NE(std::string::npos, message.find("[3]")) << message;
// x_vec, high_vec
x_vec << -5, 5, 0;
high_vec << 10, 5, 10;
try {
check_less(function, "x", x_vec, high_vec);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_NE(std::string::npos, message.find("[2]")) << message;
// x, high_vec
x = 30;
high_vec << 10, 20, 30;
try {
check_less(function, "x", x, high_vec);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_EQ(std::string::npos, message.find("["))
<< "index provided when x has none" << std::endl
<< message;
}
TEST(ErrorHandlingMat, CheckLess_nan) {
using stan::math::check_less;
const char* function = "check_less";
double nan = std::numeric_limits<double>::quiet_NaN();
Eigen::Matrix<double, Eigen::Dynamic, 1> x_vec(3);
Eigen::Matrix<double, Eigen::Dynamic, 1> low_vec(3);
// x_vec, low_vec
x_vec << -1, 0, 1;
low_vec << -2, -1, 0;
EXPECT_THROW(check_less(function, "x", x_vec, nan), std::domain_error);
for (int i = 0; i < x_vec.size(); i++) {
x_vec << -1, 0, 1;
x_vec(i) = nan;
EXPECT_THROW(check_less(function, "x", x_vec, low_vec), std::domain_error);
}
x_vec << -1, 0, 1;
for (int i = 0; i < low_vec.size(); i++) {
low_vec << -1, 0, 1;
low_vec(i) = nan;
EXPECT_THROW(check_less(function, "x", x_vec, low_vec), std::domain_error);
}
for (int i = 0; i < x_vec.size(); i++) {
x_vec << -1, 0, 1;
low_vec << -2, -1, 0;
x_vec(i) = nan;
for (int j = 0; j < low_vec.size(); j++) {
low_vec(i) = nan;
EXPECT_THROW(check_less(function, "x", x_vec, low_vec),
std::domain_error);
}
}
}
TEST(ErrorHandlingScalar, CheckLess) {
using stan::math::check_less;
const char* function = "check_less";
double x = -10.0;
double lb = 0.0;
EXPECT_NO_THROW(check_less(function, "x", x, lb))
<< "check_less should be true with x < lb";
x = 1.0;
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x > lb";
x = lb;
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x == lb";
x = -std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_less(function, "x", x, lb))
<< "check_less should be true with x == -Inf and lb = 0.0";
x = -10.0;
lb = -std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x == -10.0 and lb == -Inf";
x = -std::numeric_limits<double>::infinity();
lb = -std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x == -Inf and lb == -Inf";
}
TEST(ErrorHandlingScalar, CheckLess_nan) {
using stan::math::check_less;
const char* function = "check_less";
double x = 10.0;
double lb = 0.0;
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_THROW(check_less(function, "x", nan, lb), std::domain_error);
EXPECT_THROW(check_less(function, "x", x, nan), std::domain_error);
EXPECT_THROW(check_less(function, "x", nan, nan), std::domain_error);
}
<commit_msg>Added test for check less (Issue #2101)<commit_after>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <limits>
#include <string>
TEST(ErrorHandlingMat, CheckLess_Matrix) {
using stan::math::check_less;
const char* function = "check_less";
double x;
double high;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> x_vec(3, 1);
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> high_vec(3, 1);
// x_vec, high
x_vec << -5, 0, 5;
high = 10;
EXPECT_NO_THROW(check_less(function, "x", x_vec, high));
x_vec << -5, 0, 5;
high = std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_less(function, "x", x_vec, high));
x_vec << -5, 0, 5;
high = 5;
EXPECT_THROW(check_less(function, "x", x_vec, high), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high = 5;
EXPECT_THROW(check_less(function, "x", x_vec, high), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high = std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x_vec, high), std::domain_error);
// x_vec, high_vec
x_vec << -5, 0, 5;
high_vec << 0, 5, 10;
EXPECT_NO_THROW(check_less(function, "x", x_vec, high_vec));
x_vec << -5, 0, 5;
high_vec << std::numeric_limits<double>::infinity(), 10, 10;
EXPECT_NO_THROW(check_less(function, "x", x_vec, high_vec));
x_vec << -5, 0, 5;
high_vec << 10, 10, 5;
EXPECT_THROW(check_less(function, "x", x_vec, high_vec), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high_vec << 10, 10, 10;
EXPECT_THROW(check_less(function, "x", x_vec, high_vec), std::domain_error);
x_vec << -5, 0, std::numeric_limits<double>::infinity();
high_vec << 10, 10, std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x_vec, high_vec), std::domain_error);
// x, high_vec
x = -100;
high_vec << 0, 5, 10;
EXPECT_NO_THROW(check_less(function, "x", x, high_vec));
x = 10;
high_vec << 100, 200, std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_less(function, "x", x, high_vec));
x = 5;
high_vec << 100, 200, 5;
EXPECT_THROW(check_less(function, "x", x, high_vec), std::domain_error);
x = std::numeric_limits<double>::infinity();
high_vec << 10, 20, 30;
EXPECT_THROW(check_less(function, "x", x, high_vec), std::domain_error);
x = std::numeric_limits<double>::infinity();
high_vec << std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity(),
std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x, high_vec), std::domain_error);
}
TEST(ErrorHandlingMat, CheckLess_Matrix_one_indexed_message) {
using stan::math::check_less;
const char* function = "check_less";
double x;
double high;
Eigen::Matrix<double, Eigen::Dynamic, 1> x_vec;
Eigen::Matrix<double, Eigen::Dynamic, 1> high_vec;
x_vec.resize(3);
high_vec.resize(3);
std::string message;
// x_vec, high
x_vec << -5, 0, 5;
high = 5;
try {
check_less(function, "x", x_vec, high);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_NE(std::string::npos, message.find("[3]")) << message;
// x_vec, high_vec
x_vec << -5, 5, 0;
high_vec << 10, 5, 10;
try {
check_less(function, "x", x_vec, high_vec);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_NE(std::string::npos, message.find("[2]")) << message;
// x, high_vec
x = 30;
high_vec << 10, 20, 30;
try {
check_less(function, "x", x, high_vec);
FAIL() << "should have thrown";
} catch (std::domain_error& e) {
message = e.what();
} catch (...) {
FAIL() << "threw the wrong error";
}
EXPECT_EQ(std::string::npos, message.find("["))
<< "index provided when x has none" << std::endl
<< message;
}
TEST(ErrorHandlingMat, CheckLess_nan) {
using stan::math::check_less;
const char* function = "check_less";
double nan = std::numeric_limits<double>::quiet_NaN();
Eigen::Matrix<double, Eigen::Dynamic, 1> x_vec(3);
Eigen::Matrix<double, Eigen::Dynamic, 1> low_vec(3);
// x_vec, low_vec
x_vec << -1, 0, 1;
low_vec << -2, -1, 0;
EXPECT_THROW(check_less(function, "x", x_vec, nan), std::domain_error);
for (int i = 0; i < x_vec.size(); i++) {
x_vec << -1, 0, 1;
x_vec(i) = nan;
EXPECT_THROW(check_less(function, "x", x_vec, low_vec), std::domain_error);
}
x_vec << -1, 0, 1;
for (int i = 0; i < low_vec.size(); i++) {
low_vec << -1, 0, 1;
low_vec(i) = nan;
EXPECT_THROW(check_less(function, "x", x_vec, low_vec), std::domain_error);
}
for (int i = 0; i < x_vec.size(); i++) {
x_vec << -1, 0, 1;
low_vec << -2, -1, 0;
x_vec(i) = nan;
for (int j = 0; j < low_vec.size(); j++) {
low_vec(i) = nan;
EXPECT_THROW(check_less(function, "x", x_vec, low_vec),
std::domain_error);
}
}
}
TEST(ErrorHandlingScalar, CheckLess) {
using stan::math::check_less;
const char* function = "check_less";
double x = -10.0;
double lb = 0.0;
EXPECT_NO_THROW(check_less(function, "x", x, lb))
<< "check_less should be true with x < lb";
x = 1.0;
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x > lb";
x = lb;
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x == lb";
x = -std::numeric_limits<double>::infinity();
EXPECT_NO_THROW(check_less(function, "x", x, lb))
<< "check_less should be true with x == -Inf and lb = 0.0";
x = -10.0;
lb = -std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x == -10.0 and lb == -Inf";
x = -std::numeric_limits<double>::infinity();
lb = -std::numeric_limits<double>::infinity();
EXPECT_THROW(check_less(function, "x", x, lb), std::domain_error)
<< "check_less should throw an exception with x == -Inf and lb == -Inf";
}
TEST(ErrorHandlingScalar, CheckLess_nan) {
using stan::math::check_less;
const char* function = "check_less";
double x = 10.0;
double lb = 0.0;
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_THROW(check_less(function, "x", nan, lb), std::domain_error);
EXPECT_THROW(check_less(function, "x", x, nan), std::domain_error);
EXPECT_THROW(check_less(function, "x", nan, nan), std::domain_error);
}
<|endoftext|> |
<commit_before>
#include "journal/player.hpp"
#include <list>
#include <string>
#include <thread>
#include <vector>
#include "benchmark/benchmark.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"
namespace principia {
namespace journal {
// The benchmark is only run if --gtest_filter=PlayerTest.Benchmarks
void BM_PlayForReal(benchmark::State& state) { // NOLINT(runtime/references)
while (state.KeepRunning()) {
Player player(
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160626-143407)");
int count = 0;
while (player.Play()) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0)
<< count << " journal entries replayed";
}
}
}
BENCHMARK(BM_PlayForReal);
class PlayerTest : public ::testing::Test {
protected:
PlayerTest()
: test_info_(testing::UnitTest::GetInstance()->current_test_info()),
test_case_name_(test_info_->test_case_name()),
test_name_(test_info_->name()),
plugin_(interface::principia__NewPlugin("0 s", "0 s", 0)) {}
template<typename Profile>
bool RunIfAppropriate(serialization::Method const& method_in,
serialization::Method const& method_out_return,
Player& player) {
return player.RunIfAppropriate<Profile>(method_in, method_out_return);
}
::testing::TestInfo const* const test_info_;
std::string const test_case_name_;
std::string const test_name_;
std::unique_ptr<ksp_plugin::Plugin> plugin_;
};
TEST_F(PlayerTest, PlayTiny) {
// Do the recording in a separate thread to make sure that it activates using
// a different static variable than the one in the plugin dynamic library.
std::thread recorder([this]() {
Recorder* const r(new Recorder(test_name_ + ".journal.hex"));
Recorder::Activate(r);
{
Method<NewPlugin> m({"1 s", "2 s", 3});
m.Return(plugin_.get());
}
{
const ksp_plugin::Plugin* plugin = plugin_.get();
Method<DeletePlugin> m({&plugin}, {&plugin});
m.Return();
}
Recorder::Deactivate();
});
recorder.join();
Player player(test_name_ + ".journal.hex");
// Replay the journal.
int count = 0;
while (player.Play()) {
++count;
}
EXPECT_EQ(2, count);
}
// This test (a.k.a. benchmark) is only run if the --gtest_filter flag names it
// explicitly.
TEST_F(PlayerTest, Benchmarks) {
if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
benchmark::RunSpecifiedBenchmarks();
}
}
#if 1
// This test is only run if the --gtest_filter flag names it explicitly.
TEST_F(PlayerTest, Debug) {
if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
// An example of how journaling may be used for debugging. You must set
// |path| and fill the |method_in| and |method_out_return| protocol buffers.
std::string path =
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20170312-191519)";
Player player(path);
int count = 0;
while (player.Play()) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0) << count
<< " journal entries replayed";
}
LOG(ERROR) << count << " journal entries in total";
LOG(ERROR) << "Last successful method in:\n"
<< player.last_method_in().DebugString();
LOG(ERROR) << "Last successful method out/return: \n"
<< player.last_method_out_return().DebugString();
#if 0
serialization::Method method_in;
auto* extension = method_in.MutableExtension(
serialization::ReportCollision::extension);
auto* in = extension->mutable_in();
in->set_plugin(355375312);
in->set_vessel1_guid("14b05bd3-9707-4d49-a6be-a7de481f3e0a");
in->set_vessel2_guid("3e6fcb7e-4761-48ed-829f-0adb035f457e");
serialization::Method method_out_return;
method_out_return.MutableExtension(
serialization::ReportCollision::extension);
LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString();
CHECK(RunIfAppropriate<ReportCollision>(method_in,
method_out_return,
player));
#endif
}
}
#endif
} // namespace journal
} // namespace principia
<commit_msg>Comment out replay.<commit_after>
#include "journal/player.hpp"
#include <list>
#include <string>
#include <thread>
#include <vector>
#include "benchmark/benchmark.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"
namespace principia {
namespace journal {
// The benchmark is only run if --gtest_filter=PlayerTest.Benchmarks
void BM_PlayForReal(benchmark::State& state) { // NOLINT(runtime/references)
while (state.KeepRunning()) {
Player player(
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20160626-143407)");
int count = 0;
while (player.Play()) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0)
<< count << " journal entries replayed";
}
}
}
BENCHMARK(BM_PlayForReal);
class PlayerTest : public ::testing::Test {
protected:
PlayerTest()
: test_info_(testing::UnitTest::GetInstance()->current_test_info()),
test_case_name_(test_info_->test_case_name()),
test_name_(test_info_->name()),
plugin_(interface::principia__NewPlugin("0 s", "0 s", 0)) {}
template<typename Profile>
bool RunIfAppropriate(serialization::Method const& method_in,
serialization::Method const& method_out_return,
Player& player) {
return player.RunIfAppropriate<Profile>(method_in, method_out_return);
}
::testing::TestInfo const* const test_info_;
std::string const test_case_name_;
std::string const test_name_;
std::unique_ptr<ksp_plugin::Plugin> plugin_;
};
TEST_F(PlayerTest, PlayTiny) {
// Do the recording in a separate thread to make sure that it activates using
// a different static variable than the one in the plugin dynamic library.
std::thread recorder([this]() {
Recorder* const r(new Recorder(test_name_ + ".journal.hex"));
Recorder::Activate(r);
{
Method<NewPlugin> m({"1 s", "2 s", 3});
m.Return(plugin_.get());
}
{
const ksp_plugin::Plugin* plugin = plugin_.get();
Method<DeletePlugin> m({&plugin}, {&plugin});
m.Return();
}
Recorder::Deactivate();
});
recorder.join();
Player player(test_name_ + ".journal.hex");
// Replay the journal.
int count = 0;
while (player.Play()) {
++count;
}
EXPECT_EQ(2, count);
}
// This test (a.k.a. benchmark) is only run if the --gtest_filter flag names it
// explicitly.
TEST_F(PlayerTest, Benchmarks) {
if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
benchmark::RunSpecifiedBenchmarks();
}
}
#if 0
// This test is only run if the --gtest_filter flag names it explicitly.
TEST_F(PlayerTest, Debug) {
if (testing::FLAGS_gtest_filter == test_case_name_ + "." + test_name_) {
// An example of how journaling may be used for debugging. You must set
// |path| and fill the |method_in| and |method_out_return| protocol buffers.
std::string path =
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20170312-191519)";
Player player(path);
int count = 0;
while (player.Play()) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0) << count
<< " journal entries replayed";
}
LOG(ERROR) << count << " journal entries in total";
LOG(ERROR) << "Last successful method in:\n"
<< player.last_method_in().DebugString();
LOG(ERROR) << "Last successful method out/return: \n"
<< player.last_method_out_return().DebugString();
#if 0
serialization::Method method_in;
auto* extension = method_in.MutableExtension(
serialization::ReportCollision::extension);
auto* in = extension->mutable_in();
in->set_plugin(355375312);
in->set_vessel1_guid("14b05bd3-9707-4d49-a6be-a7de481f3e0a");
in->set_vessel2_guid("3e6fcb7e-4761-48ed-829f-0adb035f457e");
serialization::Method method_out_return;
method_out_return.MutableExtension(
serialization::ReportCollision::extension);
LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString();
CHECK(RunIfAppropriate<ReportCollision>(method_in,
method_out_return,
player));
#endif
}
}
#endif
} // namespace journal
} // namespace principia
<|endoftext|> |
<commit_before>// this node is the dispersion simulation of two wheel robots
// ros communication:
// subscribe to topic "/swarm_sim/two_wheel_robot"
// service client to service "/gazebo/set_joint_properties"
#include <ros/ros.h>
#include <swarm_robot_msg/two_wheel_robot.h>
#include <gazebo_msgs/SetJointProperties.h>
#include <math.h>
// flow control parameters
const double TOPIC_ACTIVE_PERIOD = 1.0; // threshold to tell if a topic is active
const double CONTROL_PERIOD = 0.001;
// simulation control parameters
double spring_length = 0.7; // default spring length, may change from private parameter
double upper_limit_ratio = 0.30;
const int NEIGHBOR_NUM_L_LIMIT = 3;
const int NEIGHBOR_NUM_H_LIMIT = 6;
const double FEEDBACK_RATIO = 0.382/2.0;
const double STABLE_THRESHOLD = 0.02;
// global variables
swarm_robot_msg::two_wheel_robot current_robots;
// time stamp for callback, used to check topic activity
ros::Time two_wheel_robot_topic_timer;
// callback for getting two wheel robot information
void twoWheelRobotCallback(const swarm_robot_msg::two_wheel_robot& input_msg) {
// update the time stamp every time the callback is invoked
two_wheel_robot_topic_timer = ros::Time::now();
current_robots = input_msg; // update in global variables
}
int main(int argc, char **argv) {
ros::init(argc, argv, "two_wheel_robot_dispersion");
ros::NodeHandle nh("~");
// handshake with robot name in parameter server
std::string robot_name;
bool get_name;
get_name = nh.getParam("/swarm_sim/robot_name", robot_name);
if (!get_name) {
ROS_ERROR("simulation environment(parameters) is not set");
return 0;
}
if (robot_name != "two_wheel_robot") {
ROS_ERROR("wrong robot according to parameter server");
return 0;
}
// check if gazebo service set_joint_properties is ready
ros::Duration half_sec(0.5);
bool service_ready = ros::service::exists("/gazebo/set_joint_properties", true);
if (!service_ready) {
// service not ready
while (!service_ready) {
ROS_INFO("waiting for gazebo service set_joint_properties");
half_sec.sleep();
service_ready = ros::service::exists("/gazebo/set_joint_properties", true);
}
}
ROS_INFO("gazebo service set_joint_properties is ready");
// get settings for this simulation from private parameter
bool get_spring_length = nh.getParam("spring_length", spring_length);
if (get_spring_length) {
ROS_INFO_STREAM("using spring length passed in: " << spring_length);
// delete parameter
nh.deleteParam("spring_length");
}
else
ROS_INFO_STREAM("using default spring length: 0.7");
// calculate other parameter depending on spring length
double upper_limit = spring_length * (1 + upper_limit_ratio);
// instantiate a subscriber to topic "/swarm_sim/two_wheel_robot"
ros::Subscriber two_wheel_robot_subscriber
= nh.subscribe("/swarm_sim/two_wheel_robot", 1, twoWheelRobotCallback);
// instantiate a service client for "/gazebo/set_joint_properties"
ros::ServiceClient set_joint_properties_client
= nh.serviceClient<gazebo_msgs::SetJointProperties>("/gazebo/set_joint_properties");
gazebo_msgs::SetJointProperties set_joint_properties_srv_msg;
// usually this is enough for fast response
set_joint_properties_srv_msg.request.ode_joint_config = 1.0;
// initialize callback timer
two_wheel_robot_topic_timer = ros::Time::now();
// delay for a while to avoid false judgement of topic activity
ros::Duration(TOPIC_ACTIVE_PERIOD + 0.1).sleep();
// dispersion control loop
ros::Time timer_now;
ros::Rate loop_rate(1/CONTROL_PERIOD);
bool stop_all_robot_once = false; // stop all robots for one time when topic is inactive
while (ros::ok()) {
// check if two wheel robot topic is active
timer_now = ros::Time::now();
if ((timer_now - two_wheel_robot_topic_timer).toSec() < TOPIC_ACTIVE_PERIOD) {
// the topic is been actively published
// set the stop_all_robot_once flag, prepare when topic out of active state
stop_all_robot_once = true;
// 1.calculate distance between any two robots
int robot_quantity = current_robots.index.size();
double distance[robot_quantity][robot_quantity];
for (int i=0; i<robot_quantity; i++) {
for (int j=i; j<robot_quantity; j++) {
if (i == j) {
// zero for the diagonal
distance[i][j] = 0;
}
else {
distance[i][j] = sqrt(pow(current_robots.x[i] - current_robots.x[j], 2)
+ pow(current_robots.y[i] - current_robots.y[j], 2));
// symmetrical matrix, copy the other side
distance[j][i] = distance[i][j];
}
}
}
// 2.sort the distance and record the index change
double distance_sort[robot_quantity][robot_quantity];
int index_sort[robot_quantity][robot_quantity];
// initialize distance_sort and index_sort
for (int i=0; i<robot_quantity; i++) {
for (int j=0; j<robot_quantity; j++) {
distance_sort[i][j] = distance[i][j];
index_sort[i][j] = j;
}
}
// start sorting, bubble sort method
double distance_temp;
int index_temp;
for (int i=0; i<robot_quantity; i++) {
for (int j=0; j<robot_quantity-1; j++) {
for (int k=0; k<robot_quantity-1-j; k++) {
if (distance_sort[i][k] > distance_sort[i][k+1]) {
// switch between these two distances
distance_temp = distance_sort[i][k];
distance_sort[i][k] = distance_sort[i][k+1];
distance_sort[i][k+1] = distance_temp;
// also switch corresponding indices
index_temp = index_sort[i][k];
index_sort[i][k] = index_sort[i][k+1];
index_sort[i][k+1] = index_temp;
}
}
}
}
// 3.find all neighbors that will be used in force feedback control
// find all the neighbors within the upper limit, choose closest 6 if exceed 6
// if neighbors are sparse, override upper limit and choose cloest 3
// i.e., there are 3 ~ 6 neighbors for each robot
int neighbor_num[robot_quantity]; // the number of vallid neighbors
// no need to record index
// they are the first neighbor_num robots in the sorted list
for (int i=0; i<robot_quantity; i++) {
// compare robot quantity with neighbor number limits
if ((robot_quantity - 1) <= NEIGHBOR_NUM_L_LIMIT) {
// (robot_quantity - 1) is the largest neighbor number for each robot
// set neighbor number to the largest possible
neighbor_num[i] = robot_quantity - 1;
}
else {
neighbor_num[i] = NEIGHBOR_NUM_L_LIMIT; // initialize with lower limit
for (int j=NEIGHBOR_NUM_L_LIMIT+1; j<robot_quantity; j++) {
// (NEIGHBOR_NUM_L_LIMIT+1) is the index in the distance_sort
// of the first robot except itself and the neighbors
if (distance_sort[i][j] < upper_limit) {
neighbor_num[i] = neighbor_num[i] + 1;
if (neighbor_num[i] == NEIGHBOR_NUM_H_LIMIT)
break;
}
}
}
}
// 4.calculate feedback vector for each robot
double feedback_vector[robot_quantity][2]; // vector in x and y for each robot
double distance_diff;
for (int i=0; i<robot_quantity; i++) {
feedback_vector[i][0] = 0.0;
feedback_vector[i][1] = 0.0;
for (int j=0; j<=neighbor_num[i]; j++) {
distance_diff = distance_sort[i][j] - spring_length;
// feedback on x
feedback_vector[i][0] = feedback_vector[i][0] + FEEDBACK_RATIO * distance_diff
* (current_robots.x[index_sort[i][j]] - current_robots.x[i]) / distance_sort[i][j];
// feedback on y
feedback_vector[i][1] = feedback_vector[i][1] + FEEDBACK_RATIO * distance_diff
* (current_robots.y[index_sort[i][j]] - current_robots.y[i]) / distance_sort[i][j];
}
}
// 5.calculate the wheel velocities and send service request
// the wheel velocities are calculate so that the robot will move
// in a constant radius curve to the destination defined by the feedback vector
double wheel_vel[robot_quantity][2];
}
else {
// the topic is not active
if (stop_all_robot_once) {
// set wheel speed of all robots to zero according to last topic update
// reset the stop_all_robot_once flag
stop_all_robot_once = false;
}
}
loop_rate.sleep();
ros::spinOnce(); // let the global variables update
}
return 0;
}
<commit_msg>update wheel vel calculation for dispersion<commit_after>// this node is the dispersion simulation of two wheel robots
// ros communication:
// subscribe to topic "/swarm_sim/two_wheel_robot"
// service client to service "/gazebo/set_joint_properties"
#include <ros/ros.h>
#include <swarm_robot_msg/two_wheel_robot.h>
#include <gazebo_msgs/SetJointProperties.h>
#include <math.h>
// flow control parameters
const double TOPIC_ACTIVE_PERIOD = 1.0; // threshold to tell if a topic is active
const double CONTROL_PERIOD = 0.001;
// simulation control parameters
double spring_length = 0.7; // default spring length, may change from private parameter
double upper_limit_ratio = 0.30;
const int NEIGHBOR_NUM_L_LIMIT = 3;
const int NEIGHBOR_NUM_H_LIMIT = 6;
const double DISTANCE_FEEDBACK_RATIO = 0.382/2.0;
const double VEL_RATIO = 1.0; // the ratio of robot velocity relative to feedback vector
const double STABLE_THRESHOLD = 0.02;
const double LEFT_WHEEL_POSITION = -0.0157;
const double RIGHT_WHEEL_POSITION = 0.0157; // right is positive direction
// global variables
swarm_robot_msg::two_wheel_robot current_robots;
// time stamp for callback, used to check topic activity
ros::Time two_wheel_robot_topic_timer;
// callback for getting two wheel robot information
void twoWheelRobotCallback(const swarm_robot_msg::two_wheel_robot& input_msg) {
// update the time stamp every time the callback is invoked
two_wheel_robot_topic_timer = ros::Time::now();
current_robots = input_msg; // update in global variables
}
// int to string converter
std::string intToString(int a) {
std::stringstream ss;
ss << a;
return ss.str();
}
int main(int argc, char **argv) {
ros::init(argc, argv, "two_wheel_robot_dispersion");
ros::NodeHandle nh("~");
// handshake with robot name in parameter server
std::string robot_name;
bool get_name;
get_name = nh.getParam("/swarm_sim/robot_name", robot_name);
if (!get_name) {
ROS_ERROR("simulation environment(parameters) is not set");
return 0;
}
if (robot_name != "two_wheel_robot") {
ROS_ERROR("wrong robot according to parameter server");
return 0;
}
// check if gazebo service set_joint_properties is ready
ros::Duration half_sec(0.5);
bool service_ready = ros::service::exists("/gazebo/set_joint_properties", true);
if (!service_ready) {
// service not ready
while (!service_ready) {
ROS_INFO("waiting for gazebo service set_joint_properties");
half_sec.sleep();
service_ready = ros::service::exists("/gazebo/set_joint_properties", true);
}
}
ROS_INFO("gazebo service set_joint_properties is ready");
// get settings for this simulation from private parameter
bool get_spring_length = nh.getParam("spring_length", spring_length);
if (get_spring_length) {
ROS_INFO_STREAM("using spring length passed in: " << spring_length);
// delete parameter
nh.deleteParam("spring_length");
}
else
ROS_INFO_STREAM("using default spring length: 0.7");
// calculate other parameter depending on spring length
double upper_limit = spring_length * (1 + upper_limit_ratio);
// instantiate a subscriber to topic "/swarm_sim/two_wheel_robot"
ros::Subscriber two_wheel_robot_subscriber
= nh.subscribe("/swarm_sim/two_wheel_robot", 1, twoWheelRobotCallback);
// instantiate a service client for "/gazebo/set_joint_properties"
ros::ServiceClient set_joint_properties_client
= nh.serviceClient<gazebo_msgs::SetJointProperties>("/gazebo/set_joint_properties");
gazebo_msgs::SetJointProperties set_joint_properties_srv_msg;
// usually this is enough for fast response
set_joint_properties_srv_msg.request.ode_joint_config.fmax[0] = 1.0;
// initialize callback timer
two_wheel_robot_topic_timer = ros::Time::now();
// delay for a while to avoid false judgement of topic activity
ros::Duration(TOPIC_ACTIVE_PERIOD + 0.1).sleep();
// dispersion control loop
ros::Time timer_now;
ros::Rate loop_rate(1/CONTROL_PERIOD);
bool stop_all_robot_once = false; // stop all robots for one time when topic is inactive
while (ros::ok()) {
// check if two wheel robot topic is active
timer_now = ros::Time::now();
if ((timer_now - two_wheel_robot_topic_timer).toSec() < TOPIC_ACTIVE_PERIOD) {
// the topic is been actively published
// set the stop_all_robot_once flag, prepare when topic out of active state
stop_all_robot_once = true;
// 1.calculate distance between any two robots
int robot_quantity = current_robots.index.size();
double distance[robot_quantity][robot_quantity];
for (int i=0; i<robot_quantity; i++) {
for (int j=i; j<robot_quantity; j++) {
if (i == j) {
// zero for the diagonal
distance[i][j] = 0;
}
else {
distance[i][j] = sqrt(pow(current_robots.x[i] - current_robots.x[j], 2)
+ pow(current_robots.y[i] - current_robots.y[j], 2));
// symmetrical matrix, copy the other side
distance[j][i] = distance[i][j];
}
}
}
// 2.sort the distance and record the index change
double distance_sort[robot_quantity][robot_quantity];
int index_sort[robot_quantity][robot_quantity];
// initialize distance_sort and index_sort
for (int i=0; i<robot_quantity; i++) {
for (int j=0; j<robot_quantity; j++) {
distance_sort[i][j] = distance[i][j];
index_sort[i][j] = j;
}
}
// start sorting, bubble sort method
double distance_temp;
int index_temp;
for (int i=0; i<robot_quantity; i++) {
for (int j=0; j<robot_quantity-1; j++) {
for (int k=0; k<robot_quantity-1-j; k++) {
if (distance_sort[i][k] > distance_sort[i][k+1]) {
// switch between these two distances
distance_temp = distance_sort[i][k];
distance_sort[i][k] = distance_sort[i][k+1];
distance_sort[i][k+1] = distance_temp;
// also switch corresponding indices
index_temp = index_sort[i][k];
index_sort[i][k] = index_sort[i][k+1];
index_sort[i][k+1] = index_temp;
}
}
}
}
// 3.find all neighbors that will be used in force feedback control
// find all the neighbors within the upper limit, choose closest 6 if exceed 6
// if neighbors are sparse, override upper limit and choose cloest 3
// i.e., there are 3 ~ 6 neighbors for each robot
int neighbor_num[robot_quantity]; // the number of vallid neighbors
// no need to record index
// they are the first neighbor_num robots in the sorted list
for (int i=0; i<robot_quantity; i++) {
// compare robot quantity with neighbor number limits
if ((robot_quantity - 1) <= NEIGHBOR_NUM_L_LIMIT) {
// (robot_quantity - 1) is the largest neighbor number for each robot
// set neighbor number to the largest possible
neighbor_num[i] = robot_quantity - 1;
}
else {
neighbor_num[i] = NEIGHBOR_NUM_L_LIMIT; // initialize with lower limit
for (int j=NEIGHBOR_NUM_L_LIMIT+1; j<robot_quantity; j++) {
// (NEIGHBOR_NUM_L_LIMIT+1) is the index in the distance_sort
// of the first robot except itself and the neighbors
if (distance_sort[i][j] < upper_limit) {
neighbor_num[i] = neighbor_num[i] + 1;
if (neighbor_num[i] == NEIGHBOR_NUM_H_LIMIT)
break;
}
}
}
}
// 4.calculate feedback vector for each robot
double feedback_vector[robot_quantity][2]; // vector in x and y for each robot
double distance_diff;
for (int i=0; i<robot_quantity; i++) {
feedback_vector[i][0] = 0.0;
feedback_vector[i][1] = 0.0;
for (int j=0; j<=neighbor_num[i]; j++) {
distance_diff = distance_sort[i][j] - spring_length;
// feedback on x
feedback_vector[i][0] = feedback_vector[i][0] + DISTANCE_FEEDBACK_RATIO * distance_diff
* (current_robots.x[index_sort[i][j]] - current_robots.x[i]) / distance_sort[i][j];
// feedback on y
feedback_vector[i][1] = feedback_vector[i][1] + DISTANCE_FEEDBACK_RATIO * distance_diff
* (current_robots.y[index_sort[i][j]] - current_robots.y[i]) / distance_sort[i][j];
}
}
// calculate the length and direction of feedback vector
double feedback_vector_length[robot_quantity];
double feedback_vector_direction[robot_quantity];
for (int i=0; i<robot_quantity; i++) {
feedback_vector_length[i]
= sqrt(pow(feedback_vector[i][0], 2) + pow(feedback_vector[i][1], 2));
feedback_vector_direction[i] = atan2(feedback_vector[i][1], feedback_vector[i][0]);
}
// 5.calculate the wheel velocities
// the wheel velocities are calculate so that the robot will move
// in a constant radius curve to the destination defined by the feedback vector
double wheel_vel[robot_quantity][2]; // vel of left and right wheels
// relative angle between the feedback vector and the robot orientation
double relative_direction[robot_quantity];
double wheel_rotation_center[robot_quantity];
bool rotation_direction_ccw[robot_quantity]; // true is ccw, false is cw
for (int i=0; i<robot_quantity; i++) {
relative_direction[i] = feedback_vector_direction[i] - current_robots.orientation[i];
// both feedback vector direction and robot orientation are in range of [-M_PI, M_PI]
// the difference is in range of [-2*M_PI, 2*M_PI], will convert to [-M_PI, M_PI]
if (relative_direction[i] > M_PI)
relative_direction[i] = relative_direction[i] - 2*M_PI;
if (relative_direction[i] < -M_PI)
relative_direction[i] = relative_direction[i] + 2*M_PI;
// now we have relative direction and length of feedback vector
// next step is converting them to wheel rotation center and rotation direction
// wheel rotation center is on the axis of two rotation wheels
// left side is negative, right side is positive
// rotation direction is either ccw or cw, relative to wheel rotation center
// divide relative direction into four quarters
if (relative_direction[i] > 0 && relative_direction[i] <= M_PI/2) {
// going forward and rotate ccw
wheel_rotation_center[i]
= -feedback_vector_length[i]/2 / cos(M_PI/2 - relative_direction[i]);
rotation_direction_ccw[i] = true;
}
else if (relative_direction[i] > M_PI/2 && relative_direction[i] < M_PI) {
// going backward and rotate cw
wheel_rotation_center[i]
= -feedback_vector_length[i]/2 / cos(relative_direction[i] - M_PI/2);
rotation_direction_ccw[i] = false;
}
else if (relative_direction[i] >=-M_PI/2 && relative_direction[i] < 0) {
// going forward and rotate cw
wheel_rotation_center[i]
= feedback_vector_length[i]/2 / cos(relative_direction[i] + M_PI/2);
rotation_direction_ccw[i] = false;
}
else if (relative_direction[i] > -M_PI && relative_direction[i] < -M_PI/2) {
// going backward and rotate ccw
wheel_rotation_center[i]
= feedback_vector_length[i]/2 / cos(-M_PI/2 - relative_direction[i]);
rotation_direction_ccw[i] = true;
}
else if (relative_direction[i] == 0){
// very unlikely
ROS_WARN("feedback vector relative direction is 0");
wheel_rotation_center[i] = -100; // a very large number
rotation_direction_ccw[i] = true;
}
else if (relative_direction[i] == -M_PI || relative_direction[i] == M_PI) {
// very unlikely
ROS_WARN("feedback vector relative direction is -M_PI or M_PI");
wheel_rotation_center[i] = -100;
rotation_direction_ccw[i] = false;
}
// calculate wheel velocity here
if (wheel_rotation_center[i] <= 0 && rotation_direction_ccw[i] == true) {
// rotation center at left side, and rotate ccw
// the velocity of the center of the robot: feedback_vector_length[i] * VEL_RATIO
// left wheel
wheel_vel[i][0] = feedback_vector_length[i] * VEL_RATIO
* (LEFT_WHEEL_POSITION - wheel_rotation_center[i]) / (0 - wheel_rotation_center[i]);
// right wheel
wheel_vel[i][1] = feedback_vector_length[i] * VEL_RATIO
* (RIGHT_WHEEL_POSITION - wheel_rotation_center[i]) / (0 - wheel_rotation_center[i]);
}
else if (wheel_rotation_center[i] <= 0 && rotation_direction_ccw[i] == false) {
// rotation center at left side, and rotate cw
// left wheel
wheel_vel[i][0] = -feedback_vector_length[i] * VEL_RATIO
* (LEFT_WHEEL_POSITION - wheel_rotation_center[i]) / (0 - wheel_rotation_center[i]);
// right wheel
wheel_vel[i][1] = -feedback_vector_length[i] * VEL_RATIO
* (RIGHT_WHEEL_POSITION - wheel_rotation_center[i]) / (0 - wheel_rotation_center[i]);
}
else if (wheel_rotation_center[i] > 0 && rotation_direction_ccw[i] == false) {
// rotation center at right side, and rotate cw
// left wheel
wheel_vel[i][0] = feedback_vector_length[i] * VEL_RATIO
* (wheel_rotation_center[i] - LEFT_WHEEL_POSITION) / (wheel_rotation_center[i] - 0);
// right wheel
wheel_vel[i][1] = feedback_vector_length[i] * VEL_RATIO
* (wheel_rotation_center[i] - RIGHT_WHEEL_POSITION) / (wheel_rotation_center[i] - 0);
}
else if (wheel_rotation_center[i] > 0 && rotation_direction_ccw[i] == true) {
// rotation center at right side, and rotate ccw
// left wheel
wheel_vel[i][0] = -feedback_vector_length[i] * VEL_RATIO
* (wheel_rotation_center[i] - LEFT_WHEEL_POSITION) / (wheel_rotation_center[i] - 0);
// right wheel
wheel_vel[i][1] = -feedback_vector_length[i] * VEL_RATIO
* (wheel_rotation_center[i] - RIGHT_WHEEL_POSITION) / (wheel_rotation_center[i] - 0);
}
}
// 6. send service request of wheel velocities
for (int i=0; i<robot_quantity; i++) {
// left wheel
set_joint_properties_srv_msg.request.joint_name
= "two_wheel_robot_" + intToString(i) + "::left_motor";
set_joint_properties_srv_msg.request.ode_joint_config.vel[0] = wheel_vel[i][0];
}
}
else {
// the topic is not active
if (stop_all_robot_once) {
// set wheel speed of all robots to zero according to last topic update
// reset the stop_all_robot_once flag
stop_all_robot_once = false;
}
}
loop_rate.sleep();
ros::spinOnce(); // let the global variables update
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_view_host_factory.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/tab_contents/interstitial_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/browser/ui/views/sad_tab_view.h"
#include "chrome/browser/ui/views/tab_contents/render_view_context_menu_views.h"
#include "gfx/canvas_skia_paint.h"
#include "gfx/point.h"
#include "gfx/rect.h"
#include "gfx/size.h"
#include "views/controls/native/native_view_host.h"
#include "views/fill_layout.h"
#include "views/focus/focus_manager.h"
#include "views/focus/view_storage.h"
#include "views/screen.h"
#include "views/widget/widget.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationsMask;
using WebKit::WebInputEvent;
// static
TabContentsView* TabContentsView::Create(TabContents* tab_contents) {
return new TabContentsViewViews(tab_contents);
}
TabContentsViewViews::TabContentsViewViews(TabContents* tab_contents)
: TabContentsView(tab_contents),
sad_tab_(NULL),
ignore_next_char_event_(false) {
last_focused_view_storage_id_ =
views::ViewStorage::GetInstance()->CreateStorageID();
SetLayoutManager(new views::FillLayout());
}
TabContentsViewViews::~TabContentsViewViews() {
// Make sure to remove any stored view we may still have in the ViewStorage.
//
// It is possible the view went away before us, so we only do this if the
// view is registered.
views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
view_storage->RemoveView(last_focused_view_storage_id_);
}
void TabContentsViewViews::AttachConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
// TODO(anicolao): reimplement all dialogs as DOMUI
NOTIMPLEMENTED();
}
void TabContentsViewViews::RemoveConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
// TODO(anicolao): reimplement all dialogs as DOMUI
NOTIMPLEMENTED();
}
void TabContentsViewViews::CreateView(const gfx::Size& initial_size) {
SetBounds(gfx::Rect(bounds().origin(), initial_size));
}
RenderWidgetHostView* TabContentsViewViews::CreateViewForWidget(
RenderWidgetHost* render_widget_host) {
if (render_widget_host->view()) {
// During testing, the view will already be set up in most cases to the
// test view, so we don't want to clobber it with a real one. To verify that
// this actually is happening (and somebody isn't accidentally creating the
// view twice), we check for the RVH Factory, which will be set when we're
// making special ones (which go along with the special views).
DCHECK(RenderViewHostFactory::has_factory());
return render_widget_host->view();
}
// If we were showing sad tab, remove it now.
if (sad_tab_ != NULL) {
RemoveChildView(sad_tab_.get());
sad_tab_.reset();
}
RenderWidgetHostViewViews* view =
new RenderWidgetHostViewViews(render_widget_host);
AddChildView(view);
view->Show();
view->InitAsChild();
// TODO(anicolao): implement drag'n'drop hooks if needed
return view;
}
gfx::NativeView TabContentsViewViews::GetNativeView() const {
return GetWidget()->GetNativeView();
}
gfx::NativeView TabContentsViewViews::GetContentNativeView() const {
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (!rwhv)
return NULL;
return rwhv->GetNativeView();
}
gfx::NativeWindow TabContentsViewViews::GetTopLevelNativeWindow() const {
GtkWidget* window = gtk_widget_get_ancestor(GetNativeView(), GTK_TYPE_WINDOW);
return window ? GTK_WINDOW(window) : NULL;
}
void TabContentsViewViews::GetContainerBounds(gfx::Rect* out) const {
*out = bounds();
}
void TabContentsViewViews::StartDragging(const WebDropData& drop_data,
WebDragOperationsMask ops,
const SkBitmap& image,
const gfx::Point& image_offset) {
// TODO(anicolao): implement dragging
}
void TabContentsViewViews::SetPageTitle(const std::wstring& title) {
// TODO(anicolao): figure out if there's anything useful to do here
}
void TabContentsViewViews::OnTabCrashed(base::TerminationStatus status,
int /* error_code */) {
if (sad_tab_ != NULL)
return;
sad_tab_.reset(new SadTabView(
tab_contents(),
status == TERMINATION_STATUS_PROCESS_WAS_KILLED ?
SadTabView::KILLED : SadTabView::CRASHED));
RemoveAllChildViews(true);
AddChildView(sad_tab_.get());
Layout();
}
void TabContentsViewViews::SizeContents(const gfx::Size& size) {
WasSized(size);
// We need to send this immediately.
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (rwhv)
rwhv->SetSize(size);
}
void TabContentsViewViews::Focus() {
if (tab_contents()->interstitial_page()) {
tab_contents()->interstitial_page()->Focus();
return;
}
if (tab_contents()->is_crashed() && sad_tab_ != NULL) {
sad_tab_->RequestFocus();
return;
}
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (rwhv)
rwhv->Focus();
}
void TabContentsViewViews::SetInitialFocus() {
if (tab_contents()->FocusLocationBarByDefault())
tab_contents()->SetFocusToLocationBar(false);
else
Focus();
}
void TabContentsViewViews::StoreFocus() {
views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
view_storage->RemoveView(last_focused_view_storage_id_);
views::FocusManager* focus_manager =
views::FocusManager::GetFocusManagerForNativeView(GetNativeView());
if (focus_manager) {
// |focus_manager| can be NULL if the tab has been detached but still
// exists.
views::View* focused_view = focus_manager->GetFocusedView();
if (focused_view)
view_storage->StoreView(last_focused_view_storage_id_, focused_view);
}
}
void TabContentsViewViews::RestoreFocus() {
views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
views::View* last_focused_view =
view_storage->RetrieveView(last_focused_view_storage_id_);
if (!last_focused_view) {
SetInitialFocus();
} else {
views::FocusManager* focus_manager =
views::FocusManager::GetFocusManagerForNativeView(GetNativeView());
// If you hit this DCHECK, please report it to Jay (jcampan).
DCHECK(focus_manager != NULL) << "No focus manager when restoring focus.";
if (last_focused_view->IsFocusableInRootView() && focus_manager &&
focus_manager->ContainsView(last_focused_view)) {
last_focused_view->RequestFocus();
} else {
// The focused view may not belong to the same window hierarchy (e.g.
// if the location bar was focused and the tab is dragged out), or it may
// no longer be focusable (e.g. if the location bar was focused and then
// we switched to fullscreen mode). In that case we default to the
// default focus.
SetInitialFocus();
}
view_storage->RemoveView(last_focused_view_storage_id_);
}
}
void TabContentsViewViews::DidChangeBounds(const gfx::Rect& previous,
const gfx::Rect& current) {
if (IsVisibleInRootView())
WasSized(gfx::Size(current.width(), current.height()));
}
void TabContentsViewViews::Paint(gfx::Canvas* canvas) {
}
void TabContentsViewViews::UpdateDragCursor(WebDragOperation operation) {
NOTIMPLEMENTED();
// It's not even clear a drag cursor will make sense for touch.
// TODO(anicolao): implement dragging
}
void TabContentsViewViews::GotFocus() {
if (tab_contents()->delegate())
tab_contents()->delegate()->TabContentsFocused(tab_contents());
}
void TabContentsViewViews::TakeFocus(bool reverse) {
if (tab_contents()->delegate() &&
!tab_contents()->delegate()->TakeFocus(reverse)) {
views::FocusManager* focus_manager =
views::FocusManager::GetFocusManagerForNativeView(GetNativeView());
// We may not have a focus manager if the tab has been switched before this
// message arrived.
if (focus_manager)
focus_manager->AdvanceFocus(reverse);
}
}
void TabContentsViewViews::VisibilityChanged(views::View *, bool is_visible) {
if (is_visible) {
WasShown();
} else {
WasHidden();
}
}
void TabContentsViewViews::ShowContextMenu(const ContextMenuParams& params) {
// Allow delegates to handle the context menu operation first.
if (tab_contents()->delegate()->HandleContextMenu(params))
return;
context_menu_.reset(new RenderViewContextMenuViews(tab_contents(), params));
context_menu_->Init();
gfx::Point screen_point(params.x, params.y);
RenderWidgetHostViewViews* rwhv = static_cast<RenderWidgetHostViewViews*>
(tab_contents()->GetRenderWidgetHostView());
if (rwhv) {
views::View::ConvertPointToScreen(rwhv, &screen_point);
}
// Enable recursive tasks on the message loop so we can get updates while
// the context menu is being displayed.
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
context_menu_->RunMenuAt(screen_point.x(), screen_point.y());
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
void TabContentsViewViews::ShowPopupMenu(const gfx::Rect& bounds,
int item_height,
double item_font_size,
int selected_item,
const std::vector<WebMenuItem>& items,
bool right_aligned) {
// External popup menus are only used on Mac.
NOTREACHED();
}
void TabContentsViewViews::WasHidden() {
tab_contents()->HideContents();
}
void TabContentsViewViews::WasShown() {
tab_contents()->ShowContents();
}
void TabContentsViewViews::WasSized(const gfx::Size& size) {
// We have to check that the RenderWidgetHostView is the proper size.
// It can be wrong in cases where the renderer has died and the host
// view needed to be recreated.
bool needs_resize = size != size_;
if (needs_resize) {
size_ = size;
if (tab_contents()->interstitial_page())
tab_contents()->interstitial_page()->SetSize(size);
}
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (rwhv && rwhv->GetViewBounds().size() != size)
rwhv->SetSize(size);
if (needs_resize)
SetFloatingPosition(size);
}
void TabContentsViewViews::SetFloatingPosition(const gfx::Size& size) {
// TODO(anicolao): rework this once we have DOMUI views for dialogs
SetBounds(x(), y(), size.width(), size.height());
}
<commit_msg>Fix touch compile.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/browser/download/download_shelf.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_view_host_factory.h"
#include "chrome/browser/renderer_host/render_widget_host_view_views.h"
#include "chrome/browser/tab_contents/interstitial_page.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/browser/ui/views/sad_tab_view.h"
#include "chrome/browser/ui/views/tab_contents/render_view_context_menu_views.h"
#include "gfx/canvas_skia_paint.h"
#include "gfx/point.h"
#include "gfx/rect.h"
#include "gfx/size.h"
#include "views/controls/native/native_view_host.h"
#include "views/fill_layout.h"
#include "views/focus/focus_manager.h"
#include "views/focus/view_storage.h"
#include "views/screen.h"
#include "views/widget/widget.h"
using WebKit::WebDragOperation;
using WebKit::WebDragOperationsMask;
using WebKit::WebInputEvent;
// static
TabContentsView* TabContentsView::Create(TabContents* tab_contents) {
return new TabContentsViewViews(tab_contents);
}
TabContentsViewViews::TabContentsViewViews(TabContents* tab_contents)
: TabContentsView(tab_contents),
sad_tab_(NULL),
ignore_next_char_event_(false) {
last_focused_view_storage_id_ =
views::ViewStorage::GetInstance()->CreateStorageID();
SetLayoutManager(new views::FillLayout());
}
TabContentsViewViews::~TabContentsViewViews() {
// Make sure to remove any stored view we may still have in the ViewStorage.
//
// It is possible the view went away before us, so we only do this if the
// view is registered.
views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
view_storage->RemoveView(last_focused_view_storage_id_);
}
void TabContentsViewViews::AttachConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
// TODO(anicolao): reimplement all dialogs as DOMUI
NOTIMPLEMENTED();
}
void TabContentsViewViews::RemoveConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
// TODO(anicolao): reimplement all dialogs as DOMUI
NOTIMPLEMENTED();
}
void TabContentsViewViews::CreateView(const gfx::Size& initial_size) {
SetBounds(gfx::Rect(bounds().origin(), initial_size));
}
RenderWidgetHostView* TabContentsViewViews::CreateViewForWidget(
RenderWidgetHost* render_widget_host) {
if (render_widget_host->view()) {
// During testing, the view will already be set up in most cases to the
// test view, so we don't want to clobber it with a real one. To verify that
// this actually is happening (and somebody isn't accidentally creating the
// view twice), we check for the RVH Factory, which will be set when we're
// making special ones (which go along with the special views).
DCHECK(RenderViewHostFactory::has_factory());
return render_widget_host->view();
}
// If we were showing sad tab, remove it now.
if (sad_tab_ != NULL) {
RemoveChildView(sad_tab_.get());
sad_tab_.reset();
}
RenderWidgetHostViewViews* view =
new RenderWidgetHostViewViews(render_widget_host);
AddChildView(view);
view->Show();
view->InitAsChild();
// TODO(anicolao): implement drag'n'drop hooks if needed
return view;
}
gfx::NativeView TabContentsViewViews::GetNativeView() const {
return GetWidget()->GetNativeView();
}
gfx::NativeView TabContentsViewViews::GetContentNativeView() const {
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (!rwhv)
return NULL;
return rwhv->GetNativeView();
}
gfx::NativeWindow TabContentsViewViews::GetTopLevelNativeWindow() const {
GtkWidget* window = gtk_widget_get_ancestor(GetNativeView(), GTK_TYPE_WINDOW);
return window ? GTK_WINDOW(window) : NULL;
}
void TabContentsViewViews::GetContainerBounds(gfx::Rect* out) const {
*out = bounds();
}
void TabContentsViewViews::StartDragging(const WebDropData& drop_data,
WebDragOperationsMask ops,
const SkBitmap& image,
const gfx::Point& image_offset) {
// TODO(anicolao): implement dragging
}
void TabContentsViewViews::SetPageTitle(const std::wstring& title) {
// TODO(anicolao): figure out if there's anything useful to do here
}
void TabContentsViewViews::OnTabCrashed(base::TerminationStatus status,
int /* error_code */) {
if (sad_tab_ != NULL)
return;
sad_tab_.reset(new SadTabView(
tab_contents(),
status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED ?
SadTabView::KILLED : SadTabView::CRASHED));
RemoveAllChildViews(true);
AddChildView(sad_tab_.get());
Layout();
}
void TabContentsViewViews::SizeContents(const gfx::Size& size) {
WasSized(size);
// We need to send this immediately.
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (rwhv)
rwhv->SetSize(size);
}
void TabContentsViewViews::Focus() {
if (tab_contents()->interstitial_page()) {
tab_contents()->interstitial_page()->Focus();
return;
}
if (tab_contents()->is_crashed() && sad_tab_ != NULL) {
sad_tab_->RequestFocus();
return;
}
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (rwhv)
rwhv->Focus();
}
void TabContentsViewViews::SetInitialFocus() {
if (tab_contents()->FocusLocationBarByDefault())
tab_contents()->SetFocusToLocationBar(false);
else
Focus();
}
void TabContentsViewViews::StoreFocus() {
views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
view_storage->RemoveView(last_focused_view_storage_id_);
views::FocusManager* focus_manager =
views::FocusManager::GetFocusManagerForNativeView(GetNativeView());
if (focus_manager) {
// |focus_manager| can be NULL if the tab has been detached but still
// exists.
views::View* focused_view = focus_manager->GetFocusedView();
if (focused_view)
view_storage->StoreView(last_focused_view_storage_id_, focused_view);
}
}
void TabContentsViewViews::RestoreFocus() {
views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
views::View* last_focused_view =
view_storage->RetrieveView(last_focused_view_storage_id_);
if (!last_focused_view) {
SetInitialFocus();
} else {
views::FocusManager* focus_manager =
views::FocusManager::GetFocusManagerForNativeView(GetNativeView());
// If you hit this DCHECK, please report it to Jay (jcampan).
DCHECK(focus_manager != NULL) << "No focus manager when restoring focus.";
if (last_focused_view->IsFocusableInRootView() && focus_manager &&
focus_manager->ContainsView(last_focused_view)) {
last_focused_view->RequestFocus();
} else {
// The focused view may not belong to the same window hierarchy (e.g.
// if the location bar was focused and the tab is dragged out), or it may
// no longer be focusable (e.g. if the location bar was focused and then
// we switched to fullscreen mode). In that case we default to the
// default focus.
SetInitialFocus();
}
view_storage->RemoveView(last_focused_view_storage_id_);
}
}
void TabContentsViewViews::DidChangeBounds(const gfx::Rect& previous,
const gfx::Rect& current) {
if (IsVisibleInRootView())
WasSized(gfx::Size(current.width(), current.height()));
}
void TabContentsViewViews::Paint(gfx::Canvas* canvas) {
}
void TabContentsViewViews::UpdateDragCursor(WebDragOperation operation) {
NOTIMPLEMENTED();
// It's not even clear a drag cursor will make sense for touch.
// TODO(anicolao): implement dragging
}
void TabContentsViewViews::GotFocus() {
if (tab_contents()->delegate())
tab_contents()->delegate()->TabContentsFocused(tab_contents());
}
void TabContentsViewViews::TakeFocus(bool reverse) {
if (tab_contents()->delegate() &&
!tab_contents()->delegate()->TakeFocus(reverse)) {
views::FocusManager* focus_manager =
views::FocusManager::GetFocusManagerForNativeView(GetNativeView());
// We may not have a focus manager if the tab has been switched before this
// message arrived.
if (focus_manager)
focus_manager->AdvanceFocus(reverse);
}
}
void TabContentsViewViews::VisibilityChanged(views::View *, bool is_visible) {
if (is_visible) {
WasShown();
} else {
WasHidden();
}
}
void TabContentsViewViews::ShowContextMenu(const ContextMenuParams& params) {
// Allow delegates to handle the context menu operation first.
if (tab_contents()->delegate()->HandleContextMenu(params))
return;
context_menu_.reset(new RenderViewContextMenuViews(tab_contents(), params));
context_menu_->Init();
gfx::Point screen_point(params.x, params.y);
RenderWidgetHostViewViews* rwhv = static_cast<RenderWidgetHostViewViews*>
(tab_contents()->GetRenderWidgetHostView());
if (rwhv) {
views::View::ConvertPointToScreen(rwhv, &screen_point);
}
// Enable recursive tasks on the message loop so we can get updates while
// the context menu is being displayed.
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
context_menu_->RunMenuAt(screen_point.x(), screen_point.y());
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
void TabContentsViewViews::ShowPopupMenu(const gfx::Rect& bounds,
int item_height,
double item_font_size,
int selected_item,
const std::vector<WebMenuItem>& items,
bool right_aligned) {
// External popup menus are only used on Mac.
NOTREACHED();
}
void TabContentsViewViews::WasHidden() {
tab_contents()->HideContents();
}
void TabContentsViewViews::WasShown() {
tab_contents()->ShowContents();
}
void TabContentsViewViews::WasSized(const gfx::Size& size) {
// We have to check that the RenderWidgetHostView is the proper size.
// It can be wrong in cases where the renderer has died and the host
// view needed to be recreated.
bool needs_resize = size != size_;
if (needs_resize) {
size_ = size;
if (tab_contents()->interstitial_page())
tab_contents()->interstitial_page()->SetSize(size);
}
RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView();
if (rwhv && rwhv->GetViewBounds().size() != size)
rwhv->SetSize(size);
if (needs_resize)
SetFloatingPosition(size);
}
void TabContentsViewViews::SetFloatingPosition(const gfx::Size& size) {
// TODO(anicolao): rework this once we have DOMUI views for dialogs
SetBounds(x(), y(), size.width(), size.height());
}
<|endoftext|> |
<commit_before>#include <sirikata/core/util/Standard.hh>
#include <sirikata/core/transfer/TransferMediator.hpp>
#include <sirikata/core/transfer/MaxPriorityAggregation.hpp>
#include <stdio.h>
using namespace std;
AUTO_SINGLETON_INSTANCE(Sirikata::Transfer::TransferMediator);
using namespace Sirikata;
using namespace Sirikata::Transfer;
namespace Sirikata{
namespace Transfer{
/*
* TransferMediator definitions
*/
TransferMediator& TransferMediator::getSingleton() {
return AutoSingleton<TransferMediator>::getSingleton();
}
void TransferMediator::destroy() {
AutoSingleton<TransferMediator>::destroy();
}
TransferMediator::TransferMediator() {
mCleanup = false;
mNumOutstanding = 0;
mAggregationAlgorithm = new MaxPriorityAggregation();
mThread = new Thread(std::tr1::bind(&TransferMediator::mediatorThread, this));
}
TransferMediator::~TransferMediator() {
delete mAggregationAlgorithm;
}
void TransferMediator::mediatorThread() {
while(!mCleanup) {
checkQueue();
boost::this_thread::sleep(boost::posix_time::milliseconds(5));
}
for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) {
pool->second->cleanup();
pool->second->getTransferPool()->addRequest(std::tr1::shared_ptr<TransferRequest>());
}
for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) {
pool->second->getThread()->join();
}
}
void TransferMediator::registerPool(TransferPoolPtr pool) {
//Lock exclusive to access map
boost::upgrade_lock<boost::shared_mutex> lock(mPoolMutex);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
//ensure client id doesnt already exist, they should be unique
PoolType::iterator findClientId = mPools.find(pool->getClientID());
assert(findClientId == mPools.end());
std::tr1::shared_ptr<PoolWorker> worker(new PoolWorker(pool));
mPools.insert(PoolType::value_type(pool->getClientID(), worker));
}
void TransferMediator::cleanup() {
mCleanup = true;
mThread->join();
}
void TransferMediator::execute_finished(std::tr1::shared_ptr<TransferRequest> req, std::string id) {
boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t());
lock.lock();
AggregateListByID& idIndex = mAggregateList.get<tagID>();
AggregateListByID::iterator findID = idIndex.find(id);
if(findID == idIndex.end()) {
//This can happen now if a request was canceled but it was already outstanding
mNumOutstanding--;
lock.unlock();
checkQueue();
return;
}
const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >&
allReqs = (*findID)->getTransferRequests();
for(std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::const_iterator
it = allReqs.begin(); it != allReqs.end(); it++) {
SILOG(transfer, detailed, "Notifying a caller that TransferRequest is complete");
it->second->notifyCaller(it->second, req);
}
mAggregateList.erase(findID);
mNumOutstanding--;
lock.unlock();
SILOG(transfer, detailed, "done transfer mediator execute_finished");
checkQueue();
}
void TransferMediator::checkQueue() {
boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t());
lock.lock();
AggregateListByPriority & priorityIndex = mAggregateList.get<tagPriority>();
AggregateListByPriority::iterator findTop = priorityIndex.begin();
if(findTop != priorityIndex.end()) {
std::string topId = (*findTop)->getIdentifier();
SILOG(transfer, detailed, priorityIndex.size() << " length agg list, top priority "
<< (*findTop)->getPriority() << " id " << topId);
std::tr1::shared_ptr<TransferRequest> req = (*findTop)->getSingleRequest();
if(mNumOutstanding == 0) {
mNumOutstanding++;
req->execute(req, std::tr1::bind(&TransferMediator::execute_finished, this, req, topId));
}
} else {
//SILOG(transfer, detailed, priorityIndex.size() << " length agg list");
}
lock.unlock();
}
/*
* TransferMediator::AggregateRequest definitions
*/
void TransferMediator::AggregateRequest::updateAggregatePriority() {
Priority newPriority = TransferMediator::getSingleton().mAggregationAlgorithm->aggregate(mTransferReqs);
mPriority = newPriority;
}
const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >& TransferMediator::AggregateRequest::getTransferRequests() const {
return mTransferReqs;
}
std::tr1::shared_ptr<TransferRequest> TransferMediator::AggregateRequest::getSingleRequest() {
std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator it = mTransferReqs.begin();
return it->second;
}
void TransferMediator::AggregateRequest::setClientPriority(std::tr1::shared_ptr<TransferRequest> req) {
const std::string& clientID = req->getClientID();
std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator findClient = mTransferReqs.find(clientID);
if(findClient == mTransferReqs.end()) {
mTransferReqs[clientID] = req;
updateAggregatePriority();
} else if(findClient->second->getPriority() != req->getPriority()) {
findClient->second = req;
updateAggregatePriority();
} else {
findClient->second = req;
}
}
void TransferMediator::AggregateRequest::removeClient(std::string clientID) {
std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator findClient = mTransferReqs.find(clientID);
if(findClient != mTransferReqs.end()) {
mTransferReqs.erase(findClient);
}
}
const std::string& TransferMediator::AggregateRequest::getIdentifier() const {
return mIdentifier;
}
Priority TransferMediator::AggregateRequest::getPriority() const {
return mPriority;
}
TransferMediator::AggregateRequest::AggregateRequest(std::tr1::shared_ptr<TransferRequest> req)
: mIdentifier(req->getIdentifier()) {
setClientPriority(req);
}
/*
* TransferMediator::PoolWorker definitions
*/
TransferMediator::PoolWorker::PoolWorker(std::tr1::shared_ptr<TransferPool> transferPool)
: mTransferPool(transferPool), mCleanup(false) {
mWorkerThread = new Thread(std::tr1::bind(&PoolWorker::run, this));
}
std::tr1::shared_ptr<TransferPool> TransferMediator::PoolWorker::getTransferPool() const {
return mTransferPool;
}
Thread * TransferMediator::PoolWorker::getThread() const {
return mWorkerThread;
}
void TransferMediator::PoolWorker::cleanup() {
mCleanup = true;
}
void TransferMediator::PoolWorker::run() {
while(!mCleanup) {
std::tr1::shared_ptr<TransferRequest> req = TransferMediator::getRequest(mTransferPool);
if(req == NULL) {
continue;
}
//SILOG(transfer, debug, "worker got one!");
boost::unique_lock<boost::mutex> lock(TransferMediator::getSingleton().mAggMutex);
AggregateListByID& idIndex = TransferMediator::getSingleton().mAggregateList.get<tagID>();
AggregateListByID::iterator findID = idIndex.find(req->getIdentifier());
//Check if this request already exists
if(findID != idIndex.end()) {
//Check if this request is for deleting
if(req->isDeletionRequest()) {
const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >&
allReqs = (*findID)->getTransferRequests();
std::map<std::string,
std::tr1::shared_ptr<TransferRequest> >::const_iterator findClient =
allReqs.find(req->getClientID());
/* If the client isn't in the aggregated request, it must have already
* been deleted, or the deletion request is invalid
*/
if(findClient == allReqs.end()) {
continue;
}
if(allReqs.size() > 1) {
/* If there are more than one, we need to just delete the single client
* from the aggregate request
*/
(*findID)->removeClient(req->getClientID());
} else {
// If only one in the list, we can erase the entire request
TransferMediator::getSingleton().mAggregateList.erase(findID);
}
} else {
//store original aggregated priority for later
Priority oldAggPriority = (*findID)->getPriority();
//Update the priority of this client
(*findID)->setClientPriority(req);
//And check if it's changed, we need to update the index
Priority newAggPriority = (*findID)->getPriority();
if(oldAggPriority != newAggPriority) {
//Convert the iterator to the priority one and update
AggregateListByPriority::iterator byPriority =
TransferMediator::getSingleton().mAggregateList.project<tagPriority>(findID);
AggregateListByPriority & priorityIndex =
TransferMediator::getSingleton().mAggregateList.get<tagPriority>();
priorityIndex.modify_key(byPriority, boost::lambda::_1=newAggPriority);
}
}
} else {
//Make a new one and insert it
//SILOG(transfer, debug, "worker id " << mTransferPool->getClientID() << " adding url " << req->getIdentifier());
std::tr1::shared_ptr<AggregateRequest> newAggReq(new AggregateRequest(req));
TransferMediator::getSingleton().mAggregateList.insert(newAggReq);
}
}
}
}
}
<commit_msg>Commit potentially addresses deadlock in transfermediator on sns30 shared space server. Ewen and I couldn't identify a specific cause, but there's a chance that use of boost::this_thread::sleep was the culprit.<commit_after>#include <sirikata/core/util/Standard.hh>
#include <sirikata/core/transfer/TransferMediator.hpp>
#include <sirikata/core/transfer/MaxPriorityAggregation.hpp>
#include <sirikata/core/util/Timer.hpp>
#include <stdio.h>
using namespace std;
AUTO_SINGLETON_INSTANCE(Sirikata::Transfer::TransferMediator);
using namespace Sirikata;
using namespace Sirikata::Transfer;
namespace Sirikata{
namespace Transfer{
/*
* TransferMediator definitions
*/
TransferMediator& TransferMediator::getSingleton() {
return AutoSingleton<TransferMediator>::getSingleton();
}
void TransferMediator::destroy() {
AutoSingleton<TransferMediator>::destroy();
}
TransferMediator::TransferMediator() {
mCleanup = false;
mNumOutstanding = 0;
mAggregationAlgorithm = new MaxPriorityAggregation();
mThread = new Thread(std::tr1::bind(&TransferMediator::mediatorThread, this));
}
TransferMediator::~TransferMediator() {
delete mAggregationAlgorithm;
}
void TransferMediator::mediatorThread() {
while(!mCleanup) {
checkQueue();
/**
Ewen and I weren't able to identify why the below call caused a
deadlock on the shared space hosted on sns30 (could not reproduce on
other machines). With the below line, in gdb, with bulletphysics on,
and servermap-options set to port 6880, we'd get 4 calls to
checkQueue, followed by no follow up calls. Not sure what to say.
*/
//boost::this_thread::sleep(boost::posix_time::milliseconds(5));
Timer::sleep(Duration::milliseconds(5));
}
for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) {
pool->second->cleanup();
pool->second->getTransferPool()->addRequest(std::tr1::shared_ptr<TransferRequest>());
}
for(PoolType::iterator pool = mPools.begin(); pool != mPools.end(); pool++) {
pool->second->getThread()->join();
}
}
void TransferMediator::registerPool(TransferPoolPtr pool) {
//Lock exclusive to access map
boost::upgrade_lock<boost::shared_mutex> lock(mPoolMutex);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
//ensure client id doesnt already exist, they should be unique
PoolType::iterator findClientId = mPools.find(pool->getClientID());
assert(findClientId == mPools.end());
std::tr1::shared_ptr<PoolWorker> worker(new PoolWorker(pool));
mPools.insert(PoolType::value_type(pool->getClientID(), worker));
}
void TransferMediator::cleanup() {
mCleanup = true;
mThread->join();
}
void TransferMediator::execute_finished(std::tr1::shared_ptr<TransferRequest> req, std::string id) {
boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t());
lock.lock();
AggregateListByID& idIndex = mAggregateList.get<tagID>();
AggregateListByID::iterator findID = idIndex.find(id);
if(findID == idIndex.end()) {
//This can happen now if a request was canceled but it was already outstanding
mNumOutstanding--;
lock.unlock();
checkQueue();
return;
}
const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >&
allReqs = (*findID)->getTransferRequests();
for(std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::const_iterator
it = allReqs.begin(); it != allReqs.end(); it++) {
SILOG(transfer, detailed, "Notifying a caller that TransferRequest is complete");
it->second->notifyCaller(it->second, req);
}
mAggregateList.erase(findID);
mNumOutstanding--;
lock.unlock();
SILOG(transfer, detailed, "done transfer mediator execute_finished");
checkQueue();
}
void TransferMediator::checkQueue() {
boost::unique_lock<boost::mutex> lock(mAggMutex, boost::defer_lock_t());
lock.lock();
AggregateListByPriority & priorityIndex = mAggregateList.get<tagPriority>();
AggregateListByPriority::iterator findTop = priorityIndex.begin();
if(findTop != priorityIndex.end()) {
std::string topId = (*findTop)->getIdentifier();
SILOG(transfer, detailed, priorityIndex.size() << " length agg list, top priority "
<< (*findTop)->getPriority() << " id " << topId);
std::tr1::shared_ptr<TransferRequest> req = (*findTop)->getSingleRequest();
if(mNumOutstanding == 0) {
mNumOutstanding++;
req->execute(req, std::tr1::bind(&TransferMediator::execute_finished, this, req, topId));
}
} else {
//SILOG(transfer, detailed, priorityIndex.size() << " length agg list");
}
lock.unlock();
}
/*
* TransferMediator::AggregateRequest definitions
*/
void TransferMediator::AggregateRequest::updateAggregatePriority() {
Priority newPriority = TransferMediator::getSingleton().mAggregationAlgorithm->aggregate(mTransferReqs);
mPriority = newPriority;
}
const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >& TransferMediator::AggregateRequest::getTransferRequests() const {
return mTransferReqs;
}
std::tr1::shared_ptr<TransferRequest> TransferMediator::AggregateRequest::getSingleRequest() {
std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator it = mTransferReqs.begin();
return it->second;
}
void TransferMediator::AggregateRequest::setClientPriority(std::tr1::shared_ptr<TransferRequest> req) {
const std::string& clientID = req->getClientID();
std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator findClient = mTransferReqs.find(clientID);
if(findClient == mTransferReqs.end()) {
mTransferReqs[clientID] = req;
updateAggregatePriority();
} else if(findClient->second->getPriority() != req->getPriority()) {
findClient->second = req;
updateAggregatePriority();
} else {
findClient->second = req;
}
}
void TransferMediator::AggregateRequest::removeClient(std::string clientID) {
std::map<std::string, std::tr1::shared_ptr<TransferRequest> >::iterator findClient = mTransferReqs.find(clientID);
if(findClient != mTransferReqs.end()) {
mTransferReqs.erase(findClient);
}
}
const std::string& TransferMediator::AggregateRequest::getIdentifier() const {
return mIdentifier;
}
Priority TransferMediator::AggregateRequest::getPriority() const {
return mPriority;
}
TransferMediator::AggregateRequest::AggregateRequest(std::tr1::shared_ptr<TransferRequest> req)
: mIdentifier(req->getIdentifier()) {
setClientPriority(req);
}
/*
* TransferMediator::PoolWorker definitions
*/
TransferMediator::PoolWorker::PoolWorker(std::tr1::shared_ptr<TransferPool> transferPool)
: mTransferPool(transferPool), mCleanup(false) {
mWorkerThread = new Thread(std::tr1::bind(&PoolWorker::run, this));
}
std::tr1::shared_ptr<TransferPool> TransferMediator::PoolWorker::getTransferPool() const {
return mTransferPool;
}
Thread * TransferMediator::PoolWorker::getThread() const {
return mWorkerThread;
}
void TransferMediator::PoolWorker::cleanup() {
mCleanup = true;
}
void TransferMediator::PoolWorker::run() {
while(!mCleanup) {
std::tr1::shared_ptr<TransferRequest> req = TransferMediator::getRequest(mTransferPool);
if(req == NULL) {
continue;
}
//SILOG(transfer, debug, "worker got one!");
boost::unique_lock<boost::mutex> lock(TransferMediator::getSingleton().mAggMutex);
AggregateListByID& idIndex = TransferMediator::getSingleton().mAggregateList.get<tagID>();
AggregateListByID::iterator findID = idIndex.find(req->getIdentifier());
//Check if this request already exists
if(findID != idIndex.end()) {
//Check if this request is for deleting
if(req->isDeletionRequest()) {
const std::map<std::string, std::tr1::shared_ptr<TransferRequest> >&
allReqs = (*findID)->getTransferRequests();
std::map<std::string,
std::tr1::shared_ptr<TransferRequest> >::const_iterator findClient =
allReqs.find(req->getClientID());
/* If the client isn't in the aggregated request, it must have already
* been deleted, or the deletion request is invalid
*/
if(findClient == allReqs.end()) {
continue;
}
if(allReqs.size() > 1) {
/* If there are more than one, we need to just delete the single client
* from the aggregate request
*/
(*findID)->removeClient(req->getClientID());
} else {
// If only one in the list, we can erase the entire request
TransferMediator::getSingleton().mAggregateList.erase(findID);
}
} else {
//store original aggregated priority for later
Priority oldAggPriority = (*findID)->getPriority();
//Update the priority of this client
(*findID)->setClientPriority(req);
//And check if it's changed, we need to update the index
Priority newAggPriority = (*findID)->getPriority();
if(oldAggPriority != newAggPriority) {
//Convert the iterator to the priority one and update
AggregateListByPriority::iterator byPriority =
TransferMediator::getSingleton().mAggregateList.project<tagPriority>(findID);
AggregateListByPriority & priorityIndex =
TransferMediator::getSingleton().mAggregateList.get<tagPriority>();
priorityIndex.modify_key(byPriority, boost::lambda::_1=newAggPriority);
}
}
} else {
//Make a new one and insert it
//SILOG(transfer, debug, "worker id " << mTransferPool->getClientID() << " adding url " << req->getIdentifier());
std::tr1::shared_ptr<AggregateRequest> newAggReq(new AggregateRequest(req));
TransferMediator::getSingleton().mAggregateList.insert(newAggReq);
}
}
}
}
}
<|endoftext|> |
<commit_before>
#include "journal/player.hpp"
#include <list>
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"
namespace principia {
namespace journal {
void BM_PlayForReal(benchmark::State& state) {
while (state.KeepRunning()) {
Player player(
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20180311-192733)");
int count = 0;
while (player.Play(count)) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0)
<< count << " journal entries replayed";
}
}
}
BENCHMARK(BM_PlayForReal);
class PlayerTest : public ::testing::Test {
protected:
PlayerTest()
: test_info_(testing::UnitTest::GetInstance()->current_test_info()),
test_case_name_(test_info_->test_case_name()),
test_name_(test_info_->name()),
plugin_(interface::principia__NewPlugin("MJD0", "MJD0", 0)) {}
template<typename Profile>
bool RunIfAppropriate(serialization::Method const& method_in,
serialization::Method const& method_out_return,
Player& player) {
return player.RunIfAppropriate<Profile>(method_in, method_out_return);
}
::testing::TestInfo const* const test_info_;
std::string const test_case_name_;
std::string const test_name_;
std::unique_ptr<ksp_plugin::Plugin> plugin_;
};
TEST_F(PlayerTest, PlayTiny) {
{
Recorder* const r(new Recorder(test_name_ + ".journal.hex"));
Recorder::Activate(r);
{
Method<NewPlugin> m({"MJD1", "MJD2", 3});
m.Return(plugin_.get());
}
{
const ksp_plugin::Plugin* plugin = plugin_.get();
Method<DeletePlugin> m({&plugin}, {&plugin});
m.Return();
}
Recorder::Deactivate();
}
Player player(test_name_ + ".journal.hex");
// Replay the journal.
int count = 0;
while (player.Play(count)) {
++count;
}
EXPECT_EQ(2, count);
}
TEST_F(PlayerTest, DISABLED_Benchmarks) {
benchmark::RunSpecifiedBenchmarks();
}
TEST_F(PlayerTest, DISABLED_Debug) {
// An example of how journaling may be used for debugging. You must set
// |path| and fill the |method_in| and |method_out_return| protocol buffers.
std::string path =
R"(C:\Program Files\Kerbal Space Program\1.7.0\glog\Principia\JOURNAL.20190713-140753)"; // NOLINT
Player player(path);
int count = 0;
while (player.Play(count)) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0) << count
<< " journal entries replayed";
}
LOG(ERROR) << count << " journal entries in total";
LOG(ERROR) << "Last successful method in:\n"
<< player.last_method_in().DebugString();
LOG(ERROR) << "Last successful method out/return: \n"
<< player.last_method_out_return().DebugString();
#if 0
serialization::Method method_in;
{
auto* extension = method_in.MutableExtension(
serialization::FlightPlanGetManoeuvreFrenetTrihedron::extension);
auto* in = extension->mutable_in();
in->set_plugin(2312193072);
in->set_vessel_guid("bedd9d23-de56-4fb8-881c-f647e22f848f");
in->set_index(0);
}
serialization::Method method_out_return;
{
auto* extension = method_out_return.MutableExtension(
serialization::FlightPlanGetManoeuvreFrenetTrihedron::extension);
}
LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString();
CHECK(RunIfAppropriate<FlightPlanGetManoeuvreFrenetTrihedron>(
method_in, method_out_return, player));
#endif
}
} // namespace journal
} // namespace principia
<commit_msg>mark PlayerTest.*Debug as secular<commit_after>
#include "journal/player.hpp"
#include <list>
#include <string>
#include <vector>
#include "benchmark/benchmark.h"
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "journal/method.hpp"
#include "journal/profiles.hpp"
#include "journal/recorder.hpp"
#include "ksp_plugin/interface.hpp"
#include "serialization/journal.pb.h"
namespace principia {
namespace journal {
void BM_PlayForReal(benchmark::State& state) {
while (state.KeepRunning()) {
Player player(
R"(P:\Public Mockingbird\Principia\Journals\JOURNAL.20180311-192733)");
int count = 0;
while (player.Play(count)) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0)
<< count << " journal entries replayed";
}
}
}
BENCHMARK(BM_PlayForReal);
class PlayerTest : public ::testing::Test {
protected:
PlayerTest()
: test_info_(testing::UnitTest::GetInstance()->current_test_info()),
test_case_name_(test_info_->test_case_name()),
test_name_(test_info_->name()),
plugin_(interface::principia__NewPlugin("MJD0", "MJD0", 0)) {}
template<typename Profile>
bool RunIfAppropriate(serialization::Method const& method_in,
serialization::Method const& method_out_return,
Player& player) {
return player.RunIfAppropriate<Profile>(method_in, method_out_return);
}
::testing::TestInfo const* const test_info_;
std::string const test_case_name_;
std::string const test_name_;
std::unique_ptr<ksp_plugin::Plugin> plugin_;
};
TEST_F(PlayerTest, PlayTiny) {
{
Recorder* const r(new Recorder(test_name_ + ".journal.hex"));
Recorder::Activate(r);
{
Method<NewPlugin> m({"MJD1", "MJD2", 3});
m.Return(plugin_.get());
}
{
const ksp_plugin::Plugin* plugin = plugin_.get();
Method<DeletePlugin> m({&plugin}, {&plugin});
m.Return();
}
Recorder::Deactivate();
}
Player player(test_name_ + ".journal.hex");
// Replay the journal.
int count = 0;
while (player.Play(count)) {
++count;
}
EXPECT_EQ(2, count);
}
TEST_F(PlayerTest, DISABLED_Benchmarks) {
benchmark::RunSpecifiedBenchmarks();
}
TEST_F(PlayerTest, DISABLED_SECULAR_Debug) {
// An example of how journaling may be used for debugging. You must set
// |path| and fill the |method_in| and |method_out_return| protocol buffers.
std::string path =
R"(C:\Program Files\Kerbal Space Program\1.7.0\glog\Principia\JOURNAL.20190713-140753)"; // NOLINT
Player player(path);
int count = 0;
while (player.Play(count)) {
++count;
LOG_IF(ERROR, (count % 100'000) == 0) << count
<< " journal entries replayed";
}
LOG(ERROR) << count << " journal entries in total";
LOG(ERROR) << "Last successful method in:\n"
<< player.last_method_in().DebugString();
LOG(ERROR) << "Last successful method out/return: \n"
<< player.last_method_out_return().DebugString();
#if 0
serialization::Method method_in;
{
auto* extension = method_in.MutableExtension(
serialization::FlightPlanGetManoeuvreFrenetTrihedron::extension);
auto* in = extension->mutable_in();
in->set_plugin(2312193072);
in->set_vessel_guid("bedd9d23-de56-4fb8-881c-f647e22f848f");
in->set_index(0);
}
serialization::Method method_out_return;
{
auto* extension = method_out_return.MutableExtension(
serialization::FlightPlanGetManoeuvreFrenetTrihedron::extension);
}
LOG(ERROR) << "Running unpaired method:\n" << method_in.DebugString();
CHECK(RunIfAppropriate<FlightPlanGetManoeuvreFrenetTrihedron>(
method_in, method_out_return, player));
#endif
}
} // namespace journal
} // namespace principia
<|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 <oleacc.h>
#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/test/in_process_browser_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
namespace {
VARIANT id_self = {VT_I4, CHILDID_SELF};
// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;
class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
public:
BrowserViewsAccessibilityTest() {
::CoInitialize(NULL);
}
~BrowserViewsAccessibilityTest() {
::CoUninitialize();
}
// Retrieves an instance of BrowserWindowTesting
BrowserWindowTesting* GetBrowserWindowTesting() {
BrowserWindow* browser_window = browser()->window();
if (!browser_window)
return NULL;
return browser_window->GetBrowserWindowTesting();
}
// Retrieve an instance of BrowserView
BrowserView* GetBrowserView() {
return BrowserView::GetBrowserViewForNativeWindow(
browser()->window()->GetNativeHandle());
}
// Retrieves and initializes an instance of LocationBarView.
LocationBarView* GetLocationBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return GetBrowserWindowTesting()->GetLocationBarView();
}
// Retrieves and initializes an instance of ToolbarView.
ToolbarView* GetToolbarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetToolbarView();
}
// Retrieves and initializes an instance of BookmarkBarView.
BookmarkBarView* GetBookmarkBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetBookmarkBarView();
}
// Retrieves and verifies the accessibility object for the given View.
void TestViewAccessibilityObject(views::View* view, std::wstring name,
int32 role) {
ASSERT_TRUE(NULL != view);
IAccessible* acc_obj = NULL;
HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, name, role);
}
// Verifies MSAA Name and Role properties of the given IAccessible.
void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
int32 role) {
// Verify MSAA Name property.
BSTR acc_name;
HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
ASSERT_EQ(S_OK, hr);
EXPECT_STREQ(acc_name, name.c_str());
// Verify MSAA Role property.
VARIANT acc_role;
::VariantInit(&acc_role);
hr = acc_obj->get_accRole(id_self, &acc_role);
ASSERT_EQ(S_OK, hr);
EXPECT_EQ(VT_I4, acc_role.vt);
EXPECT_EQ(role, acc_role.lVal);
::VariantClear(&acc_role);
::SysFreeString(acc_name);
}
};
// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
FAILS_TestChromeWindowAccObj) {
BrowserWindow* browser_window = browser()->window();
ASSERT_TRUE(NULL != browser_window);
HWND hwnd = browser_window->GetNativeHandle();
ASSERT_TRUE(NULL != hwnd);
// Get accessibility object.
IAccessible* acc_obj = NULL;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
// TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or
// "about:blank - Chromium"
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
acc_obj->Release();
}
// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
views::View* non_client_view =
GetBrowserView()->GetWindow()->GetNonClientView();
TestViewAccessibilityObject(non_client_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
}
// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBrowserRootViewAccObj) {
views::View* browser_root_view =
GetBrowserView()->frame()->GetFrameView()->GetRootView();
TestViewAccessibilityObject(browser_root_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_APPLICATION);
}
// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
// Verify root view MSAA name and role.
TestViewAccessibilityObject(GetBrowserView(),
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_CLIENT);
}
// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
// Verify toolbar MSAA name and role.
TestViewAccessibilityObject(GetToolbarView(),
l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
ROLE_SYSTEM_TOOLBAR);
}
// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
// Verify Back button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
// Verify Forward button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
// Verify Reload button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
// Verify Home button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestStarButtonAccObj) {
// Verify Star button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestLocationBarViewAccObj) {
// Verify location bar MSAA name and role.
TestViewAccessibilityObject(GetLocationBarView(),
l10n_util::GetString(IDS_ACCNAME_LOCATION),
ROLE_SYSTEM_GROUPING);
}
// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
// Verify Go button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
l10n_util::GetString(IDS_ACCNAME_GO),
ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
// Verify Page menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
l10n_util::GetString(IDS_ACCNAME_PAGE),
ROLE_SYSTEM_BUTTONMENU);
}
// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
// Verify App menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
l10n_util::GetString(IDS_ACCNAME_APP),
ROLE_SYSTEM_BUTTONMENU);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBookmarkBarViewAccObj) {
TestViewAccessibilityObject(GetBookmarkBarView(),
l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
ROLE_SYSTEM_TOOLBAR);
}
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestAboutChromeViewAccObj) {
// Firstly, test that the WindowDelegate got updated.
views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
AccessibilityTypes::ROLE_DIALOG);
// Also test the accessibility object directly.
IAccessible* acc_obj = NULL;
HRESULT hr =
::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
OBJID_CLIENT,
IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
ROLE_SYSTEM_DIALOG);
acc_obj->Release();
}
} // Namespace.
<commit_msg>Revert 47746 - Reenabling TestAboutChromeViewAccObj.<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 <oleacc.h>
#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/test/in_process_browser_test.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
namespace {
VARIANT id_self = {VT_I4, CHILDID_SELF};
// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;
class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
public:
BrowserViewsAccessibilityTest() {
::CoInitialize(NULL);
}
~BrowserViewsAccessibilityTest() {
::CoUninitialize();
}
// Retrieves an instance of BrowserWindowTesting
BrowserWindowTesting* GetBrowserWindowTesting() {
BrowserWindow* browser_window = browser()->window();
if (!browser_window)
return NULL;
return browser_window->GetBrowserWindowTesting();
}
// Retrieve an instance of BrowserView
BrowserView* GetBrowserView() {
return BrowserView::GetBrowserViewForNativeWindow(
browser()->window()->GetNativeHandle());
}
// Retrieves and initializes an instance of LocationBarView.
LocationBarView* GetLocationBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return GetBrowserWindowTesting()->GetLocationBarView();
}
// Retrieves and initializes an instance of ToolbarView.
ToolbarView* GetToolbarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetToolbarView();
}
// Retrieves and initializes an instance of BookmarkBarView.
BookmarkBarView* GetBookmarkBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetBookmarkBarView();
}
// Retrieves and verifies the accessibility object for the given View.
void TestViewAccessibilityObject(views::View* view, std::wstring name,
int32 role) {
ASSERT_TRUE(NULL != view);
IAccessible* acc_obj = NULL;
HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, name, role);
}
// Verifies MSAA Name and Role properties of the given IAccessible.
void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
int32 role) {
// Verify MSAA Name property.
BSTR acc_name;
HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
ASSERT_EQ(S_OK, hr);
EXPECT_STREQ(acc_name, name.c_str());
// Verify MSAA Role property.
VARIANT acc_role;
::VariantInit(&acc_role);
hr = acc_obj->get_accRole(id_self, &acc_role);
ASSERT_EQ(S_OK, hr);
EXPECT_EQ(VT_I4, acc_role.vt);
EXPECT_EQ(role, acc_role.lVal);
::VariantClear(&acc_role);
::SysFreeString(acc_name);
}
};
// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
FAILS_TestChromeWindowAccObj) {
BrowserWindow* browser_window = browser()->window();
ASSERT_TRUE(NULL != browser_window);
HWND hwnd = browser_window->GetNativeHandle();
ASSERT_TRUE(NULL != hwnd);
// Get accessibility object.
IAccessible* acc_obj = NULL;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
// TODO(ctguil): Fix. The window title could be "New Tab - Chromium" or
// "about:blank - Chromium"
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
acc_obj->Release();
}
// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
views::View* non_client_view =
GetBrowserView()->GetWindow()->GetNonClientView();
TestViewAccessibilityObject(non_client_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
}
// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBrowserRootViewAccObj) {
views::View* browser_root_view =
GetBrowserView()->frame()->GetFrameView()->GetRootView();
TestViewAccessibilityObject(browser_root_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_APPLICATION);
}
// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
// Verify root view MSAA name and role.
TestViewAccessibilityObject(GetBrowserView(),
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_CLIENT);
}
// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
// Verify toolbar MSAA name and role.
TestViewAccessibilityObject(GetToolbarView(),
l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
ROLE_SYSTEM_TOOLBAR);
}
// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
// Verify Back button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
// Verify Forward button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
// Verify Reload button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
// Verify Home button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestStarButtonAccObj) {
// Verify Star button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestLocationBarViewAccObj) {
// Verify location bar MSAA name and role.
TestViewAccessibilityObject(GetLocationBarView(),
l10n_util::GetString(IDS_ACCNAME_LOCATION),
ROLE_SYSTEM_GROUPING);
}
// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
// Verify Go button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
l10n_util::GetString(IDS_ACCNAME_GO),
ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
// Verify Page menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
l10n_util::GetString(IDS_ACCNAME_PAGE),
ROLE_SYSTEM_BUTTONMENU);
}
// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
// Verify App menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
l10n_util::GetString(IDS_ACCNAME_APP),
ROLE_SYSTEM_BUTTONMENU);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBookmarkBarViewAccObj) {
TestViewAccessibilityObject(GetBookmarkBarView(),
l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
ROLE_SYSTEM_TOOLBAR);
}
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
FAILS_TestAboutChromeViewAccObj) {
// Firstly, test that the WindowDelegate got updated.
views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
AccessibilityTypes::ROLE_DIALOG);
// Also test the accessibility object directly.
IAccessible* acc_obj = NULL;
HRESULT hr =
::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
OBJID_CLIENT,
IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
ROLE_SYSTEM_DIALOG);
acc_obj->Release();
}
} // Namespace.
<|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 <oleacc.h>
#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
namespace {
VARIANT id_self = {VT_I4, CHILDID_SELF};
// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;
class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
public:
BrowserViewsAccessibilityTest() {
::CoInitialize(NULL);
}
~BrowserViewsAccessibilityTest() {
::CoUninitialize();
}
// Retrieves an instance of BrowserWindowTesting
BrowserWindowTesting* GetBrowserWindowTesting() {
BrowserWindow* browser_window = browser()->window();
if (!browser_window)
return NULL;
return browser_window->GetBrowserWindowTesting();
}
// Retrieve an instance of BrowserView
BrowserView* GetBrowserView() {
return BrowserView::GetBrowserViewForNativeWindow(
browser()->window()->GetNativeHandle());
}
// Retrieves and initializes an instance of LocationBarView.
LocationBarView* GetLocationBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return GetBrowserWindowTesting()->GetLocationBarView();
}
// Retrieves and initializes an instance of ToolbarView.
ToolbarView* GetToolbarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetToolbarView();
}
// Retrieves and initializes an instance of BookmarkBarView.
BookmarkBarView* GetBookmarkBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetBookmarkBarView();
}
// Retrieves and verifies the accessibility object for the given View.
void TestViewAccessibilityObject(views::View* view, std::wstring name,
int32 role) {
ASSERT_TRUE(NULL != view);
IAccessible* acc_obj = NULL;
HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, name, role);
}
// Verifies MSAA Name and Role properties of the given IAccessible.
void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
int32 role) {
// Verify MSAA Name property.
BSTR acc_name;
HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
ASSERT_EQ(S_OK, hr);
EXPECT_STREQ(acc_name, name.c_str());
// Verify MSAA Role property.
VARIANT acc_role;
::VariantInit(&acc_role);
hr = acc_obj->get_accRole(id_self, &acc_role);
ASSERT_EQ(S_OK, hr);
EXPECT_EQ(VT_I4, acc_role.vt);
EXPECT_EQ(role, acc_role.lVal);
::VariantClear(&acc_role);
::SysFreeString(acc_name);
}
};
// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestChromeWindowAccObj) {
BrowserWindow* browser_window = browser()->window();
ASSERT_TRUE(NULL != browser_window);
HWND hwnd = browser_window->GetNativeHandle();
ASSERT_TRUE(NULL != hwnd);
// Get accessibility object.
IAccessible* acc_obj = NULL;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
std::wstring title =
l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,
ASCIIToWide(chrome::kAboutBlankURL));
TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
acc_obj->Release();
}
// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
views::View* non_client_view =
GetBrowserView()->GetWindow()->GetNonClientView();
TestViewAccessibilityObject(non_client_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
}
// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBrowserRootViewAccObj) {
views::View* browser_root_view =
GetBrowserView()->frame()->GetFrameView()->GetRootView();
TestViewAccessibilityObject(browser_root_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_APPLICATION);
}
// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
// Verify root view MSAA name and role.
TestViewAccessibilityObject(GetBrowserView(),
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_CLIENT);
}
// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
// Verify toolbar MSAA name and role.
TestViewAccessibilityObject(GetToolbarView(),
l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
ROLE_SYSTEM_TOOLBAR);
}
// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
// Verify Back button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
// Verify Forward button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
// Verify Reload button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
// Verify Home button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestStarButtonAccObj) {
// Verify Star button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestLocationBarViewAccObj) {
// Verify location bar MSAA name and role.
TestViewAccessibilityObject(GetLocationBarView(),
l10n_util::GetString(IDS_ACCNAME_LOCATION),
ROLE_SYSTEM_GROUPING);
}
// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
// Verify Go button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
l10n_util::GetString(IDS_ACCNAME_GO),
ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
// Verify Page menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
l10n_util::GetString(IDS_ACCNAME_PAGE),
ROLE_SYSTEM_BUTTONMENU);
}
// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
// Verify App menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
l10n_util::GetString(IDS_ACCNAME_APP),
ROLE_SYSTEM_BUTTONMENU);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBookmarkBarViewAccObj) {
TestViewAccessibilityObject(GetBookmarkBarView(),
l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
ROLE_SYSTEM_TOOLBAR);
}
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
FAILS_TestAboutChromeViewAccObj) {
// Firstly, test that the WindowDelegate got updated.
views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
AccessibilityTypes::ROLE_DIALOG);
// Also test the accessibility object directly.
IAccessible* acc_obj = NULL;
HRESULT hr =
::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
OBJID_CLIENT,
IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
ROLE_SYSTEM_DIALOG);
acc_obj->Release();
}
} // Namespace.
<commit_msg>Re-enabling TestAboutChromeViewAccObj.<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 <oleacc.h>
#include "app/l10n_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/bookmark_bar_view.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/toolbar_view.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "views/accessibility/view_accessibility_wrapper.h"
#include "views/widget/root_view.h"
#include "views/widget/widget_win.h"
#include "views/window/window.h"
namespace {
VARIANT id_self = {VT_I4, CHILDID_SELF};
// Dummy class to force creation of ATL module, needed by COM to instantiate
// ViewAccessibility.
class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {};
TestAtlModule test_atl_module_;
class BrowserViewsAccessibilityTest : public InProcessBrowserTest {
public:
BrowserViewsAccessibilityTest() {
::CoInitialize(NULL);
}
~BrowserViewsAccessibilityTest() {
::CoUninitialize();
}
// Retrieves an instance of BrowserWindowTesting
BrowserWindowTesting* GetBrowserWindowTesting() {
BrowserWindow* browser_window = browser()->window();
if (!browser_window)
return NULL;
return browser_window->GetBrowserWindowTesting();
}
// Retrieve an instance of BrowserView
BrowserView* GetBrowserView() {
return BrowserView::GetBrowserViewForNativeWindow(
browser()->window()->GetNativeHandle());
}
// Retrieves and initializes an instance of LocationBarView.
LocationBarView* GetLocationBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return GetBrowserWindowTesting()->GetLocationBarView();
}
// Retrieves and initializes an instance of ToolbarView.
ToolbarView* GetToolbarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetToolbarView();
}
// Retrieves and initializes an instance of BookmarkBarView.
BookmarkBarView* GetBookmarkBarView() {
BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting();
if (!browser_window_testing)
return NULL;
return browser_window_testing->GetBookmarkBarView();
}
// Retrieves and verifies the accessibility object for the given View.
void TestViewAccessibilityObject(views::View* view, std::wstring name,
int32 role) {
ASSERT_TRUE(NULL != view);
IAccessible* acc_obj = NULL;
HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance(
IID_IAccessible, reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, name, role);
}
// Verifies MSAA Name and Role properties of the given IAccessible.
void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name,
int32 role) {
// Verify MSAA Name property.
BSTR acc_name;
HRESULT hr = acc_obj->get_accName(id_self, &acc_name);
ASSERT_EQ(S_OK, hr);
EXPECT_STREQ(acc_name, name.c_str());
// Verify MSAA Role property.
VARIANT acc_role;
::VariantInit(&acc_role);
hr = acc_obj->get_accRole(id_self, &acc_role);
ASSERT_EQ(S_OK, hr);
EXPECT_EQ(VT_I4, acc_role.vt);
EXPECT_EQ(role, acc_role.lVal);
::VariantClear(&acc_role);
::SysFreeString(acc_name);
}
};
// Retrieve accessibility object for main window and verify accessibility info.
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestChromeWindowAccObj) {
BrowserWindow* browser_window = browser()->window();
ASSERT_TRUE(NULL != browser_window);
HWND hwnd = browser_window->GetNativeHandle();
ASSERT_TRUE(NULL != hwnd);
// Get accessibility object.
IAccessible* acc_obj = NULL;
HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
std::wstring title =
l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT,
ASCIIToWide(chrome::kAboutBlankURL));
TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW);
acc_obj->Release();
}
// Retrieve accessibility object for non client view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) {
views::View* non_client_view =
GetBrowserView()->GetWindow()->GetNonClientView();
TestViewAccessibilityObject(non_client_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_WINDOW);
}
// Retrieve accessibility object for browser root view and verify
// accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBrowserRootViewAccObj) {
views::View* browser_root_view =
GetBrowserView()->frame()->GetFrameView()->GetRootView();
TestViewAccessibilityObject(browser_root_view,
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_APPLICATION);
}
// Retrieve accessibility object for browser view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) {
// Verify root view MSAA name and role.
TestViewAccessibilityObject(GetBrowserView(),
l10n_util::GetString(IDS_PRODUCT_NAME),
ROLE_SYSTEM_CLIENT);
}
// Retrieve accessibility object for toolbar view and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) {
// Verify toolbar MSAA name and role.
TestViewAccessibilityObject(GetToolbarView(),
l10n_util::GetString(IDS_ACCNAME_TOOLBAR),
ROLE_SYSTEM_TOOLBAR);
}
// Retrieve accessibility object for Back button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) {
// Verify Back button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON),
l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Forward button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) {
// Verify Forward button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN);
}
// Retrieve accessibility object for Reload button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) {
// Verify Reload button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON),
l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Home button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) {
// Verify Home button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON),
l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Star button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestStarButtonAccObj) {
// Verify Star button MSAA name and role.
TestViewAccessibilityObject(
GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON),
l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for location bar view and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestLocationBarViewAccObj) {
// Verify location bar MSAA name and role.
TestViewAccessibilityObject(GetLocationBarView(),
l10n_util::GetString(IDS_ACCNAME_LOCATION),
ROLE_SYSTEM_GROUPING);
}
// Retrieve accessibility object for Go button and verify accessibility info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) {
// Verify Go button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON),
l10n_util::GetString(IDS_ACCNAME_GO),
ROLE_SYSTEM_PUSHBUTTON);
}
// Retrieve accessibility object for Page menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) {
// Verify Page menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU),
l10n_util::GetString(IDS_ACCNAME_PAGE),
ROLE_SYSTEM_BUTTONMENU);
}
// Retrieve accessibility object for App menu button and verify accessibility
// info.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) {
// Verify App menu button MSAA name and role.
TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU),
l10n_util::GetString(IDS_ACCNAME_APP),
ROLE_SYSTEM_BUTTONMENU);
}
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestBookmarkBarViewAccObj) {
TestViewAccessibilityObject(GetBookmarkBarView(),
l10n_util::GetString(IDS_ACCNAME_BOOKMARKS),
ROLE_SYSTEM_TOOLBAR);
}
// Fails, http://crbug.com/44486.
IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest,
TestAboutChromeViewAccObj) {
// Firstly, test that the WindowDelegate got updated.
views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog();
EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(),
l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str());
EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(),
AccessibilityTypes::ROLE_DIALOG);
// Also test the accessibility object directly.
IAccessible* acc_obj = NULL;
HRESULT hr =
::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(),
OBJID_CLIENT,
IID_IAccessible,
reinterpret_cast<void**>(&acc_obj));
ASSERT_EQ(S_OK, hr);
ASSERT_TRUE(NULL != acc_obj);
TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE),
ROLE_SYSTEM_DIALOG);
acc_obj->Release();
}
} // Namespace.
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR 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.
*/
#include "stdafx.h"
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include "util/base64_util.h"
using namespace std;
using namespace zorba;
struct test {
char const *input;
char const *expected;
};
///////////////////////////////////////////////////////////////////////////////
static int failures;
static bool assert_true( int no, char const *expr, int line, bool result ) {
if ( !result ) {
cout << '#' << no << " FAILED, line " << line << ": " << expr << endl;
++failures;
}
return result;
}
static void print_exception( int no, char const *expr, int line,
std::exception const &e ) {
assert_true( no, expr, line, false );
cout << "+ exception: " << e.what() << endl;
}
#define ASSERT_TRUE( NO, EXPR ) assert_true( NO, #EXPR, __LINE__, !!(EXPR) )
#define ASSERT_NO_EXCEPTION( NO, EXPR ) \
try { EXPR; } \
catch ( std::exception const &e ) { print_exception( NO, #EXPR, __LINE__, e ); } \
catch ( ... ) { assert_true( NO, #EXPR, __LINE__, false ); }
#define ASSERT_EXCEPTION( NO, EXPR, EXCEPTION ) \
try { EXPR; assert_true( NO, #EXPR, __LINE__, false ); } \
catch ( EXCEPTION const& ) { }
///////////////////////////////////////////////////////////////////////////////}
static void test_decode_buf_to_buf( int no, string const &in,
string const &expected ) {
base64::size_type n;
char out[ 1024 ];
ASSERT_NO_EXCEPTION(
no, n = base64::decode( in.data(), in.size(), out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
out[ n ] = '\0';
ASSERT_TRUE( no, out == expected );
}
static void test_decode_buf_to_string( int no, string const &in,
string const &expected ) {
base64::size_type n;
string out;
ASSERT_NO_EXCEPTION(
no,
n = base64::decode( in.data(), in.size(), &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_decode_buf_to_vector( int no, string const &in,
string const &expected ) {
base64::size_type n;
vector<char> out;
ASSERT_NO_EXCEPTION(
no,
n = base64::decode( in.data(), in.size(), &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
static void test_decode_stream_to_stream( int no, string const &in,
string const &expected ) {
base64::size_type n;
istringstream sin( in );
ostringstream sout;
ASSERT_NO_EXCEPTION(
no, n = base64::decode( sin, sout, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, sout.str().size() == expected.size() );
ASSERT_TRUE( no, sout.str() == expected );
}
static void test_decode_stream_to_string( int no, string const &in,
string const &expected ) {
base64::size_type n;
istringstream sin( in );
string out;
ASSERT_NO_EXCEPTION(
no, n = base64::decode( sin, &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_decode_stream_to_vector( int no, string const &in,
string const &expected ) {
base64::size_type n;
istringstream sin( in );
vector<char> out;
ASSERT_NO_EXCEPTION(
no, n = base64::decode( sin, &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
static void test_decode_exception( int no, string const &in ) {
char out[ 1024 ];
ASSERT_EXCEPTION(
no, base64::decode( in.data(), in.size(), out ), invalid_argument
);
}
///////////////////////////////////////////////////////////////////////////////
static void test_encode_buf_to_buf( int no, string const &in,
string const &expected ) {
char out[ 1024 ];
base64::size_type const n = base64::encode( in.data(), in.size(), out );
ASSERT_TRUE( no, n == expected.size() );
out[ n ] = '\0';
ASSERT_TRUE( no, out == expected );
}
static void test_encode_buf_to_string( int no, string const &in,
string const &expected ) {
base64::size_type n;
string out;
ASSERT_NO_EXCEPTION( no, n = base64::encode( in.data(), in.size(), &out ) );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_encode_buf_to_vector( int no, string const &in,
string const &expected ) {
base64::size_type n;
vector<char> out;
ASSERT_NO_EXCEPTION( no, n = base64::encode( in.data(), in.size(), &out ) );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
static void test_encode_stream_to_stream( int no, string const &in,
string const &expected ) {
base64::size_type n;
istringstream sin( in );
ostringstream sout;
ASSERT_NO_EXCEPTION( no, n = base64::encode( sin, sout ) );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, sout.str().size() == expected.size() );
ASSERT_TRUE( no, sout.str() == expected );
}
static void test_encode_stream_to_string( int no, string const &in,
string const &expected ) {
base64::size_type n;
istringstream sin( in );
string out;
ASSERT_NO_EXCEPTION( no, n = base64::encode( sin, &out ) );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_encode_stream_to_vector( int no, string const &in,
string const &expected ) {
base64::size_type n;
istringstream sin( in );
vector<char> out;
ASSERT_NO_EXCEPTION( no, n = base64::encode( sin, &out ) );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
///////////////////////////////////////////////////////////////////////////////
static test const encode_tests[] = {
/* 0 */ { "Now is the time", "Tm93IGlzIHRoZSB0aW1l" },
/* 1 */ { "Now is the time.", "Tm93IGlzIHRoZSB0aW1lLg==" },
/* 2 */ { "Now is the time..", "Tm93IGlzIHRoZSB0aW1lLi4=" },
{ 0, 0 }
};
static test const decode_tests[] = {
/* 3 */ { "Tm93IGlzIHRoZSB0aW1l", "Now is the time" },
/* 4 */ { "Tm93IGlzIHRoZSB0aW1lLg==", "Now is the time." },
/* 5 */ { "Tm93IGlzIHRoZSB0aW1lLi4=", "Now is the time.." },
// incomplete Base64 encodings
/* 6 */ { "Tm93IGlzIHRoZSB0aW1", "Now is the tim" },
/* 7 */ { "Tm93IGlzIHRoZSB0aW", "Now is the ti" },
/* 8 */ { "Tm93IGlzIHRoZSB0a", "Now is the t" },
{ 0, 0 }
};
static char const *const decode_exception_tests[] = {
"=",
"_m93",
"T_93",
"Tm_3",
"Tm9_",
"=m93",
"T=93",
"Tm=3",
"Tm93=",
"ZmX=",
"ZX==",
"ZX===",
0
};
namespace zorba {
namespace UnitTests {
int test_base64( int, char*[] ) {
int test_no = 0;
for ( test const *t = encode_tests; t->input; ++t, ++test_no ) {
test_encode_buf_to_buf( test_no, t->input, t->expected );
test_encode_buf_to_string( test_no, t->input, t->expected );
test_encode_buf_to_vector( test_no, t->input, t->expected );
test_encode_stream_to_stream( test_no, t->input, t->expected );
test_encode_stream_to_string( test_no, t->input, t->expected );
test_encode_stream_to_vector( test_no, t->input, t->expected );
}
for ( test const *t = decode_tests; t->input; ++t, ++test_no ) {
test_decode_buf_to_buf( test_no, t->input, t->expected );
test_decode_buf_to_string( test_no, t->input, t->expected );
test_decode_buf_to_vector( test_no, t->input, t->expected );
test_decode_stream_to_stream( test_no, t->input, t->expected );
test_decode_stream_to_string( test_no, t->input, t->expected );
test_decode_stream_to_vector( test_no, t->input, t->expected );
}
for ( char const *const *t = decode_exception_tests; *t; ++t, ++test_no )
test_decode_exception( test_no, *t );
cout << failures << " test(s) failed\n";
return failures ? 1 : 0;
}
} // namespace UnitTests
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<commit_msg>Fixed warnings.<commit_after>/*
* Copyright 2006-2008 The FLWOR 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.
*/
#include "stdafx.h"
#include <cstring>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include "util/base64_util.h"
using namespace std;
using namespace zorba;
struct test {
char const *input;
char const *expected;
};
///////////////////////////////////////////////////////////////////////////////
static int failures;
static bool assert_true( int no, char const *expr, int line, bool result ) {
if ( !result ) {
cout << '#' << no << " FAILED, line " << line << ": " << expr << endl;
++failures;
}
return result;
}
static void print_exception( int no, char const *expr, int line,
std::exception const &e ) {
assert_true( no, expr, line, false );
cout << "+ exception: " << e.what() << endl;
}
#define ASSERT_TRUE( NO, EXPR ) assert_true( NO, #EXPR, __LINE__, !!(EXPR) )
#define ASSERT_NO_EXCEPTION( NO, EXPR ) \
try { EXPR; } \
catch ( std::exception const &e ) { print_exception( NO, #EXPR, __LINE__, e ); }
#define ASSERT_EXCEPTION( NO, EXPR, EXCEPTION ) \
try { EXPR; assert_true( NO, #EXPR, __LINE__, false ); } \
catch ( EXCEPTION const& ) { }
///////////////////////////////////////////////////////////////////////////////}
static void test_decode_buf_to_buf( int no, string const &in,
string const &expected ) {
base64::size_type n = 0;
char out[ 1024 ];
ASSERT_NO_EXCEPTION(
no, n = base64::decode( in.data(), in.size(), out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
out[ n ] = '\0';
ASSERT_TRUE( no, out == expected );
}
static void test_decode_buf_to_string( int no, string const &in,
string const &expected ) {
base64::size_type n = 0;
string out;
ASSERT_NO_EXCEPTION(
no,
n = base64::decode( in.data(), in.size(), &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_decode_buf_to_vector( int no, string const &in,
string const &expected ) {
base64::size_type n = 0;
vector<char> out;
ASSERT_NO_EXCEPTION(
no,
n = base64::decode( in.data(), in.size(), &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
static void test_decode_stream_to_stream( int no, string const &in,
string const &expected ) {
base64::size_type n = 0;
istringstream sin( in );
ostringstream sout;
ASSERT_NO_EXCEPTION(
no, n = base64::decode( sin, sout, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, sout.str().size() == expected.size() );
ASSERT_TRUE( no, sout.str() == expected );
}
static void test_decode_stream_to_string( int no, string const &in,
string const &expected ) {
base64::size_type n = 0;
istringstream sin( in );
string out;
ASSERT_NO_EXCEPTION(
no, n = base64::decode( sin, &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_decode_stream_to_vector( int no, string const &in,
string const &expected ) {
base64::size_type n = 0;
istringstream sin( in );
vector<char> out;
ASSERT_NO_EXCEPTION(
no, n = base64::decode( sin, &out, base64::dopt_any_len )
);
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
static void test_decode_exception( int no, string const &in ) {
char out[ 1024 ];
ASSERT_EXCEPTION(
no, base64::decode( in.data(), in.size(), out ), invalid_argument
);
}
///////////////////////////////////////////////////////////////////////////////
static void test_encode_buf_to_buf( int no, string const &in,
string const &expected ) {
char out[ 1024 ];
base64::size_type const n = base64::encode( in.data(), in.size(), out );
ASSERT_TRUE( no, n == expected.size() );
out[ n ] = '\0';
ASSERT_TRUE( no, out == expected );
}
static void test_encode_buf_to_string( int no, string const &in,
string const &expected ) {
string out;
base64::size_type const n = base64::encode( in.data(), in.size(), &out );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_encode_buf_to_vector( int no, string const &in,
string const &expected ) {
vector<char> out;
base64::size_type const n = base64::encode( in.data(), in.size(), &out );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
static void test_encode_stream_to_stream( int no, string const &in,
string const &expected ) {
istringstream sin( in );
ostringstream sout;
base64::size_type const n = base64::encode( sin, sout );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, sout.str().size() == expected.size() );
ASSERT_TRUE( no, sout.str() == expected );
}
static void test_encode_stream_to_string( int no, string const &in,
string const &expected ) {
istringstream sin( in );
string out;
base64::size_type const n = base64::encode( sin, &out );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, out == expected );
}
static void test_encode_stream_to_vector( int no, string const &in,
string const &expected ) {
istringstream sin( in );
vector<char> out;
base64::size_type const n = base64::encode( sin, &out );
ASSERT_TRUE( no, n == expected.size() );
ASSERT_TRUE( no, out.size() == expected.size() );
ASSERT_TRUE( no, !strncmp( &out[0], expected.data(), expected.size() ) );
}
///////////////////////////////////////////////////////////////////////////////
static test const encode_tests[] = {
/* 0 */ { "Now is the time", "Tm93IGlzIHRoZSB0aW1l" },
/* 1 */ { "Now is the time.", "Tm93IGlzIHRoZSB0aW1lLg==" },
/* 2 */ { "Now is the time..", "Tm93IGlzIHRoZSB0aW1lLi4=" },
{ 0, 0 }
};
static test const decode_tests[] = {
/* 3 */ { "Tm93IGlzIHRoZSB0aW1l", "Now is the time" },
/* 4 */ { "Tm93IGlzIHRoZSB0aW1lLg==", "Now is the time." },
/* 5 */ { "Tm93IGlzIHRoZSB0aW1lLi4=", "Now is the time.." },
// incomplete Base64 encodings
/* 6 */ { "Tm93IGlzIHRoZSB0aW1", "Now is the tim" },
/* 7 */ { "Tm93IGlzIHRoZSB0aW", "Now is the ti" },
/* 8 */ { "Tm93IGlzIHRoZSB0a", "Now is the t" },
{ 0, 0 }
};
static char const *const decode_exception_tests[] = {
"=",
"_m93",
"T_93",
"Tm_3",
"Tm9_",
"=m93",
"T=93",
"Tm=3",
"Tm93=",
"ZmX=",
"ZX==",
"ZX===",
0
};
namespace zorba {
namespace UnitTests {
int test_base64( int, char*[] ) {
int test_no = 0;
for ( test const *t = encode_tests; t->input; ++t, ++test_no ) {
test_encode_buf_to_buf( test_no, t->input, t->expected );
test_encode_buf_to_string( test_no, t->input, t->expected );
test_encode_buf_to_vector( test_no, t->input, t->expected );
test_encode_stream_to_stream( test_no, t->input, t->expected );
test_encode_stream_to_string( test_no, t->input, t->expected );
test_encode_stream_to_vector( test_no, t->input, t->expected );
}
for ( test const *t = decode_tests; t->input; ++t, ++test_no ) {
test_decode_buf_to_buf( test_no, t->input, t->expected );
test_decode_buf_to_string( test_no, t->input, t->expected );
test_decode_buf_to_vector( test_no, t->input, t->expected );
test_decode_stream_to_stream( test_no, t->input, t->expected );
test_decode_stream_to_string( test_no, t->input, t->expected );
test_decode_stream_to_vector( test_no, t->input, t->expected );
}
for ( char const *const *t = decode_exception_tests; *t; ++t, ++test_no )
test_decode_exception( test_no, *t );
cout << failures << " test(s) failed\n";
return failures ? 1 : 0;
}
} // namespace UnitTests
} // namespace zorba
/* vim:set et sw=2 ts=2: */
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "meshobjectreader.h"
// appleseed.renderer headers.
#include "renderer/modeling/object/meshobject.h"
#include "renderer/modeling/object/triangle.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exceptionioerror.h"
#include "foundation/math/triangulator.h"
#include "foundation/mesh/genericmeshfilereader.h"
#include "foundation/mesh/imeshbuilder.h"
#include "foundation/mesh/imeshfilereader.h"
#include "foundation/mesh/objmeshfilereader.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/memory.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <exception>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// MeshObjectArray class implementation.
//
DEFINE_ARRAY(MeshObjectArray);
//
// MeshObjectReader class implementation.
//
namespace
{
class MeshObjectBuilder
: public IMeshBuilder
{
public:
typedef vector<MeshObject*> MeshObjectVector;
MeshObjectBuilder(
const ParamArray& params,
const string& base_object_name)
: m_params(params)
, m_ignore_vertex_normals(m_params.get_optional<bool>("ignore_vertex_normals"))
, m_base_object_name(base_object_name)
, m_untitled_mesh_counter(0)
, m_vertex_count(0)
, m_face_material(0)
, m_face_count(0)
, m_triangulation_error_count(0)
{
}
const MeshObjectVector& get_objects() const
{
return m_objects;
}
virtual void begin_mesh(const string& name)
{
// If the mesh has no name, assign it a number (starting with 0).
const string mesh_name = name.empty() ? to_string(m_untitled_mesh_counter++) : name;
// Construct the final object name from the base object name and the mesh name.
const string object_name = m_base_object_name + "." + mesh_name;
// Create an empty mesh object.
m_objects.push_back(
MeshObjectFactory::create(object_name.c_str(), m_params).release());
m_face_count = 0;
m_triangulation_error_count = 0;
}
virtual void end_mesh()
{
// Print the number of faces that could not be triangulated (if any).
if (m_triangulation_error_count > 0)
{
RENDERER_LOG_WARNING(
"%s polygonal %s (out of %s) could not be triangulated.",
pretty_int(m_triangulation_error_count).c_str(),
plural(m_triangulation_error_count, "face").c_str(),
pretty_int(m_face_count).c_str());
}
// Print the number of vertices and triangles in the mesh.
const size_t vertex_count = m_objects.back()->get_vertex_count();
const size_t triangle_count = m_objects.back()->get_triangle_count();
RENDERER_LOG_INFO(
"loaded mesh object \"%s\" (%s %s, %s %s).",
m_objects.back()->get_name(),
pretty_int(vertex_count).c_str(),
plural(vertex_count, "vertex", "vertices").c_str(),
pretty_int(triangle_count).c_str(),
plural(triangle_count, "triangle").c_str());
}
virtual size_t push_vertex(const Vector3d& v)
{
return m_objects.back()->push_vertex(GVector3(v));
}
virtual size_t push_vertex_normal(const Vector3d& v)
{
return m_objects.back()->push_vertex_normal(GVector3(v));
}
virtual size_t push_tex_coords(const Vector2d& v)
{
return m_objects.back()->push_tex_coords(GVector2(v));
}
virtual void begin_face(const size_t vertex_count)
{
assert(vertex_count >= 3);
clear_keep_memory(m_face_vertices);
clear_keep_memory(m_face_normals);
clear_keep_memory(m_face_tex_coords);
++m_face_count;
m_vertex_count = vertex_count;
m_face_material = Triangle::None;
}
virtual void end_face()
{
assert(m_face_vertices.size() == m_vertex_count);
assert(m_face_normals.size() == 0 || m_face_normals.size() == m_vertex_count);
assert(m_face_tex_coords.size() == 0 || m_face_tex_coords.size() == m_vertex_count);
if (m_vertex_count > 3)
{
// Create the polygon to triangulate.
clear_keep_memory(m_polygon);
for (size_t i = 0; i < m_vertex_count; ++i)
{
m_polygon.push_back(
Vector3d(m_objects.back()->get_vertex(m_face_vertices[i])));
}
// Triangulate the polygon.
clear_keep_memory(m_triangles);
if (!m_triangulator.triangulate(m_polygon, m_triangles))
{
// Skip problematic polygonal faces.
++m_triangulation_error_count;
return;
}
// Insert all triangles of the triangulation into the mesh.
const size_t m_triangle_count = m_triangles.size();
for (size_t i = 0; i < m_triangle_count; i += 3)
{
insert_triangle(
m_triangles[i + 0],
m_triangles[i + 1],
m_triangles[i + 2]);
}
}
else
{
// The face is already a triangle, no triangulation is necessary.
insert_triangle(0, 1, 2);
}
}
virtual void set_face_vertices(const size_t vertices[])
{
for (size_t i = 0; i < m_vertex_count; ++i)
m_face_vertices.push_back(static_cast<uint32>(vertices[i]));
}
virtual void set_face_vertex_normals(const size_t vertex_normals[])
{
for (size_t i = 0; i < m_vertex_count; ++i)
m_face_normals.push_back(static_cast<uint32>(vertex_normals[i]));
}
virtual void set_face_vertex_tex_coords(const size_t tex_coords[])
{
for (size_t i = 0; i < m_vertex_count; ++i)
m_face_tex_coords.push_back(static_cast<uint32>(tex_coords[i]));
}
virtual void set_face_material(const size_t material)
{
m_face_material = static_cast<uint32>(material);
}
private:
const ParamArray m_params;
const bool m_ignore_vertex_normals;
const string m_base_object_name;
size_t m_untitled_mesh_counter;
MeshObjectVector m_objects;
size_t m_vertex_count;
vector<uint32> m_face_vertices;
vector<uint32> m_face_normals;
vector<uint32> m_face_tex_coords;
uint32 m_face_material;
Triangulator<double> m_triangulator;
vector<Vector3d> m_polygon;
vector<size_t> m_triangles;
size_t m_face_count;
size_t m_triangulation_error_count;
void insert_triangle(
const size_t v0_index,
const size_t v1_index,
const size_t v2_index)
{
Triangle triangle;
// Set triangle vertices.
triangle.m_v0 = m_face_vertices[v0_index];
triangle.m_v1 = m_face_vertices[v1_index];
triangle.m_v2 = m_face_vertices[v2_index];
// Set triangle vertex normals.
if (!m_ignore_vertex_normals && m_face_normals.size() == m_vertex_count)
{
triangle.m_n0 = m_face_normals[v0_index];
triangle.m_n1 = m_face_normals[v1_index];
triangle.m_n2 = m_face_normals[v2_index];
}
else
{
// Fetch the triangle vertices.
const Vector3d v0 = Vector3d(m_objects.back()->get_vertex(triangle.m_v0));
const Vector3d v1 = Vector3d(m_objects.back()->get_vertex(triangle.m_v1));
const Vector3d v2 = Vector3d(m_objects.back()->get_vertex(triangle.m_v2));
// Compute the geometric normal to the triangle.
const Vector3d geometric_normal = normalize(cross(v1 - v0, v2 - v0));
// Insert the geometric normal into the mesh.
const size_t geometric_normal_index =
m_objects.back()->push_vertex_normal(GVector3(geometric_normal));
// Assign the geometric normal to all vertices of the triangle.
triangle.m_n0 = geometric_normal_index;
triangle.m_n1 = geometric_normal_index;
triangle.m_n2 = geometric_normal_index;
}
// Set triangle vertex texture coordinates (if any).
if (m_face_tex_coords.size() == m_vertex_count)
{
triangle.m_a0 = m_face_tex_coords[v0_index];
triangle.m_a1 = m_face_tex_coords[v1_index];
triangle.m_a2 = m_face_tex_coords[v2_index];
}
else
{
triangle.m_a0 = Triangle::None;
triangle.m_a1 = Triangle::None;
triangle.m_a2 = Triangle::None;
}
// Set triangle material.
// triangle.m_pa = m_face_material;
triangle.m_pa = 0;
// Insert the triangle into the mesh.
m_objects.back()->push_triangle(triangle);
}
};
}
MeshObjectArray MeshObjectReader::read(
const char* filename,
const char* base_object_name,
const ParamArray& params)
{
assert(filename);
assert(base_object_name);
GenericMeshFileReader reader;
MeshObjectBuilder builder(params, base_object_name);
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
try
{
reader.read(filename, builder);
}
catch (const OBJMeshFileReader::ExceptionInvalidFaceDef& e)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: invalid face definition on line " FMT_SIZE_T ".",
filename,
e.m_line);
return MeshObjectArray();
}
catch (const OBJMeshFileReader::ExceptionParseError& e)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: parse error on line " FMT_SIZE_T ".",
filename,
e.m_line);
return MeshObjectArray();
}
catch (const ExceptionIOError&)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: i/o error.",
filename);
return MeshObjectArray();
}
catch (const exception& e)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: %s.",
filename,
e.what());
return MeshObjectArray();
}
stopwatch.measure();
MeshObjectArray objects;
for (const_each<vector<MeshObject*> > i = builder.get_objects(); i; ++i)
objects.push_back(*i);
// Print the number of loaded objects.
RENDERER_LOG_INFO(
"loaded mesh file %s (%s %s) in %s.",
filename,
pretty_int(objects.size()).c_str(),
plural(objects.size(), "object").c_str(),
pretty_time(stopwatch.get_seconds()).c_str());
return objects;
}
} // namespace renderer
<commit_msg>improved the log messages emitted during geometry loading.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "meshobjectreader.h"
// appleseed.renderer headers.
#include "renderer/modeling/object/meshobject.h"
#include "renderer/modeling/object/triangle.h"
// appleseed.foundation headers.
#include "foundation/core/exceptions/exceptionioerror.h"
#include "foundation/math/triangulator.h"
#include "foundation/mesh/genericmeshfilereader.h"
#include "foundation/mesh/imeshbuilder.h"
#include "foundation/mesh/imeshfilereader.h"
#include "foundation/mesh/objmeshfilereader.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/memory.h"
#include "foundation/utility/stopwatch.h"
#include "foundation/utility/string.h"
// Standard headers.
#include <exception>
#include <vector>
using namespace foundation;
using namespace std;
namespace renderer
{
//
// MeshObjectArray class implementation.
//
DEFINE_ARRAY(MeshObjectArray);
//
// MeshObjectReader class implementation.
//
namespace
{
class MeshObjectBuilder
: public IMeshBuilder
{
public:
typedef vector<MeshObject*> MeshObjectVector;
MeshObjectBuilder(
const ParamArray& params,
const string& base_object_name)
: m_params(params)
, m_ignore_vertex_normals(m_params.get_optional<bool>("ignore_vertex_normals"))
, m_base_object_name(base_object_name)
, m_untitled_mesh_counter(0)
, m_vertex_count(0)
, m_face_material(0)
, m_face_count(0)
, m_triangulation_error_count(0)
, m_total_vertex_count(0)
, m_total_triangle_count(0)
{
}
const MeshObjectVector& get_objects() const
{
return m_objects;
}
size_t get_total_vertex_count() const
{
return m_total_vertex_count;
}
size_t get_total_triangle_count() const
{
return m_total_triangle_count;
}
virtual void begin_mesh(const string& name)
{
// If the mesh has no name, assign it a number (starting with 0).
const string mesh_name = name.empty() ? to_string(m_untitled_mesh_counter++) : name;
// Construct the final object name from the base object name and the mesh name.
const string object_name = m_base_object_name + "." + mesh_name;
// Create an empty mesh object.
m_objects.push_back(
MeshObjectFactory::create(object_name.c_str(), m_params).release());
m_face_count = 0;
m_triangulation_error_count = 0;
}
virtual void end_mesh()
{
// Print the number of faces that could not be triangulated (if any).
if (m_triangulation_error_count > 0)
{
RENDERER_LOG_WARNING(
"while loading mesh object \"%s\": %s polygonal %s (out of %s) could not be triangulated.",
m_objects.back()->get_name(),
pretty_int(m_triangulation_error_count).c_str(),
plural(m_triangulation_error_count, "face").c_str(),
pretty_int(m_face_count).c_str());
}
// Keep track of the total number of vertices and triangles that were loaded.
m_total_vertex_count += m_objects.back()->get_vertex_count();
m_total_triangle_count += m_objects.back()->get_triangle_count();
}
virtual size_t push_vertex(const Vector3d& v)
{
return m_objects.back()->push_vertex(GVector3(v));
}
virtual size_t push_vertex_normal(const Vector3d& v)
{
return m_objects.back()->push_vertex_normal(GVector3(v));
}
virtual size_t push_tex_coords(const Vector2d& v)
{
return m_objects.back()->push_tex_coords(GVector2(v));
}
virtual void begin_face(const size_t vertex_count)
{
assert(vertex_count >= 3);
clear_keep_memory(m_face_vertices);
clear_keep_memory(m_face_normals);
clear_keep_memory(m_face_tex_coords);
++m_face_count;
m_vertex_count = vertex_count;
m_face_material = Triangle::None;
}
virtual void end_face()
{
assert(m_face_vertices.size() == m_vertex_count);
assert(m_face_normals.size() == 0 || m_face_normals.size() == m_vertex_count);
assert(m_face_tex_coords.size() == 0 || m_face_tex_coords.size() == m_vertex_count);
if (m_vertex_count > 3)
{
// Create the polygon to triangulate.
clear_keep_memory(m_polygon);
for (size_t i = 0; i < m_vertex_count; ++i)
{
m_polygon.push_back(
Vector3d(m_objects.back()->get_vertex(m_face_vertices[i])));
}
// Triangulate the polygon.
clear_keep_memory(m_triangles);
if (!m_triangulator.triangulate(m_polygon, m_triangles))
{
// Skip problematic polygonal faces.
++m_triangulation_error_count;
return;
}
// Insert all triangles of the triangulation into the mesh.
const size_t m_triangle_count = m_triangles.size();
for (size_t i = 0; i < m_triangle_count; i += 3)
{
insert_triangle(
m_triangles[i + 0],
m_triangles[i + 1],
m_triangles[i + 2]);
}
}
else
{
// The face is already a triangle, no triangulation is necessary.
insert_triangle(0, 1, 2);
}
}
virtual void set_face_vertices(const size_t vertices[])
{
m_face_vertices.resize(m_vertex_count);
for (size_t i = 0; i < m_vertex_count; ++i)
m_face_vertices[i] = static_cast<uint32>(vertices[i]);
}
virtual void set_face_vertex_normals(const size_t vertex_normals[])
{
m_face_normals.resize(m_vertex_count);
for (size_t i = 0; i < m_vertex_count; ++i)
m_face_normals[i] = static_cast<uint32>(vertex_normals[i]);
}
virtual void set_face_vertex_tex_coords(const size_t tex_coords[])
{
m_face_tex_coords.resize(m_vertex_count);
for (size_t i = 0; i < m_vertex_count; ++i)
m_face_tex_coords[i] = static_cast<uint32>(tex_coords[i]);
}
virtual void set_face_material(const size_t material)
{
m_face_material = static_cast<uint32>(material);
}
private:
const ParamArray m_params;
const bool m_ignore_vertex_normals;
const string m_base_object_name;
size_t m_untitled_mesh_counter;
MeshObjectVector m_objects;
size_t m_vertex_count;
vector<uint32> m_face_vertices;
vector<uint32> m_face_normals;
vector<uint32> m_face_tex_coords;
uint32 m_face_material;
Triangulator<double> m_triangulator;
vector<Vector3d> m_polygon;
vector<size_t> m_triangles;
size_t m_face_count;
size_t m_triangulation_error_count;
size_t m_total_vertex_count;
size_t m_total_triangle_count;
void insert_triangle(
const size_t v0_index,
const size_t v1_index,
const size_t v2_index)
{
Triangle triangle;
// Set triangle vertices.
triangle.m_v0 = m_face_vertices[v0_index];
triangle.m_v1 = m_face_vertices[v1_index];
triangle.m_v2 = m_face_vertices[v2_index];
// Set triangle vertex normals.
if (!m_ignore_vertex_normals && m_face_normals.size() == m_vertex_count)
{
triangle.m_n0 = m_face_normals[v0_index];
triangle.m_n1 = m_face_normals[v1_index];
triangle.m_n2 = m_face_normals[v2_index];
}
else
{
// Fetch the triangle vertices.
const Vector3d v0 = Vector3d(m_objects.back()->get_vertex(triangle.m_v0));
const Vector3d v1 = Vector3d(m_objects.back()->get_vertex(triangle.m_v1));
const Vector3d v2 = Vector3d(m_objects.back()->get_vertex(triangle.m_v2));
// Compute the geometric normal to the triangle.
const Vector3d geometric_normal = normalize(cross(v1 - v0, v2 - v0));
// Insert the geometric normal into the mesh.
const size_t geometric_normal_index =
m_objects.back()->push_vertex_normal(GVector3(geometric_normal));
// Assign the geometric normal to all vertices of the triangle.
triangle.m_n0 = geometric_normal_index;
triangle.m_n1 = geometric_normal_index;
triangle.m_n2 = geometric_normal_index;
}
// Set triangle vertex texture coordinates (if any).
if (m_face_tex_coords.size() == m_vertex_count)
{
triangle.m_a0 = m_face_tex_coords[v0_index];
triangle.m_a1 = m_face_tex_coords[v1_index];
triangle.m_a2 = m_face_tex_coords[v2_index];
}
else
{
triangle.m_a0 = Triangle::None;
triangle.m_a1 = Triangle::None;
triangle.m_a2 = Triangle::None;
}
// Set triangle material.
// triangle.m_pa = m_face_material;
triangle.m_pa = 0;
// Insert the triangle into the mesh.
m_objects.back()->push_triangle(triangle);
}
};
}
MeshObjectArray MeshObjectReader::read(
const char* filename,
const char* base_object_name,
const ParamArray& params)
{
assert(filename);
assert(base_object_name);
GenericMeshFileReader reader;
MeshObjectBuilder builder(params, base_object_name);
Stopwatch<DefaultWallclockTimer> stopwatch;
stopwatch.start();
try
{
reader.read(filename, builder);
}
catch (const OBJMeshFileReader::ExceptionInvalidFaceDef& e)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: invalid face definition on line " FMT_SIZE_T ".",
filename,
e.m_line);
return MeshObjectArray();
}
catch (const OBJMeshFileReader::ExceptionParseError& e)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: parse error on line " FMT_SIZE_T ".",
filename,
e.m_line);
return MeshObjectArray();
}
catch (const ExceptionIOError&)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: i/o error.",
filename);
return MeshObjectArray();
}
catch (const exception& e)
{
RENDERER_LOG_ERROR(
"failed to load mesh file %s: %s.",
filename,
e.what());
return MeshObjectArray();
}
stopwatch.measure();
MeshObjectArray objects;
for (const_each<vector<MeshObject*> > i = builder.get_objects(); i; ++i)
objects.push_back(*i);
// Print the number of loaded objects.
RENDERER_LOG_INFO(
"loaded mesh file %s (%s %s, %s %s, %s %s) in %s.",
filename,
pretty_int(objects.size()).c_str(),
plural(objects.size(), "object").c_str(),
pretty_int(builder.get_total_vertex_count()).c_str(),
plural(builder.get_total_vertex_count(), "vertex", "vertices").c_str(),
pretty_int(builder.get_total_triangle_count()).c_str(),
plural(builder.get_total_triangle_count(), "triangle").c_str(),
pretty_time(stopwatch.get_seconds()).c_str());
return objects;
}
} // namespace renderer
<|endoftext|> |
<commit_before>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <bitset>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template<typename T> constexpr const T &as_const(T &t) { return t; }
template <typename T>
struct static_allocator
{
static constexpr ::std::size_t const max_instances = 16;
static ::std::bitset<max_instances> memory_map_;
static typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
store_[max_instances];
};
template <typename T>
::std::bitset<static_allocator<T>::max_instances>
static_allocator<T>::memory_map_;
template <typename T>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
static_allocator<T>::store_[static_allocator<T>::max_instances];
template <typename T, typename ...A>
T* static_new(A&& ...args)
{
using allocator = static_allocator<T>;
for (::std::size_t i{}; i != allocator::max_instances; ++i)
{
if (!as_const(allocator::memory_map_)[i])
{
auto p(new (&allocator::store_[i]) T(::std::forward<A>(args)...));
allocator::memory_map_[i] = true;
return p;
}
// else do nothing
}
assert(0);
return nullptr;
}
template <typename T>
void static_delete(T const* const p)
{
using allocator = static_allocator<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
allocator::store_)));
assert(as_const(allocator::memory_map_)[i]);
allocator::memory_map_[i] = false;
static_cast<T const*>(static_cast<void const*>(
&allocator::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
deleter_ = deleter_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
using deleter_type = void (*)(void const*);
void* object_ptr_;
stub_ptr_type stub_ptr_{};
deleter_type deleter_;
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <class T>
static void deleter_stub(void const* const p)
{
static_cast<T const*>(p)->~T();
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<commit_msg>strips<commit_after>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <bitset>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template<typename T> constexpr const T &as_const(T &t) { return t; }
template <typename T>
struct static_store
{
static constexpr ::std::size_t const max_instances = 16;
static ::std::bitset<max_instances> memory_map_;
static typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
store_[max_instances];
};
template <typename T>
::std::bitset<static_store<T>::max_instances>
static_store<T>::memory_map_;
template <typename T>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
static_store<T>::store_[static_store<T>::max_instances];
template <typename T, typename ...A>
T* static_new(A&& ...args)
{
using static_store = static_store<T>;
for (::std::size_t i{}; i != static_store::max_instances; ++i)
{
if (!as_const(static_store::memory_map_)[i])
{
auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));
static_store::memory_map_[i] = true;
return p;
}
// else do nothing
}
assert(0);
return nullptr;
}
template <typename T>
void static_delete(T const* const p)
{
using static_store = static_store<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
static_store::store_)));
assert(as_const(static_store::memory_map_)[i]);
static_store::memory_map_[i] = false;
static_cast<T const*>(static_cast<void const*>(
&static_store::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
deleter_ = deleter_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
using deleter_type = void (*)(void const*);
void* object_ptr_;
stub_ptr_type stub_ptr_{};
deleter_type deleter_;
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <class T>
static void deleter_stub(void const* const p)
{
static_cast<T const*>(p)->~T();
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<|endoftext|> |
<commit_before>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <bitset>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template<typename T> constexpr const T &as_const(T &t) { return t; }
template <typename T>
struct static_store
{
static constexpr ::std::size_t const max_instances = 16;
static ::std::bitset<max_instances> memory_map_;
static typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
store_[max_instances];
};
template <typename T>
::std::bitset<static_store<T>::max_instances>
static_store<T>::memory_map_;
template <typename T>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
static_store<T>::store_[static_store<T>::max_instances];
template <typename T, typename ...A>
T* static_new(A&& ...args)
{
using static_store = static_store<T>;
for (::std::size_t i{}; i != static_store::max_instances; ++i)
{
if (!as_const(static_store::memory_map_)[i])
{
auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));
static_store::memory_map_[i] = true;
return p;
}
// else do nothing
}
assert(0);
return nullptr;
}
template <typename T>
void static_delete(T const* const p)
{
using static_store = static_store<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
static_store::store_)));
assert(as_const(static_store::memory_map_)[i]);
static_store::memory_map_[i] = false;
static_cast<T const*>(static_cast<void const*>(
&static_store::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
deleter_ = deleter_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
using deleter_type = void (*)(void const*);
void* object_ptr_;
stub_ptr_type stub_ptr_{};
deleter_type deleter_;
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <class T>
static void deleter_stub(void const* const p)
{
static_cast<T const*>(p)->~T();
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <bitset>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
#include "lightptr.hpp"
namespace
{
template<typename T> constexpr const T &as_const(T &t) { return t; }
template <typename T>
struct static_store
{
static constexpr ::std::size_t const max_instances = 16;
static ::std::bitset<max_instances> memory_map_;
static typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
store_[max_instances];
};
template <typename T>
::std::bitset<static_store<T>::max_instances>
static_store<T>::memory_map_;
template <typename T>
typename ::std::aligned_storage<sizeof(T), alignof(T)>::type
static_store<T>::store_[static_store<T>::max_instances];
template <typename T, typename ...A>
inline T* static_new(A&& ...args)
{
using static_store = static_store<T>;
for (::std::size_t i{}; i != static_store::max_instances; ++i)
{
if (!as_const(static_store::memory_map_)[i])
{
auto p(new (&static_store::store_[i]) T(::std::forward<A>(args)...));
static_store::memory_map_[i] = true;
return p;
}
// else do nothing
}
assert(0);
return nullptr;
}
template <typename T>
inline void static_delete(T const* const p)
{
using static_store = static_store<T>;
auto const i(p - static_cast<T const*>(static_cast<void const*>(
static_store::store_)));
assert(as_const(static_store::memory_map_)[i]);
static_store::memory_map_[i] = false;
static_cast<T const*>(static_cast<void const*>(
&static_store::store_[i]))->~T();
}
}
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
delegate(::std::nullptr_t const) noexcept : delegate() { }
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate(T&& f)
{
*this = ::std::forward<T>(f);
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename ::std::enable_if<
!::std::is_same<delegate, typename ::std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename ::std::decay<T>::type;
store_.reset(static_new<functor_type>(::std::forward<T>(f)),
functor_deleter<functor_type>);
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return ::std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(::std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void reset_stub() noexcept { stub_ptr_ = nullptr; }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
bool operator==(::std::nullptr_t const) const noexcept
{
return !stub_ptr_;
}
bool operator!=(::std::nullptr_t const) const noexcept
{
return stub_ptr_;
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, ::std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
void* object_ptr_;
stub_ptr_type stub_ptr_{};
light_ptr<void> store_;
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T const*>(p)->~T();
static_delete(static_cast<T const*>(p));
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
::std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(::std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<|endoftext|> |
<commit_before>// Copyright by Contributors
#include <xgboost/metric.h>
#include "../helpers.h"
TEST(Metric, RMSE) {
xgboost::Metric * metric = xgboost::Metric::Create("rmse");
ASSERT_STREQ(metric->Name(), "rmse");
EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0, 1e-10);
EXPECT_NEAR(GetMetricEval(metric,
{0.1, 0.9, 0.1, 0.9},
{ 0, 0, 1, 1}),
0.6403, 0.001);
}
<commit_msg>tests/cpp: Add test for elementwise_metric.cc<commit_after>// Copyright by Contributors
#include <xgboost/metric.h>
#include "../helpers.h"
TEST(Metric, RMSE) {
xgboost::Metric * metric = xgboost::Metric::Create("rmse");
ASSERT_STREQ(metric->Name(), "rmse");
EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0, 1e-10);
EXPECT_NEAR(GetMetricEval(metric,
{0.1, 0.9, 0.1, 0.9},
{ 0, 0, 1, 1}),
0.6403, 0.001);
}
TEST(Metric, MAE) {
xgboost::Metric * metric = xgboost::Metric::Create("mae");
ASSERT_STREQ(metric->Name(), "mae");
EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0, 1e-10);
EXPECT_NEAR(GetMetricEval(metric,
{0.1, 0.9, 0.1, 0.9},
{ 0, 0, 1, 1}),
0.5, 0.001);
}
TEST(Metric, LogLoss) {
xgboost::Metric * metric = xgboost::Metric::Create("logloss");
ASSERT_STREQ(metric->Name(), "logloss");
EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0, 1e-10);
EXPECT_NEAR(GetMetricEval(metric,
{0.1, 0.9, 0.1, 0.9},
{ 0, 0, 1, 1}),
1.2039, 0.001);
}
TEST(Metric, Error) {
xgboost::Metric * metric = xgboost::Metric::Create("error");
ASSERT_STREQ(metric->Name(), "error");
EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0, 1e-10);
EXPECT_NEAR(GetMetricEval(metric,
{0.1, 0.9, 0.1, 0.9},
{ 0, 0, 1, 1}),
0.5, 0.001);
EXPECT_ANY_THROW(xgboost::Metric::Create("error@abc"));
delete metric;
metric = xgboost::Metric::Create("[email protected]");
EXPECT_STREQ(metric->Name(), "error");
delete metric;
metric = xgboost::Metric::Create("[email protected]");
ASSERT_STREQ(metric->Name(), "[email protected]");
EXPECT_STREQ(metric->Name(), "[email protected]");
EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0, 1e-10);
EXPECT_NEAR(GetMetricEval(metric,
{0.1, 0.2, 0.1, 0.2},
{ 0, 0, 1, 1}),
0.5, 0.001);
}
TEST(Metric, PoissionNegLogLik) {
xgboost::Metric * metric = xgboost::Metric::Create("poisson-nloglik");
ASSERT_STREQ(metric->Name(), "poisson-nloglik");
EXPECT_NEAR(GetMetricEval(metric, {0, 1}, {0, 1}), 0.5, 1e-10);
EXPECT_NEAR(GetMetricEval(metric,
{0.1, 0.2, 0.1, 0.2},
{ 0, 0, 1, 1}),
1.1280, 0.001);
}
<|endoftext|> |
<commit_before>#include "searchdialog.h"
#include "ui_searchdialog.h"
#include <QPlainTextEdit>
#include <QDebug>
/**
Object's constructor.
*/
SearchDialog::SearchDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SearchDialog)
{
ui->setupUi(this);
gbReplaceClicked = false;
gbSearchClicked = false;
gbReplaceAllClicked = false;
}
/**
Object's destructor.
*/
SearchDialog::~SearchDialog()
{
delete ui;
}
/**
Action triggered when the search button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_searchButton_clicked()
{
gbSearchClicked = true;
emit search_signal_disableHighLight();
emit search_signal_getTextEditText();
}
/**
Action triggered when the replace button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_replaceButton_clicked()
{
gbReplaceClicked = true;
emit(search_signal_getTextEditText());
}
/**
Action triggered when the replace all button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_replaceAllButton_clicked()
{
gbReplaceAllClicked = true;
emit(search_signal_getTextEditText());
}
/**
Action triggered when the swap button is clicked.
This will swap the text into the "search" line edit, with the
text into the "reaplace all" line edit.
*/
void SearchDialog::on_gobSwapTextButton_clicked()
{
QString lsReplace;
lsReplace = this->ui->seachDialog_searchLineEdit->text();
this->ui->seachDialog_searchLineEdit->setText(this->ui->searchDialog_replaceLineEdit->text());
this->ui->searchDialog_replaceLineEdit->setText(lsReplace);
}
/**
Creates a copy of the TextEdit object, and dependign on
the clicked button, the according action modifications
will be made. Then, the new object will be send in a signal
to the main UI.
*/
void SearchDialog::search_slot_setTextEdit(QPlainTextEdit *textEdit)
{
this->gobTextEdit = textEdit;
QList<QTextEdit::ExtraSelection> extraSelections;
QTextEdit::ExtraSelection selection;
if(gbReplaceAllClicked){
gbReplaceAllClicked = false;
gobTextEdit->extraSelections().clear();
gobTextEdit->textCursor().clearSelection();
emit(search_signal_resetCursor());
gsFoundText = ui->seachDialog_searchLineEdit->text();
while(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
selection.cursor = gobTextEdit->textCursor();
extraSelections.append(selection);
}
gobTextEdit->setExtraSelections(extraSelections);
QTextCursor cursor;
for(int i=0; i < extraSelections.length(); i++){
cursor = extraSelections.at(i).cursor;
cursor.insertText(ui->searchDialog_replaceLineEdit->text());
}
gsFoundText = "";
gobTextEdit->extraSelections().clear();
extraSelections.clear();
}else if(gbSearchClicked){
gbSearchClicked = false;
QColor lineColor = QColor(Qt::yellow).lighter(100);
selection.format.setBackground(lineColor);
selection.format.setForeground(QColor(0,0,0));
gobTextEdit->extraSelections().clear();
if(gsFoundText != ui->seachDialog_searchLineEdit->text()){
giOcurrencesFound = 0;
giLogCursorPos = 0;
//qDebug() << "searchDialog: Emmitting resetCursor SIGNAL";
emit(search_signal_resetCursor());
gsFoundText = ui->seachDialog_searchLineEdit->text();
while(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
giOcurrencesFound ++;
selection.cursor = gobTextEdit->textCursor();
extraSelections.append(selection);
}
extraSelections.append(selection);
gobTextEdit->setExtraSelections(extraSelections);
//qDebug() << "searchDialog: Emmitting resetCursor SIGNAL";
emit(search_signal_resetCursor());
if(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
ui->searchDialog_replaceButton->setEnabled(true);
giLogCursorPos = 1;
}
ui->ocurrencesCounterLabel->setText(QString("%1/%2").arg(giLogCursorPos).arg(giOcurrencesFound));
}else{
if(!gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
//qDebug() << "searchDialog: Emmitting resetCursor SIGNAL";
emit(search_signal_resetCursor());
giLogCursorPos = 0;
if(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
giLogCursorPos ++;
}
}else{
ui->searchDialog_replaceButton->setEnabled(true);
giLogCursorPos ++;
}
ui->ocurrencesCounterLabel->setText(QString("%1/%2").arg(giLogCursorPos).arg(giOcurrencesFound));
}
}else if(gbReplaceClicked){
gbReplaceClicked = false;
if(gsFoundText == ui->seachDialog_searchLineEdit->text()){
gobTextEdit->textCursor().insertText(ui->searchDialog_replaceLineEdit->text());
}
ui->searchDialog_replaceButton->setEnabled(false);
}
emit search_signal_enableHighLight();
}
<commit_msg>Fixed ocurrences counter behaviour<commit_after>#include "searchdialog.h"
#include "ui_searchdialog.h"
#include <QPlainTextEdit>
#include <QDebug>
/**
Object's constructor.
*/
SearchDialog::SearchDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SearchDialog)
{
ui->setupUi(this);
gbReplaceClicked = false;
gbSearchClicked = false;
gbReplaceAllClicked = false;
}
/**
Object's destructor.
*/
SearchDialog::~SearchDialog()
{
delete ui;
}
/**
Action triggered when the search button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_searchButton_clicked()
{
gbSearchClicked = true;
emit search_signal_disableHighLight();
emit search_signal_getTextEditText();
}
/**
Action triggered when the replace button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_replaceButton_clicked()
{
gbReplaceClicked = true;
emit(search_signal_getTextEditText());
}
/**
Action triggered when the replace all button is clicked.
This will rise a flag, which will be used in the
setTextEdit method.
*/
void SearchDialog::on_searchDialog_replaceAllButton_clicked()
{
gbReplaceAllClicked = true;
emit(search_signal_getTextEditText());
}
/**
Action triggered when the swap button is clicked.
This will swap the text into the "search" line edit, with the
text into the "reaplace all" line edit.
*/
void SearchDialog::on_gobSwapTextButton_clicked()
{
QString lsReplace;
lsReplace = this->ui->seachDialog_searchLineEdit->text();
this->ui->seachDialog_searchLineEdit->setText(this->ui->searchDialog_replaceLineEdit->text());
this->ui->searchDialog_replaceLineEdit->setText(lsReplace);
}
/**
Creates a copy of the TextEdit object, and dependign on
the clicked button, the according action modifications
will be made. Then, the new object will be send in a signal
to the main UI.
*/
void SearchDialog::search_slot_setTextEdit(QPlainTextEdit *textEdit)
{
this->gobTextEdit = textEdit;
QList<QTextEdit::ExtraSelection> extraSelections;
QTextEdit::ExtraSelection selection;
if(gbReplaceAllClicked){
gbReplaceAllClicked = false;
gobTextEdit->extraSelections().clear();
gobTextEdit->textCursor().clearSelection();
emit(search_signal_resetCursor());
gsFoundText = ui->seachDialog_searchLineEdit->text();
while(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
selection.cursor = gobTextEdit->textCursor();
extraSelections.append(selection);
}
gobTextEdit->setExtraSelections(extraSelections);
QTextCursor cursor;
for(int i=0; i < extraSelections.length(); i++){
cursor = extraSelections.at(i).cursor;
cursor.insertText(ui->searchDialog_replaceLineEdit->text());
}
gsFoundText = "";
gobTextEdit->extraSelections().clear();
extraSelections.clear();
}else if(gbSearchClicked){
gbSearchClicked = false;
giOcurrencesFound = 0;
gsFoundText = "";
QColor lineColor = QColor(Qt::yellow).lighter(100);
selection.format.setBackground(lineColor);
selection.format.setForeground(QColor(0,0,0));
gobTextEdit->extraSelections().clear();
if(gsFoundText != ui->seachDialog_searchLineEdit->text()){
giLogCursorPos = 0;
emit(search_signal_resetCursor());
gsFoundText = ui->seachDialog_searchLineEdit->text();
while(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
giOcurrencesFound ++;
selection.cursor = gobTextEdit->textCursor();
extraSelections.append(selection);
}
extraSelections.append(selection);
gobTextEdit->setExtraSelections(extraSelections);
emit(search_signal_resetCursor());
if(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
ui->searchDialog_replaceButton->setEnabled(true);
giLogCursorPos = 1;
}
ui->ocurrencesCounterLabel->setText(QString("%1/%2").arg(giLogCursorPos).arg(giOcurrencesFound));
}else{
if(!gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
emit(search_signal_resetCursor());
giLogCursorPos = 0;
if(gobTextEdit->find(ui->seachDialog_searchLineEdit->text())){
giLogCursorPos ++;
}
}else{
ui->searchDialog_replaceButton->setEnabled(true);
giLogCursorPos ++;
}
ui->ocurrencesCounterLabel->setText(QString("%1/%2").arg(giLogCursorPos).arg(giOcurrencesFound));
}
}else if(gbReplaceClicked){
gbReplaceClicked = false;
if(gsFoundText == ui->seachDialog_searchLineEdit->text()){
gobTextEdit->textCursor().insertText(ui->searchDialog_replaceLineEdit->text());
}
ui->searchDialog_replaceButton->setEnabled(false);
}
emit search_signal_enableHighLight();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015-present 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.
*/
// Simple test for memset.
// Also serves as a template for other tests.
/* HIT_START
* BUILD: %t %s ../../test_common.cpp
* TEST: %t
* HIT_END
*/
#include "hip/hip_runtime.h"
#include "test_common.h"
bool testhipMemset2D(int memsetval,int p_gpuDevice)
{
size_t numH = 256;
size_t numW = 256;
size_t pitch_A;
size_t width = numW * sizeof(char);
size_t sizeElements = width * numH;
size_t elements = numW* numH;
printf ("testhipMemset2D memsetval=%2x device=%d\n", memsetval, p_gpuDevice);
char *A_d;
char *A_h;
bool testResult = true;
HIPCHECK ( hipMemAllocPitch((hipDeviceptr_t*)&A_d, &pitch_A, width , numH,16) );
A_h = (char*)malloc(sizeElements);
HIPASSERT(A_h != NULL);
for (size_t i=0; i<elements; i++) {
A_h[i] = 1;
}
HIPCHECK ( hipMemset2D(A_d, pitch_A, memsetval, numW, numH) );
HIPCHECK ( hipMemcpy2D(A_h, width, A_d, pitch_A, numW, numH, hipMemcpyDeviceToHost));
for (int i=0; i<elements; i++) {
if (A_h[i] != memsetval) {
testResult = false;
printf("testhipMemset2D mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval);
break;
}
}
hipFree(A_d);
free(A_h);
return testResult;
}
bool testhipMemset2DAsync(int memsetval,int p_gpuDevice)
{
size_t numH = 256;
size_t numW = 256;
size_t pitch_A;
size_t width = numW * sizeof(char);
size_t sizeElements = width * numH;
size_t elements = numW* numH;
printf ("testhipMemset2DAsync memsetval=%2x device=%d\n", memsetval, p_gpuDevice);
char *A_d;
char *A_h;
bool testResult = true;
HIPCHECK ( hipMallocPitch((void**)&A_d, &pitch_A, width , numH) );
A_h = (char*)malloc(sizeElements);
HIPASSERT(A_h != NULL);
for (size_t i=0; i<elements; i++) {
A_h[i] = 1;
}
hipStream_t stream;
HIPCHECK(hipStreamCreate(&stream));
HIPCHECK ( hipMemset2DAsync(A_d, pitch_A, memsetval, numW, numH, stream) );
HIPCHECK ( hipMemcpy2D(A_h, width, A_d, pitch_A, numW, numH, hipMemcpyDeviceToHost));
for (int i=0; i<elements; i++) {
if (A_h[i] != memsetval) {
testResult = false;
printf("testhipMemset2DAsync mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval);
break;
}
}
hipFree(A_d);
HIPCHECK(hipStreamDestroy(stream));
free(A_h);
return testResult;
}
int main(int argc, char *argv[])
{
HipTest::parseStandardArguments(argc, argv, true);
HIPCHECK(hipSetDevice(p_gpuDevice));
hipCtx_t context;
hipCtxCreate(&context, 0, p_gpuDevice);
bool testResult = false;
testResult = testhipMemset2D(memsetval, p_gpuDevice);
testResult = testhipMemset2DAsync(memsetval, p_gpuDevice);
hipCtxDestroy(context);
if(testResult){
passed();
}
}
<commit_msg>hipMemset2D test should pass only if both async and sync subtests pass.<commit_after>/*
Copyright (c) 2015-present 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.
*/
// Simple test for memset.
// Also serves as a template for other tests.
/* HIT_START
* BUILD: %t %s ../../test_common.cpp
* TEST: %t
* HIT_END
*/
#include "hip/hip_runtime.h"
#include "test_common.h"
bool testhipMemset2D(int memsetval,int p_gpuDevice)
{
size_t numH = 256;
size_t numW = 256;
size_t pitch_A;
size_t width = numW * sizeof(char);
size_t sizeElements = width * numH;
size_t elements = numW* numH;
printf ("testhipMemset2D memsetval=%2x device=%d\n", memsetval, p_gpuDevice);
char *A_d;
char *A_h;
bool testResult = true;
HIPCHECK ( hipMemAllocPitch((hipDeviceptr_t*)&A_d, &pitch_A, width , numH,16) );
A_h = (char*)malloc(sizeElements);
HIPASSERT(A_h != NULL);
for (size_t i=0; i<elements; i++) {
A_h[i] = 1;
}
HIPCHECK ( hipMemset2D(A_d, pitch_A, memsetval, numW, numH) );
HIPCHECK ( hipMemcpy2D(A_h, width, A_d, pitch_A, numW, numH, hipMemcpyDeviceToHost));
for (int i=0; i<elements; i++) {
if (A_h[i] != memsetval) {
testResult = false;
printf("testhipMemset2D mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval);
break;
}
}
hipFree(A_d);
free(A_h);
return testResult;
}
bool testhipMemset2DAsync(int memsetval,int p_gpuDevice)
{
size_t numH = 256;
size_t numW = 256;
size_t pitch_A;
size_t width = numW * sizeof(char);
size_t sizeElements = width * numH;
size_t elements = numW* numH;
printf ("testhipMemset2DAsync memsetval=%2x device=%d\n", memsetval, p_gpuDevice);
char *A_d;
char *A_h;
bool testResult = true;
HIPCHECK ( hipMallocPitch((void**)&A_d, &pitch_A, width , numH) );
A_h = (char*)malloc(sizeElements);
HIPASSERT(A_h != NULL);
for (size_t i=0; i<elements; i++) {
A_h[i] = 1;
}
hipStream_t stream;
HIPCHECK(hipStreamCreate(&stream));
HIPCHECK ( hipMemset2DAsync(A_d, pitch_A, memsetval, numW, numH, stream) );
HIPCHECK ( hipMemcpy2D(A_h, width, A_d, pitch_A, numW, numH, hipMemcpyDeviceToHost));
for (int i=0; i<elements; i++) {
if (A_h[i] != memsetval) {
testResult = false;
printf("testhipMemset2DAsync mismatch at index:%d computed:%02x, memsetval:%02x\n", i, (int)A_h[i], (int)memsetval);
break;
}
}
hipFree(A_d);
HIPCHECK(hipStreamDestroy(stream));
free(A_h);
return testResult;
}
int main(int argc, char *argv[])
{
HipTest::parseStandardArguments(argc, argv, true);
HIPCHECK(hipSetDevice(p_gpuDevice));
hipCtx_t context;
hipCtxCreate(&context, 0, p_gpuDevice);
bool testResult = false;
testResult &= testhipMemset2D(memsetval, p_gpuDevice);
testResult &= testhipMemset2DAsync(memsetval, p_gpuDevice);
hipCtxDestroy(context);
if(testResult){
passed();
}
}
<|endoftext|> |
<commit_before>#include <QString>
#include <QtTest>
#include <getopt.h>
#include "application.h"
class Test_Application : public QObject
{
Q_OBJECT
public:
Test_Application();
private slots:
void test_process_cmd();
void test_crc_index_cmd();
void test_crc_name_cmd();
private:
void prepare_report(QuCRC_t & uCRC);
QString report;
};
Test_Application::Test_Application():
QObject(0)
{
}
void Test_Application::test_process_cmd()
{
int argc = 0;
Application& app = Application::get_instance(argc, NULL);
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
CRC_Param_Info info = QuCRC_t::CRC_List[i];
report = "For CRC: " + info.name + "\n cmd: ";
std::vector<std::string> cmd = {
"--bits" , QString::number(info.bits, 10).toStdString(),
"--poly" , QString::number(info.poly, 16).toStdString(),
"--init" , QString::number(info.init, 16).toStdString(),
"--xor_out" , QString::number(info.xor_out, 16).toStdString(),
"--ref_in" , QString::number(info.ref_in, 10).toStdString(),
"--ref_out" , QString::number(info.ref_out, 10).toStdString()
};
argc = cmd.size()+1; //+1 see getopt_long function
char *argv[argc];
for(size_t j = 1; j <= cmd.size(); j++) {
argv[j] = (char *)cmd[j-1].c_str();
report += cmd[j-1].c_str();
report += " ";
}
// We use the processing_cmd function for processing the command line
// For this we use the getopt_long function several times
// to work properly, we must reset the optind
optind = 0;
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_index_cmd()
{
int argc = 0;
Application& app = Application::get_instance(argc, NULL);
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
CRC_Param_Info info = QuCRC_t::CRC_List[i];
report = "For CRC: " + info.name + "\n cmd: ";
std::vector<std::string> cmd = {
"--crc_index" , QString::number(i).toStdString(),
};
argc = cmd.size()+1; //+1 see getopt_long function
char *argv[argc];
for(size_t j = 1; j <= cmd.size(); j++) {
argv[j] = (char *)cmd[j-1].c_str();
report += cmd[j-1].c_str();
report += " ";
}
// We use the processing_cmd function for processing the command line
// For this we use the getopt_long function several times
// to work properly, we must reset the optind
optind = 0;
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_name_cmd()
{
int argc = 0;
Application& app = Application::get_instance(argc, NULL);
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
CRC_Param_Info info = QuCRC_t::CRC_List[i];
report = "For CRC: " + info.name + "\n cmd: ";
std::vector<std::string> cmd = {
"--crc_name" , info.name.toStdString(),
};
argc = cmd.size()+1; //+1 see getopt_long function
char *argv[argc];
for(size_t j = 1; j <= cmd.size(); j++) {
argv[j] = (char *)cmd[j-1].c_str();
report += cmd[j-1].c_str();
report += " ";
}
// We use the processing_cmd function for processing the command line
// For this we use the getopt_long function several times
// to work properly, we must reset the optind
optind = 0;
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::prepare_report(QuCRC_t & uCRC)
{
report += "\n but get:";
report += " bits " + QString::number(uCRC.get_bits(), 10);
report += " poly " + QString::number(uCRC.get_poly(), 16);
report += " init " + QString::number(uCRC.get_init(), 16);
report += " xor_out " + QString::number(uCRC.get_xor_out(), 16);
report += " ref_in " + QString::number(uCRC.get_ref_in(), 10);
report += " ref_out " + QString::number(uCRC.get_ref_out(), 10);
}
QTEST_APPLESS_MAIN(Test_Application)
#include "test_application.moc"
<commit_msg>Refactoring app test<commit_after>#include <QString>
#include <QtTest>
#include <getopt.h>
#include "application.h"
class Test_Application : public QObject
{
Q_OBJECT
public:
Test_Application();
private slots:
void test_process_cmd();
void test_crc_index_cmd();
void test_crc_name_cmd();
private:
void prepare_report(QuCRC_t & uCRC);
void prepare_argv(std::vector<std::string> &cmd);
static const size_t MAX_ARGC = 512;
QString report;
int argc;
char *argv[MAX_ARGC];
Application& app;
CRC_Param_Info info;
};
Test_Application::Test_Application():
QObject(0),
//private
argc(0),
app(Application::get_instance(argc, NULL))
{
}
void Test_Application::test_process_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--bits" , QString::number(info.bits, 10).toStdString(),
"--poly" , QString::number(info.poly, 16).toStdString(),
"--init" , QString::number(info.init, 16).toStdString(),
"--xor_out" , QString::number(info.xor_out, 16).toStdString(),
"--ref_in" , QString::number(info.ref_in, 10).toStdString(),
"--ref_out" , QString::number(info.ref_out, 10).toStdString()
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_index_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--crc_index" , QString::number(i).toStdString(),
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::test_crc_name_cmd()
{
//i = 1 //without custom CRC (custom CRC have index 0)
for(size_t i = 1; i < QuCRC_t::CRC_List.size(); ++i)
{
info = QuCRC_t::CRC_List[i];
std::vector<std::string> cmd = {
"--crc_name" , info.name.toStdString(),
};
prepare_argv(cmd);
app.processing_cmd(argc, argv);
if( !(app.uCRC == info) )
{
prepare_report(app.uCRC);
QFAIL(report.toStdString().c_str());
}
}
}
void Test_Application::prepare_report(QuCRC_t & uCRC)
{
report = "For CRC: " + info.name + "\n cmd: ";
for(int j = 1; j < argc; j++)
{
report += argv[j];
report += " ";
}
report += "\n but get:";
report += " bits " + QString::number(uCRC.get_bits(), 10);
report += " poly " + QString::number(uCRC.get_poly(), 16);
report += " init " + QString::number(uCRC.get_init(), 16);
report += " xor_out " + QString::number(uCRC.get_xor_out(), 16);
report += " ref_in " + QString::number(uCRC.get_ref_in(), 10);
report += " ref_out " + QString::number(uCRC.get_ref_out(), 10);
}
void Test_Application::prepare_argv(std::vector<std::string> &cmd)
{
argc = cmd.size()+1; //+1 see getopt_long function
for(size_t j = 1; j <= cmd.size(); j++)
{
argv[j] = (char *)cmd[j-1].c_str();
}
// We use the processing_cmd function for processing the command line
// For this we use the getopt_long function several times
// to work properly, we must reset the optind
optind = 0;
}
QTEST_APPLESS_MAIN(Test_Application)
#include "test_application.moc"
<|endoftext|> |
<commit_before>//===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a '-print-cfg' analysis pass, which emits the
// cfg.<fnname>.dot file for each function in the program, with a graph of the
// CFG for that function.
//
// The other main feature of this file is that it implements the
// Function::viewCFG method, which is useful for debugging passes which operate
// on the CFG.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/CFGPrinter.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Config/config.h"
#include <sstream>
#include <fstream>
using namespace llvm;
/// CFGOnly flag - This is used to control whether or not the CFG graph printer
/// prints out the contents of basic blocks or not. This is acceptable because
/// this code is only really used for debugging purposes.
///
static bool CFGOnly = false;
namespace llvm {
template<>
struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
static std::string getGraphName(const Function *F) {
return "CFG for '" + F->getName() + "' function";
}
static std::string getNodeLabel(const BasicBlock *Node,
const Function *Graph) {
if (CFGOnly && !Node->getName().empty())
return Node->getName() + ":";
std::ostringstream Out;
if (CFGOnly) {
WriteAsOperand(Out, Node, false, true);
return Out.str();
}
if (Node->getName().empty()) {
WriteAsOperand(Out, Node, false, true);
Out << ":";
}
Out << *Node;
std::string OutStr = Out.str();
if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
// Process string output to make it nicer...
for (unsigned i = 0; i != OutStr.length(); ++i)
if (OutStr[i] == '\n') { // Left justify
OutStr[i] = '\\';
OutStr.insert(OutStr.begin()+i+1, 'l');
} else if (OutStr[i] == ';') { // Delete comments!
unsigned Idx = OutStr.find('\n', i+1); // Find end of line
OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
--i;
}
return OutStr;
}
static std::string getEdgeSourceLabel(const BasicBlock *Node,
succ_const_iterator I) {
// Label source of conditional branches with "T" or "F"
if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
if (BI->isConditional())
return (I == succ_begin(Node)) ? "T" : "F";
return "";
}
};
}
namespace {
struct CFGPrinter : public FunctionPass {
virtual bool runOnFunction(Function &F) {
std::string Filename = "cfg." + F.getName() + ".dot";
std::cerr << "Writing '" << Filename << "'...";
std::ofstream File(Filename.c_str());
if (File.good())
WriteGraph(File, (const Function*)&F);
else
std::cerr << " error opening file for writing!";
std::cerr << "\n";
return false;
}
void print(std::ostream &OS, const Module* = 0) const {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
RegisterAnalysis<CFGPrinter> P1("print-cfg",
"Print CFG of function to 'dot' file");
struct CFGOnlyPrinter : public CFGPrinter {
virtual bool runOnFunction(Function &F) {
bool OldCFGOnly = CFGOnly;
CFGOnly = true;
CFGPrinter::runOnFunction(F);
CFGOnly = OldCFGOnly;
return false;
}
void print(std::ostream &OS, const Module* = 0) const {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
RegisterAnalysis<CFGOnlyPrinter>
P2("print-cfg-only",
"Print CFG of function to 'dot' file (with no function bodies)");
}
/// viewCFG - This function is meant for use from the debugger. You can just
/// say 'call F->viewCFG()' and a ghostview window should pop up from the
/// program, displaying the CFG of the current function. This depends on there
/// being a 'dot' and 'gv' program in your path.
///
void Function::viewCFG() const {
#ifndef NDEBUG
std::string Filename = "/tmp/cfg." + getName() + ".dot";
std::cerr << "Writing '" << Filename << "'... ";
std::ofstream F(Filename.c_str());
if (!F.good()) {
std::cerr << " error opening file for writing!\n";
return;
}
WriteGraph(F, this);
F.close();
std::cerr << "\n";
#ifdef HAVE_GRAPHVIZ
std::cerr << "Running 'Graphviz' program... " << std::flush;
if (system((LLVM_PATH_GRAPHVIZ " " + Filename).c_str())) {
std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
} else {
system(("rm " + Filename).c_str());
return;
}
#endif
#ifdef HAVE_GV
std::cerr << "Running 'dot' program... " << std::flush;
if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
+ " > /tmp/cfg.tempgraph.ps").c_str())) {
std::cerr << "Error running dot: 'dot' not in path?\n";
} else {
std::cerr << "\n";
system("gv /tmp/cfg.tempgraph.ps");
}
system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
return;
#endif
#endif
std::cerr << "Function::viewCFG is only available in debug builds on "
<< "systems with Graphviz or gv!\n";
system(("rm " + Filename).c_str());
}
/// viewCFGOnly - This function is meant for use from the debugger. It works
/// just like viewCFG, but it does not include the contents of basic blocks
/// into the nodes, just the label. If you are only interested in the CFG t
/// his can make the graph smaller.
///
void Function::viewCFGOnly() const {
CFGOnly = true;
viewCFG();
CFGOnly = false;
}
FunctionPass *llvm::createCFGPrinterPass () {
return new CFGPrinter();
}
FunctionPass *llvm::createCFGOnlyPrinterPass () {
return new CFGOnlyPrinter();
}
<commit_msg>* Unbreak optimized build (noticed by Eric van Riet Paap) * Comment #endif clauses for readability<commit_after>//===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a '-print-cfg' analysis pass, which emits the
// cfg.<fnname>.dot file for each function in the program, with a graph of the
// CFG for that function.
//
// The other main feature of this file is that it implements the
// Function::viewCFG method, which is useful for debugging passes which operate
// on the CFG.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/CFGPrinter.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Config/config.h"
#include <sstream>
#include <fstream>
using namespace llvm;
/// CFGOnly flag - This is used to control whether or not the CFG graph printer
/// prints out the contents of basic blocks or not. This is acceptable because
/// this code is only really used for debugging purposes.
///
static bool CFGOnly = false;
namespace llvm {
template<>
struct DOTGraphTraits<const Function*> : public DefaultDOTGraphTraits {
static std::string getGraphName(const Function *F) {
return "CFG for '" + F->getName() + "' function";
}
static std::string getNodeLabel(const BasicBlock *Node,
const Function *Graph) {
if (CFGOnly && !Node->getName().empty())
return Node->getName() + ":";
std::ostringstream Out;
if (CFGOnly) {
WriteAsOperand(Out, Node, false, true);
return Out.str();
}
if (Node->getName().empty()) {
WriteAsOperand(Out, Node, false, true);
Out << ":";
}
Out << *Node;
std::string OutStr = Out.str();
if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
// Process string output to make it nicer...
for (unsigned i = 0; i != OutStr.length(); ++i)
if (OutStr[i] == '\n') { // Left justify
OutStr[i] = '\\';
OutStr.insert(OutStr.begin()+i+1, 'l');
} else if (OutStr[i] == ';') { // Delete comments!
unsigned Idx = OutStr.find('\n', i+1); // Find end of line
OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
--i;
}
return OutStr;
}
static std::string getEdgeSourceLabel(const BasicBlock *Node,
succ_const_iterator I) {
// Label source of conditional branches with "T" or "F"
if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
if (BI->isConditional())
return (I == succ_begin(Node)) ? "T" : "F";
return "";
}
};
}
namespace {
struct CFGPrinter : public FunctionPass {
virtual bool runOnFunction(Function &F) {
std::string Filename = "cfg." + F.getName() + ".dot";
std::cerr << "Writing '" << Filename << "'...";
std::ofstream File(Filename.c_str());
if (File.good())
WriteGraph(File, (const Function*)&F);
else
std::cerr << " error opening file for writing!";
std::cerr << "\n";
return false;
}
void print(std::ostream &OS, const Module* = 0) const {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
RegisterAnalysis<CFGPrinter> P1("print-cfg",
"Print CFG of function to 'dot' file");
struct CFGOnlyPrinter : public CFGPrinter {
virtual bool runOnFunction(Function &F) {
bool OldCFGOnly = CFGOnly;
CFGOnly = true;
CFGPrinter::runOnFunction(F);
CFGOnly = OldCFGOnly;
return false;
}
void print(std::ostream &OS, const Module* = 0) const {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
};
RegisterAnalysis<CFGOnlyPrinter>
P2("print-cfg-only",
"Print CFG of function to 'dot' file (with no function bodies)");
}
/// viewCFG - This function is meant for use from the debugger. You can just
/// say 'call F->viewCFG()' and a ghostview window should pop up from the
/// program, displaying the CFG of the current function. This depends on there
/// being a 'dot' and 'gv' program in your path.
///
void Function::viewCFG() const {
#ifndef NDEBUG
std::string Filename = "/tmp/cfg." + getName() + ".dot";
std::cerr << "Writing '" << Filename << "'... ";
std::ofstream F(Filename.c_str());
if (!F.good()) {
std::cerr << " error opening file for writing!\n";
return;
}
WriteGraph(F, this);
F.close();
std::cerr << "\n";
#ifdef HAVE_GRAPHVIZ
std::cerr << "Running 'Graphviz' program... " << std::flush;
if (system((LLVM_PATH_GRAPHVIZ " " + Filename).c_str())) {
std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
} else {
system(("rm " + Filename).c_str());
return;
}
#endif // HAVE_GRAPHVIZ
#ifdef HAVE_GV
std::cerr << "Running 'dot' program... " << std::flush;
if (system(("dot -Tps -Nfontname=Courier -Gsize=7.5,10 " + Filename
+ " > /tmp/cfg.tempgraph.ps").c_str())) {
std::cerr << "Error running dot: 'dot' not in path?\n";
} else {
std::cerr << "\n";
system("gv /tmp/cfg.tempgraph.ps");
}
system(("rm " + Filename + " /tmp/cfg.tempgraph.ps").c_str());
return;
#endif // HAVE_GV
#endif // NDEBUG
std::cerr << "Function::viewCFG is only available in debug builds on "
<< "systems with Graphviz or gv!\n";
#ifndef NDEBUG
system(("rm " + Filename).c_str());
#endif
}
/// viewCFGOnly - This function is meant for use from the debugger. It works
/// just like viewCFG, but it does not include the contents of basic blocks
/// into the nodes, just the label. If you are only interested in the CFG t
/// his can make the graph smaller.
///
void Function::viewCFGOnly() const {
CFGOnly = true;
viewCFG();
CFGOnly = false;
}
FunctionPass *llvm::createCFGPrinterPass () {
return new CFGPrinter();
}
FunctionPass *llvm::createCFGOnlyPrinterPass () {
return new CFGOnlyPrinter();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 Red Hat, 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 "condor_common.h"
#include "../condor_collector.V6/CollectorPlugin.h"
#include "hashkey.h"
#include "../condor_collector.V6/collector.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_config.h"
#include "SlotObject.h"
#include "NegotiatorObject.h"
#include "SchedulerObject.h"
#include "CollectorObject.h"
#include "GridObject.h"
#include "PoolUtils.h"
#include "broker_utils.h"
//extern DaemonCore *daemonCore;
using namespace std;
using namespace com::redhat::grid;
struct MgmtCollectorPlugin : public Service, CollectorPlugin
{
// ManagementAgent::Singleton cleans up the ManagementAgent
// instance if there are no ManagementAgent::Singleton's in
// scope!
ManagementAgent::Singleton *singleton;
typedef HashTable<AdNameHashKey, SlotObject *> SlotHashTable;
SlotHashTable *startdAds;
typedef HashTable<AdNameHashKey, NegotiatorObject *> NegotiatorHashTable;
// Why when there should be only one? Because the CollectorEngine does.
NegotiatorHashTable *negotiatorAds;
typedef HashTable<AdNameHashKey, SchedulerObject *> SchedulerHashTable;
SchedulerHashTable *schedulerAds;
typedef HashTable<AdNameHashKey, GridObject *> GridHashTable;
GridHashTable *gridAds;
CollectorObject *collector;
void
initialize()
{
char *host;
char* username;
char* password;
char* mechanism;
int port;
char *tmp;
string storefile;
string collName;
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Initializing...\n");
singleton = new ManagementAgent::Singleton();
startdAds = new SlotHashTable(4096, &adNameHashFunction);
negotiatorAds = new NegotiatorHashTable(3, &adNameHashFunction);
schedulerAds = new SchedulerHashTable(128, &adNameHashFunction);
gridAds = new GridHashTable(4096, &adNameHashFunction);
ManagementAgent *agent = singleton->getInstance();
Slot::registerSelf(agent);
Negotiator::registerSelf(agent);
Scheduler::registerSelf(agent);
Grid::registerSelf(agent);
Collector::registerSelf(agent);
port = param_integer("QMF_BROKER_PORT", 5672);
if (NULL == (host = param("QMF_BROKER_HOST"))) {
host = strdup("localhost");
}
tmp = param("QMF_STOREFILE");
if (NULL == tmp) {
storefile = ".collector_storefile";
} else {
storefile = tmp;
free(tmp); tmp = NULL;
}
if (NULL == (username = param("QMF_BROKER_USERNAME")))
{
username = strdup("");
}
if (NULL == (mechanism = param("QMF_BROKER_AUTH_MECH")))
{
mechanism = strdup("ANONYMOUS");
}
password = getBrokerPassword();
tmp = param("COLLECTOR_NAME");
if (NULL == tmp) {
collName = GetPoolName();
} else {
collName = tmp;
free(tmp); tmp = NULL;
}
agent->setName("com.redhat.grid","collector",collName.c_str());
agent->init(string(host), port,
param_integer("QMF_UPDATE_INTERVAL", 10),
true,
storefile,
username,
password,
mechanism);
free(host);
free(username);
free(password);
free(mechanism);
collector = new CollectorObject(agent, collName.c_str());
/* disable for now
ReliSock *sock = new ReliSock;
if (!sock) {
EXCEPT("Failed to allocate Mgmt socket");
}
if (!sock->assign(agent->getSignalFd())) {
EXCEPT("Failed to bind Mgmt socket");
}
int index;
if (-1 == (index =
daemonCore->Register_Socket((Stream *) sock,
"Mgmt Method Socket",
(SocketHandlercpp)
&MgmtCollectorPlugin::HandleMgmtSocket,
"Handler for Mgmt Methods.",
this))) {
EXCEPT("Failed to register Mgmt socket");
}
*/
}
void invalidate_all() {
startdAds->clear();
negotiatorAds->clear();
schedulerAds->clear();
gridAds->clear();
}
void
shutdown()
{
if (!param_boolean("QMF_DELETE_ON_SHUTDOWN", true)) {
return;
}
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: shutting down...\n");
// clean up our objects here and
// for the remote console
invalidate_all();
if (collector) {
// delete from the agent
delete collector;
collector = NULL;
}
if (singleton) {
delete singleton;
singleton = NULL;
}
}
void
update(int command, const ClassAd &ad)
{
MyString name;
AdNameHashKey hashKey;
SlotObject *slotObject;
NegotiatorObject *negotiatorObject;
SchedulerObject *schedulerObject;
GridObject *gridObject;
switch (command) {
case UPDATE_STARTD_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_STARTD_AD\n");
if (param_boolean("QMF_IGNORE_UPDATE_STARTD_AD", true)) {
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Configured to ignore UPDATE_STARTD_AD\n");
break;
}
if (!makeStartdAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
if (startdAds->lookup(hashKey, slotObject)) {
// Key doesn't exist
slotObject = new SlotObject(singleton->getInstance(),
hashKey.name.Value());
// Ignore old value, if it existed (returned)
startdAds->insert(hashKey, slotObject);
}
slotObject->update(ad);
break;
case UPDATE_NEGOTIATOR_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_NEGOTIATOR_AD\n");
if (param_boolean("QMF_IGNORE_UPDATE_NEGOTIATOR_AD", true)) {
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Configured to ignore UPDATE_NEGOTIATOR_AD\n");
break;
}
if (!makeNegotiatorAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
if (negotiatorAds->lookup(hashKey, negotiatorObject)) {
// Key doesn't exist
if (!ad.LookupString(ATTR_NAME, name)) {
name = "UNKNOWN";
}
name.sprintf("Negotiator: %s", hashKey.name.Value());
negotiatorObject =
new NegotiatorObject(singleton->getInstance(),
name.Value());
// Ignore old value, if it existed (returned)
negotiatorAds->insert(hashKey, negotiatorObject);
}
negotiatorObject->update(ad);
break;
case UPDATE_SCHEDD_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_SCHEDD_AD\n");
if (param_boolean("QMF_IGNORE_UPDATE_SCHEDD_AD", true)) {
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Configured to ignore UPDATE_SCHEDD_AD\n");
break;
}
if (!makeScheddAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
// The JobServer constructs a ref to the Scheduler
// based on this Schedd's name, thus we must construct
// the Scheduler's id in the same way or a disconnect
// will occur.
if (!ad.LookupString(ATTR_NAME, name)) {
name = "UNKNOWN";
}
if (schedulerAds->lookup(hashKey, schedulerObject)) {
// Key doesn't exist
schedulerObject =
new SchedulerObject(singleton->getInstance(),
name.Value());
// Ignore old value, if it existed (returned)
schedulerAds->insert(hashKey, schedulerObject);
}
schedulerObject->update(ad);
break;
case UPDATE_GRID_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_GRID_AD\n");
if (!makeGridAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
if (gridAds->lookup(hashKey, gridObject)) {
// Key doesn't exist
gridObject = new GridObject(singleton->getInstance(), hashKey.name.Value());
// Ignore old value, if it existed (returned)
gridAds->insert(hashKey, gridObject);
}
gridObject->update(ad);
break;
case UPDATE_COLLECTOR_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_COLLECTOR_AD\n");
// We could receive collector ads from many
// collectors, but we only maintain our own. So,
// ignore all others.
char *str;
if (ad.LookupString(ATTR_MY_ADDRESS, &str)) {
string public_addr(str);
free(str);
if (((Collector *)collector->GetManagementObject())->get_MyAddress() == public_addr) {
collector->update(ad);
}
}
break;
default:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Unsupported command: %s\n",
getCollectorCommandString(command));
}
}
void
invalidate(int command, const ClassAd &ad)
{
AdNameHashKey hashKey;
SlotObject *slotObject;
NegotiatorObject *negotaitorObject;
SchedulerObject *schedulerObject;
GridObject *gridObject;
switch (command) {
case INVALIDATE_STARTD_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_STARTD_ADS\n");
if (!makeStartdAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == startdAds->lookup(hashKey, slotObject)) {
startdAds->remove(hashKey);
delete slotObject;
}
else {
dprintf(D_FULLDEBUG, "%s startd key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_NEGOTIATOR_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_NEGOTIATOR_ADS\n");
if (!makeNegotiatorAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == negotiatorAds->lookup(hashKey, negotaitorObject)) {
negotiatorAds->remove(hashKey);
delete negotaitorObject;
}
else {
dprintf(D_FULLDEBUG, "%s negotiator key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_SCHEDD_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_SCHEDD_ADS\n");
if (!makeScheddAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == schedulerAds->lookup(hashKey, schedulerObject)) {
schedulerAds->remove(hashKey);
delete schedulerObject;
}
else {
dprintf(D_FULLDEBUG, "%s scheduler key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_GRID_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_GRID_ADS\n");
if (!makeGridAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == gridAds->lookup(hashKey, gridObject)) {
gridAds->remove(hashKey);
delete gridObject;
}
else {
dprintf(D_FULLDEBUG, "%s grid key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_COLLECTOR_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_COLLECTOR_ADS\n");
break;
default:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Unsupported command: %s\n",
getCollectorCommandString(command));
}
}
/* disable for now
int
HandleMgmtSocket(Service *, Stream *)
{
singleton->getInstance()->pollCallbacks();
return KEEP_STREAM;
}
*/
};
static MgmtCollectorPlugin instance;
<commit_msg>Re-enabled QMF method dispatch in Collector, allows r/o objects to respond to method requests with NOT_IMPLEMENTED<commit_after>/*
* Copyright 2009-2011 Red Hat, 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 "condor_common.h"
#include "../condor_collector.V6/CollectorPlugin.h"
#include "hashkey.h"
#include "../condor_collector.V6/collector.h"
#include "../condor_daemon_core.V6/condor_daemon_core.h"
#include "condor_config.h"
#include "SlotObject.h"
#include "NegotiatorObject.h"
#include "SchedulerObject.h"
#include "CollectorObject.h"
#include "GridObject.h"
#include "PoolUtils.h"
#include "broker_utils.h"
//extern DaemonCore *daemonCore;
using namespace std;
using namespace com::redhat::grid;
struct MgmtCollectorPlugin : public Service, CollectorPlugin
{
// ManagementAgent::Singleton cleans up the ManagementAgent
// instance if there are no ManagementAgent::Singleton's in
// scope!
ManagementAgent::Singleton *singleton;
typedef HashTable<AdNameHashKey, SlotObject *> SlotHashTable;
SlotHashTable *startdAds;
typedef HashTable<AdNameHashKey, NegotiatorObject *> NegotiatorHashTable;
// Why when there should be only one? Because the CollectorEngine does.
NegotiatorHashTable *negotiatorAds;
typedef HashTable<AdNameHashKey, SchedulerObject *> SchedulerHashTable;
SchedulerHashTable *schedulerAds;
typedef HashTable<AdNameHashKey, GridObject *> GridHashTable;
GridHashTable *gridAds;
CollectorObject *collector;
void
initialize()
{
char *host;
char* username;
char* password;
char* mechanism;
int port;
char *tmp;
string storefile;
string collName;
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Initializing...\n");
singleton = new ManagementAgent::Singleton();
startdAds = new SlotHashTable(4096, &adNameHashFunction);
negotiatorAds = new NegotiatorHashTable(3, &adNameHashFunction);
schedulerAds = new SchedulerHashTable(128, &adNameHashFunction);
gridAds = new GridHashTable(4096, &adNameHashFunction);
ManagementAgent *agent = singleton->getInstance();
Slot::registerSelf(agent);
Negotiator::registerSelf(agent);
Scheduler::registerSelf(agent);
Grid::registerSelf(agent);
Collector::registerSelf(agent);
port = param_integer("QMF_BROKER_PORT", 5672);
if (NULL == (host = param("QMF_BROKER_HOST"))) {
host = strdup("localhost");
}
tmp = param("QMF_STOREFILE");
if (NULL == tmp) {
storefile = ".collector_storefile";
} else {
storefile = tmp;
free(tmp); tmp = NULL;
}
if (NULL == (username = param("QMF_BROKER_USERNAME")))
{
username = strdup("");
}
if (NULL == (mechanism = param("QMF_BROKER_AUTH_MECH")))
{
mechanism = strdup("ANONYMOUS");
}
password = getBrokerPassword();
tmp = param("COLLECTOR_NAME");
if (NULL == tmp) {
collName = GetPoolName();
} else {
collName = tmp;
free(tmp); tmp = NULL;
}
agent->setName("com.redhat.grid","collector",collName.c_str());
agent->init(string(host), port,
param_integer("QMF_UPDATE_INTERVAL", 10),
true,
storefile,
username,
password,
mechanism);
free(host);
free(username);
free(password);
free(mechanism);
collector = new CollectorObject(agent, collName.c_str());
ReliSock *sock = new ReliSock;
if (!sock) {
EXCEPT("Failed to allocate Mgmt socket");
}
if (!sock->assign(agent->getSignalFd())) {
EXCEPT("Failed to bind Mgmt socket");
}
int index;
if (-1 == (index =
daemonCore->Register_Socket((Stream *) sock,
"Mgmt Method Socket",
(SocketHandlercpp)
&MgmtCollectorPlugin::HandleMgmtSocket,
"Handler for Mgmt Methods.",
this))) {
EXCEPT("Failed to register Mgmt socket");
}
}
void invalidate_all() {
startdAds->clear();
negotiatorAds->clear();
schedulerAds->clear();
gridAds->clear();
}
void
shutdown()
{
if (!param_boolean("QMF_DELETE_ON_SHUTDOWN", true)) {
return;
}
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: shutting down...\n");
// clean up our objects here and
// for the remote console
invalidate_all();
if (collector) {
// delete from the agent
delete collector;
collector = NULL;
}
if (singleton) {
delete singleton;
singleton = NULL;
}
}
void
update(int command, const ClassAd &ad)
{
MyString name;
AdNameHashKey hashKey;
SlotObject *slotObject;
NegotiatorObject *negotiatorObject;
SchedulerObject *schedulerObject;
GridObject *gridObject;
switch (command) {
case UPDATE_STARTD_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_STARTD_AD\n");
if (param_boolean("QMF_IGNORE_UPDATE_STARTD_AD", true)) {
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Configured to ignore UPDATE_STARTD_AD\n");
break;
}
if (!makeStartdAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
if (startdAds->lookup(hashKey, slotObject)) {
// Key doesn't exist
slotObject = new SlotObject(singleton->getInstance(),
hashKey.name.Value());
// Ignore old value, if it existed (returned)
startdAds->insert(hashKey, slotObject);
}
slotObject->update(ad);
break;
case UPDATE_NEGOTIATOR_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_NEGOTIATOR_AD\n");
if (param_boolean("QMF_IGNORE_UPDATE_NEGOTIATOR_AD", true)) {
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Configured to ignore UPDATE_NEGOTIATOR_AD\n");
break;
}
if (!makeNegotiatorAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
if (negotiatorAds->lookup(hashKey, negotiatorObject)) {
// Key doesn't exist
if (!ad.LookupString(ATTR_NAME, name)) {
name = "UNKNOWN";
}
name.sprintf("Negotiator: %s", hashKey.name.Value());
negotiatorObject =
new NegotiatorObject(singleton->getInstance(),
name.Value());
// Ignore old value, if it existed (returned)
negotiatorAds->insert(hashKey, negotiatorObject);
}
negotiatorObject->update(ad);
break;
case UPDATE_SCHEDD_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_SCHEDD_AD\n");
if (param_boolean("QMF_IGNORE_UPDATE_SCHEDD_AD", true)) {
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Configured to ignore UPDATE_SCHEDD_AD\n");
break;
}
if (!makeScheddAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
// The JobServer constructs a ref to the Scheduler
// based on this Schedd's name, thus we must construct
// the Scheduler's id in the same way or a disconnect
// will occur.
if (!ad.LookupString(ATTR_NAME, name)) {
name = "UNKNOWN";
}
if (schedulerAds->lookup(hashKey, schedulerObject)) {
// Key doesn't exist
schedulerObject =
new SchedulerObject(singleton->getInstance(),
name.Value());
// Ignore old value, if it existed (returned)
schedulerAds->insert(hashKey, schedulerObject);
}
schedulerObject->update(ad);
break;
case UPDATE_GRID_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_GRID_AD\n");
if (!makeGridAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
}
if (gridAds->lookup(hashKey, gridObject)) {
// Key doesn't exist
gridObject = new GridObject(singleton->getInstance(), hashKey.name.Value());
// Ignore old value, if it existed (returned)
gridAds->insert(hashKey, gridObject);
}
gridObject->update(ad);
break;
case UPDATE_COLLECTOR_AD:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received UPDATE_COLLECTOR_AD\n");
// We could receive collector ads from many
// collectors, but we only maintain our own. So,
// ignore all others.
char *str;
if (ad.LookupString(ATTR_MY_ADDRESS, &str)) {
string public_addr(str);
free(str);
if (((Collector *)collector->GetManagementObject())->get_MyAddress() == public_addr) {
collector->update(ad);
}
}
break;
default:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Unsupported command: %s\n",
getCollectorCommandString(command));
}
}
void
invalidate(int command, const ClassAd &ad)
{
AdNameHashKey hashKey;
SlotObject *slotObject;
NegotiatorObject *negotaitorObject;
SchedulerObject *schedulerObject;
GridObject *gridObject;
switch (command) {
case INVALIDATE_STARTD_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_STARTD_ADS\n");
if (!makeStartdAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == startdAds->lookup(hashKey, slotObject)) {
startdAds->remove(hashKey);
delete slotObject;
}
else {
dprintf(D_FULLDEBUG, "%s startd key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_NEGOTIATOR_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_NEGOTIATOR_ADS\n");
if (!makeNegotiatorAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == negotiatorAds->lookup(hashKey, negotaitorObject)) {
negotiatorAds->remove(hashKey);
delete negotaitorObject;
}
else {
dprintf(D_FULLDEBUG, "%s negotiator key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_SCHEDD_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_SCHEDD_ADS\n");
if (!makeScheddAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == schedulerAds->lookup(hashKey, schedulerObject)) {
schedulerAds->remove(hashKey);
delete schedulerObject;
}
else {
dprintf(D_FULLDEBUG, "%s scheduler key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_GRID_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_GRID_ADS\n");
if (!makeGridAdHashKey(hashKey, ((ClassAd *) &ad), NULL)) {
dprintf(D_FULLDEBUG, "Could not make hashkey -- ignoring ad\n");
return;
}
if (0 == gridAds->lookup(hashKey, gridObject)) {
gridAds->remove(hashKey);
delete gridObject;
}
else {
dprintf(D_FULLDEBUG, "%s grid key not found for removal\n",HashString(hashKey).Value());
}
break;
case INVALIDATE_COLLECTOR_ADS:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Received INVALIDATE_COLLECTOR_ADS\n");
break;
default:
dprintf(D_FULLDEBUG, "MgmtCollectorPlugin: Unsupported command: %s\n",
getCollectorCommandString(command));
}
}
int
HandleMgmtSocket(Service *, Stream *)
{
singleton->getInstance()->pollCallbacks();
return KEEP_STREAM;
}
};
static MgmtCollectorPlugin instance;
<|endoftext|> |
<commit_before>#ifndef EBITEN_GAME_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP
#define EBITEN_GAME_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP
#include "ebiten/game/graphics/detail/opengl/device.hpp"
#include "ebiten/game/graphics/color_matrix.hpp"
#include "ebiten/game/graphics/drawing_region.hpp"
#include "ebiten/game/graphics/geometry_matrix.hpp"
#include "ebiten/game/graphics/texture.hpp"
#include <OpenGL/gl.h>
#include <boost/noncopyable.hpp>
#include <boost/range.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>
#include <array>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <type_traits>
namespace ebiten {
namespace game {
namespace graphics {
namespace detail {
class graphics_context : private boost::noncopyable {
friend class device;
private:
GLuint shader_program;
private:
graphics_context()
: shader_program(0) {
}
public:
template<class DrawingRegions>
void
draw_textures(graphics::texture const& texture,
DrawingRegions const& drawing_regions,
graphics::geometry_matrix const& geo_mat,
int z,
graphics::color_matrix const& color_mat) {
BOOST_STATIC_ASSERT((std::is_same<typename boost::range_value<DrawingRegions>::type,
drawing_region>::value));
if (!this->shader_program) {
this->shader_program = compile_shader_program();
assert(this->shader_program);
}
if (!color_mat.is_identity()) {
::glUseProgram(this->shader_program);
::glUniform1i(glGetUniformLocation(this->shader_program, "texture"), 0);
float const gl_color_mat[] = {
static_cast<float>(color_mat.element<0, 0>()),
static_cast<float>(color_mat.element<0, 1>()),
static_cast<float>(color_mat.element<0, 2>()),
static_cast<float>(color_mat.element<0, 3>()),
static_cast<float>(color_mat.element<1, 0>()),
static_cast<float>(color_mat.element<1, 1>()),
static_cast<float>(color_mat.element<1, 2>()),
static_cast<float>(color_mat.element<1, 3>()),
static_cast<float>(color_mat.element<2, 0>()),
static_cast<float>(color_mat.element<2, 1>()),
static_cast<float>(color_mat.element<2, 2>()),
static_cast<float>(color_mat.element<2, 3>()),
static_cast<float>(color_mat.element<3, 0>()),
static_cast<float>(color_mat.element<3, 1>()),
static_cast<float>(color_mat.element<3, 2>()),
static_cast<float>(color_mat.element<3, 3>()),
};
::glUniformMatrix4fv(glGetUniformLocation(this->shader_program, "color_matrix"),
1, GL_FALSE, gl_color_mat);
float const gl_color_mat_translation[] = {
static_cast<float>(color_mat.element<0, 4>()),
static_cast<float>(color_mat.element<1, 4>()),
static_cast<float>(color_mat.element<2, 4>()),
static_cast<float>(color_mat.element<3, 4>()),
};
::glUniform4fv(glGetUniformLocation(this->shader_program, "color_matrix_translation"),
4, gl_color_mat_translation);
}
float const gl_geo_mat[] = {geo_mat.a(), geo_mat.c(), 0, 0,
geo_mat.b(), geo_mat.d(), 0, 0,
0, 0, 1, 0,
geo_mat.tx(), geo_mat.ty(), 0, 1};
::glMatrixMode(GL_MODELVIEW);
::glLoadMatrixf(gl_geo_mat);
::glBindTexture(GL_TEXTURE_2D, texture.id());
::glBegin(GL_QUADS);
float const zf = static_cast<float>(z);
float const texture_width = texture.texture_width();
float const texture_height = texture.texture_height();
for (auto const& dr : drawing_regions) {
float const tu1 = dr.src_x() / texture_width;
float const tu2 = (dr.src_x() + dr.width()) / texture_width;
float const tv1 = dr.src_y() / texture_height;
float const tv2 = (dr.src_y() + dr.height()) / texture_height;
float const x1 = dr.dst_x();
float const x2 = dr.dst_x() + dr.width();
float const y1 = dr.dst_y();
float const y2 = dr.dst_y() + dr.height();
float const vertex[4][3] = {{x1, y1, zf},
{x2, y1, zf},
{x2, y2, zf},
{x1, y2, zf}};
// TODO: use glDrawArrays?
::glTexCoord2f(tu1, tv1);
::glVertex3fv(vertex[0]);
::glTexCoord2f(tu2, tv1);
::glVertex3fv(vertex[1]);
::glTexCoord2f(tu2, tv2);
::glVertex3fv(vertex[2]);
::glTexCoord2f(tu1, tv2);
::glVertex3fv(vertex[3]);
};
::glEnd();
::glBindTexture(GL_TEXTURE_2D, 0);
::glUseProgram(0);
}
private:
GLuint
compile_shader_program() {
static std::string const sharder_source("uniform sampler2D texture;\n"
"uniform mat4 color_matrix;\n"
"uniform vec4 color_matrix_translation;\n"
"\n"
"void main(void) {\n"
" vec4 color = texture2DProj(texture, gl_TexCoord[0]);\n"
" gl_FragColor = color_matrix * color + color_matrix_translation;\n"
"}\n");
// TODO: ARB?
GLuint fragment_shader;
fragment_shader = ::glCreateShader(GL_FRAGMENT_SHADER);
assert(fragment_shader);
char const* shader_source_p = sharder_source.c_str();
::glShaderSource(fragment_shader, 1, &shader_source_p, 0);
::glCompileShader(fragment_shader);
// check status
GLint compiled;
::glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &compiled);
this->show_shader_log(fragment_shader);
if (compiled == GL_FALSE) {
throw std::runtime_error("shader compile error");
}
GLuint program;
program = ::glCreateProgram();
assert(program);
::glAttachShader(program, fragment_shader);
::glDeleteShader(fragment_shader);
::glLinkProgram(program);
// check status
GLint linked;
::glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (linked == GL_FALSE) {
throw std::runtime_error("program error");
}
return program;
}
// TODO: Debug Mode
void
show_shader_log(GLuint shader) {
int log_size = 0;
::glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_size);
if (log_size) {
int length = 0;
// TODO: 動的確保のほうがよい?
std::array<char, 1024> buffer;
// TODO: バッファ確認
::glGetShaderInfoLog(shader, buffer.size(), &length, buffer.data());
std::cerr << buffer.data() << std::endl;
}
}
// TODO: show_program_log
};
}
}
}
}
#endif
<commit_msg>Removed an extra macro<commit_after>#ifndef EBITEN_GAME_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP
#define EBITEN_GAME_GRAPHICS_DETAIL_OPENGL_GRAPHICS_CONTEXT_HPP
#include "ebiten/game/graphics/detail/opengl/device.hpp"
#include "ebiten/game/graphics/color_matrix.hpp"
#include "ebiten/game/graphics/drawing_region.hpp"
#include "ebiten/game/graphics/geometry_matrix.hpp"
#include "ebiten/game/graphics/texture.hpp"
#include <OpenGL/gl.h>
#include <boost/noncopyable.hpp>
#include <boost/range.hpp>
#include <boost/static_assert.hpp>
#include <array>
#include <algorithm>
#include <cassert>
#include <iostream>
#include <type_traits>
namespace ebiten {
namespace game {
namespace graphics {
namespace detail {
class graphics_context : private boost::noncopyable {
friend class device;
private:
GLuint shader_program;
private:
graphics_context()
: shader_program(0) {
}
public:
template<class DrawingRegions>
void
draw_textures(graphics::texture const& texture,
DrawingRegions const& drawing_regions,
graphics::geometry_matrix const& geo_mat,
int z,
graphics::color_matrix const& color_mat) {
BOOST_STATIC_ASSERT((std::is_same<typename boost::range_value<DrawingRegions>::type,
drawing_region>::value));
if (!this->shader_program) {
this->shader_program = compile_shader_program();
assert(this->shader_program);
}
if (!color_mat.is_identity()) {
::glUseProgram(this->shader_program);
::glUniform1i(glGetUniformLocation(this->shader_program, "texture"), 0);
float const gl_color_mat[] = {
static_cast<float>(color_mat.element<0, 0>()),
static_cast<float>(color_mat.element<0, 1>()),
static_cast<float>(color_mat.element<0, 2>()),
static_cast<float>(color_mat.element<0, 3>()),
static_cast<float>(color_mat.element<1, 0>()),
static_cast<float>(color_mat.element<1, 1>()),
static_cast<float>(color_mat.element<1, 2>()),
static_cast<float>(color_mat.element<1, 3>()),
static_cast<float>(color_mat.element<2, 0>()),
static_cast<float>(color_mat.element<2, 1>()),
static_cast<float>(color_mat.element<2, 2>()),
static_cast<float>(color_mat.element<2, 3>()),
static_cast<float>(color_mat.element<3, 0>()),
static_cast<float>(color_mat.element<3, 1>()),
static_cast<float>(color_mat.element<3, 2>()),
static_cast<float>(color_mat.element<3, 3>()),
};
::glUniformMatrix4fv(glGetUniformLocation(this->shader_program, "color_matrix"),
1, GL_FALSE, gl_color_mat);
float const gl_color_mat_translation[] = {
static_cast<float>(color_mat.element<0, 4>()),
static_cast<float>(color_mat.element<1, 4>()),
static_cast<float>(color_mat.element<2, 4>()),
static_cast<float>(color_mat.element<3, 4>()),
};
::glUniform4fv(glGetUniformLocation(this->shader_program, "color_matrix_translation"),
4, gl_color_mat_translation);
}
float const gl_geo_mat[] = {geo_mat.a(), geo_mat.c(), 0, 0,
geo_mat.b(), geo_mat.d(), 0, 0,
0, 0, 1, 0,
geo_mat.tx(), geo_mat.ty(), 0, 1};
::glMatrixMode(GL_MODELVIEW);
::glLoadMatrixf(gl_geo_mat);
::glBindTexture(GL_TEXTURE_2D, texture.id());
::glBegin(GL_QUADS);
float const zf = static_cast<float>(z);
float const texture_width = texture.texture_width();
float const texture_height = texture.texture_height();
for (auto const& dr : drawing_regions) {
float const tu1 = dr.src_x() / texture_width;
float const tu2 = (dr.src_x() + dr.width()) / texture_width;
float const tv1 = dr.src_y() / texture_height;
float const tv2 = (dr.src_y() + dr.height()) / texture_height;
float const x1 = dr.dst_x();
float const x2 = dr.dst_x() + dr.width();
float const y1 = dr.dst_y();
float const y2 = dr.dst_y() + dr.height();
float const vertex[4][3] = {{x1, y1, zf},
{x2, y1, zf},
{x2, y2, zf},
{x1, y2, zf}};
// TODO: use glDrawArrays?
::glTexCoord2f(tu1, tv1);
::glVertex3fv(vertex[0]);
::glTexCoord2f(tu2, tv1);
::glVertex3fv(vertex[1]);
::glTexCoord2f(tu2, tv2);
::glVertex3fv(vertex[2]);
::glTexCoord2f(tu1, tv2);
::glVertex3fv(vertex[3]);
};
::glEnd();
::glBindTexture(GL_TEXTURE_2D, 0);
::glUseProgram(0);
}
private:
GLuint
compile_shader_program() {
static std::string const sharder_source("uniform sampler2D texture;\n"
"uniform mat4 color_matrix;\n"
"uniform vec4 color_matrix_translation;\n"
"\n"
"void main(void) {\n"
" vec4 color = texture2DProj(texture, gl_TexCoord[0]);\n"
" gl_FragColor = color_matrix * color + color_matrix_translation;\n"
"}\n");
// TODO: ARB?
GLuint fragment_shader;
fragment_shader = ::glCreateShader(GL_FRAGMENT_SHADER);
assert(fragment_shader);
char const* shader_source_p = sharder_source.c_str();
::glShaderSource(fragment_shader, 1, &shader_source_p, 0);
::glCompileShader(fragment_shader);
// check status
GLint compiled;
::glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &compiled);
this->show_shader_log(fragment_shader);
if (compiled == GL_FALSE) {
throw std::runtime_error("shader compile error");
}
GLuint program;
program = ::glCreateProgram();
assert(program);
::glAttachShader(program, fragment_shader);
::glDeleteShader(fragment_shader);
::glLinkProgram(program);
// check status
GLint linked;
::glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (linked == GL_FALSE) {
throw std::runtime_error("program error");
}
return program;
}
// TODO: Debug Mode
void
show_shader_log(GLuint shader) {
int log_size = 0;
::glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_size);
if (log_size) {
int length = 0;
// TODO: 動的確保のほうがよい?
std::array<char, 1024> buffer;
// TODO: バッファ確認
::glGetShaderInfoLog(shader, buffer.size(), &length, buffer.data());
std::cerr << buffer.data() << std::endl;
}
}
// TODO: show_program_log
};
}
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "caffe2/operators/pack_segments.h"
namespace caffe2 {
namespace {
REGISTER_CPU_OPERATOR(PackSegments, PackSegmentsOp<CPUContext>);
REGISTER_CPU_OPERATOR(UnpackSegments, UnpackSegmentsOp<CPUContext>);
OPERATOR_SCHEMA(PackSegments)
.NumInputs(2)
.NumOutputs(1)
.SetDoc(
"Map N dim tensor to N+1 dim based on length blob. Sequences that \
are shorter than the longest sequence are padded with zeros.")
.Input(
0,
"lengths",
"1-d int/long tensor contains the length in each of the output.")
.Input(1, "tensor", "N dim Tensor.")
.Output(
0,
"packed_tensor",
"N + 1 dim Tesor"
"where dim(1) is the max length"
", dim(0) is the batch size.")
.Arg(
"pad_minf", "Padding number in the packed segments. Use true to pad \
-infinity, otherwise pad zeros");
OPERATOR_SCHEMA(UnpackSegments)
.NumInputs(2)
.NumOutputs(1)
.SetDoc("Map N+1 dim tensor to N dim based on length blob")
.Input(
0,
"lengths",
"1-d int/long tensor contains the length in each of the input.")
.Input(1, "tensor", "N+1 dim Tensor.")
.Output(0, "packed_tensor", "N dim Tesor");
class GetPackSegmentsGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"UnpackSegments",
"",
vector<string>{I(0), GO(0)},
vector<string>{GI(1)},
Def().arg());
}
};
REGISTER_GRADIENT(PackSegments, GetPackSegmentsGradient);
class GetUnpackSegmentsGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"PackSegments",
"",
vector<string>{I(0), GO(0)},
vector<string>{GI(1)},
Def().arg());
}
};
REGISTER_GRADIENT(UnpackSegments, GetUnpackSegmentsGradient);
}
} // namespace
<commit_msg>Fix packsegments op and text RNN models batchsize > 0<commit_after>#include "caffe2/operators/pack_segments.h"
namespace caffe2 {
namespace {
REGISTER_CPU_OPERATOR(PackSegments, PackSegmentsOp<CPUContext>);
REGISTER_CPU_OPERATOR(UnpackSegments, UnpackSegmentsOp<CPUContext>);
OPERATOR_SCHEMA(PackSegments)
.NumInputs(2)
.NumOutputs(1)
.SetDoc(
"Map N dim tensor to N+1 dim based on length blob. Sequences that \
are shorter than the longest sequence are padded with zeros.")
.Input(
0,
"lengths",
"1-d int/long tensor contains the length in each of the output.")
.Input(1, "tensor", "N dim Tensor.")
.Output(
0,
"packed_tensor",
"N + 1 dim Tesor"
"where dim(1) is the max length"
", dim(0) is the batch size.")
.Arg(
"pad_minf", "Padding number in the packed segments. Use true to pad \
-infinity, otherwise pad zeros");
OPERATOR_SCHEMA(UnpackSegments)
.NumInputs(2)
.NumOutputs(1)
.SetDoc("Map N+1 dim tensor to N dim based on length blob")
.Input(
0,
"lengths",
"1-d int/long tensor contains the length in each of the input.")
.Input(1, "tensor", "N+1 dim Tensor.")
.Output(0, "packed_tensor", "N dim Tesor");
class GetPackSegmentsGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"UnpackSegments",
"",
vector<string>{I(0), GO(0)},
vector<string>{GI(1)});
}
};
REGISTER_GRADIENT(PackSegments, GetPackSegmentsGradient);
class GetUnpackSegmentsGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"PackSegments", "", vector<string>{I(0), GO(0)}, vector<string>{GI(1)});
}
};
REGISTER_GRADIENT(UnpackSegments, GetUnpackSegmentsGradient);
}
} // namespace
<|endoftext|> |
<commit_before>#include "caffe2/operators/reduction_ops.h"
namespace caffe2 {
namespace {
REGISTER_CPU_OPERATOR(SumElements, SumElementsOp<float, CPUContext>);
REGISTER_CPU_OPERATOR(SumSqrElements, SumSqrElementsOp<float, CPUContext>);
REGISTER_CPU_OPERATOR(
SumElementsGradient,
SumElementsGradientOp<float, CPUContext>);
OPERATOR_SCHEMA(SumElements)
.NumInputs(1)
.NumOutputs(1)
.ScalarType(TensorProto::FLOAT)
.SetDoc("Sums the elements of the input tensor.")
.Arg("average", "whether to average or not")
.Input(0, "X", "Tensor to sum up")
.Output(0, "sum", "Scalar sum");
OPERATOR_SCHEMA(SumSqrElements)
.NumInputs(1)
.NumOutputs(1)
.ScalarType(TensorProto::FLOAT)
.SetDoc("Sums the squares elements of the input tensor.")
.Arg("average", "whether to average or not")
.Input(0, "X", "Tensor to sum up")
.Output(0, "sum", "Scalar sum of squares");
class GetSumElementsGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"SumElementsGradient",
"",
vector<string>{I(0), GO(0)},
vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(SumElements, GetSumElementsGradient);
} // namespace
template <typename T, class Context>
bool SumElementsGradientOp<T, Context>::RunOnDevice() {
auto& X = Input(0);
TensorCPU sum_grad = TensorCPU(Input(1));
auto* dX = Output(0);
dX->ResizeLike(X);
DCHECK_EQ(sum_grad.size(), 1);
math::Set<T, Context>(
dX->size(),
static_cast<T>(sum_grad.data<T>()[0] * (average_ ? 1.0 / X.size() : 1)),
dX->template mutable_data<T>(),
&context_);
return true;
}
} // namespace caffe2
<commit_msg>Caffe2: add schema for SumElementsGradient<commit_after>#include "caffe2/operators/reduction_ops.h"
namespace caffe2 {
namespace {
REGISTER_CPU_OPERATOR(SumElements, SumElementsOp<float, CPUContext>);
REGISTER_CPU_OPERATOR(SumSqrElements, SumSqrElementsOp<float, CPUContext>);
REGISTER_CPU_OPERATOR(
SumElementsGradient,
SumElementsGradientOp<float, CPUContext>);
OPERATOR_SCHEMA(SumElements)
.NumInputs(1)
.NumOutputs(1)
.ScalarType(TensorProto::FLOAT)
.SetDoc("Sums the elements of the input tensor.")
.Arg("average", "whether to average or not")
.Input(0, "X", "Tensor to sum up")
.Output(0, "sum", "Scalar sum");
OPERATOR_SCHEMA(SumSqrElements)
.NumInputs(1)
.NumOutputs(1)
.ScalarType(TensorProto::FLOAT)
.SetDoc("Sums the squares elements of the input tensor.")
.Arg("average", "whether to average or not")
.Input(0, "X", "Tensor to sum up")
.Output(0, "sum", "Scalar sum of squares");
OPERATOR_SCHEMA(SumElementsGradient).NumInputs(2).NumOutputs(1);
class GetSumElementsGradient : public GradientMakerBase {
using GradientMakerBase::GradientMakerBase;
vector<OperatorDef> GetGradientDefs() override {
return SingleGradientDef(
"SumElementsGradient",
"",
vector<string>{I(0), GO(0)},
vector<string>{GI(0)});
}
};
REGISTER_GRADIENT(SumElements, GetSumElementsGradient);
} // namespace
template <typename T, class Context>
bool SumElementsGradientOp<T, Context>::RunOnDevice() {
auto& X = Input(0);
TensorCPU sum_grad = TensorCPU(Input(1));
auto* dX = Output(0);
dX->ResizeLike(X);
DCHECK_EQ(sum_grad.size(), 1);
math::Set<T, Context>(
dX->size(),
static_cast<T>(sum_grad.data<T>()[0] * (average_ ? 1.0 / X.size() : 1)),
dX->template mutable_data<T>(),
&context_);
return true;
}
} // namespace caffe2
<|endoftext|> |
<commit_before>/*
* REmbeddedPosix.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <r/RExec.hpp>
#include <core/FilePath.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
// after boost stuff to prevent length (Rf_length) symbol conflict issues
#include "REmbedded.hpp"
#include <r/RInterface.hpp>
#include <r/RErrorCategory.hpp>
#include <r/RUtil.hpp>
#include <R_ext/eventloop.h>
#include <Rembedded.h>
#ifdef __APPLE__
#include <dlfcn.h>
extern "C" void R_ProcessEvents(void);
extern "C" void (*ptr_R_ProcessEvents)(void);
#define QCF_SET_PEPTR 1 /* set ProcessEvents function pointer */
#define QCF_SET_FRONT 2 /* set application mode to front */
extern "C" typedef void (*ptr_QuartzCocoa_SetupEventLoop)(int, unsigned long);
#endif
extern int R_running_as_main_program; // from unix/system.c
using namespace rstudio::core;
namespace rstudio {
namespace r {
namespace session {
void runEmbeddedR(const core::FilePath& /*rHome*/, // ignored on posix
const core::FilePath& /*userHome*/, // ignored on posix
bool quiet,
bool loadInitFile,
SA_TYPE defaultSaveAction,
const Callbacks& callbacks,
InternalCallbacks* pInternal)
{
// disable R signal handlers. see src/main/main.c for the default
// implementations. in our case ignore them for the following reasons:
//
// INT - no concept of Ctrl-C based interruption (use flag directly)
//
// SEGV, ILL, & BUS: unsupported due to prompt invoking networking
// code (unsupported from within a signal handler)
//
// USR1 & USR2: same as above SEGV, etc. + we use them for other purposes
//
// PIPE: we ignore this globally in SessionMain. before doing this we
// confirmed that asio wasn't in some way manipulating it -- on linux
// boost passes MSG_NOSIGNAL to sendmsg and on OSX sets the SO_NOSIGPIPE
// option on all sockets created. note that on other platforms including
// solaris, hpux, etc. boost uses detail/signal_init to ignore SIGPIPE
// globally (this is done in io_service.hpp).
R_SignalHandlers = 0;
// set message callback early so we can see initialization error messages
ptr_R_ShowMessage = callbacks.showMessage ;
// running as main program (affects location of R_CStackStart on platforms
// without HAVE_LIBC_STACK_END or HAVE_KERN_USRSTACK). see also discussion
// on R_CStackStart in 8.1.5 Threading issues
R_running_as_main_program = 1;
// initialize R
const char *args[]= {"RStudio", "--interactive"};
Rf_initialize_R(sizeof(args)/sizeof(args[0]), (char**)args);
// For newSession = false we need to do a few things:
//
// 1) set R_Quiet so we startup without a banner
//
// 2) set LoadInitFile to supress execution of .Rprofile
//
// 3) we also need to make sure that .First is not executed. this is
// taken care of via the fact that we set RestoreAction to SA_NORESTORE
// which means that when setup_Rmainloop there is no .First function
// available to it because we haven't restored the environment yet.
// Note that .First is executed in the case of new sessions because
// it is read from .Rprofile as part of setup_Rmainloop. This implies
// that in our version of R the .First function must be defined in
// .Rprofile rather than simply saved into the global environment
// of the default workspace
//
structRstart rp;
Rstart Rp = &rp;
R_DefParams(Rp) ;
Rp->R_Slave = FALSE ;
Rp->R_Quiet = quiet ? TRUE : FALSE;
Rp->R_Interactive = TRUE ;
Rp->SaveAction = defaultSaveAction ;
Rp->RestoreAction = SA_NORESTORE; // handled within initialize()
Rp->LoadInitFile = loadInitFile ? TRUE : FALSE;
R_SetParams(Rp) ;
// redirect console
R_Interactive = TRUE; // should have also been set by call to Rf_initialize_R
R_Consolefile = NULL;
R_Outputfile = NULL;
ptr_R_ReadConsole = callbacks.readConsole ;
ptr_R_WriteConsole = NULL; // must set this to NULL for Ex to be called
ptr_R_WriteConsoleEx = callbacks.writeConsoleEx ;
ptr_R_EditFile = callbacks.editFile ;
ptr_R_Busy = callbacks.busy;
// hook messages (in case Rf_initialize_R overwrites previously set hook)
ptr_R_ShowMessage = callbacks.showMessage ;
// hook file handling
ptr_R_ChooseFile = callbacks.chooseFile ;
ptr_R_ShowFiles = callbacks.showFiles ;
// hook history
ptr_R_loadhistory = callbacks.loadhistory;
ptr_R_savehistory = callbacks.savehistory;
ptr_R_addhistory = callbacks.addhistory;
// hook suicide, but save reference to internal suicide so we can forward
pInternal->suicide = ptr_R_Suicide;
ptr_R_Suicide = callbacks.suicide;
// hook clean up, but save reference to internal clean up so can forward
pInternal->cleanUp = ptr_R_CleanUp;
ptr_R_CleanUp = callbacks.cleanUp ;
// NOTE: we do not hook the following callbacks because they are targeted
// at clients that have a stdio-based console
// ptr_R_ResetConsole
// ptr_R_FlushConsole
// ptr_R_ClearerrConsole
// run main loop (does not return)
Rf_mainloop();
}
Error completeEmbeddedRInitialization(bool useInternet2)
{
return Success();
}
namespace event_loop {
namespace {
// currently installed polled event handler
void (*s_polledEventHandler)(void) = NULL;
// previously existing polled event handler
void (*s_oldPolledEventHandler)(void) = NULL;
// function we register with R to implement polled event handler
void polledEventHandler()
{
if (s_polledEventHandler != NULL)
s_polledEventHandler();
if (s_oldPolledEventHandler != NULL)
s_oldPolledEventHandler();
}
#ifdef __APPLE__
void logDLError(const std::string& message, const ErrorLocation& location)
{
std::string errmsg(message);
char* dlError = ::dlerror();
if (dlError)
errmsg += ": " + std::string(dlError);
core::log::logErrorMessage(errmsg, location);
}
// Note that when we passed QCF_SET_FRONT to QuartzCocoa_SetupEventLoop
// sometimes this resulted in our application having a "bouncing"
// state which we couldn't rid ourselves of.
//
// Note that in researching the way R implements QCF_SET_FRONT I discovered
// that a depricated API is called AND an explicit call to SetFront. Another
// way to go would be to call the TransformProcessType API:
//
// http://www.cocoadev.com/index.pl?TransformProcessType
// http://developer.apple.com/library/mac/#documentation/Carbon/Reference/Process_Manager/Reference/reference.html%23//apple_ref/c/func/TransformProcessType
//
// Note this would look something like (cmake and includes for completeness):
/*
find_library(CARBON_LIBRARY NAMES Carbon)
set(LINK_FLAGS ${CARBON_LIBRARY})
#include <Carbon/Carbon.h>
#undef TRUE
#undef FALSE
static const ProcessSerialNumber thePSN = { 0, kCurrentProcess };
::TransformProcessType(&thePSN, kProcessTransformToForegroundApplication);
*/
// attempt to setup quartz event loop, if this fails then log and
// return false (as a result we'll have to disable the quartz R
// function so the user doesn't get in trouble)
bool setupQuartzEventLoop()
{
// first make sure that the gdDevices pacakage is loaded
Error error = r::exec::executeString("library(grDevices)");
if (error)
{
LOG_ERROR(error);
return false;
}
// get a reference to the grDevices library
void* pGrDevices = ::dlopen("grDevices.so",
RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
if (pGrDevices)
{
ptr_QuartzCocoa_SetupEventLoop pSetupEventLoop =
(ptr_QuartzCocoa_SetupEventLoop)::dlsym(
pGrDevices,
"QuartzCocoa_SetupEventLoop");
if (pSetupEventLoop)
{
// attempt to setup event loop
pSetupEventLoop(QCF_SET_PEPTR, 100);
// check that we got the ptr_R_ProcessEvents initialized
if (ptr_R_ProcessEvents != NULL)
{
return true;
}
else
{
LOG_ERROR_MESSAGE("ptr_R_ProcessEvents not initialized");
return false;
}
}
else
{
logDLError("Error looking up QuartzCocoa_SetupEventLoop",
ERROR_LOCATION);
return false;
}
}
else
{
logDLError("Error loading grDevices.so", ERROR_LOCATION);
return false;
}
}
// On versions prior to R 2.12 the event pump is handled by R_ProcessEvents
// rather than by the expected R_PolledEvents mechanism. On the Mac
// R_ProcessEvents includes a hook (ptr_R_ProcessEvents) but this is
// taken by the quartz module. We therefore need a way to hook it but
// still delegate to quartz so the quartz device works. do this by
// ensuring quartz is loaded then calling QuartzCocoa_SetupEventLoop
void installAppleR_2_11_Workaround(void (*newPolledEventHandler)(void))
{
// attempt to initialize the quartz event loop (init ptr_R_ProcessEvents
// so that we can delegate to it after we override it)
if (!setupQuartzEventLoop())
{
Error error = r::exec::RFunction(".rs.disableQuartz").call();
if (error)
LOG_ERROR(error);
}
// copy handler function
s_polledEventHandler = newPolledEventHandler;
// preserve old handler and set new one (note that ptr_R_ProcessEvents
// might be NULL if we didn't succeed in setting up the quartz
// event loop above. in this case the polled event handler will
// ignore it
s_oldPolledEventHandler = ptr_R_ProcessEvents;
ptr_R_ProcessEvents = polledEventHandler;
}
#endif
} // anonymous namespace
void initializePolledEventHandler(void (*newPolledEventHandler)(void))
{
// can only call this once
BOOST_ASSERT(!s_polledEventHandler);
// special hack for R 2.11.1 on OSX
#ifdef __APPLE__
if (!r::util::hasRequiredVersion("2.12"))
{
installAppleR_2_11_Workaround(newPolledEventHandler);
return;
}
#endif
// implementation based on addTcl() in tcltk_unix.c
// copy handler function
s_polledEventHandler = newPolledEventHandler;
// preserve old handler and set new one
s_oldPolledEventHandler = R_PolledEvents;
R_PolledEvents = polledEventHandler;
}
// NOTE: this call is used in child process after multicore forks
// to make sure all subsequent R code is executed without any
// event handlers (appropriate since the forked child is headless).
// the prefix "permanently" is used because we explicitly don't
// handle the abilty to restore event handling by calling
// initializePolledEventHandler -- this is because we overwrite
// s_oldPolledEventHandler with NULL, thus losing any reference
// we have to a R_PolledEvents value that existed before our
// initialization (it would be possible to implement a temporary
// disable with a bit more complex control flow)
void permanentlyDisablePolledEventHandler()
{
s_polledEventHandler = NULL;
s_oldPolledEventHandler = NULL;
}
bool polledEventHandlerInitialized()
{
return s_polledEventHandler != NULL;
}
void processEvents()
{
#ifdef __APPLE__
R_ProcessEvents();
// pickup X11 graphics device events (if any) via X11 input handler
fd_set* what = R_checkActivity(0,1);
if (what != NULL)
R_runHandlers(R_InputHandlers, what);
#else
// check for activity on standard input handlers (but ignore stdin).
// return immediately if there is no input currently available
fd_set* what = R_checkActivity(0,1);
// run handlers on the input (or run the polled event handler if there
// is no input currently available)
R_runHandlers(R_InputHandlers, what);
#endif
}
} // namespace event_loop
} // namespace session
} // namespace r
} // namespace rstudio
<commit_msg>Fix issue with RPC delivery when R is busy<commit_after>/*
* REmbeddedPosix.cpp
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <r/RExec.hpp>
#include <core/FilePath.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
// after boost stuff to prevent length (Rf_length) symbol conflict issues
#include "REmbedded.hpp"
#include <r/RInterface.hpp>
#include <r/RErrorCategory.hpp>
#include <r/RUtil.hpp>
#include <R_ext/eventloop.h>
#include <Rembedded.h>
#ifdef __APPLE__
#include <dlfcn.h>
extern "C" void R_ProcessEvents(void);
extern "C" void (*ptr_R_ProcessEvents)(void);
#define QCF_SET_PEPTR 1 /* set ProcessEvents function pointer */
#define QCF_SET_FRONT 2 /* set application mode to front */
extern "C" typedef void (*ptr_QuartzCocoa_SetupEventLoop)(int, unsigned long);
#endif
extern int R_running_as_main_program; // from unix/system.c
using namespace rstudio::core;
namespace rstudio {
namespace r {
namespace session {
void runEmbeddedR(const core::FilePath& /*rHome*/, // ignored on posix
const core::FilePath& /*userHome*/, // ignored on posix
bool quiet,
bool loadInitFile,
SA_TYPE defaultSaveAction,
const Callbacks& callbacks,
InternalCallbacks* pInternal)
{
// disable R signal handlers. see src/main/main.c for the default
// implementations. in our case ignore them for the following reasons:
//
// INT - no concept of Ctrl-C based interruption (use flag directly)
//
// SEGV, ILL, & BUS: unsupported due to prompt invoking networking
// code (unsupported from within a signal handler)
//
// USR1 & USR2: same as above SEGV, etc. + we use them for other purposes
//
// PIPE: we ignore this globally in SessionMain. before doing this we
// confirmed that asio wasn't in some way manipulating it -- on linux
// boost passes MSG_NOSIGNAL to sendmsg and on OSX sets the SO_NOSIGPIPE
// option on all sockets created. note that on other platforms including
// solaris, hpux, etc. boost uses detail/signal_init to ignore SIGPIPE
// globally (this is done in io_service.hpp).
R_SignalHandlers = 0;
// set message callback early so we can see initialization error messages
ptr_R_ShowMessage = callbacks.showMessage ;
// running as main program (affects location of R_CStackStart on platforms
// without HAVE_LIBC_STACK_END or HAVE_KERN_USRSTACK). see also discussion
// on R_CStackStart in 8.1.5 Threading issues
R_running_as_main_program = 1;
// initialize R
const char *args[]= {"RStudio", "--interactive"};
Rf_initialize_R(sizeof(args)/sizeof(args[0]), (char**)args);
// For newSession = false we need to do a few things:
//
// 1) set R_Quiet so we startup without a banner
//
// 2) set LoadInitFile to supress execution of .Rprofile
//
// 3) we also need to make sure that .First is not executed. this is
// taken care of via the fact that we set RestoreAction to SA_NORESTORE
// which means that when setup_Rmainloop there is no .First function
// available to it because we haven't restored the environment yet.
// Note that .First is executed in the case of new sessions because
// it is read from .Rprofile as part of setup_Rmainloop. This implies
// that in our version of R the .First function must be defined in
// .Rprofile rather than simply saved into the global environment
// of the default workspace
//
structRstart rp;
Rstart Rp = &rp;
R_DefParams(Rp) ;
Rp->R_Slave = FALSE ;
Rp->R_Quiet = quiet ? TRUE : FALSE;
Rp->R_Interactive = TRUE ;
Rp->SaveAction = defaultSaveAction ;
Rp->RestoreAction = SA_NORESTORE; // handled within initialize()
Rp->LoadInitFile = loadInitFile ? TRUE : FALSE;
R_SetParams(Rp) ;
// redirect console
R_Interactive = TRUE; // should have also been set by call to Rf_initialize_R
R_Consolefile = NULL;
R_Outputfile = NULL;
ptr_R_ReadConsole = callbacks.readConsole ;
ptr_R_WriteConsole = NULL; // must set this to NULL for Ex to be called
ptr_R_WriteConsoleEx = callbacks.writeConsoleEx ;
ptr_R_EditFile = callbacks.editFile ;
ptr_R_Busy = callbacks.busy;
// hook messages (in case Rf_initialize_R overwrites previously set hook)
ptr_R_ShowMessage = callbacks.showMessage ;
// hook file handling
ptr_R_ChooseFile = callbacks.chooseFile ;
ptr_R_ShowFiles = callbacks.showFiles ;
// hook history
ptr_R_loadhistory = callbacks.loadhistory;
ptr_R_savehistory = callbacks.savehistory;
ptr_R_addhistory = callbacks.addhistory;
// hook suicide, but save reference to internal suicide so we can forward
pInternal->suicide = ptr_R_Suicide;
ptr_R_Suicide = callbacks.suicide;
// hook clean up, but save reference to internal clean up so can forward
pInternal->cleanUp = ptr_R_CleanUp;
ptr_R_CleanUp = callbacks.cleanUp ;
// NOTE: we do not hook the following callbacks because they are targeted
// at clients that have a stdio-based console
// ptr_R_ResetConsole
// ptr_R_FlushConsole
// ptr_R_ClearerrConsole
// run main loop (does not return)
Rf_mainloop();
}
Error completeEmbeddedRInitialization(bool useInternet2)
{
return Success();
}
namespace event_loop {
namespace {
// currently installed polled event handler
void (*s_polledEventHandler)(void) = NULL;
// previously existing polled event handler
void (*s_oldPolledEventHandler)(void) = NULL;
// function we register with R to implement polled event handler
void polledEventHandler()
{
if (s_polledEventHandler != NULL)
s_polledEventHandler();
if (s_oldPolledEventHandler != NULL)
s_oldPolledEventHandler();
}
#ifdef __APPLE__
void logDLError(const std::string& message, const ErrorLocation& location)
{
std::string errmsg(message);
char* dlError = ::dlerror();
if (dlError)
errmsg += ": " + std::string(dlError);
core::log::logErrorMessage(errmsg, location);
}
// Note that when we passed QCF_SET_FRONT to QuartzCocoa_SetupEventLoop
// sometimes this resulted in our application having a "bouncing"
// state which we couldn't rid ourselves of.
//
// Note that in researching the way R implements QCF_SET_FRONT I discovered
// that a depricated API is called AND an explicit call to SetFront. Another
// way to go would be to call the TransformProcessType API:
//
// http://www.cocoadev.com/index.pl?TransformProcessType
// http://developer.apple.com/library/mac/#documentation/Carbon/Reference/Process_Manager/Reference/reference.html%23//apple_ref/c/func/TransformProcessType
//
// Note this would look something like (cmake and includes for completeness):
/*
find_library(CARBON_LIBRARY NAMES Carbon)
set(LINK_FLAGS ${CARBON_LIBRARY})
#include <Carbon/Carbon.h>
#undef TRUE
#undef FALSE
static const ProcessSerialNumber thePSN = { 0, kCurrentProcess };
::TransformProcessType(&thePSN, kProcessTransformToForegroundApplication);
*/
// attempt to setup quartz event loop, if this fails then log and
// return false (as a result we'll have to disable the quartz R
// function so the user doesn't get in trouble)
bool setupQuartzEventLoop()
{
// first make sure that the gdDevices pacakage is loaded
Error error = r::exec::executeString("library(grDevices)");
if (error)
{
LOG_ERROR(error);
return false;
}
// get a reference to the grDevices library
void* pGrDevices = ::dlopen("grDevices.so",
RTLD_LAZY | RTLD_LOCAL | RTLD_NOLOAD);
if (pGrDevices)
{
ptr_QuartzCocoa_SetupEventLoop pSetupEventLoop =
(ptr_QuartzCocoa_SetupEventLoop)::dlsym(
pGrDevices,
"QuartzCocoa_SetupEventLoop");
if (pSetupEventLoop)
{
// attempt to setup event loop
pSetupEventLoop(QCF_SET_PEPTR, 100);
// check that we got the ptr_R_ProcessEvents initialized
if (ptr_R_ProcessEvents != NULL)
{
return true;
}
else
{
LOG_ERROR_MESSAGE("ptr_R_ProcessEvents not initialized");
return false;
}
}
else
{
logDLError("Error looking up QuartzCocoa_SetupEventLoop",
ERROR_LOCATION);
return false;
}
}
else
{
logDLError("Error loading grDevices.so", ERROR_LOCATION);
return false;
}
}
// On versions prior to R 2.12 the event pump is handled by R_ProcessEvents
// rather than by the expected R_PolledEvents mechanism. On the Mac
// R_ProcessEvents includes a hook (ptr_R_ProcessEvents) but this is
// taken by the quartz module. We therefore need a way to hook it but
// still delegate to quartz so the quartz device works. do this by
// ensuring quartz is loaded then calling QuartzCocoa_SetupEventLoop
void installAppleR_2_11_Workaround(void (*newPolledEventHandler)(void))
{
// attempt to initialize the quartz event loop (init ptr_R_ProcessEvents
// so that we can delegate to it after we override it)
if (!setupQuartzEventLoop())
{
Error error = r::exec::RFunction(".rs.disableQuartz").call();
if (error)
LOG_ERROR(error);
}
// copy handler function
s_polledEventHandler = newPolledEventHandler;
// preserve old handler and set new one (note that ptr_R_ProcessEvents
// might be NULL if we didn't succeed in setting up the quartz
// event loop above. in this case the polled event handler will
// ignore it
s_oldPolledEventHandler = ptr_R_ProcessEvents;
ptr_R_ProcessEvents = polledEventHandler;
}
#endif
} // anonymous namespace
void initializePolledEventHandler(void (*newPolledEventHandler)(void))
{
// can only call this once
BOOST_ASSERT(!s_polledEventHandler);
// special hack for R 2.11.1 on OSX
#ifdef __APPLE__
if (!r::util::hasRequiredVersion("2.12"))
{
installAppleR_2_11_Workaround(newPolledEventHandler);
return;
}
#endif
// implementation based on addTcl() in tcltk_unix.c
// copy handler function
s_polledEventHandler = newPolledEventHandler;
// preserve old handler and set new one
s_oldPolledEventHandler = R_PolledEvents;
R_PolledEvents = polledEventHandler;
// set R_wait_usec
if (R_wait_usec > 10000 || R_wait_usec == 0)
R_wait_usec = 10000;
}
// NOTE: this call is used in child process after multicore forks
// to make sure all subsequent R code is executed without any
// event handlers (appropriate since the forked child is headless).
// the prefix "permanently" is used because we explicitly don't
// handle the abilty to restore event handling by calling
// initializePolledEventHandler -- this is because we overwrite
// s_oldPolledEventHandler with NULL, thus losing any reference
// we have to a R_PolledEvents value that existed before our
// initialization (it would be possible to implement a temporary
// disable with a bit more complex control flow)
void permanentlyDisablePolledEventHandler()
{
s_polledEventHandler = NULL;
s_oldPolledEventHandler = NULL;
}
bool polledEventHandlerInitialized()
{
return s_polledEventHandler != NULL;
}
void processEvents()
{
#ifdef __APPLE__
R_ProcessEvents();
// pickup X11 graphics device events (if any) via X11 input handler
fd_set* what = R_checkActivity(0,1);
if (what != NULL)
R_runHandlers(R_InputHandlers, what);
#else
// check for activity on standard input handlers (but ignore stdin).
// return immediately if there is no input currently available
fd_set* what = R_checkActivity(0,1);
// run handlers on the input (or run the polled event handler if there
// is no input currently available)
R_runHandlers(R_InputHandlers, what);
#endif
}
} // namespace event_loop
} // namespace session
} // namespace r
} // namespace rstudio
<|endoftext|> |
<commit_before>//===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the code that manages TBAA information.
//
//===----------------------------------------------------------------------===//
#include "CodeGenTBAA.h"
#include "Mangle.h"
#include "clang/AST/ASTContext.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace clang;
using namespace CodeGen;
CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext& VMContext,
const LangOptions &Features, MangleContext &MContext)
: Context(Ctx), VMContext(VMContext), Features(Features), MContext(MContext),
Root(0), Char(0) {
}
CodeGenTBAA::~CodeGenTBAA() {
}
llvm::MDNode *CodeGenTBAA::getTBAAInfoForNamedType(llvm::StringRef NameStr,
llvm::MDNode *Parent) {
llvm::Value *Ops[] = {
llvm::MDString::get(VMContext, NameStr),
Parent
};
return llvm::MDNode::get(VMContext, Ops, llvm::array_lengthof(Ops));
}
llvm::MDNode *
CodeGenTBAA::getTBAAInfo(QualType QTy) {
Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
if (llvm::MDNode *N = MetadataCache[Ty])
return N;
if (!Root) {
Root = getTBAAInfoForNamedType("Experimental TBAA", 0);
Char = getTBAAInfoForNamedType("omnipotent char", Root);
}
// For now, just emit a very minimal tree.
if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
switch (BTy->getKind()) {
// Character types are special and can alias anything.
// In C++, this technically only includes "char" and "unsigned char",
// and not "signed char". In C, it includes all three. For now,
// the risk of exploiting this detail in C++ seems likely to outweigh
// the benefit.
case BuiltinType::Char_U:
case BuiltinType::Char_S:
case BuiltinType::UChar:
case BuiltinType::SChar:
return Char;
// Unsigned types can alias their corresponding signed types.
case BuiltinType::UShort:
return getTBAAInfo(Context.ShortTy);
case BuiltinType::UInt:
return getTBAAInfo(Context.IntTy);
case BuiltinType::ULong:
return getTBAAInfo(Context.LongTy);
case BuiltinType::ULongLong:
return getTBAAInfo(Context.LongLongTy);
case BuiltinType::UInt128:
return getTBAAInfo(Context.Int128Ty);
// Treat all other builtin types as distinct types. This includes
// treating wchar_t, char16_t, and char32_t as distinct from their
// "underlying types".
default:
return MetadataCache[Ty] =
getTBAAInfoForNamedType(BTy->getName(Features), Char);
}
}
// For now, treat all pointers as equivalent to each other.
if (Ty->isPointerType())
return MetadataCache[Ty] = getTBAAInfoForNamedType("TBAA.pointer", Char);
// Enum types are distinct types. In C++ they have "underlying types",
// however they aren't related for TBAA.
if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
// In C mode, two anonymous enums are compatible iff their members
// are the same -- see C99 6.2.7p1. For now, be conservative. We could
// theoretically implement this by combining information about all the
// members into a single identifying MDNode.
if (!Features.CPlusPlus &&
ETy->getDecl()->getTypedefForAnonDecl())
return MetadataCache[Ty] = Char;
// In C++ mode, types have linkage, so we can rely on the ODR and
// on their mangled names, if they're external.
// TODO: Is there a way to get a program-wide unique name for a
// decl with local linkage or no linkage?
if (Features.CPlusPlus &&
ETy->getDecl()->getLinkage() != ExternalLinkage)
return MetadataCache[Ty] = Char;
// TODO: This is using the RTTI name. Is there a better way to get
// a unique string for a type?
llvm::SmallString<256> OutName;
MContext.mangleCXXRTTIName(QualType(ETy, 0), OutName);
return MetadataCache[Ty] = getTBAAInfoForNamedType(OutName, Char);
}
// For now, handle any other kind of type conservatively.
return MetadataCache[Ty] = Char;
}
<commit_msg>Use a different name for pointer types in tbaa, to be a little more consistent with other names, and to look less like a magic name.<commit_after>//===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the code that manages TBAA information.
//
//===----------------------------------------------------------------------===//
#include "CodeGenTBAA.h"
#include "Mangle.h"
#include "clang/AST/ASTContext.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace clang;
using namespace CodeGen;
CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext& VMContext,
const LangOptions &Features, MangleContext &MContext)
: Context(Ctx), VMContext(VMContext), Features(Features), MContext(MContext),
Root(0), Char(0) {
}
CodeGenTBAA::~CodeGenTBAA() {
}
llvm::MDNode *CodeGenTBAA::getTBAAInfoForNamedType(llvm::StringRef NameStr,
llvm::MDNode *Parent) {
llvm::Value *Ops[] = {
llvm::MDString::get(VMContext, NameStr),
Parent
};
return llvm::MDNode::get(VMContext, Ops, llvm::array_lengthof(Ops));
}
llvm::MDNode *
CodeGenTBAA::getTBAAInfo(QualType QTy) {
Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
if (llvm::MDNode *N = MetadataCache[Ty])
return N;
if (!Root) {
Root = getTBAAInfoForNamedType("Experimental TBAA", 0);
Char = getTBAAInfoForNamedType("omnipotent char", Root);
}
// For now, just emit a very minimal tree.
if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
switch (BTy->getKind()) {
// Character types are special and can alias anything.
// In C++, this technically only includes "char" and "unsigned char",
// and not "signed char". In C, it includes all three. For now,
// the risk of exploiting this detail in C++ seems likely to outweigh
// the benefit.
case BuiltinType::Char_U:
case BuiltinType::Char_S:
case BuiltinType::UChar:
case BuiltinType::SChar:
return Char;
// Unsigned types can alias their corresponding signed types.
case BuiltinType::UShort:
return getTBAAInfo(Context.ShortTy);
case BuiltinType::UInt:
return getTBAAInfo(Context.IntTy);
case BuiltinType::ULong:
return getTBAAInfo(Context.LongTy);
case BuiltinType::ULongLong:
return getTBAAInfo(Context.LongLongTy);
case BuiltinType::UInt128:
return getTBAAInfo(Context.Int128Ty);
// Treat all other builtin types as distinct types. This includes
// treating wchar_t, char16_t, and char32_t as distinct from their
// "underlying types".
default:
return MetadataCache[Ty] =
getTBAAInfoForNamedType(BTy->getName(Features), Char);
}
}
// TODO: Implement C++'s type "similarity" and consider dis-"similar"
// pointers distinct.
if (Ty->isPointerType())
return MetadataCache[Ty] = getTBAAInfoForNamedType("any pointer", Char);
// Enum types are distinct types. In C++ they have "underlying types",
// however they aren't related for TBAA.
if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
// In C mode, two anonymous enums are compatible iff their members
// are the same -- see C99 6.2.7p1. For now, be conservative. We could
// theoretically implement this by combining information about all the
// members into a single identifying MDNode.
if (!Features.CPlusPlus &&
ETy->getDecl()->getTypedefForAnonDecl())
return MetadataCache[Ty] = Char;
// In C++ mode, types have linkage, so we can rely on the ODR and
// on their mangled names, if they're external.
// TODO: Is there a way to get a program-wide unique name for a
// decl with local linkage or no linkage?
if (Features.CPlusPlus &&
ETy->getDecl()->getLinkage() != ExternalLinkage)
return MetadataCache[Ty] = Char;
// TODO: This is using the RTTI name. Is there a better way to get
// a unique string for a type?
llvm::SmallString<256> OutName;
MContext.mangleCXXRTTIName(QualType(ETy, 0), OutName);
return MetadataCache[Ty] = getTBAAInfoForNamedType(OutName, Char);
}
// For now, handle any other kind of type conservatively.
return MetadataCache[Ty] = Char;
}
<|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 "chrome/test/in_process_browser_test.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test_file_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(OS_WIN)
#include "chrome/browser/views/frame/browser_view.h"
#endif
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
#include "sandbox/src/dep.h"
extern int BrowserMain(const MainFunctionParams&);
const wchar_t kUnitTestShowWindows[] = L"show-windows";
// Default delay for the time-out at which we stop the
// inner-message loop the first time.
const int kInitialTimeoutInMS = 30000;
// Delay for sub-sequent time-outs once the initial time-out happened.
const int kSubsequentTimeoutInMS = 5000;
InProcessBrowserTest::InProcessBrowserTest()
: browser_(NULL),
show_window_(false),
dom_automation_enabled_(false),
single_process_(false),
original_single_process_(false),
initial_timeout_(kInitialTimeoutInMS) {
}
void InProcessBrowserTest::SetUp() {
// Cleanup the user data dir.
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ASSERT_LT(10, static_cast<int>(user_data_dir.value().size())) <<
"The user data directory name passed into this test was too "
"short to delete safely. Please check the user-data-dir "
"argument and try again.";
ASSERT_TRUE(file_util::DieFileDie(user_data_dir, true));
// The unit test suite creates a testingbrowser, but we want the real thing.
// Delete the current one. We'll install the testing one in TearDown.
delete g_browser_process;
// Don't delete the resources when BrowserMain returns. Many ui classes
// cache SkBitmaps in a static field so that if we delete the resource
// bundle we'll crash.
browser_shutdown::delete_resources_on_shutdown = false;
CommandLine* command_line = CommandLine::ForCurrentProcessMutable();
original_command_line_.reset(new CommandLine(*command_line));
SetUpCommandLine(command_line);
#if defined(OS_WIN)
// Hide windows on show.
if (!command_line->HasSwitch(kUnitTestShowWindows) && !show_window_)
BrowserView::SetShowState(SW_HIDE);
#endif
if (dom_automation_enabled_)
command_line->AppendSwitch(switches::kDomAutomationController);
if (single_process_)
command_line->AppendSwitch(switches::kSingleProcess);
// TODO(arv): Reenable once kEnableWebResources is changed back to
// kDisableWebResources
// http://crbug.com/17725
// command_line->AppendSwitch(switches::kEnableWebResources);
command_line->AppendSwitchWithValue(switches::kUserDataDir,
user_data_dir.ToWStringHack());
// For some reason the sandbox wasn't happy running in test mode. These
// tests aren't intended to test the sandbox, so we turn it off.
command_line->AppendSwitch(switches::kNoSandbox);
// Don't show the first run ui.
command_line->AppendSwitch(switches::kNoFirstRun);
// Single-process mode is not set in BrowserMain so it needs to be processed
// explicitlty.
original_single_process_ = RenderProcessHost::run_renderer_in_process();
if (command_line->HasSwitch(switches::kSingleProcess))
RenderProcessHost::set_run_renderer_in_process(true);
// Explicitly set the path of the exe used for the renderer and plugin,
// otherwise they'll try to use unit_test.exe.
std::wstring subprocess_path;
PathService::Get(base::FILE_EXE, &subprocess_path);
FilePath fp_subprocess_path = FilePath::FromWStringHack(subprocess_path);
subprocess_path = fp_subprocess_path.DirName().ToWStringHack();
file_util::AppendToPath(&subprocess_path,
chrome::kBrowserProcessExecutablePath);
command_line->AppendSwitchWithValue(switches::kBrowserSubprocessPath,
subprocess_path);
// Enable warning level logging so that we can see when bad stuff happens.
command_line->AppendSwitch(switches::kEnableLogging);
command_line->AppendSwitchWithValue(switches::kLoggingLevel,
IntToWString(1)); // warning
SandboxInitWrapper sandbox_wrapper;
MainFunctionParams params(*command_line, sandbox_wrapper, NULL);
params.ui_task =
NewRunnableMethod(this, &InProcessBrowserTest::RunTestOnMainThreadLoop);
scoped_refptr<net::RuleBasedHostResolverProc> host_resolver_proc(
new net::RuleBasedHostResolverProc(NULL));
ConfigureHostResolverProc(host_resolver_proc);
net::ScopedDefaultHostResolverProc scoped_host_resolver_proc(
host_resolver_proc);
BrowserMain(params);
}
void InProcessBrowserTest::TearDown() {
// Reinstall testing browser process.
delete g_browser_process;
g_browser_process = new TestingBrowserProcess();
browser_shutdown::delete_resources_on_shutdown = true;
#if defined(WIN)
BrowserView::SetShowState(-1);
#endif
*CommandLine::ForCurrentProcessMutable() = *original_command_line_;
RenderProcessHost::set_run_renderer_in_process(original_single_process_);
}
HTTPTestServer* InProcessBrowserTest::StartHTTPServer() {
// The HTTPServer must run on the IO thread.
DCHECK(!http_server_.get());
http_server_ = HTTPTestServer::CreateServer(
L"chrome/test/data",
g_browser_process->io_thread()->message_loop());
return http_server_.get();
}
// Creates a browser with a single tab (about:blank), waits for the tab to
// finish loading and shows the browser.
Browser* InProcessBrowserTest::CreateBrowser(Profile* profile) {
Browser* browser = Browser::Create(profile);
browser->AddTabWithURL(
GURL("about:blank"), GURL(), PageTransition::START_PAGE, true, -1, false,
NULL);
// Wait for the page to finish loading.
ui_test_utils::WaitForNavigation(
&browser->GetSelectedTabContents()->controller());
browser->window()->Show();
return browser;
}
void InProcessBrowserTest::RunTestOnMainThreadLoop() {
// In the long term it would be great if we could use a TestingProfile
// here and only enable services you want tested, but that requires all
// consumers of Profile to handle NULL services.
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ProfileManager* profile_manager = g_browser_process->profile_manager();
Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
if (!profile) {
// We should only be able to get here if the profile already exists and
// has been created.
NOTREACHED();
MessageLoopForUI::current()->Quit();
return;
}
// Before we run the browser, we have to hack the path to the exe to match
// what it would be if Chrome was running, because it is used to fork renderer
// processes, on Linux at least (failure to do so will cause a browser_test to
// be run instead of a renderer).
FilePath chrome_path;
CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
chrome_path = chrome_path.DirName();
#if defined(OS_WIN)
chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);
#elif defined(OS_POSIX)
chrome_path = chrome_path.Append(
WideToASCII(chrome::kBrowserProcessExecutablePath));
#endif
CHECK(PathService::Override(base::FILE_EXE, chrome_path));
browser_ = CreateBrowser(profile);
// Start the timeout timer to prevent hangs.
MessageLoopForUI::current()->PostDelayedTask(FROM_HERE,
NewRunnableMethod(this, &InProcessBrowserTest::TimedOut),
initial_timeout_);
RunTestOnMainThread();
CleanUpOnMainThread();
// Close all browser windows. This might not happen immediately, since some
// may need to wait for beforeunload and unload handlers to fire in a tab.
// When all windows are closed, the last window will call Quit().
BrowserList::const_iterator browser = BrowserList::begin();
for (; browser != BrowserList::end(); ++browser)
(*browser)->CloseWindow();
// Stop the HTTP server.
http_server_ = NULL;
}
void InProcessBrowserTest::ConfigureHostResolverProc(
net::RuleBasedHostResolverProc* host_resolver_proc) {
host_resolver_proc->AllowDirectLookup("*.google.com");
// See http://en.wikipedia.org/wiki/Web_Proxy_Autodiscovery_Protocol
// We don't want the test code to use it.
host_resolver_proc->AddSimulatedFailure("wpad");
}
void InProcessBrowserTest::TimedOut() {
DCHECK(MessageLoopForUI::current()->IsNested());
GTEST_NONFATAL_FAILURE_("Timed-out");
// Start the timeout timer to prevent hangs.
MessageLoopForUI::current()->PostDelayedTask(FROM_HERE,
NewRunnableMethod(this, &InProcessBrowserTest::TimedOut),
kSubsequentTimeoutInMS);
MessageLoopForUI::current()->Quit();
}
void InProcessBrowserTest::SetInitialTimeoutInMS(int timeout_value) {
DCHECK_GT(timeout_value, 0);
initial_timeout_ = timeout_value;
}
<commit_msg>Enable url request mocks in browser tests.<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 "chrome/test/in_process_browser_test.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test_file_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/net/url_request_mock_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(OS_WIN)
#include "chrome/browser/views/frame/browser_view.h"
#endif
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"
#include "sandbox/src/dep.h"
extern int BrowserMain(const MainFunctionParams&);
const wchar_t kUnitTestShowWindows[] = L"show-windows";
// Default delay for the time-out at which we stop the
// inner-message loop the first time.
const int kInitialTimeoutInMS = 30000;
// Delay for sub-sequent time-outs once the initial time-out happened.
const int kSubsequentTimeoutInMS = 5000;
InProcessBrowserTest::InProcessBrowserTest()
: browser_(NULL),
show_window_(false),
dom_automation_enabled_(false),
single_process_(false),
original_single_process_(false),
initial_timeout_(kInitialTimeoutInMS) {
}
void InProcessBrowserTest::SetUp() {
// Cleanup the user data dir.
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ASSERT_LT(10, static_cast<int>(user_data_dir.value().size())) <<
"The user data directory name passed into this test was too "
"short to delete safely. Please check the user-data-dir "
"argument and try again.";
ASSERT_TRUE(file_util::DieFileDie(user_data_dir, true));
// The unit test suite creates a testingbrowser, but we want the real thing.
// Delete the current one. We'll install the testing one in TearDown.
delete g_browser_process;
// Don't delete the resources when BrowserMain returns. Many ui classes
// cache SkBitmaps in a static field so that if we delete the resource
// bundle we'll crash.
browser_shutdown::delete_resources_on_shutdown = false;
CommandLine* command_line = CommandLine::ForCurrentProcessMutable();
original_command_line_.reset(new CommandLine(*command_line));
SetUpCommandLine(command_line);
#if defined(OS_WIN)
// Hide windows on show.
if (!command_line->HasSwitch(kUnitTestShowWindows) && !show_window_)
BrowserView::SetShowState(SW_HIDE);
#endif
if (dom_automation_enabled_)
command_line->AppendSwitch(switches::kDomAutomationController);
if (single_process_)
command_line->AppendSwitch(switches::kSingleProcess);
// TODO(arv): Reenable once kEnableWebResources is changed back to
// kDisableWebResources
// http://crbug.com/17725
// command_line->AppendSwitch(switches::kEnableWebResources);
command_line->AppendSwitchWithValue(switches::kUserDataDir,
user_data_dir.ToWStringHack());
// For some reason the sandbox wasn't happy running in test mode. These
// tests aren't intended to test the sandbox, so we turn it off.
command_line->AppendSwitch(switches::kNoSandbox);
// Don't show the first run ui.
command_line->AppendSwitch(switches::kNoFirstRun);
// Single-process mode is not set in BrowserMain so it needs to be processed
// explicitlty.
original_single_process_ = RenderProcessHost::run_renderer_in_process();
if (command_line->HasSwitch(switches::kSingleProcess))
RenderProcessHost::set_run_renderer_in_process(true);
// Explicitly set the path of the exe used for the renderer and plugin,
// otherwise they'll try to use unit_test.exe.
std::wstring subprocess_path;
PathService::Get(base::FILE_EXE, &subprocess_path);
FilePath fp_subprocess_path = FilePath::FromWStringHack(subprocess_path);
subprocess_path = fp_subprocess_path.DirName().ToWStringHack();
file_util::AppendToPath(&subprocess_path,
chrome::kBrowserProcessExecutablePath);
command_line->AppendSwitchWithValue(switches::kBrowserSubprocessPath,
subprocess_path);
// Enable warning level logging so that we can see when bad stuff happens.
command_line->AppendSwitch(switches::kEnableLogging);
command_line->AppendSwitchWithValue(switches::kLoggingLevel,
IntToWString(1)); // warning
SandboxInitWrapper sandbox_wrapper;
MainFunctionParams params(*command_line, sandbox_wrapper, NULL);
params.ui_task =
NewRunnableMethod(this, &InProcessBrowserTest::RunTestOnMainThreadLoop);
scoped_refptr<net::RuleBasedHostResolverProc> host_resolver_proc(
new net::RuleBasedHostResolverProc(NULL));
ConfigureHostResolverProc(host_resolver_proc);
net::ScopedDefaultHostResolverProc scoped_host_resolver_proc(
host_resolver_proc);
BrowserMain(params);
}
void InProcessBrowserTest::TearDown() {
// Reinstall testing browser process.
delete g_browser_process;
g_browser_process = new TestingBrowserProcess();
browser_shutdown::delete_resources_on_shutdown = true;
#if defined(WIN)
BrowserView::SetShowState(-1);
#endif
*CommandLine::ForCurrentProcessMutable() = *original_command_line_;
RenderProcessHost::set_run_renderer_in_process(original_single_process_);
}
HTTPTestServer* InProcessBrowserTest::StartHTTPServer() {
// The HTTPServer must run on the IO thread.
DCHECK(!http_server_.get());
http_server_ = HTTPTestServer::CreateServer(
L"chrome/test/data",
g_browser_process->io_thread()->message_loop());
return http_server_.get();
}
// Creates a browser with a single tab (about:blank), waits for the tab to
// finish loading and shows the browser.
Browser* InProcessBrowserTest::CreateBrowser(Profile* profile) {
Browser* browser = Browser::Create(profile);
browser->AddTabWithURL(
GURL("about:blank"), GURL(), PageTransition::START_PAGE, true, -1, false,
NULL);
// Wait for the page to finish loading.
ui_test_utils::WaitForNavigation(
&browser->GetSelectedTabContents()->controller());
browser->window()->Show();
return browser;
}
void InProcessBrowserTest::RunTestOnMainThreadLoop() {
// In the long term it would be great if we could use a TestingProfile
// here and only enable services you want tested, but that requires all
// consumers of Profile to handle NULL services.
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ProfileManager* profile_manager = g_browser_process->profile_manager();
Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
if (!profile) {
// We should only be able to get here if the profile already exists and
// has been created.
NOTREACHED();
MessageLoopForUI::current()->Quit();
return;
}
// Before we run the browser, we have to hack the path to the exe to match
// what it would be if Chrome was running, because it is used to fork renderer
// processes, on Linux at least (failure to do so will cause a browser_test to
// be run instead of a renderer).
FilePath chrome_path;
CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
chrome_path = chrome_path.DirName();
#if defined(OS_WIN)
chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);
#elif defined(OS_POSIX)
chrome_path = chrome_path.Append(
WideToASCII(chrome::kBrowserProcessExecutablePath));
#endif
CHECK(PathService::Override(base::FILE_EXE, chrome_path));
g_browser_process->io_thread()->message_loop()->PostTask(FROM_HERE,
NewRunnableFunction(chrome_browser_net::SetUrlRequestMocksEnabled, true));
browser_ = CreateBrowser(profile);
// Start the timeout timer to prevent hangs.
MessageLoopForUI::current()->PostDelayedTask(FROM_HERE,
NewRunnableMethod(this, &InProcessBrowserTest::TimedOut),
initial_timeout_);
RunTestOnMainThread();
CleanUpOnMainThread();
// Close all browser windows. This might not happen immediately, since some
// may need to wait for beforeunload and unload handlers to fire in a tab.
// When all windows are closed, the last window will call Quit().
BrowserList::const_iterator browser = BrowserList::begin();
for (; browser != BrowserList::end(); ++browser)
(*browser)->CloseWindow();
// Stop the HTTP server.
http_server_ = NULL;
}
void InProcessBrowserTest::ConfigureHostResolverProc(
net::RuleBasedHostResolverProc* host_resolver_proc) {
host_resolver_proc->AllowDirectLookup("*.google.com");
// See http://en.wikipedia.org/wiki/Web_Proxy_Autodiscovery_Protocol
// We don't want the test code to use it.
host_resolver_proc->AddSimulatedFailure("wpad");
}
void InProcessBrowserTest::TimedOut() {
DCHECK(MessageLoopForUI::current()->IsNested());
GTEST_NONFATAL_FAILURE_("Timed-out");
// Start the timeout timer to prevent hangs.
MessageLoopForUI::current()->PostDelayedTask(FROM_HERE,
NewRunnableMethod(this, &InProcessBrowserTest::TimedOut),
kSubsequentTimeoutInMS);
MessageLoopForUI::current()->Quit();
}
void InProcessBrowserTest::SetInitialTimeoutInMS(int timeout_value) {
DCHECK_GT(timeout_value, 0);
initial_timeout_ = timeout_value;
}
<|endoftext|> |
<commit_before>//===--- Tool.cpp - The LLVM Compiler Driver --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Tool base class - implementation details.
//
//===----------------------------------------------------------------------===//
#include "llvm/CompilerDriver/BuiltinOptions.h"
#include "llvm/CompilerDriver/Tool.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/System/Path.h"
using namespace llvm;
using namespace llvmc;
// SplitString is used by derived Tool classes.
typedef void (*SplitStringFunPtr)(const std::string&,
std::vector<std::string>&, const char*);
SplitStringFunPtr ForceLinkageSplitString = &llvm::SplitString;
namespace {
sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
const std::string& Suffix) {
sys::Path Out;
// Make sure we don't end up with path names like '/file.o' if the
// TempDir is empty.
if (TempDir.empty()) {
Out.set(BaseName);
}
else {
Out = TempDir;
Out.appendComponent(BaseName);
}
Out.appendSuffix(Suffix);
// NOTE: makeUnique always *creates* a unique temporary file,
// which is good, since there will be no races. However, some
// tools do not like it when the output file already exists, so
// they need to be placated with -f or something like that.
Out.makeUnique(true, NULL);
return Out;
}
}
sys::Path Tool::OutFilename(const sys::Path& In,
const sys::Path& TempDir,
bool StopCompilation,
const char* OutputSuffix) const {
sys::Path Out;
if (StopCompilation) {
if (!OutputFilename.empty()) {
Out.set(OutputFilename);
}
else if (IsJoin()) {
Out.set("a");
Out.appendSuffix(OutputSuffix);
}
else {
Out.set(In.getBasename());
Out.appendSuffix(OutputSuffix);
}
}
else {
if (IsJoin())
Out = MakeTempFile(TempDir, "tmp", OutputSuffix);
else
Out = MakeTempFile(TempDir, In.getBasename(), OutputSuffix);
}
return Out;
}
<commit_msg>Remove dead code.<commit_after>//===--- Tool.cpp - The LLVM Compiler Driver --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Tool base class - implementation details.
//
//===----------------------------------------------------------------------===//
#include "llvm/CompilerDriver/BuiltinOptions.h"
#include "llvm/CompilerDriver/Tool.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/System/Path.h"
using namespace llvm;
using namespace llvmc;
namespace {
sys::Path MakeTempFile(const sys::Path& TempDir, const std::string& BaseName,
const std::string& Suffix) {
sys::Path Out;
// Make sure we don't end up with path names like '/file.o' if the
// TempDir is empty.
if (TempDir.empty()) {
Out.set(BaseName);
}
else {
Out = TempDir;
Out.appendComponent(BaseName);
}
Out.appendSuffix(Suffix);
// NOTE: makeUnique always *creates* a unique temporary file,
// which is good, since there will be no races. However, some
// tools do not like it when the output file already exists, so
// they need to be placated with -f or something like that.
Out.makeUnique(true, NULL);
return Out;
}
}
sys::Path Tool::OutFilename(const sys::Path& In,
const sys::Path& TempDir,
bool StopCompilation,
const char* OutputSuffix) const {
sys::Path Out;
if (StopCompilation) {
if (!OutputFilename.empty()) {
Out.set(OutputFilename);
}
else if (IsJoin()) {
Out.set("a");
Out.appendSuffix(OutputSuffix);
}
else {
Out.set(In.getBasename());
Out.appendSuffix(OutputSuffix);
}
}
else {
if (IsJoin())
Out = MakeTempFile(TempDir, "tmp", OutputSuffix);
else
Out = MakeTempFile(TempDir, In.getBasename(), OutputSuffix);
}
return Out;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004 Pascal Giorgi, Clément Pernet
* 2013, 2014 the LinBox group
* 2018 revamped by Pascal Giorgi
*
* Written by :
* Pascal Giorgi <[email protected]>
* Clément Pernet <[email protected]>
* Brice Boyer (briceboyer) <[email protected]>
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
/*!@internal
* @file matrix/densematrix/blas-matrix.inl
* @ingroup densematrix
* A \c BlasMatrix<\c _Field > represents a matrix as an array of
* <code>_Field</code>s.
*/
#ifndef __LINBOX_densematrix_blas_matrix_INL
#define __LINBOX_densematrix_blas_matrix_INL
#include "linbox/field/hom.h"
#include "linbox/vector/vector-domain.h"
#include "fflas-ffpack/fflas/fflas.h"
///////////////////
// PROTECTED //
///////////////////
namespace LinBox
{
template<class _Field, class _Storage>
template <class constIterator>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const constIterator& v)
{
constIterator v_end = v+(_col*_row) ;
Element_ptr iter_addr = getPointer();
for (; v != v_end ; ++v, ++iter_addr)
{
field().assign(*iter_addr,*v);
}
}
template<class _Field, class _Storage>
template <class _Matrix>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const _Matrix& A,
const size_t i0,const size_t j0,
const size_t m, const size_t n,
MatrixContainerCategory::Container)
{
linbox_check( areFieldEqual(A.field(),field() ) );
typename _Matrix::ConstIterator iter_value = A.Begin();
typename _Matrix::ConstIndexedIterator iter_index = A.IndexedBegin();
// PG -> BUG if we use iter_value !=A.End()
for (;iter_index != A.IndexedEnd(); ++iter_value,++iter_index){
int64_t i,j;
i=(int64_t)iter_index.rowIndex()-(int64_t)i0;
j=(int64_t)iter_index.colIndex()-(int64_t)j0;
if ( (i>=0) && (j>=0) && (i< (int64_t)m) && (j < (int64_t)n))
setEntry((size_t)i, (size_t)j, *iter_value);
}
}
template<class _Field, class _Storage>
template <class _Matrix>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const _Matrix& A,
const size_t i0,const size_t j0,
const size_t m, const size_t n,
MatrixContainerCategory::BlasContainer)
{
linbox_check( areFieldEqual(A.field(),field() ) );
FFLAS::fassign(field(), m, n, A.getPointer(), A.getStride(), getPointer(), getStride());
}
template<class _Field, class _Storage>
template <class Matrix>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const Matrix& A,
const size_t i0,const size_t j0,
const size_t m, const size_t n,
MatrixContainerCategory::Blackbox)
{
linbox_check( areFieldEqual(A.field(),field() ) );
BlasVector<_Field, _Storage> e(A.field(),A.coldim(), field().zero), tmp(A.field(),A.rowdim());
ColIterator col_p;
typename BlasMatrix<_Field, _Storage >::Col::iterator elt_p;
typename BlasVector<_Field, _Storage>::iterator e_p, tmp_p;
for (col_p = colBegin(), e_p = e.begin();
e_p != e.end(); ++ col_p, ++ e_p)
{
field().assign(*e_p, field().one);
A.apply (tmp, e);
for (tmp_p = tmp.begin(), elt_p = col_p -> begin();
tmp_p != tmp.end(); ++ tmp_p, ++ elt_p)
field().assign(*elt_p, *tmp_p);
field().assign(*e_p, field().zero);
}
}
////////////
// MEMORY //
////////////
template < class _Field, class _Storage >
void BlasMatrix< _Field, _Storage >::init(const size_t & m, const size_t & n)
{
_row = m; _col = n;
_rep.resize(m*n);
}
template < class _Field, class _Storage >
void BlasMatrix< _Field, _Storage >::resize (const size_t & m, const size_t & n, const Element& val )
{
#ifndef NDEBUG
if (_col > 0 && _col != n)
std::cerr << " ***Warning*** you are resizing a matrix, possibly loosing data. " << std::endl;
#endif
_rep.resize (m * n, val);
_row = m;
_col = n;
}
//////////////////
// CONSTRUCTORS //
//////////////////
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix (const _Field &F) :
_row(0),_col(0),_rep(F){}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix ( const _Field &F, const size_t & m, const size_t & n) :
_row(m),_col(n),_rep(F,_row*_col){}
template < class _Field, class _Storage >
template <class Matrix>
BlasMatrix< _Field, _Storage >::BlasMatrix (const Matrix &A) :
_row(A.rowdim()),_col(A.coldim()),_rep(A.field(),_row*_col)
{
createBlasMatrix(A,0,0,_row,_col,typename MatrixContainerTrait<Matrix>::Type());
}
template < class _Field, class _Storage >
template <class Matrix>
BlasMatrix< _Field, _Storage >::BlasMatrix (const Matrix& A,const size_t &i0, const size_t &j0,const size_t &m, const size_t &n) :
_row(m),_col(n),_rep(A.field(),_row*_col)
{
createBlasMatrix(A, i0, j0, m, n,typename MatrixContainerTrait<Matrix>::Type());
}
template < class _Field, class _Storage >
template<class constIterator>
BlasMatrix< _Field, _Storage >::BlasMatrix (const _Field &F,
const size_t & m, const size_t & n,
const constIterator& it) :
_row(m), _col(n),_rep(F, _row*_col)
{
createBlasMatrix(it);
}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix(MatrixStream<_Field>& ms) :
_row(0),_col(0),_rep(ms.getField())
{
if( !ms.getArray(_rep) || !ms.getDimensions(_row, _col) )
throw ms.reportError(__FUNCTION__,__LINE__);
}
template < class _Field, class _Storage >
template <class StreamVector>
BlasMatrix< _Field, _Storage >::BlasMatrix (const Field &F, VectorStream<StreamVector> &stream) :
_row(stream.size ()), _col(stream.dim ()), _rep(F,_row*_col)
{
VectorDomain<Field> VD(F);
StreamVector tmp(F);
typename BlasMatrix<Field,_Storage>::RowIterator p;
VectorWrapper::ensureDim (tmp, stream.dim ());
for (p = BlasMatrix<Field,_Storage>::rowBegin (); p != BlasMatrix<Field,_Storage>::rowEnd (); ++p) {
stream >> tmp;
VD.copy (*p, tmp);
}
}
template < class _Field, class _Storage >
template<class OtherMatrix>
BlasMatrix< _Field, _Storage >::BlasMatrix (const OtherMatrix &A, const _Field &F) :
_row(A.rowdim()), _col(A.coldim()), _rep(F, _row*_col)
{
//std::cout<<"GIORGI: BlasMatrix reducing mod \n";
typename OtherMatrix::template rebind<_Field>()(*this,A);
}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix (const BlasMatrix< _Field, _Storage> &A) :
_row(A.rowdim()), _col(A.coldim()),_rep(A.field(),_row*_col)
{
createBlasMatrix(A,0,0,_row,_col,MatrixContainerCategory::BlasContainer());
}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >& BlasMatrix< _Field, _Storage >::operator= (const BlasMatrix< _Field, _Storage >& A)
{
if ( &A == this)
return *this;
_col = A.coldim();
_row = A.rowdim();
_rep = Storage(A.field(),_row*_col);
createBlasMatrix(A,0,0,_row,_col,MatrixContainerCategory::BlasContainer());
return *this;
}
template < class _Field, class _Storage >
template < class Matrix>
BlasMatrix< _Field, _Storage >& BlasMatrix< _Field, _Storage >::operator= (const Matrix& A)
{
_col = A.coldim();
_row = A.rowdim();
_rep = Storage(A.field(),_row*_col);
createBlasMatrix(A,0,0,_row,_col,typename MatrixContainerTrait<Matrix>::Type());
return *this;
}
//! @bug other rep
template < class _Field, class _Storage >
template<typename _Tp1, typename _Rep2>
struct BlasMatrix< _Field, _Storage >::rebind {
typedef BlasMatrix<_Tp1, _Rep2> other;
void operator() (other & Ap, const Self_t& A) {
// typedef Self_t::ConstIterator ConstSelfIterator ;
typedef typename BlasMatrix< _Field, _Storage >::ConstIterator ConstSelfIterator ;
typedef typename other::Iterator OtherIterator ;
OtherIterator Ap_i = Ap.Begin();
ConstSelfIterator A_i = A.Begin();
Hom<Field, _Tp1> hom(A. field(), Ap. field()) ;
for ( ; A_i != A. End(); ++ A_i, ++ Ap_i)
hom.image (*Ap_i, *A_i);
//Ap.write(std::cout);
}
};
///////////////////
// I/O //
///////////////////
template < class _Field, class _Storage >
std::istream &BlasMatrix< _Field, _Storage >::read (std::istream &file)
{
MatrixStream<Field> ms(field(), file);
if( !ms.getArray(_rep) || !ms.getDimensions(_row, _col) ){
throw ms.reportError(__FUNCTION__,__LINE__);
}
return file;
}
template < class _Field, class _Storage >
std::ostream &BlasMatrix< _Field, _Storage >::write (std::ostream &os, Tag::FileFormat f) const
{
//std::cout<<"BlasMatrix write: "<<&(*_rep.getPointer())<<" "<<_rep<<std::endl;
constSubMatrixType B(*this);
return B.write(os,f);
}
} // end of LinBox namespace
#endif // __LINBOX_densematrix_blas_matrix_INL
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>more generic last<commit_after>/*
* Copyright (C) 2004 Pascal Giorgi, Clément Pernet
* 2013, 2014 the LinBox group
* 2018 revamped by Pascal Giorgi
*
* Written by :
* Pascal Giorgi <[email protected]>
* Clément Pernet <[email protected]>
* Brice Boyer (briceboyer) <[email protected]>
*
* ========LICENCE========
* This file is part of the library LinBox.
*
* LinBox 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
* ========LICENCE========
*/
/*!@internal
* @file matrix/densematrix/blas-matrix.inl
* @ingroup densematrix
* A \c BlasMatrix<\c _Field > represents a matrix as an array of
* <code>_Field</code>s.
*/
#ifndef __LINBOX_densematrix_blas_matrix_INL
#define __LINBOX_densematrix_blas_matrix_INL
#include "linbox/field/hom.h"
#include "linbox/vector/vector-domain.h"
#include "fflas-ffpack/fflas/fflas.h"
///////////////////
// PROTECTED //
///////////////////
namespace LinBox
{
template<class _Field, class _Storage>
template <class constIterator>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const constIterator& v)
{
constIterator v_end = v+(_col*_row) ;
Element_ptr iter_addr = getPointer();
for (; v != v_end ; ++v, ++iter_addr)
{
field().assign(*iter_addr,*v);
}
}
template<class _Field, class _Storage>
template <class _Matrix>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const _Matrix& A,
const size_t i0,const size_t j0,
const size_t m, const size_t n,
MatrixContainerCategory::Container)
{
linbox_check( areFieldEqual(A.field(),field() ) );
typename _Matrix::ConstIterator iter_value = A.Begin();
typename _Matrix::ConstIndexedIterator iter_index = A.IndexedBegin();
// PG -> BUG if we use iter_value !=A.End()
for (;iter_index != A.IndexedEnd(); ++iter_value,++iter_index){
int64_t i,j;
i=(int64_t)iter_index.rowIndex()-(int64_t)i0;
j=(int64_t)iter_index.colIndex()-(int64_t)j0;
if ( (i>=0) && (j>=0) && (i< (int64_t)m) && (j < (int64_t)n))
setEntry((size_t)i, (size_t)j, *iter_value);
}
}
template<class _Field, class _Storage>
template <class _Matrix>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const _Matrix& A,
const size_t i0,const size_t j0,
const size_t m, const size_t n,
MatrixContainerCategory::BlasContainer)
{
linbox_check( areFieldEqual(A.field(),field() ) );
FFLAS::fassign(field(), m, n, A.getPointer(), A.getStride(), getPointer(), getStride());
}
template<class _Field, class _Storage>
template <class Matrix>
void BlasMatrix< _Field, _Storage >::createBlasMatrix (const Matrix& A,
const size_t i0,const size_t j0,
const size_t m, const size_t n,
MatrixContainerCategory::Blackbox)
{
linbox_check( areFieldEqual(A.field(),field() ) );
BlasVector<_Field, _Storage> e(A.field(),A.coldim(), field().zero), tmp(A.field(),A.rowdim());
ColIterator col_p;
typename BlasMatrix<_Field, _Storage >::Col::iterator elt_p;
typename BlasVector<_Field, _Storage>::iterator e_p, tmp_p;
for (col_p = colBegin(), e_p = e.begin();
e_p != e.end(); ++ col_p, ++ e_p)
{
field().assign(*e_p, field().one);
A.apply (tmp, e);
for (tmp_p = tmp.begin(), elt_p = col_p -> begin();
tmp_p != tmp.end(); ++ tmp_p, ++ elt_p)
field().assign(*elt_p, *tmp_p);
field().assign(*e_p, field().zero);
}
}
////////////
// MEMORY //
////////////
template < class _Field, class _Storage >
void BlasMatrix< _Field, _Storage >::init(const size_t & m, const size_t & n)
{
_row = m; _col = n;
_rep.resize(m*n);
}
template < class _Field, class _Storage >
void BlasMatrix< _Field, _Storage >::resize (const size_t & m, const size_t & n, const Element& val )
{
#ifndef NDEBUG
if (_col > 0 && _col != n)
std::cerr << " ***Warning*** you are resizing a matrix, possibly loosing data. " << std::endl;
#endif
_rep.resize (m * n, val);
_row = m;
_col = n;
}
//////////////////
// CONSTRUCTORS //
//////////////////
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix (const _Field &F) :
_row(0),_col(0),_rep(F){}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix ( const _Field &F, const size_t & m, const size_t & n) :
_row(m),_col(n),_rep(F,_row*_col){}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix(MatrixStream<_Field>& ms) :
_row(0),_col(0),_rep(ms.getField())
{
if( !ms.getArray(_rep) || !ms.getDimensions(_row, _col) )
throw ms.reportError(__FUNCTION__,__LINE__);
}
template < class _Field, class _Storage >
template <class Matrix>
BlasMatrix< _Field, _Storage >::BlasMatrix (const Matrix &A) :
_row(A.rowdim()),_col(A.coldim()),_rep(A.field(),_row*_col)
{
createBlasMatrix(A,0,0,_row,_col,typename MatrixContainerTrait<Matrix>::Type());
}
template < class _Field, class _Storage >
template <class Matrix>
BlasMatrix< _Field, _Storage >::BlasMatrix (const Matrix& A,const size_t &i0, const size_t &j0,const size_t &m, const size_t &n) :
_row(m),_col(n),_rep(A.field(),_row*_col)
{
createBlasMatrix(A, i0, j0, m, n,typename MatrixContainerTrait<Matrix>::Type());
}
template < class _Field, class _Storage >
template<class constIterator>
BlasMatrix< _Field, _Storage >::BlasMatrix (const _Field &F,
const size_t & m, const size_t & n,
const constIterator& it) :
_row(m), _col(n),_rep(F, _row*_col)
{
createBlasMatrix(it);
}
template < class _Field, class _Storage >
template <class StreamVector>
BlasMatrix< _Field, _Storage >::BlasMatrix (const Field &F, VectorStream<StreamVector> &stream) :
_row(stream.size ()), _col(stream.dim ()), _rep(F,_row*_col)
{
VectorDomain<Field> VD(F);
StreamVector tmp(F);
typename BlasMatrix<Field,_Storage>::RowIterator p;
VectorWrapper::ensureDim (tmp, stream.dim ());
for (p = BlasMatrix<Field,_Storage>::rowBegin (); p != BlasMatrix<Field,_Storage>::rowEnd (); ++p) {
stream >> tmp;
VD.copy (*p, tmp);
}
}
template < class _Field, class _Storage >
template<class OtherMatrix>
BlasMatrix< _Field, _Storage >::BlasMatrix (const OtherMatrix &A, const _Field &F) :
_row(A.rowdim()), _col(A.coldim()), _rep(F, _row*_col)
{
//std::cout<<"GIORGI: BlasMatrix reducing mod \n";
typename OtherMatrix::template rebind<_Field>()(*this,A);
}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >::BlasMatrix (const BlasMatrix< _Field, _Storage> &A) :
_row(A.rowdim()), _col(A.coldim()),_rep(A.field(),_row*_col)
{
createBlasMatrix(A,0,0,_row,_col,MatrixContainerCategory::BlasContainer());
}
template < class _Field, class _Storage >
BlasMatrix< _Field, _Storage >& BlasMatrix< _Field, _Storage >::operator= (const BlasMatrix< _Field, _Storage >& A)
{
if ( &A == this)
return *this;
_col = A.coldim();
_row = A.rowdim();
_rep = Storage(A.field(),_row*_col);
createBlasMatrix(A,0,0,_row,_col,MatrixContainerCategory::BlasContainer());
return *this;
}
template < class _Field, class _Storage >
template < class Matrix>
BlasMatrix< _Field, _Storage >& BlasMatrix< _Field, _Storage >::operator= (const Matrix& A)
{
_col = A.coldim();
_row = A.rowdim();
_rep = Storage(A.field(),_row*_col);
createBlasMatrix(A,0,0,_row,_col,typename MatrixContainerTrait<Matrix>::Type());
return *this;
}
//! @bug other rep
template < class _Field, class _Storage >
template<typename _Tp1, typename _Rep2>
struct BlasMatrix< _Field, _Storage >::rebind {
typedef BlasMatrix<_Tp1, _Rep2> other;
void operator() (other & Ap, const Self_t& A) {
// typedef Self_t::ConstIterator ConstSelfIterator ;
typedef typename BlasMatrix< _Field, _Storage >::ConstIterator ConstSelfIterator ;
typedef typename other::Iterator OtherIterator ;
OtherIterator Ap_i = Ap.Begin();
ConstSelfIterator A_i = A.Begin();
Hom<Field, _Tp1> hom(A. field(), Ap. field()) ;
for ( ; A_i != A. End(); ++ A_i, ++ Ap_i)
hom.image (*Ap_i, *A_i);
//Ap.write(std::cout);
}
};
///////////////////
// I/O //
///////////////////
template < class _Field, class _Storage >
std::istream &BlasMatrix< _Field, _Storage >::read (std::istream &file)
{
MatrixStream<Field> ms(field(), file);
if( !ms.getArray(_rep) || !ms.getDimensions(_row, _col) ){
throw ms.reportError(__FUNCTION__,__LINE__);
}
return file;
}
template < class _Field, class _Storage >
std::ostream &BlasMatrix< _Field, _Storage >::write (std::ostream &os, Tag::FileFormat f) const
{
//std::cout<<"BlasMatrix write: "<<&(*_rep.getPointer())<<" "<<_rep<<std::endl;
constSubMatrixType B(*this);
return B.write(os,f);
}
} // end of LinBox namespace
#endif // __LINBOX_densematrix_blas_matrix_INL
// Local Variables:
// mode: C++
// tab-width: 4
// indent-tabs-mode: nil
// c-basic-offset: 4
// End:
// vim:sts=4:sw=4:ts=4:et:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|> |
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#include "catalog/PartitionSchemeHeader.hpp"
#include <cstddef>
#include <utility>
#include <vector>
#include "catalog/Catalog.pb.h"
#include "types/Type.hpp"
#include "types/Type.pb.h"
#include "types/TypeFactory.hpp"
#include "types/TypedValue.hpp"
#include "types/TypedValue.pb.h"
#include "glog/logging.h"
namespace quickstep {
PartitionSchemeHeader::PartitionSchemeHeader(const PartitionType type,
const std::size_t num_partitions,
const attribute_id attr_id)
: partition_type_(type),
num_partitions_(num_partitions),
partition_attribute_id_(attr_id) {
DCHECK_GT(num_partitions, 0u);
DCHECK_GE(attr_id, 0);
}
bool PartitionSchemeHeader::ProtoIsValid(
const serialization::PartitionSchemeHeader &proto) {
// Check that proto is fully initialized.
if (!proto.IsInitialized()) {
return false;
}
// Check if the partitioning attribute exists in the relation.
// TODO(gerald): Figure out how to find the max_attr_id of the
// relation so that we can check that partitioning attribute
// is not greater than the max_attr_id.
// Check that the proto has a valid partition type.
switch (proto.partition_type()) {
case serialization::PartitionSchemeHeader::HASH:
return true;
case serialization::PartitionSchemeHeader::RANGE: {
const std::size_t num_ranges =
proto.ExtensionSize(serialization::RangePartitionSchemeHeader::partition_range_boundaries);
return num_ranges == proto.num_partitions() - 1 &&
proto.HasExtension(serialization::RangePartitionSchemeHeader::partition_attr_type);
}
default:
// Partition type is unknown.
return false;
}
}
PartitionSchemeHeader* PartitionSchemeHeader::ReconstructFromProto(
const serialization::PartitionSchemeHeader &proto) {
DCHECK(ProtoIsValid(proto))
<< "Attempted to create PartitionSchemeHeader from an invalid proto description:\n"
<< proto.DebugString();
switch (proto.partition_type()) {
case serialization::PartitionSchemeHeader::HASH: {
return new HashPartitionSchemeHeader(proto.num_partitions(), proto.partition_attribute_id());
}
case serialization::PartitionSchemeHeader::RANGE: {
const Type &attr_type =
TypeFactory::ReconstructFromProto(proto.GetExtension(
serialization::RangePartitionSchemeHeader::partition_attr_type));
std::vector<TypedValue> partition_ranges;
for (int i = 0;
i < proto.ExtensionSize(serialization::RangePartitionSchemeHeader::partition_range_boundaries);
++i) {
partition_ranges.emplace_back(
TypedValue::ReconstructFromProto(
proto.GetExtension(serialization::RangePartitionSchemeHeader::partition_range_boundaries, i)));
}
return new RangePartitionSchemeHeader(attr_type,
proto.num_partitions(),
proto.partition_attribute_id(),
std::move(partition_ranges));
}
default:
LOG(FATAL) << "Invalid partition scheme header.";
}
}
serialization::PartitionSchemeHeader PartitionSchemeHeader::getProto() const {
serialization::PartitionSchemeHeader proto;
switch (partition_type_) {
case PartitionType::kHash:
proto.set_partition_type(serialization::PartitionSchemeHeader::HASH);
break;
case PartitionType::kRange:
LOG(FATAL) << "RangePartitionSchemeHeader should call the overridden method.";
default:
LOG(FATAL) << "Invalid Partition Type.";
}
proto.set_num_partitions(num_partitions_);
proto.set_partition_attribute_id(partition_attribute_id_);
return proto;
}
serialization::PartitionSchemeHeader RangePartitionSchemeHeader::getProto() const {
serialization::PartitionSchemeHeader proto;
proto.set_partition_type(serialization::PartitionSchemeHeader::RANGE);
proto.set_num_partitions(num_partitions_);
proto.set_partition_attribute_id(partition_attribute_id_);
proto.MutableExtension(serialization::RangePartitionSchemeHeader::partition_attr_type)
->MergeFrom(partition_attr_type_->getProto());
for (std::size_t i = 0; i < partition_range_boundaries_.size(); ++i) {
proto.AddExtension(serialization::RangePartitionSchemeHeader::partition_range_boundaries)
->MergeFrom(partition_range_boundaries_[i].getProto());
}
return proto;
}
} // namespace quickstep
<commit_msg>Minor refactored RangePartitionSchemeHeader::getProto.<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
#include "catalog/PartitionSchemeHeader.hpp"
#include <cstddef>
#include <utility>
#include <vector>
#include "catalog/Catalog.pb.h"
#include "types/Type.hpp"
#include "types/Type.pb.h"
#include "types/TypeFactory.hpp"
#include "types/TypedValue.hpp"
#include "types/TypedValue.pb.h"
#include "glog/logging.h"
namespace quickstep {
PartitionSchemeHeader::PartitionSchemeHeader(const PartitionType type,
const std::size_t num_partitions,
const attribute_id attr_id)
: partition_type_(type),
num_partitions_(num_partitions),
partition_attribute_id_(attr_id) {
DCHECK_GT(num_partitions, 0u);
DCHECK_GE(attr_id, 0);
}
bool PartitionSchemeHeader::ProtoIsValid(
const serialization::PartitionSchemeHeader &proto) {
// Check that proto is fully initialized.
if (!proto.IsInitialized()) {
return false;
}
// Check if the partitioning attribute exists in the relation.
// TODO(gerald): Figure out how to find the max_attr_id of the
// relation so that we can check that partitioning attribute
// is not greater than the max_attr_id.
// Check that the proto has a valid partition type.
switch (proto.partition_type()) {
case serialization::PartitionSchemeHeader::HASH:
return true;
case serialization::PartitionSchemeHeader::RANGE: {
const std::size_t num_ranges =
proto.ExtensionSize(serialization::RangePartitionSchemeHeader::partition_range_boundaries);
return num_ranges == proto.num_partitions() - 1 &&
proto.HasExtension(serialization::RangePartitionSchemeHeader::partition_attr_type);
}
default:
// Partition type is unknown.
return false;
}
}
PartitionSchemeHeader* PartitionSchemeHeader::ReconstructFromProto(
const serialization::PartitionSchemeHeader &proto) {
DCHECK(ProtoIsValid(proto))
<< "Attempted to create PartitionSchemeHeader from an invalid proto description:\n"
<< proto.DebugString();
switch (proto.partition_type()) {
case serialization::PartitionSchemeHeader::HASH: {
return new HashPartitionSchemeHeader(proto.num_partitions(), proto.partition_attribute_id());
}
case serialization::PartitionSchemeHeader::RANGE: {
const Type &attr_type =
TypeFactory::ReconstructFromProto(proto.GetExtension(
serialization::RangePartitionSchemeHeader::partition_attr_type));
std::vector<TypedValue> partition_ranges;
for (int i = 0;
i < proto.ExtensionSize(serialization::RangePartitionSchemeHeader::partition_range_boundaries);
++i) {
partition_ranges.emplace_back(
TypedValue::ReconstructFromProto(
proto.GetExtension(serialization::RangePartitionSchemeHeader::partition_range_boundaries, i)));
}
return new RangePartitionSchemeHeader(attr_type,
proto.num_partitions(),
proto.partition_attribute_id(),
std::move(partition_ranges));
}
default:
LOG(FATAL) << "Invalid partition scheme header.";
}
}
serialization::PartitionSchemeHeader PartitionSchemeHeader::getProto() const {
serialization::PartitionSchemeHeader proto;
switch (partition_type_) {
case PartitionType::kHash:
proto.set_partition_type(serialization::PartitionSchemeHeader::HASH);
break;
case PartitionType::kRange:
proto.set_partition_type(serialization::PartitionSchemeHeader::RANGE);
break;
default:
LOG(FATAL) << "Invalid Partition Type.";
}
proto.set_num_partitions(num_partitions_);
proto.set_partition_attribute_id(partition_attribute_id_);
return proto;
}
serialization::PartitionSchemeHeader RangePartitionSchemeHeader::getProto() const {
serialization::PartitionSchemeHeader proto = PartitionSchemeHeader::getProto();
proto.MutableExtension(serialization::RangePartitionSchemeHeader::partition_attr_type)
->MergeFrom(partition_attr_type_->getProto());
for (std::size_t i = 0; i < partition_range_boundaries_.size(); ++i) {
proto.AddExtension(serialization::RangePartitionSchemeHeader::partition_range_boundaries)
->MergeFrom(partition_range_boundaries_[i].getProto());
}
return proto;
}
} // namespace quickstep
<|endoftext|> |
<commit_before>/**
* Copyright 2011-2015 Quickstep Technologies LLC.
* Copyright 2015-2016 Pivotal Software, 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.
**/
#ifndef QUICKSTEP_CATALOG_PARTITION_SCHEME_HEADER_HPP_
#define QUICKSTEP_CATALOG_PARTITION_SCHEME_HEADER_HPP_
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
#include "catalog/Catalog.pb.h"
#include "catalog/CatalogTypedefs.hpp"
#include "types/TypedValue.hpp"
#include "types/operations/comparisons/Comparison.hpp"
#include "types/operations/comparisons/LessComparison.hpp"
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
class Type;
/** \addtogroup Catalog
* @{
*/
/**
* @brief The base class which stores the partitioning information for a
* particular relation.
**/
class PartitionSchemeHeader {
public:
enum PartitionType {
kHash = 0,
kRange
};
/**
* @brief Virtual destructor.
**/
virtual ~PartitionSchemeHeader() {
}
/**
* @brief Reconstruct a PartitionSchemeHeader from its serialized
* Protocol Buffer form.
*
* @param proto The Protocol Buffer serialization of a PartitionSchemeHeader,
* previously produced by getProto().
* @param attr_type The attribute type of the partitioning attribute.
* @return The reconstructed PartitionSchemeHeader object.
**/
static PartitionSchemeHeader* ReconstructFromProto(
const serialization::PartitionSchemeHeader &proto,
const Type &attr_type);
/**
* @brief Check whether a serialization::PartitionSchemeHeader is fully-formed
* and all parts are valid.
*
* @param proto A serialized Protocol Buffer representation of a
* PartitionSchemeHeader, originally generated by getProto().
* @return Whether proto is fully-formed and valid.
**/
static bool ProtoIsValid(const serialization::PartitionSchemeHeader &proto);
/**
* @brief Calculate the partition id into which the attribute value should
* be inserted.
*
* @param value_of_attribute The attribute value for which the
* partition id is to be determined.
* @return The partition id of the partition for the attribute value.
**/
// TODO(gerald): Make this method more efficient since currently this is
// done for each and every tuple. We can go through the entire set of tuples
// once using a value accessor and create bitmaps for each partition with
// tuples that correspond to those partitions.
virtual partition_id getPartitionId(
const TypedValue &value_of_attribute) const = 0;
/**
* @brief Serialize the Partition Scheme as Protocol Buffer.
*
* @return The Protocol Buffer representation of Partition Scheme.
**/
virtual serialization::PartitionSchemeHeader getProto() const;
/**
* @brief Get the partition type of the relation.
*
* @return The partition type used to partition the relation.
**/
inline PartitionType getPartitionType() const {
return partition_type_;
}
/**
* @brief Get the number of partitions for the relation.
*
* @return The number of partitions the relation is partitioned into.
**/
inline std::size_t getNumPartitions() const {
return num_partitions_;
}
/**
* @brief Get the partitioning attribute for the relation.
*
* @return The partitioning attribute with which the relation
* is partitioned into.
**/
inline attribute_id getPartitionAttributeId() const {
return partition_attribute_id_;
}
protected:
/**
* @brief Constructor.
*
* @param type The type of partitioning to be used to partition the
* relation.
* @param num_partitions The number of partitions to be created.
* @param attr_id The attribute on which the partitioning happens.
**/
PartitionSchemeHeader(const PartitionType type,
const std::size_t num_partitions,
const attribute_id attr_id);
// The type of partitioning: Hash or Range.
const PartitionType partition_type_;
// The number of partitions.
const std::size_t num_partitions_;
// The attribute of partioning.
const attribute_id partition_attribute_id_;
private:
DISALLOW_COPY_AND_ASSIGN(PartitionSchemeHeader);
};
/**
* @brief Implementation of PartitionSchemeHeader that partitions the tuples in
* a relation based on a hash function on the partitioning attribute.
**/
class HashPartitionSchemeHeader : public PartitionSchemeHeader {
public:
/**
* @brief Constructor.
*
* @param num_partitions The number of partitions to be created.
* @param attribute The attribute on which the partitioning happens.
**/
HashPartitionSchemeHeader(const std::size_t num_partitions, const attribute_id attribute)
: PartitionSchemeHeader(PartitionType::kHash, num_partitions, attribute) {
}
/**
* @brief Destructor.
**/
~HashPartitionSchemeHeader() override {
}
/**
* @brief Calulate the partition id into which the attribute value
* should be inserted.
*
* @param value_of_attribute The attribute value for which the
* partition id is to be determined.
* @return The partition id of the partition for the attribute value.
**/
partition_id getPartitionId(
const TypedValue &value_of_attribute) const override {
// TODO(gerald): Optimize for the case where the number of partitions is a
// power of 2. We can just mask out the lower-order hash bits rather than
// doing a division operation.
return value_of_attribute.getHash() % num_partitions_;
}
private:
DISALLOW_COPY_AND_ASSIGN(HashPartitionSchemeHeader);
};
/**
* @brief Implementation of PartitionSchemeHeader that partitions the tuples in
* a relation based on a given value range on the partitioning attribute.
**/
class RangePartitionSchemeHeader : public PartitionSchemeHeader {
public:
/**
* @brief Constructor.
*
* @param partition_attribute_type The type of CatalogAttribute that is used
* for partitioning.
* @param num_partitions The number of partitions to be created.
* @param attribute The attribute_id on which the partitioning happens.
* @param partition_range The mapping between the partition ids and the upper
* bound of the range boundaries. If two ranges R1 and
* R2 are separated by a boundary value V, then V
* would fall into range R2. For creating a range
* partition scheme with n partitions, you need to
* specify n-1 boundary values. The first partition
* will have all the values less than the first
* boundary and the last partition would have all
* values greater than or equal to the last boundary
* value.
**/
RangePartitionSchemeHeader(const Type &partition_attribute_type,
const std::size_t num_partitions,
const attribute_id attribute,
std::vector<TypedValue> &&partition_range)
: PartitionSchemeHeader(PartitionType::kRange, num_partitions, attribute),
partition_range_boundaries_(std::move(partition_range)) {
DCHECK_EQ(num_partitions - 1, partition_range_boundaries_.size());
const Comparison &less_comparison_op(LessComparison::Instance());
less_unchecked_comparator_.reset(
less_comparison_op.makeUncheckedComparatorForTypes(
partition_attribute_type, partition_attribute_type));
#ifdef QUICKSTEP_DEBUG
checkPartitionRangeBoundaries();
#endif
}
/**
* @brief Destructor.
**/
~RangePartitionSchemeHeader() override {
}
/**
* @brief Calulate the partition id into which the attribute value
* should be inserted.
*
* @param value_of_attribute The attribute value for which the
* partition id is to be determined.
* @return The partition id of the partition for the attribute value.
**/
partition_id getPartitionId(
const TypedValue &value_of_attribute) const override {
partition_id part_id = 0;
for (part_id = 0; part_id < num_partitions_ - 1; ++part_id) {
const TypedValue &partition_delimiter =
partition_range_boundaries_[part_id];
if (less_unchecked_comparator_->compareTypedValues(
value_of_attribute, partition_delimiter)) {
return part_id;
}
}
return part_id;
}
serialization::PartitionSchemeHeader getProto() const override;
/**
* @brief Get the range boundaries for partitions.
*
* @return The vector of range boundaries for partitions.
**/
inline const std::vector<TypedValue>& getPartitionRangeBoundaries() const {
return partition_range_boundaries_;
}
private:
/**
* @brief Check if the partition range boundaries are in ascending order.
**/
void checkPartitionRangeBoundaries() {
for (partition_id part_id = 1; part_id < partition_range_boundaries_.size(); ++part_id) {
if (less_unchecked_comparator_->compareTypedValues(
partition_range_boundaries_[part_id],
partition_range_boundaries_[part_id - 1])) {
LOG(FATAL) << "Partition boundaries are not in ascending order.";
}
}
}
// The boundaries for each range in the RangePartitionSchemeHeader.
// The upper bound of the range is stored here.
const std::vector<TypedValue> partition_range_boundaries_;
std::unique_ptr<UncheckedComparator> less_unchecked_comparator_;
DISALLOW_COPY_AND_ASSIGN(RangePartitionSchemeHeader);
};
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_CATALOG_PARTITION_SCHEME_HEADER_HPP_
<commit_msg>Use the binary search to get range partition id.<commit_after>/**
* Copyright 2011-2015 Quickstep Technologies LLC.
* Copyright 2015-2016 Pivotal Software, 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.
**/
#ifndef QUICKSTEP_CATALOG_PARTITION_SCHEME_HEADER_HPP_
#define QUICKSTEP_CATALOG_PARTITION_SCHEME_HEADER_HPP_
#include <cstddef>
#include <memory>
#include <utility>
#include <vector>
#include "catalog/Catalog.pb.h"
#include "catalog/CatalogTypedefs.hpp"
#include "types/TypedValue.hpp"
#include "types/operations/comparisons/Comparison.hpp"
#include "types/operations/comparisons/LessComparison.hpp"
#include "utility/Macros.hpp"
#include "glog/logging.h"
namespace quickstep {
class Type;
/** \addtogroup Catalog
* @{
*/
/**
* @brief The base class which stores the partitioning information for a
* particular relation.
**/
class PartitionSchemeHeader {
public:
enum PartitionType {
kHash = 0,
kRange
};
/**
* @brief Virtual destructor.
**/
virtual ~PartitionSchemeHeader() {
}
/**
* @brief Reconstruct a PartitionSchemeHeader from its serialized
* Protocol Buffer form.
*
* @param proto The Protocol Buffer serialization of a PartitionSchemeHeader,
* previously produced by getProto().
* @param attr_type The attribute type of the partitioning attribute.
* @return The reconstructed PartitionSchemeHeader object.
**/
static PartitionSchemeHeader* ReconstructFromProto(
const serialization::PartitionSchemeHeader &proto,
const Type &attr_type);
/**
* @brief Check whether a serialization::PartitionSchemeHeader is fully-formed
* and all parts are valid.
*
* @param proto A serialized Protocol Buffer representation of a
* PartitionSchemeHeader, originally generated by getProto().
* @return Whether proto is fully-formed and valid.
**/
static bool ProtoIsValid(const serialization::PartitionSchemeHeader &proto);
/**
* @brief Calculate the partition id into which the attribute value should
* be inserted.
*
* @param value_of_attribute The attribute value for which the
* partition id is to be determined.
* @return The partition id of the partition for the attribute value.
**/
// TODO(gerald): Make this method more efficient since currently this is
// done for each and every tuple. We can go through the entire set of tuples
// once using a value accessor and create bitmaps for each partition with
// tuples that correspond to those partitions.
virtual partition_id getPartitionId(
const TypedValue &value_of_attribute) const = 0;
/**
* @brief Serialize the Partition Scheme as Protocol Buffer.
*
* @return The Protocol Buffer representation of Partition Scheme.
**/
virtual serialization::PartitionSchemeHeader getProto() const;
/**
* @brief Get the partition type of the relation.
*
* @return The partition type used to partition the relation.
**/
inline PartitionType getPartitionType() const {
return partition_type_;
}
/**
* @brief Get the number of partitions for the relation.
*
* @return The number of partitions the relation is partitioned into.
**/
inline std::size_t getNumPartitions() const {
return num_partitions_;
}
/**
* @brief Get the partitioning attribute for the relation.
*
* @return The partitioning attribute with which the relation
* is partitioned into.
**/
inline attribute_id getPartitionAttributeId() const {
return partition_attribute_id_;
}
protected:
/**
* @brief Constructor.
*
* @param type The type of partitioning to be used to partition the
* relation.
* @param num_partitions The number of partitions to be created.
* @param attr_id The attribute on which the partitioning happens.
**/
PartitionSchemeHeader(const PartitionType type,
const std::size_t num_partitions,
const attribute_id attr_id);
// The type of partitioning: Hash or Range.
const PartitionType partition_type_;
// The number of partitions.
const std::size_t num_partitions_;
// The attribute of partioning.
const attribute_id partition_attribute_id_;
private:
DISALLOW_COPY_AND_ASSIGN(PartitionSchemeHeader);
};
/**
* @brief Implementation of PartitionSchemeHeader that partitions the tuples in
* a relation based on a hash function on the partitioning attribute.
**/
class HashPartitionSchemeHeader : public PartitionSchemeHeader {
public:
/**
* @brief Constructor.
*
* @param num_partitions The number of partitions to be created.
* @param attribute The attribute on which the partitioning happens.
**/
HashPartitionSchemeHeader(const std::size_t num_partitions, const attribute_id attribute)
: PartitionSchemeHeader(PartitionType::kHash, num_partitions, attribute) {
}
/**
* @brief Destructor.
**/
~HashPartitionSchemeHeader() override {
}
/**
* @brief Calulate the partition id into which the attribute value
* should be inserted.
*
* @param value_of_attribute The attribute value for which the
* partition id is to be determined.
* @return The partition id of the partition for the attribute value.
**/
partition_id getPartitionId(
const TypedValue &value_of_attribute) const override {
// TODO(gerald): Optimize for the case where the number of partitions is a
// power of 2. We can just mask out the lower-order hash bits rather than
// doing a division operation.
return value_of_attribute.getHash() % num_partitions_;
}
private:
DISALLOW_COPY_AND_ASSIGN(HashPartitionSchemeHeader);
};
/**
* @brief Implementation of PartitionSchemeHeader that partitions the tuples in
* a relation based on a given value range on the partitioning attribute.
**/
class RangePartitionSchemeHeader : public PartitionSchemeHeader {
public:
/**
* @brief Constructor.
*
* @param partition_attribute_type The type of CatalogAttribute that is used
* for partitioning.
* @param num_partitions The number of partitions to be created.
* @param attribute The attribute_id on which the partitioning happens.
* @param partition_range The mapping between the partition ids and the upper
* bound of the range boundaries. If two ranges R1 and
* R2 are separated by a boundary value V, then V
* would fall into range R2. For creating a range
* partition scheme with n partitions, you need to
* specify n-1 boundary values. The first partition
* will have all the values less than the first
* boundary and the last partition would have all
* values greater than or equal to the last boundary
* value.
**/
RangePartitionSchemeHeader(const Type &partition_attribute_type,
const std::size_t num_partitions,
const attribute_id attribute,
std::vector<TypedValue> &&partition_range)
: PartitionSchemeHeader(PartitionType::kRange, num_partitions, attribute),
partition_range_boundaries_(std::move(partition_range)) {
DCHECK_EQ(num_partitions - 1, partition_range_boundaries_.size());
const Comparison &less_comparison_op(LessComparison::Instance());
less_unchecked_comparator_.reset(
less_comparison_op.makeUncheckedComparatorForTypes(
partition_attribute_type, partition_attribute_type));
#ifdef QUICKSTEP_DEBUG
checkPartitionRangeBoundaries();
#endif
}
/**
* @brief Destructor.
**/
~RangePartitionSchemeHeader() override {
}
/**
* @brief Calulate the partition id into which the attribute value
* should be inserted.
*
* @param value_of_attribute The attribute value for which the
* partition id is to be determined.
* @return The partition id of the partition for the attribute value.
**/
partition_id getPartitionId(
const TypedValue &value_of_attribute) const override {
partition_id start = 0, end = partition_range_boundaries_.size() - 1;
if (!less_unchecked_comparator_->compareTypedValues(value_of_attribute, partition_range_boundaries_[end])) {
return num_partitions_ - 1;
}
while (start < end) {
const partition_id mid = start + ((end - start) >> 1);
if (less_unchecked_comparator_->compareTypedValues(value_of_attribute, partition_range_boundaries_[mid])) {
end = mid;
} else {
start = mid + 1;
}
}
return start;
}
serialization::PartitionSchemeHeader getProto() const override;
/**
* @brief Get the range boundaries for partitions.
*
* @return The vector of range boundaries for partitions.
**/
inline const std::vector<TypedValue>& getPartitionRangeBoundaries() const {
return partition_range_boundaries_;
}
private:
/**
* @brief Check if the partition range boundaries are in ascending order.
**/
void checkPartitionRangeBoundaries() {
for (partition_id part_id = 1; part_id < partition_range_boundaries_.size(); ++part_id) {
if (less_unchecked_comparator_->compareTypedValues(
partition_range_boundaries_[part_id],
partition_range_boundaries_[part_id - 1])) {
LOG(FATAL) << "Partition boundaries are not in ascending order.";
}
}
}
// The boundaries for each range in the RangePartitionSchemeHeader.
// The upper bound of the range is stored here.
const std::vector<TypedValue> partition_range_boundaries_;
std::unique_ptr<UncheckedComparator> less_unchecked_comparator_;
DISALLOW_COPY_AND_ASSIGN(RangePartitionSchemeHeader);
};
/** @} */
} // namespace quickstep
#endif // QUICKSTEP_CATALOG_PARTITION_SCHEME_HEADER_HPP_
<|endoftext|> |
<commit_before>#include "SVM.h"
#include "TrainData.h"
#include "ParamGrid.h"
#include "Mat.h"
Nan::Persistent<v8::FunctionTemplate> SVM::constructor;
NAN_MODULE_INIT(SVM::Init) {
v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(SVM::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("SVM").ToLocalChecked());
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("c"), c);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("coef0"), coef0);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("degree"), degree);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("gamma"), gamma);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("nu"), nu);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("p"), p);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("kernelType"), kernelType);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("classWeights"), classWeights);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("varCount"), varCount);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("isTrained"), isTrained);
Nan::SetPrototypeMethod(ctor, "setParams", SetParams);
Nan::SetPrototypeMethod(ctor, "train", Train);
Nan::SetPrototypeMethod(ctor, "trainAuto", TrainAuto);
Nan::SetPrototypeMethod(ctor, "predict", Predict);
Nan::SetPrototypeMethod(ctor, "getSupportVectors", GetSupportVectors);
Nan::SetPrototypeMethod(ctor, "getUncompressedSupportVectors", GetUncompressedSupportVectors);
Nan::SetPrototypeMethod(ctor, "calcError", CalcError);
Nan::SetPrototypeMethod(ctor, "save", Save);
Nan::SetPrototypeMethod(ctor, "load", Load);
target->Set(Nan::New("SVM").ToLocalChecked(), ctor->GetFunction());
};
NAN_METHOD(SVM::New) {
FF_METHOD_CONTEXT("SVM::New");
SVM* self = new SVM();
self->svm = cv::ml::SVM::create();
if (info.Length() > 0) {
FF_ARG_OBJ(0, FF_OBJ args);
Nan::TryCatch tryCatch;
self->setParams(args);
if (tryCatch.HasCaught()) {
tryCatch.ReThrow();
}
}
self->Wrap(info.Holder());
FF_RETURN(info.Holder());
};
NAN_METHOD(SVM::SetParams) {
FF_REQUIRE_ARGS_OBJ("SVM::SetParams");
Nan::TryCatch tryCatch;
FF_UNWRAP(info.This(), SVM)->setParams(args);
if (tryCatch.HasCaught()) {
tryCatch.ReThrow();
}
FF_RETURN(info.This());
};
NAN_METHOD(SVM::Train) {
FF_METHOD_CONTEXT("SVM::Train");
if (!FF_IS_INSTANCE(TrainData::constructor, info[0]) && !FF_IS_INSTANCE(Mat::constructor, info[0])) {
FF_THROW("expected arg 0 to be an instance of TrainData or Mat");
}
SVM* self = FF_UNWRAP(info.This(), SVM);
FF_VAL ret;
if (FF_IS_INSTANCE(TrainData::constructor, info[0])) {
FF_ARG_INSTANCE(0, cv::Ptr<cv::ml::TrainData> trainData, TrainData::constructor, FF_UNWRAP_TRAINDATA_AND_GET);
FF_ARG_UINT_IFDEF(1, unsigned int flags, 0);
ret = Nan::New(self->svm->train(trainData, flags));
}
else {
FF_ARG_INSTANCE(0, cv::Mat samples, Mat::constructor, FF_UNWRAP_MAT_AND_GET);
FF_ARG_UINT(1, unsigned int layout);
FF_ARG_INSTANCE(2, cv::Mat responses, Mat::constructor, FF_UNWRAP_MAT_AND_GET);
ret = Nan::New(self->svm->train(samples, (int)layout, responses));
}
FF_RETURN(ret);
}
NAN_METHOD(SVM::TrainAuto) {
FF_METHOD_CONTEXT("SVM::TrainAuto");
// required args
FF_ARG_INSTANCE(0, cv::Ptr<cv::ml::TrainData> trainData, TrainData::constructor, FF_UNWRAP_TRAINDATA_AND_GET);
// optional args
bool hasOptArgsObj = FF_HAS_ARG(1) && !info[1]->IsUint32();
FF_OBJ optArgs = hasOptArgsObj ? info[1]->ToObject() : FF_NEW_OBJ();
FF_GET_UINT_IFDEF(optArgs, unsigned int kFold, "kFold", 10);
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid cGrid, "cGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::C));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid gammaGrid, "gammaGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::GAMMA));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid pGrid, "pGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::P));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid nuGrid, "nuGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::NU));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid coeffGrid, "coeffGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::COEF));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid degreeGrid, "degreeGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::DEGREE));
FF_GET_BOOL_IFDEF(optArgs, bool balanced, "balanced", false);
if (!hasOptArgsObj) {
FF_ARG_UINT_IFDEF(1, kFold, kFold);
FF_ARG_INSTANCE_IFDEF(2, cGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, cGrid);
FF_ARG_INSTANCE_IFDEF(3, gammaGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, gammaGrid);
FF_ARG_INSTANCE_IFDEF(4, pGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, pGrid);
FF_ARG_INSTANCE_IFDEF(5, nuGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, nuGrid);
FF_ARG_INSTANCE_IFDEF(6, coeffGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, coeffGrid);
FF_ARG_INSTANCE_IFDEF(7, degreeGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, degreeGrid);
FF_ARG_BOOL_IFDEF(8, balanced, balanced);
}
bool ret = FF_UNWRAP(info.This(), SVM)->svm->trainAuto(trainData, (int)kFold, cGrid, gammaGrid, pGrid, nuGrid, coeffGrid, degreeGrid, balanced);
FF_RETURN(Nan::New(ret));
}
NAN_METHOD(SVM::Predict) {
FF_METHOD_CONTEXT("SVM::Predict");
if (!info[0]->IsArray() && !FF_IS_INSTANCE(Mat::constructor, info[0])) {
FF_THROW("expected arg 0 to be an ARRAY or an instance of Mat");
}
cv::Mat results;
if (info[0]->IsArray()) {
FF_ARG_UNPACK_FLOAT_ARRAY(0, samples);
FF_ARG_UINT_IFDEF(1, unsigned int flags, 0);
FF_UNWRAP(info.This(), SVM)->svm->predict(samples, results, (int)flags);
}
else {
FF_ARG_INSTANCE(0, cv::Mat samples, Mat::constructor, FF_UNWRAP_MAT_AND_GET);
FF_ARG_UINT_IFDEF(1, unsigned int flags, 0);
FF_UNWRAP(info.This(), SVM)->svm->predict(samples, results, (int)flags);
}
FF_VAL jsResult;
if (results.cols == 1 && results.rows == 1) {
jsResult = Nan::New((double)results.at<float>(0, 0));
}
else {
std::vector<float> resultsVec;
results.col(0).copyTo(resultsVec);
FF_PACK_ARRAY(resultArray, resultsVec);
jsResult = resultArray;
}
FF_RETURN(jsResult);
}
NAN_METHOD(SVM::GetSupportVectors) {
FF_OBJ jsSupportVectors = FF_NEW_INSTANCE(Mat::constructor);
FF_UNWRAP_MAT_AND_GET(jsSupportVectors) = FF_UNWRAP(info.This(), SVM)->svm->getSupportVectors();
FF_RETURN(jsSupportVectors);
}
NAN_METHOD(SVM::GetUncompressedSupportVectors) {
FF_METHOD_CONTEXT("SVM::GetUncompressedSupportVectors");
#if CV_VERSION_MINOR < 2
FF_THROW("getUncompressedSupportVectors not implemented for v3.0, v3.1");
#else
FF_OBJ jsSupportVectors = FF_NEW_INSTANCE(Mat::constructor);
FF_UNWRAP_MAT_AND_GET(jsSupportVectors) = FF_UNWRAP(info.This(), SVM)->svm->getUncompressedSupportVectors();
FF_RETURN(jsSupportVectors);
#endif
}
NAN_METHOD(SVM::CalcError) {
FF_METHOD_CONTEXT("SVM::CalcError");
FF_ARG_INSTANCE(0, cv::Ptr<cv::ml::TrainData> trainData, TrainData::constructor, FF_UNWRAP_TRAINDATA_AND_GET);
FF_ARG_BOOL(1, bool test);
FF_OBJ jsResponses = FF_NEW_INSTANCE(Mat::constructor);
float error = FF_UNWRAP(info.This(), SVM)->svm->calcError(trainData, test, FF_UNWRAP_MAT_AND_GET(jsResponses));
FF_OBJ ret = FF_NEW_OBJ();
Nan::Set(ret, FF_NEW_STRING("error"), Nan::New((double)error));
Nan::Set(ret, FF_NEW_STRING("responses"), jsResponses);
FF_RETURN(ret);
}
NAN_METHOD(SVM::Save) {
FF_METHOD_CONTEXT("SVM::Save");
FF_ARG_STRING(0, std::string path);
FF_UNWRAP(info.This(), SVM)->svm->save(path);
}
NAN_METHOD(SVM::Load) {
FF_METHOD_CONTEXT("SVM::Load");
FF_ARG_STRING(0, std::string path);
FF_UNWRAP(info.This(), SVM)->svm = FF_UNWRAP(info.This(), SVM)->svm->load(path);
}
void SVM::setParams(v8::Local<v8::Object> params) {
FF_METHOD_CONTEXT("SVM::SetParams");
FF_GET_NUMBER_IFDEF(params, double c, "c", this->svm->getC());
FF_GET_NUMBER_IFDEF(params, double coef0, "coef0", this->svm->getCoef0());
FF_GET_NUMBER_IFDEF(params, double degree, "degree", this->svm->getDegree());
FF_GET_NUMBER_IFDEF(params, double gamma, "gamma", this->svm->getGamma());
FF_GET_NUMBER_IFDEF(params, double nu, "nu", this->svm->getNu());
FF_GET_NUMBER_IFDEF(params, double p, "p", this->svm->getP());
FF_GET_NUMBER_IFDEF(params, unsigned int kernelType, "kernelType", this->svm->getKernelType());
FF_GET_INSTANCE_IFDEF(params, cv::Mat classWeights, "classWeights", Mat::constructor, FF_UNWRAP_MAT_AND_GET, Mat, this->svm->getClassWeights());
this->svm->setC(c);
this->svm->setCoef0(coef0);
this->svm->setDegree(degree);
this->svm->setGamma(gamma);
this->svm->setNu(nu);
this->svm->setP(p);
this->svm->setKernel(kernelType);
this->svm->setClassWeights(classWeights);
}<commit_msg>SVM load needs to be ported to 3.0, 3.1<commit_after>#include "SVM.h"
#include "TrainData.h"
#include "ParamGrid.h"
#include "Mat.h"
Nan::Persistent<v8::FunctionTemplate> SVM::constructor;
NAN_MODULE_INIT(SVM::Init) {
v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(SVM::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("SVM").ToLocalChecked());
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("c"), c);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("coef0"), coef0);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("degree"), degree);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("gamma"), gamma);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("nu"), nu);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("p"), p);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("kernelType"), kernelType);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("classWeights"), classWeights);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("varCount"), varCount);
Nan::SetAccessor(ctor->InstanceTemplate(), FF_NEW_STRING("isTrained"), isTrained);
Nan::SetPrototypeMethod(ctor, "setParams", SetParams);
Nan::SetPrototypeMethod(ctor, "train", Train);
Nan::SetPrototypeMethod(ctor, "trainAuto", TrainAuto);
Nan::SetPrototypeMethod(ctor, "predict", Predict);
Nan::SetPrototypeMethod(ctor, "getSupportVectors", GetSupportVectors);
Nan::SetPrototypeMethod(ctor, "getUncompressedSupportVectors", GetUncompressedSupportVectors);
Nan::SetPrototypeMethod(ctor, "calcError", CalcError);
Nan::SetPrototypeMethod(ctor, "save", Save);
Nan::SetPrototypeMethod(ctor, "load", Load);
target->Set(Nan::New("SVM").ToLocalChecked(), ctor->GetFunction());
};
NAN_METHOD(SVM::New) {
FF_METHOD_CONTEXT("SVM::New");
SVM* self = new SVM();
self->svm = cv::ml::SVM::create();
if (info.Length() > 0) {
FF_ARG_OBJ(0, FF_OBJ args);
Nan::TryCatch tryCatch;
self->setParams(args);
if (tryCatch.HasCaught()) {
tryCatch.ReThrow();
}
}
self->Wrap(info.Holder());
FF_RETURN(info.Holder());
};
NAN_METHOD(SVM::SetParams) {
FF_REQUIRE_ARGS_OBJ("SVM::SetParams");
Nan::TryCatch tryCatch;
FF_UNWRAP(info.This(), SVM)->setParams(args);
if (tryCatch.HasCaught()) {
tryCatch.ReThrow();
}
FF_RETURN(info.This());
};
NAN_METHOD(SVM::Train) {
FF_METHOD_CONTEXT("SVM::Train");
if (!FF_IS_INSTANCE(TrainData::constructor, info[0]) && !FF_IS_INSTANCE(Mat::constructor, info[0])) {
FF_THROW("expected arg 0 to be an instance of TrainData or Mat");
}
SVM* self = FF_UNWRAP(info.This(), SVM);
FF_VAL ret;
if (FF_IS_INSTANCE(TrainData::constructor, info[0])) {
FF_ARG_INSTANCE(0, cv::Ptr<cv::ml::TrainData> trainData, TrainData::constructor, FF_UNWRAP_TRAINDATA_AND_GET);
FF_ARG_UINT_IFDEF(1, unsigned int flags, 0);
ret = Nan::New(self->svm->train(trainData, flags));
}
else {
FF_ARG_INSTANCE(0, cv::Mat samples, Mat::constructor, FF_UNWRAP_MAT_AND_GET);
FF_ARG_UINT(1, unsigned int layout);
FF_ARG_INSTANCE(2, cv::Mat responses, Mat::constructor, FF_UNWRAP_MAT_AND_GET);
ret = Nan::New(self->svm->train(samples, (int)layout, responses));
}
FF_RETURN(ret);
}
NAN_METHOD(SVM::TrainAuto) {
FF_METHOD_CONTEXT("SVM::TrainAuto");
// required args
FF_ARG_INSTANCE(0, cv::Ptr<cv::ml::TrainData> trainData, TrainData::constructor, FF_UNWRAP_TRAINDATA_AND_GET);
// optional args
bool hasOptArgsObj = FF_HAS_ARG(1) && !info[1]->IsUint32();
FF_OBJ optArgs = hasOptArgsObj ? info[1]->ToObject() : FF_NEW_OBJ();
FF_GET_UINT_IFDEF(optArgs, unsigned int kFold, "kFold", 10);
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid cGrid, "cGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::C));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid gammaGrid, "gammaGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::GAMMA));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid pGrid, "pGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::P));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid nuGrid, "nuGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::NU));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid coeffGrid, "coeffGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::COEF));
FF_GET_INSTANCE_IFDEF(optArgs, cv::ml::ParamGrid degreeGrid, "degreeGrid", ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, ParamGrid, cv::ml::SVM::getDefaultGrid(cv::ml::SVM::DEGREE));
FF_GET_BOOL_IFDEF(optArgs, bool balanced, "balanced", false);
if (!hasOptArgsObj) {
FF_ARG_UINT_IFDEF(1, kFold, kFold);
FF_ARG_INSTANCE_IFDEF(2, cGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, cGrid);
FF_ARG_INSTANCE_IFDEF(3, gammaGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, gammaGrid);
FF_ARG_INSTANCE_IFDEF(4, pGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, pGrid);
FF_ARG_INSTANCE_IFDEF(5, nuGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, nuGrid);
FF_ARG_INSTANCE_IFDEF(6, coeffGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, coeffGrid);
FF_ARG_INSTANCE_IFDEF(7, degreeGrid, ParamGrid::constructor, FF_UNWRAP_PARAMGRID_AND_GET, degreeGrid);
FF_ARG_BOOL_IFDEF(8, balanced, balanced);
}
bool ret = FF_UNWRAP(info.This(), SVM)->svm->trainAuto(trainData, (int)kFold, cGrid, gammaGrid, pGrid, nuGrid, coeffGrid, degreeGrid, balanced);
FF_RETURN(Nan::New(ret));
}
NAN_METHOD(SVM::Predict) {
FF_METHOD_CONTEXT("SVM::Predict");
if (!info[0]->IsArray() && !FF_IS_INSTANCE(Mat::constructor, info[0])) {
FF_THROW("expected arg 0 to be an ARRAY or an instance of Mat");
}
cv::Mat results;
if (info[0]->IsArray()) {
FF_ARG_UNPACK_FLOAT_ARRAY(0, samples);
FF_ARG_UINT_IFDEF(1, unsigned int flags, 0);
FF_UNWRAP(info.This(), SVM)->svm->predict(samples, results, (int)flags);
}
else {
FF_ARG_INSTANCE(0, cv::Mat samples, Mat::constructor, FF_UNWRAP_MAT_AND_GET);
FF_ARG_UINT_IFDEF(1, unsigned int flags, 0);
FF_UNWRAP(info.This(), SVM)->svm->predict(samples, results, (int)flags);
}
FF_VAL jsResult;
if (results.cols == 1 && results.rows == 1) {
jsResult = Nan::New((double)results.at<float>(0, 0));
}
else {
std::vector<float> resultsVec;
results.col(0).copyTo(resultsVec);
FF_PACK_ARRAY(resultArray, resultsVec);
jsResult = resultArray;
}
FF_RETURN(jsResult);
}
NAN_METHOD(SVM::GetSupportVectors) {
FF_OBJ jsSupportVectors = FF_NEW_INSTANCE(Mat::constructor);
FF_UNWRAP_MAT_AND_GET(jsSupportVectors) = FF_UNWRAP(info.This(), SVM)->svm->getSupportVectors();
FF_RETURN(jsSupportVectors);
}
NAN_METHOD(SVM::GetUncompressedSupportVectors) {
FF_METHOD_CONTEXT("SVM::GetUncompressedSupportVectors");
#if CV_VERSION_MINOR < 2
FF_THROW("getUncompressedSupportVectors not implemented for v3.0, v3.1");
#else
FF_OBJ jsSupportVectors = FF_NEW_INSTANCE(Mat::constructor);
FF_UNWRAP_MAT_AND_GET(jsSupportVectors) = FF_UNWRAP(info.This(), SVM)->svm->getUncompressedSupportVectors();
FF_RETURN(jsSupportVectors);
#endif
}
NAN_METHOD(SVM::CalcError) {
FF_METHOD_CONTEXT("SVM::CalcError");
FF_ARG_INSTANCE(0, cv::Ptr<cv::ml::TrainData> trainData, TrainData::constructor, FF_UNWRAP_TRAINDATA_AND_GET);
FF_ARG_BOOL(1, bool test);
FF_OBJ jsResponses = FF_NEW_INSTANCE(Mat::constructor);
float error = FF_UNWRAP(info.This(), SVM)->svm->calcError(trainData, test, FF_UNWRAP_MAT_AND_GET(jsResponses));
FF_OBJ ret = FF_NEW_OBJ();
Nan::Set(ret, FF_NEW_STRING("error"), Nan::New((double)error));
Nan::Set(ret, FF_NEW_STRING("responses"), jsResponses);
FF_RETURN(ret);
}
NAN_METHOD(SVM::Save) {
FF_METHOD_CONTEXT("SVM::Save");
FF_ARG_STRING(0, std::string path);
FF_UNWRAP(info.This(), SVM)->svm->save(path);
}
NAN_METHOD(SVM::Load) {
FF_METHOD_CONTEXT("SVM::Load");
#if CV_VERSION_MINOR < 2
FF_THROW("SVM::Load fix for v3.0, v3.1 required");
#else
FF_ARG_STRING(0, std::string path);
FF_UNWRAP(info.This(), SVM)->svm = FF_UNWRAP(info.This(), SVM)->svm->load(path);
#endif
}
void SVM::setParams(v8::Local<v8::Object> params) {
FF_METHOD_CONTEXT("SVM::SetParams");
FF_GET_NUMBER_IFDEF(params, double c, "c", this->svm->getC());
FF_GET_NUMBER_IFDEF(params, double coef0, "coef0", this->svm->getCoef0());
FF_GET_NUMBER_IFDEF(params, double degree, "degree", this->svm->getDegree());
FF_GET_NUMBER_IFDEF(params, double gamma, "gamma", this->svm->getGamma());
FF_GET_NUMBER_IFDEF(params, double nu, "nu", this->svm->getNu());
FF_GET_NUMBER_IFDEF(params, double p, "p", this->svm->getP());
FF_GET_NUMBER_IFDEF(params, unsigned int kernelType, "kernelType", this->svm->getKernelType());
FF_GET_INSTANCE_IFDEF(params, cv::Mat classWeights, "classWeights", Mat::constructor, FF_UNWRAP_MAT_AND_GET, Mat, this->svm->getClassWeights());
this->svm->setC(c);
this->svm->setCoef0(coef0);
this->svm->setDegree(degree);
this->svm->setGamma(gamma);
this->svm->setNu(nu);
this->svm->setP(p);
this->svm->setKernel(kernelType);
this->svm->setClassWeights(classWeights);
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hints.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _HINTS_HXX
#define _HINTS_HXX
#ifndef _TABLE_HXX //autogen
#include <tools/table.hxx>
#endif
#include <swatrset.hxx>
class SwFmt;
class OutputDevice;
class SwTable;
class SwNode;
class SwNodes;
class SwCntntNode;
class SwPageFrm;
class SwFrm;
class SwTxtNode;
class SwHistory;
// Basis-Klasse fuer alle Message-Hints:
// "Overhead" vom SfxPoolItem wird hier behandelt
class SwMsgPoolItem : public SfxPoolItem
{
public:
SwMsgPoolItem( USHORT nWhich );
// "Overhead" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
};
// ---------------------------------------
// SwPtrMsgPoolItem (altes SwObjectDying!)
// ---------------------------------------
class SwPtrMsgPoolItem : public SwMsgPoolItem
{
public:
void * pObject;
SwPtrMsgPoolItem( USHORT nId, void * pObj )
: SwMsgPoolItem( nId ), pObject( pObj )
{}
};
/*
* SwFmtChg wird verschickt, wenn ein Format gegen ein anderes
* Format ausgewechselt worden ist. Es werden immer 2. Hints verschickt,
* das alte und neue Format.
*/
class SwFmtChg: public SwMsgPoolItem
{
public:
SwFmt *pChangedFmt;
SwFmtChg( SwFmt *pFmt );
};
class SwInsChr: public SwMsgPoolItem
{
public:
xub_StrLen nPos;
SwInsChr( USHORT nP );
};
class SwInsTxt: public SwMsgPoolItem
{
public:
xub_StrLen nPos;
xub_StrLen nLen;
SwInsTxt( xub_StrLen nP, xub_StrLen nL );
};
class SwDelChr: public SwMsgPoolItem
{
public:
xub_StrLen nPos;
SwDelChr( xub_StrLen nP );
};
class SwDelTxt: public SwMsgPoolItem
{
public:
xub_StrLen nStart;
xub_StrLen nLen;
SwDelTxt( xub_StrLen nS, xub_StrLen nL );
};
class SwUpdateAttr: public SwMsgPoolItem
{
public:
xub_StrLen nStart;
xub_StrLen nEnd;
USHORT nWhichAttr;
SwUpdateAttr( xub_StrLen nS, xub_StrLen nE, USHORT nW );
};
// SwRefMarkFldUpdate wird verschickt, wenn sich die ReferenzMarkierungen
// Updaten sollen. Um Seiten-/KapitelNummer feststellen zu koennen, muss
// der akt. Frame befragt werden. Dafuer wird das akt. OutputDevice benoetigt.
class SwRefMarkFldUpdate : public SwMsgPoolItem
{
public:
const OutputDevice* pOut; // Pointer auf das aktuelle Output-Device
SwRefMarkFldUpdate( const OutputDevice* );
};
// SwDocPosUpdate wird verschickt, um zu signalisieren, dass nur die
// Frames ab oder bis zu einer bestimmten dokument-globalen Position
// geupdated werden brauchen. Zur Zeit wird dies nur beim Updaten
// von Seitennummernfeldern benoetigt.
class SwDocPosUpdate : public SwMsgPoolItem
{
public:
const long nDocPos;
SwDocPosUpdate( const long nDocPos );
};
// SwTableFmlUpdate wird verschickt, wenn sich die Tabelle neu berechnen soll
// JP 16.02.99: oder wenn die Tabelle selbst gemergt oder gesplittet wird
enum TableFmlUpdtFlags { TBL_CALC = 0,
TBL_BOXNAME,
TBL_BOXPTR,
TBL_RELBOXNAME,
TBL_MERGETBL,
TBL_SPLITTBL
};
class SwTableFmlUpdate : public SwMsgPoolItem
{
public:
const SwTable* pTbl; // Pointer auf die zu aktuelle Tabelle
union {
const SwTable* pDelTbl; // Merge: Ptr auf die zu loeschende Tabelle
const String* pNewTblNm; // Split: der Name der neuen Tabelle
} DATA;
SwHistory* pHistory;
USHORT nSplitLine; // Split: ab dieser BaseLine wird gespl.
TableFmlUpdtFlags eFlags;
BOOL bModified : 1;
BOOL bBehindSplitLine : 1;
SwTableFmlUpdate( const SwTable* );
};
class SwAutoFmtGetDocNode: public SwMsgPoolItem
{
public:
const SwCntntNode* pCntntNode;
const SwNodes* pNodes;
SwAutoFmtGetDocNode( const SwNodes* pNds );
};
/*
* SwAttrSetChg wird verschicht, wenn sich in dem SwAttrSet rTheChgdSet
* etwas veraendert hat. Es werden immer 2. Hints
* verschickt, die alten und neuen Items in dem rTheChgdSet.
*/
class SwAttrSetChg: public SwMsgPoolItem
{
BOOL bDelSet;
SwAttrSet* pChgSet; // was sich veraendert hat
const SwAttrSet* pTheChgdSet; // wird nur zum Vergleichen gebraucht !!
public:
SwAttrSetChg( const SwAttrSet& rTheSet, SwAttrSet& rSet );
SwAttrSetChg( const SwAttrSetChg& );
~SwAttrSetChg();
// was sich veraendert hat
const SwAttrSet* GetChgSet() const { return pChgSet; }
SwAttrSet* GetChgSet() { return pChgSet; }
// wo es sich geaendert hat
const SwAttrSet* GetTheChgdSet() const { return pTheChgdSet; }
USHORT Count() const { return pChgSet->Count(); }
void ClearItem( USHORT nWhichL = 0 )
#ifdef PRODUCT
{ pChgSet->ClearItem( nWhichL ); }
#else
;
#endif
};
class SwCondCollCondChg: public SwMsgPoolItem
{
public:
SwFmt *pChangedFmt;
SwCondCollCondChg( SwFmt *pFmt );
};
class SwVirtPageNumInfo: public SwMsgPoolItem
{
const SwPageFrm *pPage;
const SwPageFrm *pOrigPage;
const SwFrm *pFrm; //An einem Absatz/Tabelle koennen mehrere
//Attribute sitzen. Der Frame muss dann
//muss dann letztlich bei bestimmen
//welches Attribut gilt und um welche physikalische
//Seite es sich handelt.
public:
SwVirtPageNumInfo( const SwPageFrm *pPg );
const SwPageFrm *GetPage() { return pPage; }
const SwPageFrm *GetOrigPage() { return pOrigPage;}
const SwFrm *GetFrm() { return pFrm; }
void SetInfo( const SwPageFrm *pPg,
const SwFrm *pF ) { pFrm = pF, pPage = pPg; }
};
DECLARE_TABLE( SwTxtNodeTable, SwTxtNode* )
class SwNumRuleInfo : public SwMsgPoolItem
{
SwTxtNodeTable aList;
const String& rName;
public:
SwNumRuleInfo( const String& rRuleName );
const String& GetName() const { return rName; }
void AddNode( SwTxtNode& rNd );
// erzeuge die Liste aller Nodes der NumRule in dem angegebenem Doc
// Der Code steht im docnum.cxx
// #111955#
void MakeList( SwDoc& rDoc, BOOL bOutline = FALSE );
const SwTxtNodeTable& GetList() const { return aList; }
};
class SwNRuleLowerLevel : public SwMsgPoolItem
{
const String& rName;
BYTE nLvl;
public:
SwNRuleLowerLevel( const String& rRuleName, BYTE nLevel );
const String& GetName() const { return rName; }
BYTE GetLevel() const { return nLvl; }
};
class SwFindNearestNode : public SwMsgPoolItem
{
const SwNode *pNd, *pFnd;
public:
SwFindNearestNode( const SwNode& rNd );
void CheckNode( const SwNode& rNd );
const SwNode* GetFoundNode() const { return pFnd; }
};
class SwStringMsgPoolItem : public SwMsgPoolItem
{
String sStr;
public:
const String& GetString() const { return sStr; }
SwStringMsgPoolItem( USHORT nId, const String& rStr )
: SwMsgPoolItem( nId ), sStr( rStr )
{}
};
#endif
<commit_msg>INTEGRATION: CWS swlists01 (1.8.192); FILE MERGED 2008/05/08 16:16:05 od 1.8.192.2: RESYNC: (1.8-1.9); FILE MERGED 2008/03/06 08:03:47 od 1.8.192.1: #i86732# refactoring: remove class <SwNumRuleInfo> and table <SwTxtNodeTable><commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: hints.hxx,v $
* $Revision: 1.10 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _HINTS_HXX
#define _HINTS_HXX
#ifndef _TABLE_HXX //autogen
#include <tools/table.hxx>
#endif
#include <swatrset.hxx>
class SwFmt;
class OutputDevice;
class SwTable;
class SwNode;
class SwNodes;
class SwCntntNode;
class SwPageFrm;
class SwFrm;
class SwTxtNode;
class SwHistory;
// Basis-Klasse fuer alle Message-Hints:
// "Overhead" vom SfxPoolItem wird hier behandelt
class SwMsgPoolItem : public SfxPoolItem
{
public:
SwMsgPoolItem( USHORT nWhich );
// "Overhead" vom SfxPoolItem
virtual int operator==( const SfxPoolItem& ) const;
virtual SfxPoolItem* Clone( SfxItemPool* pPool = 0 ) const;
};
// ---------------------------------------
// SwPtrMsgPoolItem (altes SwObjectDying!)
// ---------------------------------------
class SwPtrMsgPoolItem : public SwMsgPoolItem
{
public:
void * pObject;
SwPtrMsgPoolItem( USHORT nId, void * pObj )
: SwMsgPoolItem( nId ), pObject( pObj )
{}
};
/*
* SwFmtChg wird verschickt, wenn ein Format gegen ein anderes
* Format ausgewechselt worden ist. Es werden immer 2. Hints verschickt,
* das alte und neue Format.
*/
class SwFmtChg: public SwMsgPoolItem
{
public:
SwFmt *pChangedFmt;
SwFmtChg( SwFmt *pFmt );
};
class SwInsChr: public SwMsgPoolItem
{
public:
xub_StrLen nPos;
SwInsChr( USHORT nP );
};
class SwInsTxt: public SwMsgPoolItem
{
public:
xub_StrLen nPos;
xub_StrLen nLen;
SwInsTxt( xub_StrLen nP, xub_StrLen nL );
};
class SwDelChr: public SwMsgPoolItem
{
public:
xub_StrLen nPos;
SwDelChr( xub_StrLen nP );
};
class SwDelTxt: public SwMsgPoolItem
{
public:
xub_StrLen nStart;
xub_StrLen nLen;
SwDelTxt( xub_StrLen nS, xub_StrLen nL );
};
class SwUpdateAttr: public SwMsgPoolItem
{
public:
xub_StrLen nStart;
xub_StrLen nEnd;
USHORT nWhichAttr;
SwUpdateAttr( xub_StrLen nS, xub_StrLen nE, USHORT nW );
};
// SwRefMarkFldUpdate wird verschickt, wenn sich die ReferenzMarkierungen
// Updaten sollen. Um Seiten-/KapitelNummer feststellen zu koennen, muss
// der akt. Frame befragt werden. Dafuer wird das akt. OutputDevice benoetigt.
class SwRefMarkFldUpdate : public SwMsgPoolItem
{
public:
const OutputDevice* pOut; // Pointer auf das aktuelle Output-Device
SwRefMarkFldUpdate( const OutputDevice* );
};
// SwDocPosUpdate wird verschickt, um zu signalisieren, dass nur die
// Frames ab oder bis zu einer bestimmten dokument-globalen Position
// geupdated werden brauchen. Zur Zeit wird dies nur beim Updaten
// von Seitennummernfeldern benoetigt.
class SwDocPosUpdate : public SwMsgPoolItem
{
public:
const long nDocPos;
SwDocPosUpdate( const long nDocPos );
};
// SwTableFmlUpdate wird verschickt, wenn sich die Tabelle neu berechnen soll
// JP 16.02.99: oder wenn die Tabelle selbst gemergt oder gesplittet wird
enum TableFmlUpdtFlags { TBL_CALC = 0,
TBL_BOXNAME,
TBL_BOXPTR,
TBL_RELBOXNAME,
TBL_MERGETBL,
TBL_SPLITTBL
};
class SwTableFmlUpdate : public SwMsgPoolItem
{
public:
const SwTable* pTbl; // Pointer auf die zu aktuelle Tabelle
union {
const SwTable* pDelTbl; // Merge: Ptr auf die zu loeschende Tabelle
const String* pNewTblNm; // Split: der Name der neuen Tabelle
} DATA;
SwHistory* pHistory;
USHORT nSplitLine; // Split: ab dieser BaseLine wird gespl.
TableFmlUpdtFlags eFlags;
BOOL bModified : 1;
BOOL bBehindSplitLine : 1;
SwTableFmlUpdate( const SwTable* );
};
class SwAutoFmtGetDocNode: public SwMsgPoolItem
{
public:
const SwCntntNode* pCntntNode;
const SwNodes* pNodes;
SwAutoFmtGetDocNode( const SwNodes* pNds );
};
/*
* SwAttrSetChg wird verschicht, wenn sich in dem SwAttrSet rTheChgdSet
* etwas veraendert hat. Es werden immer 2. Hints
* verschickt, die alten und neuen Items in dem rTheChgdSet.
*/
class SwAttrSetChg: public SwMsgPoolItem
{
BOOL bDelSet;
SwAttrSet* pChgSet; // was sich veraendert hat
const SwAttrSet* pTheChgdSet; // wird nur zum Vergleichen gebraucht !!
public:
SwAttrSetChg( const SwAttrSet& rTheSet, SwAttrSet& rSet );
SwAttrSetChg( const SwAttrSetChg& );
~SwAttrSetChg();
// was sich veraendert hat
const SwAttrSet* GetChgSet() const { return pChgSet; }
SwAttrSet* GetChgSet() { return pChgSet; }
// wo es sich geaendert hat
const SwAttrSet* GetTheChgdSet() const { return pTheChgdSet; }
USHORT Count() const { return pChgSet->Count(); }
void ClearItem( USHORT nWhichL = 0 )
#ifdef PRODUCT
{ pChgSet->ClearItem( nWhichL ); }
#else
;
#endif
};
class SwCondCollCondChg: public SwMsgPoolItem
{
public:
SwFmt *pChangedFmt;
SwCondCollCondChg( SwFmt *pFmt );
};
class SwVirtPageNumInfo: public SwMsgPoolItem
{
const SwPageFrm *pPage;
const SwPageFrm *pOrigPage;
const SwFrm *pFrm; //An einem Absatz/Tabelle koennen mehrere
//Attribute sitzen. Der Frame muss dann
//muss dann letztlich bei bestimmen
//welches Attribut gilt und um welche physikalische
//Seite es sich handelt.
public:
SwVirtPageNumInfo( const SwPageFrm *pPg );
const SwPageFrm *GetPage() { return pPage; }
const SwPageFrm *GetOrigPage() { return pOrigPage;}
const SwFrm *GetFrm() { return pFrm; }
void SetInfo( const SwPageFrm *pPg,
const SwFrm *pF ) { pFrm = pF, pPage = pPg; }
};
// --> OD 2008-02-19 #refactorlists#
//DECLARE_TABLE( SwTxtNodeTable, SwTxtNode* )
//class SwNumRuleInfo : public SwMsgPoolItem
//{
// SwTxtNodeTable aList;
// const String& rName;
//public:
// SwNumRuleInfo( const String& rRuleName );
// const String& GetName() const { return rName; }
// void AddNode( SwTxtNode& rNd );
// // erzeuge die Liste aller Nodes der NumRule in dem angegebenem Doc
// // Der Code steht im docnum.cxx
// // #111955#
// void MakeList( SwDoc& rDoc, BOOL bOutline = FALSE );
// const SwTxtNodeTable& GetTxtNodeList() const { return aList; }
//};
// <--
class SwNRuleLowerLevel : public SwMsgPoolItem
{
const String& rName;
BYTE nLvl;
public:
SwNRuleLowerLevel( const String& rRuleName, BYTE nLevel );
const String& GetName() const { return rName; }
BYTE GetLevel() const { return nLvl; }
};
class SwFindNearestNode : public SwMsgPoolItem
{
const SwNode *pNd, *pFnd;
public:
SwFindNearestNode( const SwNode& rNd );
void CheckNode( const SwNode& rNd );
const SwNode* GetFoundNode() const { return pFnd; }
};
class SwStringMsgPoolItem : public SwMsgPoolItem
{
String sStr;
public:
const String& GetString() const { return sStr; }
SwStringMsgPoolItem( USHORT nId, const String& rStr )
: SwMsgPoolItem( nId ), sStr( rStr )
{}
};
#endif
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#include "locator/gossiping_property_file_snitch.hh"
namespace locator {
future<bool> gossiping_property_file_snitch::property_file_was_modified() {
return engine().open_file_dma(_fname, open_flags::ro)
.then([this](file f) {
_sf = make_lw_shared(std::move(f));
return _sf->stat();
}).then_wrapped([this] (auto&& f) {
try {
auto st = std::get<0>(f.get());
if (!_last_file_mod ||
_last_file_mod->tv_sec != st.st_mtim.tv_sec) {
_last_file_mod = st.st_mtim;
return true;
} else {
return false;
}
} catch (...) {
this->err("Failed to open {} for read or to get stats",
_fname);
throw;
}
});
}
gossiping_property_file_snitch::gossiping_property_file_snitch(
const sstring& fname, unsigned io_cpu_id)
: _fname(fname), _file_reader_cpu_id(io_cpu_id) {
_state = snitch_state::initializing;
}
future<> gossiping_property_file_snitch::start() {
using namespace std::chrono_literals;
// Run a timer only on specific CPU
if (engine().cpu_id() == _file_reader_cpu_id) {
//
// Here we will create a timer that will read the properties file every
// minute and load its contents into the gossiper.endpoint_state_map
//
_file_reader.set_callback([this] {
periodic_reader_callback();
});
io_cpu_id() = _file_reader_cpu_id;
_file_reader.arm(0s);
}
return _snitch_is_ready.get_future();
}
void gossiping_property_file_snitch::periodic_reader_callback() {
_file_reader_runs = true;
property_file_was_modified().then([this] (bool was_modified) {
if (was_modified) {
return read_property_file();
}
return make_ready_future<>();
}).then_wrapped([this] (auto&& f) {
try {
f.get();
if (_state == snitch_state::initializing) {
i_endpoint_snitch::snitch_instance().invoke_on_all(
[] (snitch_ptr& local_s) {
local_s->set_snitch_ready();
});
}
} catch (...) {
this->err("Exception has been thrown when parsing the property "
"file.");
}
if (_state == snitch_state::stopping) {
this->set_stopped();
} else if (_state != snitch_state::stopped) {
_file_reader.arm(reload_property_file_period());
}
_file_reader_runs = false;
});
}
void gossiping_property_file_snitch::gossiper_starting() {
using namespace gms;
using namespace service;
get_gossiper().invoke_on(0, [&] (gossiper& local_gossiper) {
#if 0 // Uncomment when versioned_vlaue_factory class gets more code (e.g. constructor)
auto internal_addr = storage_service_instance.value_factory.internal_ip(fb_utilities::get_local_address());
local_gossiper.add_local_application_state(application_state.INTERNAL_IP, internal_addr);
#endif
}).then([&] {
reload_gossiper_state();
_gossip_started = true;
});
}
future<> gossiping_property_file_snitch::read_property_file() {
using namespace exceptions;
return engine().open_file_dma(_fname, open_flags::ro).then([this](file f) {
_sf = make_lw_shared(std::move(f));
return _sf->size();
}).then([this](size_t s) {
_fsize = s;
return _sf->dma_read_exactly<char>(0, _fsize);
}).then([this](temporary_buffer<char> tb) {
_srting_buf = std::move(std::string(tb.get(), _fsize));
return reload_configuration();
}).then_wrapped([this] (auto&& f) {
try {
f.get();
return make_ready_future<>();
} catch (...) {
auto eptr = std::current_exception();
//
// In case of an error:
// - Halt if in the constructor.
// - Print an error when reloading.
//
if (_state == snitch_state::initializing) {
this->err("Failed to parse a properties file ({}). "
"Halting...", _fname);
//
// Mark all instances on other shards as ready and set the local
// instance into an exceptional state.
// This is needed to release the "invoke_on_all() in a
// create_snitch() waiting for all instances to become ready.
//
return i_endpoint_snitch::snitch_instance().invoke_on_all(
[this] (snitch_ptr& local_inst) {
if (engine().cpu_id() != _file_reader_cpu_id) {
local_inst->set_snitch_ready();
}
}).then([this, eptr] () mutable {
_snitch_is_ready.set_exception(eptr);
std::rethrow_exception(eptr);
});
} else {
this->warn("Failed to reload a properties file ({}). "
"Using previous values.", _fname);
return make_ready_future<>();
}
}
});
}
future<> gossiping_property_file_snitch::reload_configuration() {
using namespace boost::algorithm;
std::string line;
//
// Using two bool variables instead of std::experimental::optional<bool>
// since there is a bug in gcc causing it to report "'new_prefer_local' may
// be used uninitialized in this function" if we do.
//
bool new_prefer_local;
bool read_prefer_local = false;
std::experimental::optional<sstring> new_dc;
std::experimental::optional<sstring> new_rack;
std::istringstream istrm(_srting_buf);
std::vector<std::string> split_line;
while (std::getline(istrm, line)) {
trim(line);
// Skip comments or empty lines
if (!line.size() || line.at(0) == '#') {
continue;
}
split_line.clear();
split(split_line, line, is_any_of("="));
if (split_line.size() != 2) {
throw_bad_format(line);
}
auto key = split_line[0]; trim(key);
auto val = split_line[1]; trim(val);
if (!val.size()) {
throw_bad_format(line);
}
if (!key.compare("dc")) {
if (new_dc) {
throw_double_declaration("dc");
}
new_dc = sstring(val);
} else if (!key.compare("rack")) {
if (new_rack) {
throw_double_declaration("rack");
}
new_rack = sstring(val);
} else if (!key.compare("prefer_local")) {
if (read_prefer_local) {
throw_double_declaration("prefer_local");
}
if (!val.compare("false")) {
new_prefer_local = false;
} else if (!val.compare("true")) {
new_prefer_local = true;
} else {
throw_bad_format(line);
}
read_prefer_local = true;
} else {
throw_bad_format(line);
}
}
// Rack and Data Center have to be defined in the properties file!
if (!new_dc || !new_rack) {
throw_incomplete_file();
}
// "prefer_local" is FALSE by default
if (!read_prefer_local) {
new_prefer_local = false;
}
if (_state == snitch_state::initializing || _my_dc != *new_dc ||
_my_rack != *new_rack || _prefer_local != new_prefer_local) {
_my_dc = *new_dc;
_my_rack = *new_rack;
_prefer_local = new_prefer_local;
return i_endpoint_snitch::snitch_instance().invoke_on_all(
[this] (snitch_ptr& local_s) {
// Distribute the new values on all CPUs but the current one
if (engine().cpu_id() != _file_reader_cpu_id) {
local_s->set_my_dc(_my_dc);
local_s->set_my_rack(_my_rack);
}
}).then([this] {
reload_gossiper_state();
return service::get_storage_service().invoke_on_all(
[] (service::storage_service& l) {
l.get_token_metadata().invalidate_cached_rings();
}).then([this] {
if (_gossip_started) {
service::get_local_storage_service().gossip_snitch_info();
}
});
});
}
return make_ready_future<>();
}
void gossiping_property_file_snitch::set_stopped() {
_state = snitch_state::stopped;
_snitch_is_stopped.set_value();
}
future<> gossiping_property_file_snitch::stop() {
if (_state == snitch_state::stopped) {
return make_ready_future<>();
}
_state = snitch_state::stopping;
if (engine().cpu_id() == _file_reader_cpu_id) {
_file_reader.cancel();
// If timer is not running then set the STOPPED state right away.
if (!_file_reader_runs) {
set_stopped();
}
} else {
set_stopped();
}
return _snitch_is_stopped.get_future();
}
void gossiping_property_file_snitch::reload_gossiper_state()
{
#if 0 // TODO - needed to EC2 only
ReconnectableSnitchHelper pendingHelper = new ReconnectableSnitchHelper(this, myDC, preferLocal);
Gossiper.instance.register(pendingHelper);
pendingHelper = snitchHelperReference.getAndSet(pendingHelper);
if (pendingHelper != null)
Gossiper.instance.unregister(pendingHelper);
#endif
// else this will eventually rerun at gossiperStarting()
}
namespace locator {
using registry = class_registrator<i_endpoint_snitch,
gossiping_property_file_snitch,
const sstring&>;
static registry registrator1("org.apache.cassandra.locator.GossipingPropertyFileSnitch");
static registry registrator2("GossipingPropertyFileSnitch");
}
} // namespace locator
<commit_msg>gossiping_property_file_snitch: Register creators for all parameters set options.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#include "locator/gossiping_property_file_snitch.hh"
namespace locator {
future<bool> gossiping_property_file_snitch::property_file_was_modified() {
return engine().open_file_dma(_fname, open_flags::ro)
.then([this](file f) {
_sf = make_lw_shared(std::move(f));
return _sf->stat();
}).then_wrapped([this] (auto&& f) {
try {
auto st = std::get<0>(f.get());
if (!_last_file_mod ||
_last_file_mod->tv_sec != st.st_mtim.tv_sec) {
_last_file_mod = st.st_mtim;
return true;
} else {
return false;
}
} catch (...) {
this->err("Failed to open {} for read or to get stats",
_fname);
throw;
}
});
}
gossiping_property_file_snitch::gossiping_property_file_snitch(
const sstring& fname, unsigned io_cpu_id)
: _fname(fname), _file_reader_cpu_id(io_cpu_id) {
_state = snitch_state::initializing;
}
future<> gossiping_property_file_snitch::start() {
using namespace std::chrono_literals;
// Run a timer only on specific CPU
if (engine().cpu_id() == _file_reader_cpu_id) {
//
// Here we will create a timer that will read the properties file every
// minute and load its contents into the gossiper.endpoint_state_map
//
_file_reader.set_callback([this] {
periodic_reader_callback();
});
io_cpu_id() = _file_reader_cpu_id;
_file_reader.arm(0s);
}
return _snitch_is_ready.get_future();
}
void gossiping_property_file_snitch::periodic_reader_callback() {
_file_reader_runs = true;
property_file_was_modified().then([this] (bool was_modified) {
if (was_modified) {
return read_property_file();
}
return make_ready_future<>();
}).then_wrapped([this] (auto&& f) {
try {
f.get();
if (_state == snitch_state::initializing) {
i_endpoint_snitch::snitch_instance().invoke_on_all(
[] (snitch_ptr& local_s) {
local_s->set_snitch_ready();
});
}
} catch (...) {
this->err("Exception has been thrown when parsing the property "
"file.");
}
if (_state == snitch_state::stopping) {
this->set_stopped();
} else if (_state != snitch_state::stopped) {
_file_reader.arm(reload_property_file_period());
}
_file_reader_runs = false;
});
}
void gossiping_property_file_snitch::gossiper_starting() {
using namespace gms;
using namespace service;
get_gossiper().invoke_on(0, [&] (gossiper& local_gossiper) {
#if 0 // Uncomment when versioned_vlaue_factory class gets more code (e.g. constructor)
auto internal_addr = storage_service_instance.value_factory.internal_ip(fb_utilities::get_local_address());
local_gossiper.add_local_application_state(application_state.INTERNAL_IP, internal_addr);
#endif
}).then([&] {
reload_gossiper_state();
_gossip_started = true;
});
}
future<> gossiping_property_file_snitch::read_property_file() {
using namespace exceptions;
return engine().open_file_dma(_fname, open_flags::ro).then([this](file f) {
_sf = make_lw_shared(std::move(f));
return _sf->size();
}).then([this](size_t s) {
_fsize = s;
return _sf->dma_read_exactly<char>(0, _fsize);
}).then([this](temporary_buffer<char> tb) {
_srting_buf = std::move(std::string(tb.get(), _fsize));
return reload_configuration();
}).then_wrapped([this] (auto&& f) {
try {
f.get();
return make_ready_future<>();
} catch (...) {
auto eptr = std::current_exception();
//
// In case of an error:
// - Halt if in the constructor.
// - Print an error when reloading.
//
if (_state == snitch_state::initializing) {
this->err("Failed to parse a properties file ({}). "
"Halting...", _fname);
//
// Mark all instances on other shards as ready and set the local
// instance into an exceptional state.
// This is needed to release the "invoke_on_all() in a
// create_snitch() waiting for all instances to become ready.
//
return i_endpoint_snitch::snitch_instance().invoke_on_all(
[this] (snitch_ptr& local_inst) {
if (engine().cpu_id() != _file_reader_cpu_id) {
local_inst->set_snitch_ready();
}
}).then([this, eptr] () mutable {
_snitch_is_ready.set_exception(eptr);
std::rethrow_exception(eptr);
});
} else {
this->warn("Failed to reload a properties file ({}). "
"Using previous values.", _fname);
return make_ready_future<>();
}
}
});
}
future<> gossiping_property_file_snitch::reload_configuration() {
using namespace boost::algorithm;
std::string line;
//
// Using two bool variables instead of std::experimental::optional<bool>
// since there is a bug in gcc causing it to report "'new_prefer_local' may
// be used uninitialized in this function" if we do.
//
bool new_prefer_local;
bool read_prefer_local = false;
std::experimental::optional<sstring> new_dc;
std::experimental::optional<sstring> new_rack;
std::istringstream istrm(_srting_buf);
std::vector<std::string> split_line;
while (std::getline(istrm, line)) {
trim(line);
// Skip comments or empty lines
if (!line.size() || line.at(0) == '#') {
continue;
}
split_line.clear();
split(split_line, line, is_any_of("="));
if (split_line.size() != 2) {
throw_bad_format(line);
}
auto key = split_line[0]; trim(key);
auto val = split_line[1]; trim(val);
if (!val.size()) {
throw_bad_format(line);
}
if (!key.compare("dc")) {
if (new_dc) {
throw_double_declaration("dc");
}
new_dc = sstring(val);
} else if (!key.compare("rack")) {
if (new_rack) {
throw_double_declaration("rack");
}
new_rack = sstring(val);
} else if (!key.compare("prefer_local")) {
if (read_prefer_local) {
throw_double_declaration("prefer_local");
}
if (!val.compare("false")) {
new_prefer_local = false;
} else if (!val.compare("true")) {
new_prefer_local = true;
} else {
throw_bad_format(line);
}
read_prefer_local = true;
} else {
throw_bad_format(line);
}
}
// Rack and Data Center have to be defined in the properties file!
if (!new_dc || !new_rack) {
throw_incomplete_file();
}
// "prefer_local" is FALSE by default
if (!read_prefer_local) {
new_prefer_local = false;
}
if (_state == snitch_state::initializing || _my_dc != *new_dc ||
_my_rack != *new_rack || _prefer_local != new_prefer_local) {
_my_dc = *new_dc;
_my_rack = *new_rack;
_prefer_local = new_prefer_local;
return i_endpoint_snitch::snitch_instance().invoke_on_all(
[this] (snitch_ptr& local_s) {
// Distribute the new values on all CPUs but the current one
if (engine().cpu_id() != _file_reader_cpu_id) {
local_s->set_my_dc(_my_dc);
local_s->set_my_rack(_my_rack);
}
}).then([this] {
reload_gossiper_state();
return service::get_storage_service().invoke_on_all(
[] (service::storage_service& l) {
l.get_token_metadata().invalidate_cached_rings();
}).then([this] {
if (_gossip_started) {
service::get_local_storage_service().gossip_snitch_info();
}
});
});
}
return make_ready_future<>();
}
void gossiping_property_file_snitch::set_stopped() {
_state = snitch_state::stopped;
_snitch_is_stopped.set_value();
}
future<> gossiping_property_file_snitch::stop() {
if (_state == snitch_state::stopped) {
return make_ready_future<>();
}
_state = snitch_state::stopping;
if (engine().cpu_id() == _file_reader_cpu_id) {
_file_reader.cancel();
// If timer is not running then set the STOPPED state right away.
if (!_file_reader_runs) {
set_stopped();
}
} else {
set_stopped();
}
return _snitch_is_stopped.get_future();
}
void gossiping_property_file_snitch::reload_gossiper_state()
{
#if 0 // TODO - needed to EC2 only
ReconnectableSnitchHelper pendingHelper = new ReconnectableSnitchHelper(this, myDC, preferLocal);
Gossiper.instance.register(pendingHelper);
pendingHelper = snitchHelperReference.getAndSet(pendingHelper);
if (pendingHelper != null)
Gossiper.instance.unregister(pendingHelper);
#endif
// else this will eventually rerun at gossiperStarting()
}
namespace locator {
using registry_2_params = class_registrator<i_endpoint_snitch,
gossiping_property_file_snitch,
const sstring&, unsigned>;
static registry_2_params registrator2("org.apache.cassandra.locator.GossipingPropertyFileSnitch");
using registry_1_param = class_registrator<i_endpoint_snitch,
gossiping_property_file_snitch,
const sstring&>;
static registry_1_param registrator1("org.apache.cassandra.locator.GossipingPropertyFileSnitch");
using registry_default = class_registrator<i_endpoint_snitch,
gossiping_property_file_snitch>;
static registry_default registrator_default("org.apache.cassandra.locator.GossipingPropertyFileSnitch");
static registry_default registrator_default_short_name("GossipingPropertyFileSnitch");
}
} // namespace locator
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* 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: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* For LWP filter architecture prototype
************************************************************************/
/*************************************************************************
* Change History
Jan 2005 Created
************************************************************************/
#include "lwpstory.hxx"
#include "lwpfilehdr.hxx"
#include "lwpholder.hxx"
LwpHeadContent::LwpHeadContent(LwpObjectHeader &objHdr, LwpSvStream* pStrm)
: LwpContent(objHdr, pStrm)
{}
void LwpHeadContent::Read()
{
LwpContent::Read();
m_pObjStrm->SkipExtra();
}
LwpContent::LwpContent(LwpObjectHeader &objHdr, LwpSvStream* pStrm)
: LwpDLNFVList(objHdr, pStrm)
{}
void LwpContent::Read()
{
LwpDLNFVList::Read();
LwpObjectStream* pStrm = m_pObjStrm;
m_LayoutsWithMe.Read(pStrm);
m_nFlags = pStrm->QuickReaduInt16();
m_nFlags &= ~(CF_CHANGED | CF_DISABLEVALUECHECKING);
//LwpAtomHolder ClassName;
//ClassName.Read(pStrm);
m_ClassName.Read(pStrm);
LwpObjectID SkipID;
if(LwpFileHeader::m_nFileRevision >= 0x0006)
{
//SkipID.ReadIndexed(pStrm);
//SkipID.ReadIndexed(pStrm);
m_NextEnumerated.ReadIndexed(pStrm);
m_PreviousEnumerated.ReadIndexed(pStrm);
}
if (LwpFileHeader::m_nFileRevision >= 0x0007)
{
if(LwpFileHeader::m_nFileRevision < 0x000B)
{
SkipID.ReadIndexed(pStrm);
pStrm->SkipExtra();
}
else
{
sal_uInt8 HasNotify = pStrm->QuickReaduInt8();
if(HasNotify)
{
SkipID.ReadIndexed(pStrm);
pStrm->SkipExtra();
}
}
}
pStrm->SkipExtra();
}
LwpVirtualLayout* LwpContent::GetLayout(LwpVirtualLayout* pStartLayout)
{
return m_LayoutsWithMe.GetLayout(pStartLayout);
}
sal_Bool LwpContent::HasNonEmbeddedLayouts()
{
LwpVirtualLayout* pLayout = NULL;
while( (pLayout = GetLayout(pLayout)) )
{
if(!pLayout->NoContentReference())
return sal_True;
}
return sal_False;
}
sal_Bool LwpContent::IsStyleContent()
{
LwpVirtualLayout* pLayout = NULL;
while( (pLayout = GetLayout(pLayout)) )
{
if(pLayout->IsStyleLayout())
return sal_True;
}
return sal_False;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#738689 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* 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: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* For LWP filter architecture prototype
************************************************************************/
/*************************************************************************
* Change History
Jan 2005 Created
************************************************************************/
#include "lwpstory.hxx"
#include "lwpfilehdr.hxx"
#include "lwpholder.hxx"
LwpHeadContent::LwpHeadContent(LwpObjectHeader &objHdr, LwpSvStream* pStrm)
: LwpContent(objHdr, pStrm)
{}
void LwpHeadContent::Read()
{
LwpContent::Read();
m_pObjStrm->SkipExtra();
}
LwpContent::LwpContent(LwpObjectHeader &objHdr, LwpSvStream* pStrm)
: LwpDLNFVList(objHdr, pStrm)
, m_nFlags(0)
{
}
void LwpContent::Read()
{
LwpDLNFVList::Read();
LwpObjectStream* pStrm = m_pObjStrm;
m_LayoutsWithMe.Read(pStrm);
m_nFlags = pStrm->QuickReaduInt16();
m_nFlags &= ~(CF_CHANGED | CF_DISABLEVALUECHECKING);
//LwpAtomHolder ClassName;
//ClassName.Read(pStrm);
m_ClassName.Read(pStrm);
LwpObjectID SkipID;
if(LwpFileHeader::m_nFileRevision >= 0x0006)
{
//SkipID.ReadIndexed(pStrm);
//SkipID.ReadIndexed(pStrm);
m_NextEnumerated.ReadIndexed(pStrm);
m_PreviousEnumerated.ReadIndexed(pStrm);
}
if (LwpFileHeader::m_nFileRevision >= 0x0007)
{
if(LwpFileHeader::m_nFileRevision < 0x000B)
{
SkipID.ReadIndexed(pStrm);
pStrm->SkipExtra();
}
else
{
sal_uInt8 HasNotify = pStrm->QuickReaduInt8();
if(HasNotify)
{
SkipID.ReadIndexed(pStrm);
pStrm->SkipExtra();
}
}
}
pStrm->SkipExtra();
}
LwpVirtualLayout* LwpContent::GetLayout(LwpVirtualLayout* pStartLayout)
{
return m_LayoutsWithMe.GetLayout(pStartLayout);
}
sal_Bool LwpContent::HasNonEmbeddedLayouts()
{
LwpVirtualLayout* pLayout = NULL;
while( (pLayout = GetLayout(pLayout)) )
{
if(!pLayout->NoContentReference())
return sal_True;
}
return sal_False;
}
sal_Bool LwpContent::IsStyleContent()
{
LwpVirtualLayout* pLayout = NULL;
while( (pLayout = GetLayout(pLayout)) )
{
if(pLayout->IsStyleLayout())
return sal_True;
}
return sal_False;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <[email protected]>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtthemeconfig.h"
#include "ui_lxqtthemeconfig.h"
#include <QtGui/QTreeWidget>
#include <QtCore/QDebug>
LxQtThemeConfig::LxQtThemeConfig(LxQt::Settings *settings, QWidget *parent) :
QWidget(parent),
ui(new Ui::LxQtThemeConfig),
mSettings(settings)
{
ui->setupUi(this);
connect(ui->lxqtThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this, SLOT(lxqtThemeSelected(QTreeWidgetItem*,int)));
QList<LxQt::LxQtTheme> themes = LxQt::LxQtTheme::allThemes();
foreach(LxQt::LxQtTheme theme, themes)
{
QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(theme.name()));
if (!theme.previewImage().isEmpty())
{
item->setIcon(0, QIcon(theme.previewImage()));
}
item->setSizeHint(0, QSize(42,42)); // make icons non-cropped
item->setData(0, Qt::UserRole, theme.name());
ui->lxqtThemeList->addTopLevelItem(item);
}
initControls();
}
LxQtThemeConfig::~LxQtThemeConfig()
{
delete ui;
}
void LxQtThemeConfig::initControls()
{
QString currentTheme = mSettings->value("theme").toString();
QTreeWidgetItemIterator it(ui->lxqtThemeList);
while (*it) {
if ((*it)->data(0, Qt::UserRole).toString() == currentTheme)
{
ui->lxqtThemeList->setCurrentItem((*it));
break;
}
++it;
}
update();
}
void LxQtThemeConfig::lxqtThemeSelected(QTreeWidgetItem* item, int column)
{
Q_UNUSED(column);
if (!item)
return;
mSettings->setValue("theme", item->data(0, Qt::UserRole));
}
<commit_msg>Support changing the wallpaper of pcmanfm-qt.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXDE-Qt - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Alexander Sokoloff <[email protected]>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "lxqtthemeconfig.h"
#include "ui_lxqtthemeconfig.h"
#include <QtGui/QTreeWidget>
#include <QtCore/QDebug>
#include <QProcess>
LxQtThemeConfig::LxQtThemeConfig(LxQt::Settings *settings, QWidget *parent) :
QWidget(parent),
ui(new Ui::LxQtThemeConfig),
mSettings(settings)
{
ui->setupUi(this);
connect(ui->lxqtThemeList, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
this, SLOT(lxqtThemeSelected(QTreeWidgetItem*,int)));
QList<LxQt::LxQtTheme> themes = LxQt::LxQtTheme::allThemes();
foreach(LxQt::LxQtTheme theme, themes)
{
QTreeWidgetItem *item = new QTreeWidgetItem(QStringList(theme.name()));
if (!theme.previewImage().isEmpty())
{
item->setIcon(0, QIcon(theme.previewImage()));
}
item->setSizeHint(0, QSize(42,42)); // make icons non-cropped
item->setData(0, Qt::UserRole, theme.name());
ui->lxqtThemeList->addTopLevelItem(item);
}
initControls();
}
LxQtThemeConfig::~LxQtThemeConfig()
{
delete ui;
}
void LxQtThemeConfig::initControls()
{
QString currentTheme = mSettings->value("theme").toString();
QTreeWidgetItemIterator it(ui->lxqtThemeList);
while (*it) {
if ((*it)->data(0, Qt::UserRole).toString() == currentTheme)
{
ui->lxqtThemeList->setCurrentItem((*it));
break;
}
++it;
}
update();
}
void LxQtThemeConfig::lxqtThemeSelected(QTreeWidgetItem* item, int column)
{
Q_UNUSED(column);
if (!item)
return;
QVariant themeName = item->data(0, Qt::UserRole);
mSettings->setValue("theme", themeName);
LxQt::LxQtTheme theme(themeName.toString());
if(theme.isValid()) {
QString wallpaper = theme.desktopBackground();
if(!wallpaper.isEmpty()) {
// call pcmanfm-qt to update wallpaper
QProcess process;
QStringList args;
args << "--set-wallpaper" << wallpaper;
process.start("pcmanfm-qt", args, QIODevice::NotOpen);
process.waitForFinished();
}
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include "servicelayer.h"
#include "sortings.h"
ServiceLayer::ServiceLayer()
{
sortByName(1); //Defaults to sorting the list by name.
}
vector<Persons> ServiceLayer::list()
{
return dl.getVector();
}
//regular sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool sortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() < rhs.getName(); }
bool sortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() < rhs.getGender(); }
bool sortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() < rhs.getBirthYear(); }
bool sortByDeathYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getDeathYear() < rhs.getDeathYear(); }
//reverse sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool rSortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() > rhs.getName(); }
bool rSortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() > rhs.getGender(); }
bool rSortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() > rhs.getBirthYear(); }
bool rSortByDeathYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getDeathYear() > rhs.getDeathYear(); }
void ServiceLayer::sortByName(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByName);
stable_sort(people.begin(), people.end(), sortByName2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByName);
stable_sort(people.begin(), people.end(), rSortByName2);
}
dl.setVector(people);
}
void ServiceLayer::sortByGender(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByGender);
stable_sort(people.begin(), people.end(), sortByGender2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByGender);
stable_sort(people.begin(), people.end(), rSortByGender2);
}
dl.setVector(people);
}
void ServiceLayer::sortByBirthYear(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByBirthYear);
stable_sort(people.begin(), people.end(), sortByBirthYear2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByBirthYear);
stable_sort(people.begin(), people.end(), rSortByBirthYear2);
}
dl.setVector(people);
}
void ServiceLayer::sortByDeathYear(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByDeathYear);
stable_sort(people.begin(), people.end(), sortByDeathYear2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByDeathYear);
stable_sort(people.begin(), people.end(), rSortByDeathYear2);
}
dl.setVector(people);
}
void ServiceLayer::add(const Persons& p)
{
dl.addPerson(p);
}
bool ServiceLayer::addFromFile(string input)
{
return dl.loadFromOtherFile(input);
}
vector<int> ServiceLayer::searchByName(const string name)
{
vector<int> v;
for (unsigned int i = 0; i < list().size(); i++)
{
if (name.length() <= list()[i].getName().length())
{
if (list()[i].getName() == name)
{
v.push_back(i);
break;
}
else
{
for (unsigned int p = 0; p <=(list()[i].getName().length() - name.length()); p++)
{
if(name == list()[i].getName().substr(p, name.length()))
{
v.push_back(i);
break;
}
}
}
}
}
return v;
}
vector<int> ServiceLayer::searchByGender(const char gender)
{
vector<int> v;
for(unsigned int i = 0; i < list().size(); i++)
{
if(list()[i].getGender() == gender)
{
v.push_back(i);
}
}
return v;
}
vector<int> ServiceLayer::searchByYear(const int year)
{
vector<int> v;
for (unsigned int i = 0; i < list().size(); i++)
{
if (list()[i].getBirthYear() == year)
{
v.push_back(i);
}
}
return v;
}
vector<int> ServiceLayer::searchByRange(const int f, const int l)
{
vector<int> v;
for(unsigned int i = 0; i < list().size(); i++)
{
if(list()[i].getBirthYear() >= f && list()[i].getBirthYear() <= l)
{
v.push_back(i);
}
}
return v;
}
void ServiceLayer::deletePerson(int n)
{
dl.deletePerson(n);
}
<commit_msg>breytti röð í sort og search<commit_after>#include <algorithm>
#include "servicelayer.h"
#include "sortings.h"
ServiceLayer::ServiceLayer()
{
sortByName(1); //Defaults to sorting the list by name.
}
vector<Persons> ServiceLayer::list()
{
return dl.getVector();
}
//regular sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool sortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() < rhs.getName(); }
bool sortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() < rhs.getGender(); }
bool sortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() < rhs.getBirthYear(); }
bool sortByDeathYear2(const Persons &lhs, const Persons &rhs)
{
if (lhs.getDeathYear() == 0 && rhs.getDeathYear() == 0)
{
return lhs.getDeathYear() < rhs.getDeathYear();
}
else if (lhs.getDeathYear() == 0)
{
return lhs.getDeathYear() > rhs.getDeathYear();
}
else if (rhs.getDeathYear() == 0)
{
return lhs.getDeathYear() > rhs.getDeathYear();
}
else
{
return lhs.getDeathYear() < rhs.getDeathYear();
}
}
//reverse sorting. Reyndi að nota klasaföll, en það vill þýðandinn ekki.
bool rSortByName2(const Persons &lhs, const Persons &rhs)
{ return lhs.getName() > rhs.getName(); }
bool rSortByGender2(const Persons &lhs, const Persons &rhs)
{ return lhs.getGender() > rhs.getGender(); }
bool rSortByBirthYear2(const Persons &lhs, const Persons &rhs)
{ return lhs.getBirthYear() > rhs.getBirthYear(); }
bool rSortByDeathYear2(const Persons &lhs, const Persons &rhs)
{
if (lhs.getDeathYear() == 0 && rhs.getDeathYear() == 0)
{
return lhs.getDeathYear() > rhs.getDeathYear();
}
else if (lhs.getDeathYear() == 0)
{
return lhs.getDeathYear() < rhs.getDeathYear();
}
else if (rhs.getDeathYear() == 0)
{
return lhs.getDeathYear() < rhs.getDeathYear();
}
else
{
return lhs.getDeathYear() > rhs.getDeathYear();
}
}
void ServiceLayer::sortByName(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByName);
stable_sort(people.begin(), people.end(), sortByName2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByName);
stable_sort(people.begin(), people.end(), rSortByName2);
}
dl.setVector(people);
}
void ServiceLayer::sortByGender(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByGender);
stable_sort(people.begin(), people.end(), sortByGender2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByGender);
stable_sort(people.begin(), people.end(), rSortByGender2);
}
dl.setVector(people);
}
void ServiceLayer::sortByBirthYear(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByBirthYear);
stable_sort(people.begin(), people.end(), sortByBirthYear2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByBirthYear);
stable_sort(people.begin(), people.end(), rSortByBirthYear2);
}
dl.setVector(people);
}
void ServiceLayer::sortByDeathYear(int order)
{
vector <Persons> people = dl.getVector();
if (order == 1)
{
//stable_sort(people.begin(), people.end(), sorter.sortByDeathYear);
stable_sort(people.begin(), people.end(), sortByDeathYear2);
}
else //order == 2
{
//stable_sort(people.begin(), people.end(), sorter.rSortByDeathYear);
stable_sort(people.begin(), people.end(), rSortByDeathYear2);
}
dl.setVector(people);
}
void ServiceLayer::add(const Persons& p)
{
dl.addPerson(p);
}
bool ServiceLayer::addFromFile(string input)
{
return dl.loadFromOtherFile(input);
}
vector<int> ServiceLayer::searchByName(const string name)
{
vector<int> v;
for (unsigned int i = 0; i < list().size(); i++)
{
if (name.length() <= list()[i].getName().length())
{
if (list()[i].getName() == name)
{
v.push_back(i);
break;
}
else
{
for (unsigned int p = 0; p <=(list()[i].getName().length() - name.length()); p++)
{
if(name == list()[i].getName().substr(p, name.length()))
{
v.push_back(i);
break;
}
}
}
}
}
return v;
}
vector<int> ServiceLayer::searchByGender(const char gender)
{
vector<int> v;
for(unsigned int i = 0; i < list().size(); i++)
{
if(list()[i].getGender() == gender)
{
v.push_back(i);
}
}
return v;
}
vector<int> ServiceLayer::searchByYear(const int year)
{
vector<int> v;
for (unsigned int i = 0; i < list().size(); i++)
{
if (list()[i].getBirthYear() == year)
{
v.push_back(i);
}
}
return v;
}
vector<int> ServiceLayer::searchByRange(const int f, const int l)
{
vector<int> v;
for(unsigned int i = 0; i < list().size(); i++)
{
if(list()[i].getBirthYear() >= f && list()[i].getBirthYear() <= l)
{
v.push_back(i);
}
}
return v;
}
void ServiceLayer::deletePerson(int n)
{
dl.deletePerson(n);
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief force symbols into programm
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "InitialiseRest.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#ifndef OPENSSL_THREADS
#error missing thread support for openssl, please recomple OpenSSL with threads
#endif
#include "Basics/logging.h"
#include "Basics/InitialiseBasics.h"
#include "Rest/HttpResponse.h"
#include "Rest/Version.h"
#include "Statistics/statistics.h"
// -----------------------------------------------------------------------------
// OPEN SSL support
// -----------------------------------------------------------------------------
#ifdef TRI_HAVE_POSIX_THREADS
namespace {
long* opensslLockCount;
pthread_mutex_t* opensslLocks;
#if OPENSSL_VERSION_NUMBER < 0x01000000L
unsigned long opensslThreadId () {
return (unsigned long) pthread_self();
}
#else
// The compiler chooses the right one from the following two,
// according to the type of the return value of pthread_self():
template<typename T> void setter (CRYPTO_THREADID* id, T p) {
CRYPTO_THREADID_set_pointer(id, p);
}
template<> void setter (CRYPTO_THREADID* id, unsigned long val) {
CRYPTO_THREADID_set_numeric(id, val);
}
static void arango_threadid_func (CRYPTO_THREADID *id) {
auto self = pthread_self();
setter<decltype(self)>(id, self);
}
#endif
void opensslLockingCallback (int mode, int type, char const* /* file */, int /* line */) {
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(opensslLocks[type]));
opensslLockCount[type]++;
}
else {
pthread_mutex_unlock(&(opensslLocks[type]));
}
}
void opensslSetup () {
opensslLockCount = (long*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
opensslLocks = (pthread_mutex_t*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
for (long i = 0; i < CRYPTO_num_locks(); ++i) {
opensslLockCount[i] = 0;
pthread_mutex_init(&(opensslLocks[i]), 0);
}
#if OPENSSL_VERSION_NUMBER < 0x01000000L
CRYPTO_set_id_callback(opensslThreadId);
CRYPTO_set_locking_callback(opensslLockingCallback);
#else
CRYPTO_THREADID_set_callback(arango_threadid_func);
CRYPTO_set_locking_callback(opensslLockingCallback);
#endif
}
void opensslCleanup () {
CRYPTO_set_locking_callback(nullptr);
#if OPENSSL_VERSION_NUMBER < 0x01000000L
CRYPTO_set_id_callback(nullptr);
#else
CRYPTO_THREADID_set_callback(nullptr);
#endif
for (long i = 0; i < CRYPTO_num_locks(); ++i) {
pthread_mutex_destroy(&(opensslLocks[i]));
}
OPENSSL_free(opensslLocks);
OPENSSL_free(opensslLockCount);
}
}
#endif
// -----------------------------------------------------------------------------
// initialisation
// -----------------------------------------------------------------------------
namespace triagens {
namespace rest {
void InitialiseRest (int argc, char* argv[]) {
TRIAGENS_BASICS_INITIALISE(argc, argv);
TRI_InitialiseStatistics();
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
#ifdef TRI_HAVE_POSIX_THREADS
opensslSetup();
#endif
Version::initialise();
}
void ShutdownRest () {
#ifdef TRI_HAVE_POSIX_THREADS
opensslCleanup();
#endif
TRI_ShutdownStatistics();
TRIAGENS_BASICS_SHUTDOWN;
}
}
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>Use porting functions for initialisation, so ssl locking works on windows<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief force symbols into programm
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2009-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "InitialiseRest.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#define OPENSSL_THREAD_DEFINES
#include <openssl/opensslconf.h>
#ifndef OPENSSL_THREADS
#error missing thread support for openssl, please recomple OpenSSL with threads
#endif
#include "Basics/logging.h"
#include "Basics/threads.h"
#include "Basics/InitialiseBasics.h"
#include "Rest/HttpResponse.h"
#include "Rest/Version.h"
#include "Statistics/statistics.h"
// -----------------------------------------------------------------------------
// OPEN SSL support
// -----------------------------------------------------------------------------
namespace {
long* opensslLockCount;
TRI_mutex_t* opensslLocks;
#if OPENSSL_VERSION_NUMBER < 0x01000000L
unsigned long opensslThreadId () {
return (unsigned long) TRI_CurrentThreadId();
}
#else
// The compiler chooses the right one from the following two,
// according to the type of the return value of pthread_self():
template<typename T> void setter (CRYPTO_THREADID* id, T p) {
CRYPTO_THREADID_set_pointer(id, p);
}
template<> void setter (CRYPTO_THREADID* id, unsigned long val) {
CRYPTO_THREADID_set_numeric(id, val);
}
static void arango_threadid_func (CRYPTO_THREADID *id) {
auto self = TRI_CurrentThreadId();
setter<decltype(self)>(id, self);
}
#endif
void opensslLockingCallback (int mode, int type, char const* /* file */, int /* line */) {
if (mode & CRYPTO_LOCK) {
TRI_LockMutex(&(opensslLocks[type]));
opensslLockCount[type]++;
}
else {
TRI_UnlockMutex(&(opensslLocks[type]));
}
}
void opensslSetup () {
opensslLockCount = (long*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
opensslLocks = (TRI_mutex_t*) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(TRI_mutex_t));
for (long i = 0; i < CRYPTO_num_locks(); ++i) {
opensslLockCount[i] = 0;
TRI_InitMutex(&(opensslLocks[i]));
}
#if OPENSSL_VERSION_NUMBER < 0x01000000L
CRYPTO_set_id_callback(opensslThreadId);
CRYPTO_set_locking_callback(opensslLockingCallback);
#else
CRYPTO_THREADID_set_callback(arango_threadid_func);
CRYPTO_set_locking_callback(opensslLockingCallback);
#endif
}
void opensslCleanup () {
CRYPTO_set_locking_callback(nullptr);
#if OPENSSL_VERSION_NUMBER < 0x01000000L
CRYPTO_set_id_callback(nullptr);
#else
CRYPTO_THREADID_set_callback(nullptr);
#endif
for (long i = 0; i < CRYPTO_num_locks(); ++i) {
TRI_DestroyMutex(&(opensslLocks[i]));
}
OPENSSL_free(opensslLocks);
OPENSSL_free(opensslLockCount);
}
}
// -----------------------------------------------------------------------------
// initialisation
// -----------------------------------------------------------------------------
namespace triagens {
namespace rest {
void InitialiseRest (int argc, char* argv[]) {
TRIAGENS_BASICS_INITIALISE(argc, argv);
TRI_InitialiseStatistics();
SSL_library_init();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
opensslSetup();
Version::initialise();
}
void ShutdownRest () {
opensslCleanup();
TRI_ShutdownStatistics();
TRIAGENS_BASICS_SHUTDOWN;
}
}
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>/*
Copyright (C) 2003-2013 by Kristina Simpson <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "AttributeSet.hpp"
#include "Blittable.hpp"
#include "DisplayDevice.hpp"
#include "SceneObject.hpp"
#include "Shaders.hpp"
#include "solid_renderable.hpp"
#include "xhtml_layout_engine.hpp"
namespace xhtml
{
SolidRenderable::SolidRenderable()
: KRE::SceneObject("SolidRenderable")
{
init();
}
SolidRenderable::SolidRenderable(const rect& r, const KRE::Color& color)
: KRE::SceneObject("SolidRenderable")
{
init();
const float vx1 = static_cast<float>(r.x1());
const float vy1 = static_cast<float>(r.y1());
const float vx2 = static_cast<float>(r.x2());
const float vy2 = static_cast<float>(r.y2());
std::vector<KRE::vertex_color> vc;
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
attribs_->update(&vc);
}
SolidRenderable::SolidRenderable(const rectf& r, const KRE::Color& color)
: KRE::SceneObject("SolidRenderable")
{
init();
const float vx1 = r.x1();
const float vy1 = r.y1();
const float vx2 = r.x2();
const float vy2 = r.y2();
std::vector<KRE::vertex_color> vc;
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
attribs_->update(&vc);
}
void SolidRenderable::setDrawMode(KRE::DrawMode draw_mode)
{
getAttributeSet().back()->setDrawMode(draw_mode);
}
void SolidRenderable::init()
{
using namespace KRE;
setShader(ShaderProgram::getProgram("attr_color_shader"));
auto as = DisplayDevice::createAttributeSet();
attribs_.reset(new KRE::Attribute<KRE::vertex_color>(AccessFreqHint::DYNAMIC, AccessTypeHint::DRAW));
attribs_->addAttributeDesc(AttributeDesc(AttrType::POSITION, 2, AttrFormat::FLOAT, false, sizeof(vertex_color), offsetof(vertex_color, vertex)));
attribs_->addAttributeDesc(AttributeDesc(AttrType::COLOR, 4, AttrFormat::UNSIGNED_BYTE, true, sizeof(vertex_color), offsetof(vertex_color, color)));
as->addAttribute(AttributeBasePtr(attribs_));
as->setDrawMode(DrawMode::TRIANGLES);
addAttributeSet(as);
}
void SolidRenderable::update(std::vector<KRE::vertex_color>* coords)
{
attribs_->update(coords);
}
SimpleRenderable::SimpleRenderable()
: KRE::SceneObject("SimpleRenderable")
{
init();
}
SimpleRenderable::SimpleRenderable(KRE::DrawMode draw_mode)
: KRE::SceneObject("SimpleRenderable")
{
init(draw_mode);
}
void SimpleRenderable::init(KRE::DrawMode draw_mode)
{
using namespace KRE;
setShader(ShaderProgram::getProgram("simple"));
auto as = DisplayDevice::createAttributeSet();
attribs_.reset(new KRE::Attribute<glm::vec2>(AccessFreqHint::DYNAMIC, AccessTypeHint::DRAW));
attribs_->addAttributeDesc(AttributeDesc(AttrType::POSITION, 2, AttrFormat::FLOAT, false));
as->addAttribute(AttributeBasePtr(attribs_));
as->setDrawMode(draw_mode);
addAttributeSet(as);
}
void SimpleRenderable::update(std::vector<glm::vec2>* coords)
{
attribs_->update(coords);
}
void SimpleRenderable::setDrawMode(KRE::DrawMode draw_mode)
{
getAttributeSet().back()->setDrawMode(draw_mode);
}
}
<commit_msg>Remove a superfluous pragma.<commit_after>/*
Copyright (C) 2003-2013 by Kristina Simpson <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "AttributeSet.hpp"
#include "Blittable.hpp"
#include "DisplayDevice.hpp"
#include "SceneObject.hpp"
#include "Shaders.hpp"
#include "solid_renderable.hpp"
#include "xhtml_layout_engine.hpp"
namespace xhtml
{
SolidRenderable::SolidRenderable()
: KRE::SceneObject("SolidRenderable")
{
init();
}
SolidRenderable::SolidRenderable(const rect& r, const KRE::Color& color)
: KRE::SceneObject("SolidRenderable")
{
init();
const float vx1 = static_cast<float>(r.x1());
const float vy1 = static_cast<float>(r.y1());
const float vx2 = static_cast<float>(r.x2());
const float vy2 = static_cast<float>(r.y2());
std::vector<KRE::vertex_color> vc;
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
attribs_->update(&vc);
}
SolidRenderable::SolidRenderable(const rectf& r, const KRE::Color& color)
: KRE::SceneObject("SolidRenderable")
{
init();
const float vx1 = r.x1();
const float vy1 = r.y1();
const float vx2 = r.x2();
const float vy2 = r.y2();
std::vector<KRE::vertex_color> vc;
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy1), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx2, vy2), color.as_u8vec4());
vc.emplace_back(glm::vec2(vx1, vy2), color.as_u8vec4());
attribs_->update(&vc);
}
void SolidRenderable::setDrawMode(KRE::DrawMode draw_mode)
{
getAttributeSet().back()->setDrawMode(draw_mode);
}
void SolidRenderable::init()
{
using namespace KRE;
setShader(ShaderProgram::getProgram("attr_color_shader"));
auto as = DisplayDevice::createAttributeSet();
attribs_.reset(new KRE::Attribute<KRE::vertex_color>(AccessFreqHint::DYNAMIC, AccessTypeHint::DRAW));
attribs_->addAttributeDesc(AttributeDesc(AttrType::POSITION, 2, AttrFormat::FLOAT, false, sizeof(vertex_color), offsetof(vertex_color, vertex)));
attribs_->addAttributeDesc(AttributeDesc(AttrType::COLOR, 4, AttrFormat::UNSIGNED_BYTE, true, sizeof(vertex_color), offsetof(vertex_color, color)));
as->addAttribute(AttributeBasePtr(attribs_));
as->setDrawMode(DrawMode::TRIANGLES);
addAttributeSet(as);
}
void SolidRenderable::update(std::vector<KRE::vertex_color>* coords)
{
attribs_->update(coords);
}
SimpleRenderable::SimpleRenderable()
: KRE::SceneObject("SimpleRenderable")
{
init();
}
SimpleRenderable::SimpleRenderable(KRE::DrawMode draw_mode)
: KRE::SceneObject("SimpleRenderable")
{
init(draw_mode);
}
void SimpleRenderable::init(KRE::DrawMode draw_mode)
{
using namespace KRE;
setShader(ShaderProgram::getProgram("simple"));
auto as = DisplayDevice::createAttributeSet();
attribs_.reset(new KRE::Attribute<glm::vec2>(AccessFreqHint::DYNAMIC, AccessTypeHint::DRAW));
attribs_->addAttributeDesc(AttributeDesc(AttrType::POSITION, 2, AttrFormat::FLOAT, false));
as->addAttribute(AttributeBasePtr(attribs_));
as->setDrawMode(draw_mode);
addAttributeSet(as);
}
void SimpleRenderable::update(std::vector<glm::vec2>* coords)
{
attribs_->update(coords);
}
void SimpleRenderable::setDrawMode(KRE::DrawMode draw_mode)
{
getAttributeSet().back()->setDrawMode(draw_mode);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <zmq/zmqpublishnotifier.h>
#include <chain.h>
#include <chainparams.h>
#include <rpc/server.h>
#include <streams.h>
#include <util/system.h>
#include <validation.h>
#include <zmq/zmqutil.h>
#include <zmq.h>
#include <cstdarg>
#include <cstddef>
#include <map>
#include <string>
#include <utility>
// SYSCOIN
#include <governance/governance-vote.h>
#include <governance/governance-object.h>
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
// SYSCOIN
static const char *MSG_RAWMEMPOOLTX = "rawmempooltx";
static const char *MSG_HASHGVOTE = "hashgovernancevote";
static const char *MSG_HASHGOBJ = "hashgovernanceobject";
static const char *MSG_RAWGVOTE = "rawgovernancevote";
static const char *MSG_RAWGOBJ = "rawgovernanceobject";
static const char *MSG_SEQUENCE = "sequence";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
int rc = zmq_setsockopt(psocket, ZMQ_SNDHWM, &outbound_message_high_water_mark, sizeof(outbound_message_high_water_mark));
if (rc != 0)
{
zmqError("Failed to set outbound message high water mark");
zmq_close(psocket);
return false;
}
const int so_keepalive_option {1};
rc = zmq_setsockopt(psocket, ZMQ_TCP_KEEPALIVE, &so_keepalive_option, sizeof(so_keepalive_option));
if (rc != 0) {
zmqError("Failed to set SO_KEEPALIVE");
zmq_close(psocket);
return false;
}
rc = zmq_bind(psocket, address.c_str());
if (rc != 0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint(BCLog::ZMQ, "zmq: Reusing socket for address %s\n", address);
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
// Early return if Initialize was not called
if (!psocket) return;
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint(BCLog::ZMQ, "zmq: Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = nullptr;
}
bool CZMQAbstractPublishNotifier::SendZmqMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint(BCLog::ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendZmqMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendZmqMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
// SYSCOIN
bool CZMQPublishHashGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 hash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernancevote %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHGVOTE, data, 32);
}
bool CZMQPublishHashGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &object)
{
uint256 hash = object.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernanceobject %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHGOBJ, data, 32);
}
bool CZMQPublishRawGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 nHash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, vote = %d\n", nHash.ToString(), vote.ToString());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << vote;
return SendZmqMessage(MSG_RAWGVOTE, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &govobj)
{
uint256 nHash = govobj.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << govobj;
return SendZmqMessage(MSG_RAWGOBJ, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawMempoolTransactionNotifier::NotifyTransactionMempool(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawmempooltx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendZmqMessage(MSG_RAWMEMPOOLTX, &(*ss.begin()), ss.size());
}
// TODO: Dedup this code to take label char, log string
bool CZMQPublishSequenceNotifier::NotifyBlockConnect(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish sequence block connect %s\n", hash.GetHex());
char data[sizeof(uint256)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(data) - 1] = 'C'; // Block (C)onnect
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
bool CZMQPublishSequenceNotifier::NotifyBlockDisconnect(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish sequence block disconnect %s\n", hash.GetHex());
char data[sizeof(uint256)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(data) - 1] = 'D'; // Block (D)isconnect
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
bool CZMQPublishSequenceNotifier::NotifyTransactionAcceptance(const CTransaction &transaction, uint64_t mempool_sequence)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx mempool acceptance %s\n", hash.GetHex());
unsigned char data[sizeof(uint256)+sizeof(mempool_sequence)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(uint256)] = 'A'; // Mempool (A)cceptance
WriteLE64(data+sizeof(uint256)+1, mempool_sequence);
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
bool CZMQPublishSequenceNotifier::NotifyTransactionRemoval(const CTransaction &transaction, uint64_t mempool_sequence)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx mempool removal %s\n", hash.GetHex());
unsigned char data[sizeof(uint256)+sizeof(mempool_sequence)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(uint256)] = 'R'; // Mempool (R)emoval
WriteLE64(data+sizeof(uint256)+1, mempool_sequence);
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
<commit_msg>zmq: Append address to notify log output<commit_after>// Copyright (c) 2015-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <zmq/zmqpublishnotifier.h>
#include <chain.h>
#include <chainparams.h>
#include <rpc/server.h>
#include <streams.h>
#include <util/system.h>
#include <validation.h>
#include <zmq/zmqutil.h>
#include <zmq.h>
#include <cstdarg>
#include <cstddef>
#include <map>
#include <string>
#include <utility>
// SYSCOIN
#include <governance/governance-vote.h>
#include <governance/governance-object.h>
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
// SYSCOIN
static const char *MSG_RAWMEMPOOLTX = "rawmempooltx";
static const char *MSG_HASHGVOTE = "hashgovernancevote";
static const char *MSG_HASHGOBJ = "hashgovernanceobject";
static const char *MSG_RAWGVOTE = "rawgovernancevote";
static const char *MSG_RAWGOBJ = "rawgovernanceobject";
static const char *MSG_SEQUENCE = "sequence";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
int rc = zmq_setsockopt(psocket, ZMQ_SNDHWM, &outbound_message_high_water_mark, sizeof(outbound_message_high_water_mark));
if (rc != 0)
{
zmqError("Failed to set outbound message high water mark");
zmq_close(psocket);
return false;
}
const int so_keepalive_option {1};
rc = zmq_setsockopt(psocket, ZMQ_TCP_KEEPALIVE, &so_keepalive_option, sizeof(so_keepalive_option));
if (rc != 0) {
zmqError("Failed to set SO_KEEPALIVE");
zmq_close(psocket);
return false;
}
rc = zmq_bind(psocket, address.c_str());
if (rc != 0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint(BCLog::ZMQ, "zmq: Reusing socket for address %s\n", address);
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
// Early return if Initialize was not called
if (!psocket) return;
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint(BCLog::ZMQ, "zmq: Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = nullptr;
}
bool CZMQAbstractPublishNotifier::SendZmqMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashblock %s to %s\n", hash.GetHex(), this->address);
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx %s to %s\n", hash.GetHex(), this->address);
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint(BCLog::ZMQ, "zmq: Publish rawblock %s to %s\n", pindex->GetBlockHash().GetHex(), this->address);
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendZmqMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawtx %s to %s\n", hash.GetHex(), this->address);
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendZmqMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
// SYSCOIN
bool CZMQPublishHashGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 hash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernancevote %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHGVOTE, data, 32);
}
bool CZMQPublishHashGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &object)
{
uint256 hash = object.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernanceobject %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendZmqMessage(MSG_HASHGOBJ, data, 32);
}
bool CZMQPublishRawGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 nHash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, vote = %d\n", nHash.ToString(), vote.ToString());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << vote;
return SendZmqMessage(MSG_RAWGVOTE, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &govobj)
{
uint256 nHash = govobj.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << govobj;
return SendZmqMessage(MSG_RAWGOBJ, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawMempoolTransactionNotifier::NotifyTransactionMempool(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawmempooltx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendZmqMessage(MSG_RAWMEMPOOLTX, &(*ss.begin()), ss.size());
}
// TODO: Dedup this code to take label char, log string
bool CZMQPublishSequenceNotifier::NotifyBlockConnect(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish sequence block connect %s to %s\n", hash.GetHex(), this->address);
char data[sizeof(uint256)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(data) - 1] = 'C'; // Block (C)onnect
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
bool CZMQPublishSequenceNotifier::NotifyBlockDisconnect(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish sequence block disconnect %s to %s\n", hash.GetHex(), this->address);
char data[sizeof(uint256)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(data) - 1] = 'D'; // Block (D)isconnect
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
bool CZMQPublishSequenceNotifier::NotifyTransactionAcceptance(const CTransaction &transaction, uint64_t mempool_sequence)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx mempool acceptance %s to %s\n", hash.GetHex(), this->address);
unsigned char data[sizeof(uint256)+sizeof(mempool_sequence)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(uint256)] = 'A'; // Mempool (A)cceptance
WriteLE64(data+sizeof(uint256)+1, mempool_sequence);
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
bool CZMQPublishSequenceNotifier::NotifyTransactionRemoval(const CTransaction &transaction, uint64_t mempool_sequence)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx mempool removal %s to %s\n", hash.GetHex(), this->address);
unsigned char data[sizeof(uint256)+sizeof(mempool_sequence)+1];
for (unsigned int i = 0; i < sizeof(uint256); i++)
data[sizeof(uint256) - 1 - i] = hash.begin()[i];
data[sizeof(uint256)] = 'R'; // Mempool (R)emoval
WriteLE64(data+sizeof(uint256)+1, mempool_sequence);
return SendZmqMessage(MSG_SEQUENCE, data, sizeof(data));
}
<|endoftext|> |
<commit_before>//===- PassRegistry.cpp - Pass Registration Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PassRegistry, with which passes are registered on
// initialization, and supports the PassManager in dependency resolution.
//
//===----------------------------------------------------------------------===//
#include "llvm/PassRegistry.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/System/Mutex.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include <vector>
using namespace llvm;
// FIXME: We use ManagedStatic to erase the pass registrar on shutdown.
// Unfortunately, passes are registered with static ctors, and having
// llvm_shutdown clear this map prevents successful ressurection after
// llvm_shutdown is run. Ideally we should find a solution so that we don't
// leak the map, AND can still resurrect after shutdown.
static ManagedStatic<PassRegistry> PassRegistryObj;
PassRegistry *PassRegistry::getPassRegistry() {
return &*PassRegistryObj;
}
sys::SmartMutex<true> Lock;
//===----------------------------------------------------------------------===//
// PassRegistryImpl
//
struct PassRegistryImpl {
/// PassInfoMap - Keep track of the PassInfo object for each registered pass.
typedef DenseMap<const void*, const PassInfo*> MapType;
MapType PassInfoMap;
typedef StringMap<const PassInfo*> StringMapType;
StringMapType PassInfoStringMap;
/// AnalysisGroupInfo - Keep track of information for each analysis group.
struct AnalysisGroupInfo {
SmallPtrSet<const PassInfo *, 8> Implementations;
};
DenseMap<const PassInfo*, AnalysisGroupInfo> AnalysisGroupInfoMap;
std::vector<PassRegistrationListener*> Listeners;
};
void *PassRegistry::getImpl() const {
if (!pImpl)
pImpl = new PassRegistryImpl();
return pImpl;
}
//===----------------------------------------------------------------------===//
// Accessors
//
PassRegistry::~PassRegistry() {
sys::SmartScopedLock<true> Guard(Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(pImpl);
if (Impl) delete Impl;
pImpl = 0;
}
const PassInfo *PassRegistry::getPassInfo(const void *TI) const {
sys::SmartScopedLock<true> Guard(Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.find(TI);
return I != Impl->PassInfoMap.end() ? I->second : 0;
}
const PassInfo *PassRegistry::getPassInfo(StringRef Arg) const {
sys::SmartScopedLock<true> Guard(Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::StringMapType::const_iterator
I = Impl->PassInfoStringMap.find(Arg);
return I != Impl->PassInfoStringMap.end() ? I->second : 0;
}
//===----------------------------------------------------------------------===//
// Pass Registration mechanism
//
void PassRegistry::registerPass(const PassInfo &PI) {
sys::SmartScopedLock<true> Guard(Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
bool Inserted =
Impl->PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted;
Impl->PassInfoStringMap[PI.getPassArgument()] = &PI;
// Notify any listeners.
for (std::vector<PassRegistrationListener*>::iterator
I = Impl->Listeners.begin(), E = Impl->Listeners.end(); I != E; ++I)
(*I)->passRegistered(&PI);
}
void PassRegistry::unregisterPass(const PassInfo &PI) {
sys::SmartScopedLock<true> Guard(Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::iterator I =
Impl->PassInfoMap.find(PI.getTypeInfo());
assert(I != Impl->PassInfoMap.end() && "Pass registered but not in map!");
// Remove pass from the map.
Impl->PassInfoMap.erase(I);
Impl->PassInfoStringMap.erase(PI.getPassArgument());
}
void PassRegistry::enumerateWith(PassRegistrationListener *L) {
sys::SmartScopedLock<true> Guard(Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
for (PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.begin(),
E = Impl->PassInfoMap.end(); I != E; ++I)
L->passEnumerate(I->second);
}
/// Analysis Group Mechanisms.
void PassRegistry::registerAnalysisGroup(const void *InterfaceID,
const void *PassID,
PassInfo& Registeree,
bool isDefault) {
PassInfo *InterfaceInfo = const_cast<PassInfo*>(getPassInfo(InterfaceID));
if (InterfaceInfo == 0) {
// First reference to Interface, register it now.
registerPass(Registeree);
InterfaceInfo = &Registeree;
}
assert(Registeree.isAnalysisGroup() &&
"Trying to join an analysis group that is a normal pass!");
if (PassID) {
PassInfo *ImplementationInfo = const_cast<PassInfo*>(getPassInfo(PassID));
assert(ImplementationInfo &&
"Must register pass before adding to AnalysisGroup!");
sys::SmartScopedLock<true> Guard(Lock);
// Make sure we keep track of the fact that the implementation implements
// the interface.
ImplementationInfo->addInterfaceImplemented(InterfaceInfo);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::AnalysisGroupInfo &AGI =
Impl->AnalysisGroupInfoMap[InterfaceInfo];
assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
"Cannot add a pass to the same analysis group more than once!");
AGI.Implementations.insert(ImplementationInfo);
if (isDefault) {
assert(InterfaceInfo->getNormalCtor() == 0 &&
"Default implementation for analysis group already specified!");
assert(ImplementationInfo->getNormalCtor() &&
"Cannot specify pass as default if it does not have a default ctor");
InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
}
}
}
void PassRegistry::addRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedLock<true> Guard(Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
Impl->Listeners.push_back(L);
}
void PassRegistry::removeRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedLock<true> Guard(Lock);
// NOTE: This is necessary, because removeRegistrationListener() can be called
// as part of the llvm_shutdown sequence. Since we have no control over the
// order of that sequence, we need to gracefully handle the case where the
// PassRegistry is destructed before the object that triggers this call.
if (!pImpl) return;
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
std::vector<PassRegistrationListener*>::iterator I =
std::find(Impl->Listeners.begin(), Impl->Listeners.end(), L);
assert(I != Impl->Listeners.end() &&
"PassRegistrationListener not registered!");
Impl->Listeners.erase(I);
}
<commit_msg>Allow the PassRegistry mutex to be lazily initialized, and clean up the global namespace at the same time.<commit_after>//===- PassRegistry.cpp - Pass Registration Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the PassRegistry, with which passes are registered on
// initialization, and supports the PassManager in dependency resolution.
//
//===----------------------------------------------------------------------===//
#include "llvm/PassRegistry.h"
#include "llvm/PassSupport.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/System/Mutex.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include <vector>
using namespace llvm;
// FIXME: We use ManagedStatic to erase the pass registrar on shutdown.
// Unfortunately, passes are registered with static ctors, and having
// llvm_shutdown clear this map prevents successful ressurection after
// llvm_shutdown is run. Ideally we should find a solution so that we don't
// leak the map, AND can still resurrect after shutdown.
static ManagedStatic<PassRegistry> PassRegistryObj;
PassRegistry *PassRegistry::getPassRegistry() {
return &*PassRegistryObj;
}
static ManagedStatic<sys::SmartMutex<true> > Lock;
//===----------------------------------------------------------------------===//
// PassRegistryImpl
//
struct PassRegistryImpl {
/// PassInfoMap - Keep track of the PassInfo object for each registered pass.
typedef DenseMap<const void*, const PassInfo*> MapType;
MapType PassInfoMap;
typedef StringMap<const PassInfo*> StringMapType;
StringMapType PassInfoStringMap;
/// AnalysisGroupInfo - Keep track of information for each analysis group.
struct AnalysisGroupInfo {
SmallPtrSet<const PassInfo *, 8> Implementations;
};
DenseMap<const PassInfo*, AnalysisGroupInfo> AnalysisGroupInfoMap;
std::vector<PassRegistrationListener*> Listeners;
};
void *PassRegistry::getImpl() const {
if (!pImpl)
pImpl = new PassRegistryImpl();
return pImpl;
}
//===----------------------------------------------------------------------===//
// Accessors
//
PassRegistry::~PassRegistry() {
sys::SmartScopedLock<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(pImpl);
if (Impl) delete Impl;
pImpl = 0;
}
const PassInfo *PassRegistry::getPassInfo(const void *TI) const {
sys::SmartScopedLock<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.find(TI);
return I != Impl->PassInfoMap.end() ? I->second : 0;
}
const PassInfo *PassRegistry::getPassInfo(StringRef Arg) const {
sys::SmartScopedLock<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::StringMapType::const_iterator
I = Impl->PassInfoStringMap.find(Arg);
return I != Impl->PassInfoStringMap.end() ? I->second : 0;
}
//===----------------------------------------------------------------------===//
// Pass Registration mechanism
//
void PassRegistry::registerPass(const PassInfo &PI) {
sys::SmartScopedLock<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
bool Inserted =
Impl->PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted;
Impl->PassInfoStringMap[PI.getPassArgument()] = &PI;
// Notify any listeners.
for (std::vector<PassRegistrationListener*>::iterator
I = Impl->Listeners.begin(), E = Impl->Listeners.end(); I != E; ++I)
(*I)->passRegistered(&PI);
}
void PassRegistry::unregisterPass(const PassInfo &PI) {
sys::SmartScopedLock<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::MapType::iterator I =
Impl->PassInfoMap.find(PI.getTypeInfo());
assert(I != Impl->PassInfoMap.end() && "Pass registered but not in map!");
// Remove pass from the map.
Impl->PassInfoMap.erase(I);
Impl->PassInfoStringMap.erase(PI.getPassArgument());
}
void PassRegistry::enumerateWith(PassRegistrationListener *L) {
sys::SmartScopedLock<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
for (PassRegistryImpl::MapType::const_iterator I = Impl->PassInfoMap.begin(),
E = Impl->PassInfoMap.end(); I != E; ++I)
L->passEnumerate(I->second);
}
/// Analysis Group Mechanisms.
void PassRegistry::registerAnalysisGroup(const void *InterfaceID,
const void *PassID,
PassInfo& Registeree,
bool isDefault) {
PassInfo *InterfaceInfo = const_cast<PassInfo*>(getPassInfo(InterfaceID));
if (InterfaceInfo == 0) {
// First reference to Interface, register it now.
registerPass(Registeree);
InterfaceInfo = &Registeree;
}
assert(Registeree.isAnalysisGroup() &&
"Trying to join an analysis group that is a normal pass!");
if (PassID) {
PassInfo *ImplementationInfo = const_cast<PassInfo*>(getPassInfo(PassID));
assert(ImplementationInfo &&
"Must register pass before adding to AnalysisGroup!");
sys::SmartScopedLock<true> Guard(*Lock);
// Make sure we keep track of the fact that the implementation implements
// the interface.
ImplementationInfo->addInterfaceImplemented(InterfaceInfo);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
PassRegistryImpl::AnalysisGroupInfo &AGI =
Impl->AnalysisGroupInfoMap[InterfaceInfo];
assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
"Cannot add a pass to the same analysis group more than once!");
AGI.Implementations.insert(ImplementationInfo);
if (isDefault) {
assert(InterfaceInfo->getNormalCtor() == 0 &&
"Default implementation for analysis group already specified!");
assert(ImplementationInfo->getNormalCtor() &&
"Cannot specify pass as default if it does not have a default ctor");
InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
}
}
}
void PassRegistry::addRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedLock<true> Guard(*Lock);
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
Impl->Listeners.push_back(L);
}
void PassRegistry::removeRegistrationListener(PassRegistrationListener *L) {
sys::SmartScopedLock<true> Guard(*Lock);
// NOTE: This is necessary, because removeRegistrationListener() can be called
// as part of the llvm_shutdown sequence. Since we have no control over the
// order of that sequence, we need to gracefully handle the case where the
// PassRegistry is destructed before the object that triggers this call.
if (!pImpl) return;
PassRegistryImpl *Impl = static_cast<PassRegistryImpl*>(getImpl());
std::vector<PassRegistrationListener*>::iterator I =
std::find(Impl->Listeners.begin(), Impl->Listeners.end(), L);
assert(I != Impl->Listeners.end() &&
"PassRegistrationListener not registered!");
Impl->Listeners.erase(I);
}
<|endoftext|> |
<commit_before>/*
aboutdata.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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 <config-kleopatra.h>
#include "aboutdata.h"
#include <klocale.h>
static const char kleopatra_version[] = KLEOPATRA_VERSION_STRING;
static const char description[] = I18N_NOOP("Certificate Manager and Unified Crypto GUI");
struct about_data {
const char * name;
const char * desc;
const char * email;
const char * web;
};
static const about_data authors[] = {
{ "Marc Mutz", I18N_NOOP("Current Maintainer"), "[email protected]", 0 },
{ "Steffen Hansen", I18N_NOOP("Former Maintainer"), "[email protected]", 0 },
{ "Kalle Dalheimer", I18N_NOOP("Original Author"), "[email protected]", 0 },
{ "Jesper Petersen", I18N_NOOP("Original Author"), "[email protected]", 0 },
};
static const about_data credits[] = {
{ I18N_NOOP("Till Adam"),
I18N_NOOP("UI Server commands and dialogs"),
"[email protected]", 0 },
{ I18N_NOOP("David Faure"),
I18N_NOOP("Backend configuration framework, KIO integration"),
"[email protected]", 0 },
{ I18N_NOOP("Michel Boyer de la Giroday"),
I18N_NOOP("Key-state dependant colors and fonts in the key list"),
"[email protected]", 0 },
{ I18N_NOOP("Volker Krause"),
I18N_NOOP("UI Server dialogs"),
"[email protected]", 0 },
{ I18N_NOOP("Thomas Moenicke"),
I18N_NOOP("Artwork"),
"[email protected]", 0 },
{ I18N_NOOP("Daniel Molkentin"),
I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"),
"[email protected]", 0 },
{ I18N_NOOP("Ralf Nolden"),
I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"),
"[email protected]", 0 },
{ I18N_NOOP("Frank Osterfeld"),
I18N_NOOP("Resident gpgme/win wrangler, UI Server commands and dialogs"),
"[email protected]", 0 },
{ I18N_NOOP("Karl-Heinz Zimmer"),
I18N_NOOP("DN display ordering support, infrastructure"),
"[email protected]", 0 },
};
AboutData::AboutData()
: KAboutData( "kleopatra", 0, ki18n("Kleopatra"),
kleopatra_version, ki18n(description), License_GPL,
ki18n("(c) 2002 Steffen Hansen, Jesper Pedersen,\n"
"Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n"
"(c) 2004, 2007, 2008 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB") )
{
using ::authors;
using ::credits;
for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
addAuthor( ki18n(authors[i].name), ki18n(authors[i].desc),
authors[i].email, authors[i].web );
for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
addCredit( ki18n(credits[i].name), ki18n(credits[i].desc),
credits[i].email, credits[i].web );
}
<commit_msg>Sorry, Till, Volker, but there's no code from you two left in here...<commit_after>/*
aboutdata.cpp
This file is part of Kleopatra, the KDE keymanager
Copyright (c) 2001,2002,2004 Klarälvdalens Datakonsult AB
Kleopatra 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.
Kleopatra is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
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 <config-kleopatra.h>
#include "aboutdata.h"
#include <klocale.h>
static const char kleopatra_version[] = KLEOPATRA_VERSION_STRING;
static const char description[] = I18N_NOOP("Certificate Manager and Unified Crypto GUI");
struct about_data {
const char * name;
const char * desc;
const char * email;
const char * web;
};
static const about_data authors[] = {
{ "Marc Mutz", I18N_NOOP("Current Maintainer"), "[email protected]", 0 },
{ "Steffen Hansen", I18N_NOOP("Former Maintainer"), "[email protected]", 0 },
{ "Kalle Dalheimer", I18N_NOOP("Original Author"), "[email protected]", 0 },
{ "Jesper Petersen", I18N_NOOP("Original Author"), "[email protected]", 0 },
};
static const about_data credits[] = {
{ I18N_NOOP("David Faure"),
I18N_NOOP("Backend configuration framework, KIO integration"),
"[email protected]", 0 },
{ I18N_NOOP("Michel Boyer de la Giroday"),
I18N_NOOP("Key-state dependant colors and fonts in the key list"),
"[email protected]", 0 },
{ I18N_NOOP("Thomas Moenicke"),
I18N_NOOP("Artwork"),
"[email protected]", 0 },
{ I18N_NOOP("Daniel Molkentin"),
I18N_NOOP("Certificate Wizard KIOSK integration, infrastructure"),
"[email protected]", 0 },
{ I18N_NOOP("Ralf Nolden"),
I18N_NOOP("Support for obsolete EMAIL RDN in Certificate Wizard"),
"[email protected]", 0 },
{ I18N_NOOP("Frank Osterfeld"),
I18N_NOOP("Resident gpgme/win wrangler, UI Server commands and dialogs"),
"[email protected]", 0 },
{ I18N_NOOP("Karl-Heinz Zimmer"),
I18N_NOOP("DN display ordering support, infrastructure"),
"[email protected]", 0 },
};
AboutData::AboutData()
: KAboutData( "kleopatra", 0, ki18n("Kleopatra"),
kleopatra_version, ki18n(description), License_GPL,
ki18n("(c) 2002 Steffen Hansen, Jesper Pedersen,\n"
"Kalle Dalheimer, Klar\xC3\xA4lvdalens Datakonsult AB\n\n"
"(c) 2004, 2007, 2008 Marc Mutz, Klar\xC3\xA4lvdalens Datakonsult AB") )
{
using ::authors;
using ::credits;
for ( unsigned int i = 0 ; i < sizeof authors / sizeof *authors ; ++i )
addAuthor( ki18n(authors[i].name), ki18n(authors[i].desc),
authors[i].email, authors[i].web );
for ( unsigned int i = 0 ; i < sizeof credits / sizeof *credits ; ++i )
addCredit( ki18n(credits[i].name), ki18n(credits[i].desc),
credits[i].email, credits[i].web );
}
<|endoftext|> |
<commit_before>/***************************************************************************
Kopete Instant Messenger
kopetewindows.cpp
-------------------
(C) 2001-2002 by Duncan Mac-Vicar P. <[email protected]>
(C) 2001-2002 by Stefan Gehn <[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. *
* *
***************************************************************************/
#include "kopetewindow.h"
#include "kopetewindow.moc"
#include "contactlist.h"
#include "kopetecontact.h"
#include "kopete.h"
#include "kopeteballoon.h"
#include "systemtray.h"
#include <qlayout.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstdaction.h>
KopeteWindow::KopeteWindow(QWidget *parent, const char *name ): KMainWindow(parent,name)
{
kdDebug() << "[KopeteWindow] KopeteWindow()" << endl;
/* -------------------------------------------------------------------------------- */
initView();
initActions();
initSystray();
/* -------------------------------------------------------------------------------- */
loadOptions();
// we always show our statusbar
// it's important because it shows the protocol-icons
statusBar()->show();
// for now systemtray is also always shown
// TODO: make the configurable
tray->show();
}
void KopeteWindow::initView ( void )
{
mainwidget = new QWidget(this);
setCentralWidget(mainwidget);
QBoxLayout *layout = new QBoxLayout(mainwidget,QBoxLayout::TopToBottom);
contactlist = new ContactList(mainwidget);
layout->insertWidget ( -1, contactlist );
connect( contactlist, SIGNAL(executed(QListViewItem *)), this, SLOT(slotExecuted(QListViewItem *)) );
}
void KopeteWindow::initActions ( void )
{
actionAddContact = new KAction( i18n("&Add contact"),"bookmark_add", 0 ,
kopeteapp, SLOT(slotAddContact()),
actionCollection(), "AddContact" );
actionConnect = new KAction( i18n("&Connect All"),"connect_creating", 0 ,
kopeteapp, SLOT(slotConnectAll()),
actionCollection(), "Connect" );
actionDisconnect = new KAction( i18n("&Disconnect All"),"connect_no", 0 ,
kopeteapp, SLOT(slotDisconnectAll()),
actionCollection(), "Disconnect" );
actionConnectionMenu = new KActionMenu( i18n("Connection"),"connect_established",
actionCollection(), "Connection" );
actionConnectionMenu->insert(actionConnect);
actionConnectionMenu->insert(actionDisconnect);
actionSetAway = new KAction( i18n("&Set Away Globally"), "kopeteaway", 0 ,
kopeteapp, SLOT(slotSetAwayAll()),
actionCollection(), "SetAway" );
actionSetAvailable = new KAction( i18n("Set Availa&ble Globally"), "kopeteavailable", 0 ,
kopeteapp, SLOT(slotSetAvailableAll()),
actionCollection(), "SetAvailable" );
actionAwayMenu = new KActionMenu( i18n("Status"),"kopetestatus",
actionCollection(), "Status" );
actionAwayMenu->insert(actionSetAvailable);
actionAwayMenu->insert(actionSetAway);
actionPrefs = KStdAction::preferences(kopeteapp, SLOT(slotPreferences()), actionCollection());
// actionQuit = KStdAction::quit(kopeteapp, SLOT(slotExit()), actionCollection());
KStdAction::quit(kopeteapp, SLOT(quit()), actionCollection());
toolbarAction = KStdAction::showToolbar(this, SLOT(showToolbar()), actionCollection());
createGUI ( "kopeteui.rc" );
}
void KopeteWindow::initSystray ( void )
{
tray = new KopeteSystemTray(this, "KopeteSystemTray");
KPopupMenu *tm = tray->contextMenu();
tm->insertSeparator();
actionAddContact->plug( tm );
tm->insertSeparator();
// actionConnect->plug( tm );
// actionDisconnect->plug( tm );
actionConnectionMenu->plug ( tm );
actionAwayMenu->plug( tm );
tm->insertSeparator();
actionPrefs->plug( tm );
// tm->insertSeparator();
}
KopeteWindow::~KopeteWindow()
{
// delete tray;
kdDebug() << "[KopeteWindow] ~KopeteWindow()" << endl;
}
bool KopeteWindow::queryExit()
{
kdDebug() << "[KopeteWindow] queryExit()" << endl;
saveOptions();
return true;
}
void KopeteWindow::loadOptions(void)
{
KConfig *config = KGlobal::config();
toolBar("mainToolBar")->applySettings( config, "ToolBar Settings" );
applyMainWindowSettings ( config, "General Options" );
QPoint pos = config->readPointEntry("Position");
move(pos);
QSize size = config->readSizeEntry("Geometry");
if(!size.isEmpty())
{
resize(size);
}
QString tmp = config->readEntry("State", "Shown");
if ( tmp == "Minimized" )
{
showMinimized();
}
else if ( tmp == "Hidden" )
{
hide();
}
else
{
KConfig *config = KGlobal::config();
config->setGroup("Appearance");
if ( !config->readBoolEntry("StartDocked", false) )
show();
}
toolbarAction->setChecked( !toolBar("mainToolBar")->isHidden() );
}
void KopeteWindow::saveOptions(void)
{
KConfig *config = KGlobal::config();
toolBar("mainToolBar")->saveSettings ( config, "ToolBar Settings" );
saveMainWindowSettings( config, "General Options" );
config->setGroup("General Options");
config->writeEntry("Position", pos());
config->writeEntry("Geometry", size());
if(isMinimized())
{
config->writeEntry("State", "Minimized");
}
else if(isHidden())
{
config->writeEntry("State", "Hidden");
}
else
{
config->writeEntry("State", "Shown");
}
config->sync();
}
void KopeteWindow::showToolbar(void)
{
if( toolbarAction->isChecked() )
toolBar("mainToolBar")->show();
else
toolBar("mainToolBar")->hide();
}
void KopeteWindow::slotExecuted( QListViewItem *item )
{
KopeteContactViewItem *contactvi = dynamic_cast<KopeteContactViewItem *>(item);
if ( contactvi )
contactvi->contact()->execute();
}
// vim: set noet sw=4 ts=4 sts=4:
<commit_msg>Double string-fixing action<commit_after>/***************************************************************************
Kopete Instant Messenger
kopetewindows.cpp
-------------------
(C) 2001-2002 by Duncan Mac-Vicar P. <[email protected]>
(C) 2001-2002 by Stefan Gehn <[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. *
* *
***************************************************************************/
#include "kopetewindow.h"
#include "kopetewindow.moc"
#include "contactlist.h"
#include "kopetecontact.h"
#include "kopete.h"
#include "kopeteballoon.h"
#include "systemtray.h"
#include <qlayout.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstdaction.h>
KopeteWindow::KopeteWindow(QWidget *parent, const char *name ): KMainWindow(parent,name)
{
kdDebug() << "[KopeteWindow] KopeteWindow()" << endl;
/* -------------------------------------------------------------------------------- */
initView();
initActions();
initSystray();
/* -------------------------------------------------------------------------------- */
loadOptions();
// we always show our statusbar
// it's important because it shows the protocol-icons
statusBar()->show();
// for now systemtray is also always shown
// TODO: make the configurable
tray->show();
}
void KopeteWindow::initView ( void )
{
mainwidget = new QWidget(this);
setCentralWidget(mainwidget);
QBoxLayout *layout = new QBoxLayout(mainwidget,QBoxLayout::TopToBottom);
contactlist = new ContactList(mainwidget);
layout->insertWidget ( -1, contactlist );
connect( contactlist, SIGNAL(executed(QListViewItem *)), this, SLOT(slotExecuted(QListViewItem *)) );
}
void KopeteWindow::initActions ( void )
{
actionAddContact = new KAction( i18n("&Add Contact..."),"bookmark_add", 0 ,
kopeteapp, SLOT(slotAddContact()),
actionCollection(), "AddContact" );
actionConnect = new KAction( i18n("&Connect All"),"connect_creating", 0 ,
kopeteapp, SLOT(slotConnectAll()),
actionCollection(), "Connect" );
actionDisconnect = new KAction( i18n("&Disconnect All"),"connect_no", 0 ,
kopeteapp, SLOT(slotDisconnectAll()),
actionCollection(), "Disconnect" );
actionConnectionMenu = new KActionMenu( i18n("Connection"),"connect_established",
actionCollection(), "Connection" );
actionConnectionMenu->insert(actionConnect);
actionConnectionMenu->insert(actionDisconnect);
actionSetAway = new KAction( i18n("&Set Away Globally"), "kopeteaway", 0 ,
kopeteapp, SLOT(slotSetAwayAll()),
actionCollection(), "SetAway" );
actionSetAvailable = new KAction( i18n("Set Availa&ble Globally"), "kopeteavailable", 0 ,
kopeteapp, SLOT(slotSetAvailableAll()),
actionCollection(), "SetAvailable" );
actionAwayMenu = new KActionMenu( i18n("Status"),"kopetestatus",
actionCollection(), "Status" );
actionAwayMenu->insert(actionSetAvailable);
actionAwayMenu->insert(actionSetAway);
actionPrefs = KStdAction::preferences(kopeteapp, SLOT(slotPreferences()), actionCollection());
// actionQuit = KStdAction::quit(kopeteapp, SLOT(slotExit()), actionCollection());
KStdAction::quit(kopeteapp, SLOT(quit()), actionCollection());
toolbarAction = KStdAction::showToolbar(this, SLOT(showToolbar()), actionCollection());
createGUI ( "kopeteui.rc" );
}
void KopeteWindow::initSystray ( void )
{
tray = new KopeteSystemTray(this, "KopeteSystemTray");
KPopupMenu *tm = tray->contextMenu();
tm->insertSeparator();
actionAddContact->plug( tm );
tm->insertSeparator();
// actionConnect->plug( tm );
// actionDisconnect->plug( tm );
actionConnectionMenu->plug ( tm );
actionAwayMenu->plug( tm );
tm->insertSeparator();
actionPrefs->plug( tm );
// tm->insertSeparator();
}
KopeteWindow::~KopeteWindow()
{
// delete tray;
kdDebug() << "[KopeteWindow] ~KopeteWindow()" << endl;
}
bool KopeteWindow::queryExit()
{
kdDebug() << "[KopeteWindow] queryExit()" << endl;
saveOptions();
return true;
}
void KopeteWindow::loadOptions(void)
{
KConfig *config = KGlobal::config();
toolBar("mainToolBar")->applySettings( config, "ToolBar Settings" );
applyMainWindowSettings ( config, "General Options" );
QPoint pos = config->readPointEntry("Position");
move(pos);
QSize size = config->readSizeEntry("Geometry");
if(!size.isEmpty())
{
resize(size);
}
QString tmp = config->readEntry("State", "Shown");
if ( tmp == "Minimized" )
{
showMinimized();
}
else if ( tmp == "Hidden" )
{
hide();
}
else
{
KConfig *config = KGlobal::config();
config->setGroup("Appearance");
if ( !config->readBoolEntry("StartDocked", false) )
show();
}
toolbarAction->setChecked( !toolBar("mainToolBar")->isHidden() );
}
void KopeteWindow::saveOptions(void)
{
KConfig *config = KGlobal::config();
toolBar("mainToolBar")->saveSettings ( config, "ToolBar Settings" );
saveMainWindowSettings( config, "General Options" );
config->setGroup("General Options");
config->writeEntry("Position", pos());
config->writeEntry("Geometry", size());
if(isMinimized())
{
config->writeEntry("State", "Minimized");
}
else if(isHidden())
{
config->writeEntry("State", "Hidden");
}
else
{
config->writeEntry("State", "Shown");
}
config->sync();
}
void KopeteWindow::showToolbar(void)
{
if( toolbarAction->isChecked() )
toolBar("mainToolBar")->show();
else
toolBar("mainToolBar")->hide();
}
void KopeteWindow::slotExecuted( QListViewItem *item )
{
KopeteContactViewItem *contactvi = dynamic_cast<KopeteContactViewItem *>(item);
if ( contactvi )
contactvi->contact()->execute();
}
// vim: set noet sw=4 ts=4 sts=4:
<|endoftext|> |
<commit_before>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <thrift/lib/cpp2/util/ScopedServerThread.h>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <utility>
#include <folly/ScopeGuard.h>
#include <folly/SocketAddress.h>
#include <thrift/lib/cpp/concurrency/PosixThreadFactory.h>
#include <thrift/lib/cpp2/server/BaseThriftServer.h>
using std::shared_ptr;
using std::weak_ptr;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::server;
using namespace apache::thrift::transport;
namespace apache {
namespace thrift {
namespace util {
/**
* ScopedServerThread::Helper runs the server loop in the new server thread.
*
* It also provides a waitUntilStarted() method that the main thread can use to
* block until the server has started listening for new connections.
*/
class ScopedServerThread::Helper : public Runnable, public TServerEventHandler {
public:
Helper() : state_(STATE_NOT_STARTED) {}
~Helper() override;
void init(
shared_ptr<BaseThriftServer> server,
shared_ptr<Helper> self,
Func onExit);
void run() override;
/**
* Stop the server.
*
* This may be called from the main thread.
*/
void stop();
/**
* Get the address that the server is listening on.
*
* This may be called from the main thread.
*/
const folly::SocketAddress* getAddress() const {
return &address_;
}
/**
* Wait until the server has started.
*
* Raises TException if the server failed to start.
*/
void waitUntilStarted();
void preServe(const folly::SocketAddress* address) override;
const shared_ptr<BaseThriftServer>& getServer() const {
return server_;
}
void releaseServer() {
server_.reset();
}
private:
enum StateEnum {
STATE_NOT_STARTED,
STATE_RUNNING,
STATE_START_ERROR,
};
class EventHandler : public TServerEventHandler {
public:
explicit EventHandler(const shared_ptr<Helper>& outer) : outer_(outer) {}
void preServe(const folly::SocketAddress* address) override;
private:
weak_ptr<Helper> outer_;
};
// Helper class to polymorphically re-throw a saved exception type
class SavedException {
public:
virtual ~SavedException() {}
virtual void rethrow() = 0;
};
template <typename ExceptionT>
class SavedExceptionImpl : public SavedException {
public:
explicit SavedExceptionImpl(const ExceptionT& x) : exception_(x) {}
void rethrow() override {
throw exception_;
}
private:
ExceptionT exception_;
};
// Attempt to downcast to a specific type to avoid slicing.
template <typename ExceptionT>
bool tryHandleServeError(const std::exception& x) {
auto e = dynamic_cast<const ExceptionT*>(&x);
if (e) {
handleServeError<ExceptionT>(*e);
}
return e;
}
// Copying exceptions is difficult because of the slicing problem. Match the
// most commonly expected exception types, and try our best to copy as much
// state as possible.
void handleServeError(const std::exception& x) override {
tryHandleServeError<TTransportException>(x) ||
tryHandleServeError<TException>(x) ||
tryHandleServeError<std::system_error>(x) ||
tryHandleServeError<std::exception>(x);
}
template <typename ExceptionT>
void handleServeError(const ExceptionT& x) {
if (eventHandler_ && *eventHandler_) {
(*eventHandler_)->handleServeError(x);
}
std::unique_lock<std::mutex> l(stateMutex_);
if (state_ == STATE_NOT_STARTED) {
// If the error occurred before the server started,
// save a copy of the error and notify the main thread
savedError_.reset(new SavedExceptionImpl<ExceptionT>(x));
state_ = STATE_START_ERROR;
stateCondVar_.notify_one();
} else {
// The error occurred during normal server execution.
// Just log an error message.
T_ERROR(
"ScopedServerThread: serve() raised a %s while running: %s",
typeid(x).name(),
x.what());
}
}
StateEnum state_;
std::mutex stateMutex_;
std::condition_variable stateCondVar_;
shared_ptr<BaseThriftServer> server_;
Func onExit_;
// If the server event handler has been intercepted, then this field will be
// set to the replaced event handler, which could be nullptr.
folly::Optional<shared_ptr<TServerEventHandler>> eventHandler_;
shared_ptr<SavedException> savedError_;
folly::SocketAddress address_;
};
ScopedServerThread::Helper::~Helper() {
if (eventHandler_) {
server_->setServerEventHandler(*eventHandler_);
}
}
void ScopedServerThread::Helper::init(
shared_ptr<BaseThriftServer> server,
shared_ptr<Helper> self,
Func onExit) {
server_ = std::move(server);
onExit_ = std::move(onExit);
// Install ourself as the server event handler, so that our preServe() method
// will be called once we've successfully bound to the port and are about to
// start listening. If there is already an installed event handler, uninstall
// it, but remember it so we can re-install it once the server starts.
eventHandler_ = server_->getEventHandler();
// This function takes self as an argument since we need a shared_ptr to
// ourselves.
server_->setServerEventHandler(std::make_shared<EventHandler>(self));
}
void ScopedServerThread::Helper::run() {
// Call serve()
//
// If an error occurs before the server finishes starting, save the error and
// notify the main thread of the failure.
try {
server_->serve();
} catch (const std::exception& x) {
handleServeError(x);
} catch (...) {
TServerEventHandler::handleServeError();
}
if (onExit_) {
onExit_();
}
}
void ScopedServerThread::Helper::stop() {
if (server_) {
server_->stop();
}
}
void ScopedServerThread::Helper::waitUntilStarted() {
std::unique_lock<std::mutex> l(stateMutex_);
while (state_ == STATE_NOT_STARTED) {
stateCondVar_.wait(l);
}
// If an error occurred starting the server,
// throw the saved error in the main thread
if (state_ == STATE_START_ERROR) {
assert(savedError_);
savedError_->rethrow();
}
}
void ScopedServerThread::Helper::preServe(const folly::SocketAddress* address) {
// Save a copy of the address
address_ = *address;
// The eventHandler_ should have been assigned in init, even if it is only
// set to an empty shared_ptr.
CHECK(eventHandler_);
auto eventHandler = *eventHandler_;
// Re-install the old eventHandler_.
server_->setServerEventHandler(eventHandler);
eventHandler_ = folly::none;
if (eventHandler) {
// Invoke preServe() on eventHandler,
// since we intercepted the real preServe() call.
eventHandler->preServe(address);
}
// Inform the main thread that the server has started
std::unique_lock<std::mutex> l(stateMutex_);
assert(state_ == STATE_NOT_STARTED);
state_ = STATE_RUNNING;
stateCondVar_.notify_one();
}
void ScopedServerThread::Helper::EventHandler::preServe(
const folly::SocketAddress* address) {
auto outer = outer_.lock();
CHECK(outer);
outer->preServe(address);
}
/*
* ScopedServerThread methods
*/
ScopedServerThread::ScopedServerThread() {}
ScopedServerThread::ScopedServerThread(shared_ptr<BaseThriftServer> server) {
start(std::move(server));
}
ScopedServerThread::~ScopedServerThread() {
stop();
}
void ScopedServerThread::start(
shared_ptr<BaseThriftServer> server,
Func onExit) {
if (helper_) {
throw TLibraryException("ScopedServerThread is already running");
}
// Thrift forces us to use shared_ptr for both Runnable and
// TServerEventHandler objects, so we have to allocate Helper on the heap,
// rather than having it as a member variable or deriving from Runnable and
// TServerEventHandler ourself.
auto helper = std::make_shared<Helper>();
helper->init(std::move(server), helper, std::move(onExit));
// Start the thread
PosixThreadFactory threadFactory;
threadFactory.setDetached(false);
auto thread = threadFactory.newThread(helper);
thread->start();
auto threadGuard = folly::makeGuard([&] {
helper->stop();
thread->join();
});
// Wait for the server to start
helper->waitUntilStarted();
helper_ = std::move(helper);
thread_ = std::move(thread);
threadGuard.dismiss();
}
void ScopedServerThread::stop() {
if (!helper_) {
return;
}
helper_->stop();
join();
helper_.reset();
}
void ScopedServerThread::join() {
if (thread_) {
thread_->join();
}
if (helper_) {
helper_->releaseServer();
}
}
const folly::SocketAddress* ScopedServerThread::getAddress() const {
if (!helper_) {
throw TTransportException(
TTransportException::NOT_OPEN,
"attempted to get address of stopped "
"ScopedServerThread");
}
return helper_->getAddress();
}
weak_ptr<BaseThriftServer> ScopedServerThread::getServer() const {
if (!helper_) {
return weak_ptr<BaseThriftServer>();
}
return helper_->getServer();
}
bool ScopedServerThread::setServeThreadName(const std::string& name) {
return thread_->setName(name);
}
} // namespace util
} // namespace thrift
} // namespace apache
<commit_msg>thrift: Reset ScopedServerThread thread_ pointer to nullptr after join()<commit_after>/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <thrift/lib/cpp2/util/ScopedServerThread.h>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <utility>
#include <folly/ScopeGuard.h>
#include <folly/SocketAddress.h>
#include <thrift/lib/cpp/concurrency/PosixThreadFactory.h>
#include <thrift/lib/cpp2/server/BaseThriftServer.h>
using std::shared_ptr;
using std::weak_ptr;
using namespace apache::thrift::concurrency;
using namespace apache::thrift::server;
using namespace apache::thrift::transport;
namespace apache {
namespace thrift {
namespace util {
/**
* ScopedServerThread::Helper runs the server loop in the new server thread.
*
* It also provides a waitUntilStarted() method that the main thread can use to
* block until the server has started listening for new connections.
*/
class ScopedServerThread::Helper : public Runnable, public TServerEventHandler {
public:
Helper() : state_(STATE_NOT_STARTED) {}
~Helper() override;
void init(
shared_ptr<BaseThriftServer> server,
shared_ptr<Helper> self,
Func onExit);
void run() override;
/**
* Stop the server.
*
* This may be called from the main thread.
*/
void stop();
/**
* Get the address that the server is listening on.
*
* This may be called from the main thread.
*/
const folly::SocketAddress* getAddress() const {
return &address_;
}
/**
* Wait until the server has started.
*
* Raises TException if the server failed to start.
*/
void waitUntilStarted();
void preServe(const folly::SocketAddress* address) override;
const shared_ptr<BaseThriftServer>& getServer() const {
return server_;
}
void releaseServer() {
server_.reset();
}
private:
enum StateEnum {
STATE_NOT_STARTED,
STATE_RUNNING,
STATE_START_ERROR,
};
class EventHandler : public TServerEventHandler {
public:
explicit EventHandler(const shared_ptr<Helper>& outer) : outer_(outer) {}
void preServe(const folly::SocketAddress* address) override;
private:
weak_ptr<Helper> outer_;
};
// Helper class to polymorphically re-throw a saved exception type
class SavedException {
public:
virtual ~SavedException() {}
virtual void rethrow() = 0;
};
template <typename ExceptionT>
class SavedExceptionImpl : public SavedException {
public:
explicit SavedExceptionImpl(const ExceptionT& x) : exception_(x) {}
void rethrow() override {
throw exception_;
}
private:
ExceptionT exception_;
};
// Attempt to downcast to a specific type to avoid slicing.
template <typename ExceptionT>
bool tryHandleServeError(const std::exception& x) {
auto e = dynamic_cast<const ExceptionT*>(&x);
if (e) {
handleServeError<ExceptionT>(*e);
}
return e;
}
// Copying exceptions is difficult because of the slicing problem. Match the
// most commonly expected exception types, and try our best to copy as much
// state as possible.
void handleServeError(const std::exception& x) override {
tryHandleServeError<TTransportException>(x) ||
tryHandleServeError<TException>(x) ||
tryHandleServeError<std::system_error>(x) ||
tryHandleServeError<std::exception>(x);
}
template <typename ExceptionT>
void handleServeError(const ExceptionT& x) {
if (eventHandler_ && *eventHandler_) {
(*eventHandler_)->handleServeError(x);
}
std::unique_lock<std::mutex> l(stateMutex_);
if (state_ == STATE_NOT_STARTED) {
// If the error occurred before the server started,
// save a copy of the error and notify the main thread
savedError_.reset(new SavedExceptionImpl<ExceptionT>(x));
state_ = STATE_START_ERROR;
stateCondVar_.notify_one();
} else {
// The error occurred during normal server execution.
// Just log an error message.
T_ERROR(
"ScopedServerThread: serve() raised a %s while running: %s",
typeid(x).name(),
x.what());
}
}
StateEnum state_;
std::mutex stateMutex_;
std::condition_variable stateCondVar_;
shared_ptr<BaseThriftServer> server_;
Func onExit_;
// If the server event handler has been intercepted, then this field will be
// set to the replaced event handler, which could be nullptr.
folly::Optional<shared_ptr<TServerEventHandler>> eventHandler_;
shared_ptr<SavedException> savedError_;
folly::SocketAddress address_;
};
ScopedServerThread::Helper::~Helper() {
if (eventHandler_) {
server_->setServerEventHandler(*eventHandler_);
}
}
void ScopedServerThread::Helper::init(
shared_ptr<BaseThriftServer> server,
shared_ptr<Helper> self,
Func onExit) {
server_ = std::move(server);
onExit_ = std::move(onExit);
// Install ourself as the server event handler, so that our preServe() method
// will be called once we've successfully bound to the port and are about to
// start listening. If there is already an installed event handler, uninstall
// it, but remember it so we can re-install it once the server starts.
eventHandler_ = server_->getEventHandler();
// This function takes self as an argument since we need a shared_ptr to
// ourselves.
server_->setServerEventHandler(std::make_shared<EventHandler>(self));
}
void ScopedServerThread::Helper::run() {
// Call serve()
//
// If an error occurs before the server finishes starting, save the error and
// notify the main thread of the failure.
try {
server_->serve();
} catch (const std::exception& x) {
handleServeError(x);
} catch (...) {
TServerEventHandler::handleServeError();
}
if (onExit_) {
onExit_();
}
}
void ScopedServerThread::Helper::stop() {
if (server_) {
server_->stop();
}
}
void ScopedServerThread::Helper::waitUntilStarted() {
std::unique_lock<std::mutex> l(stateMutex_);
while (state_ == STATE_NOT_STARTED) {
stateCondVar_.wait(l);
}
// If an error occurred starting the server,
// throw the saved error in the main thread
if (state_ == STATE_START_ERROR) {
assert(savedError_);
savedError_->rethrow();
}
}
void ScopedServerThread::Helper::preServe(const folly::SocketAddress* address) {
// Save a copy of the address
address_ = *address;
// The eventHandler_ should have been assigned in init, even if it is only
// set to an empty shared_ptr.
CHECK(eventHandler_);
auto eventHandler = *eventHandler_;
// Re-install the old eventHandler_.
server_->setServerEventHandler(eventHandler);
eventHandler_ = folly::none;
if (eventHandler) {
// Invoke preServe() on eventHandler,
// since we intercepted the real preServe() call.
eventHandler->preServe(address);
}
// Inform the main thread that the server has started
std::unique_lock<std::mutex> l(stateMutex_);
assert(state_ == STATE_NOT_STARTED);
state_ = STATE_RUNNING;
stateCondVar_.notify_one();
}
void ScopedServerThread::Helper::EventHandler::preServe(
const folly::SocketAddress* address) {
auto outer = outer_.lock();
CHECK(outer);
outer->preServe(address);
}
/*
* ScopedServerThread methods
*/
ScopedServerThread::ScopedServerThread() {}
ScopedServerThread::ScopedServerThread(shared_ptr<BaseThriftServer> server) {
start(std::move(server));
}
ScopedServerThread::~ScopedServerThread() {
stop();
}
void ScopedServerThread::start(
shared_ptr<BaseThriftServer> server,
Func onExit) {
if (helper_) {
throw TLibraryException("ScopedServerThread is already running");
}
// Thrift forces us to use shared_ptr for both Runnable and
// TServerEventHandler objects, so we have to allocate Helper on the heap,
// rather than having it as a member variable or deriving from Runnable and
// TServerEventHandler ourself.
auto helper = std::make_shared<Helper>();
helper->init(std::move(server), helper, std::move(onExit));
// Start the thread
PosixThreadFactory threadFactory;
threadFactory.setDetached(false);
auto thread = threadFactory.newThread(helper);
thread->start();
auto threadGuard = folly::makeGuard([&] {
helper->stop();
thread->join();
});
// Wait for the server to start
helper->waitUntilStarted();
helper_ = std::move(helper);
thread_ = std::move(thread);
threadGuard.dismiss();
}
void ScopedServerThread::stop() {
if (!helper_) {
return;
}
helper_->stop();
join();
helper_.reset();
}
void ScopedServerThread::join() {
if (thread_) {
thread_->join();
// Make sure we don't try to join the thread again from the destructor.
thread_ = nullptr;
}
if (helper_) {
helper_->releaseServer();
}
}
const folly::SocketAddress* ScopedServerThread::getAddress() const {
if (!helper_) {
throw TTransportException(
TTransportException::NOT_OPEN,
"attempted to get address of stopped "
"ScopedServerThread");
}
return helper_->getAddress();
}
weak_ptr<BaseThriftServer> ScopedServerThread::getServer() const {
if (!helper_) {
return weak_ptr<BaseThriftServer>();
}
return helper_->getServer();
}
bool ScopedServerThread::setServeThreadName(const std::string& name) {
return thread_->setName(name);
}
} // namespace util
} // namespace thrift
} // namespace apache
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_tracearray.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_sbe_tracearray.H
///
/// @brief Collect contents of specified trace array via SCOM.
///
/// Collects contents of specified trace array via SCOM. Optionally
/// manages chiplet domain trace engine state (start/stop/reset) around
/// trace array data collection. Trace array data can be collected only
/// when its controlling chiplet trace engine is stopped.
///
/// Request number of Trace array entries will be packed into data buffer from
/// oldest->youngest entry.
///
/// Calling code is expected to pass the proper target type based on the
/// desired trace resource; a convenience function is provided to find out
/// the expected target type for a given trace resource.
//------------------------------------------------------------------------------
// *HWP HW Owner : Joachim Fenkes <[email protected]>
// *HWP HW Backup Owner : Joe McGill <[email protected]>
// *HWP FW Owner : Shakeeb Pasha<[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : Conus, SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_TRACEARRAY_H
#define _P9_SBE_TRACEARRAY_H
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
#include "p9_tracearray_defs.H"
constexpr uint32_t P9_TRACEARRAY_FIRST_ROW = 0;
constexpr uint32_t MCBIST_CHIPLET_ID_START = 0x07;
constexpr uint32_t MCBIST_CHIPLET_ID_END = 0x08;
constexpr uint32_t OBUS_CHIPLET_ID_START = 0x09;
constexpr uint32_t OBUS_CHIPLET_ID_END = 0x0C;
#define IS_MCBIST(chipletId) \
((chipletId >= MCBIST_CHIPLET_ID_START) && \
(chipletId <= MCBIST_CHIPLET_ID_END))
#define IS_OBUS(chipletId) \
((chipletId >= OBUS_CHIPLET_ID_START) && \
(chipletId <= OBUS_CHIPLET_ID_END))
// structure to represent HWP arguments
struct proc_gettracearray_args
{
p9_tracearray_bus_id trace_bus; ///< The trace bus whose associated trace array should be dumped
bool stop_pre_dump; ///< Stop the trace array before starting the dump
bool ignore_mux_setting; ///< Do not fail if the primary trace mux is set to a different bus
bool collect_dump; ///< Do dump the trace array; useful if you just want to start/stop
bool reset_post_dump; ///< Reset the debug logic after dumping
bool restart_post_dump; ///< Start the trace array after dumping
};
static const fapi2::TargetType P9_SBE_TRACEARRAY_TARGET_TYPES =
fapi2::TARGET_TYPE_PROC_CHIP |
fapi2::TARGET_TYPE_PERV |
fapi2::TARGET_TYPE_EX |
fapi2::TARGET_TYPE_CORE;
//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_sbe_tracearray_FP_t) (
const fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES>& i_target,
const proc_gettracearray_args& i_args,
uint64_t* o_ta_data,
const uint32_t i_cur_row,
const uint32_t i_num_rows
);
extern "C" {
/**
* @brief Return the target type needed to access a given trace array
*
* @param ta_id The trace array / trace bus ID requested.
*
* @return The type of target to hand to p9_sbe_tracearray to clearly
* identify the array instance.
*/
static inline fapi2::TargetType p9_sbe_tracearray_target_type(
p9_tracearray_bus_id i_trace_bus)
{
if (i_trace_bus <= _PROC_TB_LAST_PROC_TARGET)
{
return fapi2::TARGET_TYPE_PROC_CHIP;
}
else if (i_trace_bus <= _PROC_TB_LAST_MC_TARGET)
{
return fapi2::TARGET_TYPE_PERV;
}
else if (i_trace_bus <= _PROC_TB_LAST_EX_TARGET)
{
return fapi2::TARGET_TYPE_EX;
}
else
{
return fapi2::TARGET_TYPE_CORE;
}
}
/* TODO via RTC:164528 - Look at optimization to improve performance
* @brief Retrieve trace array data, based on the number of
* rows requested, from selected trace array via SCOM.
* Optionally performing trace stop (prior to dump) and/or
* trace restart, reset (after dump).
* If a partial dump is requested along with other control flags,
* pre-dump control would take effect before reading row 0 and
* post-dump control would take effect after reading last row.
*
* @param i_target Chip or chiplet target. The necessary target type can be
* queried through p9_sbe_tracearray_target_type().
* @param i_args Argument structure with additional parameters
* @param o_ta_data Trace array data. Will contain requested number of trace
* rows from the array concatenated,
* starting with the oldest trace entry after the previous
* dump call and ending with the newest
* @param i_cur_row Current count of the row being extracted.
* Internally used to determine the order of
* pre and post dump control in case of partial dump.
* @param i_num_rows Number of rows of the tracearray to read.
* By default P9_TRACEARRAY_NUM_ROWS are read
*
* @return FAPI2_RC_SUCCESS
* if trace array dump sequence completes successfully,
* RC_PROC_GETTRACEARRAY_INVALID_BUS
* if an invalid trace bus ID has been requested
* RC_PROC_GETTRACEARRAY_INVALID_TARGET
* if the supplied target type does not match the requested trace bus
* RC_PROC_GETTRACEARRAY_CORE_NOT_DUMPABLE
* if a core trace array has been requested but the chip's core
* is not dumpable via SCOM -> use fastarray instead
* RC_PROC_GETTRACEARRAY_TRACE_RUNNING
* if trace array is running when dump collection is attempted,
* RC_PROC_GETTRACEARRAY_TRACE_MUX_INCORRECT
* if the primary trace mux is not set up to trace the requested bus,
* else FAPI getscom/putscom return code for failing operation
*/
fapi2::ReturnCode p9_sbe_tracearray(
const fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES>& i_target,
const proc_gettracearray_args& i_args,
uint64_t* o_ta_data,
const uint32_t i_cur_row = P9_TRACEARRAY_FIRST_ROW,
const uint32_t i_num_rows = P9_TRACEARRAY_NUM_ROWS
);
} // extern "C"
#endif //_P9_SBE_TRACEARRAY_H
<commit_msg>p9_sbe_tracearray: Level 3<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_tracearray.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
/// @file p9_sbe_tracearray.H
///
/// @brief Collect contents of specified trace array via SCOM.
///
/// Collects contents of specified trace array via SCOM. Optionally
/// manages chiplet domain trace engine state (start/stop/reset) around
/// trace array data collection. Trace array data can be collected only
/// when its controlling chiplet trace engine is stopped.
///
/// Request number of Trace array entries will be packed into data buffer from
/// oldest->youngest entry.
///
/// Calling code is expected to pass the proper target type based on the
/// desired trace resource; a convenience function is provided to find out
/// the expected target type for a given trace resource.
//------------------------------------------------------------------------------
// *HWP HW Owner : Joachim Fenkes <[email protected]>
// *HWP HW Backup Owner : Joe McGill <[email protected]>
// *HWP FW Owner : Shakeeb Pasha<[email protected]>
// *HWP Team : Perv
// *HWP Level : 3
// *HWP Consumed by : Conus, SBE
//------------------------------------------------------------------------------
#ifndef _P9_SBE_TRACEARRAY_H
#define _P9_SBE_TRACEARRAY_H
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
#include "p9_tracearray_defs.H"
constexpr uint32_t P9_TRACEARRAY_FIRST_ROW = 0;
constexpr uint32_t MCBIST_CHIPLET_ID_START = 0x07;
constexpr uint32_t MCBIST_CHIPLET_ID_END = 0x08;
constexpr uint32_t OBUS_CHIPLET_ID_START = 0x09;
constexpr uint32_t OBUS_CHIPLET_ID_END = 0x0C;
#define IS_MCBIST(chipletId) \
((chipletId >= MCBIST_CHIPLET_ID_START) && \
(chipletId <= MCBIST_CHIPLET_ID_END))
#define IS_OBUS(chipletId) \
((chipletId >= OBUS_CHIPLET_ID_START) && \
(chipletId <= OBUS_CHIPLET_ID_END))
// structure to represent HWP arguments
struct proc_gettracearray_args
{
p9_tracearray_bus_id trace_bus; ///< The trace bus whose associated trace array should be dumped
bool stop_pre_dump; ///< Stop the trace array before starting the dump
bool ignore_mux_setting; ///< Do not fail if the primary trace mux is set to a different bus
bool collect_dump; ///< Do dump the trace array; useful if you just want to start/stop
bool reset_post_dump; ///< Reset the debug logic after dumping
bool restart_post_dump; ///< Start the trace array after dumping
};
static const fapi2::TargetType P9_SBE_TRACEARRAY_TARGET_TYPES =
fapi2::TARGET_TYPE_PROC_CHIP |
fapi2::TARGET_TYPE_PERV |
fapi2::TARGET_TYPE_EX |
fapi2::TARGET_TYPE_CORE;
//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_sbe_tracearray_FP_t) (
const fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES>& i_target,
const proc_gettracearray_args& i_args,
uint64_t* o_ta_data,
const uint32_t i_cur_row,
const uint32_t i_num_rows
);
extern "C" {
/**
* @brief Return the target type needed to access a given trace array
*
* @param ta_id The trace array / trace bus ID requested.
*
* @return The type of target to hand to p9_sbe_tracearray to clearly
* identify the array instance.
*/
static inline fapi2::TargetType p9_sbe_tracearray_target_type(
p9_tracearray_bus_id i_trace_bus)
{
if (i_trace_bus <= _PROC_TB_LAST_PROC_TARGET)
{
return fapi2::TARGET_TYPE_PROC_CHIP;
}
else if (i_trace_bus <= _PROC_TB_LAST_MC_TARGET)
{
return fapi2::TARGET_TYPE_PERV;
}
else if (i_trace_bus <= _PROC_TB_LAST_EX_TARGET)
{
return fapi2::TARGET_TYPE_EX;
}
else
{
return fapi2::TARGET_TYPE_CORE;
}
}
/* TODO via RTC:164528 - Look at optimization to improve performance
* @brief Retrieve trace array data, based on the number of
* rows requested, from selected trace array via SCOM.
* Optionally performing trace stop (prior to dump) and/or
* trace restart, reset (after dump).
* If a partial dump is requested along with other control flags,
* pre-dump control would take effect before reading row 0 and
* post-dump control would take effect after reading last row.
*
* @param i_target Chip or chiplet target. The necessary target type can be
* queried through p9_sbe_tracearray_target_type().
* @param i_args Argument structure with additional parameters
* @param o_ta_data Trace array data. Will contain requested number of trace
* rows from the array concatenated,
* starting with the oldest trace entry after the previous
* dump call and ending with the newest
* @param i_cur_row Current count of the row being extracted.
* Internally used to determine the order of
* pre and post dump control in case of partial dump.
* @param i_num_rows Number of rows of the tracearray to read.
* By default P9_TRACEARRAY_NUM_ROWS are read
*
* @return FAPI2_RC_SUCCESS
* if trace array dump sequence completes successfully,
* RC_PROC_GETTRACEARRAY_INVALID_BUS
* if an invalid trace bus ID has been requested
* RC_PROC_GETTRACEARRAY_INVALID_TARGET
* if the supplied target type does not match the requested trace bus
* RC_PROC_GETTRACEARRAY_CORE_NOT_DUMPABLE
* if a core trace array has been requested but the chip's core
* is not dumpable via SCOM -> use fastarray instead
* RC_PROC_GETTRACEARRAY_TRACE_RUNNING
* if trace array is running when dump collection is attempted,
* RC_PROC_GETTRACEARRAY_TRACE_MUX_INCORRECT
* if the primary trace mux is not set up to trace the requested bus,
* else FAPI getscom/putscom return code for failing operation
*/
fapi2::ReturnCode p9_sbe_tracearray(
const fapi2::Target<P9_SBE_TRACEARRAY_TARGET_TYPES>& i_target,
const proc_gettracearray_args& i_args,
uint64_t* o_ta_data,
const uint32_t i_cur_row = P9_TRACEARRAY_FIRST_ROW,
const uint32_t i_num_rows = P9_TRACEARRAY_NUM_ROWS
);
} // extern "C"
#endif //_P9_SBE_TRACEARRAY_H
<|endoftext|> |
<commit_before>#pragma once
#include <fc/io/enum_type.hpp>
#include <fc/io/raw.hpp>
#include <fc/reflect/reflect.hpp>
/**
* The C keyword 'not' is NOT friendly on VC++ but we still want to use
* it for readability, so we will have the pre-processor convert it to the
* more traditional form. The goal here is to make the understanding of
* the validation logic as english-like as possible.
*/
#define NOT !
namespace bts { namespace blockchain {
class transaction_evaluation_state;
enum operation_type_enum
{
null_op_type = 0,
/** balance operations */
withdraw_op_type = 1,
deposit_op_type = 2,
/** account operations */
register_account_op_type = 3,
update_account_op_type = 4,
withdraw_pay_op_type = 5,
/** asset operations */
create_asset_op_type = 6,
update_asset_op_type = 7,
issue_asset_op_type = 8,
/** delegate operations */
fire_delegate_op_type = 9,
/** proposal operations */
submit_proposal_op_type = 10,
vote_proposal_op_type = 11,
/** market operations */
bid_op_type = 12,
ask_op_type = 13,
short_op_type = 14,
cover_op_type = 15,
add_collateral_op_type = 16,
remove_collateral_op_type = 17,
define_delegate_slate_op_type = 18,
update_feed_op_type = 19,
burn_op_type = 20,
link_account_op_type = 21,
withdraw_all_op_type = 22
};
/**
* A poly-morphic operator that modifies the blockchain database
* is some manner.
*/
struct operation
{
operation():type(null_op_type){}
operation( const operation& o )
:type(o.type),data(o.data){}
operation( operation&& o )
:type(o.type),data(std::move(o.data)){}
template<typename OperationType>
operation( const OperationType& t )
{
type = OperationType::type;
data = fc::raw::pack( t );
}
template<typename OperationType>
OperationType as()const
{
FC_ASSERT( (operation_type_enum)type == OperationType::type, "", ("type",type)("OperationType",OperationType::type) );
return fc::raw::unpack<OperationType>(data);
}
operation& operator=( const operation& o )
{
if( this == &o ) return *this;
type = o.type;
data = o.data;
return *this;
}
operation& operator=( operation&& o )
{
if( this == &o ) return *this;
type = o.type;
data = std::move(o.data);
return *this;
}
fc::enum_type<uint8_t,operation_type_enum> type;
std::vector<char> data;
};
} } // bts::blockchain
FC_REFLECT_ENUM( bts::blockchain::operation_type_enum,
(null_op_type)
(withdraw_op_type)
(deposit_op_type)
(register_account_op_type)
(update_account_op_type)
(withdraw_pay_op_type)
(create_asset_op_type)
(update_asset_op_type)
(issue_asset_op_type)
(submit_proposal_op_type)
(vote_proposal_op_type)
(bid_op_type)
(ask_op_type)
(short_op_type)
(cover_op_type)
(add_collateral_op_type)
(remove_collateral_op_type)
(define_delegate_slate_op_type)
(update_feed_op_type)
(burn_op_type)
(link_account_op_type)
)
FC_REFLECT( bts::blockchain::operation, (type)(data) )
namespace fc {
void to_variant( const bts::blockchain::operation& var, variant& vo );
void from_variant( const variant& var, bts::blockchain::operation& vo );
}
<commit_msg>Add missing reflection of withdraw_all_op_type<commit_after>#pragma once
#include <fc/io/enum_type.hpp>
#include <fc/io/raw.hpp>
#include <fc/reflect/reflect.hpp>
/**
* The C keyword 'not' is NOT friendly on VC++ but we still want to use
* it for readability, so we will have the pre-processor convert it to the
* more traditional form. The goal here is to make the understanding of
* the validation logic as english-like as possible.
*/
#define NOT !
namespace bts { namespace blockchain {
class transaction_evaluation_state;
enum operation_type_enum
{
null_op_type = 0,
/** balance operations */
withdraw_op_type = 1,
deposit_op_type = 2,
/** account operations */
register_account_op_type = 3,
update_account_op_type = 4,
withdraw_pay_op_type = 5,
/** asset operations */
create_asset_op_type = 6,
update_asset_op_type = 7,
issue_asset_op_type = 8,
/** delegate operations */
fire_delegate_op_type = 9,
/** proposal operations */
submit_proposal_op_type = 10,
vote_proposal_op_type = 11,
/** market operations */
bid_op_type = 12,
ask_op_type = 13,
short_op_type = 14,
cover_op_type = 15,
add_collateral_op_type = 16,
remove_collateral_op_type = 17,
define_delegate_slate_op_type = 18,
update_feed_op_type = 19,
burn_op_type = 20,
link_account_op_type = 21,
withdraw_all_op_type = 22
};
/**
* A poly-morphic operator that modifies the blockchain database
* is some manner.
*/
struct operation
{
operation():type(null_op_type){}
operation( const operation& o )
:type(o.type),data(o.data){}
operation( operation&& o )
:type(o.type),data(std::move(o.data)){}
template<typename OperationType>
operation( const OperationType& t )
{
type = OperationType::type;
data = fc::raw::pack( t );
}
template<typename OperationType>
OperationType as()const
{
FC_ASSERT( (operation_type_enum)type == OperationType::type, "", ("type",type)("OperationType",OperationType::type) );
return fc::raw::unpack<OperationType>(data);
}
operation& operator=( const operation& o )
{
if( this == &o ) return *this;
type = o.type;
data = o.data;
return *this;
}
operation& operator=( operation&& o )
{
if( this == &o ) return *this;
type = o.type;
data = std::move(o.data);
return *this;
}
fc::enum_type<uint8_t,operation_type_enum> type;
std::vector<char> data;
};
} } // bts::blockchain
FC_REFLECT_ENUM( bts::blockchain::operation_type_enum,
(null_op_type)
(withdraw_op_type)
(deposit_op_type)
(register_account_op_type)
(update_account_op_type)
(withdraw_pay_op_type)
(create_asset_op_type)
(update_asset_op_type)
(issue_asset_op_type)
(submit_proposal_op_type)
(vote_proposal_op_type)
(bid_op_type)
(ask_op_type)
(short_op_type)
(cover_op_type)
(add_collateral_op_type)
(remove_collateral_op_type)
(define_delegate_slate_op_type)
(update_feed_op_type)
(burn_op_type)
(link_account_op_type)
(withdraw_all_op_type)
)
FC_REFLECT( bts::blockchain::operation, (type)(data) )
namespace fc {
void to_variant( const bts::blockchain::operation& var, variant& vo );
void from_variant( const variant& var, bts::blockchain::operation& vo );
}
<|endoftext|> |
<commit_before>/* medDropSite.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Fri Feb 19 17:41:43 2010 (+0100)
* Version: $Id$
* Last-Updated: Mon Feb 22 21:15:03 2010 (+0100)
* By: Julien Wintz
* Update #: 18
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "medViewPool.h"
#include <medCore/medMessageController.h>
#include <medCore/medAbstractView.h>
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractProcess.h>
#include <dtkCore/dtkAbstractProcessFactory.h>
#include "medCore/medMessageController.h"
class medViewPoolPrivate
{
public:
QList<medAbstractView *> views;
QMap<medAbstractView*, dtkAbstractData*> viewData;
QHash<QString, QString> propertySet;
};
medViewPool::medViewPool(void) : d (new medViewPoolPrivate)
{
connect(this,SIGNAL(showInfo(QObject*,const QString&,unsigned int)),
medMessageController::instance(),SLOT(showInfo(QObject*,const QString&,unsigned int)));
connect(this,SIGNAL(showError(QObject*,const QString&,unsigned int)),
medMessageController::instance(),SLOT(showError(QObject*,const QString&,unsigned int)));
}
medViewPool::~medViewPool(void)
{
delete d;
d = NULL;
}
void medViewPool::appendView (medAbstractView *view)
{
if (!view || d->views.contains (view))
return;
if (d->views.count()==0) { // view will become daddy
view->setProperty ("Daddy", "true");
}
d->views.append (view);
connect (view, SIGNAL (propertySet(const QString&, const QString&)), this, SLOT (onViewPropertySet(const QString&, const QString &)));
connect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (onViewDaddy(bool)));
connect (view, SIGNAL (reg(bool)), this, SLOT (onViewReg(bool)));
connect (view, SIGNAL (positionChanged (const QVector3D &, bool)), this, SLOT (onViewPositionChanged (const QVector3D &, bool)));
connect (view, SIGNAL (zoomChanged (double, bool)), this, SLOT (onViewZoomChanged (double, bool)));
connect (view, SIGNAL (panChanged (const QVector2D &, bool)), this, SLOT (onViewPanChanged (const QVector2D &, bool)));
connect (view, SIGNAL (windowingChanged (double, double, bool)), this, SLOT (onViewWindowingChanged (double, double, bool)));
connect (view, SIGNAL (cameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)),
this, SLOT (onViewCameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)));
// set properties
QHashIterator<QString, QString> it(d->propertySet);
while (it.hasNext()) {
it.next();
view->setProperty (it.key(), it.value());
}
}
void medViewPool::removeView (medAbstractView *view)
{
if (!view || !d->views.contains (view))
return;
// look if a view is a daddy
medAbstractView *refView = this->daddy();
if (refView) {
if (refView==view) { // we are daddy, we need to find a new daddy
// change daddy
QList<medAbstractView *>::iterator it = d->views.begin();
for( ; it!=d->views.end(); it++)
if ((*it)!=refView && (*it)->property ("Daddy")=="false") {
(*it)->setProperty ("Daddy", "true");
break;
}
medAbstractView *oldDaddy = refView;
oldDaddy->setProperty ("Daddy", "false"); // not necessary
}
}
disconnect (view, SIGNAL (propertySet(const QString&, const QString&)), this, SLOT (onViewPropertySet(const QString&, const QString &)));
disconnect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (onViewDaddy(bool)));
disconnect (view, SIGNAL (reg(bool)), this, SLOT (onViewReg(bool)));
disconnect (view, SIGNAL (positionChanged (const QVector3D &, bool)), this, SLOT (onViewPositionChanged (const QVector3D &, bool)));
disconnect (view, SIGNAL (zoomChanged (double, bool)), this, SLOT (onViewZoomChanged (double, bool)));
disconnect (view, SIGNAL (panChanged (const QVector2D &, bool)), this, SLOT (onViewPanChanged (const QVector2D &, bool)));
disconnect (view, SIGNAL (windowingChanged (double, double, bool)), this, SLOT (onViewWindowingChanged (double, double, bool)));
disconnect (view, SIGNAL (cameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)),
this, SLOT (onViewCameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)));
d->views.removeOne (view);
}
medAbstractView *medViewPool::daddy (void)
{
QList<medAbstractView *>::iterator it = d->views.begin();
for( ; it!=d->views.end(); it++) {
if ((*it)->property ("Daddy")=="true")
return (*it);
}
return NULL;
}
void medViewPool::onViewDaddy (bool daddy)
{
if (medAbstractView *view = dynamic_cast<medAbstractView *>(this->sender())) {
if (daddy) { // view wants to become daddy
medAbstractView *refView = this->daddy();
// tell all views that they are not daddys
QList<medAbstractView *>::iterator it = d->views.begin();
for( ; it!=d->views.end(); it++)
(*it)->setProperty ("Daddy", "false");
// tell the sender it is now daddy
view->setProperty ("Daddy", "true");
// restore the previous data (if any)
if ( d->viewData[view] ) {
view->setData (d->viewData[view], 0);
d->viewData[view] = NULL;
if (view->widget()->isVisible())
view->update();
}
}
else { // view does not want to become daddy
view->setProperty ("Daddy", "false");
}
}
}
void medViewPool::onViewReg(bool value)
{
if (medAbstractView *view = dynamic_cast<medAbstractView *>(this->sender())) {
medAbstractView *refView = this->daddy();
if (value) {
if (refView==view) // do not register the view with itself
return;
if (refView) {
dtkAbstractData *data1 = static_cast<dtkAbstractData *>(refView->data());
dtkAbstractData *data2 = static_cast<dtkAbstractData *>(view->data());
if (data1!=data2) {// do not register the same data
dtkAbstractProcess *process = dtkAbstractProcessFactory::instance()->create("itkProcessRegistration");
if (!process)
return;
process->setInput (data1, 0);
process->setInput (data2, 1);
if (process->run()==0) {
dtkAbstractData *output = process->output();
d->viewData[view] = data2;
view->setData (output, 0);
view->blockSignals(true);
view->setPosition(refView->position());
view->setZoom(refView->zoom());
view->setPan(refView->pan());
QVector3D position, viewup, focal;
double parallelScale;
refView->camera(position, viewup, focal, parallelScale);
view->setCamera(position, viewup, focal, parallelScale);
view->blockSignals(false);
if (view->widget()->isVisible())
view->update();
emit showInfo (this, tr ("Automatic registration successful"),3000);
}
else {
emit showError(this, tr ("Automatic registration failed"),3000);
}
process->deleteLater();
}
}
}
else { // restore the previous data (if any)
if ( d->viewData[view] ) {
dtkAbstractData *oldData = static_cast<dtkAbstractData*>( view->data() );
view->setData (d->viewData[view], 0);
view->blockSignals(true);
view->setPosition(refView->position());
view->setZoom(refView->zoom());
view->setPan(refView->pan());
QVector3D position, viewup, focal;
double parallelScale;
refView->camera(position, viewup, focal, parallelScale);
view->setCamera(position, viewup, focal, parallelScale);
view->blockSignals(false);
d->viewData[view] = NULL;
if (oldData)
oldData->deleteLater();
if (view->widget()->isVisible())
view->update();
}
}
}
}
void medViewPool::onViewPropertySet (const QString &key, const QString &value)
{
// property that we do not want to synchronize
if (key=="Daddy" ||
key=="PositionLinked" ||
key=="CameraLinked" ||
key=="WindowingLinked" ||
key=="Orientation" ||
key=="LookupTable")
return;
d->propertySet[key] = value;
// first, block all signals
foreach (medAbstractView *lview, d->views)
lview->blockSignals (true);
// second, propagate properties
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender()) {
lview->setProperty (key, value);
if (lview->widget()->isVisible())
lview->update();
}
}
// third, restore signals
foreach (medAbstractView *lview, d->views)
lview->blockSignals (false);
}
void medViewPool::onViewPositionChanged (const QVector3D &position, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if ( lview != vsender && lview->positionLinked() ) {
lview->onPositionChanged(position);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewCameraChanged (const QVector3D &position,
const QVector3D &viewup,
const QVector3D &focal,
double parallelScale,
bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->cameraLinked()) {
lview->onCameraChanged(position, viewup, focal, parallelScale);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewZoomChanged (double zoom, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->cameraLinked()) {
lview->onZoomChanged(zoom);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewPanChanged (const QVector2D &pan, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->cameraLinked()) {
lview->onPanChanged(pan);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewWindowingChanged (double level, double window, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->windowingLinked()) {
lview->onWindowingChanged(level, window);
if (lview->widget()->isVisible())
lview->update();
}
}
}
int medViewPool::count (void)
{
return d->views.count();
}
<commit_msg>Code simplification + do not transmit presets in medViewPool<commit_after>/* medDropSite.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008 - Julien Wintz, Inria.
* Created: Fri Feb 19 17:41:43 2010 (+0100)
* Version: $Id$
* Last-Updated: Mon Feb 22 21:15:03 2010 (+0100)
* By: Julien Wintz
* Update #: 18
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "medViewPool.h"
#include <medCore/medMessageController.h>
#include <medCore/medAbstractView.h>
#include <dtkCore/dtkAbstractData.h>
#include <dtkCore/dtkAbstractProcess.h>
#include <dtkCore/dtkAbstractProcessFactory.h>
#include "medCore/medMessageController.h"
class medViewPoolPrivate
{
public:
QList<medAbstractView *> views;
QMap<medAbstractView*, dtkAbstractData*> viewData;
QHash<QString, QString> propertySet;
};
medViewPool::medViewPool(void) : d (new medViewPoolPrivate)
{
connect(this,SIGNAL(showInfo(QObject*,const QString&,unsigned int)),
medMessageController::instance(),SLOT(showInfo(QObject*,const QString&,unsigned int)));
connect(this,SIGNAL(showError(QObject*,const QString&,unsigned int)),
medMessageController::instance(),SLOT(showError(QObject*,const QString&,unsigned int)));
}
medViewPool::~medViewPool(void)
{
delete d;
d = NULL;
}
void medViewPool::appendView (medAbstractView *view)
{
if (!view || d->views.contains (view))
return;
if (d->views.count()==0) { // view will become daddy
view->setProperty ("Daddy", "true");
}
d->views.append (view);
connect (view, SIGNAL (propertySet(const QString&, const QString&)), this, SLOT (onViewPropertySet(const QString&, const QString &)));
connect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (onViewDaddy(bool)));
connect (view, SIGNAL (reg(bool)), this, SLOT (onViewReg(bool)));
connect (view, SIGNAL (positionChanged (const QVector3D &, bool)), this, SLOT (onViewPositionChanged (const QVector3D &, bool)));
connect (view, SIGNAL (zoomChanged (double, bool)), this, SLOT (onViewZoomChanged (double, bool)));
connect (view, SIGNAL (panChanged (const QVector2D &, bool)), this, SLOT (onViewPanChanged (const QVector2D &, bool)));
connect (view, SIGNAL (windowingChanged (double, double, bool)), this, SLOT (onViewWindowingChanged (double, double, bool)));
connect (view, SIGNAL (cameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)),
this, SLOT (onViewCameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)));
// set properties
QHashIterator<QString, QString> it(d->propertySet);
while (it.hasNext()) {
it.next();
view->setProperty (it.key(), it.value());
}
}
void medViewPool::removeView (medAbstractView *view)
{
if (!view || !d->views.contains (view))
return;
// look if a view is a daddy
medAbstractView *refView = this->daddy();
if (refView) {
if (refView==view) { // we are daddy, we need to find a new daddy
// change daddy
foreach(medAbstractView *lview, d->views) {
if (lview!=refView && lview->property ("Daddy")=="false") {
lview->setProperty ("Daddy", "true");
break;
}
}
medAbstractView *oldDaddy = refView;
oldDaddy->setProperty ("Daddy", "false"); // not necessary
}
}
disconnect (view, SIGNAL (propertySet(const QString&, const QString&)), this, SLOT (onViewPropertySet(const QString&, const QString &)));
disconnect (view, SIGNAL (becomeDaddy(bool)), this, SLOT (onViewDaddy(bool)));
disconnect (view, SIGNAL (reg(bool)), this, SLOT (onViewReg(bool)));
disconnect (view, SIGNAL (positionChanged (const QVector3D &, bool)), this, SLOT (onViewPositionChanged (const QVector3D &, bool)));
disconnect (view, SIGNAL (zoomChanged (double, bool)), this, SLOT (onViewZoomChanged (double, bool)));
disconnect (view, SIGNAL (panChanged (const QVector2D &, bool)), this, SLOT (onViewPanChanged (const QVector2D &, bool)));
disconnect (view, SIGNAL (windowingChanged (double, double, bool)), this, SLOT (onViewWindowingChanged (double, double, bool)));
disconnect (view, SIGNAL (cameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)),
this, SLOT (onViewCameraChanged (const QVector3D &, const QVector3D &, const QVector3D &, double, bool)));
d->views.removeOne (view);
}
medAbstractView *medViewPool::daddy (void)
{
QList<medAbstractView *>::iterator it = d->views.begin();
for( ; it!=d->views.end(); it++) {
if ((*it)->property ("Daddy")=="true")
return (*it);
}
return NULL;
}
void medViewPool::onViewDaddy (bool daddy)
{
if (medAbstractView *view = dynamic_cast<medAbstractView *>(this->sender())) {
if (daddy) { // view wants to become daddy
medAbstractView *refView = this->daddy();
// tell all views that they are not daddys
QList<medAbstractView *>::iterator it = d->views.begin();
for( ; it!=d->views.end(); it++)
(*it)->setProperty ("Daddy", "false");
// tell the sender it is now daddy
view->setProperty ("Daddy", "true");
// restore the previous data (if any)
if ( d->viewData[view] ) {
view->setData (d->viewData[view], 0);
d->viewData[view] = NULL;
if (view->widget()->isVisible())
view->update();
}
}
else { // view does not want to become daddy
view->setProperty ("Daddy", "false");
}
}
}
void medViewPool::onViewReg(bool value)
{
if (medAbstractView *view = dynamic_cast<medAbstractView *>(this->sender())) {
medAbstractView *refView = this->daddy();
if (value) {
if (refView==view) // do not register the view with itself
return;
if (refView) {
dtkAbstractData *data1 = static_cast<dtkAbstractData *>(refView->data());
dtkAbstractData *data2 = static_cast<dtkAbstractData *>(view->data());
if (data1!=data2) {// do not register the same data
dtkAbstractProcess *process = dtkAbstractProcessFactory::instance()->create("itkProcessRegistration");
if (!process)
return;
process->setInput (data1, 0);
process->setInput (data2, 1);
if (process->run()==0) {
dtkAbstractData *output = process->output();
d->viewData[view] = data2;
view->setData (output, 0);
view->blockSignals(true);
view->setPosition(refView->position());
view->setZoom(refView->zoom());
view->setPan(refView->pan());
QVector3D position, viewup, focal;
double parallelScale;
refView->camera(position, viewup, focal, parallelScale);
view->setCamera(position, viewup, focal, parallelScale);
view->blockSignals(false);
if (view->widget()->isVisible())
view->update();
emit showInfo (this, tr ("Automatic registration successful"),3000);
}
else {
emit showError(this, tr ("Automatic registration failed"),3000);
}
process->deleteLater();
}
}
}
else { // restore the previous data (if any)
if ( d->viewData[view] ) {
dtkAbstractData *oldData = static_cast<dtkAbstractData*>( view->data() );
view->setData (d->viewData[view], 0);
view->blockSignals(true);
view->setPosition(refView->position());
view->setZoom(refView->zoom());
view->setPan(refView->pan());
QVector3D position, viewup, focal;
double parallelScale;
refView->camera(position, viewup, focal, parallelScale);
view->setCamera(position, viewup, focal, parallelScale);
view->blockSignals(false);
d->viewData[view] = NULL;
if (oldData)
oldData->deleteLater();
if (view->widget()->isVisible())
view->update();
}
}
}
}
void medViewPool::onViewPropertySet (const QString &key, const QString &value)
{
// property that we do not want to synchronize
if (key=="Daddy" ||
key=="PositionLinked" ||
key=="CameraLinked" ||
key=="WindowingLinked" ||
key=="Orientation" ||
key=="LookupTable" ||
key=="Preset")
return;
d->propertySet[key] = value;
// first, block all signals
foreach (medAbstractView *lview, d->views)
lview->blockSignals (true);
// second, propagate properties
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender()) {
lview->setProperty (key, value);
if (lview->widget()->isVisible())
lview->update();
}
}
// third, restore signals
foreach (medAbstractView *lview, d->views)
lview->blockSignals (false);
}
void medViewPool::onViewPositionChanged (const QVector3D &position, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if ( lview != vsender && lview->positionLinked() ) {
lview->onPositionChanged(position);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewCameraChanged (const QVector3D &position,
const QVector3D &viewup,
const QVector3D &focal,
double parallelScale,
bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->cameraLinked()) {
lview->onCameraChanged(position, viewup, focal, parallelScale);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewZoomChanged (double zoom, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->cameraLinked()) {
lview->onZoomChanged(zoom);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewPanChanged (const QVector2D &pan, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->cameraLinked()) {
lview->onPanChanged(pan);
if (lview->widget()->isVisible())
lview->update();
}
}
}
void medViewPool::onViewWindowingChanged (double level, double window, bool propagate)
{
if (!propagate)
return;
medAbstractView *vsender = dynamic_cast<medAbstractView*>(this->sender());
if (!vsender) {
qDebug() << "Sender seems not to be a medAbstractView";
return;
}
foreach (medAbstractView *lview, d->views) {
if (lview!=this->sender() && lview->windowingLinked()) {
lview->onWindowingChanged(level, window);
if (lview->widget()->isVisible())
lview->update();
}
}
}
int medViewPool::count (void)
{
return d->views.count();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenVoronoi.
*
* OpenVoronoi 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.
*
* OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <iostream>
#include "graph.hpp"
#include "common/numeric.hpp"
#include "site.hpp"
#include "filter.hpp"
namespace ovd
{
/// \brief Filter for retaining the medial-axis of a voronoi diagram
///
/// (approximate) medial-axis Filter.
/// marks the valid-property true for edges belonging to the medial axis
/// and false for other edges.
struct medial_axis_filter : public Filter {
/// \param thr dot-product threshold used to decide whether the segments
/// that connect to a given Edge are nearly parallel
medial_axis_filter( double thr=0.8) : _dot_product_threshold(thr) { }
/// predicate that decides if an edge is to be included or not.
bool operator()(const HEEdge& e) const {
if ( (*g)[e].type == LINESITE || (*g)[e].type == NULLEDGE)
return true; // we keep linesites and nulledges
if ( (*g)[e].type == SEPARATOR)
return false; // separators are allways removed
if (both_endpoints_positive(e)) // these are interior edges which we keep.
return true;
// this leaves us with edges where one end connects to the polygon (dist==0)
// and the other end does not.
// figure out the angle between the adjacent line-segments and decide based on the angle.
if (segments_parallel(e))
return false;
return true; // otherwise we keep the edge
}
private:
/// return true if this is an internal edge, i.e. both endpoints have a nonzero clearance-disk radius
bool both_endpoints_positive(HEEdge e) const {
HEVertex src = g->source(e);
HEVertex trg = g->target(e);
return ((*g)[src].dist()>0) && ((*g)[trg].dist()>0);
}
/// return true if the segments that connect to the given Edge are nearly parallel
bool segments_parallel( HEEdge e ) const {
HEVertex endp1 = find_endpoint(e);
HEVertex endp2 = find_endpoint( (*g)[e].twin );
// find the segments
HEEdge e1 = find_segment(endp1);
HEEdge e2 = find_segment(endp2);
e2 = (*g)[e2].twin; // this makes the edges oriented in the same direction
double dotprod = edge_dotprod(e1,e2);
return fabs(dotprod)>_dot_product_threshold;
}
/// \brief calculate the dot-product between unit vectors aligned along edges e1->e2
///
/// since e1 and e2 are both line-sites the direction is easy to find
/// FIXME: more code needed here for tangent calculation if we have arc-sites
double edge_dotprod(HEEdge e1, HEEdge e2) const {
HEVertex src1 = g->source(e1);
HEVertex trg1 = g->target(e1);
HEVertex src2 = g->source(e2);
HEVertex trg2 = g->target(e2);
Point sp1 = (*g)[src1].position;
Point tp1 = (*g)[trg1].position;
Point sp2 = (*g)[src2].position;
Point tp2 = (*g)[trg2].position;
Point dir1 = tp1-sp1;
Point dir2 = tp2-sp2;
dir1.normalize();
dir2.normalize();
return dir1.dot(dir2);
}
/// find the LineSite edge that connects to \a v
HEEdge find_segment(HEVertex v) const {
BOOST_FOREACH(HEEdge e, g->out_edges(v)) {
if ( (*g)[e].type == LINESITE )
return e;
}
assert(0);
exit(-1);
return HEEdge();
}
/// find an ::ENDPOINT vertex that connects to Edge e through a ::NULLEDGE at either the source or target of e.
HEVertex find_endpoint(HEEdge e) const {
HEEdge next = (*g)[e].next;
HEEdge prev = g->previous_edge(e);
HEVertex endp;
if ( (*g)[next].type == NULLEDGE ) {
endp = g->target(next);
assert( (*g)[endp].type == ENDPOINT );
} else if ( (*g)[prev].type == NULLEDGE ) {
endp = g->source(prev);
assert( (*g)[endp].type == ENDPOINT );
} else {
assert(0);
exit(-1);
}
return endp;
}
double _dot_product_threshold; ///< a dot-product threshold in [0,1] for filtering out edges between nearly parallel LineSite segments
};
} // end namespace
// end file
<commit_msg>Fix medial-axis filter discarding skeleton edges at very pointy polygon corners.<commit_after>/*
* Copyright 2012 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenVoronoi.
*
* OpenVoronoi 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.
*
* OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <iostream>
#include "graph.hpp"
#include "common/numeric.hpp"
#include "site.hpp"
#include "filter.hpp"
namespace ovd
{
/// \brief Filter for retaining the medial-axis of a voronoi diagram
///
/// (approximate) medial-axis Filter.
/// marks the valid-property true for edges belonging to the medial axis
/// and false for other edges.
struct medial_axis_filter : public Filter {
/// \param thr dot-product threshold used to decide whether the segments
/// that connect to a given Edge are nearly parallel
medial_axis_filter( double thr=0.8) : _dot_product_threshold(thr) { }
/// predicate that decides if an edge is to be included or not.
bool operator()(const HEEdge& e) const {
if ( (*g)[e].type == LINESITE || (*g)[e].type == NULLEDGE)
return true; // we keep linesites and nulledges
if ( (*g)[e].type == SEPARATOR)
return false; // separators are allways removed
if (both_endpoints_positive(e)) // these are interior edges which we keep.
return true;
// this leaves us with edges where one end connects to the polygon (dist==0)
// and the other end does not.
// figure out the angle between the adjacent line-segments and decide based on the angle.
if (segments_parallel(e))
return false;
return true; // otherwise we keep the edge
}
private:
/// return true if this is an internal edge, i.e. both endpoints have a nonzero clearance-disk radius
bool both_endpoints_positive(HEEdge e) const {
HEVertex src = g->source(e);
HEVertex trg = g->target(e);
return ((*g)[src].dist()>0) && ((*g)[trg].dist()>0);
}
/// return true if the segments that connect to the given Edge are nearly parallel
bool segments_parallel( HEEdge e ) const {
HEVertex endp1 = find_endpoint(e);
HEVertex endp2 = find_endpoint( (*g)[e].twin );
// find the segments
HEEdge e1 = find_segment(endp1);
HEEdge e2 = find_segment(endp2);
e2 = (*g)[e2].twin; // this makes the edges oriented in the same direction
double dotprod = edge_dotprod(e1,e2);
return dotprod >_dot_product_threshold;
}
/// \brief calculate the dot-product between unit vectors aligned along edges e1->e2
///
/// since e1 and e2 are both line-sites the direction is easy to find
/// FIXME: more code needed here for tangent calculation if we have arc-sites
double edge_dotprod(HEEdge e1, HEEdge e2) const {
HEVertex src1 = g->source(e1);
HEVertex trg1 = g->target(e1);
HEVertex src2 = g->source(e2);
HEVertex trg2 = g->target(e2);
Point sp1 = (*g)[src1].position;
Point tp1 = (*g)[trg1].position;
Point sp2 = (*g)[src2].position;
Point tp2 = (*g)[trg2].position;
Point dir1 = tp1-sp1;
Point dir2 = tp2-sp2;
dir1.normalize();
dir2.normalize();
return dir1.dot(dir2);
}
/// find the LineSite edge that connects to \a v
HEEdge find_segment(HEVertex v) const {
BOOST_FOREACH(HEEdge e, g->out_edges(v)) {
if ( (*g)[e].type == LINESITE )
return e;
}
assert(0);
exit(-1);
return HEEdge();
}
/// find an ::ENDPOINT vertex that connects to Edge e through a ::NULLEDGE at either the source or target of e.
HEVertex find_endpoint(HEEdge e) const {
HEEdge next = (*g)[e].next;
HEEdge prev = g->previous_edge(e);
HEVertex endp;
if ( (*g)[next].type == NULLEDGE ) {
endp = g->target(next);
assert( (*g)[endp].type == ENDPOINT );
} else if ( (*g)[prev].type == NULLEDGE ) {
endp = g->source(prev);
assert( (*g)[endp].type == ENDPOINT );
} else {
assert(0);
exit(-1);
}
return endp;
}
double _dot_product_threshold; ///< a dot-product threshold in [0,1] for filtering out edges between nearly parallel LineSite segments
};
} // end namespace
// end file
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2017 Axel Waggershauser
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/AbstractLJpegDecompressor.h"
#include "common/Common.h" // for uint32, make_unique, uchar8
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/ByteStream.h" // for ByteStream
#include <array> // for array
#include <memory> // for unique_ptr, allocator
#include <utility> // for move
#include <vector> // for vector
namespace rawspeed {
void AbstractLJpegDecompressor::decode() {
if (getNextMarker(false) != M_SOI)
ThrowRDE("Image did not start with SOI. Probably not an LJPEG");
struct FoundMarkers {
bool DHT = false;
bool SOF = false;
bool SOS = false;
} FoundMarkers;
JpegMarker m;
do {
m = getNextMarker(true);
switch (m) {
case M_DHT:
// there can be more than one DHT markers.
// FIXME: do we really want to reparse and use the last one?
parseDHT();
FoundMarkers.DHT = true;
break;
case M_SOF3:
if (FoundMarkers.SOF)
ThrowRDE("Found second SOF marker");
// SOF is not required to be after DHT
parseSOF(&frame);
FoundMarkers.SOF = true;
break;
case M_SOS:
if (FoundMarkers.SOS)
ThrowRDE("Found second SOS marker");
if (!FoundMarkers.DHT)
ThrowRDE("Did not find DHT marker before SOS.");
if (!FoundMarkers.SOF)
ThrowRDE("Did not find SOF marker before SOS.");
parseSOS();
FoundMarkers.SOS = true;
break;
case M_DQT:
ThrowRDE("Not a valid RAW file.");
default: // Just let it skip to next marker
break;
}
} while (m != M_EOI);
if (!FoundMarkers.SOS)
ThrowRDE("Did not find SOS marker.");
}
void AbstractLJpegDecompressor::parseSOF(SOFInfo* sof) {
uint32 headerLength = input.getU16();
sof->prec = input.getByte();
sof->h = input.getU16();
sof->w = input.getU16();
sof->cps = input.getByte();
if (sof->h == 0 || sof->w == 0)
ThrowRDE("Frame width or height set to zero");
if (sof->prec > 16)
ThrowRDE("More than 16 bits per channel is not supported.");
if (sof->cps > 4 || sof->cps < 1)
ThrowRDE("Only from 1 to 4 components are supported.");
if (headerLength != 8 + sof->cps*3)
ThrowRDE("Header size mismatch.");
for (uint32 i = 0; i < sof->cps; i++) {
sof->compInfo[i].componentId = input.getByte();
uint32 subs = input.getByte();
frame.compInfo[i].superV = subs & 0xf;
frame.compInfo[i].superH = subs >> 4;
uint32 Tq = input.getByte();
if (Tq != 0)
ThrowRDE("Quantized components not supported.");
}
sof->initialized = true;
mRaw->metadata.subsampling.x = sof->compInfo[0].superH;
mRaw->metadata.subsampling.y = sof->compInfo[0].superV;
}
void AbstractLJpegDecompressor::parseSOS() {
if (!frame.initialized)
ThrowRDE("Frame not yet initialized (SOF Marker not parsed)");
uint32 headerLength = input.getU16();
if (headerLength != 3 + frame.cps * 2 + 3)
ThrowRDE("Invalid SOS header length.");
uint32 soscps = input.getByte();
if (frame.cps != soscps)
ThrowRDE("Component number mismatch.");
for (uint32 i = 0; i < frame.cps; i++) {
uint32 cs = input.getByte();
uint32 td = input.getByte() >> 4;
if (td > 3 || !huff[td])
ThrowRDE("Invalid Huffman table selection.");
int ciIndex = -1;
for (uint32 j = 0; j < frame.cps; ++j) {
if (frame.compInfo[j].componentId == cs)
ciIndex = j;
}
if (ciIndex == -1)
ThrowRDE("Invalid Component Selector");
frame.compInfo[ciIndex].dcTblNo = td;
}
// Get predictor, see table H.1 from the JPEG spec
predictorMode = input.getByte();
// The spec says predictoreMode is in [0..7], but Hasselblad uses '8'.
if (predictorMode > 8)
ThrowRDE("Invalid predictor mode.");
input.skipBytes(1); // Se + Ah Not used in LJPEG
Pt = input.getByte() & 0xf; // Point Transform
decodeScan();
}
void AbstractLJpegDecompressor::parseDHT() {
uint32 headerLength = input.getU16() - 2; // Subtract myself
while (headerLength) {
uint32 b = input.getByte();
uint32 htClass = b >> 4;
if (htClass != 0)
ThrowRDE("Unsupported Table class.");
uint32 htIndex = b & 0xf;
if (htIndex >= huff.size())
ThrowRDE("Invalid huffman table destination id.");
if (huff[htIndex] != nullptr)
ThrowRDE("Duplicate table definition");
// copy 16 bytes from input stream to number of codes per length table
uint32 nCodes = ht_.setNCodesPerLength(input.getBuffer(16));
// spec says 16 different codes is max but Hasselblad violates that -> 17
if (nCodes > 17 || headerLength < 1 + 16 + nCodes)
ThrowRDE("Invalid DHT table.");
// copy nCodes bytes from input stream to code values table
ht_.setCodeValues(input.getBuffer(nCodes));
// see if we already have a HuffmanTable with the same codes
for (const auto& i : huffmanTableStore)
if (*i == ht_)
huff[htIndex] = i.get();
if (!huff[htIndex]) {
// setup new ht_ and put it into the store
auto dHT = std::make_unique<HuffmanTable>(ht_);
dHT->setup(fullDecodeHT, fixDng16Bug);
huff[htIndex] = dHT.get();
huffmanTableStore.emplace_back(std::move(dHT));
}
headerLength -= 1 + 16 + nCodes;
}
}
JpegMarker AbstractLJpegDecompressor::getNextMarker(bool allowskip) {
uchar8 c0;
uchar8 c1 = input.getByte();
do {
c0 = c1;
c1 = input.getByte();
} while (allowskip && !(c0 == 0xFF && c1 != 0 && c1 != 0xFF));
if (!(c0 == 0xFF && c1 != 0 && c1 != 0xFF))
ThrowRDE("(Noskip) Expected marker not found. Propably corrupt file.");
return static_cast<JpegMarker>(c1);
}
} // namespace rawspeed
<commit_msg>AbstractLJpegDecompressor::decode(): check that no DHT/SOF after SOS.<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2017 Axel Waggershauser
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/AbstractLJpegDecompressor.h"
#include "common/Common.h" // for uint32, make_unique, uchar8
#include "common/Point.h" // for iPoint2D
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/ByteStream.h" // for ByteStream
#include <array> // for array
#include <memory> // for unique_ptr, allocator
#include <utility> // for move
#include <vector> // for vector
namespace rawspeed {
void AbstractLJpegDecompressor::decode() {
if (getNextMarker(false) != M_SOI)
ThrowRDE("Image did not start with SOI. Probably not an LJPEG");
struct FoundMarkers {
bool DHT = false;
bool SOF = false;
bool SOS = false;
} FoundMarkers;
JpegMarker m;
do {
m = getNextMarker(true);
switch (m) {
case M_DHT:
if (FoundMarkers.SOS)
ThrowRDE("Found second DHT marker after SOS");
// there can be more than one DHT markers.
// FIXME: do we really want to reparse and use the last one?
parseDHT();
FoundMarkers.DHT = true;
break;
case M_SOF3:
if (FoundMarkers.SOS)
ThrowRDE("Found second SOF marker after SOS");
if (FoundMarkers.SOF)
ThrowRDE("Found second SOF marker");
// SOF is not required to be after DHT
parseSOF(&frame);
FoundMarkers.SOF = true;
break;
case M_SOS:
if (FoundMarkers.SOS)
ThrowRDE("Found second SOS marker");
if (!FoundMarkers.DHT)
ThrowRDE("Did not find DHT marker before SOS.");
if (!FoundMarkers.SOF)
ThrowRDE("Did not find SOF marker before SOS.");
parseSOS();
FoundMarkers.SOS = true;
break;
case M_DQT:
ThrowRDE("Not a valid RAW file.");
default: // Just let it skip to next marker
break;
}
} while (m != M_EOI);
if (!FoundMarkers.SOS)
ThrowRDE("Did not find SOS marker.");
}
void AbstractLJpegDecompressor::parseSOF(SOFInfo* sof) {
uint32 headerLength = input.getU16();
sof->prec = input.getByte();
sof->h = input.getU16();
sof->w = input.getU16();
sof->cps = input.getByte();
if (sof->h == 0 || sof->w == 0)
ThrowRDE("Frame width or height set to zero");
if (sof->prec > 16)
ThrowRDE("More than 16 bits per channel is not supported.");
if (sof->cps > 4 || sof->cps < 1)
ThrowRDE("Only from 1 to 4 components are supported.");
if (headerLength != 8 + sof->cps*3)
ThrowRDE("Header size mismatch.");
for (uint32 i = 0; i < sof->cps; i++) {
sof->compInfo[i].componentId = input.getByte();
uint32 subs = input.getByte();
frame.compInfo[i].superV = subs & 0xf;
frame.compInfo[i].superH = subs >> 4;
uint32 Tq = input.getByte();
if (Tq != 0)
ThrowRDE("Quantized components not supported.");
}
sof->initialized = true;
mRaw->metadata.subsampling.x = sof->compInfo[0].superH;
mRaw->metadata.subsampling.y = sof->compInfo[0].superV;
}
void AbstractLJpegDecompressor::parseSOS() {
if (!frame.initialized)
ThrowRDE("Frame not yet initialized (SOF Marker not parsed)");
uint32 headerLength = input.getU16();
if (headerLength != 3 + frame.cps * 2 + 3)
ThrowRDE("Invalid SOS header length.");
uint32 soscps = input.getByte();
if (frame.cps != soscps)
ThrowRDE("Component number mismatch.");
for (uint32 i = 0; i < frame.cps; i++) {
uint32 cs = input.getByte();
uint32 td = input.getByte() >> 4;
if (td > 3 || !huff[td])
ThrowRDE("Invalid Huffman table selection.");
int ciIndex = -1;
for (uint32 j = 0; j < frame.cps; ++j) {
if (frame.compInfo[j].componentId == cs)
ciIndex = j;
}
if (ciIndex == -1)
ThrowRDE("Invalid Component Selector");
frame.compInfo[ciIndex].dcTblNo = td;
}
// Get predictor, see table H.1 from the JPEG spec
predictorMode = input.getByte();
// The spec says predictoreMode is in [0..7], but Hasselblad uses '8'.
if (predictorMode > 8)
ThrowRDE("Invalid predictor mode.");
input.skipBytes(1); // Se + Ah Not used in LJPEG
Pt = input.getByte() & 0xf; // Point Transform
decodeScan();
}
void AbstractLJpegDecompressor::parseDHT() {
uint32 headerLength = input.getU16() - 2; // Subtract myself
while (headerLength) {
uint32 b = input.getByte();
uint32 htClass = b >> 4;
if (htClass != 0)
ThrowRDE("Unsupported Table class.");
uint32 htIndex = b & 0xf;
if (htIndex >= huff.size())
ThrowRDE("Invalid huffman table destination id.");
if (huff[htIndex] != nullptr)
ThrowRDE("Duplicate table definition");
// copy 16 bytes from input stream to number of codes per length table
uint32 nCodes = ht_.setNCodesPerLength(input.getBuffer(16));
// spec says 16 different codes is max but Hasselblad violates that -> 17
if (nCodes > 17 || headerLength < 1 + 16 + nCodes)
ThrowRDE("Invalid DHT table.");
// copy nCodes bytes from input stream to code values table
ht_.setCodeValues(input.getBuffer(nCodes));
// see if we already have a HuffmanTable with the same codes
for (const auto& i : huffmanTableStore)
if (*i == ht_)
huff[htIndex] = i.get();
if (!huff[htIndex]) {
// setup new ht_ and put it into the store
auto dHT = std::make_unique<HuffmanTable>(ht_);
dHT->setup(fullDecodeHT, fixDng16Bug);
huff[htIndex] = dHT.get();
huffmanTableStore.emplace_back(std::move(dHT));
}
headerLength -= 1 + 16 + nCodes;
}
}
JpegMarker AbstractLJpegDecompressor::getNextMarker(bool allowskip) {
uchar8 c0;
uchar8 c1 = input.getByte();
do {
c0 = c1;
c1 = input.getByte();
} while (allowskip && !(c0 == 0xFF && c1 != 0 && c1 != 0xFF));
if (!(c0 == 0xFF && c1 != 0 && c1 != 0xFF))
ThrowRDE("(Noskip) Expected marker not found. Propably corrupt file.");
return static_cast<JpegMarker>(c1);
}
} // namespace rawspeed
<|endoftext|> |
<commit_before><commit_msg>Coverity: Allocate |cache| after we have a logic path where we can return and leak.<commit_after><|endoftext|> |
<commit_before>#pragma once
#ifndef VARIANT_HPP
# define VARIANT_HPP
#include <exception>
#include <array>
#include <utility>
#include <type_traits>
#include <typeinfo>
namespace detail
{
template <typename A, typename ...B>
struct max_align
{
static constexpr auto const align =
(alignof(A) > max_align<B...>::align)
? alignof(A)
: max_align<B...>::align;
};
template <typename A, typename B>
struct max_align<A, B>
{
static constexpr auto const align =
(alignof(A) > alignof(B)) ? alignof(A) : alignof(B);
};
template <typename A>
struct max_align<A>
{
static constexpr auto const align = alignof(A);
};
template <typename A, typename ...B>
struct max_type
{
typedef typename std::conditional<
(sizeof(A) > sizeof(typename max_type<B...>::type)),
A,
typename max_type<B...>::type
>::type type;
};
template <typename A, typename B>
struct max_type<A, B>
{
typedef typename std::conditional<(sizeof(A) > sizeof(B)), A, B>::type type;
};
template <typename A>
struct max_type<A>
{
typedef A type;
};
template <int I, typename A, typename B, typename ...C>
struct index_of
{
static constexpr int const value =
std::is_same<A, B>::value ? I : index_of<I + 1, A, C...>::value;
};
template <int I, typename A, typename B>
struct index_of<I, A, B>
{
static constexpr int const value =
std::is_same<A, B>::value ? I : -1;
};
template <bool B>
using bool_ = std::integral_constant<bool, B>;
template <class A, class ...B>
struct one_of : bool_<A::value || one_of<B...>::value> { };
template <class A>
struct one_of<A> : bool_<A::value> { };
}
template <typename ...T>
struct variant
{
static constexpr auto const max_align = detail::max_align<T...>::align;
typedef typename detail::max_type<T...>::type max_type;
variant() = default;
~variant()
{
if (store_type_)
{
deleter_(store_);
}
// else do nothing
}
variant(variant const&) = delete;
variant(variant&& other)
{
*this = std::move(other);
}
variant& operator=(variant const&) = delete;
variant& operator=(variant&& rhs)
{
if (rhs.store_type_)
{
rhs.mover_(rhs, *this);
deleter_ = rhs.deleter_;
mover_ = rhs.mover_;
store_type_ = rhs.store_type_;
rhs.store_type_ = nullptr;
}
// else do nothing
return *this;
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<T,
typename std::remove_const<U>::type>...
>::value
>::type
>
variant(U&& f)
{
*this = std::forward<U>(f);
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<T,
typename std::remove_const<U>::type>...
>::value
>::type
>
variant& operator=(U&& f)
{
if (store_type_)
{
deleter_(store_);
}
// else do nothing
new (store_) U(std::forward<U>(f));
deleter_ = destructor_stub<U>;
mover_ = mover_stub<U>;
store_type_ = &typeid(U);
return *this;
}
template <typename U>
bool contains() const
{
return store_type_ && (typeid(U) == *store_type_);
}
template <typename U>
U const& get() const
{
if (contains<U>())
{
return *(static_cast<U const*>(static_cast<void const*>(store_)));
}
else
{
throw std::bad_typeid();
}
}
template <typename U>
U& get()
{
if (contains<U>())
{
return *(static_cast<U*>(static_cast<void*>(store_)));
}
else
{
throw std::bad_typeid();
}
}
private:
template <typename U>
static void destructor_stub(void* const p)
{
static_cast<U*>(p)->~U();
}
template <typename U>
static void mover_stub(variant& src, variant& dst)
{
new (dst.store_) U(std::move(*static_cast<U*>(
static_cast<void*>(src.store_))));
src.deleter_(src.store_);
}
alignas(max_align) char store_[sizeof(max_type)];
std::type_info const* store_type_{ };
typedef void (*deleter_type)(void*);
deleter_type deleter_;
typedef void (*mover_type)(variant&, variant&);
mover_type mover_;
};
#endif // VARIANT_HPP
<commit_msg>strips<commit_after>#pragma once
#ifndef VARIANT_HPP
# define VARIANT_HPP
#include <exception>
#include <array>
#include <utility>
#include <type_traits>
#include <typeinfo>
namespace detail
{
template <typename A, typename ...B>
struct max_align
{
static constexpr auto const align =
(alignof(A) > max_align<B...>::align)
? alignof(A)
: max_align<B...>::align;
};
template <typename A, typename B>
struct max_align<A, B>
{
static constexpr auto const align =
(alignof(A) > alignof(B)) ? alignof(A) : alignof(B);
};
template <typename A>
struct max_align<A>
{
static constexpr auto const align = alignof(A);
};
template <typename A, typename ...B>
struct max_type
{
typedef typename std::conditional<
(sizeof(A) > sizeof(typename max_type<B...>::type)),
A,
typename max_type<B...>::type
>::type type;
};
template <typename A, typename B>
struct max_type<A, B>
{
typedef typename std::conditional<(sizeof(A) > sizeof(B)), A, B>::type type;
};
template <typename A>
struct max_type<A>
{
typedef A type;
};
template <std::size_t I, typename A, typename B...>
struct at
{
typedef std::conditional<I, typename at<I - 1, B...>::type, A> type;
};
template <std::size_t I, typename A>
struct at<0, A>
{
typedef A type;
};
template <int I, typename A, typename B, typename ...C>
struct index_of
{
static constexpr int const value =
std::is_same<A, B>::value ? I : index_of<I + 1, A, C...>::value;
};
template <int I, typename A, typename B>
struct index_of<I, A, B>
{
static constexpr int const value =
std::is_same<A, B>::value ? I : -1;
};
template <bool B>
using bool_ = std::integral_constant<bool, B>;
template <class A, class ...B>
struct one_of : bool_<A::value || one_of<B...>::value> { };
template <class A>
struct one_of<A> : bool_<A::value> { };
}
template <typename ...T>
struct variant
{
static constexpr auto const max_align = detail::max_align<T...>::align;
typedef typename detail::max_type<T...>::type max_type;
variant() = default;
~variant()
{
if (store_type_)
{
deleter_(store_);
}
// else do nothing
}
variant(variant const&) = delete;
variant(variant&& other)
{
*this = std::move(other);
}
variant& operator=(variant const&) = delete;
variant& operator=(variant&& rhs)
{
if (rhs.store_type_)
{
rhs.mover_(rhs, *this);
deleter_ = rhs.deleter_;
mover_ = rhs.mover_;
store_type_ = rhs.store_type_;
rhs.store_type_ = nullptr;
}
// else do nothing
return *this;
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<T,
typename std::remove_const<U>::type>...
>::value
>::type
>
variant(U&& f)
{
*this = std::forward<U>(f);
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<T,
typename std::remove_const<U>::type>...
>::value
>::type
>
variant& operator=(U&& f)
{
if (store_type_)
{
deleter_(store_);
}
// else do nothing
new (store_) U(std::forward<U>(f));
deleter_ = destructor_stub<U>;
mover_ = mover_stub<U>;
store_type_ = &typeid(U);
return *this;
}
template <typename U>
bool contains() const
{
return store_type_ && (typeid(U) == *store_type_);
}
template <typename U>
U const& get() const
{
if (contains<U>())
{
return *(static_cast<U const*>(static_cast<void const*>(store_)));
}
else
{
throw std::bad_typeid();
}
}
template <typename U>
U& get()
{
if (contains<U>())
{
return *(static_cast<U*>(static_cast<void*>(store_)));
}
else
{
throw std::bad_typeid();
}
}
private:
template <typename U>
static void destructor_stub(void* const p)
{
static_cast<U*>(p)->~U();
}
template <typename U>
static void mover_stub(variant& src, variant& dst)
{
new (dst.store_) U(std::move(*static_cast<U*>(
static_cast<void*>(src.store_))));
src.deleter_(src.store_);
}
alignas(max_align) char store_[sizeof(max_type)];
std::type_info const* store_type_{ };
typedef void (*deleter_type)(void*);
deleter_type deleter_;
typedef void (*mover_type)(variant&, variant&);
mover_type mover_;
};
#endif // VARIANT_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/gpu/gpu_video_layer_glx.h"
#include <GL/glew.h>
#include "chrome/common/gpu_messages.h"
#include "chrome/gpu/gpu_thread.h"
#include "chrome/gpu/gpu_view_x.h"
// Handy constants for addressing YV12 data.
static const int kYUVPlanes = 3;
static const int kYPlane = 0;
static const int kUPlane = 1;
static const int kVPlane = 2;
// Buffer size for shader compile errors.
static const unsigned int kErrorSize = 4096;
// Matrix used for the YUV to RGB conversion.
static const float kYUV2RGB[9] = {
1.f, 0.f, 1.403f,
1.f, -.344f, -.714f,
1.f, 1.772f, 0.f,
};
// Texture coordinates mapping the entire texture.
static const float kTextureCoords[8] = {
0, 0,
0, 1,
1, 0,
1, 1,
};
#define I915_WORKAROUND
// Pass-through vertex shader.
static const char kVertexShader[] =
"varying vec2 interp_tc;\n"
"\n"
"attribute vec4 in_pos;\n"
"attribute vec2 in_tc;\n"
"\n"
"void main() {\n"
#if defined(I915_WORKAROUND)
" gl_TexCoord[0].st = in_tc;\n"
#else
" interp_tc = in_tc;\n"
#endif
" gl_Position = in_pos;\n"
"}\n";
// YUV to RGB pixel shader. Loads a pixel from each plane and pass through the
// matrix.
static const char kFragmentShader[] =
"varying vec2 interp_tc;\n"
"\n"
"uniform sampler2D y_tex;\n"
"uniform sampler2D u_tex;\n"
"uniform sampler2D v_tex;\n"
"uniform mat3 yuv2rgb;\n"
"\n"
"void main() {\n"
#if defined(I915_WORKAROUND)
" float y = texture2D(y_tex, gl_TexCoord[0].st).x;\n"
" float u = texture2D(u_tex, gl_TexCoord[0].st).r - .5;\n"
" float v = texture2D(v_tex, gl_TexCoord[0].st).r - .5;\n"
" float r = y + v * 1.403;\n"
" float g = y - u * 0.344 - v * 0.714;\n"
" float b = y + u * 1.772;\n"
" gl_FragColor = vec4(r, g, b, 1);\n"
#else
" float y = texture2D(y_tex, interp_tc).x;\n"
" float u = texture2D(u_tex, interp_tc).r - .5;\n"
" float v = texture2D(v_tex, interp_tc).r - .5;\n"
" vec3 rgb = yuv2rgb * vec3(y, u, v);\n"
" gl_FragColor = vec4(rgb, 1);\n"
#endif
"}\n";
GpuVideoLayerGLX::GpuVideoLayerGLX(GpuViewX* view,
GpuThread* gpu_thread,
int32 routing_id,
const gfx::Size& size)
: view_(view),
gpu_thread_(gpu_thread),
routing_id_(routing_id),
native_size_(size),
program_(0) {
memset(textures_, 0, sizeof(textures_));
// Load identity vertices.
gfx::Rect identity(0, 0, 1, 1);
CalculateVertices(identity.size(), identity, target_vertices_);
gpu_thread_->AddRoute(routing_id_, this);
view_->BindContext(); // Must do this before issuing OpenGl.
glMatrixMode(GL_MODELVIEW);
// Create 3 textures, one for each plane, and bind them to different
// texture units.
glGenTextures(kYUVPlanes, textures_);
glBindTexture(GL_TEXTURE_2D, textures_[kYPlane]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, textures_[kUPlane]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, textures_[kVPlane]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Create our YUV->RGB shader.
program_ = glCreateProgram();
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
const char* vs_source = kVertexShader;
int vs_size = sizeof(kVertexShader);
glShaderSource(vertex_shader, 1, &vs_source, &vs_size);
glCompileShader(vertex_shader);
int result = GL_FALSE;
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &result);
if (!result) {
char log[kErrorSize];
int len;
glGetShaderInfoLog(vertex_shader, kErrorSize - 1, &len, log);
log[kErrorSize - 1] = 0;
LOG(FATAL) << log;
}
glAttachShader(program_, vertex_shader);
glDeleteShader(vertex_shader);
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
const char* ps_source = kFragmentShader;
int ps_size = sizeof(kFragmentShader);
glShaderSource(fragment_shader, 1, &ps_source, &ps_size);
glCompileShader(fragment_shader);
result = GL_FALSE;
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &result);
if (!result) {
char log[kErrorSize];
int len;
glGetShaderInfoLog(fragment_shader, kErrorSize - 1, &len, log);
log[kErrorSize - 1] = 0;
LOG(FATAL) << log;
}
glAttachShader(program_, fragment_shader);
glDeleteShader(fragment_shader);
glLinkProgram(program_);
result = GL_FALSE;
glGetProgramiv(program_, GL_LINK_STATUS, &result);
if (!result) {
char log[kErrorSize];
int len;
glGetProgramInfoLog(program_, kErrorSize - 1, &len, log);
log[kErrorSize - 1] = 0;
LOG(FATAL) << log;
}
}
GpuVideoLayerGLX::~GpuVideoLayerGLX() {
// TODO(scherkus): this seems like a bad idea.. we might be better off with
// separate Initialize()/Teardown() calls instead.
view_->BindContext();
if (program_) {
glDeleteProgram(program_);
}
gpu_thread_->RemoveRoute(routing_id_);
}
void GpuVideoLayerGLX::Render(const gfx::Size& viewport_size) {
// Nothing to do if we're not visible or have no YUV data.
if (target_rect_.IsEmpty()) {
return;
}
// Calculate the position of our quad.
CalculateVertices(viewport_size, target_rect_, target_vertices_);
// Bind Y, U and V textures to texture units.
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures_[kYPlane]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures_[kUPlane]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, textures_[kVPlane]);
// Bind vertex/fragment shader program.
glUseProgram(program_);
// Bind parameters.
glUniform1i(glGetUniformLocation(program_, "y_tex"), 0);
glUniform1i(glGetUniformLocation(program_, "u_tex"), 1);
glUniform1i(glGetUniformLocation(program_, "v_tex"), 2);
#if !defined(I915_WORKAROUND)
int yuv2rgb_location = glGetUniformLocation(program_, "yuv2rgb");
glUniformMatrix3fv(yuv2rgb_location, 1, GL_TRUE, kYUV2RGB);
#endif
// TODO(scherkus): instead of calculating and loading a geometry each time,
// we should store a constant geometry in a VBO and use a vertex shader.
int pos_location = glGetAttribLocation(program_, "in_pos");
glEnableVertexAttribArray(pos_location);
glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, 0,
target_vertices_);
int tc_location = glGetAttribLocation(program_, "in_tc");
glEnableVertexAttribArray(tc_location);
glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, 0,
kTextureCoords);
// Render!
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Reset back to original state.
glDisableVertexAttribArray(pos_location);
glDisableVertexAttribArray(tc_location);
glActiveTexture(GL_TEXTURE0);
glUseProgram(0);
}
void GpuVideoLayerGLX::OnMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(GpuVideoLayerGLX, msg)
IPC_MESSAGE_HANDLER(GpuMsg_PaintToVideoLayer, OnPaintToVideoLayer)
IPC_END_MESSAGE_MAP_EX()
}
void GpuVideoLayerGLX::OnChannelConnected(int32 peer_pid) {
}
void GpuVideoLayerGLX::OnChannelError() {
// FIXME(brettw) does this mean we aren't getting any more messages and we
// should delete outselves?
NOTIMPLEMENTED();
}
void GpuVideoLayerGLX::OnPaintToVideoLayer(base::ProcessId source_process_id,
TransportDIB::Id id,
const gfx::Rect& bitmap_rect) {
// Assume that somewhere along the line, someone will do width * height * 4
// with signed numbers. If the maximum value is 2**31, then 2**31 / 4 =
// 2**29 and floor(sqrt(2**29)) = 23170.
//
// TODO(scherkus): |native_size_| is set in constructor, so perhaps this check
// should be a DCHECK().
const int width = native_size_.width();
const int height = native_size_.height();
const int stride = width;
if (width > 23170 || height > 23170)
return;
TransportDIB* dib = TransportDIB::Map(id);
if (!dib)
return;
// Everything looks good, update our target position and size.
target_rect_ = bitmap_rect;
// Perform colour space conversion.
uint8* planes[kYUVPlanes];
planes[kYPlane] = reinterpret_cast<uint8*>(dib->memory());
planes[kUPlane] = planes[kYPlane] + width * height;
planes[kVPlane] = planes[kUPlane] + ((width * height) >> 2);
view_->BindContext(); // Must do this before issuing OpenGl.
// Assume YV12 format.
for (int i = 0; i < kYUVPlanes; ++i) {
int plane_width = (i == kYPlane ? width : width / 2);
int plane_height = (i == kYPlane ? height : height / 2);
int plane_stride = (i == kYPlane ? stride : stride / 2);
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, textures_[i]);
glPixelStorei(GL_UNPACK_ROW_LENGTH, plane_stride);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, plane_width, plane_height, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, planes[i]);
}
// Reset back to original state.
glActiveTexture(GL_TEXTURE0);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glFlush();
// TODO(scherkus): we may not need to ACK video layer updates at all.
gpu_thread_->Send(new GpuHostMsg_PaintToVideoLayer_ACK(routing_id_));
}
// static
void GpuVideoLayerGLX::CalculateVertices(const gfx::Size& world,
const gfx::Rect& object,
float* vertices) {
// Don't forget GL has a flipped Y-axis!
float width = world.width();
float height = world.height();
// Top left.
vertices[0] = 2.0f * (object.x() / width) - 1.0f;
vertices[1] = -2.0f * (object.y() / height) + 1.0f;
// Bottom left.
vertices[2] = 2.0f * (object.x() / width) - 1.0f;
vertices[3] = -2.0f * (object.bottom() / height) + 1.0f;
// Top right.
vertices[4] = 2.0f * (object.right() / width) - 1.0f;
vertices[5] = -2.0f * (object.y() / height) + 1.0f;
// Bottom right.
vertices[6] = 2.0f * (object.right() / width) - 1.0f;
vertices[7] = -2.0f * (object.bottom() / height) + 1.0f;
}
<commit_msg>Added check for negative height/width and ensure that buffer size has not changed before reading buffers.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/gpu/gpu_video_layer_glx.h"
#include <GL/glew.h>
#include "chrome/common/gpu_messages.h"
#include "chrome/gpu/gpu_thread.h"
#include "chrome/gpu/gpu_view_x.h"
// Handy constants for addressing YV12 data.
static const int kYUVPlanes = 3;
static const int kYPlane = 0;
static const int kUPlane = 1;
static const int kVPlane = 2;
// Buffer size for shader compile errors.
static const unsigned int kErrorSize = 4096;
// Matrix used for the YUV to RGB conversion.
static const float kYUV2RGB[9] = {
1.f, 0.f, 1.403f,
1.f, -.344f, -.714f,
1.f, 1.772f, 0.f,
};
// Texture coordinates mapping the entire texture.
static const float kTextureCoords[8] = {
0, 0,
0, 1,
1, 0,
1, 1,
};
#define I915_WORKAROUND
// Pass-through vertex shader.
static const char kVertexShader[] =
"varying vec2 interp_tc;\n"
"\n"
"attribute vec4 in_pos;\n"
"attribute vec2 in_tc;\n"
"\n"
"void main() {\n"
#if defined(I915_WORKAROUND)
" gl_TexCoord[0].st = in_tc;\n"
#else
" interp_tc = in_tc;\n"
#endif
" gl_Position = in_pos;\n"
"}\n";
// YUV to RGB pixel shader. Loads a pixel from each plane and pass through the
// matrix.
static const char kFragmentShader[] =
"varying vec2 interp_tc;\n"
"\n"
"uniform sampler2D y_tex;\n"
"uniform sampler2D u_tex;\n"
"uniform sampler2D v_tex;\n"
"uniform mat3 yuv2rgb;\n"
"\n"
"void main() {\n"
#if defined(I915_WORKAROUND)
" float y = texture2D(y_tex, gl_TexCoord[0].st).x;\n"
" float u = texture2D(u_tex, gl_TexCoord[0].st).r - .5;\n"
" float v = texture2D(v_tex, gl_TexCoord[0].st).r - .5;\n"
" float r = y + v * 1.403;\n"
" float g = y - u * 0.344 - v * 0.714;\n"
" float b = y + u * 1.772;\n"
" gl_FragColor = vec4(r, g, b, 1);\n"
#else
" float y = texture2D(y_tex, interp_tc).x;\n"
" float u = texture2D(u_tex, interp_tc).r - .5;\n"
" float v = texture2D(v_tex, interp_tc).r - .5;\n"
" vec3 rgb = yuv2rgb * vec3(y, u, v);\n"
" gl_FragColor = vec4(rgb, 1);\n"
#endif
"}\n";
// Assume that somewhere along the line, someone will do width * height * 4
// with signed numbers. If the maximum value is 2**31, then 2**31 / 4 =
// 2**29 and floor(sqrt(2**29)) = 23170.
// Max height and width for layers
static const int kMaxVideoLayerSize = 23170;
GpuVideoLayerGLX::GpuVideoLayerGLX(GpuViewX* view,
GpuThread* gpu_thread,
int32 routing_id,
const gfx::Size& size)
: view_(view),
gpu_thread_(gpu_thread),
routing_id_(routing_id),
native_size_(size),
program_(0) {
memset(textures_, 0, sizeof(textures_));
// Load identity vertices.
gfx::Rect identity(0, 0, 1, 1);
CalculateVertices(identity.size(), identity, target_vertices_);
gpu_thread_->AddRoute(routing_id_, this);
view_->BindContext(); // Must do this before issuing OpenGl.
glMatrixMode(GL_MODELVIEW);
// Create 3 textures, one for each plane, and bind them to different
// texture units.
glGenTextures(kYUVPlanes, textures_);
glBindTexture(GL_TEXTURE_2D, textures_[kYPlane]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, textures_[kUPlane]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, textures_[kVPlane]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// Create our YUV->RGB shader.
program_ = glCreateProgram();
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
const char* vs_source = kVertexShader;
int vs_size = sizeof(kVertexShader);
glShaderSource(vertex_shader, 1, &vs_source, &vs_size);
glCompileShader(vertex_shader);
int result = GL_FALSE;
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &result);
if (!result) {
char log[kErrorSize];
int len;
glGetShaderInfoLog(vertex_shader, kErrorSize - 1, &len, log);
log[kErrorSize - 1] = 0;
LOG(FATAL) << log;
}
glAttachShader(program_, vertex_shader);
glDeleteShader(vertex_shader);
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
const char* ps_source = kFragmentShader;
int ps_size = sizeof(kFragmentShader);
glShaderSource(fragment_shader, 1, &ps_source, &ps_size);
glCompileShader(fragment_shader);
result = GL_FALSE;
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &result);
if (!result) {
char log[kErrorSize];
int len;
glGetShaderInfoLog(fragment_shader, kErrorSize - 1, &len, log);
log[kErrorSize - 1] = 0;
LOG(FATAL) << log;
}
glAttachShader(program_, fragment_shader);
glDeleteShader(fragment_shader);
glLinkProgram(program_);
result = GL_FALSE;
glGetProgramiv(program_, GL_LINK_STATUS, &result);
if (!result) {
char log[kErrorSize];
int len;
glGetProgramInfoLog(program_, kErrorSize - 1, &len, log);
log[kErrorSize - 1] = 0;
LOG(FATAL) << log;
}
}
GpuVideoLayerGLX::~GpuVideoLayerGLX() {
// TODO(scherkus): this seems like a bad idea.. we might be better off with
// separate Initialize()/Teardown() calls instead.
view_->BindContext();
if (program_) {
glDeleteProgram(program_);
}
gpu_thread_->RemoveRoute(routing_id_);
}
void GpuVideoLayerGLX::Render(const gfx::Size& viewport_size) {
// Nothing to do if we're not visible or have no YUV data.
if (target_rect_.IsEmpty()) {
return;
}
// Calculate the position of our quad.
CalculateVertices(viewport_size, target_rect_, target_vertices_);
// Bind Y, U and V textures to texture units.
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures_[kYPlane]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures_[kUPlane]);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, textures_[kVPlane]);
// Bind vertex/fragment shader program.
glUseProgram(program_);
// Bind parameters.
glUniform1i(glGetUniformLocation(program_, "y_tex"), 0);
glUniform1i(glGetUniformLocation(program_, "u_tex"), 1);
glUniform1i(glGetUniformLocation(program_, "v_tex"), 2);
#if !defined(I915_WORKAROUND)
int yuv2rgb_location = glGetUniformLocation(program_, "yuv2rgb");
glUniformMatrix3fv(yuv2rgb_location, 1, GL_TRUE, kYUV2RGB);
#endif
// TODO(scherkus): instead of calculating and loading a geometry each time,
// we should store a constant geometry in a VBO and use a vertex shader.
int pos_location = glGetAttribLocation(program_, "in_pos");
glEnableVertexAttribArray(pos_location);
glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, 0,
target_vertices_);
int tc_location = glGetAttribLocation(program_, "in_tc");
glEnableVertexAttribArray(tc_location);
glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, 0,
kTextureCoords);
// Render!
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Reset back to original state.
glDisableVertexAttribArray(pos_location);
glDisableVertexAttribArray(tc_location);
glActiveTexture(GL_TEXTURE0);
glUseProgram(0);
}
void GpuVideoLayerGLX::OnMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(GpuVideoLayerGLX, msg)
IPC_MESSAGE_HANDLER(GpuMsg_PaintToVideoLayer, OnPaintToVideoLayer)
IPC_END_MESSAGE_MAP_EX()
}
void GpuVideoLayerGLX::OnChannelConnected(int32 peer_pid) {
}
void GpuVideoLayerGLX::OnChannelError() {
// FIXME(brettw) does this mean we aren't getting any more messages and we
// should delete outselves?
NOTIMPLEMENTED();
}
void GpuVideoLayerGLX::OnPaintToVideoLayer(base::ProcessId source_process_id,
TransportDIB::Id id,
const gfx::Rect& bitmap_rect) {
// TODO(scherkus): |native_size_| is set in constructor, so perhaps this check
// should be a DCHECK().
const int width = native_size_.width();
const int height = native_size_.height();
const int stride = width;
if (width <= 0 || width > kMaxVideoLayerSize ||
height <= 0 || height > kMaxVideoLayerSize)
return;
TransportDIB* dib = TransportDIB::Map(id);
if (!dib)
return;
// Everything looks good, update our target position and size.
target_rect_ = bitmap_rect;
// Perform colour space conversion.
uint8* planes[kYUVPlanes];
planes[kYPlane] = reinterpret_cast<uint8*>(dib->memory());
planes[kUPlane] = planes[kYPlane] + width * height;
planes[kVPlane] = planes[kUPlane] + ((width * height) >> 2);
view_->BindContext(); // Must do this before issuing OpenGl.
// Assume YV12 format.
for (int i = 0; i < kYUVPlanes; ++i) {
int plane_width = (i == kYPlane ? width : width / 2);
int plane_height = (i == kYPlane ? height : height / 2);
int plane_stride = (i == kYPlane ? stride : stride / 2);
// Ensure that we will not read outside the shared mem region.
if (planes[i] >= planes[kYPlane] &&
(dib->size() - (planes[kYPlane] - planes[i])) >=
static_cast<unsigned int>(plane_width * plane_height)) {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, textures_[i]);
glPixelStorei(GL_UNPACK_ROW_LENGTH, plane_stride);
glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, plane_width, plane_height, 0,
GL_LUMINANCE, GL_UNSIGNED_BYTE, planes[i]);
}
}
// Reset back to original state.
glActiveTexture(GL_TEXTURE0);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glFlush();
// TODO(scherkus): we may not need to ACK video layer updates at all.
gpu_thread_->Send(new GpuHostMsg_PaintToVideoLayer_ACK(routing_id_));
}
// static
void GpuVideoLayerGLX::CalculateVertices(const gfx::Size& world,
const gfx::Rect& object,
float* vertices) {
// Don't forget GL has a flipped Y-axis!
float width = world.width();
float height = world.height();
// Top left.
vertices[0] = 2.0f * (object.x() / width) - 1.0f;
vertices[1] = -2.0f * (object.y() / height) + 1.0f;
// Bottom left.
vertices[2] = 2.0f * (object.x() / width) - 1.0f;
vertices[3] = -2.0f * (object.bottom() / height) + 1.0f;
// Top right.
vertices[4] = 2.0f * (object.right() / width) - 1.0f;
vertices[5] = -2.0f * (object.y() / height) + 1.0f;
// Bottom right.
vertices[6] = 2.0f * (object.right() / width) - 1.0f;
vertices[7] = -2.0f * (object.bottom() / height) + 1.0f;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/android/media_player_bridge.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/message_loop/message_loop_proxy.h"
#include "jni/MediaPlayerBridge_jni.h"
#include "media/base/android/media_player_manager.h"
#include "media/base/android/media_resource_getter.h"
#include "media/base/android/media_source_player.h"
using base::android::ConvertUTF8ToJavaString;
using base::android::ScopedJavaLocalRef;
// Time update happens every 250ms.
static const int kTimeUpdateInterval = 250;
// Android MediaMetadataRetriever may fail to extract the metadata from the
// media under some circumstances. This makes the user unable to perform
// seek. To solve this problem, we use a temporary duration of 100 seconds when
// the duration is unknown. And we scale the seek position later when duration
// is available.
static const int kTemporaryDuration = 100;
namespace media {
#if !defined(GOOGLE_TV)
// static
MediaPlayerAndroid* MediaPlayerAndroid::Create(
int player_id,
const GURL& url,
SourceType source_type,
const GURL& first_party_for_cookies,
bool hide_url_log,
MediaPlayerManager* manager) {
if (source_type == SOURCE_TYPE_URL) {
MediaPlayerBridge* media_player_bridge = new MediaPlayerBridge(
player_id,
url,
first_party_for_cookies,
hide_url_log,
manager);
media_player_bridge->Initialize();
return media_player_bridge;
} else {
return new MediaSourcePlayer(
player_id,
manager);
}
}
#endif
MediaPlayerBridge::MediaPlayerBridge(
int player_id,
const GURL& url,
const GURL& first_party_for_cookies,
bool hide_url_log,
MediaPlayerManager* manager)
: MediaPlayerAndroid(player_id,
manager),
prepared_(false),
pending_play_(false),
url_(url),
first_party_for_cookies_(first_party_for_cookies),
hide_url_log_(hide_url_log),
duration_(base::TimeDelta::FromSeconds(kTemporaryDuration)),
width_(0),
height_(0),
can_pause_(true),
can_seek_forward_(true),
can_seek_backward_(true),
weak_this_(this),
listener_(base::MessageLoopProxy::current(),
weak_this_.GetWeakPtr()) {
}
MediaPlayerBridge::~MediaPlayerBridge() {
Release();
}
void MediaPlayerBridge::Initialize() {
if (url_.SchemeIsFile()) {
cookies_.clear();
ExtractMediaMetadata(url_.spec());
return;
}
media::MediaResourceGetter* resource_getter =
manager()->GetMediaResourceGetter();
if (url_.SchemeIsFileSystem()) {
cookies_.clear();
resource_getter->GetPlatformPathFromFileSystemURL(url_, base::Bind(
&MediaPlayerBridge::ExtractMediaMetadata, weak_this_.GetWeakPtr()));
return;
}
resource_getter->GetCookies(url_, first_party_for_cookies_, base::Bind(
&MediaPlayerBridge::OnCookiesRetrieved, weak_this_.GetWeakPtr()));
}
void MediaPlayerBridge::CreateJavaMediaPlayerBridge() {
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
j_media_player_bridge_.Reset(Java_MediaPlayerBridge_create(env));
SetMediaPlayerListener();
}
void MediaPlayerBridge::SetJavaMediaPlayerBridge(
jobject j_media_player_bridge) {
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
j_media_player_bridge_.Reset(env, j_media_player_bridge);
}
void MediaPlayerBridge::SetMediaPlayerListener() {
jobject j_context = base::android::GetApplicationContext();
DCHECK(j_context);
listener_.CreateMediaPlayerListener(j_context, j_media_player_bridge_.obj());
}
void MediaPlayerBridge::SetDuration(base::TimeDelta duration) {
duration_ = duration;
}
void MediaPlayerBridge::SetVideoSurface(gfx::ScopedJavaSurface surface) {
if (j_media_player_bridge_.is_null()) {
if (surface.IsEmpty())
return;
Prepare();
}
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
Java_MediaPlayerBridge_setSurface(
env, j_media_player_bridge_.obj(), surface.j_surface().obj());
}
void MediaPlayerBridge::Prepare() {
if (j_media_player_bridge_.is_null())
CreateJavaMediaPlayerBridge();
if (url_.SchemeIsFileSystem()) {
manager()->GetMediaResourceGetter()->GetPlatformPathFromFileSystemURL(
url_, base::Bind(&MediaPlayerBridge::SetDataSource,
weak_this_.GetWeakPtr()));
} else {
SetDataSource(url_.spec());
}
}
void MediaPlayerBridge::SetDataSource(const std::string& url) {
if (j_media_player_bridge_.is_null())
return;
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
// Create a Java String for the URL.
ScopedJavaLocalRef<jstring> j_url_string = ConvertUTF8ToJavaString(env, url);
ScopedJavaLocalRef<jstring> j_cookies = ConvertUTF8ToJavaString(
env, cookies_);
jobject j_context = base::android::GetApplicationContext();
DCHECK(j_context);
if (Java_MediaPlayerBridge_setDataSource(
env, j_media_player_bridge_.obj(), j_context, j_url_string.obj(),
j_cookies.obj(), hide_url_log_)) {
RequestMediaResourcesFromManager();
Java_MediaPlayerBridge_prepareAsync(
env, j_media_player_bridge_.obj());
} else {
OnMediaError(MEDIA_ERROR_FORMAT);
}
}
void MediaPlayerBridge::OnCookiesRetrieved(const std::string& cookies) {
cookies_ = cookies;
ExtractMediaMetadata(url_.spec());
}
void MediaPlayerBridge::ExtractMediaMetadata(const std::string& url) {
manager()->GetMediaResourceGetter()->ExtractMediaMetadata(
url, cookies_, base::Bind(&MediaPlayerBridge::OnMediaMetadataExtracted,
weak_this_.GetWeakPtr()));
}
void MediaPlayerBridge::OnMediaMetadataExtracted(
base::TimeDelta duration, int width, int height, bool success) {
if (success) {
duration_ = duration;
width_ = width;
height_ = height;
}
OnMediaMetadataChanged(duration_, width_, height_, success);
}
void MediaPlayerBridge::Start() {
if (j_media_player_bridge_.is_null()) {
pending_play_ = true;
Prepare();
} else {
if (prepared_)
StartInternal();
else
pending_play_ = true;
}
}
void MediaPlayerBridge::Pause() {
if (j_media_player_bridge_.is_null()) {
pending_play_ = false;
} else {
if (prepared_ && IsPlaying())
PauseInternal();
else
pending_play_ = false;
}
}
bool MediaPlayerBridge::IsPlaying() {
if (!prepared_)
return pending_play_;
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
jboolean result = Java_MediaPlayerBridge_isPlaying(
env, j_media_player_bridge_.obj());
return result;
}
int MediaPlayerBridge::GetVideoWidth() {
if (!prepared_)
return width_;
JNIEnv* env = base::android::AttachCurrentThread();
return Java_MediaPlayerBridge_getVideoWidth(
env, j_media_player_bridge_.obj());
}
int MediaPlayerBridge::GetVideoHeight() {
if (!prepared_)
return height_;
JNIEnv* env = base::android::AttachCurrentThread();
return Java_MediaPlayerBridge_getVideoHeight(
env, j_media_player_bridge_.obj());
}
void MediaPlayerBridge::SeekTo(base::TimeDelta time) {
// Record the time to seek when OnMediaPrepared() is called.
pending_seek_ = time;
if (j_media_player_bridge_.is_null())
Prepare();
else if (prepared_)
SeekInternal(time);
}
base::TimeDelta MediaPlayerBridge::GetCurrentTime() {
if (!prepared_)
return pending_seek_;
JNIEnv* env = base::android::AttachCurrentThread();
return base::TimeDelta::FromMilliseconds(
Java_MediaPlayerBridge_getCurrentPosition(
env, j_media_player_bridge_.obj()));
}
base::TimeDelta MediaPlayerBridge::GetDuration() {
if (!prepared_)
return duration_;
JNIEnv* env = base::android::AttachCurrentThread();
return base::TimeDelta::FromMilliseconds(
Java_MediaPlayerBridge_getDuration(
env, j_media_player_bridge_.obj()));
}
void MediaPlayerBridge::Release() {
if (j_media_player_bridge_.is_null())
return;
time_update_timer_.Stop();
if (prepared_)
pending_seek_ = GetCurrentTime();
prepared_ = false;
pending_play_ = false;
SetVideoSurface(gfx::ScopedJavaSurface());
JNIEnv* env = base::android::AttachCurrentThread();
Java_MediaPlayerBridge_release(env, j_media_player_bridge_.obj());
j_media_player_bridge_.Reset();
ReleaseMediaResourcesFromManager();
listener_.ReleaseMediaPlayerListenerResources();
}
void MediaPlayerBridge::SetVolume(double volume) {
if (j_media_player_bridge_.is_null())
return;
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
Java_MediaPlayerBridge_setVolume(
env, j_media_player_bridge_.obj(), volume);
}
void MediaPlayerBridge::OnVideoSizeChanged(int width, int height) {
width_ = width;
height_ = height;
MediaPlayerAndroid::OnVideoSizeChanged(width, height);
}
void MediaPlayerBridge::OnPlaybackComplete() {
time_update_timer_.Stop();
MediaPlayerAndroid::OnPlaybackComplete();
}
void MediaPlayerBridge::OnMediaInterrupted() {
time_update_timer_.Stop();
MediaPlayerAndroid::OnMediaInterrupted();
}
void MediaPlayerBridge::OnMediaPrepared() {
if (j_media_player_bridge_.is_null())
return;
prepared_ = true;
base::TimeDelta dur = duration_;
duration_ = GetDuration();
if (duration_ != dur && 0 != dur.InMilliseconds()) {
// Scale the |pending_seek_| according to the new duration.
pending_seek_ = base::TimeDelta::FromSeconds(
pending_seek_.InSecondsF() * duration_.InSecondsF() / dur.InSecondsF());
}
// If media player was recovered from a saved state, consume all the pending
// events.
PendingSeekInternal(pending_seek_);
if (pending_play_) {
StartInternal();
pending_play_ = false;
}
GetAllowedOperations();
OnMediaMetadataChanged(duration_, width_, height_, true);
}
void MediaPlayerBridge::GetAllowedOperations() {
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
ScopedJavaLocalRef<jobject> allowedOperations =
Java_MediaPlayerBridge_getAllowedOperations(
env, j_media_player_bridge_.obj());
can_pause_ = Java_AllowedOperations_canPause(env, allowedOperations.obj());
can_seek_forward_ = Java_AllowedOperations_canSeekForward(
env, allowedOperations.obj());
can_seek_backward_ = Java_AllowedOperations_canSeekBackward(
env, allowedOperations.obj());
}
void MediaPlayerBridge::StartInternal() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_MediaPlayerBridge_start(env, j_media_player_bridge_.obj());
if (!time_update_timer_.IsRunning()) {
time_update_timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kTimeUpdateInterval),
this, &MediaPlayerBridge::OnTimeUpdated);
}
}
void MediaPlayerBridge::PauseInternal() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_MediaPlayerBridge_pause(env, j_media_player_bridge_.obj());
time_update_timer_.Stop();
}
void MediaPlayerBridge::PendingSeekInternal(base::TimeDelta time) {
SeekInternal(time);
}
void MediaPlayerBridge::SeekInternal(base::TimeDelta time) {
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
int time_msec = static_cast<int>(time.InMilliseconds());
Java_MediaPlayerBridge_seekTo(
env, j_media_player_bridge_.obj(), time_msec);
}
bool MediaPlayerBridge::RegisterMediaPlayerBridge(JNIEnv* env) {
bool ret = RegisterNativesImpl(env);
DCHECK(g_MediaPlayerBridge_clazz);
return ret;
}
bool MediaPlayerBridge::CanPause() {
return can_pause_;
}
bool MediaPlayerBridge::CanSeekForward() {
return can_seek_forward_;
}
bool MediaPlayerBridge::CanSeekBackward() {
return can_seek_backward_;
}
bool MediaPlayerBridge::IsPlayerReady() {
return prepared_;
}
GURL MediaPlayerBridge::GetUrl() {
return url_;
}
GURL MediaPlayerBridge::GetFirstPartyForCookies() {
return first_party_for_cookies_;
}
} // namespace media
<commit_msg>Fix HLS playback on android 4.3<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/android/media_player_bridge.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/message_loop/message_loop_proxy.h"
#include "jni/MediaPlayerBridge_jni.h"
#include "media/base/android/media_player_manager.h"
#include "media/base/android/media_resource_getter.h"
#include "media/base/android/media_source_player.h"
using base::android::ConvertUTF8ToJavaString;
using base::android::ScopedJavaLocalRef;
// Time update happens every 250ms.
static const int kTimeUpdateInterval = 250;
// Android MediaMetadataRetriever may fail to extract the metadata from the
// media under some circumstances. This makes the user unable to perform
// seek. To solve this problem, we use a temporary duration of 100 seconds when
// the duration is unknown. And we scale the seek position later when duration
// is available.
static const int kTemporaryDuration = 100;
namespace media {
#if !defined(GOOGLE_TV)
// static
MediaPlayerAndroid* MediaPlayerAndroid::Create(
int player_id,
const GURL& url,
SourceType source_type,
const GURL& first_party_for_cookies,
bool hide_url_log,
MediaPlayerManager* manager) {
if (source_type == SOURCE_TYPE_URL) {
MediaPlayerBridge* media_player_bridge = new MediaPlayerBridge(
player_id,
url,
first_party_for_cookies,
hide_url_log,
manager);
media_player_bridge->Initialize();
return media_player_bridge;
} else {
return new MediaSourcePlayer(
player_id,
manager);
}
}
#endif
MediaPlayerBridge::MediaPlayerBridge(
int player_id,
const GURL& url,
const GURL& first_party_for_cookies,
bool hide_url_log,
MediaPlayerManager* manager)
: MediaPlayerAndroid(player_id,
manager),
prepared_(false),
pending_play_(false),
url_(url),
first_party_for_cookies_(first_party_for_cookies),
hide_url_log_(hide_url_log),
duration_(base::TimeDelta::FromSeconds(kTemporaryDuration)),
width_(0),
height_(0),
can_pause_(true),
can_seek_forward_(true),
can_seek_backward_(true),
weak_this_(this),
listener_(base::MessageLoopProxy::current(),
weak_this_.GetWeakPtr()) {
}
MediaPlayerBridge::~MediaPlayerBridge() {
Release();
}
void MediaPlayerBridge::Initialize() {
if (url_.SchemeIsFile()) {
cookies_.clear();
ExtractMediaMetadata(url_.spec());
return;
}
media::MediaResourceGetter* resource_getter =
manager()->GetMediaResourceGetter();
if (url_.SchemeIsFileSystem()) {
cookies_.clear();
resource_getter->GetPlatformPathFromFileSystemURL(url_, base::Bind(
&MediaPlayerBridge::ExtractMediaMetadata, weak_this_.GetWeakPtr()));
return;
}
resource_getter->GetCookies(url_, first_party_for_cookies_, base::Bind(
&MediaPlayerBridge::OnCookiesRetrieved, weak_this_.GetWeakPtr()));
}
void MediaPlayerBridge::CreateJavaMediaPlayerBridge() {
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
j_media_player_bridge_.Reset(Java_MediaPlayerBridge_create(env));
SetMediaPlayerListener();
}
void MediaPlayerBridge::SetJavaMediaPlayerBridge(
jobject j_media_player_bridge) {
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
j_media_player_bridge_.Reset(env, j_media_player_bridge);
}
void MediaPlayerBridge::SetMediaPlayerListener() {
jobject j_context = base::android::GetApplicationContext();
DCHECK(j_context);
listener_.CreateMediaPlayerListener(j_context, j_media_player_bridge_.obj());
}
void MediaPlayerBridge::SetDuration(base::TimeDelta duration) {
duration_ = duration;
}
void MediaPlayerBridge::SetVideoSurface(gfx::ScopedJavaSurface surface) {
if (j_media_player_bridge_.is_null()) {
if (surface.IsEmpty())
return;
Prepare();
}
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
Java_MediaPlayerBridge_setSurface(
env, j_media_player_bridge_.obj(), surface.j_surface().obj());
}
void MediaPlayerBridge::Prepare() {
if (j_media_player_bridge_.is_null())
CreateJavaMediaPlayerBridge();
if (url_.SchemeIsFileSystem()) {
manager()->GetMediaResourceGetter()->GetPlatformPathFromFileSystemURL(
url_, base::Bind(&MediaPlayerBridge::SetDataSource,
weak_this_.GetWeakPtr()));
} else {
SetDataSource(url_.spec());
}
}
void MediaPlayerBridge::SetDataSource(const std::string& url) {
if (j_media_player_bridge_.is_null())
return;
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
// Create a Java String for the URL.
ScopedJavaLocalRef<jstring> j_url_string = ConvertUTF8ToJavaString(env, url);
ScopedJavaLocalRef<jstring> j_cookies = ConvertUTF8ToJavaString(
env, cookies_);
jobject j_context = base::android::GetApplicationContext();
DCHECK(j_context);
if (Java_MediaPlayerBridge_setDataSource(
env, j_media_player_bridge_.obj(), j_context, j_url_string.obj(),
j_cookies.obj(), hide_url_log_)) {
RequestMediaResourcesFromManager();
Java_MediaPlayerBridge_prepareAsync(
env, j_media_player_bridge_.obj());
} else {
OnMediaError(MEDIA_ERROR_FORMAT);
}
}
void MediaPlayerBridge::OnCookiesRetrieved(const std::string& cookies) {
cookies_ = cookies;
ExtractMediaMetadata(url_.spec());
}
void MediaPlayerBridge::ExtractMediaMetadata(const std::string& url) {
manager()->GetMediaResourceGetter()->ExtractMediaMetadata(
url, cookies_, base::Bind(&MediaPlayerBridge::OnMediaMetadataExtracted,
weak_this_.GetWeakPtr()));
}
void MediaPlayerBridge::OnMediaMetadataExtracted(
base::TimeDelta duration, int width, int height, bool success) {
if (success) {
duration_ = duration;
width_ = width;
height_ = height;
}
OnMediaMetadataChanged(duration_, width_, height_, success);
}
void MediaPlayerBridge::Start() {
if (j_media_player_bridge_.is_null()) {
pending_play_ = true;
Prepare();
} else {
if (prepared_)
StartInternal();
else
pending_play_ = true;
}
}
void MediaPlayerBridge::Pause() {
if (j_media_player_bridge_.is_null()) {
pending_play_ = false;
} else {
if (prepared_ && IsPlaying())
PauseInternal();
else
pending_play_ = false;
}
}
bool MediaPlayerBridge::IsPlaying() {
if (!prepared_)
return pending_play_;
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
jboolean result = Java_MediaPlayerBridge_isPlaying(
env, j_media_player_bridge_.obj());
return result;
}
int MediaPlayerBridge::GetVideoWidth() {
if (!prepared_)
return width_;
JNIEnv* env = base::android::AttachCurrentThread();
return Java_MediaPlayerBridge_getVideoWidth(
env, j_media_player_bridge_.obj());
}
int MediaPlayerBridge::GetVideoHeight() {
if (!prepared_)
return height_;
JNIEnv* env = base::android::AttachCurrentThread();
return Java_MediaPlayerBridge_getVideoHeight(
env, j_media_player_bridge_.obj());
}
void MediaPlayerBridge::SeekTo(base::TimeDelta time) {
// Record the time to seek when OnMediaPrepared() is called.
pending_seek_ = time;
if (j_media_player_bridge_.is_null())
Prepare();
else if (prepared_)
SeekInternal(time);
}
base::TimeDelta MediaPlayerBridge::GetCurrentTime() {
if (!prepared_)
return pending_seek_;
JNIEnv* env = base::android::AttachCurrentThread();
return base::TimeDelta::FromMilliseconds(
Java_MediaPlayerBridge_getCurrentPosition(
env, j_media_player_bridge_.obj()));
}
base::TimeDelta MediaPlayerBridge::GetDuration() {
if (!prepared_)
return duration_;
JNIEnv* env = base::android::AttachCurrentThread();
return base::TimeDelta::FromMilliseconds(
Java_MediaPlayerBridge_getDuration(
env, j_media_player_bridge_.obj()));
}
void MediaPlayerBridge::Release() {
if (j_media_player_bridge_.is_null())
return;
time_update_timer_.Stop();
if (prepared_)
pending_seek_ = GetCurrentTime();
prepared_ = false;
pending_play_ = false;
SetVideoSurface(gfx::ScopedJavaSurface());
JNIEnv* env = base::android::AttachCurrentThread();
Java_MediaPlayerBridge_release(env, j_media_player_bridge_.obj());
j_media_player_bridge_.Reset();
ReleaseMediaResourcesFromManager();
listener_.ReleaseMediaPlayerListenerResources();
}
void MediaPlayerBridge::SetVolume(double volume) {
if (j_media_player_bridge_.is_null())
return;
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
Java_MediaPlayerBridge_setVolume(
env, j_media_player_bridge_.obj(), volume);
}
void MediaPlayerBridge::OnVideoSizeChanged(int width, int height) {
width_ = width;
height_ = height;
MediaPlayerAndroid::OnVideoSizeChanged(width, height);
}
void MediaPlayerBridge::OnPlaybackComplete() {
time_update_timer_.Stop();
MediaPlayerAndroid::OnPlaybackComplete();
}
void MediaPlayerBridge::OnMediaInterrupted() {
time_update_timer_.Stop();
MediaPlayerAndroid::OnMediaInterrupted();
}
void MediaPlayerBridge::OnMediaPrepared() {
if (j_media_player_bridge_.is_null())
return;
prepared_ = true;
base::TimeDelta dur = duration_;
duration_ = GetDuration();
if (duration_ != dur && 0 != dur.InMilliseconds()) {
// Scale the |pending_seek_| according to the new duration.
pending_seek_ = base::TimeDelta::FromSeconds(
pending_seek_.InSecondsF() * duration_.InSecondsF() / dur.InSecondsF());
}
// If media player was recovered from a saved state, consume all the pending
// events.
PendingSeekInternal(pending_seek_);
if (pending_play_) {
StartInternal();
pending_play_ = false;
}
GetAllowedOperations();
OnMediaMetadataChanged(duration_, width_, height_, true);
}
void MediaPlayerBridge::GetAllowedOperations() {
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
ScopedJavaLocalRef<jobject> allowedOperations =
Java_MediaPlayerBridge_getAllowedOperations(
env, j_media_player_bridge_.obj());
can_pause_ = Java_AllowedOperations_canPause(env, allowedOperations.obj());
can_seek_forward_ = Java_AllowedOperations_canSeekForward(
env, allowedOperations.obj());
can_seek_backward_ = Java_AllowedOperations_canSeekBackward(
env, allowedOperations.obj());
}
void MediaPlayerBridge::StartInternal() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_MediaPlayerBridge_start(env, j_media_player_bridge_.obj());
if (!time_update_timer_.IsRunning()) {
time_update_timer_.Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(kTimeUpdateInterval),
this, &MediaPlayerBridge::OnTimeUpdated);
}
}
void MediaPlayerBridge::PauseInternal() {
JNIEnv* env = base::android::AttachCurrentThread();
Java_MediaPlayerBridge_pause(env, j_media_player_bridge_.obj());
time_update_timer_.Stop();
}
void MediaPlayerBridge::PendingSeekInternal(base::TimeDelta time) {
SeekInternal(time);
}
void MediaPlayerBridge::SeekInternal(base::TimeDelta time) {
if (time > duration_)
time = duration_;
// Seeking to an invalid position may cause media player to stuck in an
// error state.
if (time < base::TimeDelta()) {
DCHECK_EQ(-1.0, time.InMillisecondsF());
return;
}
JNIEnv* env = base::android::AttachCurrentThread();
CHECK(env);
int time_msec = static_cast<int>(time.InMilliseconds());
Java_MediaPlayerBridge_seekTo(
env, j_media_player_bridge_.obj(), time_msec);
}
bool MediaPlayerBridge::RegisterMediaPlayerBridge(JNIEnv* env) {
bool ret = RegisterNativesImpl(env);
DCHECK(g_MediaPlayerBridge_clazz);
return ret;
}
bool MediaPlayerBridge::CanPause() {
return can_pause_;
}
bool MediaPlayerBridge::CanSeekForward() {
return can_seek_forward_;
}
bool MediaPlayerBridge::CanSeekBackward() {
return can_seek_backward_;
}
bool MediaPlayerBridge::IsPlayerReady() {
return prepared_;
}
GURL MediaPlayerBridge::GetUrl() {
return url_;
}
GURL MediaPlayerBridge::GetFirstPartyForCookies() {
return first_party_for_cookies_;
}
} // namespace media
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fntctl.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 05:25:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <string> // HACK: prevent conflict between STLPORT and Workshop headern
#ifndef _STDMENU_HXX //autogen
#include <svtools/stdmenu.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#define ITEMID_FONT 1
#define ITEMID_FONTLIST 2
#include "fntctl.hxx" // ITEMID_FONT muss vorher definiert sein!
#include "svxids.hrc"
#ifndef _SVX_FLSTITEM_HXX //autogen
#include "flstitem.hxx"
#endif
#ifndef _SVX_FONTITEM_HXX //autogen
#include "fontitem.hxx"
#endif
// STATIC DATA -----------------------------------------------------------
SFX_IMPL_MENU_CONTROL(SvxFontMenuControl, SvxFontItem);
//--------------------------------------------------------------------
/* [Beschreibung]
Ctor; setzt den Select-Handler am Men"u und tr"agt das Men"u
in seinen Parent ein.
*/
SvxFontMenuControl::SvxFontMenuControl
(
USHORT nId,
Menu& rMenu,
SfxBindings& rBindings
) :
pMenu ( new FontNameMenu ),
rParent ( rMenu )
{
rMenu.SetPopupMenu( nId, pMenu );
pMenu->SetSelectHdl( LINK( this, SvxFontMenuControl, MenuSelect ) );
StartListening( rBindings );
FillMenu();
}
//--------------------------------------------------------------------
/* [Beschreibung]
F"ullt das Men"u mit den aktuellen Fonts aus der Fontlist
der DocumentShell.
*/
void SvxFontMenuControl::FillMenu()
{
SfxObjectShell *pDoc = SfxObjectShell::Current();
if ( pDoc )
{
const SvxFontListItem* pFonts =
(const SvxFontListItem*)pDoc->GetItem( SID_ATTR_CHAR_FONTLIST );
const FontList* pList = pFonts ? pFonts->GetFontList(): 0;
DBG_ASSERT( pList, "Kein Fonts gefunden" );
pMenu->Fill( pList );
}
}
//--------------------------------------------------------------------
/* [Beschreibung]
Statusbenachrichtigung;
f"ullt ggf. das Men"u mit den aktuellen Fonts aus der Fontlist
der DocumentShell.
Ist die Funktionalit"at disabled, wird der entsprechende
Men"ueintrag im Parentmen"u disabled, andernfalls wird er enabled.
Der aktuelle Font wird mit einer Checkmark versehen.
*/
void SvxFontMenuControl::StateChanged(
USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
rParent.EnableItem( GetId(), SFX_ITEM_DISABLED != eState );
if ( SFX_ITEM_AVAILABLE == eState )
{
if ( !pMenu->GetItemCount() )
FillMenu();
const SvxFontItem* pFontItem = PTR_CAST( SvxFontItem, pState );
String aFont;
if ( pFontItem )
aFont = pFontItem->GetFamilyName();
pMenu->SetCurName( aFont );
}
}
//--------------------------------------------------------------------
/* [Beschreibung]
Statusbenachrichtigung "uber Bindings; bei DOCCHANGED
wird das Men"u mit den aktuellen Fonts aus der Fontlist
der DocumentShell gef"ullt.
*/
void SvxFontMenuControl::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType )
{
if ( rHint.Type() != TYPE(SfxSimpleHint) &&
( (SfxSimpleHint&)rHint ).GetId() == SFX_HINT_DOCCHANGED )
FillMenu();
}
//--------------------------------------------------------------------
/* [Beschreibung]
Select-Handler des Men"us; der Name des selektierten Fonts
wird in einem SvxFontItem verschickt. Das F"ullen mit den
weiteren Fontinformationen mu\s durch die Applikation geschehen.
*/
IMPL_LINK_INLINE_START( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )
{
SvxFontItem aItem( GetId() );
aItem.GetFamilyName() = pMen->GetCurName();
GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_RECORD, &aItem, 0L );
return 0;
}
IMPL_LINK_INLINE_END( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )
//--------------------------------------------------------------------
/* [Beschreibung]
Dtor; gibt das Men"u frei.
*/
SvxFontMenuControl::~SvxFontMenuControl()
{
delete pMenu;
}
//--------------------------------------------------------------------
/* [Beschreibung]
Gibt das Men"u zur"uck
*/
PopupMenu* SvxFontMenuControl::GetPopup() const
{
return pMenu;
}
<commit_msg>INTEGRATION: CWS sb59 (1.3.62); FILE MERGED 2006/08/03 13:51:50 cl 1.3.62.1: removed compiler warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fntctl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-10-12 12:57:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include <string> // HACK: prevent conflict between STLPORT and Workshop headern
#ifndef _STDMENU_HXX //autogen
#include <svtools/stdmenu.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFX_OBJSH_HXX //autogen
#include <sfx2/objsh.hxx>
#endif
#ifndef _SFXDISPATCH_HXX //autogen
#include <sfx2/dispatch.hxx>
#endif
#define ITEMID_FONT 1
#define ITEMID_FONTLIST 2
#include "fntctl.hxx" // ITEMID_FONT muss vorher definiert sein!
#include "svxids.hrc"
#ifndef _SVX_FLSTITEM_HXX //autogen
#include "flstitem.hxx"
#endif
#ifndef _SVX_FONTITEM_HXX //autogen
#include "fontitem.hxx"
#endif
// STATIC DATA -----------------------------------------------------------
SFX_IMPL_MENU_CONTROL(SvxFontMenuControl, SvxFontItem);
//--------------------------------------------------------------------
/* [Beschreibung]
Ctor; setzt den Select-Handler am Men"u und tr"agt das Men"u
in seinen Parent ein.
*/
SvxFontMenuControl::SvxFontMenuControl
(
USHORT _nId,
Menu& rMenu,
SfxBindings& rBindings
) :
pMenu ( new FontNameMenu ),
rParent ( rMenu )
{
rMenu.SetPopupMenu( _nId, pMenu );
pMenu->SetSelectHdl( LINK( this, SvxFontMenuControl, MenuSelect ) );
StartListening( rBindings );
FillMenu();
}
//--------------------------------------------------------------------
/* [Beschreibung]
F"ullt das Men"u mit den aktuellen Fonts aus der Fontlist
der DocumentShell.
*/
void SvxFontMenuControl::FillMenu()
{
SfxObjectShell *pDoc = SfxObjectShell::Current();
if ( pDoc )
{
const SvxFontListItem* pFonts =
(const SvxFontListItem*)pDoc->GetItem( SID_ATTR_CHAR_FONTLIST );
const FontList* pList = pFonts ? pFonts->GetFontList(): 0;
DBG_ASSERT( pList, "Kein Fonts gefunden" );
pMenu->Fill( pList );
}
}
//--------------------------------------------------------------------
/* [Beschreibung]
Statusbenachrichtigung;
f"ullt ggf. das Men"u mit den aktuellen Fonts aus der Fontlist
der DocumentShell.
Ist die Funktionalit"at disabled, wird der entsprechende
Men"ueintrag im Parentmen"u disabled, andernfalls wird er enabled.
Der aktuelle Font wird mit einer Checkmark versehen.
*/
void SvxFontMenuControl::StateChanged(
USHORT, SfxItemState eState, const SfxPoolItem* pState )
{
rParent.EnableItem( GetId(), SFX_ITEM_DISABLED != eState );
if ( SFX_ITEM_AVAILABLE == eState )
{
if ( !pMenu->GetItemCount() )
FillMenu();
const SvxFontItem* pFontItem = PTR_CAST( SvxFontItem, pState );
String aFont;
if ( pFontItem )
aFont = pFontItem->GetFamilyName();
pMenu->SetCurName( aFont );
}
}
//--------------------------------------------------------------------
/* [Beschreibung]
Statusbenachrichtigung "uber Bindings; bei DOCCHANGED
wird das Men"u mit den aktuellen Fonts aus der Fontlist
der DocumentShell gef"ullt.
*/
void SvxFontMenuControl::SFX_NOTIFY( SfxBroadcaster&, const TypeId& rBCType,
const SfxHint& rHint, const TypeId& rHintType )
{
if ( rHint.Type() != TYPE(SfxSimpleHint) &&
( (SfxSimpleHint&)rHint ).GetId() == SFX_HINT_DOCCHANGED )
FillMenu();
}
//--------------------------------------------------------------------
/* [Beschreibung]
Select-Handler des Men"us; der Name des selektierten Fonts
wird in einem SvxFontItem verschickt. Das F"ullen mit den
weiteren Fontinformationen mu\s durch die Applikation geschehen.
*/
IMPL_LINK_INLINE_START( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )
{
SvxFontItem aItem( GetId() );
aItem.GetFamilyName() = pMen->GetCurName();
GetBindings().GetDispatcher()->Execute( GetId(), SFX_CALLMODE_RECORD, &aItem, 0L );
return 0;
}
IMPL_LINK_INLINE_END( SvxFontMenuControl, MenuSelect, FontNameMenu *, pMen )
//--------------------------------------------------------------------
/* [Beschreibung]
Dtor; gibt das Men"u frei.
*/
SvxFontMenuControl::~SvxFontMenuControl()
{
delete pMenu;
}
//--------------------------------------------------------------------
/* [Beschreibung]
Gibt das Men"u zur"uck
*/
PopupMenu* SvxFontMenuControl::GetPopup() const
{
return pMenu;
}
<|endoftext|> |
<commit_before><commit_msg>Add error message to help debug install status inconsistency from logs.<commit_after><|endoftext|> |
<commit_before>#pragma once
#ifndef VARIANT_HPP
# define VARIANT_HPP
#include <cassert>
#include <type_traits>
#include <typeinfo>
#include <utility>
namespace detail
{
template <typename A, typename ...B>
struct max_align
{
static constexpr auto const align =
(alignof(A) > max_align<B...>::align)
? alignof(A)
: max_align<B...>::align;
};
template <typename A, typename B>
struct max_align<A, B>
{
static constexpr auto const align =
(alignof(A) > alignof(B)) ? alignof(A) : alignof(B);
};
template <typename A>
struct max_align<A>
{
static constexpr auto const align = alignof(A);
};
template <typename A, typename ...B>
struct max_type
{
typedef typename std::conditional<
(sizeof(A) > sizeof(typename max_type<B...>::type)),
A,
typename max_type<B...>::type
>::type type;
};
template <typename A, typename B>
struct max_type<A, B>
{
typedef typename std::conditional<(sizeof(A) > sizeof(B)), A, B>::type type;
};
template <typename A>
struct max_type<A>
{
typedef A type;
};
template <typename A, typename B, typename... C>
struct index_of
: std::integral_constant<int,
std::is_same<A, B>{}
+ (index_of<A, C...>{} == -1 ? -1 : 1+index_of<A, C...>{})
>
{
};
template <typename A, typename B>
struct index_of<A, B>
: std::integral_constant < int, std::is_same<A, B>{} -1 >
{
};
template <typename A, typename B, typename... C>
struct compatible_index_of
: std::integral_constant<int,
std::is_constructible<A, B>{}
+ (compatible_index_of<A, C...>{} == -1
? -1
: 1 + compatible_index_of<A, C...>{})
>
{
};
template <typename A, typename B>
struct compatible_index_of<A, B>
: std::integral_constant<int, std::is_constructible<A, B>{} - 1>
{
};
template <typename A, typename B, typename... C>
struct compatible_type
{
typedef typename std::conditional<std::is_constructible<A, B>{}, B,
typename compatible_type<A, C...>::type>::type type;
};
template <typename A, typename B>
struct compatible_type<A, B>
{
typedef typename std::conditional<
std::is_constructible<A, B>{}, B, void>::type type;
};
template <std::size_t I, typename A, typename ...B>
struct type_at : type_at<I - 1, B...>
{
};
template <typename A, typename ...B>
struct type_at<0, A, B...>
{
typedef A type;
};
template <bool B>
using bool_ = std::integral_constant<bool, B>;
template <class A, class ...B>
struct all_of : bool_<A::value && all_of<B...>::value> { };
template <class A>
struct all_of<A> : bool_<A::value> { };
template <class A, class ...B>
struct one_of : bool_<A::value || one_of<B...>::value> { };
template <class A>
struct one_of<A> : bool_<A::value> { };
template <class A>
struct is_move_or_copy_constructible
{
static constexpr auto const value =
std::is_copy_constructible<A>::value
|| std::is_move_constructible<A>::value;
};
}
template <typename ...T>
struct variant
{
static_assert(!::detail::one_of<std::is_reference<T>...>::value,
"reference types are unsupported");
static_assert(::detail::all_of<
::detail::is_move_or_copy_constructible<T>...>::value,
"unmovable and uncopyable types are unsupported");
static constexpr auto const max_align = detail::max_align<T...>::align;
typedef typename detail::max_type<T...>::type max_type;
constexpr variant() = default;
~variant()
{
if (-1 != store_type_)
{
deleter_(store_);
}
// else do nothing
}
variant(variant const& other)
{
*this = other;
}
variant(variant&& other)
{
*this = std::move(other);
}
variant& operator=(variant const& rhs)
{
if (-1 == rhs.store_type_)
{
if (-1 != store_type_)
{
store_type_ = -1;
deleter_(store_);
}
// else do nothing
}
else if (rhs.copier_)
{
rhs.copier_(const_cast<variant&>(rhs), *this);
deleter_ = rhs.deleter_;
copier_ = rhs.copier_;
mover_ = rhs.mover_;
store_type_ = rhs.store_type_;
}
else
{
throw std::bad_typeid();
}
return *this;
}
variant& operator=(variant&& rhs)
{
if (-1 == rhs.store_type)
{
if (-1 != store_type_)
{
store_type_ = -1;
deleter_(store_);
}
// else do nothing
}
else if (rhs.mover_)
{
rhs.mover_(rhs, *this);
deleter_ = rhs.deleter_;
copier_ = rhs.copier_;
mover_ = rhs.mover_;
store_type_ = rhs.store_type_;
}
else
{
throw std::bad_typeid();
}
return *this;
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<T,
typename std::remove_const<U>::type>...
>::value
>::type
>
variant(U&& f)
{
*this = std::forward<U>(f);
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<
typename std::remove_const<T>::type, U>...
>::value
>::type
>
variant& operator=(U&& f)
{
if (-1 != store_type_)
{
deleter_(store_);
}
// else do nothing
new (store_) U(std::forward<U>(f));
deleter_ = destructor_stub<U>;
copier_ = std::is_copy_constructible<U>::value
? copier_stub<U>
: nullptr;
mover_ = std::is_move_constructible<U>::value
? mover_stub<U>
: nullptr;
store_type_ = ::detail::index_of<U,
typename std::remove_const<T>::type...>::value;
return *this;
}
constexpr explicit operator bool() const { return -1 != store_type_; }
template <typename U>
constexpr bool contains() const
{
return (-1 != store_type_)
&& (::detail::index_of<U,
typename std::remove_const<T>::type...>::value == store_type_);
}
template <typename U,
typename = typename std::enable_if<
-1 != ::detail::index_of<U,
typename std::remove_const<T>::type...>::value
>::type
>
U& get() const
{
if (::detail::index_of<U,
typename std::remove_const<T>::type...>::value == store_type_)
{
return *(const_cast<U*>(static_cast<U const*>(
static_cast<void const*>(store_))));
}
else
{
throw std::bad_typeid();
}
}
template <typename U>
U get(typename std::enable_if<(-1 ==
::detail::index_of<U, typename std::remove_const<T>::type...>::value)
&& (-1 != ::detail::compatible_index_of<U,
typename std::remove_const<T>::type...>::value)
&& (std::is_arithmetic<U>::value
|| std::is_enum<U>::value)
&& (std::is_arithmetic<typename ::detail::compatible_type<U, T...>::type>
::value
|| std::is_enum<typename ::detail::compatible_type<U, T...>::type>
::value)
>::type* = nullptr)
{
static_assert(std::is_same<
typename ::detail::type_at<::detail::compatible_index_of<U,
typename std::remove_const<T>::type...>::value, T...>::type,
typename ::detail::compatible_type<U, T...>::type>::value,
"internal error");
if (::detail::compatible_index_of<U,
typename std::remove_const<T>::type...>::value == store_type_)
{
return U(*static_cast<typename ::detail::compatible_type<U, T...>::type
const*>(static_cast<void const*>(store_)));
}
else
{
throw std::bad_typeid();
}
}
private:
template <typename U>
static void destructor_stub(void* const p)
{
static_cast<U*>(p)->~U();
}
template <typename U>
static void copier_stub(variant& src, variant& dst)
{
new (dst.store_) U(*static_cast<U*>(static_cast<void*>(src.store_)));
}
template <typename U>
static void mover_stub(variant& src, variant& dst)
{
new (dst.store_) U(std::move(*static_cast<U*>(
static_cast<void*>(src.store_))));
}
int store_type_{ -1 };
typedef void (*deleter_type)(void*);
deleter_type deleter_;
typedef void (*mover_type)(variant&, variant&);
mover_type copier_;
mover_type mover_;
alignas(max_align) char store_[sizeof(max_type)];
};
#endif // VARIANT_HPP
<commit_msg>strips<commit_after>#pragma once
#ifndef VARIANT_HPP
# define VARIANT_HPP
#include <cassert>
#include <type_traits>
#include <typeinfo>
#include <utility>
namespace detail
{
template <typename A, typename ...B>
struct max_align
{
static constexpr auto const align =
(alignof(A) > max_align<B...>::align)
? alignof(A)
: max_align<B...>::align;
};
template <typename A, typename B>
struct max_align<A, B>
{
static constexpr auto const align =
(alignof(A) > alignof(B)) ? alignof(A) : alignof(B);
};
template <typename A>
struct max_align<A>
{
static constexpr auto const align = alignof(A);
};
template <typename A, typename ...B>
struct max_type
{
typedef typename std::conditional<
(sizeof(A) > sizeof(typename max_type<B...>::type)),
A,
typename max_type<B...>::type
>::type type;
};
template <typename A, typename B>
struct max_type<A, B>
{
typedef typename std::conditional<(sizeof(A) > sizeof(B)), A, B>::type type;
};
template <typename A>
struct max_type<A>
{
typedef A type;
};
template <typename A, typename B, typename... C>
struct index_of
: std::integral_constant<int,
std::is_same<A, B>{}
+ (index_of<A, C...>{} == -1 ? -1 : 1+index_of<A, C...>{})
>
{
};
template <typename A, typename B>
struct index_of<A, B>
: std::integral_constant < int, std::is_same<A, B>{} -1 >
{
};
template <typename A, typename B, typename... C>
struct compatible_index_of
: std::integral_constant<int,
std::is_constructible<A, B>{}
+ (compatible_index_of<A, C...>{} == -1
? -1
: 1 + compatible_index_of<A, C...>{})
>
{
};
template <typename A, typename B>
struct compatible_index_of<A, B>
: std::integral_constant<int, std::is_constructible<A, B>{} - 1>
{
};
template <typename A, typename B, typename... C>
struct compatible_type
{
typedef typename std::conditional<std::is_constructible<A, B>{}, B,
typename compatible_type<A, C...>::type>::type type;
};
template <typename A, typename B>
struct compatible_type<A, B>
{
typedef typename std::conditional<
std::is_constructible<A, B>{}, B, void>::type type;
};
template <std::size_t I, typename A, typename ...B>
struct type_at : type_at<I - 1, B...>
{
};
template <typename A, typename ...B>
struct type_at<0, A, B...>
{
typedef A type;
};
template <bool B>
using bool_ = std::integral_constant<bool, B>;
template <class A, class ...B>
struct all_of : bool_<A::value && all_of<B...>::value> { };
template <class A>
struct all_of<A> : bool_<A::value> { };
template <class A, class ...B>
struct one_of : bool_<A::value || one_of<B...>::value> { };
template <class A>
struct one_of<A> : bool_<A::value> { };
template <class A>
struct is_move_or_copy_constructible
{
static constexpr auto const value =
std::is_copy_constructible<A>::value
|| std::is_move_constructible<A>::value;
};
}
template <typename ...T>
struct variant
{
static_assert(!::detail::one_of<std::is_reference<T>...>::value,
"reference types are unsupported");
static_assert(::detail::all_of<
::detail::is_move_or_copy_constructible<T>...>::value,
"unmovable and uncopyable types are unsupported");
static constexpr auto const max_align = detail::max_align<T...>::align;
typedef typename detail::max_type<T...>::type max_type;
constexpr variant() = default;
~variant()
{
if (-1 != store_type_)
{
deleter_(store_);
}
// else do nothing
}
variant(variant const& other)
{
*this = other;
}
variant(variant&& other)
{
*this = std::move(other);
}
variant& operator=(variant const& rhs)
{
if (-1 == rhs.store_type_)
{
if (*this)
{
store_type_ = -1;
deleter_(store_);
}
// else do nothing
}
else if (rhs.copier_)
{
rhs.copier_(const_cast<variant&>(rhs), *this);
deleter_ = rhs.deleter_;
copier_ = rhs.copier_;
mover_ = rhs.mover_;
store_type_ = rhs.store_type_;
}
else
{
throw std::bad_typeid();
}
return *this;
}
variant& operator=(variant&& rhs)
{
if (-1 == rhs.store_type)
{
if (*this)
{
store_type_ = -1;
deleter_(store_);
}
// else do nothing
}
else if (rhs.mover_)
{
rhs.mover_(rhs, *this);
deleter_ = rhs.deleter_;
copier_ = rhs.copier_;
mover_ = rhs.mover_;
store_type_ = rhs.store_type_;
}
else
{
throw std::bad_typeid();
}
return *this;
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<T,
typename std::remove_const<U>::type>...
>::value
>::type
>
variant(U&& f)
{
*this = std::forward<U>(f);
}
template <
typename U,
typename = typename std::enable_if<
::detail::one_of<std::is_same<
typename std::remove_const<T>::type, U>...
>::value
>::type
>
variant& operator=(U&& f)
{
if (*this)
{
deleter_(store_);
}
// else do nothing
new (store_) U(std::forward<U>(f));
deleter_ = destructor_stub<U>;
copier_ = std::is_copy_constructible<U>::value
? copier_stub<U>
: nullptr;
mover_ = std::is_move_constructible<U>::value
? mover_stub<U>
: nullptr;
store_type_ = ::detail::index_of<U,
typename std::remove_const<T>::type...>::value;
return *this;
}
constexpr explicit operator bool() const { return -1 != store_type_; }
template <typename U>
constexpr bool contains() const
{
return (-1 != store_type_)
&& (::detail::index_of<U,
typename std::remove_const<T>::type...>::value == store_type_);
}
template <typename U,
typename = typename std::enable_if<
-1 != ::detail::index_of<U,
typename std::remove_const<T>::type...>::value
>::type
>
U& get() const
{
if (::detail::index_of<U,
typename std::remove_const<T>::type...>::value == store_type_)
{
return *(const_cast<U*>(static_cast<U const*>(
static_cast<void const*>(store_))));
}
else
{
throw std::bad_typeid();
}
}
template <typename U>
U get(typename std::enable_if<(-1 ==
::detail::index_of<U, typename std::remove_const<T>::type...>::value)
&& (-1 != ::detail::compatible_index_of<U,
typename std::remove_const<T>::type...>::value)
&& (std::is_arithmetic<U>::value
|| std::is_enum<U>::value)
&& (std::is_arithmetic<typename ::detail::compatible_type<U, T...>::type>
::value
|| std::is_enum<typename ::detail::compatible_type<U, T...>::type>
::value)
>::type* = nullptr)
{
static_assert(std::is_same<
typename ::detail::type_at<::detail::compatible_index_of<U,
typename std::remove_const<T>::type...>::value, T...>::type,
typename ::detail::compatible_type<U, T...>::type>::value,
"internal error");
if (::detail::compatible_index_of<U,
typename std::remove_const<T>::type...>::value == store_type_)
{
return U(*static_cast<typename ::detail::compatible_type<U, T...>::type
const*>(static_cast<void const*>(store_)));
}
else
{
throw std::bad_typeid();
}
}
private:
template <typename U>
static void destructor_stub(void* const p)
{
static_cast<U*>(p)->~U();
}
template <typename U>
static void copier_stub(variant& src, variant& dst)
{
if (dst)
{
dst.deleter_(dst.store_);
}
// else do nothing
new (dst.store_) U(*static_cast<U*>(static_cast<void*>(src.store_)));
}
template <typename U>
static void mover_stub(variant& src, variant& dst)
{
if (dst)
{
dst.deleter_(dst.store_);
}
// else do nothing
new (dst.store_) U(std::move(*static_cast<U*>(
static_cast<void*>(src.store_))));
}
int store_type_{ -1 };
typedef void (*deleter_type)(void*);
deleter_type deleter_;
typedef void (*mover_type)(variant&, variant&);
mover_type copier_;
mover_type mover_;
alignas(max_align) char store_[sizeof(max_type)];
};
#endif // VARIANT_HPP
<|endoftext|> |
<commit_before>// Unique ownership
#include <memory>
#include <utility>
struct foo {};
void func(std::unique_ptr<foo> obj)
{ }
int main()
{
std::unique_ptr<foo> obj = std::make_unique<foo>();
func(std::move(obj));
}
// Transfer unique ownership of a dynamically allocated object to
// another unit of code.
//
// On [13], we create a [`std::unique_ptr`](cpp/memory/unique_ptr)
// which has ownership of a dynamically allocated `foo` object
// (created with the [`std::make_unique`](cpp/memory/unique_ptr/make_unique)
// utility function). [!14] then demonstrates passing ownership of this
// object to the function `func`. After passing ownership, `main` no
// longer has access to the `foo` object. The call to
// [`std::move`](cpp/utility/move) is required to allow the
// `std::unique_ptr` to be moved into the function.
//
// In other cases, you may instead wish to
// [share ownership of an object](/common-tasks/shared-ownership.html).
<commit_msg>Clarify unique ownership description<commit_after>// Unique ownership
#include <memory>
#include <utility>
struct foo {};
void func(std::unique_ptr<foo> obj)
{ }
int main()
{
std::unique_ptr<foo> obj = std::make_unique<foo>();
func(std::move(obj));
}
// Transfer unique ownership of a dynamically allocated object to
// another unit of code.
//
// On [13], we create a [`std::unique_ptr`](cpp/memory/unique_ptr)
// which has ownership of a dynamically allocated `foo` object
// (created with the [`std::make_unique`](cpp/memory/unique_ptr/make_unique)
// utility function). [!14] then demonstrates passing ownership of this
// object to the function `func`. After passing ownership, `main` no
// longer has access to the `foo` object.
//
// As `std::unique_ptr` is non-copyable, it must be moved instead of
// being copied. The call to [`std::move`](cpp/utility/move) on [14]
// allows `obj` to be treated like a temporary object (the expression
// `std::move(obj)` is an rvalue) so that it can be moved into the
// function.
//
// In other cases, you may instead wish to
// [share ownership of an object](/common-tasks/shared-ownership.html).
<|endoftext|> |
<commit_before><commit_msg>fdo#46340: fix crash in SdrGrafObj::getInputStream:<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "translatormessage.h"
#include <qplatformdefs.h>
#ifndef QT_NO_TRANSLATION
#include <QDataStream>
#include <QDebug>
#include <stdlib.h>
QT_BEGIN_NAMESPACE
TranslatorMessage::TranslatorMessage()
: m_lineNumber(-1), m_type(Unfinished), m_utf8(false), m_nonUtf8(false), m_plural(false)
{
}
TranslatorMessage::TranslatorMessage(const QString &context,
const QString &sourceText, const QString &comment,
const QString &userData,
const QString &fileName, int lineNumber, const QStringList &translations,
Type type, bool plural)
: m_context(context), m_sourcetext(sourceText), m_comment(comment),
m_userData(userData),
m_translations(translations), m_fileName(fileName), m_lineNumber(lineNumber),
m_type(type), m_utf8(false), m_nonUtf8(false), m_plural(plural)
{
}
void TranslatorMessage::addReference(const QString &fileName, int lineNumber)
{
if (m_fileName.isEmpty()) {
m_fileName = fileName;
m_lineNumber = lineNumber;
} else {
m_extraRefs.append(Reference(fileName, lineNumber));
}
}
void TranslatorMessage::addReferenceUniq(const QString &fileName, int lineNumber)
{
if (m_fileName.isEmpty()) {
m_fileName = fileName;
m_lineNumber = lineNumber;
} else {
if (fileName == m_fileName && lineNumber == m_lineNumber)
return;
if (!m_extraRefs.isEmpty()) // Rather common case, so special-case it
foreach (const Reference &ref, m_extraRefs)
if (fileName == ref.fileName() && lineNumber == ref.lineNumber())
return;
m_extraRefs.append(Reference(fileName, lineNumber));
}
}
void TranslatorMessage::clearReferences()
{
m_fileName.clear();
m_lineNumber = -1;
m_extraRefs.clear();
}
void TranslatorMessage::setReferences(const TranslatorMessage::References &refs0)
{
if (!refs0.isEmpty()) {
References refs = refs0;
const Reference &ref = refs.takeFirst();
m_fileName = ref.fileName();
m_lineNumber = ref.lineNumber();
m_extraRefs = refs;
} else {
clearReferences();
}
}
TranslatorMessage::References TranslatorMessage::allReferences() const
{
References refs;
if (!m_fileName.isEmpty()) {
refs.append(Reference(m_fileName, m_lineNumber));
refs += m_extraRefs;
}
return refs;
}
static bool needs8BitHelper(const QString &ba)
{
for (int i = ba.size(); --i >= 0; )
if (ba.at(i).unicode() >= 0x80)
return true;
return false;
}
bool TranslatorMessage::needs8Bit() const
{
//dump();
return needs8BitHelper(m_sourcetext)
|| needs8BitHelper(m_comment)
|| needs8BitHelper(m_context);
}
bool TranslatorMessage::operator==(const TranslatorMessage& m) const
{
static QString msgIdPlural = QLatin1String("po-msgid_plural");
// Special treatment for context comments (empty source).
return (m_context == m.m_context)
&& m_sourcetext == m.m_sourcetext
&& m_extra[msgIdPlural] == m.m_extra[msgIdPlural]
&& m_id == m.m_id
&& (m_sourcetext.isEmpty() || m_comment == m.m_comment);
}
int qHash(const TranslatorMessage &msg)
{
return
qHash(msg.context()) ^
qHash(msg.sourceText()) ^
qHash(msg.extra(QLatin1String("po-msgid_plural"))) ^
qHash(msg.comment()) ^
qHash(msg.id());
}
bool TranslatorMessage::hasExtra(const QString &key) const
{
return m_extra.contains(key);
}
QString TranslatorMessage::extra(const QString &key) const
{
return m_extra[key];
}
void TranslatorMessage::setExtra(const QString &key, const QString &value)
{
m_extra[key] = value;
}
void TranslatorMessage::unsetExtra(const QString &key)
{
m_extra.remove(key);
}
void TranslatorMessage::dump() const
{
qDebug()
<< "\nId : " << m_id
<< "\nContext : " << m_context
<< "\nSource : " << m_sourcetext
<< "\nComment : " << m_comment
<< "\nUserData : " << m_userData
<< "\nExtraComment : " << m_extraComment
<< "\nTranslatorComment : " << m_translatorComment
<< "\nTranslations : " << m_translations
<< "\nFileName : " << m_fileName
<< "\nLineNumber : " << m_lineNumber
<< "\nType : " << m_type
<< "\nPlural : " << m_plural
<< "\nExtra : " << m_extra;
}
QT_END_NAMESPACE
#endif // QT_NO_TRANSLATION
<commit_msg>do not consider plural source in comparisons<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Linguist of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "translatormessage.h"
#include <qplatformdefs.h>
#ifndef QT_NO_TRANSLATION
#include <QDataStream>
#include <QDebug>
#include <stdlib.h>
QT_BEGIN_NAMESPACE
TranslatorMessage::TranslatorMessage()
: m_lineNumber(-1), m_type(Unfinished), m_utf8(false), m_nonUtf8(false), m_plural(false)
{
}
TranslatorMessage::TranslatorMessage(const QString &context,
const QString &sourceText, const QString &comment,
const QString &userData,
const QString &fileName, int lineNumber, const QStringList &translations,
Type type, bool plural)
: m_context(context), m_sourcetext(sourceText), m_comment(comment),
m_userData(userData),
m_translations(translations), m_fileName(fileName), m_lineNumber(lineNumber),
m_type(type), m_utf8(false), m_nonUtf8(false), m_plural(plural)
{
}
void TranslatorMessage::addReference(const QString &fileName, int lineNumber)
{
if (m_fileName.isEmpty()) {
m_fileName = fileName;
m_lineNumber = lineNumber;
} else {
m_extraRefs.append(Reference(fileName, lineNumber));
}
}
void TranslatorMessage::addReferenceUniq(const QString &fileName, int lineNumber)
{
if (m_fileName.isEmpty()) {
m_fileName = fileName;
m_lineNumber = lineNumber;
} else {
if (fileName == m_fileName && lineNumber == m_lineNumber)
return;
if (!m_extraRefs.isEmpty()) // Rather common case, so special-case it
foreach (const Reference &ref, m_extraRefs)
if (fileName == ref.fileName() && lineNumber == ref.lineNumber())
return;
m_extraRefs.append(Reference(fileName, lineNumber));
}
}
void TranslatorMessage::clearReferences()
{
m_fileName.clear();
m_lineNumber = -1;
m_extraRefs.clear();
}
void TranslatorMessage::setReferences(const TranslatorMessage::References &refs0)
{
if (!refs0.isEmpty()) {
References refs = refs0;
const Reference &ref = refs.takeFirst();
m_fileName = ref.fileName();
m_lineNumber = ref.lineNumber();
m_extraRefs = refs;
} else {
clearReferences();
}
}
TranslatorMessage::References TranslatorMessage::allReferences() const
{
References refs;
if (!m_fileName.isEmpty()) {
refs.append(Reference(m_fileName, m_lineNumber));
refs += m_extraRefs;
}
return refs;
}
static bool needs8BitHelper(const QString &ba)
{
for (int i = ba.size(); --i >= 0; )
if (ba.at(i).unicode() >= 0x80)
return true;
return false;
}
bool TranslatorMessage::needs8Bit() const
{
//dump();
return needs8BitHelper(m_sourcetext)
|| needs8BitHelper(m_comment)
|| needs8BitHelper(m_context);
}
bool TranslatorMessage::operator==(const TranslatorMessage& m) const
{
// Special treatment for context comments (empty source).
return (m_context == m.m_context)
&& m_sourcetext == m.m_sourcetext
&& m_id == m.m_id
&& (m_sourcetext.isEmpty() || m_comment == m.m_comment);
}
int qHash(const TranslatorMessage &msg)
{
return
qHash(msg.context()) ^
qHash(msg.sourceText()) ^
qHash(msg.comment()) ^
qHash(msg.id());
}
bool TranslatorMessage::hasExtra(const QString &key) const
{
return m_extra.contains(key);
}
QString TranslatorMessage::extra(const QString &key) const
{
return m_extra[key];
}
void TranslatorMessage::setExtra(const QString &key, const QString &value)
{
m_extra[key] = value;
}
void TranslatorMessage::unsetExtra(const QString &key)
{
m_extra.remove(key);
}
void TranslatorMessage::dump() const
{
qDebug()
<< "\nId : " << m_id
<< "\nContext : " << m_context
<< "\nSource : " << m_sourcetext
<< "\nComment : " << m_comment
<< "\nUserData : " << m_userData
<< "\nExtraComment : " << m_extraComment
<< "\nTranslatorComment : " << m_translatorComment
<< "\nTranslations : " << m_translations
<< "\nFileName : " << m_fileName
<< "\nLineNumber : " << m_lineNumber
<< "\nType : " << m_type
<< "\nPlural : " << m_plural
<< "\nExtra : " << m_extra;
}
QT_END_NAMESPACE
#endif // QT_NO_TRANSLATION
<|endoftext|> |
<commit_before>//===-- BenchmarkResult.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "BenchmarkResult.h"
#include "BenchmarkRunner.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/bit.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ObjectYAML/YAML.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
static constexpr const char kIntegerPrefix[] = "i_0x";
static constexpr const char kDoublePrefix[] = "f_";
static constexpr const char kInvalidOperand[] = "INVALID";
namespace llvm {
namespace {
// A mutable struct holding an LLVMState that can be passed through the
// serialization process to encode/decode registers and instructions.
struct YamlContext {
YamlContext(const exegesis::LLVMState &State)
: State(&State), ErrorStream(LastError) {}
void serializeMCInst(const llvm::MCInst &MCInst, llvm::raw_ostream &OS) {
OS << getInstrName(MCInst.getOpcode());
for (const auto &Op : MCInst) {
OS << ' ';
serializeMCOperand(Op, OS);
}
}
void deserializeMCInst(llvm::StringRef String, llvm::MCInst &Value) {
llvm::SmallVector<llvm::StringRef, 16> Pieces;
String.split(Pieces, " ", /* MaxSplit */ -1, /* KeepEmpty */ false);
if (Pieces.empty()) {
ErrorStream << "Unknown Instruction: '" << String << "'";
return;
}
bool ProcessOpcode = true;
for (llvm::StringRef Piece : Pieces) {
if (ProcessOpcode)
Value.setOpcode(getInstrOpcode(Piece));
else
Value.addOperand(deserializeMCOperand(Piece));
ProcessOpcode = false;
}
}
std::string &getLastError() { return ErrorStream.str(); }
llvm::raw_string_ostream &getErrorStream() { return ErrorStream; }
llvm::StringRef getRegName(unsigned RegNo) {
const llvm::StringRef RegName = State->getRegInfo().getName(RegNo);
if (RegName.empty())
ErrorStream << "No register with enum value" << RegNo;
return RegName;
}
unsigned getRegNo(llvm::StringRef RegName) {
const llvm::MCRegisterInfo &RegInfo = State->getRegInfo();
for (unsigned E = RegInfo.getNumRegs(), I = 0; I < E; ++I)
if (RegInfo.getName(I) == RegName)
return I;
ErrorStream << "No register with name " << RegName;
return 0;
}
private:
void serializeIntegerOperand(llvm::raw_ostream &OS, int64_t Value) {
OS << kIntegerPrefix;
OS.write_hex(llvm::bit_cast<uint64_t>(Value));
}
bool tryDeserializeIntegerOperand(llvm::StringRef String, int64_t &Value) {
if (!String.consume_front(kIntegerPrefix))
return false;
return !String.consumeInteger(16, Value);
}
void serializeFPOperand(llvm::raw_ostream &OS, double Value) {
OS << kDoublePrefix << llvm::format("%la", Value);
}
bool tryDeserializeFPOperand(llvm::StringRef String, double &Value) {
if (!String.consume_front(kDoublePrefix))
return false;
char *EndPointer = nullptr;
Value = strtod(String.begin(), &EndPointer);
return EndPointer == String.end();
}
void serializeMCOperand(const llvm::MCOperand &MCOperand,
llvm::raw_ostream &OS) {
if (MCOperand.isReg()) {
OS << getRegName(MCOperand.getReg());
} else if (MCOperand.isImm()) {
serializeIntegerOperand(OS, MCOperand.getImm());
} else if (MCOperand.isFPImm()) {
serializeFPOperand(OS, MCOperand.getFPImm());
} else {
OS << kInvalidOperand;
}
}
llvm::MCOperand deserializeMCOperand(llvm::StringRef String) {
assert(!String.empty());
int64_t IntValue = 0;
double DoubleValue = 0;
if (tryDeserializeIntegerOperand(String, IntValue))
return llvm::MCOperand::createImm(IntValue);
if (tryDeserializeFPOperand(String, DoubleValue))
return llvm::MCOperand::createFPImm(DoubleValue);
if (unsigned RegNo = getRegNo(String))
return llvm::MCOperand::createReg(RegNo);
if (String != kInvalidOperand)
ErrorStream << "Unknown Operand: '" << String << "'";
return {};
}
llvm::StringRef getInstrName(unsigned InstrNo) {
const llvm::StringRef InstrName = State->getInstrInfo().getName(InstrNo);
if (InstrName.empty())
ErrorStream << "No opcode with enum value" << InstrNo;
return InstrName;
}
unsigned getInstrOpcode(llvm::StringRef InstrName) {
const llvm::MCInstrInfo &InstrInfo = State->getInstrInfo();
for (unsigned E = InstrInfo.getNumOpcodes(), I = 0; I < E; ++I)
if (InstrInfo.getName(I) == InstrName)
return I;
ErrorStream << "No opcode with name " << InstrName;
return 0;
}
const llvm::exegesis::LLVMState *State;
std::string LastError;
llvm::raw_string_ostream ErrorStream;
};
} // namespace
// Defining YAML traits for IO.
namespace yaml {
static YamlContext &getTypedContext(void *Ctx) {
return *reinterpret_cast<YamlContext *>(Ctx);
}
// std::vector<llvm::MCInst> will be rendered as a list.
template <> struct SequenceElementTraits<llvm::MCInst> {
static const bool flow = false;
};
template <> struct ScalarTraits<llvm::MCInst> {
static void output(const llvm::MCInst &Value, void *Ctx,
llvm::raw_ostream &Out) {
getTypedContext(Ctx).serializeMCInst(Value, Out);
}
static StringRef input(StringRef Scalar, void *Ctx, llvm::MCInst &Value) {
YamlContext &Context = getTypedContext(Ctx);
Context.deserializeMCInst(Scalar, Value);
return Context.getLastError();
}
// By default strings are quoted only when necessary.
// We force the use of single quotes for uniformity.
static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
static const bool flow = true;
};
// std::vector<exegesis::Measure> will be rendered as a list.
template <> struct SequenceElementTraits<exegesis::BenchmarkMeasure> {
static const bool flow = false;
};
// exegesis::Measure is rendererd as a flow instead of a list.
// e.g. { "key": "the key", "value": 0123 }
template <> struct MappingTraits<exegesis::BenchmarkMeasure> {
static void mapping(IO &Io, exegesis::BenchmarkMeasure &Obj) {
Io.mapRequired("key", Obj.Key);
if (!Io.outputting()) {
// For backward compatibility, interpret debug_string as a key.
Io.mapOptional("debug_string", Obj.Key);
}
Io.mapRequired("value", Obj.PerInstructionValue);
Io.mapOptional("per_snippet_value", Obj.PerSnippetValue);
}
static const bool flow = true;
};
template <>
struct ScalarEnumerationTraits<exegesis::InstructionBenchmark::ModeE> {
static void enumeration(IO &Io,
exegesis::InstructionBenchmark::ModeE &Value) {
Io.enumCase(Value, "", exegesis::InstructionBenchmark::Unknown);
Io.enumCase(Value, "latency", exegesis::InstructionBenchmark::Latency);
Io.enumCase(Value, "uops", exegesis::InstructionBenchmark::Uops);
Io.enumCase(Value, "inverse_throughput",
exegesis::InstructionBenchmark::InverseThroughput);
}
};
// std::vector<exegesis::RegisterValue> will be rendered as a list.
template <> struct SequenceElementTraits<exegesis::RegisterValue> {
static const bool flow = false;
};
template <> struct ScalarTraits<exegesis::RegisterValue> {
static constexpr const unsigned kRadix = 16;
static constexpr const bool kSigned = false;
static void output(const exegesis::RegisterValue &RV, void *Ctx,
llvm::raw_ostream &Out) {
YamlContext &Context = getTypedContext(Ctx);
Out << Context.getRegName(RV.Register) << "=0x"
<< RV.Value.toString(kRadix, kSigned);
}
static StringRef input(StringRef String, void *Ctx,
exegesis::RegisterValue &RV) {
llvm::SmallVector<llvm::StringRef, 2> Pieces;
String.split(Pieces, "=0x", /* MaxSplit */ -1,
/* KeepEmpty */ false);
YamlContext &Context = getTypedContext(Ctx);
if (Pieces.size() == 2) {
RV.Register = Context.getRegNo(Pieces[0]);
const unsigned BitsNeeded = llvm::APInt::getBitsNeeded(Pieces[1], kRadix);
RV.Value = llvm::APInt(BitsNeeded, Pieces[1], kRadix);
} else {
Context.getErrorStream()
<< "Unknown initial register value: '" << String << "'";
}
return Context.getLastError();
}
static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
static const bool flow = true;
};
template <>
struct MappingContextTraits<exegesis::InstructionBenchmarkKey, YamlContext> {
static void mapping(IO &Io, exegesis::InstructionBenchmarkKey &Obj,
YamlContext &Context) {
Io.setContext(&Context);
Io.mapRequired("instructions", Obj.Instructions);
Io.mapOptional("config", Obj.Config);
Io.mapRequired("register_initial_values", Obj.RegisterInitialValues);
}
};
template <>
struct MappingContextTraits<exegesis::InstructionBenchmark, YamlContext> {
struct NormalizedBinary {
NormalizedBinary(IO &io) {}
NormalizedBinary(IO &, std::vector<uint8_t> &Data) : Binary(Data) {}
std::vector<uint8_t> denormalize(IO &) {
std::vector<uint8_t> Data;
std::string Str;
raw_string_ostream OSS(Str);
Binary.writeAsBinary(OSS);
OSS.flush();
Data.assign(Str.begin(), Str.end());
return Data;
}
BinaryRef Binary;
};
static void mapping(IO &Io, exegesis::InstructionBenchmark &Obj,
YamlContext &Context) {
Io.mapRequired("mode", Obj.Mode);
Io.mapRequired("key", Obj.Key, Context);
Io.mapRequired("cpu_name", Obj.CpuName);
Io.mapRequired("llvm_triple", Obj.LLVMTriple);
Io.mapRequired("num_repetitions", Obj.NumRepetitions);
Io.mapRequired("measurements", Obj.Measurements);
Io.mapRequired("error", Obj.Error);
Io.mapOptional("info", Obj.Info);
// AssembledSnippet
MappingNormalization<NormalizedBinary, std::vector<uint8_t>> BinaryString(
Io, Obj.AssembledSnippet);
Io.mapOptional("assembled_snippet", BinaryString->Binary);
}
};
} // namespace yaml
namespace exegesis {
llvm::Expected<InstructionBenchmark>
InstructionBenchmark::readYaml(const LLVMState &State,
llvm::StringRef Filename) {
if (auto ExpectedMemoryBuffer =
llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) {
llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get());
YamlContext Context(State);
InstructionBenchmark Benchmark;
if (Yin.setCurrentDocument())
llvm::yaml::yamlize(Yin, Benchmark, /*unused*/ true, Context);
if (!Context.getLastError().empty())
return llvm::make_error<BenchmarkFailure>(Context.getLastError());
return Benchmark;
} else {
return ExpectedMemoryBuffer.takeError();
}
}
llvm::Expected<std::vector<InstructionBenchmark>>
InstructionBenchmark::readYamls(const LLVMState &State,
llvm::StringRef Filename) {
if (auto ExpectedMemoryBuffer =
llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) {
llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get());
YamlContext Context(State);
std::vector<InstructionBenchmark> Benchmarks;
while (Yin.setCurrentDocument()) {
Benchmarks.emplace_back();
yamlize(Yin, Benchmarks.back(), /*unused*/ true, Context);
if (Yin.error())
return llvm::errorCodeToError(Yin.error());
if (!Context.getLastError().empty())
return llvm::make_error<BenchmarkFailure>(Context.getLastError());
Yin.nextDocument();
}
return Benchmarks;
} else {
return ExpectedMemoryBuffer.takeError();
}
}
void InstructionBenchmark::writeYamlTo(const LLVMState &State,
llvm::raw_ostream &OS) {
llvm::yaml::Output Yout(OS, nullptr /*Ctx*/, 200 /*WrapColumn*/);
YamlContext Context(State);
Yout.beginDocuments();
llvm::yaml::yamlize(Yout, *this, /*unused*/ true, Context);
Yout.endDocuments();
}
void InstructionBenchmark::readYamlFrom(const LLVMState &State,
llvm::StringRef InputContent) {
llvm::yaml::Input Yin(InputContent);
YamlContext Context(State);
if (Yin.setCurrentDocument())
llvm::yaml::yamlize(Yin, *this, /*unused*/ true, Context);
}
llvm::Error InstructionBenchmark::writeYaml(const LLVMState &State,
const llvm::StringRef Filename) {
if (Filename == "-") {
writeYamlTo(State, llvm::outs());
} else {
int ResultFD = 0;
if (auto E = llvm::errorCodeToError(
openFileForWrite(Filename, ResultFD, llvm::sys::fs::CD_CreateAlways,
llvm::sys::fs::F_Text))) {
return E;
}
llvm::raw_fd_ostream Ostr(ResultFD, true /*shouldClose*/);
writeYamlTo(State, Ostr);
}
return llvm::Error::success();
}
void PerInstructionStats::push(const BenchmarkMeasure &BM) {
if (Key.empty())
Key = BM.Key;
assert(Key == BM.Key);
++NumValues;
SumValues += BM.PerInstructionValue;
MaxValue = std::max(MaxValue, BM.PerInstructionValue);
MinValue = std::min(MinValue, BM.PerInstructionValue);
}
} // namespace exegesis
} // namespace llvm
<commit_msg>[llvm-exegesis] Cut run time of analysis mode by -84% (*sic*) (YamlContext::getInstrOpcode())<commit_after>//===-- BenchmarkResult.cpp -------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "BenchmarkResult.h"
#include "BenchmarkRunner.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/bit.h"
#include "llvm/ObjectYAML/YAML.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
static constexpr const char kIntegerPrefix[] = "i_0x";
static constexpr const char kDoublePrefix[] = "f_";
static constexpr const char kInvalidOperand[] = "INVALID";
namespace llvm {
namespace {
// A mutable struct holding an LLVMState that can be passed through the
// serialization process to encode/decode registers and instructions.
struct YamlContext {
YamlContext(const exegesis::LLVMState &State)
: State(&State), ErrorStream(LastError),
OpcodeNameToOpcodeIdx(
generateOpcodeNameToOpcodeIdxMapping(State.getInstrInfo())) {}
static llvm::StringMap<unsigned>
generateOpcodeNameToOpcodeIdxMapping(const llvm::MCInstrInfo &InstrInfo) {
llvm::StringMap<unsigned> Map(InstrInfo.getNumOpcodes());
for (unsigned I = 0, E = InstrInfo.getNumOpcodes(); I < E; ++I)
Map[InstrInfo.getName(I)] = I;
assert(Map.size() == InstrInfo.getNumOpcodes() && "Size prediction failed");
return Map;
};
void serializeMCInst(const llvm::MCInst &MCInst, llvm::raw_ostream &OS) {
OS << getInstrName(MCInst.getOpcode());
for (const auto &Op : MCInst) {
OS << ' ';
serializeMCOperand(Op, OS);
}
}
void deserializeMCInst(llvm::StringRef String, llvm::MCInst &Value) {
llvm::SmallVector<llvm::StringRef, 16> Pieces;
String.split(Pieces, " ", /* MaxSplit */ -1, /* KeepEmpty */ false);
if (Pieces.empty()) {
ErrorStream << "Unknown Instruction: '" << String << "'";
return;
}
bool ProcessOpcode = true;
for (llvm::StringRef Piece : Pieces) {
if (ProcessOpcode)
Value.setOpcode(getInstrOpcode(Piece));
else
Value.addOperand(deserializeMCOperand(Piece));
ProcessOpcode = false;
}
}
std::string &getLastError() { return ErrorStream.str(); }
llvm::raw_string_ostream &getErrorStream() { return ErrorStream; }
llvm::StringRef getRegName(unsigned RegNo) {
const llvm::StringRef RegName = State->getRegInfo().getName(RegNo);
if (RegName.empty())
ErrorStream << "No register with enum value" << RegNo;
return RegName;
}
unsigned getRegNo(llvm::StringRef RegName) {
const llvm::MCRegisterInfo &RegInfo = State->getRegInfo();
for (unsigned E = RegInfo.getNumRegs(), I = 0; I < E; ++I)
if (RegInfo.getName(I) == RegName)
return I;
ErrorStream << "No register with name " << RegName;
return 0;
}
private:
void serializeIntegerOperand(llvm::raw_ostream &OS, int64_t Value) {
OS << kIntegerPrefix;
OS.write_hex(llvm::bit_cast<uint64_t>(Value));
}
bool tryDeserializeIntegerOperand(llvm::StringRef String, int64_t &Value) {
if (!String.consume_front(kIntegerPrefix))
return false;
return !String.consumeInteger(16, Value);
}
void serializeFPOperand(llvm::raw_ostream &OS, double Value) {
OS << kDoublePrefix << llvm::format("%la", Value);
}
bool tryDeserializeFPOperand(llvm::StringRef String, double &Value) {
if (!String.consume_front(kDoublePrefix))
return false;
char *EndPointer = nullptr;
Value = strtod(String.begin(), &EndPointer);
return EndPointer == String.end();
}
void serializeMCOperand(const llvm::MCOperand &MCOperand,
llvm::raw_ostream &OS) {
if (MCOperand.isReg()) {
OS << getRegName(MCOperand.getReg());
} else if (MCOperand.isImm()) {
serializeIntegerOperand(OS, MCOperand.getImm());
} else if (MCOperand.isFPImm()) {
serializeFPOperand(OS, MCOperand.getFPImm());
} else {
OS << kInvalidOperand;
}
}
llvm::MCOperand deserializeMCOperand(llvm::StringRef String) {
assert(!String.empty());
int64_t IntValue = 0;
double DoubleValue = 0;
if (tryDeserializeIntegerOperand(String, IntValue))
return llvm::MCOperand::createImm(IntValue);
if (tryDeserializeFPOperand(String, DoubleValue))
return llvm::MCOperand::createFPImm(DoubleValue);
if (unsigned RegNo = getRegNo(String))
return llvm::MCOperand::createReg(RegNo);
if (String != kInvalidOperand)
ErrorStream << "Unknown Operand: '" << String << "'";
return {};
}
llvm::StringRef getInstrName(unsigned InstrNo) {
const llvm::StringRef InstrName = State->getInstrInfo().getName(InstrNo);
if (InstrName.empty())
ErrorStream << "No opcode with enum value" << InstrNo;
return InstrName;
}
unsigned getInstrOpcode(llvm::StringRef InstrName) {
auto Iter = OpcodeNameToOpcodeIdx.find(InstrName);
if (Iter != OpcodeNameToOpcodeIdx.end())
return Iter->second;
ErrorStream << "No opcode with name " << InstrName;
return 0;
}
const llvm::exegesis::LLVMState *State;
std::string LastError;
llvm::raw_string_ostream ErrorStream;
const llvm::StringMap<unsigned> OpcodeNameToOpcodeIdx;
};
} // namespace
// Defining YAML traits for IO.
namespace yaml {
static YamlContext &getTypedContext(void *Ctx) {
return *reinterpret_cast<YamlContext *>(Ctx);
}
// std::vector<llvm::MCInst> will be rendered as a list.
template <> struct SequenceElementTraits<llvm::MCInst> {
static const bool flow = false;
};
template <> struct ScalarTraits<llvm::MCInst> {
static void output(const llvm::MCInst &Value, void *Ctx,
llvm::raw_ostream &Out) {
getTypedContext(Ctx).serializeMCInst(Value, Out);
}
static StringRef input(StringRef Scalar, void *Ctx, llvm::MCInst &Value) {
YamlContext &Context = getTypedContext(Ctx);
Context.deserializeMCInst(Scalar, Value);
return Context.getLastError();
}
// By default strings are quoted only when necessary.
// We force the use of single quotes for uniformity.
static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
static const bool flow = true;
};
// std::vector<exegesis::Measure> will be rendered as a list.
template <> struct SequenceElementTraits<exegesis::BenchmarkMeasure> {
static const bool flow = false;
};
// exegesis::Measure is rendererd as a flow instead of a list.
// e.g. { "key": "the key", "value": 0123 }
template <> struct MappingTraits<exegesis::BenchmarkMeasure> {
static void mapping(IO &Io, exegesis::BenchmarkMeasure &Obj) {
Io.mapRequired("key", Obj.Key);
if (!Io.outputting()) {
// For backward compatibility, interpret debug_string as a key.
Io.mapOptional("debug_string", Obj.Key);
}
Io.mapRequired("value", Obj.PerInstructionValue);
Io.mapOptional("per_snippet_value", Obj.PerSnippetValue);
}
static const bool flow = true;
};
template <>
struct ScalarEnumerationTraits<exegesis::InstructionBenchmark::ModeE> {
static void enumeration(IO &Io,
exegesis::InstructionBenchmark::ModeE &Value) {
Io.enumCase(Value, "", exegesis::InstructionBenchmark::Unknown);
Io.enumCase(Value, "latency", exegesis::InstructionBenchmark::Latency);
Io.enumCase(Value, "uops", exegesis::InstructionBenchmark::Uops);
Io.enumCase(Value, "inverse_throughput",
exegesis::InstructionBenchmark::InverseThroughput);
}
};
// std::vector<exegesis::RegisterValue> will be rendered as a list.
template <> struct SequenceElementTraits<exegesis::RegisterValue> {
static const bool flow = false;
};
template <> struct ScalarTraits<exegesis::RegisterValue> {
static constexpr const unsigned kRadix = 16;
static constexpr const bool kSigned = false;
static void output(const exegesis::RegisterValue &RV, void *Ctx,
llvm::raw_ostream &Out) {
YamlContext &Context = getTypedContext(Ctx);
Out << Context.getRegName(RV.Register) << "=0x"
<< RV.Value.toString(kRadix, kSigned);
}
static StringRef input(StringRef String, void *Ctx,
exegesis::RegisterValue &RV) {
llvm::SmallVector<llvm::StringRef, 2> Pieces;
String.split(Pieces, "=0x", /* MaxSplit */ -1,
/* KeepEmpty */ false);
YamlContext &Context = getTypedContext(Ctx);
if (Pieces.size() == 2) {
RV.Register = Context.getRegNo(Pieces[0]);
const unsigned BitsNeeded = llvm::APInt::getBitsNeeded(Pieces[1], kRadix);
RV.Value = llvm::APInt(BitsNeeded, Pieces[1], kRadix);
} else {
Context.getErrorStream()
<< "Unknown initial register value: '" << String << "'";
}
return Context.getLastError();
}
static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
static const bool flow = true;
};
template <>
struct MappingContextTraits<exegesis::InstructionBenchmarkKey, YamlContext> {
static void mapping(IO &Io, exegesis::InstructionBenchmarkKey &Obj,
YamlContext &Context) {
Io.setContext(&Context);
Io.mapRequired("instructions", Obj.Instructions);
Io.mapOptional("config", Obj.Config);
Io.mapRequired("register_initial_values", Obj.RegisterInitialValues);
}
};
template <>
struct MappingContextTraits<exegesis::InstructionBenchmark, YamlContext> {
struct NormalizedBinary {
NormalizedBinary(IO &io) {}
NormalizedBinary(IO &, std::vector<uint8_t> &Data) : Binary(Data) {}
std::vector<uint8_t> denormalize(IO &) {
std::vector<uint8_t> Data;
std::string Str;
raw_string_ostream OSS(Str);
Binary.writeAsBinary(OSS);
OSS.flush();
Data.assign(Str.begin(), Str.end());
return Data;
}
BinaryRef Binary;
};
static void mapping(IO &Io, exegesis::InstructionBenchmark &Obj,
YamlContext &Context) {
Io.mapRequired("mode", Obj.Mode);
Io.mapRequired("key", Obj.Key, Context);
Io.mapRequired("cpu_name", Obj.CpuName);
Io.mapRequired("llvm_triple", Obj.LLVMTriple);
Io.mapRequired("num_repetitions", Obj.NumRepetitions);
Io.mapRequired("measurements", Obj.Measurements);
Io.mapRequired("error", Obj.Error);
Io.mapOptional("info", Obj.Info);
// AssembledSnippet
MappingNormalization<NormalizedBinary, std::vector<uint8_t>> BinaryString(
Io, Obj.AssembledSnippet);
Io.mapOptional("assembled_snippet", BinaryString->Binary);
}
};
} // namespace yaml
namespace exegesis {
llvm::Expected<InstructionBenchmark>
InstructionBenchmark::readYaml(const LLVMState &State,
llvm::StringRef Filename) {
if (auto ExpectedMemoryBuffer =
llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) {
llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get());
YamlContext Context(State);
InstructionBenchmark Benchmark;
if (Yin.setCurrentDocument())
llvm::yaml::yamlize(Yin, Benchmark, /*unused*/ true, Context);
if (!Context.getLastError().empty())
return llvm::make_error<BenchmarkFailure>(Context.getLastError());
return Benchmark;
} else {
return ExpectedMemoryBuffer.takeError();
}
}
llvm::Expected<std::vector<InstructionBenchmark>>
InstructionBenchmark::readYamls(const LLVMState &State,
llvm::StringRef Filename) {
if (auto ExpectedMemoryBuffer =
llvm::errorOrToExpected(llvm::MemoryBuffer::getFile(Filename))) {
llvm::yaml::Input Yin(*ExpectedMemoryBuffer.get());
YamlContext Context(State);
std::vector<InstructionBenchmark> Benchmarks;
while (Yin.setCurrentDocument()) {
Benchmarks.emplace_back();
yamlize(Yin, Benchmarks.back(), /*unused*/ true, Context);
if (Yin.error())
return llvm::errorCodeToError(Yin.error());
if (!Context.getLastError().empty())
return llvm::make_error<BenchmarkFailure>(Context.getLastError());
Yin.nextDocument();
}
return Benchmarks;
} else {
return ExpectedMemoryBuffer.takeError();
}
}
void InstructionBenchmark::writeYamlTo(const LLVMState &State,
llvm::raw_ostream &OS) {
llvm::yaml::Output Yout(OS, nullptr /*Ctx*/, 200 /*WrapColumn*/);
YamlContext Context(State);
Yout.beginDocuments();
llvm::yaml::yamlize(Yout, *this, /*unused*/ true, Context);
Yout.endDocuments();
}
void InstructionBenchmark::readYamlFrom(const LLVMState &State,
llvm::StringRef InputContent) {
llvm::yaml::Input Yin(InputContent);
YamlContext Context(State);
if (Yin.setCurrentDocument())
llvm::yaml::yamlize(Yin, *this, /*unused*/ true, Context);
}
llvm::Error InstructionBenchmark::writeYaml(const LLVMState &State,
const llvm::StringRef Filename) {
if (Filename == "-") {
writeYamlTo(State, llvm::outs());
} else {
int ResultFD = 0;
if (auto E = llvm::errorCodeToError(
openFileForWrite(Filename, ResultFD, llvm::sys::fs::CD_CreateAlways,
llvm::sys::fs::F_Text))) {
return E;
}
llvm::raw_fd_ostream Ostr(ResultFD, true /*shouldClose*/);
writeYamlTo(State, Ostr);
}
return llvm::Error::success();
}
void PerInstructionStats::push(const BenchmarkMeasure &BM) {
if (Key.empty())
Key = BM.Key;
assert(Key == BM.Key);
++NumValues;
SumValues += BM.PerInstructionValue;
MaxValue = std::max(MaxValue, BM.PerInstructionValue);
MinValue = std::min(MinValue, BM.PerInstructionValue);
}
} // namespace exegesis
} // namespace llvm
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process.h"
#include <errno.h>
#include <sys/resource.h>
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/string_split.h"
#include "base/synchronization/lock.h"
namespace {
const int kForegroundPriority = 0;
#if defined(OS_CHROMEOS)
// We are more aggressive in our lowering of background process priority
// for chromeos as we have much more control over other processes running
// on the machine.
//
// TODO(davemoore) Refactor this by adding support for higher levels to set
// the foregrounding / backgrounding process so we don't have to keep
// chrome / chromeos specific logic here.
const int kBackgroundPriority = 19;
const char kControlPath[] = "/tmp/cgroup/cpu%s/cgroup.procs";
const char kForeground[] = "/chrome_renderers/foreground";
const char kBackground[] = "/chrome_renderers/background";
const char kProcPath[] = "/proc/%d/cgroup";
struct CGroups {
// Check for cgroups files. ChromeOS supports these by default. It creates
// a cgroup mount in /tmp/cgroup and then configures two cpu task groups,
// one contains at most a single foreground renderer and the other contains
// all background renderers. This allows us to limit the impact of background
// renderers on foreground ones to a greater level than simple renicing.
bool enabled;
FilePath foreground_file;
FilePath background_file;
CGroups() {
foreground_file = FilePath(StringPrintf(kControlPath, kForeground));
background_file = FilePath(StringPrintf(kControlPath, kBackground));
file_util::FileSystemType foreground_type;
file_util::FileSystemType background_type;
enabled =
file_util::GetFileSystemType(foreground_file, &foreground_type) &&
file_util::GetFileSystemType(background_file, &background_type) &&
foreground_type == file_util::FILE_SYSTEM_CGROUP &&
background_type == file_util::FILE_SYSTEM_CGROUP;
}
};
base::LazyInstance<CGroups> cgroups = LAZY_INSTANCE_INITIALIZER;
#else
const int kBackgroundPriority = 5;
#endif
}
namespace base {
bool Process::IsProcessBackgrounded() const {
DCHECK(process_);
#if defined(OS_CHROMEOS)
if (cgroups.Get().enabled) {
std::string proc;
if (file_util::ReadFileToString(
FilePath(StringPrintf(kProcPath, process_)),
&proc)) {
std::vector<std::string> proc_parts;
base::SplitString(proc, ':', &proc_parts);
DCHECK(proc_parts.size() == 3);
bool ret = proc_parts[2] == std::string(kBackground);
return ret;
} else {
return false;
}
}
#endif
return GetPriority() == kBackgroundPriority;
}
bool Process::SetProcessBackgrounded(bool background) {
DCHECK(process_);
#if defined(OS_CHROMEOS)
if (cgroups.Get().enabled) {
std::string pid = StringPrintf("%d", process_);
const FilePath file =
background ?
cgroups.Get().background_file : cgroups.Get().foreground_file;
return file_util::WriteFile(file, pid.c_str(), pid.size()) > 0;
}
#endif // OS_CHROMEOS
if (!CanBackgroundProcesses())
return false;
int priority = background ? kBackgroundPriority : kForegroundPriority;
int result = setpriority(PRIO_PROCESS, process_, priority);
DPCHECK(result == 0);
return result == 0;
}
struct CheckForNicePermission {
bool can_reraise_priority;
CheckForNicePermission() {
// We won't be able to raise the priority if we don't have the right rlimit.
// The limit may be adjusted in /etc/security/limits.conf for PAM systems.
struct rlimit rlim;
if ((getrlimit(RLIMIT_NICE, &rlim) == 0) &&
(20 - kForegroundPriority) <= static_cast<int>(rlim.rlim_cur)) {
can_reraise_priority = true;
}
};
};
// static
bool Process::CanBackgroundProcesses() {
#if defined(OS_CHROMEOS)
if (cgroups.Get().enabled)
return true;
#endif
static LazyInstance<CheckForNicePermission> check_for_nice_permission =
LAZY_INSTANCE_INITIALIZER;
return check_for_nice_permission.Get().can_reraise_priority;
}
} // namespace base
<commit_msg>CheckForNicePermission: Make sure can_reraise_priority is set in ctor<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process.h"
#include <errno.h>
#include <sys/resource.h>
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/string_split.h"
#include "base/synchronization/lock.h"
namespace {
const int kForegroundPriority = 0;
#if defined(OS_CHROMEOS)
// We are more aggressive in our lowering of background process priority
// for chromeos as we have much more control over other processes running
// on the machine.
//
// TODO(davemoore) Refactor this by adding support for higher levels to set
// the foregrounding / backgrounding process so we don't have to keep
// chrome / chromeos specific logic here.
const int kBackgroundPriority = 19;
const char kControlPath[] = "/tmp/cgroup/cpu%s/cgroup.procs";
const char kForeground[] = "/chrome_renderers/foreground";
const char kBackground[] = "/chrome_renderers/background";
const char kProcPath[] = "/proc/%d/cgroup";
struct CGroups {
// Check for cgroups files. ChromeOS supports these by default. It creates
// a cgroup mount in /tmp/cgroup and then configures two cpu task groups,
// one contains at most a single foreground renderer and the other contains
// all background renderers. This allows us to limit the impact of background
// renderers on foreground ones to a greater level than simple renicing.
bool enabled;
FilePath foreground_file;
FilePath background_file;
CGroups() {
foreground_file = FilePath(StringPrintf(kControlPath, kForeground));
background_file = FilePath(StringPrintf(kControlPath, kBackground));
file_util::FileSystemType foreground_type;
file_util::FileSystemType background_type;
enabled =
file_util::GetFileSystemType(foreground_file, &foreground_type) &&
file_util::GetFileSystemType(background_file, &background_type) &&
foreground_type == file_util::FILE_SYSTEM_CGROUP &&
background_type == file_util::FILE_SYSTEM_CGROUP;
}
};
base::LazyInstance<CGroups> cgroups = LAZY_INSTANCE_INITIALIZER;
#else
const int kBackgroundPriority = 5;
#endif
}
namespace base {
bool Process::IsProcessBackgrounded() const {
DCHECK(process_);
#if defined(OS_CHROMEOS)
if (cgroups.Get().enabled) {
std::string proc;
if (file_util::ReadFileToString(
FilePath(StringPrintf(kProcPath, process_)),
&proc)) {
std::vector<std::string> proc_parts;
base::SplitString(proc, ':', &proc_parts);
DCHECK(proc_parts.size() == 3);
bool ret = proc_parts[2] == std::string(kBackground);
return ret;
} else {
return false;
}
}
#endif
return GetPriority() == kBackgroundPriority;
}
bool Process::SetProcessBackgrounded(bool background) {
DCHECK(process_);
#if defined(OS_CHROMEOS)
if (cgroups.Get().enabled) {
std::string pid = StringPrintf("%d", process_);
const FilePath file =
background ?
cgroups.Get().background_file : cgroups.Get().foreground_file;
return file_util::WriteFile(file, pid.c_str(), pid.size()) > 0;
}
#endif // OS_CHROMEOS
if (!CanBackgroundProcesses())
return false;
int priority = background ? kBackgroundPriority : kForegroundPriority;
int result = setpriority(PRIO_PROCESS, process_, priority);
DPCHECK(result == 0);
return result == 0;
}
struct CheckForNicePermission {
CheckForNicePermission() : can_reraise_priority(false) {
// We won't be able to raise the priority if we don't have the right rlimit.
// The limit may be adjusted in /etc/security/limits.conf for PAM systems.
struct rlimit rlim;
if ((getrlimit(RLIMIT_NICE, &rlim) == 0) &&
(20 - kForegroundPriority) <= static_cast<int>(rlim.rlim_cur)) {
can_reraise_priority = true;
}
};
bool can_reraise_priority;
};
// static
bool Process::CanBackgroundProcesses() {
#if defined(OS_CHROMEOS)
if (cgroups.Get().enabled)
return true;
#endif
static LazyInstance<CheckForNicePermission> check_for_nice_permission =
LAZY_INSTANCE_INITIALIZER;
return check_for_nice_permission.Get().can_reraise_priority;
}
} // namespace base
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018 Egor Pugin
*
* 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.
*/
#ifdef HAVE_CURL
#include "tgbot/net/CurlHttpClient.h"
#include <boost/asio/ssl.hpp>
namespace TgBot {
CurlHttpClient::CurlHttpClient() : _httpParser() {
curlSettings = curl_easy_init();
}
CurlHttpClient::~CurlHttpClient() {
curl_easy_cleanup(curlSettings);
}
static size_t curlWriteString(char* ptr, size_t size, size_t nmemb, void* userdata) {
std::string &s = *(std::string *)userdata;
auto read = size * nmemb;
s.append(ptr, ptr + read);
return read;
};
std::string CurlHttpClient::makeRequest(const Url& url, const std::vector<HttpReqArg>& args) const {
// Copy settings for each call because we change CURLOPT_URL and other stuff.
// This also protects multithreaded case.
auto curl = curl_easy_duphandle(curlSettings);
std::string u = url.protocol + "://" + url.host + url.path;
curl_easy_setopt(curl, CURLOPT_URL, u.c_str());
// disable keep-alive
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Connection: close");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
std::string data;
std::vector<char*> escaped;
if (!args.empty()) {
for (const HttpReqArg& a : args) {
escaped.push_back(curl_easy_escape(curl, a.name.c_str(), a.name.size()));
data += escaped.back() + std::string("=");
escaped.push_back(curl_easy_escape(curl, a.value.c_str(), a.value.size()));
data += escaped.back() + std::string("&");
}
data.resize(data.size() - 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)data.size());
}
std::string response;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteString);
auto res = curl_easy_perform(curl);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
for (auto& e : escaped) {
curl_free(e);
}
if (res != CURLE_OK) {
throw std::runtime_error(std::string("curl error: ") + curl_easy_strerror(res));
}
return _httpParser.extractBody(response);
}
}
#endif
<commit_msg>Fix curl client issue https://github.com/reo7sp/tgbot-cpp/issues/84<commit_after>/*
* Copyright (c) 2018 Egor Pugin
*
* 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.
*/
#ifdef HAVE_CURL
#include "tgbot/net/CurlHttpClient.h"
#include <boost/asio/ssl.hpp>
namespace TgBot {
CurlHttpClient::CurlHttpClient() : _httpParser() {
curlSettings = curl_easy_init();
}
CurlHttpClient::~CurlHttpClient() {
curl_easy_cleanup(curlSettings);
}
static size_t curlWriteString(char* ptr, size_t size, size_t nmemb, void* userdata) {
static_cast<std::string *>(userdata)->append(ptr, size * nmemb);
return size * nmemb;
};
std::string CurlHttpClient::makeRequest(const Url& url, const std::vector<HttpReqArg>& args) const {
// Copy settings for each call because we change CURLOPT_URL and other stuff.
// This also protects multithreaded case.
auto curl = curl_easy_duphandle(curlSettings);
std::string u = url.protocol + "://" + url.host + url.path;
curl_easy_setopt(curl, CURLOPT_URL, u.c_str());
// disable keep-alive
struct curl_slist* headers = nullptr;
headers = curl_slist_append(headers, "Connection: close");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_mime *mime;
curl_mimepart *part;
mime = curl_mime_init(curl);
if (!args.empty()) {
for (const HttpReqArg& a : args) {
part = curl_mime_addpart(mime);
curl_mime_data(part, a.value.c_str(), a.value.size());
curl_mime_type(part, a.mimeType.c_str());
curl_mime_name(part, a.name.c_str());
if (a.isFile) {
curl_mime_filename(part, a.fileName.c_str());
}
}
curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);
}
std::string response;
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteString);
auto res = curl_easy_perform(curl);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
curl_mime_free(mime);
if (res != CURLE_OK) {
throw std::runtime_error(std::string("curl error: ") + curl_easy_strerror(res));
}
return _httpParser.extractBody(response);
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IDocumentStatistics.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2007-07-17 13:04:39 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef IDOCUMENTSTATISTICS_HXX_INCLUDED
#define IDOCUMENTSTATISTICS_HXX_INCLUDED
class SfxDocumentInfo;
struct SwDocStat;
/** Document statistics information
*/
class IDocumentStatistics
{
public:
/** Dokument info
@return the current document information
*/
virtual SfxDocumentInfo* GetDocumentInfo() = 0;
/** Return a pointer to the document info.
May also return NULL!
*/
virtual const SfxDocumentInfo* GetpInfo() const = 0;
/** setze ueber die DocShell in den entsp. Storage-Stream. Hier wird
jetzt die DocInfo verwaltet. Fuer die Felder ist am Doc eine Kopie
der Info, um einen schnellen Zugriff zu ermoeglichen.
(impl. in docsh2.cxx)
*/
virtual void SetDocumentInfo(const SfxDocumentInfo& rInfo) = 0;
/** die DocInfo hat siche geaendert (Notify ueber die DocShell)
stosse die entsp. Felder zum Updaten an.
*/
virtual void DocInfoChgd(const SfxDocumentInfo& rInfo) = 0;
/** Dokument - Statistics
*/
virtual const SwDocStat &GetDocStat() const = 0;
/**
*/
virtual void SetDocStat(const SwDocStat& rStat) = 0;
/**
*/
virtual void UpdateDocStat(SwDocStat& rStat) = 0;
protected:
virtual ~IDocumentStatistics() {};
};
#endif // IDOCUMENTSTATISTICS_HXX_INCLUDED
<commit_msg>INTEGRATION: CWS custommeta (1.4.170); FILE MERGED 2008/01/17 15:36:36 mst 1.4.170.1: interface change: IDocumentStatistics, SwDoc - sw/inc/IDocumentStatistics.hxx: + remove methods GetDocumentInfo, GetpInfo, SetDocumentInfo + method DocInfoChgd no longer takes a parameter - sw/inc/doc.hxx: + remove MAINTAINABILITY-HORROR: SwDoc no longer has a SfxDocumentInfo member<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: IDocumentStatistics.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2008-02-26 13:57:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef IDOCUMENTSTATISTICS_HXX_INCLUDED
#define IDOCUMENTSTATISTICS_HXX_INCLUDED
struct SwDocStat;
/** Document statistics information
*/
class IDocumentStatistics
{
public:
/** die DocInfo hat siche geaendert (Notify ueber die DocShell)
stosse die entsp. Felder zum Updaten an.
*/
virtual void DocInfoChgd() = 0;
/** Dokument - Statistics
*/
virtual const SwDocStat &GetDocStat() const = 0;
/**
*/
virtual void SetDocStat(const SwDocStat& rStat) = 0;
/**
*/
virtual void UpdateDocStat(SwDocStat& rStat) = 0;
protected:
virtual ~IDocumentStatistics() {};
};
#endif // IDOCUMENTSTATISTICS_HXX_INCLUDED
<|endoftext|> |
<commit_before>// Copyright (c) 2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "consensus/validation.h"
#include "data/sighash.json.h"
#include "main.h"
#include "random.h"
#include "script/interpreter.h"
#include "script/script.h"
#include "serialize.h"
#include "test/test_bitcoin.h"
#include "util.h"
#include "version.h"
#include <iostream>
#include <boost/test/unit_test.hpp>
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_utils.h"
#include "json/json_spirit_writer_template.h"
using namespace json_spirit;
extern Array read_json(const std::string& jsondata);
// Old script.cpp SignatureHash function
uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
if (nIn >= txTo.vin.size())
{
printf("ERROR: SignatureHash(): nIn=%d out of range\n", nIn);
return one;
}
CMutableTransaction txTmp(txTo);
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible incompatibilities.
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
// Blank out some of the outputs
if ((nHashType & 0x1f) == SIGHASH_NONE)
{
// Wildcard payee
txTmp.vout.clear();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
// Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
printf("ERROR: SignatureHash(): nOut=%d out of range\n", nOut);
return one;
}
txTmp.vout.resize(nOut+1);
for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
// Blank out other inputs completely, not recommended for open transactions
if (nHashType & SIGHASH_ANYONECANPAY)
{
txTmp.vin[0] = txTmp.vin[nIn];
txTmp.vin.resize(1);
}
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
void static RandomScript(CScript &script) {
static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
script = CScript();
int ops = (insecure_rand() % 10);
for (int i=0; i<ops; i++)
script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))];
}
void static RandomTransaction(CMutableTransaction &tx, bool fSingle) {
tx.nVersion = insecure_rand();
tx.vin.clear();
tx.vout.clear();
tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;
int ins = (insecure_rand() % 4) + 1;
int outs = fSingle ? ins : (insecure_rand() % 4) + 1;
int pours = (insecure_rand() % 4);
for (int in = 0; in < ins; in++) {
tx.vin.push_back(CTxIn());
CTxIn &txin = tx.vin.back();
txin.prevout.hash = GetRandHash();
txin.prevout.n = insecure_rand() % 4;
RandomScript(txin.scriptSig);
txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;
}
for (int out = 0; out < outs; out++) {
tx.vout.push_back(CTxOut());
CTxOut &txout = tx.vout.back();
txout.nValue = insecure_rand() % 100000000;
RandomScript(txout.scriptPubKey);
}
if (tx.nVersion >= 2) {
for (int pour = 0; pour < pours; pour++) {
CPourTx pourtx;
if (insecure_rand() % 2 == 0) {
pourtx.vpub_old = insecure_rand() % 100000000;
} else {
pourtx.vpub_new = insecure_rand() % 100000000;
}
pourtx.anchor = GetRandHash();
pourtx.serials[0] = GetRandHash();
pourtx.serials[1] = GetRandHash();
pourtx.ephemeralKey = GetRandHash();
pourtx.randomSeed = GetRandHash();
pourtx.ciphertexts[0] = {insecure_rand() % 100, insecure_rand() % 100};
pourtx.ciphertexts[1] = {insecure_rand() % 100, insecure_rand() % 100};
pourtx.macs[0] = GetRandHash();
pourtx.macs[1] = GetRandHash();
{
std::vector<unsigned char> txt;
int prooflen = insecure_rand() % 1000;
for (int i = 0; i < prooflen; i++) {
txt.push_back(insecure_rand() % 256);
}
pourtx.proof = std::string(txt.begin(), txt.end());
}
tx.vpour.push_back(pourtx);
}
}
}
BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(sighash_test)
{
seed_insecure_rand(false);
#if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n";
std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
#endif
int nRandomTests = 50000;
#if defined(PRINT_SIGHASH_JSON)
nRandomTests = 500;
#endif
for (int i=0; i<nRandomTests; i++) {
int nHashType = insecure_rand();
CMutableTransaction txTo;
RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
CScript scriptCode;
RandomScript(scriptCode);
int nIn = insecure_rand() % txTo.vin.size();
uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);
sh = SignatureHash(scriptCode, txTo, nIn, nHashType);
#if defined(PRINT_SIGHASH_JSON)
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << txTo;
std::cout << "\t[\"" ;
std::cout << HexStr(ss.begin(), ss.end()) << "\", \"";
std::cout << HexStr(scriptCode) << "\", ";
std::cout << nIn << ", ";
std::cout << nHashType << ", \"";
std::cout << sho.GetHex() << "\"]";
if (i+1 != nRandomTests) {
std::cout << ",";
}
std::cout << "\n";
#endif
BOOST_CHECK(sh == sho);
}
#if defined(PRINT_SIGHASH_JSON)
std::cout << "]\n";
#endif
}
// Goal: check that SignatureHash generates correct hash
BOOST_AUTO_TEST_CASE(sighash_from_data)
{
Array tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
if (test.size() == 1) continue; // comment
std::string raw_tx, raw_script, sigHashHex;
int nIn, nHashType;
uint256 sh;
CTransaction tx;
CScript scriptCode = CScript();
try {
// deserialize test data
raw_tx = test[0].get_str();
raw_script = test[1].get_str();
nIn = test[2].get_int();
nHashType = test[3].get_int();
sigHashHex = test[4].get_str();
uint256 sh;
CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);
stream >> tx;
CValidationState state;
state.SetPerformPourVerification(false); // don't verify the snark
BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
BOOST_CHECK(state.IsValid());
std::vector<unsigned char> raw = ParseHex(raw_script);
scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
} catch (...) {
BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
continue;
}
sh = SignatureHash(scriptCode, tx, nIn, nHashType);
BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix build warnings in sighash tests.<commit_after>// Copyright (c) 2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "consensus/validation.h"
#include "data/sighash.json.h"
#include "main.h"
#include "random.h"
#include "script/interpreter.h"
#include "script/script.h"
#include "serialize.h"
#include "test/test_bitcoin.h"
#include "util.h"
#include "version.h"
#include "sodium.h"
#include <iostream>
#include <boost/test/unit_test.hpp>
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_utils.h"
#include "json/json_spirit_writer_template.h"
using namespace json_spirit;
extern Array read_json(const std::string& jsondata);
// Old script.cpp SignatureHash function
uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
{
static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
if (nIn >= txTo.vin.size())
{
printf("ERROR: SignatureHash(): nIn=%d out of range\n", nIn);
return one;
}
CMutableTransaction txTmp(txTo);
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible incompatibilities.
scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
// Blank out other inputs' signatures
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
txTmp.vin[i].scriptSig = CScript();
txTmp.vin[nIn].scriptSig = scriptCode;
// Blank out some of the outputs
if ((nHashType & 0x1f) == SIGHASH_NONE)
{
// Wildcard payee
txTmp.vout.clear();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
{
// Only lock-in the txout payee at same index as txin
unsigned int nOut = nIn;
if (nOut >= txTmp.vout.size())
{
printf("ERROR: SignatureHash(): nOut=%d out of range\n", nOut);
return one;
}
txTmp.vout.resize(nOut+1);
for (unsigned int i = 0; i < nOut; i++)
txTmp.vout[i].SetNull();
// Let the others update at will
for (unsigned int i = 0; i < txTmp.vin.size(); i++)
if (i != nIn)
txTmp.vin[i].nSequence = 0;
}
// Blank out other inputs completely, not recommended for open transactions
if (nHashType & SIGHASH_ANYONECANPAY)
{
txTmp.vin[0] = txTmp.vin[nIn];
txTmp.vin.resize(1);
}
// Serialize and hash
CHashWriter ss(SER_GETHASH, 0);
ss << txTmp << nHashType;
return ss.GetHash();
}
void static RandomScript(CScript &script) {
static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
script = CScript();
int ops = (insecure_rand() % 10);
for (int i=0; i<ops; i++)
script << oplist[insecure_rand() % (sizeof(oplist)/sizeof(oplist[0]))];
}
void static RandomTransaction(CMutableTransaction &tx, bool fSingle) {
tx.nVersion = insecure_rand();
tx.vin.clear();
tx.vout.clear();
tx.nLockTime = (insecure_rand() % 2) ? insecure_rand() : 0;
int ins = (insecure_rand() % 4) + 1;
int outs = fSingle ? ins : (insecure_rand() % 4) + 1;
int pours = (insecure_rand() % 4);
for (int in = 0; in < ins; in++) {
tx.vin.push_back(CTxIn());
CTxIn &txin = tx.vin.back();
txin.prevout.hash = GetRandHash();
txin.prevout.n = insecure_rand() % 4;
RandomScript(txin.scriptSig);
txin.nSequence = (insecure_rand() % 2) ? insecure_rand() : (unsigned int)-1;
}
for (int out = 0; out < outs; out++) {
tx.vout.push_back(CTxOut());
CTxOut &txout = tx.vout.back();
txout.nValue = insecure_rand() % 100000000;
RandomScript(txout.scriptPubKey);
}
if (tx.nVersion >= 2) {
for (int pour = 0; pour < pours; pour++) {
CPourTx pourtx;
if (insecure_rand() % 2 == 0) {
pourtx.vpub_old = insecure_rand() % 100000000;
} else {
pourtx.vpub_new = insecure_rand() % 100000000;
}
pourtx.anchor = GetRandHash();
pourtx.serials[0] = GetRandHash();
pourtx.serials[1] = GetRandHash();
pourtx.ephemeralKey = GetRandHash();
pourtx.randomSeed = GetRandHash();
randombytes_buf(pourtx.ciphertexts[0].begin(), pourtx.ciphertexts[0].size());
randombytes_buf(pourtx.ciphertexts[1].begin(), pourtx.ciphertexts[1].size());
pourtx.macs[0] = GetRandHash();
pourtx.macs[1] = GetRandHash();
{
std::vector<unsigned char> txt;
int prooflen = insecure_rand() % 1000;
for (int i = 0; i < prooflen; i++) {
txt.push_back(insecure_rand() % 256);
}
pourtx.proof = std::string(txt.begin(), txt.end());
}
tx.vpour.push_back(pourtx);
}
}
}
BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(sighash_test)
{
seed_insecure_rand(false);
#if defined(PRINT_SIGHASH_JSON)
std::cout << "[\n";
std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
#endif
int nRandomTests = 50000;
#if defined(PRINT_SIGHASH_JSON)
nRandomTests = 500;
#endif
for (int i=0; i<nRandomTests; i++) {
int nHashType = insecure_rand();
CMutableTransaction txTo;
RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
CScript scriptCode;
RandomScript(scriptCode);
int nIn = insecure_rand() % txTo.vin.size();
uint256 sh, sho;
sho = SignatureHashOld(scriptCode, txTo, nIn, nHashType);
sh = SignatureHash(scriptCode, txTo, nIn, nHashType);
#if defined(PRINT_SIGHASH_JSON)
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << txTo;
std::cout << "\t[\"" ;
std::cout << HexStr(ss.begin(), ss.end()) << "\", \"";
std::cout << HexStr(scriptCode) << "\", ";
std::cout << nIn << ", ";
std::cout << nHashType << ", \"";
std::cout << sho.GetHex() << "\"]";
if (i+1 != nRandomTests) {
std::cout << ",";
}
std::cout << "\n";
#endif
BOOST_CHECK(sh == sho);
}
#if defined(PRINT_SIGHASH_JSON)
std::cout << "]\n";
#endif
}
// Goal: check that SignatureHash generates correct hash
BOOST_AUTO_TEST_CASE(sighash_from_data)
{
Array tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
BOOST_FOREACH(Value& tv, tests)
{
Array test = tv.get_array();
std::string strTest = write_string(tv, false);
if (test.size() < 1) // Allow for extra stuff (useful for comments)
{
BOOST_ERROR("Bad test: " << strTest);
continue;
}
if (test.size() == 1) continue; // comment
std::string raw_tx, raw_script, sigHashHex;
int nIn, nHashType;
uint256 sh;
CTransaction tx;
CScript scriptCode = CScript();
try {
// deserialize test data
raw_tx = test[0].get_str();
raw_script = test[1].get_str();
nIn = test[2].get_int();
nHashType = test[3].get_int();
sigHashHex = test[4].get_str();
uint256 sh;
CDataStream stream(ParseHex(raw_tx), SER_NETWORK, PROTOCOL_VERSION);
stream >> tx;
CValidationState state;
state.SetPerformPourVerification(false); // don't verify the snark
BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest);
BOOST_CHECK(state.IsValid());
std::vector<unsigned char> raw = ParseHex(raw_script);
scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
} catch (...) {
BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
continue;
}
sh = SignatureHash(scriptCode, tx, nIn, nHashType);
BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
Copyright (C) 2012 Lasath Fernando <[email protected]>
Copyright (C) 2012 David Edmundson <[email protected]>
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 "filters.h"
#include <QImageReader>
#include <KUrl>
#include <KProtocolInfo>
#include <KDebug>
UrlFilter::UrlFilter(QObject *parent)
: AbstractMessageFilter(parent)
{
}
void UrlFilter::filterMessage(Message &info) {
QString message = info.mainMessagePart();
//FIXME: make "Urls" into a constant
QVariantList urls = info.property("Urls").toList();
// link detection
QRegExp link(QLatin1String("\\b(?:(\\w+)://|(www\\.))([^\\s]+)"));
int fromIndex = 0;
while ((fromIndex = message.indexOf(link, fromIndex)) != -1) {
QString realUrl = link.cap(0);
QString protocol = link.cap(1);
//if cap(1) is empty cap(2) was matched -> starts with www.
const bool startsWithWWW = link.cap(1).isEmpty();
kDebug() << "Found URL " << realUrl << "with protocol : " << (startsWithWWW ? QLatin1String("http") : protocol);
// if url has a supported protocol
if (startsWithWWW || KProtocolInfo::protocols().contains(protocol, Qt::CaseInsensitive)) {
// text not wanted in a link ( <,> )
QRegExp unwanted(QLatin1String("(<|>)"));
if (!realUrl.contains(unwanted)) {
// string to show to user
QString shownUrl = realUrl;
// check for newline and cut link when found
if (realUrl.contains(QLatin1String(("<br/>")))) {
int findIndex = realUrl.indexOf(QLatin1String("<br/>"));
realUrl.truncate(findIndex);
shownUrl.truncate(findIndex);
}
// check prefix
if (startsWithWWW) {
realUrl.prepend(QLatin1String("http://"));
}
// if the url is changed, show in chat what the user typed in
QString link = QLatin1String("<a href='") + realUrl + QLatin1String("'>") + shownUrl + QLatin1String("</a>");
message.replace(fromIndex, shownUrl.length(), link);
// advance position otherwise I end up parsing the same link
fromIndex += link.length();
} else {
fromIndex += realUrl.length();
}
urls.append(KUrl(realUrl));
} else {
fromIndex += link.matchedLength();
}
}
info.setProperty("Urls", urls);
info.setMainMessagePart(message);
}
<commit_msg>Use KTp::TextUrlData to parse URL's instead of custom parsing<commit_after>/*
Copyright (C) 2012 Lasath Fernando <[email protected]>
Copyright (C) 2012 David Edmundson <[email protected]>
Copyright (C) 2012 Rohan Garg <[email protected]>
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 "filters.h"
#include <QImageReader>
#include <KUrl>
#include <KProtocolInfo>
#include <KDebug>
#include <KTp/text-parser.h>
UrlFilter::UrlFilter(QObject *parent)
: AbstractMessageFilter(parent)
{
}
void UrlFilter::filterMessage(Message &info) {
QString message = info.mainMessagePart();
//FIXME: make "Urls" into a constant
QVariantList urls = info.property("Urls").toList();
// link detection
KTp::TextUrlData parsedUrl = KTp::TextParser::instance()->extractUrlData(message);
int offset = 0;
for (int i = 0; i < parsedUrl.fixedUrls.size(); i++) {
QString originalText = message.mid(parsedUrl.urlRanges.at(i).first + offset, parsedUrl.urlRanges.at(i).second);
QString link = QString::fromLatin1("<a href='%1'>%2</a>").arg(parsedUrl.fixedUrls.at(i), originalText);
message.replace(parsedUrl.urlRanges.at(i).first + offset, parsedUrl.urlRanges.at(i).second, link);
urls.append(KUrl(parsedUrl.fixedUrls.at(i)));
//after the first replacement is made, the original position values are not valid anymore, this adjusts them
offset += link.length() - originalText.length();
}
info.setProperty("Urls", urls);
info.setMainMessagePart(message);
}
<|endoftext|> |
<commit_before><commit_msg>unnecessary cast<commit_after><|endoftext|> |
<commit_before><commit_msg>tdf#91917 tdf#91602: avoid layout recursion differently<commit_after><|endoftext|> |
<commit_before>/*
Print.cpp - Base class that provides print() and println()
Copyright (c) 2008 David A. Mellis. All right reserved.
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
Modified 23 November 2006 by David A. Mellis
Modified 03 August 2015 by Chuck Todd
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "Arduino.h"
#include "Print.h"
// Public Methods //////////////////////////////////////////////////////////////
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while (size--) {
if (write(*buffer++)) n++;
else break;
}
return n;
}
size_t Print::print(const __FlashStringHelper *ifsh)
{
return print(reinterpret_cast<const char *>(ifsh));
}
size_t Print::print(const String &s)
{
return write(s.c_str(), s.length());
}
size_t Print::print(const char str[])
{
return write(str);
}
size_t Print::print(char c)
{
return write(c);
}
size_t Print::print(unsigned char b, int base)
{
return print((unsigned long) b, base);
}
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
size_t Print::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t Print::print(long n, int base)
{
if (base == 0) {
return write(n);
} else if (base == 10) {
if (n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t Print::print(unsigned long n, int base)
{
if (base == 0) return write(n);
else return printNumber(n, base);
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t Print::println(const __FlashStringHelper *ifsh)
{
size_t n = print(ifsh);
n += println();
return n;
}
size_t Print::print(const Printable& x)
{
return x.printTo(*this);
}
size_t Print::println(void)
{
return write("\r\n");
}
size_t Print::println(const String &s)
{
size_t n = print(s);
n += println();
return n;
}
size_t Print::println(const char c[])
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t Print::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n;
}
size_t Print::println(const Printable& x)
{
size_t n = print(x);
n += println();
return n;
}
// Private Methods /////////////////////////////////////////////////////////////
size_t Print::printNumber(unsigned long n, uint8_t base)
{
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if (base < 2) base = 10;
do {
char c = n % base;
n /= base;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return write(str);
}
size_t Print::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if (isnan(number)) return print("nan");
if (isinf(number)) return print("inf");
if (number > 4294967040.0) return print ("ovf"); // constant determined empirically
if (number <-4294967040.0) return print ("ovf"); // constant determined empirically
// Handle negative numbers
if (number < 0.0)
{
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i=0; i<digits; ++i)
rounding /= 10.0;
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0) {
n += print(".");
}
// Extract digits from the remainder one at a time
while (digits-- > 0)
{
remainder *= 10.0;
unsigned int toPrint = (unsigned int)remainder;
n += print(toPrint);
remainder -= toPrint;
}
return n;
}
<commit_msg>Change quote style for single char in sam too<commit_after>/*
Print.cpp - Base class that provides print() and println()
Copyright (c) 2008 David A. Mellis. All right reserved.
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
Modified 23 November 2006 by David A. Mellis
Modified 03 August 2015 by Chuck Todd
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "Arduino.h"
#include "Print.h"
// Public Methods //////////////////////////////////////////////////////////////
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while (size--) {
if (write(*buffer++)) n++;
else break;
}
return n;
}
size_t Print::print(const __FlashStringHelper *ifsh)
{
return print(reinterpret_cast<const char *>(ifsh));
}
size_t Print::print(const String &s)
{
return write(s.c_str(), s.length());
}
size_t Print::print(const char str[])
{
return write(str);
}
size_t Print::print(char c)
{
return write(c);
}
size_t Print::print(unsigned char b, int base)
{
return print((unsigned long) b, base);
}
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
size_t Print::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t Print::print(long n, int base)
{
if (base == 0) {
return write(n);
} else if (base == 10) {
if (n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t Print::print(unsigned long n, int base)
{
if (base == 0) return write(n);
else return printNumber(n, base);
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t Print::println(const __FlashStringHelper *ifsh)
{
size_t n = print(ifsh);
n += println();
return n;
}
size_t Print::print(const Printable& x)
{
return x.printTo(*this);
}
size_t Print::println(void)
{
return write("\r\n");
}
size_t Print::println(const String &s)
{
size_t n = print(s);
n += println();
return n;
}
size_t Print::println(const char c[])
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t Print::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n;
}
size_t Print::println(const Printable& x)
{
size_t n = print(x);
n += println();
return n;
}
// Private Methods /////////////////////////////////////////////////////////////
size_t Print::printNumber(unsigned long n, uint8_t base)
{
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if (base < 2) base = 10;
do {
char c = n % base;
n /= base;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while(n);
return write(str);
}
size_t Print::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if (isnan(number)) return print("nan");
if (isinf(number)) return print("inf");
if (number > 4294967040.0) return print ("ovf"); // constant determined empirically
if (number <-4294967040.0) return print ("ovf"); // constant determined empirically
// Handle negative numbers
if (number < 0.0)
{
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i=0; i<digits; ++i)
rounding /= 10.0;
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0) {
n += print('.');
}
// Extract digits from the remainder one at a time
while (digits-- > 0)
{
remainder *= 10.0;
unsigned int toPrint = (unsigned int)remainder;
n += print(toPrint);
remainder -= toPrint;
}
return n;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ftnboss.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:48:34 $
*
* 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 _FTNBOSS_HXX
#define _FTNBOSS_HXX
#include "layfrm.hxx"
class SwFtnBossFrm;
class SwFtnContFrm;
class SwFtnFrm;
class SwTxtFtn;
//Setzen des maximalen Fussnotenbereiches. Restaurieren des alten Wertes im DTor.
//Implementierung im ftnfrm.cxx
class SwSaveFtnHeight
{
SwFtnBossFrm *pBoss;
const SwTwips nOldHeight;
SwTwips nNewHeight;
public:
SwSaveFtnHeight( SwFtnBossFrm *pBs, const SwTwips nDeadLine );
~SwSaveFtnHeight();
};
#define NA_ONLY_ADJUST 0
#define NA_GROW_SHRINK 1
#define NA_GROW_ADJUST 2
#define NA_ADJUST_GROW 3
class SwFtnBossFrm: public SwLayoutFrm
{
//Fuer die privaten Fussnotenoperationen
friend class SwFrm;
friend class SwSaveFtnHeight;
friend class SwPageFrm; // fuer das Setzen der MaxFtnHeight
//Maximale Hoehe des Fussnotencontainers fuer diese Seite.
SwTwips nMaxFtnHeight;
SwFtnContFrm *MakeFtnCont();
SwFtnFrm *FindFirstFtn();
BYTE _NeighbourhoodAdjustment( const SwFrm* pFrm ) const;
protected:
void InsertFtn( SwFtnFrm * );
static void ResetFtn( const SwFtnFrm *pAssumed );
public:
inline SwFtnBossFrm( SwFrmFmt* pFmt) : SwLayoutFrm( pFmt ) {}
SwLayoutFrm *FindBodyCont();
inline const SwLayoutFrm *FindBodyCont() const;
inline void SetMaxFtnHeight( const SwTwips nNewMax ) { nMaxFtnHeight = nNewMax; }
//Fussnotenschnittstelle
void AppendFtn( SwCntntFrm *, SwTxtFtn * );
void RemoveFtn( const SwCntntFrm *, const SwTxtFtn *, BOOL bPrep = TRUE );
static SwFtnFrm *FindFtn( const SwCntntFrm *, const SwTxtFtn * );
SwFtnContFrm *FindFtnCont();
inline const SwFtnContFrm *FindFtnCont() const;
const SwFtnFrm *FindFirstFtn( SwCntntFrm* ) const;
SwFtnContFrm *FindNearestFtnCont( BOOL bDontLeave = FALSE );
void ChangeFtnRef( const SwCntntFrm *pOld, const SwTxtFtn *,
SwCntntFrm *pNew );
void RearrangeFtns( const SwTwips nDeadLine, const BOOL bLock = FALSE,
const SwTxtFtn *pAttr = 0 );
//SS damit der Textformatierer Temporaer die Fussnotenhoehe begrenzen
//kann. DeadLine in Dokumentkoordinaten.
void SetFtnDeadLine( const SwTwips nDeadLine );
SwTwips GetMaxFtnHeight() const { return nMaxFtnHeight; }
//Liefert den Wert, der noch uebrig ist, bis der Body seine minimale
//Hoehe erreicht hat.
SwTwips GetVarSpace() const;
//Layoutseitig benoetigte Methoden
/// OD 03.04.2003 #108446# - add parameters <_bCollectOnlyPreviousFtns> and
/// <_pRefFtnBossFrm> in order to control, if only footnotes, which are positioned
/// before the given reference footnote boss frame have to be collected.
/// Note: if parameter <_bCollectOnlyPreviousFtns> is true, then parameter
/// <_pRefFtnBossFrm> have to be referenced to an object.
static void _CollectFtns( const SwCntntFrm* _pRef,
SwFtnFrm* _pFtn,
SvPtrarr& _rFtnArr,
const sal_Bool _bCollectOnlyPreviousFtns = sal_False,
const SwFtnBossFrm* _pRefFtnBossFrm = NULL);
/// OD 03.04.2003 #108446# - add parameter <_bCollectOnlyPreviousFtns> in
/// order to control, if only footnotes, which are positioned before the
/// footnote boss frame <this> have to be collected.
void CollectFtns( const SwCntntFrm* _pRef,
SwFtnBossFrm* _pOld,
SvPtrarr& _rFtnArr,
const sal_Bool _bCollectOnlyPreviousFtns = sal_False );
void _MoveFtns( SvPtrarr &rFtnArr, BOOL bCalc = FALSE );
void MoveFtns( const SwCntntFrm *pSrc, SwCntntFrm *pDest,
SwTxtFtn *pAttr );
// Sollte AdjustNeighbourhood gerufen werden (oder Grow/Shrink)?
BYTE NeighbourhoodAdjustment( const SwFrm* pFrm ) const
{ return IsPageFrm() ? NA_ONLY_ADJUST : _NeighbourhoodAdjustment( pFrm ); }
};
inline const SwLayoutFrm *SwFtnBossFrm::FindBodyCont() const
{
return ((SwFtnBossFrm*)this)->FindBodyCont();
}
inline const SwFtnContFrm *SwFtnBossFrm::FindFtnCont() const
{
return ((SwFtnBossFrm*)this)->FindFtnCont();
}
#endif //_FTNBOSS_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.1202); FILE MERGED 2008/03/31 16:54:14 rt 1.4.1202.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ftnboss.hxx,v $
* $Revision: 1.5 $
*
* 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 _FTNBOSS_HXX
#define _FTNBOSS_HXX
#include "layfrm.hxx"
class SwFtnBossFrm;
class SwFtnContFrm;
class SwFtnFrm;
class SwTxtFtn;
//Setzen des maximalen Fussnotenbereiches. Restaurieren des alten Wertes im DTor.
//Implementierung im ftnfrm.cxx
class SwSaveFtnHeight
{
SwFtnBossFrm *pBoss;
const SwTwips nOldHeight;
SwTwips nNewHeight;
public:
SwSaveFtnHeight( SwFtnBossFrm *pBs, const SwTwips nDeadLine );
~SwSaveFtnHeight();
};
#define NA_ONLY_ADJUST 0
#define NA_GROW_SHRINK 1
#define NA_GROW_ADJUST 2
#define NA_ADJUST_GROW 3
class SwFtnBossFrm: public SwLayoutFrm
{
//Fuer die privaten Fussnotenoperationen
friend class SwFrm;
friend class SwSaveFtnHeight;
friend class SwPageFrm; // fuer das Setzen der MaxFtnHeight
//Maximale Hoehe des Fussnotencontainers fuer diese Seite.
SwTwips nMaxFtnHeight;
SwFtnContFrm *MakeFtnCont();
SwFtnFrm *FindFirstFtn();
BYTE _NeighbourhoodAdjustment( const SwFrm* pFrm ) const;
protected:
void InsertFtn( SwFtnFrm * );
static void ResetFtn( const SwFtnFrm *pAssumed );
public:
inline SwFtnBossFrm( SwFrmFmt* pFmt) : SwLayoutFrm( pFmt ) {}
SwLayoutFrm *FindBodyCont();
inline const SwLayoutFrm *FindBodyCont() const;
inline void SetMaxFtnHeight( const SwTwips nNewMax ) { nMaxFtnHeight = nNewMax; }
//Fussnotenschnittstelle
void AppendFtn( SwCntntFrm *, SwTxtFtn * );
void RemoveFtn( const SwCntntFrm *, const SwTxtFtn *, BOOL bPrep = TRUE );
static SwFtnFrm *FindFtn( const SwCntntFrm *, const SwTxtFtn * );
SwFtnContFrm *FindFtnCont();
inline const SwFtnContFrm *FindFtnCont() const;
const SwFtnFrm *FindFirstFtn( SwCntntFrm* ) const;
SwFtnContFrm *FindNearestFtnCont( BOOL bDontLeave = FALSE );
void ChangeFtnRef( const SwCntntFrm *pOld, const SwTxtFtn *,
SwCntntFrm *pNew );
void RearrangeFtns( const SwTwips nDeadLine, const BOOL bLock = FALSE,
const SwTxtFtn *pAttr = 0 );
//SS damit der Textformatierer Temporaer die Fussnotenhoehe begrenzen
//kann. DeadLine in Dokumentkoordinaten.
void SetFtnDeadLine( const SwTwips nDeadLine );
SwTwips GetMaxFtnHeight() const { return nMaxFtnHeight; }
//Liefert den Wert, der noch uebrig ist, bis der Body seine minimale
//Hoehe erreicht hat.
SwTwips GetVarSpace() const;
//Layoutseitig benoetigte Methoden
/// OD 03.04.2003 #108446# - add parameters <_bCollectOnlyPreviousFtns> and
/// <_pRefFtnBossFrm> in order to control, if only footnotes, which are positioned
/// before the given reference footnote boss frame have to be collected.
/// Note: if parameter <_bCollectOnlyPreviousFtns> is true, then parameter
/// <_pRefFtnBossFrm> have to be referenced to an object.
static void _CollectFtns( const SwCntntFrm* _pRef,
SwFtnFrm* _pFtn,
SvPtrarr& _rFtnArr,
const sal_Bool _bCollectOnlyPreviousFtns = sal_False,
const SwFtnBossFrm* _pRefFtnBossFrm = NULL);
/// OD 03.04.2003 #108446# - add parameter <_bCollectOnlyPreviousFtns> in
/// order to control, if only footnotes, which are positioned before the
/// footnote boss frame <this> have to be collected.
void CollectFtns( const SwCntntFrm* _pRef,
SwFtnBossFrm* _pOld,
SvPtrarr& _rFtnArr,
const sal_Bool _bCollectOnlyPreviousFtns = sal_False );
void _MoveFtns( SvPtrarr &rFtnArr, BOOL bCalc = FALSE );
void MoveFtns( const SwCntntFrm *pSrc, SwCntntFrm *pDest,
SwTxtFtn *pAttr );
// Sollte AdjustNeighbourhood gerufen werden (oder Grow/Shrink)?
BYTE NeighbourhoodAdjustment( const SwFrm* pFrm ) const
{ return IsPageFrm() ? NA_ONLY_ADJUST : _NeighbourhoodAdjustment( pFrm ); }
};
inline const SwLayoutFrm *SwFtnBossFrm::FindBodyCont() const
{
return ((SwFtnBossFrm*)this)->FindBodyCont();
}
inline const SwFtnContFrm *SwFtnBossFrm::FindFtnCont() const
{
return ((SwFtnBossFrm*)this)->FindFtnCont();
}
#endif //_FTNBOSS_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: frmdlg.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2004-06-17 16:05:06 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _UIPARAM_HXX
#include <uiparam.hxx>
#endif
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
//CHINA001 #ifndef _SVX_BORDER_HXX
//CHINA001 #include <svx/border.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SVX_BACKGRND_HXX //autogen
//CHINA001 #include <svx/backgrnd.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SVX_GRFPAGE_HXX //autogen
//CHINA001 #include <svx/grfpage.hxx>
//CHINA001 #endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _FRMDLG_HXX
#include <frmdlg.hxx>
#endif
#ifndef _FRMPAGE_HXX
#include <frmpage.hxx>
#endif
#ifndef _WRAP_HXX
#include <wrap.hxx>
#endif
#ifndef _COLUMN_HXX
#include <column.hxx>
#endif
#ifndef _MACASSGN_HXX
#include <macassgn.hxx>
#endif
#ifndef _FRMUI_HRC
#include <frmui.hrc>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#include <svx/svxids.hrc> //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#include <svx/svxdlg.hxx> //CHINA001
/*--------------------------------------------------------------------
Beschreibung: Der Traeger des Dialoges
--------------------------------------------------------------------*/
SwFrmDlg::SwFrmDlg( SfxViewFrame* pFrame,
Window* pParent,
const SfxItemSet& rCoreSet,
BOOL bNewFrm,
USHORT nResType,
BOOL bFmt,
UINT16 nDefPage,
const String* pStr) :
SfxTabDialog(pFrame, pParent, SW_RES(nResType), &rCoreSet, pStr != 0),
bNew(bNewFrm),
bFormat(bFmt),
rSet(rCoreSet),
nDlgType(nResType),
pWrtShell(((SwView*)pFrame->GetViewShell())->GetWrtShellPtr())
{
FreeResource();
USHORT nHtmlMode = ::GetHtmlMode(pWrtShell->GetView().GetDocShell());
bHTMLMode = nHtmlMode & HTMLMODE_ON;
// BspFont fuer beide Bsp-TabPages
//
if(pStr)
{
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_COLL_HEADER);
aTmp += *pStr;
aTmp += ')';
}
AddTabPage(TP_FRM_STD, SwFrmPage::Create, 0);
AddTabPage(TP_FRM_ADD, SwFrmAddPage::Create, 0);
AddTabPage(TP_FRM_WRAP, SwWrapTabPage::Create, 0);
AddTabPage(TP_FRM_URL, SwFrmURLPage::Create, 0);
if(nDlgType == DLG_FRM_GRF)
{
AddTabPage( TP_GRF_EXT, SwGrfExtPage::Create, 0 );
AddTabPage( RID_SVXPAGE_GRFCROP ); //CHINA001 AddTabPage( RID_SVXPAGE_GRFCROP, SvxGrfCropPage::Create, 0 );
}
if (nDlgType == DLG_FRM_STD)
{
AddTabPage(TP_COLUMN, SwColumnPage::Create, 0);
}
SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); //CHINA001
DBG_ASSERT(pFact, "Dialogdiet fail!"); //CHINA001
AddTabPage(TP_BACKGROUND, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 ); //CHINA001 AddTabPage(TP_BACKGROUND,SvxBackgroundTabPage::Create, 0);
AddTabPage( TP_MACRO_ASSIGN, SfxMacroTabPage::Create, 0);
AddTabPage( TP_BORDER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), 0 ); //CHINA001 AddTabPage( TP_BORDER, SvxBorderTabPage::Create, 0);
if(bHTMLMode)
{
switch( nDlgType )
{
case DLG_FRM_STD:
if(0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS))
RemoveTabPage(TP_BORDER);
RemoveTabPage(TP_COLUMN);
// kein break
case DLG_FRM_OLE:
RemoveTabPage(TP_FRM_URL);
RemoveTabPage(TP_MACRO_ASSIGN);
break;
case DLG_FRM_GRF:
RemoveTabPage(RID_SVXPAGE_GRFCROP);
break;
}
if( 0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS) ||
nDlgType != DLG_FRM_STD )
RemoveTabPage(TP_BACKGROUND);
}
if (bNew)
SetCurPageId(TP_FRM_STD);
if (nDefPage)
SetCurPageId(nDefPage);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwFrmDlg::~SwFrmDlg()
{
}
void SwFrmDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//CHINA001
switch ( nId )
{
case TP_FRM_STD:
((SwFrmPage&)rPage).SetNewFrame(bNew);
((SwFrmPage&)rPage).SetFormatUsed(bFormat);
((SwFrmPage&)rPage).SetFrmType(nDlgType);
break;
case TP_FRM_ADD:
((SwFrmAddPage&)rPage).SetFormatUsed(bFormat);
((SwFrmAddPage&)rPage).SetFrmType(nDlgType);
((SwFrmAddPage&)rPage).SetNewFrame(bNew);
((SwFrmAddPage&)rPage).SetShell(pWrtShell);
break;
case TP_FRM_WRAP:
((SwWrapTabPage&)rPage).SetNewFrame(bNew);
((SwWrapTabPage&)rPage).SetFormatUsed(bFormat, FALSE);
((SwWrapTabPage&)rPage).SetShell(pWrtShell);
break;
case TP_COLUMN:
{
((SwColumnPage&)rPage).SetFrmMode(TRUE);
((SwColumnPage&)rPage).SetFormatUsed(bFormat);
const SwFmtFrmSize& rSize = (const SwFmtFrmSize&)
rSet.Get( RES_FRM_SIZE );
((SwColumnPage&)rPage).SetPageWidth( rSize.GetWidth() );
}
break;
case TP_MACRO_ASSIGN:
SwMacroAssignDlg::AddEvents( (SfxMacroTabPage&)rPage,
DLG_FRM_GRF == nDlgType ? MACASSGN_GRAPHIC
: DLG_FRM_OLE == nDlgType ? MACASSGN_OLE
: MACASSGN_FRMURL );
break;
case TP_BACKGROUND:
if( DLG_FRM_STD == nDlgType )
{
sal_Int32 nFlagType = SVX_SHOW_SELECTOR;
if(!bHTMLMode)
nFlagType |= SVX_ENABLE_TRANSPARENCY;
aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, nFlagType));
rPage.PageCreated(aSet);
}
break;
case TP_BORDER:
//CHINA001 ((SvxBorderTabPage&) rPage).SetSWMode(SW_BORDER_MODE_FRAME);
{
aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,SW_BORDER_MODE_FRAME));
rPage.PageCreated(aSet);
}
break;
}
}
<commit_msg>INTEGRATION: CWS tune03 (1.8.14); FILE MERGED 2004/07/19 19:11:20 mhu 1.8.14.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
*
* $RCSfile: frmdlg.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2004-08-23 08:55:35 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _UIPARAM_HXX
#include <uiparam.hxx>
#endif
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX //autogen
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
//CHINA001 #ifndef _SVX_BORDER_HXX
//CHINA001 #include <svx/border.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SVX_BACKGRND_HXX //autogen
//CHINA001 #include <svx/backgrnd.hxx>
//CHINA001 #endif
//CHINA001 #ifndef _SVX_GRFPAGE_HXX //autogen
//CHINA001 #include <svx/grfpage.hxx>
//CHINA001 #endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _FRMDLG_HXX
#include <frmdlg.hxx>
#endif
#ifndef _FRMPAGE_HXX
#include <frmpage.hxx>
#endif
#ifndef _WRAP_HXX
#include <wrap.hxx>
#endif
#ifndef _COLUMN_HXX
#include <column.hxx>
#endif
#ifndef _MACASSGN_HXX
#include <macassgn.hxx>
#endif
#ifndef _FRMUI_HRC
#include <frmui.hrc>
#endif
#ifndef _GLOBALS_HRC
#include <globals.hrc>
#endif
#include <svx/svxids.hrc> //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#include <svx/svxdlg.hxx> //CHINA001
/*--------------------------------------------------------------------
Beschreibung: Der Traeger des Dialoges
--------------------------------------------------------------------*/
SwFrmDlg::SwFrmDlg( SfxViewFrame* pFrame,
Window* pParent,
const SfxItemSet& rCoreSet,
BOOL bNewFrm,
USHORT nResType,
BOOL bFmt,
UINT16 nDefPage,
const String* pStr) :
SfxTabDialog(pFrame, pParent, SW_RES(nResType), &rCoreSet, pStr != 0),
bNew(bNewFrm),
bFormat(bFmt),
rSet(rCoreSet),
nDlgType(nResType),
pWrtShell(((SwView*)pFrame->GetViewShell())->GetWrtShellPtr())
{
FreeResource();
USHORT nHtmlMode = ::GetHtmlMode(pWrtShell->GetView().GetDocShell());
bHTMLMode = nHtmlMode & HTMLMODE_ON;
// BspFont fuer beide Bsp-TabPages
//
if(pStr)
{
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_COLL_HEADER);
aTmp += *pStr;
aTmp += ')';
}
AddTabPage(TP_FRM_STD, SwFrmPage::Create, 0);
AddTabPage(TP_FRM_ADD, SwFrmAddPage::Create, 0);
AddTabPage(TP_FRM_WRAP, SwWrapTabPage::Create, 0);
AddTabPage(TP_FRM_URL, SwFrmURLPage::Create, 0);
if(nDlgType == DLG_FRM_GRF)
{
AddTabPage( TP_GRF_EXT, SwGrfExtPage::Create, 0 );
AddTabPage( RID_SVXPAGE_GRFCROP ); //CHINA001 AddTabPage( RID_SVXPAGE_GRFCROP, SvxGrfCropPage::Create, 0 );
}
if (nDlgType == DLG_FRM_STD)
{
AddTabPage(TP_COLUMN, SwColumnPage::Create, 0);
}
SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); //CHINA001
DBG_ASSERT(pFact, "Dialogdiet fail!"); //CHINA001
AddTabPage(TP_BACKGROUND, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BACKGROUND ), 0 ); //CHINA001 AddTabPage(TP_BACKGROUND,SvxBackgroundTabPage::Create, 0);
AddTabPage( TP_MACRO_ASSIGN, SfxMacroTabPage::Create, 0);
AddTabPage( TP_BORDER, pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ), 0 ); //CHINA001 AddTabPage( TP_BORDER, SvxBorderTabPage::Create, 0);
if(bHTMLMode)
{
switch( nDlgType )
{
case DLG_FRM_STD:
if(0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS))
RemoveTabPage(TP_BORDER);
RemoveTabPage(TP_COLUMN);
// kein break
case DLG_FRM_OLE:
RemoveTabPage(TP_FRM_URL);
RemoveTabPage(TP_MACRO_ASSIGN);
break;
case DLG_FRM_GRF:
RemoveTabPage(RID_SVXPAGE_GRFCROP);
break;
}
if( 0 == (nHtmlMode & HTMLMODE_SOME_ABS_POS) ||
nDlgType != DLG_FRM_STD )
RemoveTabPage(TP_BACKGROUND);
}
if (bNew)
SetCurPageId(TP_FRM_STD);
if (nDefPage)
SetCurPageId(nDefPage);
}
/*--------------------------------------------------------------------
Beschreibung:
--------------------------------------------------------------------*/
SwFrmDlg::~SwFrmDlg()
{
}
void SwFrmDlg::PageCreated( USHORT nId, SfxTabPage &rPage )
{
SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));//CHINA001
switch ( nId )
{
case TP_FRM_STD:
((SwFrmPage&)rPage).SetNewFrame(bNew);
((SwFrmPage&)rPage).SetFormatUsed(bFormat);
((SwFrmPage&)rPage).SetFrmType(nDlgType);
break;
case TP_FRM_ADD:
((SwFrmAddPage&)rPage).SetFormatUsed(bFormat);
((SwFrmAddPage&)rPage).SetFrmType(nDlgType);
((SwFrmAddPage&)rPage).SetNewFrame(bNew);
((SwFrmAddPage&)rPage).SetShell(pWrtShell);
break;
case TP_FRM_WRAP:
((SwWrapTabPage&)rPage).SetNewFrame(bNew);
((SwWrapTabPage&)rPage).SetFormatUsed(bFormat, FALSE);
((SwWrapTabPage&)rPage).SetShell(pWrtShell);
break;
case TP_COLUMN:
{
((SwColumnPage&)rPage).SetFrmMode(TRUE);
((SwColumnPage&)rPage).SetFormatUsed(bFormat);
const SwFmtFrmSize& rSize = (const SwFmtFrmSize&)
rSet.Get( RES_FRM_SIZE );
((SwColumnPage&)rPage).SetPageWidth( rSize.GetWidth() );
}
break;
case TP_MACRO_ASSIGN:
SwMacroAssignDlg::AddEvents( (SfxMacroTabPage&)rPage,
DLG_FRM_GRF == nDlgType ? MACASSGN_GRAPHIC
: DLG_FRM_OLE == nDlgType ? MACASSGN_OLE
: MACASSGN_FRMURL );
break;
case TP_BACKGROUND:
if( DLG_FRM_STD == nDlgType )
{
sal_Int32 nFlagType = SVX_SHOW_SELECTOR;
if(!bHTMLMode)
nFlagType |= SVX_ENABLE_TRANSPARENCY;
aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, nFlagType));
rPage.PageCreated(aSet);
}
break;
case TP_BORDER:
//CHINA001 ((SvxBorderTabPage&) rPage).SetSWMode(SW_BORDER_MODE_FRAME);
{
aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,SW_BORDER_MODE_FRAME));
rPage.PageCreated(aSet);
}
break;
}
}
<|endoftext|> |
<commit_before>/**
* @file thread/win32thread.cpp
* @brief Win32 thread/mutex handling
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*
* This file is also distributed under the terms of the GNU General
* Public License, see http://www.gnu.org/copyleft/gpl.txt for details.
*/
#include "mega/thread/win32thread.h"
#include "mega/logging.h"
namespace mega {
//Thread
Win32Thread::Win32Thread()
{
}
DWORD WINAPI Win32Thread::run(LPVOID lpParameter)
{
Win32Thread *object = (Win32Thread *)lpParameter;
return (DWORD)object->start_routine(object->pointer);
}
void Win32Thread::start(void *(*start_routine)(void*), void *parameter)
{
this->start_routine = start_routine;
this->pointer = parameter;
hThread = CreateThread(NULL, 0, Win32Thread::run, this, 0, NULL);
}
void Win32Thread::join()
{
WaitForSingleObject(hThread, INFINITE);
}
unsigned long long Win32Thread::currentThreadId()
{
return (unsigned long long) GetCurrentThreadId();
}
Win32Thread::~Win32Thread()
{
CloseHandle(hThread);
}
//Mutex
Win32Mutex::Win32Mutex()
{
InitializeCriticalSection(&mutex);
}
Win32Mutex::Win32Mutex(bool recursive)
{
InitializeCriticalSection(&mutex);
init(recursive); // just for correctness
}
void Win32Mutex::init(bool recursive)
{
}
void Win32Mutex::lock()
{
EnterCriticalSection(&mutex);
}
void Win32Mutex::unlock()
{
LeaveCriticalSection(&mutex);
}
Win32Mutex::~Win32Mutex()
{
DeleteCriticalSection(&mutex);
}
//Semaphore
Win32Semaphore::Win32Semaphore()
{
semaphore = CreateSemaphore(NULL, 0, INT_MAX, NULL);
if (semaphore == NULL)
{
LOG_fatal << "Error creating semaphore: " << GetLastError();
}
}
void Win32Semaphore::release()
{
if (!ReleaseSemaphore(semaphore, 1, NULL))
{
LOG_fatal << "Error in ReleaseSemaphore: " << GetLastError();
}
}
void Win32Semaphore::wait()
{
DWORD ret = WaitForSingleObject(semaphore, INFINITE);
if (ret == WAIT_OBJECT_0)
{
return;
}
LOG_fatal << "Error in WaitForSingleObject: " << GetLastError();
}
int Win32Semaphore::timedwait(int milliseconds)
{
DWORD ret = WaitForSingleObject(semaphore, milliseconds);
if (ret == WAIT_OBJECT_0)
{
return 0;
}
if (ret == WAIT_TIMEOUT)
{
return -1;
}
LOG_err << "Error in WaitForSingleObject: " << GetLastError();
return -2;
}
Win32Semaphore::~Win32Semaphore()
{
CloseHandle(semaphore);
}
} // namespace
<commit_msg>added missing include for MINGW<commit_after>/**
* @file thread/win32thread.cpp
* @brief Win32 thread/mutex handling
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*
* This file is also distributed under the terms of the GNU General
* Public License, see http://www.gnu.org/copyleft/gpl.txt for details.
*/
#include "mega/thread/win32thread.h"
#include "mega/logging.h"
#include <limits.h>
namespace mega {
//Thread
Win32Thread::Win32Thread()
{
}
DWORD WINAPI Win32Thread::run(LPVOID lpParameter)
{
Win32Thread *object = (Win32Thread *)lpParameter;
return (DWORD)object->start_routine(object->pointer);
}
void Win32Thread::start(void *(*start_routine)(void*), void *parameter)
{
this->start_routine = start_routine;
this->pointer = parameter;
hThread = CreateThread(NULL, 0, Win32Thread::run, this, 0, NULL);
}
void Win32Thread::join()
{
WaitForSingleObject(hThread, INFINITE);
}
unsigned long long Win32Thread::currentThreadId()
{
return (unsigned long long) GetCurrentThreadId();
}
Win32Thread::~Win32Thread()
{
CloseHandle(hThread);
}
//Mutex
Win32Mutex::Win32Mutex()
{
InitializeCriticalSection(&mutex);
}
Win32Mutex::Win32Mutex(bool recursive)
{
InitializeCriticalSection(&mutex);
init(recursive); // just for correctness
}
void Win32Mutex::init(bool recursive)
{
}
void Win32Mutex::lock()
{
EnterCriticalSection(&mutex);
}
void Win32Mutex::unlock()
{
LeaveCriticalSection(&mutex);
}
Win32Mutex::~Win32Mutex()
{
DeleteCriticalSection(&mutex);
}
//Semaphore
Win32Semaphore::Win32Semaphore()
{
semaphore = CreateSemaphore(NULL, 0, INT_MAX, NULL);
if (semaphore == NULL)
{
LOG_fatal << "Error creating semaphore: " << GetLastError();
}
}
void Win32Semaphore::release()
{
if (!ReleaseSemaphore(semaphore, 1, NULL))
{
LOG_fatal << "Error in ReleaseSemaphore: " << GetLastError();
}
}
void Win32Semaphore::wait()
{
DWORD ret = WaitForSingleObject(semaphore, INFINITE);
if (ret == WAIT_OBJECT_0)
{
return;
}
LOG_fatal << "Error in WaitForSingleObject: " << GetLastError();
}
int Win32Semaphore::timedwait(int milliseconds)
{
DWORD ret = WaitForSingleObject(semaphore, milliseconds);
if (ret == WAIT_OBJECT_0)
{
return 0;
}
if (ret == WAIT_TIMEOUT)
{
return -1;
}
LOG_err << "Error in WaitForSingleObject: " << GetLastError();
return -2;
}
Win32Semaphore::~Win32Semaphore()
{
CloseHandle(semaphore);
}
} // namespace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: impfnote.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:32:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _IMPFNOTE_HXX
#define _IMPFNOTE_HXX
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#ifndef _NUMBERINGTYPELISTBOX_HXX
#include <numberingtypelistbox.hxx>
#endif
class SwWrtShell;
class SwEndNoteOptionPage : public SfxTabPage
{
FixedText aNumTypeFT;
SwNumberingTypeListBox aNumViewBox;
FixedText aOffsetLbl;
NumericField aOffsetFld;
FixedText aNumCountFT;
ListBox aNumCountBox;
FixedText aPrefixFT;
Edit aPrefixED;
FixedText aSuffixFT;
Edit aSuffixED;
FixedText aPosFT;
RadioButton aPosPageBox;
RadioButton aPosChapterBox;
FixedLine aNumFL;
FixedText aParaTemplLbl;
ListBox aParaTemplBox;
FixedText aPageTemplLbl;
ListBox aPageTemplBox;
FixedLine aTemplFL;
FixedText aFtnCharAnchorTemplLbl;
ListBox aFtnCharAnchorTemplBox;
FixedText aFtnCharTextTemplLbl;
ListBox aFtnCharTextTemplBox;
FixedLine aCharTemplFL;
FixedText aContLbl;
Edit aContEdit;
FixedText aContFromLbl;
Edit aContFromEdit;
FixedLine aContFL;
String aNumDoc;
String aNumPage;
String aNumChapter;
SwWrtShell *pSh;
BOOL bPosDoc;
BOOL bEndNote;
inline void SelectNumbering(int eNum);
int GetNumbering() const;
DECL_LINK( PosPageHdl, Button * );
DECL_LINK( PosChapterHdl, Button * );
DECL_LINK( NumCountHdl, ListBox * );
public:
SwEndNoteOptionPage( Window *pParent, BOOL bEndNote,
const SfxItemSet &rSet );
~SwEndNoteOptionPage();
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset( const SfxItemSet& );
void SetShell( SwWrtShell &rShell );
};
class SwFootNoteOptionPage : public SwEndNoteOptionPage
{
SwFootNoteOptionPage( Window *pParent, const SfxItemSet &rSet );
~SwFootNoteOptionPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.7.1202); FILE MERGED 2008/04/01 15:59:33 thb 1.7.1202.3: #i85898# Stripping all external header guards 2008/04/01 12:55:43 thb 1.7.1202.2: #i85898# Stripping all external header guards 2008/03/31 16:59:03 rt 1.7.1202.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: impfnote.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _IMPFNOTE_HXX
#define _IMPFNOTE_HXX
#include <sfx2/tabdlg.hxx>
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif
#include <numberingtypelistbox.hxx>
class SwWrtShell;
class SwEndNoteOptionPage : public SfxTabPage
{
FixedText aNumTypeFT;
SwNumberingTypeListBox aNumViewBox;
FixedText aOffsetLbl;
NumericField aOffsetFld;
FixedText aNumCountFT;
ListBox aNumCountBox;
FixedText aPrefixFT;
Edit aPrefixED;
FixedText aSuffixFT;
Edit aSuffixED;
FixedText aPosFT;
RadioButton aPosPageBox;
RadioButton aPosChapterBox;
FixedLine aNumFL;
FixedText aParaTemplLbl;
ListBox aParaTemplBox;
FixedText aPageTemplLbl;
ListBox aPageTemplBox;
FixedLine aTemplFL;
FixedText aFtnCharAnchorTemplLbl;
ListBox aFtnCharAnchorTemplBox;
FixedText aFtnCharTextTemplLbl;
ListBox aFtnCharTextTemplBox;
FixedLine aCharTemplFL;
FixedText aContLbl;
Edit aContEdit;
FixedText aContFromLbl;
Edit aContFromEdit;
FixedLine aContFL;
String aNumDoc;
String aNumPage;
String aNumChapter;
SwWrtShell *pSh;
BOOL bPosDoc;
BOOL bEndNote;
inline void SelectNumbering(int eNum);
int GetNumbering() const;
DECL_LINK( PosPageHdl, Button * );
DECL_LINK( PosChapterHdl, Button * );
DECL_LINK( NumCountHdl, ListBox * );
public:
SwEndNoteOptionPage( Window *pParent, BOOL bEndNote,
const SfxItemSet &rSet );
~SwEndNoteOptionPage();
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
virtual BOOL FillItemSet(SfxItemSet &rSet);
virtual void Reset( const SfxItemSet& );
void SetShell( SwWrtShell &rShell );
};
class SwFootNoteOptionPage : public SwEndNoteOptionPage
{
SwFootNoteOptionPage( Window *pParent, const SfxItemSet &rSet );
~SwFootNoteOptionPage();
public:
static SfxTabPage *Create(Window *pParent, const SfxItemSet &rSet);
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: listsh.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: mba $ $Date: 2002-07-19 11:16:30 $
*
* 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): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include "cmdid.h"
#include "uiparam.hxx"
#include "hintids.hxx"
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SVX_SRCHITEM_HXX //autogen
#include <svx/srchitem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#include "wrtsh.hxx"
#include "swmodule.hxx"
#include "frmatr.hxx"
#include "helpid.h"
#include "globals.hrc"
#include "shells.hrc"
#include "uinums.hxx"
#include "listsh.hxx"
#include "poolfmt.hxx"
#include "view.hxx"
#include "edtwin.hxx"
#define SwListShell
#include "itemdef.hxx"
#include "swslots.hxx"
SFX_IMPL_INTERFACE(SwListShell, SwBaseShell, SW_RES(STR_SHELLNAME_LIST))
{
SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_NUM_TOOLBOX));
SFX_OBJECTMENU_REGISTRATION(SID_OBJECTMENU0, SW_RES(MN_OBJECTMENU_LIST));
}
TYPEINIT1(SwListShell,SwBaseShell)
void SwListShell::Execute(SfxRequest &rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
SwWrtShell& rSh = GetShell();
switch (nSlot)
{
case FN_NUM_BULLET_DOWN:
rSh.NumUpDown();
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_BULLET_NEXT:
rSh.GotoNextNum();
rReq.Done();
break;
case FN_NUM_BULLET_NONUM:
rSh.NoNum();
rReq.Done();
break;
case FN_NUM_BULLET_OFF:
{
rReq.Ignore();
SfxRequest aReq( GetView().GetViewFrame(), FN_NUM_BULLET_ON );
aReq.AppendItem( SfxBoolItem( FN_PARAM_1, FALSE ) );
aReq.Done();
rSh.DelNumRules();
break;
}
case FN_NUM_BULLET_OUTLINE_DOWN:
rSh.MoveNumParas(FALSE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEDOWN:
rSh.MoveNumParas(TRUE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEUP:
rSh.MoveNumParas(TRUE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_UP:
rSh.MoveNumParas(FALSE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_PREV:
rSh.GotoPrevNum();
rReq.Done();
break;
case FN_NUM_BULLET_UP:
rSh.NumUpDown(FALSE);
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_OR_NONUM:
{
BOOL bApi = rReq.IsAPI();
BOOL bDelete = !rSh.IsNoNum(!bApi);
if(pArgs )
bDelete = ((SfxBoolItem &)pArgs->Get(rReq.GetSlot())).GetValue();
rSh.NumOrNoNum( bDelete, !bApi );
rReq.AppendItem( SfxBoolItem( nSlot, bDelete ) );
rReq.Done();
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwListShell::GetState(SfxItemSet &rSet)
{
SfxWhichIter aIter( rSet );
USHORT nWhich = aIter.FirstWhich();
BOOL bHasChildren;
SwWrtShell& rSh = GetShell();
BYTE nCurrentNumLevel = rSh.GetNumLevel( &bHasChildren );
BOOL bNoNumbering = nCurrentNumLevel == NO_NUMBERING;
BOOL bNoNumLevel = 0 != (nCurrentNumLevel&NO_NUMLEVEL);
nCurrentNumLevel &= ~NO_NUMLEVEL;
while ( nWhich )
{
switch( nWhich )
{
case FN_NUM_OR_NONUM:
rSet.Put(SfxBoolItem(nWhich, GetShell().IsNoNum(FALSE)));
break;
case FN_NUM_BULLET_OUTLINE_UP:
case FN_NUM_BULLET_UP:
if(!nCurrentNumLevel)
rSet.DisableItem(nWhich);
break;
case FN_NUM_BULLET_OUTLINE_DOWN :
{
sal_uInt8 nUpper, nLower;
rSh.GetCurrentOutlineLevels( nUpper, nLower );
if(nLower == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
}
break;
case FN_NUM_BULLET_DOWN:
if(nCurrentNumLevel == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
break;
}
nWhich = aIter.NextWhich();
}
}
SwListShell::SwListShell(SwView &rView) :
SwBaseShell(rView)
{
SetName(String::CreateFromAscii("List"));
SetHelpId(SW_LISTSHELL);
}
<commit_msg>INTEGRATION: CWS os8 (1.4.146); FILE MERGED 2003/04/03 07:15:04 os 1.4.146.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
*
* $RCSfile: listsh.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:42:32 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "uiparam.hxx"
#include "hintids.hxx"
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SVX_SRCHITEM_HXX //autogen
#include <svx/srchitem.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#include "wrtsh.hxx"
#include "swmodule.hxx"
#include "frmatr.hxx"
#include "helpid.h"
#include "globals.hrc"
#include "shells.hrc"
#include "uinums.hxx"
#include "listsh.hxx"
#include "poolfmt.hxx"
#include "view.hxx"
#include "edtwin.hxx"
#define SwListShell
#include "itemdef.hxx"
#include "swslots.hxx"
SFX_IMPL_INTERFACE(SwListShell, SwBaseShell, SW_RES(STR_SHELLNAME_LIST))
{
SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_NUM_TOOLBOX));
SFX_OBJECTMENU_REGISTRATION(SID_OBJECTMENU0, SW_RES(MN_OBJECTMENU_LIST));
}
TYPEINIT1(SwListShell,SwBaseShell)
void SwListShell::Execute(SfxRequest &rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
SwWrtShell& rSh = GetShell();
switch (nSlot)
{
case FN_NUM_BULLET_DOWN:
rSh.NumUpDown();
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_BULLET_NEXT:
rSh.GotoNextNum();
rReq.Done();
break;
case FN_NUM_BULLET_NONUM:
rSh.NoNum();
rReq.Done();
break;
case FN_NUM_BULLET_OFF:
{
rReq.Ignore();
SfxRequest aReq( GetView().GetViewFrame(), FN_NUM_BULLET_ON );
aReq.AppendItem( SfxBoolItem( FN_PARAM_1, FALSE ) );
aReq.Done();
rSh.DelNumRules();
break;
}
case FN_NUM_BULLET_OUTLINE_DOWN:
rSh.MoveNumParas(FALSE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEDOWN:
rSh.MoveNumParas(TRUE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEUP:
rSh.MoveNumParas(TRUE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_UP:
rSh.MoveNumParas(FALSE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_PREV:
rSh.GotoPrevNum();
rReq.Done();
break;
case FN_NUM_BULLET_UP:
rSh.NumUpDown(FALSE);
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_OR_NONUM:
{
BOOL bApi = rReq.IsAPI();
BOOL bDelete = !rSh.IsNoNum(!bApi);
if(pArgs )
bDelete = ((SfxBoolItem &)pArgs->Get(rReq.GetSlot())).GetValue();
rSh.NumOrNoNum( bDelete, !bApi );
rReq.AppendItem( SfxBoolItem( nSlot, bDelete ) );
rReq.Done();
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwListShell::GetState(SfxItemSet &rSet)
{
SfxWhichIter aIter( rSet );
USHORT nWhich = aIter.FirstWhich();
BOOL bHasChildren;
SwWrtShell& rSh = GetShell();
BYTE nCurrentNumLevel = rSh.GetNumLevel( &bHasChildren );
BOOL bNoNumbering = nCurrentNumLevel == NO_NUMBERING;
BOOL bNoNumLevel = 0 != (nCurrentNumLevel&NO_NUMLEVEL);
nCurrentNumLevel &= ~NO_NUMLEVEL;
while ( nWhich )
{
switch( nWhich )
{
case FN_NUM_OR_NONUM:
rSet.Put(SfxBoolItem(nWhich, GetShell().IsNoNum(FALSE)));
break;
case FN_NUM_BULLET_OUTLINE_UP:
case FN_NUM_BULLET_UP:
if(!nCurrentNumLevel)
rSet.DisableItem(nWhich);
break;
case FN_NUM_BULLET_OUTLINE_DOWN :
{
sal_uInt8 nUpper, nLower;
rSh.GetCurrentOutlineLevels( nUpper, nLower );
if(nLower == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
}
break;
case FN_NUM_BULLET_DOWN:
if(nCurrentNumLevel == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
break;
}
nWhich = aIter.NextWhich();
}
}
SwListShell::SwListShell(SwView &rView) :
SwBaseShell(rView)
{
SetName(String::CreateFromAscii("List"));
SetHelpId(SW_LISTSHELL);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: listsh.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-08-14 17:54:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "uiparam.hxx"
#include "hintids.hxx"
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SVX_SRCHITEM_HXX //autogen
#include <svx/srchitem.hxx>
#endif
// --> FME 2005-01-04 #i35572#
#ifndef _NUMRULE_HXX
#include <numrule.hxx>
#endif
// <--
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#include "wrtsh.hxx"
#include "swmodule.hxx"
#include "frmatr.hxx"
#include "helpid.h"
#include "globals.hrc"
#include "shells.hrc"
#include "uinums.hxx"
#include "listsh.hxx"
#include "poolfmt.hxx"
#include "view.hxx"
#include "edtwin.hxx"
#define SwListShell
#include "itemdef.hxx"
#include "swslots.hxx"
SFX_IMPL_INTERFACE(SwListShell, SwBaseShell, SW_RES(STR_SHELLNAME_LIST))
{
SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_NUM_TOOLBOX));
}
TYPEINIT1(SwListShell,SwBaseShell)
// --> FME 2005-01-04 #i35572# Functionality of Numbering/Bullet toolbar
// for outline numbered paragraphs should match the functions for outlines
// available in the navigator. Therefore the code in the following
// function is quite similar the the code in SwContentTree::ExecCommand.
void lcl_OutlineUpDownWithSubPoints( SwWrtShell& rSh, bool bMove, bool bUp )
{
const sal_uInt16 nActPos = rSh.GetOutlinePos();
if ( nActPos < USHRT_MAX && rSh.IsOutlineMovable( nActPos ) )
{
rSh.Push();
rSh.MakeOutlineSel( nActPos, nActPos, TRUE );
if ( bMove )
{
const sal_uInt16 nActLevel = rSh.GetOutlineLevel( nActPos );
sal_uInt16 nActEndPos = nActPos + 1;
sal_Int16 nDir = 0;
if ( !bUp )
{
// Move down with subpoints:
while ( nActEndPos < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nActEndPos ) > nActLevel )
++nActEndPos;
if ( nActEndPos < rSh.GetOutlineCnt() )
{
// The current subpoint which should be moved
// starts at nActPos and ends at nActEndPos - 1
--nActEndPos;
sal_uInt16 nDest = nActEndPos + 2;
while ( nDest < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nDest ) > nActLevel )
++nDest;
nDir = nDest - 1 - nActEndPos;
}
}
else
{
// Move up with subpoints:
if ( nActPos > 0 )
{
--nActEndPos;
sal_uInt16 nDest = nActPos - 1;
while ( nDest > 0 && rSh.GetOutlineLevel( nDest ) > nActLevel )
--nDest;
nDir = nDest - nActPos;
}
}
if ( nDir )
{
rSh.MoveOutlinePara( nDir );
rSh.GotoOutline( nActPos + nDir );
}
}
else
{
// Up/down with subpoints:
rSh.OutlineUpDown( bUp ? -1 : 1 );
}
rSh.ClearMark();
rSh.Pop( sal_False );
}
}
// <--
void SwListShell::Execute(SfxRequest &rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
SwWrtShell& rSh = GetShell();
// --> FME 2005-01-04 #i35572#
const SwNumRule* pCurRule = rSh.GetCurNumRule();
ASSERT( pCurRule, "SwListShell::Execute without NumRule" )
bool bOutline = pCurRule && pCurRule->IsOutlineRule();
// <--
switch (nSlot)
{
case FN_NUM_BULLET_DOWN:
{
SfxViewFrame * pFrame = GetView().GetViewFrame();
rReq.Done();
rSh.NumUpDown();
pFrame->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
}
break;
case FN_NUM_BULLET_NEXT:
rSh.GotoNextNum();
rReq.Done();
break;
case FN_NUM_BULLET_NONUM:
rSh.NoNum();
rReq.Done();
break;
case FN_NUM_BULLET_OFF:
{
rReq.Ignore();
SfxRequest aReq( GetView().GetViewFrame(), FN_NUM_BULLET_ON );
aReq.AppendItem( SfxBoolItem( FN_PARAM_1, FALSE ) );
aReq.Done();
rSh.DelNumRules();
break;
}
case FN_NUM_BULLET_OUTLINE_DOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, false );
else
rSh.MoveNumParas(FALSE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEDOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, false );
else
rSh.MoveNumParas(TRUE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEUP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, true );
else
rSh.MoveNumParas(TRUE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_UP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, true );
else
rSh.MoveNumParas(FALSE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_PREV:
rSh.GotoPrevNum();
rReq.Done();
break;
case FN_NUM_BULLET_UP:
rSh.NumUpDown(FALSE);
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_OR_NONUM:
{
BOOL bApi = rReq.IsAPI();
BOOL bDelete = !rSh.IsNoNum(!bApi);
if(pArgs )
bDelete = ((SfxBoolItem &)pArgs->Get(rReq.GetSlot())).GetValue();
rSh.NumOrNoNum( bDelete, !bApi );
rReq.AppendItem( SfxBoolItem( nSlot, bDelete ) );
rReq.Done();
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwListShell::GetState(SfxItemSet &rSet)
{
SfxWhichIter aIter( rSet );
USHORT nWhich = aIter.FirstWhich();
BOOL bHasChildren;
SwWrtShell& rSh = GetShell();
BYTE nCurrentNumLevel = rSh.GetNumLevel( &bHasChildren );
BOOL bNoNumbering = nCurrentNumLevel == NO_NUMBERING;
BOOL bNoNumLevel = ! IsNum(nCurrentNumLevel);
nCurrentNumLevel = GetRealLevel(nCurrentNumLevel);
while ( nWhich )
{
switch( nWhich )
{
case FN_NUM_OR_NONUM:
rSet.Put(SfxBoolItem(nWhich, GetShell().IsNoNum(FALSE)));
break;
case FN_NUM_BULLET_OUTLINE_UP:
case FN_NUM_BULLET_UP:
if(!nCurrentNumLevel)
rSet.DisableItem(nWhich);
break;
case FN_NUM_BULLET_OUTLINE_DOWN :
{
sal_uInt8 nUpper, nLower;
rSh.GetCurrentOutlineLevels( nUpper, nLower );
if(nLower == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
}
break;
case FN_NUM_BULLET_DOWN:
if(nCurrentNumLevel == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
break;
}
nWhich = aIter.NextWhich();
}
}
SwListShell::SwListShell(SwView &rView) :
SwBaseShell(rView)
{
SetName(String::CreateFromAscii("List"));
SetHelpId(SW_LISTSHELL);
}
<commit_msg>INTEGRATION: CWS os86 (1.11.28); FILE MERGED 2006/09/04 12:46:43 os 1.11.28.1: #i68430# missing initialization fixed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: listsh.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-15 12:57:01 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "cmdid.h"
#include "uiparam.hxx"
#include "hintids.hxx"
#ifndef _SVX_SIZEITEM_HXX //autogen
#include <svx/sizeitem.hxx>
#endif
#ifndef _SVX_BRSHITEM_HXX //autogen
#include <svx/brshitem.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXOBJFACE_HXX //autogen
#include <sfx2/objface.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SHL_HXX //autogen
#include <tools/shl.hxx>
#endif
#ifndef _SVX_SRCHITEM_HXX //autogen
#include <svx/srchitem.hxx>
#endif
// --> FME 2005-01-04 #i35572#
#ifndef _NUMRULE_HXX
#include <numrule.hxx>
#endif
// <--
#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#include "wrtsh.hxx"
#include "swmodule.hxx"
#include "frmatr.hxx"
#include "helpid.h"
#include "globals.hrc"
#include "shells.hrc"
#include "uinums.hxx"
#include "listsh.hxx"
#include "poolfmt.hxx"
#include "view.hxx"
#include "edtwin.hxx"
#define SwListShell
#include "itemdef.hxx"
#include "swslots.hxx"
SFX_IMPL_INTERFACE(SwListShell, SwBaseShell, SW_RES(STR_SHELLNAME_LIST))
{
SFX_OBJECTBAR_REGISTRATION(SFX_OBJECTBAR_OBJECT, SW_RES(RID_NUM_TOOLBOX));
}
TYPEINIT1(SwListShell,SwBaseShell)
// --> FME 2005-01-04 #i35572# Functionality of Numbering/Bullet toolbar
// for outline numbered paragraphs should match the functions for outlines
// available in the navigator. Therefore the code in the following
// function is quite similar the the code in SwContentTree::ExecCommand.
void lcl_OutlineUpDownWithSubPoints( SwWrtShell& rSh, bool bMove, bool bUp )
{
const sal_uInt16 nActPos = rSh.GetOutlinePos();
if ( nActPos < USHRT_MAX && rSh.IsOutlineMovable( nActPos ) )
{
rSh.Push();
rSh.MakeOutlineSel( nActPos, nActPos, TRUE );
if ( bMove )
{
const sal_uInt16 nActLevel = rSh.GetOutlineLevel( nActPos );
sal_uInt16 nActEndPos = nActPos + 1;
sal_Int16 nDir = 0;
if ( !bUp )
{
// Move down with subpoints:
while ( nActEndPos < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nActEndPos ) > nActLevel )
++nActEndPos;
if ( nActEndPos < rSh.GetOutlineCnt() )
{
// The current subpoint which should be moved
// starts at nActPos and ends at nActEndPos - 1
--nActEndPos;
sal_uInt16 nDest = nActEndPos + 2;
while ( nDest < rSh.GetOutlineCnt() &&
rSh.GetOutlineLevel( nDest ) > nActLevel )
++nDest;
nDir = nDest - 1 - nActEndPos;
}
}
else
{
// Move up with subpoints:
if ( nActPos > 0 )
{
--nActEndPos;
sal_uInt16 nDest = nActPos - 1;
while ( nDest > 0 && rSh.GetOutlineLevel( nDest ) > nActLevel )
--nDest;
nDir = nDest - nActPos;
}
}
if ( nDir )
{
rSh.MoveOutlinePara( nDir );
rSh.GotoOutline( nActPos + nDir );
}
}
else
{
// Up/down with subpoints:
rSh.OutlineUpDown( bUp ? -1 : 1 );
}
rSh.ClearMark();
rSh.Pop( sal_False );
}
}
// <--
void SwListShell::Execute(SfxRequest &rReq)
{
const SfxItemSet* pArgs = rReq.GetArgs();
USHORT nSlot = rReq.GetSlot();
SwWrtShell& rSh = GetShell();
// --> FME 2005-01-04 #i35572#
const SwNumRule* pCurRule = rSh.GetCurNumRule();
ASSERT( pCurRule, "SwListShell::Execute without NumRule" )
bool bOutline = pCurRule && pCurRule->IsOutlineRule();
// <--
switch (nSlot)
{
case FN_NUM_BULLET_DOWN:
{
SfxViewFrame * pFrame = GetView().GetViewFrame();
rReq.Done();
rSh.NumUpDown();
pFrame->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
}
break;
case FN_NUM_BULLET_NEXT:
rSh.GotoNextNum();
rReq.Done();
break;
case FN_NUM_BULLET_NONUM:
rSh.NoNum();
rReq.Done();
break;
case FN_NUM_BULLET_OFF:
{
rReq.Ignore();
SfxRequest aReq( GetView().GetViewFrame(), FN_NUM_BULLET_ON );
aReq.AppendItem( SfxBoolItem( FN_PARAM_1, FALSE ) );
aReq.Done();
rSh.DelNumRules();
break;
}
case FN_NUM_BULLET_OUTLINE_DOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, false );
else
rSh.MoveNumParas(FALSE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEDOWN:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, false );
else
rSh.MoveNumParas(TRUE, FALSE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_MOVEUP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, true, true );
else
rSh.MoveNumParas(TRUE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_OUTLINE_UP:
if ( bOutline )
lcl_OutlineUpDownWithSubPoints( rSh, false, true );
else
rSh.MoveNumParas(FALSE, TRUE);
rReq.Done();
break;
case FN_NUM_BULLET_PREV:
rSh.GotoPrevNum();
rReq.Done();
break;
case FN_NUM_BULLET_UP:
rSh.NumUpDown(FALSE);
GetView().GetViewFrame()->GetBindings().Invalidate( SID_TABLE_CELL ); // StatusZeile updaten!
rReq.Done();
break;
case FN_NUM_OR_NONUM:
{
BOOL bApi = rReq.IsAPI();
BOOL bDelete = !rSh.IsNoNum(!bApi);
if(pArgs )
bDelete = ((SfxBoolItem &)pArgs->Get(rReq.GetSlot())).GetValue();
rSh.NumOrNoNum( bDelete, !bApi );
rReq.AppendItem( SfxBoolItem( nSlot, bDelete ) );
rReq.Done();
}
break;
default:
ASSERT(!this, falscher Dispatcher);
return;
}
}
void SwListShell::GetState(SfxItemSet &rSet)
{
SfxWhichIter aIter( rSet );
USHORT nWhich = aIter.FirstWhich();
BOOL bHasChildren;
SwWrtShell& rSh = GetShell();
BYTE nCurrentNumLevel = rSh.GetNumLevel( &bHasChildren );
BOOL bNoNumbering = nCurrentNumLevel == NO_NUMBERING;
BOOL bNoNumLevel = ! IsNum(nCurrentNumLevel);
nCurrentNumLevel = GetRealLevel(nCurrentNumLevel);
while ( nWhich )
{
switch( nWhich )
{
case FN_NUM_OR_NONUM:
rSet.Put(SfxBoolItem(nWhich, GetShell().IsNoNum(FALSE)));
break;
case FN_NUM_BULLET_OUTLINE_UP:
case FN_NUM_BULLET_UP:
if(!nCurrentNumLevel)
rSet.DisableItem(nWhich);
break;
case FN_NUM_BULLET_OUTLINE_DOWN :
{
sal_uInt8 nUpper = 0;
sal_uInt8 nLower = 0;
rSh.GetCurrentOutlineLevels( nUpper, nLower );
if(nLower == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
}
break;
case FN_NUM_BULLET_DOWN:
if(nCurrentNumLevel == (MAXLEVEL - 1))
rSet.DisableItem(nWhich);
break;
}
nWhich = aIter.NextWhich();
}
}
SwListShell::SwListShell(SwView &rView) :
SwBaseShell(rView)
{
SetName(String::CreateFromAscii("List"));
SetHelpId(SW_LISTSHELL);
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef NET_IP4_HEADER_HPP
#define NET_IP4_HEADER_HPP
namespace net {
namespace ip4 {
/** IP4 header representation */
struct Header {
uint8_t version_ihl;
uint8_t tos;
uint16_t tot_len;
uint16_t id;
uint16_t frag_off_flags;
uint8_t ttl;
uint8_t protocol;
uint16_t check;
Addr saddr;
Addr daddr;
};
}
}
#endif
<commit_msg>net: Add documentation to ip4::Header<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef NET_IP4_HEADER_HPP
#define NET_IP4_HEADER_HPP
#include <cstdint>
namespace net {
namespace ip4 {
/**
* This type contain the valid set of flags that can be set on an
* IPv4 datagram
*/
enum class Flags : uint8_t {
NONE = 0b000,
MF = 0b001,
DF = 0b010,
MFDF = 0b011
}; //< enum class Flags
/**
* This type is used to represent the standard IPv4 header
*/
struct Header {
uint8_t version_ihl; //< IP version and header length
uint8_t ds_ecn; //< IP datagram differentiated services codepoint and explicit congestion notification
uint16_t tot_len; //< IP datagram total length
uint16_t id; //< IP datagram identification number
uint16_t frag_off_flags; //< IP datagram fragment offset and control flags
uint8_t ttl; //< IP datagram time to live value
uint8_t protocol; //< IP datagram protocol value
uint16_t check; //< IP datagram checksum value
Addr saddr; //< IP datagram source address
Addr daddr; //< IP datagram destination address
}; //< struct Header
} //< namespace ip4
} //< namespace net
#endif //< NET_IP4_HEADER_HPP
<|endoftext|> |
<commit_before><commit_msg>remove Remove()<commit_after><|endoftext|> |
<commit_before>/*****************************************************************************
* playlist_item.cpp : Manage playlist item
****************************************************************************
* Copyright © 2006-2008 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[email protected]>
* Jean-Baptiste Kempf <[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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <assert.h>
#include "qt4.hpp"
#include "components/playlist/playlist_model.hpp"
#include <vlc_intf_strings.h>
#include <QSettings>
#include "sorting.h"
/*************************************************************************
* Playlist item implementation
*************************************************************************/
/*
Playlist item is just a wrapper, an abstraction of the playlist_item
in order to be managed by PLModel
PLItem have a parent, and id and a input Id
*/
void PLItem::init( playlist_item_t *_playlist_item, PLItem *parent, PLModel *m, QSettings *settings )
{
parentItem = parent; /* Can be NULL, but only for the rootItem */
i_id = _playlist_item->i_id; /* Playlist item specific id */
i_input_id = _playlist_item->p_input->i_id; /* Identifier of the input */
model = m; /* PLModel (QAbsmodel) */
i_type = -1; /* Item type - Avoid segfault */
b_current = false; /* Is the item the current Item or not */
b_is_node = _playlist_item->i_children > -1;
p_input = _playlist_item->p_input;
vlc_gc_incref( p_input );
assert( model ); /* We need a model */
/* No parent, should be the 2 main ones */
if( parentItem == NULL )
{
if( model->i_depth == DEPTH_SEL ) /* Selector Panel */
{
i_showflags = 0;
}
else
{
i_showflags = settings->value( "qt-pl-showflags", COLUMN_DEFAULT ).toInt();
if( i_showflags < 1)
i_showflags = COLUMN_DEFAULT; /* reasonable default to show something; */
else if ( i_showflags >= COLUMN_END )
i_showflags = COLUMN_END - 1; /* show everything */
updateColumnHeaders();
}
}
else
{
i_showflags = parentItem->i_showflags;
//Add empty string and update() handles data appending
}
}
/*
Constructors
Call the above function init
So far the first constructor isn't used...
*/
PLItem::PLItem( playlist_item_t *p_item, PLItem *parent, PLModel *m )
{
init( p_item, parent, m, NULL );
}
PLItem::PLItem( playlist_item_t * p_item, QSettings *settings, PLModel *m )
{
init( p_item, NULL, m, settings );
}
PLItem::~PLItem()
{
qDeleteAll( children );
children.clear();
}
/* Column manager */
void PLItem::updateColumnHeaders()
{
assert( i_showflags < COLUMN_END );
}
/* So far signal is always true.
Using signal false would not call PLModel... Why ?
*/
void PLItem::insertChild( PLItem *item, int i_pos, bool signal )
{
if( signal )
model->beginInsertRows( model->index( this , 0 ), i_pos, i_pos );
children.insert( i_pos, item );
if( signal )
model->endInsertRows();
}
void PLItem::remove( PLItem *removed )
{
if( model->i_depth == DEPTH_SEL || parentItem )
{
int i_index = parentItem->children.indexOf( removed );
model->beginRemoveRows( model->index( parentItem, 0 ),
i_index, i_index );
parentItem->children.removeAt( i_index );
model->endRemoveRows();
}
}
/* This function is used to get one's parent's row number in the model */
int PLItem::row() const
{
if( parentItem )
return parentItem->children.indexOf( const_cast<PLItem*>(this) );
// We don't ever inherit PLItem, yet, but it might come :D
return 0;
}
/* update the PL Item, get the good names and so on */
/* This function may not be the best way to do it
It destroys everything and gets everything again instead of just
building the necessary columns.
This does extra work if you re-display the same column. Slower...
On the other hand, this way saves memory.
There must be a more clever way.
*/
void PLItem::update( playlist_item_t *p_item, bool iscurrent )
{
assert( p_item->p_input->i_id == i_input_id );
/* Useful for the model */
i_type = p_item->p_input->i_type;
b_current = iscurrent;
b_is_node = p_item->i_children > -1;
i_showflags = parentItem ? parentItem->i_showflags : i_showflags;
}
<commit_msg>Qt4: playlist_item, forgotten dec_ref<commit_after>/*****************************************************************************
* playlist_item.cpp : Manage playlist item
****************************************************************************
* Copyright © 2006-2008 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[email protected]>
* Jean-Baptiste Kempf <[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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <assert.h>
#include "qt4.hpp"
#include "components/playlist/playlist_model.hpp"
#include <vlc_intf_strings.h>
#include <QSettings>
#include "sorting.h"
/*************************************************************************
* Playlist item implementation
*************************************************************************/
/*
Playlist item is just a wrapper, an abstraction of the playlist_item
in order to be managed by PLModel
PLItem have a parent, and id and a input Id
*/
void PLItem::init( playlist_item_t *_playlist_item, PLItem *parent, PLModel *m, QSettings *settings )
{
parentItem = parent; /* Can be NULL, but only for the rootItem */
i_id = _playlist_item->i_id; /* Playlist item specific id */
i_input_id = _playlist_item->p_input->i_id; /* Identifier of the input */
model = m; /* PLModel (QAbsmodel) */
i_type = -1; /* Item type - Avoid segfault */
b_current = false; /* Is the item the current Item or not */
b_is_node = _playlist_item->i_children > -1;
p_input = _playlist_item->p_input;
vlc_gc_incref( p_input );
assert( model ); /* We need a model */
/* No parent, should be the 2 main ones */
if( parentItem == NULL )
{
if( model->i_depth == DEPTH_SEL ) /* Selector Panel */
{
i_showflags = 0;
}
else
{
i_showflags = settings->value( "qt-pl-showflags", COLUMN_DEFAULT ).toInt();
if( i_showflags < 1)
i_showflags = COLUMN_DEFAULT; /* reasonable default to show something; */
else if ( i_showflags >= COLUMN_END )
i_showflags = COLUMN_END - 1; /* show everything */
updateColumnHeaders();
}
}
else
{
i_showflags = parentItem->i_showflags;
//Add empty string and update() handles data appending
}
}
/*
Constructors
Call the above function init
So far the first constructor isn't used...
*/
PLItem::PLItem( playlist_item_t *p_item, PLItem *parent, PLModel *m )
{
init( p_item, parent, m, NULL );
}
PLItem::PLItem( playlist_item_t * p_item, QSettings *settings, PLModel *m )
{
init( p_item, NULL, m, settings );
}
PLItem::~PLItem()
{
vlc_gc_decref( p_input );
qDeleteAll( children );
children.clear();
}
/* Column manager */
void PLItem::updateColumnHeaders()
{
assert( i_showflags < COLUMN_END );
}
/* So far signal is always true.
Using signal false would not call PLModel... Why ?
*/
void PLItem::insertChild( PLItem *item, int i_pos, bool signal )
{
if( signal )
model->beginInsertRows( model->index( this , 0 ), i_pos, i_pos );
children.insert( i_pos, item );
if( signal )
model->endInsertRows();
}
void PLItem::remove( PLItem *removed )
{
if( model->i_depth == DEPTH_SEL || parentItem )
{
int i_index = parentItem->children.indexOf( removed );
model->beginRemoveRows( model->index( parentItem, 0 ),
i_index, i_index );
parentItem->children.removeAt( i_index );
model->endRemoveRows();
}
}
/* This function is used to get one's parent's row number in the model */
int PLItem::row() const
{
if( parentItem )
return parentItem->children.indexOf( const_cast<PLItem*>(this) );
// We don't ever inherit PLItem, yet, but it might come :D
return 0;
}
/* update the PL Item, get the good names and so on */
/* This function may not be the best way to do it
It destroys everything and gets everything again instead of just
building the necessary columns.
This does extra work if you re-display the same column. Slower...
On the other hand, this way saves memory.
There must be a more clever way.
*/
void PLItem::update( playlist_item_t *p_item, bool iscurrent )
{
assert( p_item->p_input->i_id == i_input_id );
/* Useful for the model */
i_type = p_item->p_input->i_type;
b_current = iscurrent;
b_is_node = p_item->i_children > -1;
i_showflags = parentItem ? parentItem->i_showflags : i_showflags;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* standardpanel.cpp : The "standard" playlist panel : just a treeview
****************************************************************************
* Copyright (C) 2000-2005 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "components/playlist/playlist_model.hpp"
#include "components/playlist/panels.hpp"
#include "util/customwidgets.hpp"
#include <vlc_intf_strings.h>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QModelIndexList>
#include <QLabel>
#include <QSpacerItem>
#include <QMenu>
#include <QSignalMapper>
#include <assert.h>
#include "sorting.h"
StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent,
intf_thread_t *_p_intf,
playlist_t *p_playlist,
playlist_item_t *p_root ):
PLPanel( _parent, _p_intf )
{
model = new PLModel( p_playlist, p_intf, p_root, -1, this );
QVBoxLayout *layout = new QVBoxLayout();
layout->setSpacing( 0 ); layout->setMargin( 0 );
/* Create and configure the QTreeView */
view = new QVLCTreeView;
view->setModel( model );
view->setIconSize( QSize( 20, 20 ) );
view->setAlternatingRowColors( true );
view->setAnimated( true );
view->setSelectionBehavior( QAbstractItemView::SelectRows );
view->setSelectionMode( QAbstractItemView::ExtendedSelection );
view->setDragEnabled( true );
view->setAcceptDrops( true );
view->setDropIndicatorShown( true );
view->header()->setSortIndicator( -1 , Qt::AscendingOrder );
view->setUniformRowHeights( true );
view->setSortingEnabled( true );
getSettings()->beginGroup("Playlist");
if( getSettings()->contains( "headerState" ) )
{
view->header()->restoreState(
getSettings()->value( "headerState" ).toByteArray() );
}
else
{
/* Configure the size of the header */
view->header()->resizeSection( 0, 200 );
view->header()->resizeSection( 1, 80 );
}
view->header()->setSortIndicatorShown( true );
view->header()->setClickable( true );
view->header()->setContextMenuPolicy( Qt::CustomContextMenu );
getSettings()->endGroup();
/* Connections for the TreeView */
CONNECT( view, activated( const QModelIndex& ) ,
model,activateItem( const QModelIndex& ) );
CONNECT( view, rightClicked( QModelIndex , QPoint ),
this, doPopup( QModelIndex, QPoint ) );
CONNECT( view->header(), customContextMenuRequested( const QPoint & ),
this, popupSelectColumn( QPoint ) );
CONNECT( model, currentChanged( const QModelIndex& ),
this, handleExpansion( const QModelIndex& ) );
CONNECT( model, columnsChanged( int ),
this, checkSortingIndicator( int ) );
currentRootId = -1;
CONNECT( parent, rootChanged( int ), this, setCurrentRootId( int ) );
/* Buttons configuration */
QHBoxLayout *buttons = new QHBoxLayout;
/* Add item to the playlist button */
addButton = new QPushButton;
addButton->setIcon( QIcon( ":/buttons/playlist/playlist_add" ) );
addButton->setMaximumWidth( 30 );
BUTTONACT( addButton, popupAdd() );
buttons->addWidget( addButton );
/* Random 2-state button */
randomButton = new QPushButton( this );
randomButton->setIcon( QIcon( ":/buttons/playlist/shuffle_on" ));
randomButton->setToolTip( qtr( I_PL_RANDOM ));
randomButton->setCheckable( true );
randomButton->setChecked( model->hasRandom() );
BUTTONACT( randomButton, toggleRandom() );
buttons->addWidget( randomButton );
/* Repeat 3-state button */
repeatButton = new QPushButton( this );
repeatButton->setToolTip( qtr( "Click to toggle between loop one, loop all" ) );
repeatButton->setCheckable( true );
if( model->hasRepeat() )
{
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
repeatButton->setChecked( true );
}
else if( model->hasLoop() )
{
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_all" ) );
repeatButton->setChecked( true );
}
else
{
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
repeatButton->setChecked( false );
}
BUTTONACT( repeatButton, toggleRepeat() );
buttons->addWidget( repeatButton );
/* Goto */
gotoPlayingButton = new QPushButton;
BUTTON_SET_ACT_I( gotoPlayingButton, "", buttons/playlist/jump_to,
qtr( "Show the current item" ), gotoPlayingItem() );
buttons->addWidget( gotoPlayingButton );
/* A Spacer and the search possibilities */
QSpacerItem *spacer = new QSpacerItem( 10, 20 );
buttons->addItem( spacer );
QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " );
buttons->addWidget( filter );
SearchLineEdit *search = new SearchLineEdit( this );
buttons->addWidget( search );
filter->setBuddy( search );
CONNECT( search, textChanged( const QString& ), this, search( const QString& ) );
/* Finish the layout */
layout->addWidget( view );
layout->addLayout( buttons );
// layout->addWidget( bar );
setLayout( layout );
}
/* Function to toggle between the Repeat states */
void StandardPLPanel::toggleRepeat()
{
if( model->hasRepeat() )
{
model->setRepeat( false ); model->setLoop( true );
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_all" ) );
repeatButton->setChecked( true );
}
else if( model->hasLoop() )
{
model->setRepeat( false ) ; model->setLoop( false );
repeatButton->setChecked( false );
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
}
else
{
model->setRepeat( true ); model->setLoop( false );
repeatButton->setChecked( true );
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
}
}
/* Function to toggle between the Random states */
void StandardPLPanel::toggleRandom()
{
bool prev = model->hasRandom();
model->setRandom( !prev );
}
void StandardPLPanel::gotoPlayingItem()
{
view->scrollTo( view->currentIndex() );
}
void StandardPLPanel::handleExpansion( const QModelIndex& index )
{
view->scrollTo( index, QAbstractItemView::EnsureVisible );
}
void StandardPLPanel::setCurrentRootId( int _new )
{
currentRootId = _new;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDPL) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDML) );
}
else
addButton->setEnabled( false );
}
/* PopupAdd Menu for the Add Menu */
void StandardPLPanel::popupAdd()
{
QMenu popup;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT( simplePLAppendDialog()) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
popup.addAction( qtr(I_OP_ADVOP), THEDP, SLOT( PLAppendDialog()) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT( simpleMLAppendDialog()) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
popup.addAction( qtr(I_OP_ADVOP), THEDP, SLOT( MLAppendDialog() ) );
}
popup.exec( QCursor::pos() - addButton->mapFromGlobal( QCursor::pos() )
+ QPoint( 0, addButton->height() ) );
}
/* Set sortingindicator to -1 if it's on column thats removed,
* else check that it's still showing on correct column
*/
void StandardPLPanel::checkSortingIndicator( int meta )
{
int index=0;
if( view->header()->isSortIndicatorShown() == false )
return;
int sortIndex = view->header()->sortIndicatorSection();
if( sortIndex < 0 || sortIndex > view->header()->count() || meta == 0 )
return;
int _meta = meta;
while( _meta )
{
if( _meta & model->shownFlags() )
index++;
_meta >>= 1;
}
/* Adding column */
if( model->shownFlags() & meta )
{
/* If column is added before sortIndex, move it one to right*/
if( sortIndex >= index )
{
sortIndex += 1;
}
} else {
/* Column removed */
if( sortIndex == index )
{
sortIndex = -1;
} else if( sortIndex > index )
{
/* Move indicator left one step*/
sortIndex -= 1;
}
}
view->header()->setSortIndicator( sortIndex ,
view->header()->sortIndicatorOrder() );
}
void StandardPLPanel::popupSelectColumn( QPoint pos )
{
ContextUpdateMapper = new QSignalMapper(this);
QMenu selectColMenu;
int i_column = 1;
for( i_column = 1; i_column != COLUMN_END; i_column<<=1 )
{
QAction* option = selectColMenu.addAction(
qfu( psz_column_title( i_column ) ) );
option->setCheckable( true );
option->setChecked( model->shownFlags() & i_column );
ContextUpdateMapper->setMapping( option, i_column );
CONNECT( option, triggered(), ContextUpdateMapper, map() );
}
CONNECT( ContextUpdateMapper, mapped( int ), model, viewchanged( int ) );
selectColMenu.exec( QCursor::pos() );
}
/* Search in the playlist */
void StandardPLPanel::search( const QString& searchText )
{
model->search( searchText );
}
void StandardPLPanel::doPopup( QModelIndex index, QPoint point )
{
if( !index.isValid() ) return;
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->popup( index, point, list );
}
/* Set the root of the new Playlist */
/* This activated by the selector selection */
void StandardPLPanel::setRoot( int i_root_id )
{
QPL_LOCK;
playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id );
assert( p_item );
p_item = playlist_GetPreferredNode( THEPL, p_item );
assert( p_item );
QPL_UNLOCK;
model->rebuild( p_item );
}
void StandardPLPanel::removeItem( int i_id )
{
model->removeItem( i_id );
}
/* Delete and Suppr key remove the selection
FilterKey function and code function */
void StandardPLPanel::keyPressEvent( QKeyEvent *e )
{
switch( e->key() )
{
case Qt::Key_Back:
case Qt::Key_Delete:
deleteSelection();
break;
}
}
void StandardPLPanel::deleteSelection()
{
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->doDelete( list );
}
StandardPLPanel::~StandardPLPanel()
{
getSettings()->beginGroup("Playlist");
getSettings()->setValue( "headerState", view->header()->saveState() );
getSettings()->endGroup();
}
<commit_msg>QT4: remove Ensurevisible from scrollTo<commit_after>/*****************************************************************************
* standardpanel.cpp : The "standard" playlist panel : just a treeview
****************************************************************************
* Copyright (C) 2000-2005 the VideoLAN team
* $Id$
*
* Authors: Clément Stenac <[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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "qt4.hpp"
#include "dialogs_provider.hpp"
#include "components/playlist/playlist_model.hpp"
#include "components/playlist/panels.hpp"
#include "util/customwidgets.hpp"
#include <vlc_intf_strings.h>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QHeaderView>
#include <QKeyEvent>
#include <QModelIndexList>
#include <QLabel>
#include <QSpacerItem>
#include <QMenu>
#include <QSignalMapper>
#include <assert.h>
#include "sorting.h"
StandardPLPanel::StandardPLPanel( PlaylistWidget *_parent,
intf_thread_t *_p_intf,
playlist_t *p_playlist,
playlist_item_t *p_root ):
PLPanel( _parent, _p_intf )
{
model = new PLModel( p_playlist, p_intf, p_root, -1, this );
QVBoxLayout *layout = new QVBoxLayout();
layout->setSpacing( 0 ); layout->setMargin( 0 );
/* Create and configure the QTreeView */
view = new QVLCTreeView;
view->setModel( model );
view->setIconSize( QSize( 20, 20 ) );
view->setAlternatingRowColors( true );
view->setAnimated( true );
view->setSelectionBehavior( QAbstractItemView::SelectRows );
view->setSelectionMode( QAbstractItemView::ExtendedSelection );
view->setDragEnabled( true );
view->setAcceptDrops( true );
view->setDropIndicatorShown( true );
view->header()->setSortIndicator( -1 , Qt::AscendingOrder );
view->setUniformRowHeights( true );
view->setSortingEnabled( true );
getSettings()->beginGroup("Playlist");
if( getSettings()->contains( "headerState" ) )
{
view->header()->restoreState(
getSettings()->value( "headerState" ).toByteArray() );
}
else
{
/* Configure the size of the header */
view->header()->resizeSection( 0, 200 );
view->header()->resizeSection( 1, 80 );
}
view->header()->setSortIndicatorShown( true );
view->header()->setClickable( true );
view->header()->setContextMenuPolicy( Qt::CustomContextMenu );
getSettings()->endGroup();
/* Connections for the TreeView */
CONNECT( view, activated( const QModelIndex& ) ,
model,activateItem( const QModelIndex& ) );
CONNECT( view, rightClicked( QModelIndex , QPoint ),
this, doPopup( QModelIndex, QPoint ) );
CONNECT( view->header(), customContextMenuRequested( const QPoint & ),
this, popupSelectColumn( QPoint ) );
CONNECT( model, currentChanged( const QModelIndex& ),
this, handleExpansion( const QModelIndex& ) );
CONNECT( model, columnsChanged( int ),
this, checkSortingIndicator( int ) );
currentRootId = -1;
CONNECT( parent, rootChanged( int ), this, setCurrentRootId( int ) );
/* Buttons configuration */
QHBoxLayout *buttons = new QHBoxLayout;
/* Add item to the playlist button */
addButton = new QPushButton;
addButton->setIcon( QIcon( ":/buttons/playlist/playlist_add" ) );
addButton->setMaximumWidth( 30 );
BUTTONACT( addButton, popupAdd() );
buttons->addWidget( addButton );
/* Random 2-state button */
randomButton = new QPushButton( this );
randomButton->setIcon( QIcon( ":/buttons/playlist/shuffle_on" ));
randomButton->setToolTip( qtr( I_PL_RANDOM ));
randomButton->setCheckable( true );
randomButton->setChecked( model->hasRandom() );
BUTTONACT( randomButton, toggleRandom() );
buttons->addWidget( randomButton );
/* Repeat 3-state button */
repeatButton = new QPushButton( this );
repeatButton->setToolTip( qtr( "Click to toggle between loop one, loop all" ) );
repeatButton->setCheckable( true );
if( model->hasRepeat() )
{
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
repeatButton->setChecked( true );
}
else if( model->hasLoop() )
{
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_all" ) );
repeatButton->setChecked( true );
}
else
{
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
repeatButton->setChecked( false );
}
BUTTONACT( repeatButton, toggleRepeat() );
buttons->addWidget( repeatButton );
/* Goto */
gotoPlayingButton = new QPushButton;
BUTTON_SET_ACT_I( gotoPlayingButton, "", buttons/playlist/jump_to,
qtr( "Show the current item" ), gotoPlayingItem() );
buttons->addWidget( gotoPlayingButton );
/* A Spacer and the search possibilities */
QSpacerItem *spacer = new QSpacerItem( 10, 20 );
buttons->addItem( spacer );
QLabel *filter = new QLabel( qtr(I_PL_SEARCH) + " " );
buttons->addWidget( filter );
SearchLineEdit *search = new SearchLineEdit( this );
buttons->addWidget( search );
filter->setBuddy( search );
CONNECT( search, textChanged( const QString& ), this, search( const QString& ) );
/* Finish the layout */
layout->addWidget( view );
layout->addLayout( buttons );
// layout->addWidget( bar );
setLayout( layout );
}
/* Function to toggle between the Repeat states */
void StandardPLPanel::toggleRepeat()
{
if( model->hasRepeat() )
{
model->setRepeat( false ); model->setLoop( true );
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_all" ) );
repeatButton->setChecked( true );
}
else if( model->hasLoop() )
{
model->setRepeat( false ) ; model->setLoop( false );
repeatButton->setChecked( false );
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
}
else
{
model->setRepeat( true ); model->setLoop( false );
repeatButton->setChecked( true );
repeatButton->setIcon( QIcon( ":/buttons/playlist/repeat_one" ) );
}
}
/* Function to toggle between the Random states */
void StandardPLPanel::toggleRandom()
{
bool prev = model->hasRandom();
model->setRandom( !prev );
}
void StandardPLPanel::gotoPlayingItem()
{
view->scrollTo( view->currentIndex() );
}
void StandardPLPanel::handleExpansion( const QModelIndex& index )
{
view->scrollTo( index );
}
void StandardPLPanel::setCurrentRootId( int _new )
{
currentRootId = _new;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDPL) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
addButton->setEnabled( true );
addButton->setToolTip( qtr(I_PL_ADDML) );
}
else
addButton->setEnabled( false );
}
/* PopupAdd Menu for the Add Menu */
void StandardPLPanel::popupAdd()
{
QMenu popup;
if( currentRootId == THEPL->p_local_category->i_id ||
currentRootId == THEPL->p_local_onelevel->i_id )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT( simplePLAppendDialog()) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( PLAppendDir()) );
popup.addAction( qtr(I_OP_ADVOP), THEDP, SLOT( PLAppendDialog()) );
}
else if( ( THEPL->p_ml_category &&
currentRootId == THEPL->p_ml_category->i_id ) ||
( THEPL->p_ml_onelevel &&
currentRootId == THEPL->p_ml_onelevel->i_id ) )
{
popup.addAction( qtr(I_PL_ADDF), THEDP, SLOT( simpleMLAppendDialog()) );
popup.addAction( qtr(I_PL_ADDDIR), THEDP, SLOT( MLAppendDir() ) );
popup.addAction( qtr(I_OP_ADVOP), THEDP, SLOT( MLAppendDialog() ) );
}
popup.exec( QCursor::pos() - addButton->mapFromGlobal( QCursor::pos() )
+ QPoint( 0, addButton->height() ) );
}
/* Set sortingindicator to -1 if it's on column thats removed,
* else check that it's still showing on correct column
*/
void StandardPLPanel::checkSortingIndicator( int meta )
{
int index=0;
if( view->header()->isSortIndicatorShown() == false )
return;
int sortIndex = view->header()->sortIndicatorSection();
if( sortIndex < 0 || sortIndex > view->header()->count() || meta == 0 )
return;
int _meta = meta;
while( _meta )
{
if( _meta & model->shownFlags() )
index++;
_meta >>= 1;
}
/* Adding column */
if( model->shownFlags() & meta )
{
/* If column is added before sortIndex, move it one to right*/
if( sortIndex >= index )
{
sortIndex += 1;
}
} else {
/* Column removed */
if( sortIndex == index )
{
sortIndex = -1;
} else if( sortIndex > index )
{
/* Move indicator left one step*/
sortIndex -= 1;
}
}
view->header()->setSortIndicator( sortIndex ,
view->header()->sortIndicatorOrder() );
}
void StandardPLPanel::popupSelectColumn( QPoint pos )
{
ContextUpdateMapper = new QSignalMapper(this);
QMenu selectColMenu;
int i_column = 1;
for( i_column = 1; i_column != COLUMN_END; i_column<<=1 )
{
QAction* option = selectColMenu.addAction(
qfu( psz_column_title( i_column ) ) );
option->setCheckable( true );
option->setChecked( model->shownFlags() & i_column );
ContextUpdateMapper->setMapping( option, i_column );
CONNECT( option, triggered(), ContextUpdateMapper, map() );
}
CONNECT( ContextUpdateMapper, mapped( int ), model, viewchanged( int ) );
selectColMenu.exec( QCursor::pos() );
}
/* Search in the playlist */
void StandardPLPanel::search( const QString& searchText )
{
model->search( searchText );
}
void StandardPLPanel::doPopup( QModelIndex index, QPoint point )
{
if( !index.isValid() ) return;
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->popup( index, point, list );
}
/* Set the root of the new Playlist */
/* This activated by the selector selection */
void StandardPLPanel::setRoot( int i_root_id )
{
QPL_LOCK;
playlist_item_t *p_item = playlist_ItemGetById( THEPL, i_root_id );
assert( p_item );
p_item = playlist_GetPreferredNode( THEPL, p_item );
assert( p_item );
QPL_UNLOCK;
model->rebuild( p_item );
}
void StandardPLPanel::removeItem( int i_id )
{
model->removeItem( i_id );
}
/* Delete and Suppr key remove the selection
FilterKey function and code function */
void StandardPLPanel::keyPressEvent( QKeyEvent *e )
{
switch( e->key() )
{
case Qt::Key_Back:
case Qt::Key_Delete:
deleteSelection();
break;
}
}
void StandardPLPanel::deleteSelection()
{
QItemSelectionModel *selection = view->selectionModel();
QModelIndexList list = selection->selectedIndexes();
model->doDelete( list );
}
StandardPLPanel::~StandardPLPanel()
{
getSettings()->beginGroup("Playlist");
getSettings()->setValue( "headerState", view->header()->saveState() );
getSettings()->endGroup();
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: TestUnicodeStringArrayAPI.cxx
-------------------------------------------------------------------------
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.
-------------------------------------------------------------------------
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.
=========================================================================*/
#include <vtkSmartPointer.h>
#include <vtkUnicodeStringArray.h>
#include <vtksys/stl/iterator>
#include <vtksys/ios/iostream>
#include <vtksys/ios/sstream>
#include <vtksys/stl/stdexcept>
#define test_expression(expression) \
{ \
if(!(expression)) \
{ \
vtksys_ios::ostringstream buffer; \
buffer << "Expression failed at line " << __LINE__ << ": " << #expression; \
throw std::runtime_error(buffer.str()); \
} \
}
// Sample strings - nothing risque, I hope ...
static const vtkUnicodeString sample_utf8_ascii = vtkUnicodeString::from_utf8("abcde123");
static const vtkUnicodeString sample_utf8_greek = vtkUnicodeString::from_utf8("\xce\xb1\xce\xb2\xce\xb3"); // Greek lower-case alpha, beta, gamma.
static const vtkUnicodeString sample_utf8_thai = vtkUnicodeString::from_utf8("\xe0\xb8\x81\xe0\xb8\x82\xe0\xb8\x83"); // Thai ko kai, kho khai, kho khuat.
static const vtkUnicodeString sample_utf8_linear_b = vtkUnicodeString::from_utf8("\xf0\x90\x80\x80\xf0\x90\x80\x81\xf0\x90\x80\x82\xf0\x90\x80\x83\xf0\x90\x80\x84"); // Linear-B syllables a, e, i, o, u.
static const vtkUnicodeString sample_utf8_mixed = vtkUnicodeString::from_utf8("a\xce\xb1\xe0\xb8\x81\xf0\x90\x80\x80"); // a, alpha, ko kai, syllable-a.
int TestUnicodeStringArrayAPI(int, char*[])
{
try
{
vtkSmartPointer<vtkUnicodeStringArray> array = vtkSmartPointer<vtkUnicodeStringArray>::New();
test_expression(array->GetNumberOfTuples() == 0);
test_expression(array->GetDataType() == VTK_UNICODE_STRING);
test_expression(array->GetDataTypeSize() == 0);
test_expression(array->GetElementComponentSize() == 4);
test_expression(array->IsNumeric() == 0);
array->InsertNextValue(sample_utf8_ascii);
test_expression(array->GetNumberOfTuples() == 1);
test_expression((array->GetValue(0)) == sample_utf8_ascii);
array->InsertNextValue(vtkUnicodeString::from_utf8("foo"));
test_expression(array->GetNumberOfTuples() == 2);
test_expression(array->LookupValue(vtkUnicodeString::from_utf8("foo")) == 1);
test_expression(array->LookupValue(vtkUnicodeString::from_utf8("bar")) == -1);
return 0;
}
catch(std::exception& e)
{
cerr << e.what() << endl;
return 1;
}
}
<commit_msg>ENH: Improve code coverage for UnicodeStringArray<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: TestUnicodeStringArrayAPI.cxx
-------------------------------------------------------------------------
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.
-------------------------------------------------------------------------
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.
=========================================================================*/
#include <vtkSmartPointer.h>
#include <vtkUnicodeStringArray.h>
#include <vtkIdList.h>
#include <vtkDoubleArray.h>
#include <vtkVariant.h>
#include <vtkTestErrorObserver.h>
#include <vtksys/stl/iterator>
#include <vtksys/ios/iostream>
#include <vtksys/ios/sstream>
#include <vtksys/stl/stdexcept>
static int TestErrorsAndWarnings();
#define test_expression(expression) \
{ \
if(!(expression)) \
{ \
vtksys_ios::ostringstream buffer; \
buffer << "Expression failed at line " << __LINE__ << ": " << #expression; \
throw std::runtime_error(buffer.str()); \
} \
}
// Sample strings - nothing risque, I hope ...
static const vtkUnicodeString sample_utf8_ascii = vtkUnicodeString::from_utf8("abcde123");
static const vtkUnicodeString sample_utf8_greek = vtkUnicodeString::from_utf8("\xce\xb1\xce\xb2\xce\xb3"); // Greek lower-case alpha, beta, gamma.
static const vtkUnicodeString sample_utf8_thai = vtkUnicodeString::from_utf8("\xe0\xb8\x81\xe0\xb8\x82\xe0\xb8\x83"); // Thai ko kai, kho khai, kho khuat.
static const vtkUnicodeString sample_utf8_linear_b = vtkUnicodeString::from_utf8("\xf0\x90\x80\x80\xf0\x90\x80\x81\xf0\x90\x80\x82\xf0\x90\x80\x83\xf0\x90\x80\x84"); // Linear-B syllables a, e, i, o, u.
static const vtkUnicodeString sample_utf8_mixed = vtkUnicodeString::from_utf8("a\xce\xb1\xe0\xb8\x81\xf0\x90\x80\x80"); // a, alpha, ko kai, syllable-a.
int TestUnicodeStringArrayAPI(int, char*[])
{
try
{
vtkSmartPointer<vtkUnicodeStringArray> array =
vtkSmartPointer<vtkUnicodeStringArray>::New();
array->ClearLookup(); // noop
test_expression(array->GetNumberOfTuples() == 0);
test_expression(array->GetDataType() == VTK_UNICODE_STRING);
test_expression(array->GetDataTypeSize() == 0);
test_expression(array->GetElementComponentSize() == 4);
test_expression(array->IsNumeric() == 0);
array->InsertNextValue(sample_utf8_ascii);
test_expression(array->GetNumberOfTuples() == 1);
test_expression((array->GetValue(0)) == sample_utf8_ascii);
test_expression((array->GetVariantValue(0)) == sample_utf8_ascii);
array->InsertNextValue(vtkUnicodeString::from_utf8("foo"));
test_expression(array->GetNumberOfTuples() == 2);
test_expression(array->LookupValue(vtkUnicodeString::from_utf8("foo")) == 1);
test_expression(array->LookupValue(vtkUnicodeString::from_utf8("bar")) == -1);
vtkSmartPointer<vtkUnicodeStringArray> array2 =
vtkSmartPointer<vtkUnicodeStringArray>::New();
array2->SetNumberOfTuples(3);
array2->SetValue(2, sample_utf8_thai);
array2->SetValue(1, sample_utf8_greek);
array2->SetValue(0, sample_utf8_linear_b);
test_expression(array2->GetNumberOfTuples() == 3);
array2->InsertNextUTF8Value("bar");
test_expression(array2->GetNumberOfTuples() == 4);
array2->InsertValue(100, sample_utf8_ascii);
test_expression(array2->GetNumberOfTuples() == 101);
array2->SetVariantValue(100, "foo");
test_expression(array2->GetValue(100) == vtkUnicodeString::from_utf8("foo"));
array2->SetUTF8Value(100, "barfoo");
test_expression(strcmp(array2->GetUTF8Value(100), "barfoo") == 0);
array2->Initialize();
test_expression(array2->GetNumberOfTuples() == 0);
vtkSmartPointer<vtkUnicodeStringArray> array3 =
vtkSmartPointer<vtkUnicodeStringArray>::New();
void * ptr1 = array3->GetVoidPointer(0);
test_expression(ptr1 == NULL);
array3->InsertTuple(0, 1, array);
test_expression(array3->GetValue(0) == array->GetValue(1));
array3->InsertTuple(100, 1, array);
test_expression(array3->GetValue(100) == array->GetValue(1));
array3->InsertNextTuple(1, array);
test_expression(array3->GetValue(101) == array->GetValue(1));
array3->SetTuple(0, 0, array);
test_expression(array3->GetValue(0) == array->GetValue(0));
vtkSmartPointer<vtkIdList> toIds =
vtkSmartPointer<vtkIdList>::New();
vtkSmartPointer<vtkIdList> fromIds =
vtkSmartPointer<vtkIdList>::New();
fromIds->InsertId(0, 1);
fromIds->InsertId(1, 0);
toIds->InsertId(0, array3->GetNumberOfTuples() + 1);
toIds->InsertId(1, 1);
array3->InsertTuples(toIds, fromIds, array);
test_expression(array3->GetValue(array3->GetNumberOfTuples() - 1) == array->GetValue(1));
test_expression(array3->GetValue(1) == array->GetValue(0));
array3->InsertNextValue(vtkUnicodeString::from_utf8("foobar"));
array3->InsertNextValue(vtkUnicodeString::from_utf8("foobar"));
array3->InsertNextValue(vtkUnicodeString::from_utf8("foobar"));
vtkSmartPointer<vtkIdList> lookupIds =
vtkSmartPointer<vtkIdList>::New();
array3->LookupValue(vtkUnicodeString::from_utf8("foobar"), lookupIds);
test_expression(lookupIds->GetNumberOfIds() == 3);
array3->DeepCopy(NULL); // noop
array3->DeepCopy(array3); // noop
array3->DeepCopy(array);
test_expression(array3->GetActualMemorySize() == array->GetActualMemorySize());
vtkSmartPointer<vtkUnicodeStringArray> array4 =
vtkSmartPointer<vtkUnicodeStringArray>::New();
array4->InsertNextValue(vtkUnicodeString::from_utf8("array4_0"));
array4->InsertNextValue(vtkUnicodeString::from_utf8("array4_1"));
array4->InsertNextValue(vtkUnicodeString::from_utf8("array4_2"));
vtkSmartPointer<vtkUnicodeStringArray> array5 =
vtkSmartPointer<vtkUnicodeStringArray>::New();
array5->InsertNextValue(vtkUnicodeString::from_utf8("array5_0"));
array5->InsertNextValue(vtkUnicodeString::from_utf8("array5_1"));
array5->InsertNextValue(vtkUnicodeString::from_utf8("array5_2"));
array5->InsertNextValue(vtkUnicodeString::from_utf8("array5_3"));
vtkSmartPointer<vtkIdList> interpIds =
vtkSmartPointer<vtkIdList>::New();
array3->InterpolateTuple(5, interpIds, array4, NULL); // noop
interpIds->InsertId(0, 0);
interpIds->InsertId(1, 1);
interpIds->InsertId(2, 2);
double weights[3];
weights[0] = .2;
weights[1] = .8;
weights[2] = .5;
array3->InterpolateTuple(5, interpIds, array4, weights);
test_expression(array3->GetValue(5) == array4->GetValue(1));
array3->InterpolateTuple(0,
0, array4,
0, array5,
0.1);
test_expression(array3->GetValue(0) == array4->GetValue(0));
array3->InterpolateTuple(1,
0, array4,
0, array5,
0.6);
test_expression(array3->GetValue(1) == array5->GetValue(0));
array3->Squeeze();
test_expression(array3->GetValue(5) == array4->GetValue(1));
array3->Resize(20);
test_expression(array3->GetValue(5) == array4->GetValue(1));
array3->GetVoidPointer(0);
if (TestErrorsAndWarnings() != 0)
{
return EXIT_FAILURE;
}
array3->Print(std::cout);
return EXIT_SUCCESS;
}
catch(std::exception& e)
{
cerr << e.what() << endl;
return EXIT_FAILURE;
}
}
int TestErrorsAndWarnings()
{
int status = 0;
vtkSmartPointer<vtkTest::ErrorObserver> errorObserver =
vtkSmartPointer<vtkTest::ErrorObserver>::New();
vtkSmartPointer<vtkUnicodeStringArray> array =
vtkSmartPointer<vtkUnicodeStringArray>::New();
array->Allocate(100, 0);
array->AddObserver(vtkCommand::ErrorEvent, errorObserver);
array->AddObserver(vtkCommand::WarningEvent, errorObserver);
// ERROR: Not implmented
array->SetVoidArray(0, 1, 1);
if (errorObserver->GetError())
{
std::cout << "Caught expected error: "
<< errorObserver->GetErrorMessage();
}
else
{
std::cout << "Failed to catch expected 'Not implemented' error" << std::endl;
++status;
}
errorObserver->Clear();
// ERROR: Not implmented
array->NewIterator();
if (errorObserver->GetError())
{
std::cout << "Caught expected error: "
<< errorObserver->GetErrorMessage();
}
else
{
std::cout << "Failed to catch expected 'Not implemented' error" << std::endl;
++status;
}
errorObserver->Clear();
// Warning: Input and output array data types do not match.
vtkSmartPointer<vtkDoubleArray> doubleArray =
vtkSmartPointer<vtkDoubleArray>::New();
array->SetTuple(0, 0, doubleArray);
if (errorObserver->GetWarning())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetWarningMessage();
}
else
{
std::cout << "Failed to catch expected 'Input and output array data types do not match.' warning" << std::endl;
++status;
}
errorObserver->Clear();
// Warning: Input and output array data types do not match.
array->InsertTuple(0, 0, doubleArray);
if (errorObserver->GetWarning())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetWarningMessage();
}
else
{
std::cout << "Failed to catch expected 'Input and output array data types do not match.' warning" << std::endl;
++status;
}
errorObserver->Clear();
// Warning: Input and output array data types do not match.
array->InsertNextTuple(0, doubleArray);
if (errorObserver->GetWarning())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetWarningMessage();
}
else
{
std::cout << "Failed to catch expected 'Input and output array data types do not match.' warning" << std::endl;
++status;
}
errorObserver->Clear();
// Warning: Input and output array data types do not match.
array->DeepCopy(doubleArray);
if (errorObserver->GetWarning())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetWarningMessage();
}
else
{
std::cout << "Failed to catch expected 'Input and output array data types do not match.' warning" << std::endl;
++status;
}
errorObserver->Clear();
// Warning: Input and output array data types do not match.
vtkSmartPointer<vtkIdList> id1 =
vtkSmartPointer<vtkIdList>::New();
array->InsertTuples(id1, id1, doubleArray);
if (errorObserver->GetWarning())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetWarningMessage();
}
else
{
std::cout << "Failed to catch expected 'Input and output array data types do not match.' warning" << std::endl;
++status;
}
errorObserver->Clear();
// Warning: Input and output id array sizes do not match.
vtkSmartPointer<vtkIdList> id2 =
vtkSmartPointer<vtkIdList>::New();
id1->SetNumberOfIds(10);
id2->SetNumberOfIds(5);
array->InsertTuples(id1, id2, array);
if (errorObserver->GetWarning())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetWarningMessage();
}
else
{
std::cout << "Failed to catch expected 'Input and output id array sizes do not match.' warning" << std::endl;
++status;
}
errorObserver->Clear();
// ERROR: Cannot CopyValue from array of type
array->InterpolateTuple(0, id1, doubleArray, NULL);
if (errorObserver->GetError())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetErrorMessage();
}
else
{
std::cout << "Failed to catch expected 'Cannot CopyValue from array of type' error" << std::endl;
++status;
}
errorObserver->Clear();
// ERROR: All arrays to InterpolateValue() must be of same type.
array->InterpolateTuple(0,
0, doubleArray,
2, array,
0.0);
if (errorObserver->GetError())
{
std::cout << "Caught expected warning: "
<< errorObserver->GetErrorMessage();
}
else
{
std::cout << "Failed to catch expected 'All arrays to InterpolateValue() must be of same type.' error" << std::endl;
++status;
}
errorObserver->Clear();
return status;
}
<|endoftext|> |
<commit_before>
////using the C++ API
#include "zorba_api.h"
#include "store/naive/basic_item_factory.h"
#include "store/naive/simple_store.h"
//for debug
#include "compiler/parser/xquery_driver.h"
#include "util/logging/loggermanager.hh"
#include "timer.h"
#include "api/serialization/serializer.h"
#include <fstream>
using namespace xqp;
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
Timer timer;
timer.start();
xqp::LoggerManager::logmanager()->setLoggerConfig("#1#logging.log");
bool useResultFile = false, inline_query = false;
bool useSerializer = false;
std::string resultFileName;
std::ofstream* resultFile = NULL;
std::string query_text = "1+1";///the default query if no file or query is specified
///pick up all the runtime options
#ifdef UNICODE
#define TEST_ARGV_FLAG( str ) (_tcscmp(*argv, _T(str)) == 0)
#else
#define TEST_ARGV_FLAG( str ) (*argv == std::string (str))
#endif
for (++argv; argv[0]; ++argv)
{
const char *fname;
if (TEST_ARGV_FLAG ("-p")) {
g_trace_parsing = true;
} else if (TEST_ARGV_FLAG ("-s")) {
g_trace_scanning = true;
} else if (TEST_ARGV_FLAG ("-r")) {
useSerializer = true;
} else if (TEST_ARGV_FLAG ("-o")) {
useResultFile = true;
resultFileName = *++argv;
} else if (TEST_ARGV_FLAG ("-e")) {
inline_query = true;
} else {
fname = *argv;
#ifndef UNICODE
if (inline_query) {
// fname = "zorba_query.tmp";
// ofstream qf (fname);
// qf << *argv;
query_text = *argv;
}
#endif
#ifdef UNICODE
if(! inline_query)
{
char testfile[1024];
WideCharToMultiByte(CP_ACP, 0, // or CP_UTF8
*argv, -1,
testfile, sizeof(testfile)/sizeof(char),
NULL, NULL);
fname = testfile;
}
#endif
if(!inline_query)
{
///read the file
std::ifstream qfile(fname);
//istringstream iss;
qfile >> query_text;
}
}
}
///now start the zorba engine
BasicItemFactory basicItemFactory;
SimpleStore simpleStore;
ZorbaFactory zorba_factory(&basicItemFactory, &simpleStore);
///some workarounds until we have a store factory
basicItemFactory.addReference();
simpleStore.addReference();
///thread specific
zorba_factory.InitThread();
XQuery_t query;
query = zorba_factory.createQuery(query_text.c_str());
query->compile();
XQueryResult *result;
result = query->execute();
if(result)
{
if (useResultFile)
{
resultFile = new ofstream(resultFileName.c_str());
*resultFile << "Iterator run:" << std::endl << std::endl;
}
Item_t it;
if (useSerializer)
{
// *resultFile << i_p->show() << endl;
serializer* ser = new serializer();
ser->serialize(result, *resultFile);
*resultFile << endl;
}
else
{
while( true )
{
it = result->next();
if(it == NULL)
break;
if (resultFile != NULL)
*resultFile << it->show() << endl;
else
cout << it->show() << endl;
}
}
delete result;
}//if (result)
//delete query;
// zorba_factory.destroyQuery(query);
zorba_factory.UninitThread();
timer.end();
if (resultFile != NULL)
{
// *resultFile << std::endl;
// timer.print(*resultFile);
}
else
timer.print(cout);
delete resultFile;
}
<commit_msg>Fix for multiline xqueries<commit_after>
////using the C++ API
#include "zorba_api.h"
#include "store/naive/basic_item_factory.h"
#include "store/naive/simple_store.h"
//for debug
#include "compiler/parser/xquery_driver.h"
#include "util/logging/loggermanager.hh"
#include "timer.h"
#include "api/serialization/serializer.h"
#include <fstream>
using namespace xqp;
#ifndef _WIN32_WCE
int main(int argc, char* argv[])
#else
int _tmain(int argc, _TCHAR* argv[])
#endif
{
Timer timer;
timer.start();
xqp::LoggerManager::logmanager()->setLoggerConfig("#1#logging.log");
bool useResultFile = false, inline_query = false;
bool useSerializer = false;
std::string resultFileName;
std::ofstream* resultFile = NULL;
std::string query_text = "1+1";///the default query if no file or query is specified
///pick up all the runtime options
#ifdef UNICODE
#define TEST_ARGV_FLAG( str ) (_tcscmp(*argv, _T(str)) == 0)
#else
#define TEST_ARGV_FLAG( str ) (*argv == std::string (str))
#endif
for (++argv; argv[0]; ++argv)
{
const char *fname;
if (TEST_ARGV_FLAG ("-p")) {
g_trace_parsing = true;
} else if (TEST_ARGV_FLAG ("-s")) {
g_trace_scanning = true;
} else if (TEST_ARGV_FLAG ("-r")) {
useSerializer = true;
} else if (TEST_ARGV_FLAG ("-o")) {
useResultFile = true;
resultFileName = *++argv;
} else if (TEST_ARGV_FLAG ("-e")) {
inline_query = true;
} else {
fname = *argv;
#ifndef UNICODE
if (inline_query) {
// fname = "zorba_query.tmp";
// ofstream qf (fname);
// qf << *argv;
query_text = *argv;
}
#endif
#ifdef UNICODE
if(! inline_query)
{
char testfile[1024];
WideCharToMultiByte(CP_ACP, 0, // or CP_UTF8
*argv, -1,
testfile, sizeof(testfile)/sizeof(char),
NULL, NULL);
fname = testfile;
}
#endif
if(!inline_query)
{
///read the file
std::ifstream qfile(fname);
//istringstream iss;
string temp;
query_text = "";
// warning: this method of reading a file will trim the
// whitespace at the end of lines
while (qfile >> temp)
{
if (query_text != "")
query_text += "\n";
query_text += temp;
}
}
}
}
///now start the zorba engine
BasicItemFactory basicItemFactory;
SimpleStore simpleStore;
ZorbaFactory zorba_factory(&basicItemFactory, &simpleStore);
///some workarounds until we have a store factory
basicItemFactory.addReference();
simpleStore.addReference();
///thread specific
zorba_factory.InitThread();
XQuery_t query;
query = zorba_factory.createQuery(query_text.c_str());
query->compile();
XQueryResult *result;
result = query->execute();
if(result)
{
if (useResultFile)
{
resultFile = new ofstream(resultFileName.c_str());
*resultFile << "Iterator run:" << std::endl << std::endl;
}
Item_t it;
if (useSerializer)
{
// *resultFile << i_p->show() << endl;
serializer* ser = new serializer();
ser->serialize(result, *resultFile);
*resultFile << endl;
}
else
{
while( true )
{
it = result->next();
if(it == NULL)
break;
if (resultFile != NULL)
*resultFile << it->show() << endl;
else
cout << it->show() << endl;
}
}
delete result;
}//if (result)
//delete query;
// zorba_factory.destroyQuery(query);
zorba_factory.UninitThread();
timer.end();
if (resultFile != NULL)
{
// *resultFile << std::endl;
// timer.print(*resultFile);
}
else
timer.print(cout);
delete resultFile;
}
<|endoftext|> |
<commit_before>/************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2007 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*************** <auto-copyright.pl END do not edit this line> ***************/
// ---------------------------------------
// Performance Monitoring OpenGL sample application
//
// main.cpp
// --------------------------------------
#include <collideApp.h>
#include <vrj/Kernel/Kernel.h>
using namespace vrj;
int main(int argc, char* argv[])
{
Kernel* kernel = Kernel::instance();
collideApp* application = new collideApp();
if (argc <= 1)
{
std::cout << "\n\n";
std::cout << "Usage: " << argv[0] << "vjconfigfile[0] vjconfigfile[1] ... vjconfigfile[n] " << std::endl;
exit(1);
}
for (int i=1; i< argc; ++i)
{
kernel->loadConfigFile(argv[i]);
}
kernel->start();
kernel->setApplication(application);
kernel->waitForKernelStop();
delete application;
return 0;
}
<commit_msg>MFT r19996: When using Cocoa, it is not necessary to identify the configuration files to load on the command line. One of the fun thinks (at least in my opinion) about the way that I have put the Cocoa stuff together is that we can leverage run-time reconfiguration of VR Juggler and load config files through the application's built-in "File -> Open..." menu item.<commit_after>/************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2007 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
*************** <auto-copyright.pl END do not edit this line> ***************/
// ---------------------------------------
// Performance Monitoring OpenGL sample application
//
// main.cpp
// --------------------------------------
#include <collideApp.h>
#include <vrj/Kernel/Kernel.h>
using namespace vrj;
int main(int argc, char* argv[])
{
Kernel* kernel = Kernel::instance();
collideApp* application = new collideApp();
#if ! defined(VRJ_USE_COCOA)
if (argc <= 1)
{
std::cout << "\n\n";
std::cout << "Usage: " << argv[0] << "vjconfigfile[0] vjconfigfile[1] ... vjconfigfile[n] " << std::endl;
exit(1);
}
#endif
for (int i=1; i< argc; ++i)
{
kernel->loadConfigFile(argv[i]);
}
kernel->start();
kernel->setApplication(application);
kernel->waitForKernelStop();
delete application;
return 0;
}
<|endoftext|> |
<commit_before>/* TyTools - public domain
Niels Martignène <[email protected]>
https://koromix.dev/tytools
This software is in the public domain. Where that dedication is not
recognized, you are granted a perpetual, irrevocable license to copy,
distribute, and modify this file as you see fit.
See the LICENSE file for more details. */
#include <QApplication>
#include <QMessageBox>
#include <QTranslator>
#include "../libhs/common.h"
#include "../libty/common.h"
#include "../libty/class.h"
#include "../tycommander/log_dialog.hpp"
#include "../tycommander/monitor.hpp"
#include "tyupdater.hpp"
#include "updater_window.hpp"
#ifdef QT_STATIC
#include <QtPlugin>
#if defined(_WIN32)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
#elif defined(__APPLE__)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin)
#endif
#endif
using namespace std;
TyUpdater::TyUpdater(int &argc, char *argv[])
: QApplication(argc, argv)
{
setOrganizationName("ty");
setApplicationName(TY_CONFIG_TYUPDATER_NAME);
setApplicationVersion(ty_version_string());
ty_message_redirect([](const ty_message_data *msg, void *) {
ty_message_default_handler(msg, nullptr);
if (msg->type == TY_MESSAGE_LOG) {
if (msg->u.log.level <= TY_LOG_WARNING) {
tyUpdater->reportError(msg->u.log.msg, msg->ctx);
} else {
tyUpdater->reportDebug(msg->u.log.msg, msg->ctx);
}
}
}, nullptr);
log_dialog_ = unique_ptr<LogDialog>(new LogDialog());
log_dialog_->setAttribute(Qt::WA_QuitOnClose, false);
log_dialog_->setWindowIcon(QIcon(":/tyupdater"));
connect(this, &TyUpdater::globalError, log_dialog_.get(), &LogDialog::appendError);
connect(this, &TyUpdater::globalDebug, log_dialog_.get(), &LogDialog::appendDebug);
}
TyUpdater::~TyUpdater()
{
ty_message_redirect(ty_message_default_handler, nullptr);
}
void TyUpdater::showLogWindow()
{
log_dialog_->show();
}
void TyUpdater::reportError(const QString &msg, const QString &ctx)
{
emit globalError(msg, ctx);
}
void TyUpdater::reportDebug(const QString &msg, const QString &ctx)
{
emit globalDebug(msg, ctx);
}
int TyUpdater::exec()
{
return tyUpdater->run();
}
int TyUpdater::run()
{
monitor_.reset(new Monitor());
monitor_->setIgnoreGeneric(true);
monitor_->setSerialByDefault(false);
monitor_->setSerialLogSize(0);
if (!monitor_->start()) {
QMessageBox::critical(nullptr, tr("%1 (error)").arg(applicationName()),
ty_error_last_message());
return EXIT_FAILURE;
}
UpdaterWindow win;
win.show();
return QApplication::exec();
}
int main(int argc, char *argv[])
{
hs_log_set_handler(ty_libhs_log_handler, NULL);
qRegisterMetaType<ty_log_level>("ty_log_level");
qRegisterMetaType<std::shared_ptr<void>>("std::shared_ptr<void>");
qRegisterMetaType<ty_descriptor>("ty_descriptor");
qRegisterMetaType<uint64_t>("uint64_t");
TyUpdater app(argc, argv);
return app.exec();
}
<commit_msg>Fix broken Qt uxtheme integration on Win32 (TyUpdater)<commit_after>/* TyTools - public domain
Niels Martignène <[email protected]>
https://koromix.dev/tytools
This software is in the public domain. Where that dedication is not
recognized, you are granted a perpetual, irrevocable license to copy,
distribute, and modify this file as you see fit.
See the LICENSE file for more details. */
#include <QApplication>
#include <QMessageBox>
#include <QTranslator>
#include "../libhs/common.h"
#include "../libty/common.h"
#include "../libty/class.h"
#include "../tycommander/log_dialog.hpp"
#include "../tycommander/monitor.hpp"
#include "tyupdater.hpp"
#include "updater_window.hpp"
#ifdef QT_STATIC
#include <QtPlugin>
#if defined(_WIN32)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
Q_IMPORT_PLUGIN(QWindowsVistaStylePlugin)
#elif defined(__APPLE__)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin)
#endif
#endif
using namespace std;
TyUpdater::TyUpdater(int &argc, char *argv[])
: QApplication(argc, argv)
{
setOrganizationName("ty");
setApplicationName(TY_CONFIG_TYUPDATER_NAME);
setApplicationVersion(ty_version_string());
ty_message_redirect([](const ty_message_data *msg, void *) {
ty_message_default_handler(msg, nullptr);
if (msg->type == TY_MESSAGE_LOG) {
if (msg->u.log.level <= TY_LOG_WARNING) {
tyUpdater->reportError(msg->u.log.msg, msg->ctx);
} else {
tyUpdater->reportDebug(msg->u.log.msg, msg->ctx);
}
}
}, nullptr);
log_dialog_ = unique_ptr<LogDialog>(new LogDialog());
log_dialog_->setAttribute(Qt::WA_QuitOnClose, false);
log_dialog_->setWindowIcon(QIcon(":/tyupdater"));
connect(this, &TyUpdater::globalError, log_dialog_.get(), &LogDialog::appendError);
connect(this, &TyUpdater::globalDebug, log_dialog_.get(), &LogDialog::appendDebug);
}
TyUpdater::~TyUpdater()
{
ty_message_redirect(ty_message_default_handler, nullptr);
}
void TyUpdater::showLogWindow()
{
log_dialog_->show();
}
void TyUpdater::reportError(const QString &msg, const QString &ctx)
{
emit globalError(msg, ctx);
}
void TyUpdater::reportDebug(const QString &msg, const QString &ctx)
{
emit globalDebug(msg, ctx);
}
int TyUpdater::exec()
{
return tyUpdater->run();
}
int TyUpdater::run()
{
monitor_.reset(new Monitor());
monitor_->setIgnoreGeneric(true);
monitor_->setSerialByDefault(false);
monitor_->setSerialLogSize(0);
if (!monitor_->start()) {
QMessageBox::critical(nullptr, tr("%1 (error)").arg(applicationName()),
ty_error_last_message());
return EXIT_FAILURE;
}
UpdaterWindow win;
win.show();
return QApplication::exec();
}
int main(int argc, char *argv[])
{
hs_log_set_handler(ty_libhs_log_handler, NULL);
qRegisterMetaType<ty_log_level>("ty_log_level");
qRegisterMetaType<std::shared_ptr<void>>("std::shared_ptr<void>");
qRegisterMetaType<ty_descriptor>("ty_descriptor");
qRegisterMetaType<uint64_t>("uint64_t");
TyUpdater app(argc, argv);
return app.exec();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
/*
Parts of this code come from Konversation and are copyrighted to:
Copyright (C) 2002 Dario Abatianni <[email protected]>
Copyright (C) 2004 Peter Simonsson <[email protected]>
Copyright (C) 2006-2008 Eike Hein <[email protected]>
Copyright (C) 2004-2009 Eli Mackenzie <[email protected]>
*/
#include "irctextformat.h"
#include <QStringList>
#include <QRegExp>
#include <QHash>
#include "irc.h"
IRC_BEGIN_NAMESPACE
/*!
\file irctextformat.h
\brief #include <IrcTextFormat>
*/
/*!
\class IrcTextFormat irctextformat.h <IrcTextFormat>
\ingroup util
\brief Provides methods for text formatting.
IrcTextFormat is used to convert IRC-style formatted messages to either
plain text or HTML. When converting to plain text, the IRC-style formatting
(colors, bold, underline etc.) are simply stripped away. When converting
to HTML, the IRC-style formatting is converted to the corresponding HTML
formatting.
\code
IrcTextFormat format;
QString text = format.toPlainText(message);
format.setColorName(Irc::Red, "#ff3333");
format.setColorName(Irc::Green, "#33ff33");
format.setColorName(Irc::Blue, "#3333ff");
// ...
QString html = format.toHtml(message);
\endcode
\sa <a href="http://www.mirc.com/colors.html">mIRC colors</a>, <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color keyword names</a>
*/
class IrcTextFormatPrivate
{
public:
QString urlPattern;
QHash<int, QString> colors;
};
static QHash<int, QString>& irc_default_colors()
{
static QHash<int, QString> x;
if (x.isEmpty()) {
x.insert(Irc::White, QLatin1String("white"));
x.insert(Irc::Black, QLatin1String("black"));
x.insert(Irc::Blue, QLatin1String("navy"));
x.insert(Irc::Green, QLatin1String("green"));
x.insert(Irc::Red, QLatin1String("red"));
x.insert(Irc::Brown, QLatin1String("maroon"));
x.insert(Irc::Purple, QLatin1String("purple"));
x.insert(Irc::Orange, QLatin1String("olive"));
x.insert(Irc::Yellow, QLatin1String("yellow"));
x.insert(Irc::LightGreen, QLatin1String("lime"));
x.insert(Irc::Cyan, QLatin1String("teal"));
x.insert(Irc::LightCyan, QLatin1String("aqua"));
x.insert(Irc::LightBlue, QLatin1String("royalblue"));
x.insert(Irc::Pink, QLatin1String("fuchsia"));
x.insert(Irc::Gray, QLatin1String("gray"));
x.insert(Irc::LightGray, QLatin1String("lightgray"));
}
return x;
}
/*!
Constructs a new text format with \a parent.
*/
IrcTextFormat::IrcTextFormat(QObject* parent) : QObject(parent), d_ptr(new IrcTextFormatPrivate)
{
Q_D(IrcTextFormat);
d->urlPattern = QString("\\b((?:(?:([a-z][\\w\\.-]+:/{1,3})|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|\\}\\]|[^\\s`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6])|[a-z0-9.\\-+_]+@[a-z0-9.\\-]+[.][a-z]{1,5}[^\\s/`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6]))").arg(QChar(0x00AB)).arg(QChar(0x00BB)).arg(QChar(0x201C)).arg(QChar(0x201D)).arg(QChar(0x2018)).arg(QChar(0x2019));
d->colors = irc_default_colors();
}
/*!
Destructs the text format.
*/
IrcTextFormat::~IrcTextFormat()
{
}
/*!
This property holds the regular expression pattern used for matching URLs.
\par Access functions:
\li QString <b>urlPattern</b>() const
\li void <b>setUrlPattern</b>(const QString& pattern)
*/
QString IrcTextFormat::urlPattern() const
{
Q_D(const IrcTextFormat);
return d->urlPattern;
}
void IrcTextFormat::setUrlPattern(const QString& pattern)
{
Q_D(IrcTextFormat);
d->urlPattern = pattern;
}
/*!
Converts a \a color code to a color name. If the \a color code
is unknown, the function returns the \a fallback color name.
\sa setColorName()
*/
QString IrcTextFormat::colorName(int color, const QString& fallback) const
{
Q_D(const IrcTextFormat);
return d->colors.value(color, fallback);
}
/*!
Assigns a \a name for \a color code.
The color \a name may be in one of these formats:
\li #RGB (each of R, G, and B is a single hex digit)
\li #RRGGBB
\li #RRRGGGBBB
\li #RRRRGGGGBBBB
\li A name from the list of colors defined in the list of <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color keyword names</a>
provided by the World Wide Web Consortium; for example, "steelblue" or "gainsboro". These color names work on all platforms. Note that these
color names are not the same as defined by the Qt::GlobalColor enums, e.g. "green" and Qt::green does not refer to the same color.
\li transparent - representing the absence of a color.
\sa colorName(), QColor::setNamedColor()
*/
void IrcTextFormat::setColorName(int color, const QString& name)
{
Q_D(IrcTextFormat);
d->colors.insert(color, name);
}
static bool parseColors(const QString& message, int pos, int* len, int* fg = 0, int* bg = 0)
{
// fg(,bg)
*len = 0;
if (fg)
*fg = -1;
if (bg)
*bg = -1;
QRegExp rx(QLatin1String("(\\d{1,2})(?:,(\\d{1,2}))?"));
int idx = rx.indexIn(message, pos);
if (idx == pos) {
*len = rx.matchedLength();
if (fg)
*fg = rx.cap(1).toInt();
if (bg) {
bool ok = false;
int tmp = rx.cap(2).toInt(&ok);
if (ok)
*bg = tmp;
}
}
return *len > 0;
}
/*!
Converts \a text to HTML. This function parses the text and replaces
IRC-style formatting (colors, bold, underline etc.) to the corresponding
HTML formatting. Furthermore, this function detects URLs and replaces
them with appropriate HTML hyperlinks.
\note URL detection can be disabled by setting an empty
regular expression pattern used for matching URLs.
\sa palette, urlPattern, toPlainText()
*/
QString IrcTextFormat::toHtml(const QString& text) const
{
Q_D(const IrcTextFormat);
QString processed = text;
// TODO:
//processed.replace(QLatin1Char('&'), QLatin1String("&"));
processed.replace(QLatin1Char('<'), QLatin1String("<"));
//processed.replace(QLatin1Char('>'), QLatin1String(">"));
//processed.replace(QLatin1Char('"'), QLatin1String("""));
//processed.replace(QLatin1Char('\''), QLatin1String("'"));
//processed.replace(QLatin1Char('\t'), QLatin1String(" "));
enum {
None = 0x0,
Bold = 0x1,
Italic = 0x4,
StrikeThrough = 0x8,
Underline = 0x10,
Inverse = 0x20
};
int state = None;
int pos = 0;
int len = 0;
int fg = -1;
int bg = -1;
int depth = 0;
bool potentialUrl = false;
while (pos < processed.size()) {
QString replacement;
switch (processed.at(pos).unicode()) {
case '\x02': // bold
if (state & Bold) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='font-weight: bold'>");
}
state ^= Bold;
break;
case '\x03': // color
if (parseColors(processed, pos + 1, &len, &fg, &bg)) {
depth++;
QStringList styles;
styles += QString(QLatin1String("color:%1")).arg(colorName(fg, QLatin1String("black")));
if (bg != -1)
styles += QString(QLatin1String("background-color:%1")).arg(colorName(bg, QLatin1String("transparent")));
replacement = QString(QLatin1String("<span style='%1'>")).arg(styles.join(QLatin1String(";")));
// \x03FF(,BB)
processed.replace(pos, len + 1, replacement);
pos += replacement.length();
continue;
} else {
depth--;
replacement = QLatin1String("</span>");
}
break;
//case '\x09': // italic
case '\x1d': // italic
if (state & Italic) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='font-style: italic'>");
}
state ^= Italic;
break;
case '\x13': // strike-through
if (state & StrikeThrough) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='text-decoration: line-through'>");
}
state ^= StrikeThrough;
break;
case '\x15': // underline
case '\x1f': // underline
if (state & Underline) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='text-decoration: underline'>");
}
state ^= Underline;
break;
case '\x16': // inverse
if (state & Inverse) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='font-weight: bold'>");
}
state ^= Inverse;
break;
case '\x0f': // none
if (depth > 0)
replacement = QString(QLatin1String("</span>")).repeated(depth);
else
processed.remove(pos--, 1); // must rewind back for ++pos below...
state = None;
depth = 0;
break;
case '.':
case '/':
case ':':
// a dot, slash or colon NOT surrounded by a space indicates a potential URL
if (!potentialUrl && pos > 0 && !processed.at(pos - 1).isSpace()
&& pos < processed.length() - 1 && !processed.at(pos + 1).isSpace())
potentialUrl = true;
break;
default:
break;
}
if (!replacement.isEmpty()) {
processed.replace(pos, 1, replacement);
pos += replacement.length();
} else {
++pos;
}
}
if (potentialUrl && !d->urlPattern.isEmpty()) {
pos = 0;
QRegExp rx(d->urlPattern);
while ((pos = rx.indexIn(processed, pos)) >= 0) {
int len = rx.matchedLength();
QString href = processed.mid(pos, len);
QString protocol;
if (rx.cap(2).isEmpty())
{
if (rx.cap(1).contains(QLatin1Char('@')))
protocol = QLatin1String("mailto:");
else if (rx.cap(1).startsWith(QLatin1String("ftp."), Qt::CaseInsensitive))
protocol = QLatin1String("ftp://");
else
protocol = QLatin1String("http://");
}
QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, href, href);
processed.replace(pos, len, link);
pos += link.length();
}
}
return processed;
}
/*!
Converts \a text to plain text. This function parses the text and
strips away IRC-style formatting (colors, bold, underline etc.)
\sa toHtml()
*/
QString IrcTextFormat::toPlainText(const QString& text) const
{
QString processed = text;
int pos = 0;
int len = 0;
while (pos < processed.size()) {
switch (processed.at(pos).unicode()) {
case '\x02': // bold
case '\x0f': // none
case '\x13': // strike-through
case '\x15': // underline
case '\x16': // inverse
case '\x1d': // italic
case '\x1f': // underline
processed.remove(pos, 1);
break;
case '\x03': // color
if (parseColors(processed, pos + 1, &len))
processed.remove(pos, len + 1);
else
processed.remove(pos, 1);
break;
default:
++pos;
break;
}
}
return processed;
}
#include "moc_irctextformat.cpp"
IRC_END_NAMESPACE
<commit_msg>IrcTextFormat: fix ftp links<commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*/
/*
Parts of this code come from Konversation and are copyrighted to:
Copyright (C) 2002 Dario Abatianni <[email protected]>
Copyright (C) 2004 Peter Simonsson <[email protected]>
Copyright (C) 2006-2008 Eike Hein <[email protected]>
Copyright (C) 2004-2009 Eli Mackenzie <[email protected]>
*/
#include "irctextformat.h"
#include <QStringList>
#include <QRegExp>
#include <QHash>
#include "irc.h"
IRC_BEGIN_NAMESPACE
/*!
\file irctextformat.h
\brief #include <IrcTextFormat>
*/
/*!
\class IrcTextFormat irctextformat.h <IrcTextFormat>
\ingroup util
\brief Provides methods for text formatting.
IrcTextFormat is used to convert IRC-style formatted messages to either
plain text or HTML. When converting to plain text, the IRC-style formatting
(colors, bold, underline etc.) are simply stripped away. When converting
to HTML, the IRC-style formatting is converted to the corresponding HTML
formatting.
\code
IrcTextFormat format;
QString text = format.toPlainText(message);
format.setColorName(Irc::Red, "#ff3333");
format.setColorName(Irc::Green, "#33ff33");
format.setColorName(Irc::Blue, "#3333ff");
// ...
QString html = format.toHtml(message);
\endcode
\sa <a href="http://www.mirc.com/colors.html">mIRC colors</a>, <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color keyword names</a>
*/
class IrcTextFormatPrivate
{
public:
QString urlPattern;
QHash<int, QString> colors;
};
static QHash<int, QString>& irc_default_colors()
{
static QHash<int, QString> x;
if (x.isEmpty()) {
x.insert(Irc::White, QLatin1String("white"));
x.insert(Irc::Black, QLatin1String("black"));
x.insert(Irc::Blue, QLatin1String("navy"));
x.insert(Irc::Green, QLatin1String("green"));
x.insert(Irc::Red, QLatin1String("red"));
x.insert(Irc::Brown, QLatin1String("maroon"));
x.insert(Irc::Purple, QLatin1String("purple"));
x.insert(Irc::Orange, QLatin1String("olive"));
x.insert(Irc::Yellow, QLatin1String("yellow"));
x.insert(Irc::LightGreen, QLatin1String("lime"));
x.insert(Irc::Cyan, QLatin1String("teal"));
x.insert(Irc::LightCyan, QLatin1String("aqua"));
x.insert(Irc::LightBlue, QLatin1String("royalblue"));
x.insert(Irc::Pink, QLatin1String("fuchsia"));
x.insert(Irc::Gray, QLatin1String("gray"));
x.insert(Irc::LightGray, QLatin1String("lightgray"));
}
return x;
}
/*!
Constructs a new text format with \a parent.
*/
IrcTextFormat::IrcTextFormat(QObject* parent) : QObject(parent), d_ptr(new IrcTextFormatPrivate)
{
Q_D(IrcTextFormat);
d->urlPattern = QString("\\b((?:(?:([a-z][\\w\\.-]+:/{1,3})|www|ftp\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|\\}\\]|[^\\s`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6])|[a-z0-9.\\-+_]+@[a-z0-9.\\-]+[.][a-z]{1,5}[^\\s/`!()\\[\\]{};:'\".,<>?%1%2%3%4%5%6]))").arg(QChar(0x00AB)).arg(QChar(0x00BB)).arg(QChar(0x201C)).arg(QChar(0x201D)).arg(QChar(0x2018)).arg(QChar(0x2019));
d->colors = irc_default_colors();
}
/*!
Destructs the text format.
*/
IrcTextFormat::~IrcTextFormat()
{
}
/*!
This property holds the regular expression pattern used for matching URLs.
\par Access functions:
\li QString <b>urlPattern</b>() const
\li void <b>setUrlPattern</b>(const QString& pattern)
*/
QString IrcTextFormat::urlPattern() const
{
Q_D(const IrcTextFormat);
return d->urlPattern;
}
void IrcTextFormat::setUrlPattern(const QString& pattern)
{
Q_D(IrcTextFormat);
d->urlPattern = pattern;
}
/*!
Converts a \a color code to a color name. If the \a color code
is unknown, the function returns the \a fallback color name.
\sa setColorName()
*/
QString IrcTextFormat::colorName(int color, const QString& fallback) const
{
Q_D(const IrcTextFormat);
return d->colors.value(color, fallback);
}
/*!
Assigns a \a name for \a color code.
The color \a name may be in one of these formats:
\li #RGB (each of R, G, and B is a single hex digit)
\li #RRGGBB
\li #RRRGGGBBB
\li #RRRRGGGGBBBB
\li A name from the list of colors defined in the list of <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color keyword names</a>
provided by the World Wide Web Consortium; for example, "steelblue" or "gainsboro". These color names work on all platforms. Note that these
color names are not the same as defined by the Qt::GlobalColor enums, e.g. "green" and Qt::green does not refer to the same color.
\li transparent - representing the absence of a color.
\sa colorName(), QColor::setNamedColor()
*/
void IrcTextFormat::setColorName(int color, const QString& name)
{
Q_D(IrcTextFormat);
d->colors.insert(color, name);
}
static bool parseColors(const QString& message, int pos, int* len, int* fg = 0, int* bg = 0)
{
// fg(,bg)
*len = 0;
if (fg)
*fg = -1;
if (bg)
*bg = -1;
QRegExp rx(QLatin1String("(\\d{1,2})(?:,(\\d{1,2}))?"));
int idx = rx.indexIn(message, pos);
if (idx == pos) {
*len = rx.matchedLength();
if (fg)
*fg = rx.cap(1).toInt();
if (bg) {
bool ok = false;
int tmp = rx.cap(2).toInt(&ok);
if (ok)
*bg = tmp;
}
}
return *len > 0;
}
/*!
Converts \a text to HTML. This function parses the text and replaces
IRC-style formatting (colors, bold, underline etc.) to the corresponding
HTML formatting. Furthermore, this function detects URLs and replaces
them with appropriate HTML hyperlinks.
\note URL detection can be disabled by setting an empty
regular expression pattern used for matching URLs.
\sa palette, urlPattern, toPlainText()
*/
QString IrcTextFormat::toHtml(const QString& text) const
{
Q_D(const IrcTextFormat);
QString processed = text;
// TODO:
//processed.replace(QLatin1Char('&'), QLatin1String("&"));
processed.replace(QLatin1Char('<'), QLatin1String("<"));
//processed.replace(QLatin1Char('>'), QLatin1String(">"));
//processed.replace(QLatin1Char('"'), QLatin1String("""));
//processed.replace(QLatin1Char('\''), QLatin1String("'"));
//processed.replace(QLatin1Char('\t'), QLatin1String(" "));
enum {
None = 0x0,
Bold = 0x1,
Italic = 0x4,
StrikeThrough = 0x8,
Underline = 0x10,
Inverse = 0x20
};
int state = None;
int pos = 0;
int len = 0;
int fg = -1;
int bg = -1;
int depth = 0;
bool potentialUrl = false;
while (pos < processed.size()) {
QString replacement;
switch (processed.at(pos).unicode()) {
case '\x02': // bold
if (state & Bold) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='font-weight: bold'>");
}
state ^= Bold;
break;
case '\x03': // color
if (parseColors(processed, pos + 1, &len, &fg, &bg)) {
depth++;
QStringList styles;
styles += QString(QLatin1String("color:%1")).arg(colorName(fg, QLatin1String("black")));
if (bg != -1)
styles += QString(QLatin1String("background-color:%1")).arg(colorName(bg, QLatin1String("transparent")));
replacement = QString(QLatin1String("<span style='%1'>")).arg(styles.join(QLatin1String(";")));
// \x03FF(,BB)
processed.replace(pos, len + 1, replacement);
pos += replacement.length();
continue;
} else {
depth--;
replacement = QLatin1String("</span>");
}
break;
//case '\x09': // italic
case '\x1d': // italic
if (state & Italic) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='font-style: italic'>");
}
state ^= Italic;
break;
case '\x13': // strike-through
if (state & StrikeThrough) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='text-decoration: line-through'>");
}
state ^= StrikeThrough;
break;
case '\x15': // underline
case '\x1f': // underline
if (state & Underline) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='text-decoration: underline'>");
}
state ^= Underline;
break;
case '\x16': // inverse
if (state & Inverse) {
depth--;
replacement = QLatin1String("</span>");
} else {
depth++;
replacement = QLatin1String("<span style='font-weight: bold'>");
}
state ^= Inverse;
break;
case '\x0f': // none
if (depth > 0)
replacement = QString(QLatin1String("</span>")).repeated(depth);
else
processed.remove(pos--, 1); // must rewind back for ++pos below...
state = None;
depth = 0;
break;
case '.':
case '/':
case ':':
// a dot, slash or colon NOT surrounded by a space indicates a potential URL
if (!potentialUrl && pos > 0 && !processed.at(pos - 1).isSpace()
&& pos < processed.length() - 1 && !processed.at(pos + 1).isSpace())
potentialUrl = true;
break;
default:
break;
}
if (!replacement.isEmpty()) {
processed.replace(pos, 1, replacement);
pos += replacement.length();
} else {
++pos;
}
}
if (potentialUrl && !d->urlPattern.isEmpty()) {
pos = 0;
QRegExp rx(d->urlPattern);
while ((pos = rx.indexIn(processed, pos)) >= 0) {
int len = rx.matchedLength();
QString href = processed.mid(pos, len);
QString protocol;
if (rx.cap(2).isEmpty())
{
if (rx.cap(1).contains(QLatin1Char('@')))
protocol = QLatin1String("mailto:");
else if (rx.cap(1).startsWith(QLatin1String("ftp."), Qt::CaseInsensitive))
protocol = QLatin1String("ftp://");
else
protocol = QLatin1String("http://");
}
QString link = QString(QLatin1String("<a href='%1%2'>%3</a>")).arg(protocol, href, href);
processed.replace(pos, len, link);
pos += link.length();
}
}
return processed;
}
/*!
Converts \a text to plain text. This function parses the text and
strips away IRC-style formatting (colors, bold, underline etc.)
\sa toHtml()
*/
QString IrcTextFormat::toPlainText(const QString& text) const
{
QString processed = text;
int pos = 0;
int len = 0;
while (pos < processed.size()) {
switch (processed.at(pos).unicode()) {
case '\x02': // bold
case '\x0f': // none
case '\x13': // strike-through
case '\x15': // underline
case '\x16': // inverse
case '\x1d': // italic
case '\x1f': // underline
processed.remove(pos, 1);
break;
case '\x03': // color
if (parseColors(processed, pos + 1, &len))
processed.remove(pos, len + 1);
else
processed.remove(pos, 1);
break;
default:
++pos;
break;
}
}
return processed;
}
#include "moc_irctextformat.cpp"
IRC_END_NAMESPACE
<|endoftext|> |
<commit_before>#pragma once
#include <math.h>
// base vector struct
template <int n> struct Vec {
float v[n];
float& operator[]( const int i ) {
return this->v[i];
}
const float& operator[]( const int i ) const {
return this->v[i];
}
};
typedef Vec<2> Vec2;
typedef Vec<3> Vec3;
typedef Vec<4> Vec4;
// specialized definitions for Vec2, Vec3, and Vec4
template<> struct Vec<2> {
union {
float v[2];
struct { float x, y; };
struct { float r, g; };
};
Vec( float _x, float _y )
: x( _x ) , y( _y ) {}
Vec()
: x( 0 ), y ( 0 ) {}
float& operator[]( const int i ) {
return this->v[i];
}
const float& operator[]( const int i ) const {
return this->v[i];
}
};
template<> struct Vec<3> {
union {
float v[3];
struct { float x, y, z; };
struct { float r, g, b; };
Vec<2> xy;
};
Vec( float _x, float _y, float _z )
: x( _x ), y( _y ), z( _z ) {}
Vec()
: x( 0 ), y( 0 ), z( 0 ) {}
float& operator[]( const int i ) {
return this->v[i];
}
const float& operator[]( const int i ) const {
return this->v[i];
}
};
template<> struct Vec<4> {
union {
float v[4];
struct { float x, y, z, w; };
struct { float r, g, b, a; };
Vec<2> xy;
Vec<3> xyz;
Vec<3> rgb;
};
Vec( float _x, float _y, float _z, float _w )
: x( _x ), y( _y ), z( _z ), w( _w ) {}
Vec()
: x( 0 ), y( 0 ), z( 0 ), w( 1 ) {}
float& operator[]( const int i ) {
return this->v[i];
}
const float& operator[]( const int i ) const {
return this->v[i];
}
};
// generic operators
template <int n> Vec<n> operator+ ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator+= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator- ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator-= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator* ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator*= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator* ( const Vec<n> lhs , const float rhs );
template <int n> Vec<n>& operator*= ( Vec<n>& lhs , const float rhs );
template <int n> Vec<n> operator* ( const float lhs , const Vec<n> rhs );
template <int n> Vec<n> operator/ ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator/= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator/ ( const Vec<n> lhs , const float rhs );
template <int n> Vec<n> operator/= ( Vec<n>& lhs , const float rhs );
// vector-specific operations
template <int n> float dot ( const Vec<n> lhs, const Vec<n> rhs );
template <int n> Vec<n> cross ( const Vec<n> lhs, const Vec<n> rhs );
template <int n> float cross2D ( const Vec<n> lhs, const Vec<n> rhs ); // only for vec2s
template <int n> float lengthsq ( const Vec<n> in );
template <int n> float length ( const Vec<n> in );
template <int n> Vec<n> normalize ( const Vec<n> in );
// free-floating constructors
template <int n> Vec<n> zero ();
// generic operator definitions
template <int n>
Vec<n> operator+ ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> sum;
for ( int i = 0; i < n; i++ ) {
sum[i] = lhs[i] + rhs[i];
}
return sum;
}
template <int n>
Vec<n>& operator+= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] += rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator- ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> difference;
for ( int i = 0; i < n; i++ ) {
difference[i] = lhs[i] - rhs[i];
}
return difference;
}
template <int n>
Vec<n>& operator-= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] -= rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator* ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> product;
for ( int i = 0; i < n; i++ ) {
product[i] = lhs[i] * rhs[i];
}
return product;
}
template <int n>
Vec<n>& operator*= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] *= rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator* ( const Vec<n> lhs, const float rhs ) {
Vec<n> scaled;
for ( int i = 0; i < n; i++ ) {
scaled[i] = lhs[i] * rhs;
}
return scaled;
}
template <int n>
Vec<n>& operator*= ( Vec<n>& lhs, const float rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] *= rhs;
}
return lhs;
}
template <int n>
Vec<n> operator* ( const float lhs, const Vec<n> rhs ) {
return operator*( rhs, lhs );
}
template <int n>
Vec<n> operator/ ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> quotient;
for ( int i = 0; i < n; i++ ) {
quotient[i] = lhs[i] / rhs[i];
}
return quotient;
}
template <int n>
Vec<n>& operator/= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] /= rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator/ ( const Vec<n> lhs, const float rhs ) {
Vec<n> scaled;
for ( int i = 0; i < n; i++ ) {
scaled[i] = lhs[i] / rhs;
}
return scaled;
}
template <int n>
Vec<n> operator/= ( Vec<n>& lhs, const float rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] /= rhs;
}
return lhs;
}
template <int n>
float dot( const Vec<n> lhs, const Vec<n> rhs ) {
float dp = 0.f;
for ( int i = 0; i < n; i++ ) {
dp += lhs[i] * rhs[i];
}
return dp;
}
template <int n>
float lengthsq( const Vec<n> in ) {
float sum = 0.f;
for ( int i = 0; i < n; i++ ) {
sum += in[i] * in[i];
}
return sum;
}
template <int n>
float length( const Vec<n> in ) {
return sqrt( lengthsq( in ) );
}
template <int n>
Vec<n> normalize( const Vec<n> in ) {
return in / length( in );
}
template <int n>
Vec<n> cross( const Vec<n> lhs, const Vec<n> rhs ) {
static_assert( n == 3, "cross only defined for Vec<3>!" );
return { lhs[1] * rhs[2] - lhs[2] * rhs[1]
, lhs[2] * rhs[0] - lhs[0] * rhs[2]
, lhs[0] * rhs[1] - lhs[1] * rhs[0] };
}
template <int n>
float cross2D( const Vec<n> lhs, const Vec<n> rhs ) {
static_assert( n == 2, "cross2D only defined for Vec<2>!" );
return lhs[0] * rhs[1] - lhs[1] * rhs[0];
}
template <int n>
Vec<n> zero() {
Vec<n> out;
for ( int i = 0; i < n; i++ ) {
out[i] = 0;
}
return out;
}
<commit_msg>add u/v accessors to Vec2<commit_after>#pragma once
#include <math.h>
// base vector struct
template <int n> struct Vec {
float v[n];
float& operator[]( const int i ) {
return this->v[i];
}
const float& operator[]( const int i ) const {
return this->v[i];
}
};
typedef Vec<2> Vec2;
typedef Vec<3> Vec3;
typedef Vec<4> Vec4;
// specialized definitions for Vec2, Vec3, and Vec4
template<> struct Vec<2> {
union {
float vals[2];
struct { float x, y; };
struct { float r, g; };
struct { float u, v; };
};
Vec( float _x, float _y )
: x( _x ) , y( _y ) {}
Vec()
: x( 0 ), y ( 0 ) {}
float& operator[]( const int i ) {
return this->vals[i];
}
const float& operator[]( const int i ) const {
return this->vals[i];
}
};
template<> struct Vec<3> {
union {
float v[3];
struct { float x, y, z; };
struct { float r, g, b; };
Vec<2> xy;
};
Vec( float _x, float _y, float _z )
: x( _x ), y( _y ), z( _z ) {}
Vec()
: x( 0 ), y( 0 ), z( 0 ) {}
float& operator[]( const int i ) {
return this->v[i];
}
const float& operator[]( const int i ) const {
return this->v[i];
}
};
template<> struct Vec<4> {
union {
float v[4];
struct { float x, y, z, w; };
struct { float r, g, b, a; };
Vec<2> xy;
Vec<3> xyz;
Vec<3> rgb;
};
Vec( float _x, float _y, float _z, float _w )
: x( _x ), y( _y ), z( _z ), w( _w ) {}
Vec()
: x( 0 ), y( 0 ), z( 0 ), w( 1 ) {}
float& operator[]( const int i ) {
return this->v[i];
}
const float& operator[]( const int i ) const {
return this->v[i];
}
};
// generic operators
template <int n> Vec<n> operator+ ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator+= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator- ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator-= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator* ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator*= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator* ( const Vec<n> lhs , const float rhs );
template <int n> Vec<n>& operator*= ( Vec<n>& lhs , const float rhs );
template <int n> Vec<n> operator* ( const float lhs , const Vec<n> rhs );
template <int n> Vec<n> operator/ ( const Vec<n> lhs , const Vec<n> rhs );
template <int n> Vec<n>& operator/= ( Vec<n>& lhs , const Vec<n> rhs );
template <int n> Vec<n> operator/ ( const Vec<n> lhs , const float rhs );
template <int n> Vec<n> operator/= ( Vec<n>& lhs , const float rhs );
// vector-specific operations
template <int n> float dot ( const Vec<n> lhs, const Vec<n> rhs );
template <int n> Vec<n> cross ( const Vec<n> lhs, const Vec<n> rhs );
template <int n> float cross2D ( const Vec<n> lhs, const Vec<n> rhs ); // only for vec2s
template <int n> float lengthsq ( const Vec<n> in );
template <int n> float length ( const Vec<n> in );
template <int n> Vec<n> normalize ( const Vec<n> in );
// free-floating constructors
template <int n> Vec<n> zero ();
// generic operator definitions
template <int n>
Vec<n> operator+ ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> sum;
for ( int i = 0; i < n; i++ ) {
sum[i] = lhs[i] + rhs[i];
}
return sum;
}
template <int n>
Vec<n>& operator+= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] += rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator- ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> difference;
for ( int i = 0; i < n; i++ ) {
difference[i] = lhs[i] - rhs[i];
}
return difference;
}
template <int n>
Vec<n>& operator-= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] -= rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator* ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> product;
for ( int i = 0; i < n; i++ ) {
product[i] = lhs[i] * rhs[i];
}
return product;
}
template <int n>
Vec<n>& operator*= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] *= rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator* ( const Vec<n> lhs, const float rhs ) {
Vec<n> scaled;
for ( int i = 0; i < n; i++ ) {
scaled[i] = lhs[i] * rhs;
}
return scaled;
}
template <int n>
Vec<n>& operator*= ( Vec<n>& lhs, const float rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] *= rhs;
}
return lhs;
}
template <int n>
Vec<n> operator* ( const float lhs, const Vec<n> rhs ) {
return operator*( rhs, lhs );
}
template <int n>
Vec<n> operator/ ( const Vec<n> lhs, const Vec<n> rhs ) {
Vec<n> quotient;
for ( int i = 0; i < n; i++ ) {
quotient[i] = lhs[i] / rhs[i];
}
return quotient;
}
template <int n>
Vec<n>& operator/= ( Vec<n>& lhs, const Vec<n> rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] /= rhs[i];
}
return lhs;
}
template <int n>
Vec<n> operator/ ( const Vec<n> lhs, const float rhs ) {
Vec<n> scaled;
for ( int i = 0; i < n; i++ ) {
scaled[i] = lhs[i] / rhs;
}
return scaled;
}
template <int n>
Vec<n> operator/= ( Vec<n>& lhs, const float rhs ) {
for ( int i = 0; i < n; i++ ) {
lhs[i] /= rhs;
}
return lhs;
}
template <int n>
float dot( const Vec<n> lhs, const Vec<n> rhs ) {
float dp = 0.f;
for ( int i = 0; i < n; i++ ) {
dp += lhs[i] * rhs[i];
}
return dp;
}
template <int n>
float lengthsq( const Vec<n> in ) {
float sum = 0.f;
for ( int i = 0; i < n; i++ ) {
sum += in[i] * in[i];
}
return sum;
}
template <int n>
float length( const Vec<n> in ) {
return sqrt( lengthsq( in ) );
}
template <int n>
Vec<n> normalize( const Vec<n> in ) {
return in / length( in );
}
template <int n>
Vec<n> cross( const Vec<n> lhs, const Vec<n> rhs ) {
static_assert( n == 3, "cross only defined for Vec<3>!" );
return { lhs[1] * rhs[2] - lhs[2] * rhs[1]
, lhs[2] * rhs[0] - lhs[0] * rhs[2]
, lhs[0] * rhs[1] - lhs[1] * rhs[0] };
}
template <int n>
float cross2D( const Vec<n> lhs, const Vec<n> rhs ) {
static_assert( n == 2, "cross2D only defined for Vec<2>!" );
return lhs[0] * rhs[1] - lhs[1] * rhs[0];
}
template <int n>
Vec<n> zero() {
Vec<n> out;
for ( int i = 0; i < n; i++ ) {
out[i] = 0;
}
return out;
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud.h>
#include <math.h>
static const float tol = 0.000000000000001f;
double magnitude(double vec[3]){
return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
}
void normalize(double vec[3]){
float m = magnitude(vec);
if(tol >= m) m = 1;
vec[0] /= m;
vec[1] /= m;
vec[2] /= m;
if(fabs(vec[0]) < tol) vec[0] = 0.0f;
if(fabs(vec[1]) < tol) vec[1] = 0.0f;
if(fabs(vec[2]) < tol) vec[2] = 0.0f;
}
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("slam_cloud", 10, &ArtificialPotentialField::obstacleCallback, this))
{
for(int i=0; i < 3; i++) obs_[i] = 0;
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double A = 0;
const double B = 3;
const double n = 1;
const double m = 1.5;
const double force = 0.025;
while(ros::ok()){
double Fs[3];
Fs[0] = Fs[1] = Fs[2] = 0;
double f_in[3];
get_potential_force(obs_, f_in, 0, 3, 1, 1.5);
Fs[0] += f_in[0];
Fs[1] += f_in[1];
Fs[2] += f_in[2];
double g[3];
g[0] = 0.5;
g[1] = 0;
g[2] = 0;
get_potential_force(g, f_in, 3, 0, 1.5, 1);
Fs[0] += f_in[0];
Fs[1] += f_in[1];
Fs[2] += f_in[2];
cmd.linear.x = -Fs[0] * force;
cmd.linear.y = Fs[1] * force;
ROS_INFO("obs = (%f, %f)", obs_[0], obs_[1]);
ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
r.sleep();
ros::spinOnce();
}
}
private:
void get_potential_force(double dest_lc[3], double f_out[3], double A = 1, double B = 3, double n = 1, double m = 1.5){
double u[3];
u[0] = dest_lc[0];
u[1] = dest_lc[1];
u[2] = dest_lc[2];
normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > tol){
U = -A/pow(d, n) + B/pow(d, m);
}
f_out[0] = U * u[0];
f_out[1] = U * u[1];
f_out[2] = U * u[2];
}
void obstacleCallback(const sensor_msgs::PointCloudPtr &obs_msg){
if(obs_msg->points.size() == 0){
obs_[0] = 0;
obs_[1] = 0;
obs_[2] = 0;
return;
}
double min_obs[3];
min_obs[0] = obs_msg->points[0].x;
min_obs[1] = obs_msg->points[0].y;
min_obs[2] = obs_msg->points[0].z;
float min_dist = magnitude(min_obs);
for(int i=1; i < obs_msg->points.size(); i++){
double obs[3];
obs[0] = obs_msg->points[i].x;
obs[1] = obs_msg->points[i].y;
obs[2] = obs_msg->points[i].z;
//ROS_INFO("(%f, %f)", obs[0], obs[1]);
double dist = magnitude(obs);
if(dist < min_dist){
min_obs[0] = obs[0];
min_obs[1] = obs[1];
min_obs[2] = obs[2];
min_dist = dist;
}
}
obs_[0] = min_obs[0];
obs_[1] = min_obs[1];
obs_[2] = min_obs[2];
}
double obs_[3];
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "obstacle_avoidance");
ros::NodeHandle node;
ArtificialPotentialField apf = ArtificialPotentialField(node);
apf.spin();
return 0;
}
<commit_msg>fixed attraction parameters<commit_after>#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/PointCloud.h>
#include <math.h>
static const float tol = 0.000000000000001f;
double magnitude(double vec[3]){
return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
}
void normalize(double vec[3]){
float m = magnitude(vec);
if(tol >= m) m = 1;
vec[0] /= m;
vec[1] /= m;
vec[2] /= m;
if(fabs(vec[0]) < tol) vec[0] = 0.0f;
if(fabs(vec[1]) < tol) vec[1] = 0.0f;
if(fabs(vec[2]) < tol) vec[2] = 0.0f;
}
class ArtificialPotentialField{
public:
ArtificialPotentialField(ros::NodeHandle &node) :
cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)),
obs_sub_(node.subscribe("slam_cloud", 10, &ArtificialPotentialField::obstacleCallback, this))
{
for(int i=0; i < 3; i++) obs_[i] = 0;
}
void spin(){
ros::Rate r(10);
ros::Duration(1).sleep();
geometry_msgs::Twist cmd;
cmd.linear.z = 0.15;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
cmd.linear.z = 0;
cmd_pub_.publish(cmd);
ros::Duration(3).sleep();
const double A = 0;
const double B = 3;
const double n = 1;
const double m = 1.5;
const double force = 0.025;
while(ros::ok()){
double Fs[3];
Fs[0] = Fs[1] = Fs[2] = 0;
double f_in[3];
get_potential_force(obs_, f_in, 0, 2, 1, 1.5);
Fs[0] += f_in[0];
Fs[1] += f_in[1];
Fs[2] += f_in[2];
double g[3];
g[0] = 0.5;
g[1] = 0;
g[2] = 0;
get_potential_force(g, f_in, 3, 0, 1.5, 1);
Fs[0] += f_in[0];
Fs[1] += f_in[1];
Fs[2] += f_in[2];
cmd.linear.x = -Fs[0] * force;
cmd.linear.y = Fs[1] * force;
ROS_INFO("obs = (%f, %f)", obs_[0], obs_[1]);
ROS_INFO_STREAM("cmd = " << cmd);
cmd_pub_.publish(cmd);
r.sleep();
ros::spinOnce();
}
}
private:
void get_potential_force(double dest_lc[3], double f_out[3], double A = 1, double B = 3, double n = 1, double m = 1.5){
double u[3];
u[0] = dest_lc[0];
u[1] = dest_lc[1];
u[2] = dest_lc[2];
normalize(u);
const double d = magnitude(dest_lc);
double U = 0;
if(fabs(d) > tol){
U = -A/pow(d, n) + B/pow(d, m);
}
f_out[0] = U * u[0];
f_out[1] = U * u[1];
f_out[2] = U * u[2];
}
void obstacleCallback(const sensor_msgs::PointCloudPtr &obs_msg){
if(obs_msg->points.size() == 0){
obs_[0] = 0;
obs_[1] = 0;
obs_[2] = 0;
return;
}
double min_obs[3];
min_obs[0] = obs_msg->points[0].x;
min_obs[1] = obs_msg->points[0].y;
min_obs[2] = obs_msg->points[0].z;
float min_dist = magnitude(min_obs);
for(int i=1; i < obs_msg->points.size(); i++){
double obs[3];
obs[0] = obs_msg->points[i].x;
obs[1] = obs_msg->points[i].y;
obs[2] = obs_msg->points[i].z;
//ROS_INFO("(%f, %f)", obs[0], obs[1]);
double dist = magnitude(obs);
if(dist < min_dist){
min_obs[0] = obs[0];
min_obs[1] = obs[1];
min_obs[2] = obs[2];
min_dist = dist;
}
}
obs_[0] = min_obs[0];
obs_[1] = min_obs[1];
obs_[2] = min_obs[2];
}
double obs_[3];
ros::Publisher cmd_pub_;
ros::Subscriber obs_sub_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "obstacle_avoidance");
ros::NodeHandle node;
ArtificialPotentialField apf = ArtificialPotentialField(node);
apf.spin();
return 0;
}
<|endoftext|> |
<commit_before>#include <mlopen/convolution.hpp>
#include <mlopen/mlo_internal.hpp>
namespace mlopen {
mlopenStatus_t ConvolutionDescriptor::FindConvFwdAlgorithm(mlopen::Context& handle,
const mlopen::TensorDescriptor& xDesc,
const cl_mem x,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
const mlopen::TensorDescriptor& yDesc,
const cl_mem y,
const int requestAlgoCount,
int *returnedAlgoCount,
mlopenConvAlgoPerf_t *perfResults,
mlopenConvPreference_t preference,
void *workSpace,
size_t workSpaceSize,
bool exhaustiveSearch) const {
if(x == nullptr || w == nullptr || y == nullptr) {
return mlopenStatusBadParm;
}
#if 0
if(returnedAlgoCount == nullptr || perfResults == nullptr) {
return mlopenStatusBadParm;
}
if(requestAlgoCount < 1) {
return mlopenStatusBadParm;
}
#endif
// Generate kernels if OpenCL
// Compile, cache kernels, etc.
// Launch all kernels and store the perf, workspace limits, etc.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(1); // forward
{
construct_params.setTimerIter(100);
construct_params.doSearch(exhaustiveSearch);
construct_params.saveSearchRequest(true);
// TO DO WHERE IS THE PATH ?
std::string kernel_path = "../src/Kernels/";
construct_params.setKernelPath(kernel_path);
std::string generic_comp_otions;
// if (debug)
{
// generic_comp_otions += std::string(" -cl-std=CL2.0 ");
}
construct_params.setGeneralCompOptions(generic_comp_otions);
mlopenAcceleratorQueue_t queue = handle.GetStream();
construct_params.setStream(queue);
output_sz = construct_params.setOutputDescFromMLDesc(yDesc);
input_sz = construct_params.setInputDescFromMLDesc(xDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley);
construct_params.mloConstructDirect2D();
}
std::string program_name = std::string("../src/Kernels/") + construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename
std::string kernel_name = construct_params.getKernelName(); // "hello_world_kernel"; // kernel name
std::string parms = construct_params.getCompilerOptions(); // kernel parameters
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
const std::vector<size_t> & vld = construct_params.getLocalWkSize();
const std::vector<size_t> & vgd = construct_params.getGlobalWkSize();
float padding_val = 0;
handle.Run("mlopenConvolutionFwdAlgoDirect",
network_config,
program_name,
kernel_name,
vld,
vgd,
parms)(x, w, y, padding_val);
handle.Finish();
std::cout << "Find Forward Convolution Finished !!" << std::endl;
return mlopenStatusSuccess;
}
mlopenStatus_t ConvolutionDescriptor::ConvolutionForward(mlopen::Context& handle,
const void *alpha,
const mlopen::TensorDescriptor& xDesc,
const cl_mem x,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
mlopenConvFwdAlgorithm_t algo,
const void *beta,
const mlopen::TensorDescriptor& yDesc,
cl_mem y,
void *workSpace,
size_t workSpaceSize) const {
if(x == nullptr || w == nullptr || y == nullptr) {
return mlopenStatusBadParm;
}
if(xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize()) {
return mlopenStatusBadParm;
}
if(xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType()) {
return mlopenStatusBadParm;
}
if(xDesc.GetLengths()[1] != wDesc.GetLengths()[1]) {
return mlopenStatusBadParm;
}
if(xDesc.GetSize() < 3) {
return mlopenStatusBadParm;
}
// TODO: Replicating code for now.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(1); // forward
{
output_sz = construct_params.setOutputDescFromMLDesc(yDesc);
input_sz = construct_params.setInputDescFromMLDesc(xDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
}
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
std::string algorithm_name;
switch(algo) {
case mlopenConvolutionFwdAlgoDirect:
// Compile the kernel if not aleady compiled
algorithm_name = "mlopenConvolutionFwdAlgoDirect";
break;
}
float padding_val = 0;
handle.Run(algorithm_name, network_config)(x, w, y, padding_val);
handle.Finish();
return mlopenStatusSuccess;
}
// FindBackwardDataAlgorithm()
//
mlopenStatus_t ConvolutionDescriptor::FindConvBwdDataAlgorithm(mlopen::Context& handle,
const mlopen::TensorDescriptor& dyDesc,
const cl_mem dy,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
const mlopen::TensorDescriptor& dxDesc,
const cl_mem dx,
const int requestAlgoCount,
int *returnedAlgoCount,
mlopenConvAlgoPerf_t *perfResults,
mlopenConvPreference_t preference,
void *workSpace,
size_t workSpaceSize,
bool exhaustiveSearch) const {
if(dx == nullptr || w == nullptr || dy == nullptr) {
return mlopenStatusBadParm;
}
#if 0
if(returnedAlgoCount == nullptr || perfResults == nullptr) {
return mlopenStatusBadParm;
}
if(requestAlgoCount < 1) {
return mlopenStatusBadParm;
}
#endif
// Generate kernels if OpenCL
// Compile, cache kernels, etc.
// Launch all kernels and store the perf, workspace limits, etc.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(0); // backward
{
construct_params.setTimerIter(100);
construct_params.doSearch(exhaustiveSearch);
construct_params.saveSearchRequest(true);
// TO DO WHERE IS THE PATH ?
std::string kernel_path = "../src/Kernels/";
construct_params.setKernelPath(kernel_path);
std::string generic_comp_otions;
// if (debug)
{
// generic_comp_otions += std::string(" -cl-std=CL2.0 ");
}
construct_params.setGeneralCompOptions(generic_comp_otions);
mlopenAcceleratorQueue_t queue = handle.GetStream();
construct_params.setStream(queue);
output_sz = construct_params.setOutputDescFromMLDesc(dxDesc);
input_sz = construct_params.setInputDescFromMLDesc(dyDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley);
construct_params.mloConstructDirect2D();
}
std::string program_name = std::string("../src/Kernels/") + construct_params.getKernelFile();
std::string kernel_name = construct_params.getKernelName(); // kernel name
std::string parms = construct_params.getCompilerOptions(); // kernel parameters
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
const std::vector<size_t> & vld = construct_params.getLocalWkSize();
const std::vector<size_t> & vgd = construct_params.getGlobalWkSize();
// Compile the kernel if not aleady compiled
OCLKernel obj = KernelCache::get(queue,
"mlopenConvolutionBwdDataAlgo_0",
network_config,
program_name,
kernel_name,
vld,
vgd,
parms);
cl_int status;
std::string kernName;
obj.GetKernelName(kernName);
printf("kname: %s\n", kernName.c_str());
// Set kernel arguments
// Use proper arguments
float padding_val = 0;
obj.SetArgs(0, dy, w, dx, padding_val);
int dim = (int)vld.size();
// Run the kernel
obj.run(queue, dim, 0, vgd.data(), vld.data(), NULL);
clFinish(queue);
std::cout << "Find Backward Data Finished !!" << std::endl;
return mlopenStatusSuccess;
}
// BackwardDataAlgorithm()
mlopenStatus_t ConvolutionDescriptor::ConvolutionBackwardData(mlopen::Context& handle,
const void *alpha,
const mlopen::TensorDescriptor& dyDesc,
const cl_mem dy,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
mlopenConvBwdDataAlgorithm_t algo,
const void *beta,
const mlopen::TensorDescriptor& dxDesc,
cl_mem dx,
void *workSpace,
size_t workSpaceSize) const {
if(dx == nullptr || w == nullptr || dy == nullptr) {
return mlopenStatusBadParm;
}
if(dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize()) {
return mlopenStatusBadParm;
}
if(dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType()) {
return mlopenStatusBadParm;
}
if(dyDesc.GetLengths()[1] != wDesc.GetLengths()[1]) {
return mlopenStatusBadParm;
}
if(dyDesc.GetSize() < 3) {
return mlopenStatusBadParm;
}
// TODO: Replicating code for now.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(0); // backward
{
output_sz = construct_params.setOutputDescFromMLDesc(dxDesc);
input_sz = construct_params.setInputDescFromMLDesc(dyDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
}
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
OCLKernel kernel;
switch(algo) {
case mlopenConvolutionBwdDataAlgo_0:
// Compile the kernel if not aleady compiled
kernel = KernelCache::get( "mlopenConvolutionBwdDataAlgo_0",
network_config);
// if(!kernel) {printf("kenrel not found in hash table\n");
break;
default:
printf("Algorithm not found\n");
break;
}
cl_int status;
std::string kernName;
kernel.GetKernelName(kernName);
printf("kname: %s\n", kernName.c_str());
// Set kernel arguments
// Use proper arguments
float padding_val = 0;
kernel.SetArgs(0, dy, w, dx, padding_val);
const std::vector<size_t> & vld = kernel.GetLocalDims();
const std::vector<size_t> & vgd = kernel.GetGlobalDims();
int dim = (int)vld.size();
// Run the kernel
kernel.run(queue, dim, 0, vgd.data(), vld.data(), NULL);
clFinish(queue);
std::cout << "Run Backward Data Finished !!" << std::endl;
return mlopenStatusSuccess;
}
}
<commit_msg>Run backwards convolution using handle<commit_after>#include <mlopen/convolution.hpp>
#include <mlopen/mlo_internal.hpp>
namespace mlopen {
mlopenStatus_t ConvolutionDescriptor::FindConvFwdAlgorithm(mlopen::Context& handle,
const mlopen::TensorDescriptor& xDesc,
const cl_mem x,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
const mlopen::TensorDescriptor& yDesc,
const cl_mem y,
const int requestAlgoCount,
int *returnedAlgoCount,
mlopenConvAlgoPerf_t *perfResults,
mlopenConvPreference_t preference,
void *workSpace,
size_t workSpaceSize,
bool exhaustiveSearch) const {
if(x == nullptr || w == nullptr || y == nullptr) {
return mlopenStatusBadParm;
}
#if 0
if(returnedAlgoCount == nullptr || perfResults == nullptr) {
return mlopenStatusBadParm;
}
if(requestAlgoCount < 1) {
return mlopenStatusBadParm;
}
#endif
// Generate kernels if OpenCL
// Compile, cache kernels, etc.
// Launch all kernels and store the perf, workspace limits, etc.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(1); // forward
{
construct_params.setTimerIter(100);
construct_params.doSearch(exhaustiveSearch);
construct_params.saveSearchRequest(true);
// TO DO WHERE IS THE PATH ?
std::string kernel_path = "../src/Kernels/";
construct_params.setKernelPath(kernel_path);
std::string generic_comp_otions;
// if (debug)
{
// generic_comp_otions += std::string(" -cl-std=CL2.0 ");
}
construct_params.setGeneralCompOptions(generic_comp_otions);
mlopenAcceleratorQueue_t queue = handle.GetStream();
construct_params.setStream(queue);
output_sz = construct_params.setOutputDescFromMLDesc(yDesc);
input_sz = construct_params.setInputDescFromMLDesc(xDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley);
construct_params.mloConstructDirect2D();
}
std::string program_name = std::string("../src/Kernels/") + construct_params.getKernelFile(); //"../src/Hello.cl"; // CL kernel filename
std::string kernel_name = construct_params.getKernelName(); // "hello_world_kernel"; // kernel name
std::string parms = construct_params.getCompilerOptions(); // kernel parameters
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
const std::vector<size_t> & vld = construct_params.getLocalWkSize();
const std::vector<size_t> & vgd = construct_params.getGlobalWkSize();
float padding_val = 0;
handle.Run("mlopenConvolutionFwdAlgoDirect",
network_config,
program_name,
kernel_name,
vld,
vgd,
parms)(x, w, y, padding_val);
handle.Finish();
std::cout << "Find Forward Convolution Finished !!" << std::endl;
return mlopenStatusSuccess;
}
mlopenStatus_t ConvolutionDescriptor::ConvolutionForward(mlopen::Context& handle,
const void *alpha,
const mlopen::TensorDescriptor& xDesc,
const cl_mem x,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
mlopenConvFwdAlgorithm_t algo,
const void *beta,
const mlopen::TensorDescriptor& yDesc,
cl_mem y,
void *workSpace,
size_t workSpaceSize) const {
if(x == nullptr || w == nullptr || y == nullptr) {
return mlopenStatusBadParm;
}
if(xDesc.GetSize() != yDesc.GetSize() || xDesc.GetSize() != wDesc.GetSize()) {
return mlopenStatusBadParm;
}
if(xDesc.GetType() != yDesc.GetType() || xDesc.GetType() != wDesc.GetType()) {
return mlopenStatusBadParm;
}
if(xDesc.GetLengths()[1] != wDesc.GetLengths()[1]) {
return mlopenStatusBadParm;
}
if(xDesc.GetSize() < 3) {
return mlopenStatusBadParm;
}
// TODO: Replicating code for now.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(1); // forward
{
output_sz = construct_params.setOutputDescFromMLDesc(yDesc);
input_sz = construct_params.setInputDescFromMLDesc(xDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
}
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
std::string algorithm_name;
switch(algo) {
case mlopenConvolutionFwdAlgoDirect:
// Compile the kernel if not aleady compiled
algorithm_name = "mlopenConvolutionFwdAlgoDirect";
break;
}
float padding_val = 0;
handle.Run(algorithm_name, network_config)(x, w, y, padding_val);
handle.Finish();
return mlopenStatusSuccess;
}
// FindBackwardDataAlgorithm()
//
mlopenStatus_t ConvolutionDescriptor::FindConvBwdDataAlgorithm(mlopen::Context& handle,
const mlopen::TensorDescriptor& dyDesc,
const cl_mem dy,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
const mlopen::TensorDescriptor& dxDesc,
const cl_mem dx,
const int requestAlgoCount,
int *returnedAlgoCount,
mlopenConvAlgoPerf_t *perfResults,
mlopenConvPreference_t preference,
void *workSpace,
size_t workSpaceSize,
bool exhaustiveSearch) const {
if(dx == nullptr || w == nullptr || dy == nullptr) {
return mlopenStatusBadParm;
}
#if 0
if(returnedAlgoCount == nullptr || perfResults == nullptr) {
return mlopenStatusBadParm;
}
if(requestAlgoCount < 1) {
return mlopenStatusBadParm;
}
#endif
// Generate kernels if OpenCL
// Compile, cache kernels, etc.
// Launch all kernels and store the perf, workspace limits, etc.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(0); // backward
{
construct_params.setTimerIter(100);
construct_params.doSearch(exhaustiveSearch);
construct_params.saveSearchRequest(true);
// TO DO WHERE IS THE PATH ?
std::string kernel_path = "../src/Kernels/";
construct_params.setKernelPath(kernel_path);
std::string generic_comp_otions;
// if (debug)
{
// generic_comp_otions += std::string(" -cl-std=CL2.0 ");
}
construct_params.setGeneralCompOptions(generic_comp_otions);
mlopenAcceleratorQueue_t queue = handle.GetStream();
construct_params.setStream(queue);
output_sz = construct_params.setOutputDescFromMLDesc(dxDesc);
input_sz = construct_params.setInputDescFromMLDesc(dyDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
construct_params.setConvDescr(pad_h, pad_w, u, v, upscalex, upscaley);
construct_params.mloConstructDirect2D();
}
std::string program_name = std::string("../src/Kernels/") + construct_params.getKernelFile();
std::string kernel_name = construct_params.getKernelName(); // kernel name
std::string parms = construct_params.getCompilerOptions(); // kernel parameters
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
const std::vector<size_t> & vld = construct_params.getLocalWkSize();
const std::vector<size_t> & vgd = construct_params.getGlobalWkSize();
float padding_val = 0;
handle.Run("mlopenConvolutionBwdDataAlgo_0",
network_config,
program_name,
kernel_name,
vld,
vgd,
parms)(dy, w, dx, padding_val);
handle.Finish();
return mlopenStatusSuccess;
}
// BackwardDataAlgorithm()
mlopenStatus_t ConvolutionDescriptor::ConvolutionBackwardData(mlopen::Context& handle,
const void *alpha,
const mlopen::TensorDescriptor& dyDesc,
const cl_mem dy,
const mlopen::TensorDescriptor& wDesc,
const cl_mem w,
mlopenConvBwdDataAlgorithm_t algo,
const void *beta,
const mlopen::TensorDescriptor& dxDesc,
cl_mem dx,
void *workSpace,
size_t workSpaceSize) const {
if(dx == nullptr || w == nullptr || dy == nullptr) {
return mlopenStatusBadParm;
}
if(dyDesc.GetSize() != dxDesc.GetSize() || dyDesc.GetSize() != wDesc.GetSize()) {
return mlopenStatusBadParm;
}
if(dyDesc.GetType() != dxDesc.GetType() || dyDesc.GetType() != wDesc.GetType()) {
return mlopenStatusBadParm;
}
if(dyDesc.GetLengths()[1] != wDesc.GetLengths()[1]) {
return mlopenStatusBadParm;
}
if(dyDesc.GetSize() < 3) {
return mlopenStatusBadParm;
}
// TODO: Replicating code for now.
size_t input_sz = 0;
size_t output_sz = 0;
size_t weights_sz = 0;
mlo_construct_direct2D construct_params(0); // backward
{
output_sz = construct_params.setOutputDescFromMLDesc(dxDesc);
input_sz = construct_params.setInputDescFromMLDesc(dyDesc);
weights_sz = construct_params.setWeightDescFromMLDesc(wDesc);
}
std::string network_config;
construct_params.mloBuildConf_Key(network_config);
// Get the queue associated with this handle
mlopenAcceleratorQueue_t queue = handle.GetStream();
std::string algorithm_name;
switch(algo) {
case mlopenConvolutionBwdDataAlgo_0:
algorithm_name = "mlopenConvolutionBwdDataAlgo_0";
break;
default:
printf("Algorithm not found\n");
break;
}
float padding_val = 0;
handle.Run(algorithm_name, network_config)(dy, w, dx, padding_val);
handle.Finish();
return mlopenStatusSuccess;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 Jonas Weber ([email protected])
* 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. 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 AUTHOR 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 AUTHOR
* 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.
*/
// xmlwrapp includes
#include "xmlwrapp/xpath.h"
#include "xmlwrapp/document.h"
#include "xmlwrapp/node.h"
#include "xmlwrapp/exception.h"
// libxml includes
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <iostream>
namespace xml {
namespace xpath {
bool XMLWRAPP_API operator==(const xml::xpath::node_set::iterator& l, const xml::xpath::node_set::iterator& r)
{
return ((l.pos == r.pos) && (l.data == r.data));
}
bool XMLWRAPP_API operator!=(const xml::xpath::node_set::iterator& l, const xml::xpath::node_set::iterator& r)
{
return ((l.pos != r.pos) || (l.data != r.data));
}}
namespace impl
{
struct xpitimpl
{
xml::node node;
xpitimpl() : node(0) { };
void set_data(xmlNodePtr n) { node.set_node_data(n); };
xml::node& get() { return node; }
};
}
namespace xpath
{
//------------------------
// node_set
//------------------------
//[data] is xmlXPathObjectPtr
node_set::node_set(void* data) : data(data)
{
}
node_set::~node_set()
{
if (data != NULL)
xmlXPathFreeObject(static_cast<xmlXPathObjectPtr>(data));
}
int node_set::count() const
{
if (data != NULL && static_cast<xmlXPathObjectPtr>(data)->nodesetval != NULL)
return static_cast<xmlXPathObjectPtr>(data)->nodesetval->nodeNr;
else
return 0;
}
bool node_set::empty() const
{
return (count() == 0); // TODO: best way?
}
node_set::iterator node_set::begin()
{
if (data != NULL && static_cast<xmlXPathObjectPtr>(data)->nodesetval != NULL)
{
xmlNodeSetPtr nset = static_cast<xmlXPathObjectPtr>(data)->nodesetval;
return node_set::iterator(nset, 0);
} else {
return node_set::iterator(NULL, 0);
}
}
node_set::iterator node_set::end()
{
if (data != NULL && static_cast<xmlXPathObjectPtr>(data)->nodesetval != NULL)
{
xmlNodeSetPtr nset = static_cast<xmlXPathObjectPtr>(data)->nodesetval;
if (nset == 0)
{
return iterator(nset, 0);
} else {
return iterator(nset, nset->nodeNr);
}
} else {
return iterator(NULL, 0);
}
}
bool node_set::contains(const xml::node& n) const
{
xmlNodeSetPtr nset = static_cast<xmlXPathObjectPtr>(data)->nodesetval;
xmlNodePtr nodeptr = static_cast<xmlNodePtr>(const_cast<xml::node&>(n).get_node_data());
return (xmlXPathNodeSetContains(nset, nodeptr) == 1);
}
//-----------------------
//node_set::iterator
//----------------------
node_set::iterator::iterator (void* data, int pos) : data(data), pos(pos)
{
pimpl_ = new xml::impl::xpitimpl();
}
node_set::iterator& node_set::iterator::operator++()
{
if (data != NULL && pos < static_cast<xmlNodeSetPtr>(data)->nodeNr)
++pos;
return *this;
}
node_set::iterator node_set::iterator::operator++(int)
{
node_set::iterator tmp = *this;
++(*this);
return tmp;
}
xml::node& xml::xpath::node_set::iterator::operator*()
{
xmlNodeSetPtr nodeset = static_cast<xmlNodeSetPtr>(data);
if (data == NULL || nodeset->nodeNr == pos) throw xml::exception("dereferencing end");
pimpl_->set_data((nodeset->nodeTab)[pos]);
return pimpl_->get();
}
xml::node* xml::xpath::node_set::iterator::operator->()
{
xmlNodeSetPtr nodeset = static_cast<xmlNodeSetPtr>(data);
if (data == NULL || nodeset->nodeNr == pos) throw xml::exception("dereferencing end");
pimpl_->set_data((nodeset->nodeTab)[pos]);
return &(pimpl_->get());
}
node_set::iterator::~iterator()
{
delete pimpl_;
}
node_set::iterator& node_set::iterator::operator=(const iterator& i)
{
data = i.data;
pos = i.pos;
return *this;
}
node_set::iterator::iterator(const node_set::iterator& i) : data(i.data), pos(i.pos), pimpl_(new impl::xpitimpl)
{
}
//-----------------
// xpath::context
//-----------------
context::context(const xml::document& doc)
{
ctxtptr = xmlXPathNewContext(static_cast<xmlDocPtr>(doc.get_doc_data_read_only()));
}
context::~context()
{
xmlXPathFreeContext(static_cast<xmlXPathContextPtr>(ctxtptr));
}
void context::register_namespace(const char* prefix, const char* href)
{
xmlXPathRegisterNs(static_cast<xmlXPathContextPtr>(ctxtptr),
reinterpret_cast<const xmlChar*>(prefix),
reinterpret_cast<const xmlChar*>(href));
}
node_set context::evaluate(const char* expr)
{
xmlXPathObjectPtr nsptr = xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(expr),
static_cast<xmlXPathContextPtr>(ctxtptr));
return node_set(nsptr);
}
}
}
<commit_msg>Use errors.h, not the old exception.h.<commit_after>/*
* Copyright (C) 2011 Jonas Weber ([email protected])
* 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. 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 AUTHOR 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 AUTHOR
* 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.
*/
// xmlwrapp includes
#include "xmlwrapp/xpath.h"
#include "xmlwrapp/document.h"
#include "xmlwrapp/node.h"
#include "xmlwrapp/errors.h"
// libxml includes
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
#include <iostream>
namespace xml {
namespace xpath {
bool XMLWRAPP_API operator==(const xml::xpath::node_set::iterator& l, const xml::xpath::node_set::iterator& r)
{
return ((l.pos == r.pos) && (l.data == r.data));
}
bool XMLWRAPP_API operator!=(const xml::xpath::node_set::iterator& l, const xml::xpath::node_set::iterator& r)
{
return ((l.pos != r.pos) || (l.data != r.data));
}}
namespace impl
{
struct xpitimpl
{
xml::node node;
xpitimpl() : node(0) { };
void set_data(xmlNodePtr n) { node.set_node_data(n); };
xml::node& get() { return node; }
};
}
namespace xpath
{
//------------------------
// node_set
//------------------------
//[data] is xmlXPathObjectPtr
node_set::node_set(void* data) : data(data)
{
}
node_set::~node_set()
{
if (data != NULL)
xmlXPathFreeObject(static_cast<xmlXPathObjectPtr>(data));
}
int node_set::count() const
{
if (data != NULL && static_cast<xmlXPathObjectPtr>(data)->nodesetval != NULL)
return static_cast<xmlXPathObjectPtr>(data)->nodesetval->nodeNr;
else
return 0;
}
bool node_set::empty() const
{
return (count() == 0); // TODO: best way?
}
node_set::iterator node_set::begin()
{
if (data != NULL && static_cast<xmlXPathObjectPtr>(data)->nodesetval != NULL)
{
xmlNodeSetPtr nset = static_cast<xmlXPathObjectPtr>(data)->nodesetval;
return node_set::iterator(nset, 0);
} else {
return node_set::iterator(NULL, 0);
}
}
node_set::iterator node_set::end()
{
if (data != NULL && static_cast<xmlXPathObjectPtr>(data)->nodesetval != NULL)
{
xmlNodeSetPtr nset = static_cast<xmlXPathObjectPtr>(data)->nodesetval;
if (nset == 0)
{
return iterator(nset, 0);
} else {
return iterator(nset, nset->nodeNr);
}
} else {
return iterator(NULL, 0);
}
}
bool node_set::contains(const xml::node& n) const
{
xmlNodeSetPtr nset = static_cast<xmlXPathObjectPtr>(data)->nodesetval;
xmlNodePtr nodeptr = static_cast<xmlNodePtr>(const_cast<xml::node&>(n).get_node_data());
return (xmlXPathNodeSetContains(nset, nodeptr) == 1);
}
//-----------------------
//node_set::iterator
//----------------------
node_set::iterator::iterator (void* data, int pos) : data(data), pos(pos)
{
pimpl_ = new xml::impl::xpitimpl();
}
node_set::iterator& node_set::iterator::operator++()
{
if (data != NULL && pos < static_cast<xmlNodeSetPtr>(data)->nodeNr)
++pos;
return *this;
}
node_set::iterator node_set::iterator::operator++(int)
{
node_set::iterator tmp = *this;
++(*this);
return tmp;
}
xml::node& xml::xpath::node_set::iterator::operator*()
{
xmlNodeSetPtr nodeset = static_cast<xmlNodeSetPtr>(data);
if (data == NULL || nodeset->nodeNr == pos) throw xml::exception("dereferencing end");
pimpl_->set_data((nodeset->nodeTab)[pos]);
return pimpl_->get();
}
xml::node* xml::xpath::node_set::iterator::operator->()
{
xmlNodeSetPtr nodeset = static_cast<xmlNodeSetPtr>(data);
if (data == NULL || nodeset->nodeNr == pos) throw xml::exception("dereferencing end");
pimpl_->set_data((nodeset->nodeTab)[pos]);
return &(pimpl_->get());
}
node_set::iterator::~iterator()
{
delete pimpl_;
}
node_set::iterator& node_set::iterator::operator=(const iterator& i)
{
data = i.data;
pos = i.pos;
return *this;
}
node_set::iterator::iterator(const node_set::iterator& i) : data(i.data), pos(i.pos), pimpl_(new impl::xpitimpl)
{
}
//-----------------
// xpath::context
//-----------------
context::context(const xml::document& doc)
{
ctxtptr = xmlXPathNewContext(static_cast<xmlDocPtr>(doc.get_doc_data_read_only()));
}
context::~context()
{
xmlXPathFreeContext(static_cast<xmlXPathContextPtr>(ctxtptr));
}
void context::register_namespace(const char* prefix, const char* href)
{
xmlXPathRegisterNs(static_cast<xmlXPathContextPtr>(ctxtptr),
reinterpret_cast<const xmlChar*>(prefix),
reinterpret_cast<const xmlChar*>(href));
}
node_set context::evaluate(const char* expr)
{
xmlXPathObjectPtr nsptr = xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>(expr),
static_cast<xmlXPathContextPtr>(ctxtptr));
return node_set(nsptr);
}
}
}
<|endoftext|> |
<commit_before>/***********************************************************
*
* omxAlgebraFunctions.h
*
* Created: Timothy R. Brick Date: 2008-11-13 12:33:06
*
* Includes the functions required for omxAlgebra statements.
* These functions should take a number of values that
* evenly matches the number of args requested by the
* omxSymbolTable.
*
**********************************************************/
#include "omxAlgebraFunctions.h"
void omxMatrixTranspose(omxMatrix *inMat, omxMatrix* result) {
*result = *inMat;
result->transpose();
}
void omxMatrixInvert(omxMatrix *inMat, omxMatrix* result)
{
int ipiv[inMat->rows];
int l = 0;
/* TODO: Does this interact with transposition? */
*result = *inMat;
F77_CALL(dgetrf)(&(result->cols), &(result->rows), result->data, &(result->leading), ipiv, &l);
}
void omxElementPower(omxMatrix *inMat, omxMatrix *power, omxMatrix* result)
{
*result = *inMat;
if(power->rows == 1 && power->cols ==1) {
for(int j = 0; j < result->cols * result->rows; j++) {
result->data[j] = pow(result->data[j], power->data[0]);
}
} else if(power->rows == inMat->rows && power->cols == inMat->cols) {
for(int j = 0; j < result->rows; j++)
for(int k = 0; k < result->cols; k++)
result->setElement(j, k, pow(result->element(j,k), power->element(j,k)));
} else {
error("Non-conformable matrices in elementPower.");
}
};
void omxMatrixMult(omxMatrix *preMul, omxMatrix *postMul, omxMatrix* result) {
if(OMX_DEBUG) { Rprintf("Multiplying two matrices.\n"); preMul->print("This one"); postMul->print("by this");}
if(preMul == NULL || postMul == NULL) {
error("Null matrix pointer detected.\n");
}
static double zero = 0.0;
static double one = 1.0;
/* Conformability Check! */
if(preMul->cols != postMul->rows)
error("Non-conformable matrices in Matrix Multiply.");
if(result->rows != preMul->rows || result->cols != preMul->cols)
result->resize(preMul->rows, postMul->cols);
/* For debugging */
if(OMX_DEBUG) {
result->print("NewMatrix");
Rprintf("DGEMM: %c, %c, %d, %d, %d, %d\n", *(preMul->majority), *(postMul->majority), (preMul->rows), (postMul->cols), preMul->leading, postMul->leading);
Rprintf("Note: majorityList is [%c, %c]\n", *(preMul->majorityList), *(preMul->majorityList + 1));
}
/* The call itself */
F77_CALL(dgemm)((preMul->majority), (postMul->majority), &(preMul->rows), &(postMul->cols), &(preMul->cols), &one, preMul->data, &(preMul->leading), postMul->data, &(postMul->leading), &zero, result->data, &(result->leading));
};
void omxMatrixDot(omxMatrix* preDot, omxMatrix* postDot, omxMatrix* result) {
// Actually, this is element-by-element multiplication.
/* Conformability Check! */
if(preDot->cols != postDot->cols || preDot->rows != postDot->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = postDot;
int max = preDot->cols * preDot->rows;
/* The call itself */
//F77_CALL(dgemm)((preDot->majority), (result->majority), &(preDot->rows), &(result->cols), &(preDot->cols), &zero, preDot->data, &(preDot->leading), result->data, &(result->leading), &one, result->data, &(result->leading));
for(int j = 0; j < max; j++) {
result->data[j] = preDot->data[j] * postDot->data[j];
}
};
void omxKroneckerProd(omxMatrix* preMul, omxMatrix* postMul, omxMatrix* result) {
int rows = preMul->rows * postMul->rows;
int cols = preMul->cols * postMul->cols;
if(result->rows != rows || result->cols != cols)
result->resize(rows, cols);
for(int preRow = 0; preRow < preMul->rows; preRow++)
for(int postRow = 0; postRow < postMul->rows; postRow++)
for(int preCol = 0; preCol < preMul->cols; preCol++)
for(int postCol = 0; postCol < postMul->cols; postCol++)
result->setElement(preRow*postMul->rows + postRow, preCol*postMul->cols + postCol, preMul->element(preRow, preCol)*postMul->element(postRow, postCol));
};
void omxQuadraticProd(omxMatrix* preMul, omxMatrix* postMul, omxMatrix* result) {
/* A %&% B = ABA' */
static double zero = 0.0;
static double one = 1.0;
/* Conformability Check! */
if(preMul->cols != postMul->rows)
error("Non-conformable matrices in Matrix Multiply.");
omxMatrix* intermediate = new omxMatrix(preMul->rows, postMul->cols);
if(result->rows != preMul->rows || result->cols != preMul->rows)
result->resize(preMul->cols, preMul->cols);
/* The call itself */
F77_CALL(dgemm)((preMul->majority), (postMul->majority), &(preMul->rows), &(postMul->cols), &(preMul->cols), &one, preMul->data, &(preMul->leading), postMul->data, &(postMul->leading), &zero, intermediate->data, &(intermediate->leading));
F77_CALL(dgemm)((intermediate->majority), (preMul->minority), &(intermediate->rows), &(preMul->cols), &(intermediate->cols), &one, intermediate->data, &(intermediate->leading), preMul->data, &(preMul->leading), &zero, result->data, &(result->leading));
};
void omxElementDivide(omxMatrix* inMat, omxMatrix* divisor, omxMatrix* result) {
/* Conformability Check! */
if(inMat->cols != divisor->cols || inMat->rows != divisor->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = divisor;
int max = inMat->cols * inMat->rows;
for(int j = 0; j < max; j++) {
result->data[j] = inMat->data[j] / divisor->data[j];
}
};
void omxMatrixAdd(omxMatrix* inMat, omxMatrix* addend, omxMatrix* result) {
/* Conformability Check! */
if(inMat->cols != addend->cols || inMat->rows != addend->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = addend;
int max = inMat->cols * inMat->rows;
for(int j = 0; j < max; j++) {
result->data[j] = inMat->data[j] + addend->data[j];
}
};
void omxMatrixSubtract(omxMatrix* inMat, omxMatrix* subtrahend, omxMatrix* result) { /* Conformability Check! */
if(inMat->cols != subtrahend->cols || inMat->rows != subtrahend->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = subtrahend;
int max = inMat->cols * inMat->rows;
//F77_CALL(dgemm)((inMat->majority), (result->majority), &(inMat->rows), &(result->cols), &(inMat->cols), &zero, inMat->data, &(inMat->leading), result->data, &(result->leading), &one, result->data, &(result->leading)); // TODO: Compare performance on BLAS vs for.
for(int j = 0; j < max; j++) {
result->data[j] = inMat->data[j] - subtrahend->data[j];
}
};
void omxUnaryMinus(omxMatrix* inMat, omxMatrix* result) {
int max = inMat->cols * inMat->rows;
result = inMat;
for(int j = 0; j < max; j++) {
result->data[j] = -result->data[j];
}
};
void omxMatrixHorizCat(omxMatrix** matList, double numArgs, omxMatrix* result) {
int totalRows = 0, totalCols = 0, currentCol=0;
if(numArgs == 0) return;
totalRows = matList[0]->rows; // Assumed constant. Assert this below.
for(int j = 0; j < numArgs; j++) {
if(totalRows != matList[j]->rows) {
error("Non-conformable matrices in horizontal concatenation.");
}
totalCols += matList[j]->cols;
}
if(result->rows != totalRows || result->cols != totalCols) {
result->resize(totalRows, totalCols);
}
for(int j = 0; j < numArgs; j++) {
for(int k = 0; k < matList[j]->cols; j++) {
for(int l = 0; l < totalRows; l++) { // Gotta be a faster way to do this.
result->setElement(l, currentCol, matList[j]->element(l, k));
}
currentCol++;
}
}
};
void omxMatrixVertCat(omxMatrix** matList, double numArgs, omxMatrix* result) {
int totalRows = 0, totalCols = 0, currentRow=0;
if(numArgs == 0) return;
totalCols = matList[0]->cols; // Assumed constant. Assert this below.
for(int j = 0; j < numArgs; j++) {
if(totalCols != matList[j]->cols) {
error("Non-conformable matrices in horizontal concatenation.");
}
totalRows += matList[j]->rows;
}
if(result->rows != totalRows || result->cols != totalCols) {
result->resize(totalRows, totalCols);
}
for(int j = 0; j < numArgs; j++) {
for(int k = 0; k < matList[j]->rows; j++) {
for(int l = 0; l < totalCols; l++) { // Gotta be a faster way to do this.
result->setElement(currentRow, l, matList[j]->element(k, l));
}
currentRow++;
}
}
};
<commit_msg>Change to omxAlgebraFunctions.cc commit<commit_after>/***********************************************************
*
* omxAlgebraFunctions.h
*
* Created: Timothy R. Brick Date: 2008-11-13 12:33:06
*
* Includes the functions required for omxAlgebra statements.
* These functions should take a number of values that
* evenly matches the number of args requested by the
* omxSymbolTable.
*
**********************************************************/
#include "omxAlgebraFunctions.h"
void omxMatrixTranspose(omxMatrix *inMat, omxMatrix* result) {
*result = *inMat;
result->transpose();
}
void omxMatrixInvert(omxMatrix *inMat, omxMatrix* result)
{
int ipiv[inMat->rows];
int l = 0;
/* TODO: Does this interact with transposition? */
*result = *inMat;
F77_CALL(dgetrf)(&(result->cols), &(result->rows), result->data, &(result->leading), ipiv, &l);
}
void omxElementPower(omxMatrix *inMat, omxMatrix *power, omxMatrix* result)
{
*result = *inMat;
if(power->rows == 1 && power->cols ==1) {
for(int j = 0; j < result->cols * result->rows; j++) {
result->data[j] = pow(result->data[j], power->data[0]);
}
} else if(power->rows == inMat->rows && power->cols == inMat->cols) {
for(int j = 0; j < result->rows; j++)
for(int k = 0; k < result->cols; k++)
result->setElement(j, k, pow(result->element(j,k), power->element(j,k)));
} else {
error("Non-conformable matrices in elementPower.");
}
};
void omxMatrixMult(omxMatrix *preMul, omxMatrix *postMul, omxMatrix* result) {
if(OMX_DEBUG) { Rprintf("Multiplying two matrices.\n"); preMul->print("This one"); postMul->print("by this");}
if(preMul == NULL || postMul == NULL) {
error("Null matrix pointer detected.\n");
}
static double zero = 0.0;
static double one = 1.0;
/* Conformability Check! */
if(preMul->cols != postMul->rows)
error("Non-conformable matrices in Matrix Multiply.");
if(result->rows != preMul->rows || result->cols != preMul->cols)
result->resize(preMul->rows, postMul->cols);
/* For debugging */
if(OMX_DEBUG) {
result->print("NewMatrix");
Rprintf("DGEMM: %c, %c, %d, %d, %d, %d\n", *(preMul->majority), *(postMul->majority), (preMul->rows), (postMul->cols), preMul->leading, postMul->leading);
Rprintf("Note: majorityList is [%c, %c]\n", *(preMul->majorityList), *(preMul->majorityList + 1));
}
/* The call itself */
F77_CALL(dgemm)((preMul->majority), (postMul->majority), &(preMul->rows), &(postMul->cols), &(preMul->cols), &one, preMul->data, &(preMul->leading), postMul->data, &(postMul->leading), &zero, result->data, &(result->leading));
};
void omxMatrixDot(omxMatrix *preDot, omxMatrix *postDot, omxMatrix* result) {
// Actually, this is element-by-element multiplication.
/* Conformability Check! */
if(preDot->cols != postDot->cols || preDot->rows != postDot->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = postDot;
int max = preDot->cols * preDot->rows;
/* The call itself */
//F77_CALL(dgemm)((preDot->majority), (result->majority), &(preDot->rows), &(result->cols), &(preDot->cols), &zero, preDot->data, &(preDot->leading), result->data, &(result->leading), &one, result->data, &(result->leading));
for(int j = 0; j < max; j++) {
result->data[j] = preDot->data[j] * postDot->data[j];
}
};
void omxKroneckerProd(omxMatrix* preMul, omxMatrix* postMul, omxMatrix* result) {
int rows = preMul->rows * postMul->rows;
int cols = preMul->cols * postMul->cols;
if(result->rows != rows || result->cols != cols)
result->resize(rows, cols);
for(int preRow = 0; preRow < preMul->rows; preRow++)
for(int postRow = 0; postRow < postMul->rows; postRow++)
for(int preCol = 0; preCol < preMul->cols; preCol++)
for(int postCol = 0; postCol < postMul->cols; postCol++)
result->setElement(preRow*postMul->rows + postRow, preCol*postMul->cols + postCol, preMul->element(preRow, preCol)*postMul->element(postRow, postCol));
};
void omxQuadraticProd(omxMatrix* preMul, omxMatrix* postMul, omxMatrix* result) {
/* A %&% B = ABA' */
static double zero = 0.0;
static double one = 1.0;
/* Conformability Check! */
if(preMul->cols != postMul->rows)
error("Non-conformable matrices in Matrix Multiply.");
omxMatrix* intermediate = new omxMatrix(preMul->rows, postMul->cols);
if(result->rows != preMul->rows || result->cols != preMul->rows)
result->resize(preMul->cols, preMul->cols);
/* The call itself */
F77_CALL(dgemm)((preMul->majority), (postMul->majority), &(preMul->rows), &(postMul->cols), &(preMul->cols), &one, preMul->data, &(preMul->leading), postMul->data, &(postMul->leading), &zero, intermediate->data, &(intermediate->leading));
F77_CALL(dgemm)((intermediate->majority), (preMul->minority), &(intermediate->rows), &(preMul->cols), &(intermediate->cols), &one, intermediate->data, &(intermediate->leading), preMul->data, &(preMul->leading), &zero, result->data, &(result->leading));
};
void omxElementDivide(omxMatrix* inMat, omxMatrix* divisor, omxMatrix* result) {
/* Conformability Check! */
if(inMat->cols != divisor->cols || inMat->rows != divisor->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = divisor;
int max = inMat->cols * inMat->rows;
for(int j = 0; j < max; j++) {
result->data[j] = inMat->data[j] / divisor->data[j];
}
};
void omxMatrixAdd(omxMatrix* inMat, omxMatrix* addend, omxMatrix* result) {
/* Conformability Check! */
if(inMat->cols != addend->cols || inMat->rows != addend->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = addend;
int max = inMat->cols * inMat->rows;
for(int j = 0; j < max; j++) {
result->data[j] = inMat->data[j] + addend->data[j];
}
};
void omxMatrixSubtract(omxMatrix* inMat, omxMatrix* subtrahend, omxMatrix* result) { /* Conformability Check! */
if(inMat->cols != subtrahend->cols || inMat->rows != subtrahend->rows)
error("Non-conformable matrices in Matrix Multiply.");
result = subtrahend;
int max = inMat->cols * inMat->rows;
//F77_CALL(dgemm)((inMat->majority), (result->majority), &(inMat->rows), &(result->cols), &(inMat->cols), &zero, inMat->data, &(inMat->leading), result->data, &(result->leading), &one, result->data, &(result->leading)); // TODO: Compare performance on BLAS vs for.
for(int j = 0; j < max; j++) {
result->data[j] = inMat->data[j] - subtrahend->data[j];
}
};
void omxUnaryMinus(omxMatrix* inMat, omxMatrix* result) {
int max = inMat->cols * inMat->rows;
result = inMat;
for(int j = 0; j < max; j++) {
result->data[j] = -result->data[j];
}
};
void omxMatrixHorizCat(omxMatrix** matList, double numArgs, omxMatrix* result) {
int totalRows = 0, totalCols = 0, currentCol=0;
if(numArgs == 0) return;
totalRows = matList[0]->rows; // Assumed constant. Assert this below.
for(int j = 0; j < numArgs; j++) {
if(totalRows != matList[j]->rows) {
error("Non-conformable matrices in horizontal concatenation.");
}
totalCols += matList[j]->cols;
}
if(result->rows != totalRows || result->cols != totalCols) {
result->resize(totalRows, totalCols);
}
for(int j = 0; j < numArgs; j++) {
for(int k = 0; k < matList[j]->cols; j++) {
for(int l = 0; l < totalRows; l++) { // Gotta be a faster way to do this.
result->setElement(l, currentCol, matList[j]->element(l, k));
}
currentCol++;
}
}
};
void omxMatrixVertCat(omxMatrix** matList, double numArgs, omxMatrix* result) {
int totalRows = 0, totalCols = 0, currentRow=0;
if(numArgs == 0) return;
totalCols = matList[0]->cols; // Assumed constant. Assert this below.
for(int j = 0; j < numArgs; j++) {
if(totalCols != matList[j]->cols) {
error("Non-conformable matrices in horizontal concatenation.");
}
totalRows += matList[j]->rows;
}
if(result->rows != totalRows || result->cols != totalCols) {
result->resize(totalRows, totalCols);
}
for(int j = 0; j < numArgs; j++) {
for(int k = 0; k < matList[j]->rows; j++) {
for(int l = 0; l < totalCols; l++) { // Gotta be a faster way to do this.
result->setElement(currentRow, l, matList[j]->element(k, l));
}
currentRow++;
}
}
};
<|endoftext|> |
<commit_before>
/*
Olimpíada Brasileira de Informática
Seletiva para a IOI, Teste Final, 2009
Problema: Boliche
Data de submissão: 29/05/2012
Autor da solução: Luiz Rodrigo <@lurodrigo> <[email protected]>
Tags: ad-hoc
Complexidade: O(1)
*/
#include <iostream>
#include <string>
using namespace std;
using std::string;
enum Tipo { NORMAL, SPARE, STRIKE };
int main() {
string jogada;
int bola[21], tipo[21];
int i, j, k, emPe, total = 0;
for (i = k = 0; i < 10; i++) {
cin >> jogada;
for (j = 0, emPe = 10; j < jogada.length(); j++, k++) {
if ( jogada[j] == '-' ) {
bola[k] = 0;
tipo[k] = NORMAL;
} else if ( jogada[j] == 'X' ) {
bola[k] = 10;
tipo[k] = STRIKE;
emPe = 10;
} else if ( jogada[j] == '/' ) {
bola[k] = emPe;
tipo[k] = SPARE;
emPe = 10;
} else {
bola[k] = jogada[j] - '0';
tipo[k] = NORMAL;
emPe -= jogada[j] - '0';
}
if ( i == 9 )
tipo[k] = NORMAL;
}
}
for (i = 0; i < k; total += bola[i], i++)
for (j = 0; j < tipo[i]; j++)
bola[i] += bola[i + j + 1];
cout << total;
return 0;
}
<commit_msg>Pequena otimizacao para reutilizacao de codigo<commit_after>
/*
Olimpíada Brasileira de Informática
Seletiva para a IOI, Teste Final, 2009
Problema: Boliche
Data de submissão: 29/05/2012
Autor da solução: Luiz Rodrigo <@lurodrigo> <[email protected]>
Tags: ad-hoc
Complexidade: O(1)
*/
#include <iostream>
#include <string>
using namespace std;
using std::string;
enum Tipo { NORMAL, SPARE, STRIKE };
int to_int(char c) {
return (c == '-') ? 0 : c-'0';
}
int main() {
string jogada;
int bola[21], tipo[21];
int i, j, k, emPe, total = 0;
for (i = k = 0; i < 10; i++) {
cin >> jogada;
for (j = 0, emPe = 10; j < jogada.length(); j++, k++) {
if ( jogada[j] == 'X' ) {
bola[k] = 10;
tipo[k] = STRIKE;
emPe = 10;
} else if ( jogada[j] == '/' ) {
bola[k] = emPe;
tipo[k] = SPARE;
emPe = 10;
} else {
bola[k] = to_int(jogada[j]);
tipo[k] = NORMAL;
emPe -= to_int(jogada[j]);
}
if ( i == 9 )
tipo[k] = NORMAL;
}
}
for (i = 0; i < k; total += bola[i], i++)
for (j = 0; j < tipo[i]; j++)
bola[i] += bola[i + j + 1];
cout << total;
return 0;
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using af::cfloat;
using af::cdouble;
template<typename T>
class ImageIO : public ::testing::Test
{
public:
virtual void SetUp() {
}
};
typedef ::testing::Types<float> TestTypes;
// register the type list
TYPED_TEST_CASE(ImageIO, TestTypes);
// Disable tests if FreeImage is not found
#if defined(WITH_FREEIMAGE)
void loadImageTest(string pTestFile, string pImageFile, const bool isColor)
{
if (noDoubleTests<float>()) return;
vector<af::dim4> numDims;
vector<vector<float> > in;
vector<vector<float> > tests;
readTests<float, float, float>(pTestFile,numDims,in,tests);
af::dim4 dims = numDims[0];
af_array imgArray = 0;
ASSERT_EQ(AF_SUCCESS, af_load_image(&imgArray, pImageFile.c_str(), isColor));
// Get result
float *imgData = new float[dims.elements()];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*) imgData, imgArray));
// Compare result
size_t nElems = in[0].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(in[0][elIter], imgData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] imgData;
if(imgArray != 0) af_destroy_array(imgArray);
}
TYPED_TEST(ImageIO, ColorSmall)
{
loadImageTest(string(TEST_DIR"/imageio/color_small.test"), string(TEST_DIR"/imageio/color_small.png"), true);
}
TYPED_TEST(ImageIO, GraySmall)
{
loadImageTest(string(TEST_DIR"/imageio/gray_small.test"), string(TEST_DIR"/imageio/gray_small.jpg"), false);
}
TYPED_TEST(ImageIO, GraySeq)
{
loadImageTest(string(TEST_DIR"/imageio/gray_seq.test"), string(TEST_DIR"/imageio/gray_seq.png"), false);
}
TYPED_TEST(ImageIO, ColorSeq)
{
loadImageTest(string(TEST_DIR"/imageio/color_seq.test"), string(TEST_DIR"/imageio/color_seq.png"), true);
}
void loadimageArgsTest(string pImageFile, const bool isColor, af_err err)
{
af_array imgArray = 0;
ASSERT_EQ(err, af_load_image(&imgArray, pImageFile.c_str(), isColor));
if(imgArray != 0) af_destroy_array(imgArray);
}
TYPED_TEST(ImageIO,InvalidArgsMissingFile)
{
loadimageArgsTest(string(TEST_DIR"/imageio/nofile.png"), false, AF_ERR_RUNTIME);
}
TYPED_TEST(ImageIO,InvalidArgsWrongExt)
{
loadimageArgsTest(string(TEST_DIR"/imageio/image.wrongext"), true, AF_ERR_NOT_SUPPORTED);
}
////////////////////////////////// CPP //////////////////////////////////////
TEST(ImageIO, CPP)
{
if (noDoubleTests<float>()) return;
vector<af::dim4> numDims;
vector<vector<float> > in;
vector<vector<float> > tests;
readTests<float, float, float>(string(TEST_DIR"/imageio/color_small.test"),numDims,in,tests);
af::dim4 dims = numDims[0];
af::array img = af::loadImage(string(TEST_DIR"/imageio/color_small.png").c_str(), true);
// Get result
float *imgData = new float[dims.elements()];
img.host((void*)imgData);
// Compare result
size_t nElems = in[0].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(in[0][elIter], imgData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] imgData;
}
#endif // WITH_FREEIMAGE
<commit_msg>Image save tests<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using af::cfloat;
using af::cdouble;
template<typename T>
class ImageIO : public ::testing::Test
{
public:
virtual void SetUp() {
}
};
typedef ::testing::Types<float> TestTypes;
// register the type list
TYPED_TEST_CASE(ImageIO, TestTypes);
// Disable tests if FreeImage is not found
#if defined(WITH_FREEIMAGE)
void loadImageTest(string pTestFile, string pImageFile, const bool isColor)
{
if (noDoubleTests<float>()) return;
vector<af::dim4> numDims;
vector<vector<float> > in;
vector<vector<float> > tests;
readTests<float, float, float>(pTestFile,numDims,in,tests);
af::dim4 dims = numDims[0];
af_array imgArray = 0;
ASSERT_EQ(AF_SUCCESS, af_load_image(&imgArray, pImageFile.c_str(), isColor));
// Get result
float *imgData = new float[dims.elements()];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*) imgData, imgArray));
// Compare result
size_t nElems = in[0].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(in[0][elIter], imgData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] imgData;
if(imgArray != 0) af_destroy_array(imgArray);
}
TYPED_TEST(ImageIO, ColorSmall)
{
loadImageTest(string(TEST_DIR"/imageio/color_small.test"), string(TEST_DIR"/imageio/color_small.png"), true);
}
TYPED_TEST(ImageIO, GraySmall)
{
loadImageTest(string(TEST_DIR"/imageio/gray_small.test"), string(TEST_DIR"/imageio/gray_small.jpg"), false);
}
TYPED_TEST(ImageIO, GraySeq)
{
loadImageTest(string(TEST_DIR"/imageio/gray_seq.test"), string(TEST_DIR"/imageio/gray_seq.png"), false);
}
TYPED_TEST(ImageIO, ColorSeq)
{
loadImageTest(string(TEST_DIR"/imageio/color_seq.test"), string(TEST_DIR"/imageio/color_seq.png"), true);
}
void loadimageArgsTest(string pImageFile, const bool isColor, af_err err)
{
af_array imgArray = 0;
ASSERT_EQ(err, af_load_image(&imgArray, pImageFile.c_str(), isColor));
if(imgArray != 0) af_destroy_array(imgArray);
}
TYPED_TEST(ImageIO,InvalidArgsMissingFile)
{
loadimageArgsTest(string(TEST_DIR"/imageio/nofile.png"), false, AF_ERR_RUNTIME);
}
TYPED_TEST(ImageIO,InvalidArgsWrongExt)
{
loadimageArgsTest(string(TEST_DIR"/imageio/image.wrongext"), true, AF_ERR_NOT_SUPPORTED);
}
////////////////////////////////// CPP //////////////////////////////////////
TEST(ImageIO, CPP)
{
if (noDoubleTests<float>()) return;
vector<af::dim4> numDims;
vector<vector<float> > in;
vector<vector<float> > tests;
readTests<float, float, float>(string(TEST_DIR"/imageio/color_small.test"),numDims,in,tests);
af::dim4 dims = numDims[0];
af::array img = af::loadImage(string(TEST_DIR"/imageio/color_small.png").c_str(), true);
// Get result
float *imgData = new float[dims.elements()];
img.host((void*)imgData);
// Compare result
size_t nElems = in[0].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(in[0][elIter], imgData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] imgData;
}
TEST(ImageIO, SavePNGCPP) {
af::array input(10, 10, 3, f32);
input(af::span, af::span, af::span) = 0;
input(0, 0, 0) = 255;
input(0, 9, 1) = 255;
input(9, 0, 2) = 255;
input(9, 9, af::span) = 255;
saveImage("SaveCPP.png", input);
af::array out = af::loadImage("SaveCPP.png", true);
ASSERT_FALSE(af::anytrue<bool>(out - input));
}
TEST(ImageIO, SaveBMPCPP) {
af::array input(10, 10, 3, f32);
input(af::span, af::span, af::span) = 0;
input(0, 0, 0) = 255;
input(0, 9, 1) = 255;
input(9, 0, 2) = 255;
input(9, 9, af::span) = 255;
saveImage("SaveCPP.bmp", input);
af::array out = af::loadImage("SaveCPP.bmp", true);
ASSERT_FALSE(af::anytrue<bool>(out - input));
}
#endif // WITH_FREEIMAGE
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dispatchrecordersupplier.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-19 10:58:01 $
*
* 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 __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#define __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
//_________________________________________________________________________________________________________________
// include own things
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif
#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif
//_________________________________________________________________________________________________________________
// include interfaces
#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHRECORDERSUPPLIER_HPP_
#include <com/sun/star/frame/XDispatchRecorderSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.HPP>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
//_________________________________________________________________________________________________________________
// include other projects
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
namespace framework{
//_________________________________________________________________________________________________________________
// exported const
//_________________________________________________________________________________________________________________
// exported definitions
//_______________________________________________
/** @short implement a supplier for dispatch recorder
@descr This supplier can be set on property "DispatchRecorderSupplier" on a frame.
By using of this supplier and his internal XDispatchRecorder it's possible to
record XDispatch::dispatch() requests.
@threadsafe yes
*/
class DispatchRecorderSupplier : // interfaces
public css::lang::XTypeProvider ,
public css::lang::XServiceInfo ,
public css::frame::XDispatchRecorderSupplier ,
// baseclasses
// Order is neccessary for right initialization!
private ThreadHelpBase ,
public ::cppu::OWeakObject
{
//___________________________________________
// member
private:
//_______________________________________
/** provided dispatch recorder of this supplier instance
@life Is controled from outside. Because this variable is setted
from there and not created internaly. But we release our
reference to it if we die.
*/
css::uno::Reference< css::frame::XDispatchRecorder > m_xDispatchRecorder;
//_______________________________________
/** reference to the global uno service manager
*/
css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;
//___________________________________________
// uno interface
public:
//_______________________________________
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
//_______________________________________
// XDispatchRecorderSupplier
virtual void SAL_CALL setDispatchRecorder( const css::uno::Reference< css::frame::XDispatchRecorder >& xRecorder ) throw (css::uno::RuntimeException);
virtual css::uno::Reference< css::frame::XDispatchRecorder > SAL_CALL getDispatchRecorder( ) throw (css::uno::RuntimeException);
virtual void SAL_CALL dispatchAndRecord ( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ,
const css::uno::Reference< css::frame::XDispatch >& xDispatcher ) throw (css::uno::RuntimeException);
//___________________________________________
// native interface
public:
DispatchRecorderSupplier( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory );
~DispatchRecorderSupplier();
}; // class DispatchRecorderSupplier
} // namespace framework
#endif // #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.3.318); FILE MERGED 2008/04/01 15:18:21 thb 1.3.318.3: #i85898# Stripping all external header guards 2008/04/01 10:57:51 thb 1.3.318.2: #i85898# Stripping all external header guards 2008/03/28 15:34:47 rt 1.3.318.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dispatchrecordersupplier.hxx,v $
* $Revision: 1.4 $
*
* 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 __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#define __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
//_________________________________________________________________________________________________________________
// include own things
#include <threadhelp/threadhelpbase.hxx>
#include <macros/xinterface.hxx>
#include <macros/xtypeprovider.hxx>
#include <macros/xserviceinfo.hxx>
#include <macros/debug.hxx>
#include <macros/generic.hxx>
#include <general.h>
#include <stdtypes.h>
//_________________________________________________________________________________________________________________
// include interfaces
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/frame/XDispatchRecorderSupplier.hpp>
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.HPP>
#endif
#include <com/sun/star/util/URL.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
//_________________________________________________________________________________________________________________
// include other projects
#include <cppuhelper/weak.hxx>
//_________________________________________________________________________________________________________________
// namespace
namespace framework{
//_________________________________________________________________________________________________________________
// exported const
//_________________________________________________________________________________________________________________
// exported definitions
//_______________________________________________
/** @short implement a supplier for dispatch recorder
@descr This supplier can be set on property "DispatchRecorderSupplier" on a frame.
By using of this supplier and his internal XDispatchRecorder it's possible to
record XDispatch::dispatch() requests.
@threadsafe yes
*/
class DispatchRecorderSupplier : // interfaces
public css::lang::XTypeProvider ,
public css::lang::XServiceInfo ,
public css::frame::XDispatchRecorderSupplier ,
// baseclasses
// Order is neccessary for right initialization!
private ThreadHelpBase ,
public ::cppu::OWeakObject
{
//___________________________________________
// member
private:
//_______________________________________
/** provided dispatch recorder of this supplier instance
@life Is controled from outside. Because this variable is setted
from there and not created internaly. But we release our
reference to it if we die.
*/
css::uno::Reference< css::frame::XDispatchRecorder > m_xDispatchRecorder;
//_______________________________________
/** reference to the global uno service manager
*/
css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;
//___________________________________________
// uno interface
public:
//_______________________________________
// XInterface, XTypeProvider, XServiceInfo
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
DECLARE_XSERVICEINFO
//_______________________________________
// XDispatchRecorderSupplier
virtual void SAL_CALL setDispatchRecorder( const css::uno::Reference< css::frame::XDispatchRecorder >& xRecorder ) throw (css::uno::RuntimeException);
virtual css::uno::Reference< css::frame::XDispatchRecorder > SAL_CALL getDispatchRecorder( ) throw (css::uno::RuntimeException);
virtual void SAL_CALL dispatchAndRecord ( const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments ,
const css::uno::Reference< css::frame::XDispatch >& xDispatcher ) throw (css::uno::RuntimeException);
//___________________________________________
// native interface
public:
DispatchRecorderSupplier( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory );
~DispatchRecorderSupplier();
}; // class DispatchRecorderSupplier
} // namespace framework
#endif // #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/core/behavior/BaseMechanicalState.h>
namespace sofa
{
namespace core
{
namespace behavior
{
BaseMechanicalState::BaseMechanicalState()
: useMask(initData(&useMask, true, "useMask", "Usage of a mask to optimize the computation of the system, highly reducing the passage through the mappings"))
, forceMask(helper::ParticleMask(useMask.getValue()))
{
}
BaseMechanicalState::~BaseMechanicalState()
{
}
/// Perform a sequence of linear vector accumulation operation $r_i = sum_j (v_j*f_{ij})$
///
/// This is used to compute in on steps operations such as $v = v + a*dt, x = x + v*dt$.
/// Note that if the result vector appears inside the expression, it must be the first operand.
/// By default this method decompose the computation into multiple vOp calls.
void BaseMechanicalState::vMultiOp(const VMultiOp& ops)
{
for(VMultiOp::const_iterator it = ops.begin(), itend = ops.end(); it != itend; ++it)
{
VecId r = it->first.getId(this);
const helper::vector< std::pair< ConstMultiVecId, double > >& operands = it->second;
int nop = operands.size();
if (nop==0)
{
vOp(r);
}
else if (nop==1)
{
if (operands[0].second == 1.0)
vOp(r, operands[0].first.getId(this));
else
vOp(r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
}
else
{
int i;
if (operands[0].second == 1.0)
{
vOp(r, operands[0].first.getId(this), operands[1].first.getId(this), operands[1].second);
i = 2;
}
else
{
vOp(r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
i = 1;
}
for (; i<nop; ++i)
vOp(r, r, operands[i].first.getId(this), operands[i].second);
}
}
}
} // namespace behavior
} // namespace core
} // namespace sofa
<commit_msg>r8656/sofa-dev : Trying to fix crash in ParticleMask due to reference to Data<bool> that might be using a temporary instance created by the compiler<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* 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. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: [email protected] *
******************************************************************************/
#include <sofa/core/behavior/BaseMechanicalState.h>
namespace sofa
{
namespace core
{
namespace behavior
{
BaseMechanicalState::BaseMechanicalState()
: useMask(initData(&useMask, true, "useMask", "Usage of a mask to optimize the computation of the system, highly reducing the passage through the mappings"))
, forceMask(&useMask)
{
}
BaseMechanicalState::~BaseMechanicalState()
{
}
/// Perform a sequence of linear vector accumulation operation $r_i = sum_j (v_j*f_{ij})$
///
/// This is used to compute in on steps operations such as $v = v + a*dt, x = x + v*dt$.
/// Note that if the result vector appears inside the expression, it must be the first operand.
/// By default this method decompose the computation into multiple vOp calls.
void BaseMechanicalState::vMultiOp(const VMultiOp& ops)
{
for(VMultiOp::const_iterator it = ops.begin(), itend = ops.end(); it != itend; ++it)
{
VecId r = it->first.getId(this);
const helper::vector< std::pair< ConstMultiVecId, double > >& operands = it->second;
int nop = operands.size();
if (nop==0)
{
vOp(r);
}
else if (nop==1)
{
if (operands[0].second == 1.0)
vOp(r, operands[0].first.getId(this));
else
vOp(r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
}
else
{
int i;
if (operands[0].second == 1.0)
{
vOp(r, operands[0].first.getId(this), operands[1].first.getId(this), operands[1].second);
i = 2;
}
else
{
vOp(r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
i = 1;
}
for (; i<nop; ++i)
vOp(r, r, operands[i].first.getId(this), operands[i].second);
}
}
}
} // namespace behavior
} // namespace core
} // namespace sofa
<|endoftext|> |
<commit_before>#include <cassert>
#include <iostream>
#include "dinit.h"
#include "service.h"
#include "baseproc-sys.h"
#include "control.h"
#define RUN_TEST(name) \
std::cout << #name "... "; \
name(); \
std::cout << "PASSED" << std::endl;
void cptest1()
{
service_set sset;
int fd = bp_sys::allocfd();
auto *cc = new control_conn_t(event_loop, &sset, fd);
bp_sys::supply_read_data(fd, { DINIT_CP_QUERYVERSION });
event_loop.regd_bidi_watchers[fd]->read_ready(event_loop, fd);
// Write will process immediately, so there's no need for this:
//event_loop.regd_bidi_watchers[fd]->write_ready(event_loop, fd);
// We expect a version number back:
std::vector<char> wdata;
bp_sys::extract_written_data(fd, wdata);
assert(wdata.size() == 5);
assert(wdata[0] == DINIT_RP_CPVERSION);
delete cc;
}
int main(int argc, char **argv)
{
RUN_TEST(cptest1);
return 0;
}
<commit_msg>tests: add c.p. test for list services command.<commit_after>#include <cassert>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include "dinit.h"
#include "service.h"
#include "baseproc-sys.h"
#include "control.h"
// Control protocol tests.
void cptest_queryver()
{
service_set sset;
int fd = bp_sys::allocfd();
auto *cc = new control_conn_t(event_loop, &sset, fd);
bp_sys::supply_read_data(fd, { DINIT_CP_QUERYVERSION });
event_loop.regd_bidi_watchers[fd]->read_ready(event_loop, fd);
// Write will process immediately, so there's no need for this:
//event_loop.regd_bidi_watchers[fd]->write_ready(event_loop, fd);
// We expect a version number back:
std::vector<char> wdata;
bp_sys::extract_written_data(fd, wdata);
assert(wdata.size() == 5);
assert(wdata[0] == DINIT_RP_CPVERSION);
delete cc;
}
void cptest_listservices()
{
service_set sset;
service_record *s1 = new service_record(&sset, "test-service-1", service_type_t::INTERNAL, {});
sset.add_service(s1);
service_record *s2 = new service_record(&sset, "test-service-2", service_type_t::INTERNAL, {});
sset.add_service(s2);
service_record *s3 = new service_record(&sset, "test-service-3", service_type_t::INTERNAL, {});
sset.add_service(s3);
int fd = bp_sys::allocfd();
auto *cc = new control_conn_t(event_loop, &sset, fd);
bp_sys::supply_read_data(fd, { DINIT_CP_LISTSERVICES });
event_loop.regd_bidi_watchers[fd]->read_ready(event_loop, fd);
// Write will process immediately, so there's no need for this:
//event_loop.regd_bidi_watchers[fd]->write_ready(event_loop, fd);
// We expect, for each service:
// (1 byte) DINIT_RP_SVCINFO
// (1 byte) service name length
// (1 byte) state
// (1 byte) target state
// (1 byte) flags: has console, waiting for console, start skipped
// (1 byte) stop reason
// (2 bytes) reserved
// (? bytes) exit status (int) / process id (pid_t)
// (N bytes) service name
std::vector<char> wdata;
bp_sys::extract_written_data(fd, wdata);
std::set<std::string> names = {"test-service-1", "test-service-2", "test-service-3"};
int pos = 0;
for (int i = 0; i < 3; i++) {
assert(wdata[pos++] == DINIT_RP_SVCINFO);
unsigned char name_len_c = wdata[pos++];
pos += 6;
pos += std::max(sizeof(int), sizeof(pid_t));
std::string name;
for (int j = 0; j < (int)name_len_c; j++) {
name += wdata[pos++];
}
// Check the service name matches one from the set, and remove it:
auto fn = names.find(name);
assert (fn != names.end());
names.erase(fn);
}
delete cc;
}
#define RUN_TEST(name, spacing) \
std::cout << #name "..." spacing; \
name(); \
std::cout << "PASSED" << std::endl;
int main(int argc, char **argv)
{
RUN_TEST(cptest_queryver, " ");
RUN_TEST(cptest_listservices, "");
return 0;
}
<|endoftext|> |
<commit_before>/**
** \file libport/file-library.cc
** \brief Implements libport::file_library.
*/
#include <cstdlib>
#include <stdexcept>
#include <iostream>
#include "libport/config.h"
#ifdef LIBPORT_HAVE_DIRECT_H
# include <direct.h>
#endif
#ifdef LIBPORT_HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#include "libport/contract.hh"
#include "libport/file-library.hh"
#include "libport/foreach.hh"
#include "libport/unistd.h"
#ifndef MAXPATHLEN
# define MAXPATHLEN 4096
#endif
namespace libport
{
void
file_library::push_cwd ()
{
// Store the working directory
char cwd[MAXPATHLEN + 1];
if (!getcwd (cwd, MAXPATHLEN))
throw std::runtime_error ("working directory name too long");
push_current_directory (cwd);
}
file_library::file_library ()
{
push_cwd ();
}
file_library::file_library (path p)
{
push_cwd ();
// Then only process given path.
search_path_.push_back (p);
}
void
file_library::append_dir_list (std::string path_list)
{
std::string::size_type pos;
while ((pos = path_list.find (':')) != std::string::npos)
{
append_dir (path_list.substr (0, pos));
path_list.erase (0, pos + 1);
}
append_dir (path_list);
}
path
file_library::ensure_absolute_path (path p) const
{
if (p.absolute_get ())
return p;
else
return current_directory_get () / p;
}
void
file_library::push_back (path p)
{
search_path_.push_back (ensure_absolute_path (p));
}
void
file_library::push_front (path p)
{
search_path_.push_front (ensure_absolute_path (p));
}
void
file_library::push_current_directory (path p)
{
// Ensure that path is absolute.
if (!p.absolute_get ())
p = this->current_directory_get () / p;
current_directory_.push_front (p);
}
void
file_library::pop_current_directory ()
{
precondition (!current_directory_.empty ());
current_directory_.pop_front ();
}
path
file_library::current_directory_get () const
{
precondition (!current_directory_.empty ());
return *current_directory_.begin ();
}
path
file_library::find_file (const path& file)
{
// Split file in two components, basename and basedir.
path directory = file.dirname();
if (directory.absolute_get ())
{
// If file is absolute, just check that it exists.
if (!file.exists())
return path ();
else
return directory;
}
else
{
// Does the file can be found in current directory?
if (find_in_directory (current_directory_get (), file))
return (current_directory_get () / file).dirname();
else
return find_in_search_path (directory, file.basename());
}
}
bool
file_library::find_in_directory (const path& dir,
const std::string& file) const
{
return (dir / file).exists();
}
path
file_library::find_in_search_path (const path& relative_path,
const std::string& filename) const
{
path checked_dir;
// Otherwise start scanning the search path.
foreach (const path& p, search_path_)
{
if (p.absolute_get ())
checked_dir = p;
else
checked_dir = current_directory_get () / p;
checked_dir /= relative_path;
if (find_in_directory (checked_dir, filename))
return checked_dir;
}
// File not found in search path.
return path ();
}
std::ostream&
file_library::dump (std::ostream& ostr) const
{
ostr << ".";
for (path_list_type::const_iterator it = search_path_.begin ();
it != search_path_.end ();
++it)
ostr << ":" << *it;
return ostr;
}
}
<commit_msg>Add comment regarding the second argument of getcwd()<commit_after>/**
** \file libport/file-library.cc
** \brief Implements libport::file_library.
*/
#include <cstdlib>
#include <stdexcept>
#include <iostream>
#include "libport/config.h"
#ifdef LIBPORT_HAVE_DIRECT_H
# include <direct.h>
#endif
#ifdef LIBPORT_HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#include "libport/contract.hh"
#include "libport/file-library.hh"
#include "libport/foreach.hh"
#include "libport/unistd.h"
#ifndef MAXPATHLEN
# define MAXPATHLEN 4096
#endif
namespace libport
{
void
file_library::push_cwd ()
{
// Store the working directory
char cwd[MAXPATHLEN + 1];
// The various getcwd() documentations are not clear on whether the
// NUL string terminator is accounted for in the length or not. To err
// on the safe side, we assume it is not.
if (!getcwd (cwd, MAXPATHLEN))
throw std::runtime_error ("working directory name too long");
push_current_directory (cwd);
}
file_library::file_library ()
{
push_cwd ();
}
file_library::file_library (path p)
{
push_cwd ();
// Then only process given path.
search_path_.push_back (p);
}
void
file_library::append_dir_list (std::string path_list)
{
std::string::size_type pos;
while ((pos = path_list.find (':')) != std::string::npos)
{
append_dir (path_list.substr (0, pos));
path_list.erase (0, pos + 1);
}
append_dir (path_list);
}
path
file_library::ensure_absolute_path (path p) const
{
if (p.absolute_get ())
return p;
else
return current_directory_get () / p;
}
void
file_library::push_back (path p)
{
search_path_.push_back (ensure_absolute_path (p));
}
void
file_library::push_front (path p)
{
search_path_.push_front (ensure_absolute_path (p));
}
void
file_library::push_current_directory (path p)
{
// Ensure that path is absolute.
if (!p.absolute_get ())
p = this->current_directory_get () / p;
current_directory_.push_front (p);
}
void
file_library::pop_current_directory ()
{
precondition (!current_directory_.empty ());
current_directory_.pop_front ();
}
path
file_library::current_directory_get () const
{
precondition (!current_directory_.empty ());
return *current_directory_.begin ();
}
path
file_library::find_file (const path& file)
{
// Split file in two components, basename and basedir.
path directory = file.dirname();
if (directory.absolute_get ())
{
// If file is absolute, just check that it exists.
if (!file.exists())
return path ();
else
return directory;
}
else
{
// Does the file can be found in current directory?
if (find_in_directory (current_directory_get (), file))
return (current_directory_get () / file).dirname();
else
return find_in_search_path (directory, file.basename());
}
}
bool
file_library::find_in_directory (const path& dir,
const std::string& file) const
{
return (dir / file).exists();
}
path
file_library::find_in_search_path (const path& relative_path,
const std::string& filename) const
{
path checked_dir;
// Otherwise start scanning the search path.
foreach (const path& p, search_path_)
{
if (p.absolute_get ())
checked_dir = p;
else
checked_dir = current_directory_get () / p;
checked_dir /= relative_path;
if (find_in_directory (checked_dir, filename))
return checked_dir;
}
// File not found in search path.
return path ();
}
std::ostream&
file_library::dump (std::ostream& ostr) const
{
ostr << ".";
for (path_list_type::const_iterator it = search_path_.begin ();
it != search_path_.end ();
++it)
ostr << ":" << *it;
return ostr;
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QPainter>
#include <QPropertyAnimation>
#include "mspinnerview.h"
#include "mspinnerview_p.h"
#include "mprogressindicator.h"
#include "mtheme.h"
MSpinnerViewPrivate::MSpinnerViewPrivate()
: q_ptr(NULL),
controller(NULL),
positionAnimation(NULL),
currentFrame(0)
{
}
MSpinnerViewPrivate::~MSpinnerViewPrivate()
{
delete positionAnimation;
releaseUsedPixmaps();
}
QPropertyAnimation *MSpinnerViewPrivate::createAnimation()
{
Q_Q(MSpinnerView);
QPropertyAnimation *animation = new QPropertyAnimation(q, "currentFrame", q);
animation->setLoopCount(-1);
return animation;
}
void MSpinnerViewPrivate::refreshStyle()
{
Q_Q(MSpinnerView);
positionAnimation->setDuration(q->style()->period());
positionAnimation->setStartValue(0);
positionAnimation->setEndValue(q->style()->numberOfFrames());
reloadFrames();
}
void MSpinnerViewPrivate::refreshModel()
{
Q_Q(MSpinnerView);
if (q->model()->unknownDuration()) {
if (positionAnimation->state() == QPropertyAnimation::Paused)
positionAnimation->resume();
else
positionAnimation->start();
} else {
if (positionAnimation->state() == QPropertyAnimation::Running)
positionAnimation->pause();
}
}
void MSpinnerViewPrivate::reloadFrames()
{
Q_Q(MSpinnerView);
releaseUsedPixmaps();
// Starts from 1 because that's the agreed convention
// for the image file names
for (int i = 1; i <= q->style()->numberOfFrames(); i++) {
QString frame_name = QString("%1_%2_%3").arg(q->style()->baseImageName())\
.arg(q->style()->baseImageSize())\
.arg(i);
const QPixmap *p = MTheme::pixmap(frame_name);
animationPixmaps << p;
}
}
void MSpinnerViewPrivate::releaseUsedPixmaps()
{
foreach(const QPixmap *p, animationPixmaps)
MTheme::releasePixmap(p);
animationPixmaps.clear();
}
void MSpinnerViewPrivate::_q_resumeAnimation()
{
Q_Q(MSpinnerView);
if (q->model()->unknownDuration()) {
if (positionAnimation->state() == QPropertyAnimation::Paused)
positionAnimation->resume();
}
}
void MSpinnerViewPrivate::_q_pauseAnimation()
{
if (positionAnimation->state() == QPropertyAnimation::Running)
positionAnimation->pause();
}
void MSpinnerViewPrivate::_q_pauseOrResumeAnimation()
{
if (controller->isVisible() && controller->isOnDisplay())
_q_resumeAnimation();
else
_q_pauseAnimation();
}
MSpinnerView::MSpinnerView(MProgressIndicator *controller) :
MWidgetView(controller),
d_ptr(new MSpinnerViewPrivate)
{
Q_D(MSpinnerView);
d->q_ptr = this;
d->controller = controller;
d->positionAnimation = d->createAnimation();
connect(controller, SIGNAL(visibleChanged()), this, SLOT(_q_pauseOrResumeAnimation()));
connect(controller, SIGNAL(displayEntered()), this, SLOT(_q_pauseOrResumeAnimation()));
connect(controller, SIGNAL(displayExited()), this, SLOT(_q_pauseOrResumeAnimation()));
}
MSpinnerView::~MSpinnerView()
{
delete d_ptr;
}
int MSpinnerView::currentFrame() const
{
Q_D(const MSpinnerView);
return d->currentFrame;
}
void MSpinnerView::setCurrentFrame(int currentFrame)
{
Q_D(MSpinnerView);
if (currentFrame >= d->animationPixmaps.length())
currentFrame %= d->animationPixmaps.length();
d->currentFrame = currentFrame;
update();
}
void MSpinnerView::updateData(const QList<const char *>& modifications)
{
Q_D(MSpinnerView);
MWidgetView::updateData(modifications);
foreach(const char * member, modifications) {
if (member == MProgressIndicatorModel::UnknownDuration)
d->refreshModel();
}
update();
}
void MSpinnerView::applyStyle()
{
Q_D(MSpinnerView);
MWidgetView::applyStyle();
d->refreshStyle();
}
void MSpinnerView::setupModel()
{
Q_D(MSpinnerView);
MWidgetView::setupModel();
d->refreshModel();
}
void MSpinnerView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MSpinnerView);
if (d->animationPixmaps.isEmpty())
return;
const QPixmap *p = d->animationPixmaps[d->currentFrame];
if (p && !p->isNull())
painter->drawPixmap(QRectF(QPointF(0, 0), size()), *p, QRectF(p->rect()));
}
#include "moc_mspinnerview.cpp"
// bind controller widget and view widget together by registration macro
M_REGISTER_VIEW_NEW(MSpinnerView, MProgressIndicator)
<commit_msg>Fixes: NB#217657 - COREWEB: /usr/bin/cherry '__aeabi_ldiv0 MSpinnerView::setCurrentFrame MSpinnerView::qt_metacall QMetaObject::metacall'<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QPainter>
#include <QPropertyAnimation>
#include "mspinnerview.h"
#include "mspinnerview_p.h"
#include "mprogressindicator.h"
#include "mtheme.h"
MSpinnerViewPrivate::MSpinnerViewPrivate()
: q_ptr(NULL),
controller(NULL),
positionAnimation(NULL),
currentFrame(0)
{
}
MSpinnerViewPrivate::~MSpinnerViewPrivate()
{
delete positionAnimation;
releaseUsedPixmaps();
}
QPropertyAnimation *MSpinnerViewPrivate::createAnimation()
{
Q_Q(MSpinnerView);
QPropertyAnimation *animation = new QPropertyAnimation(q, "currentFrame", q);
animation->setLoopCount(-1);
return animation;
}
void MSpinnerViewPrivate::refreshStyle()
{
Q_Q(MSpinnerView);
positionAnimation->setDuration(q->style()->period());
positionAnimation->setStartValue(0);
positionAnimation->setEndValue(q->style()->numberOfFrames());
reloadFrames();
}
void MSpinnerViewPrivate::refreshModel()
{
Q_Q(MSpinnerView);
if (q->model()->unknownDuration()) {
if (positionAnimation->state() == QPropertyAnimation::Paused)
positionAnimation->resume();
else
positionAnimation->start();
} else {
if (positionAnimation->state() == QPropertyAnimation::Running)
positionAnimation->pause();
}
}
void MSpinnerViewPrivate::reloadFrames()
{
Q_Q(MSpinnerView);
releaseUsedPixmaps();
// Starts from 1 because that's the agreed convention
// for the image file names
for (int i = 1; i <= q->style()->numberOfFrames(); i++) {
QString frame_name = QString("%1_%2_%3").arg(q->style()->baseImageName())\
.arg(q->style()->baseImageSize())\
.arg(i);
const QPixmap *p = MTheme::pixmap(frame_name);
animationPixmaps << p;
}
}
void MSpinnerViewPrivate::releaseUsedPixmaps()
{
foreach(const QPixmap *p, animationPixmaps)
MTheme::releasePixmap(p);
animationPixmaps.clear();
}
void MSpinnerViewPrivate::_q_resumeAnimation()
{
Q_Q(MSpinnerView);
if (q->model()->unknownDuration()) {
if (positionAnimation->state() == QPropertyAnimation::Paused)
positionAnimation->resume();
}
}
void MSpinnerViewPrivate::_q_pauseAnimation()
{
if (positionAnimation->state() == QPropertyAnimation::Running)
positionAnimation->pause();
}
void MSpinnerViewPrivate::_q_pauseOrResumeAnimation()
{
if (controller->isVisible() && controller->isOnDisplay())
_q_resumeAnimation();
else
_q_pauseAnimation();
}
MSpinnerView::MSpinnerView(MProgressIndicator *controller) :
MWidgetView(controller),
d_ptr(new MSpinnerViewPrivate)
{
Q_D(MSpinnerView);
d->q_ptr = this;
d->controller = controller;
d->positionAnimation = d->createAnimation();
connect(controller, SIGNAL(visibleChanged()), this, SLOT(_q_pauseOrResumeAnimation()));
connect(controller, SIGNAL(displayEntered()), this, SLOT(_q_pauseOrResumeAnimation()));
connect(controller, SIGNAL(displayExited()), this, SLOT(_q_pauseOrResumeAnimation()));
}
MSpinnerView::~MSpinnerView()
{
delete d_ptr;
}
int MSpinnerView::currentFrame() const
{
Q_D(const MSpinnerView);
return d->currentFrame;
}
void MSpinnerView::setCurrentFrame(int currentFrame)
{
Q_D(MSpinnerView);
if (currentFrame >= d->animationPixmaps.length())
currentFrame = 0;
d->currentFrame = currentFrame;
update();
}
void MSpinnerView::updateData(const QList<const char *>& modifications)
{
Q_D(MSpinnerView);
MWidgetView::updateData(modifications);
foreach(const char * member, modifications) {
if (member == MProgressIndicatorModel::UnknownDuration)
d->refreshModel();
}
update();
}
void MSpinnerView::applyStyle()
{
Q_D(MSpinnerView);
MWidgetView::applyStyle();
d->refreshStyle();
}
void MSpinnerView::setupModel()
{
Q_D(MSpinnerView);
MWidgetView::setupModel();
d->refreshModel();
}
void MSpinnerView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
Q_UNUSED(option);
Q_D(const MSpinnerView);
if (d->animationPixmaps.isEmpty())
return;
const QPixmap *p = d->animationPixmaps[d->currentFrame];
if (p && !p->isNull())
painter->drawPixmap(QRectF(QPointF(0, 0), size()), *p, QRectF(p->rect()));
}
#include "moc_mspinnerview.cpp"
// bind controller widget and view widget together by registration macro
M_REGISTER_VIEW_NEW(MSpinnerView, MProgressIndicator)
<|endoftext|> |
<commit_before><commit_msg>Remove verbose log message<commit_after><|endoftext|> |
<commit_before><commit_msg>ClusterVarsAction fix<commit_after><|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.