text
stringlengths 54
60.6k
|
---|
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN set_intersection tests
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <cmath>
#include <functional>
#include <iterator>
#include <list>
#include <vector>
BOOST_AUTO_TEST_SUITE( set_intersection_test_suite )
BOOST_AUTO_TEST_CASE( empty_primary_input_default_compare )
{
const std::vector<int> primary;
const std::list<int> secondary{1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected;
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( empty_primary_input_custom_compare )
{
const std::vector<int> primary;
const std::list<int> secondary{3, 2, 1};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), std::greater<int>());
const std::vector<int> expected;
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( empty_primary_input_conversion_compare )
{
const std::vector<int> primary;
const std::list<int> secondary{1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), std::less<double>());
const std::vector<int> expected;
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( same_type_inputs_default_compare )
{
const std::vector<int> primary{1, 3, 4, 5, 6};
const std::list<int> secondary{1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected{1, 3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( same_type_inputs_custom_compare )
{
const std::vector<int> primary{1, -3, -4, 5, -6};
const std::list<int> secondary{1, -2, 3};
std::vector<int> output;
auto comp = [](int lhs, int rhs){ return std::less<int>()(std::abs(lhs), std::abs(rhs)); };
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), comp);
const std::vector<int> expected{1, -3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( same_type_inputs_conversion_compare )
{
const std::vector<int> primary{1, -3, -4, 5, -6};
const std::list<int> secondary{1, -2, 3};
std::vector<int> output;
auto comp = [](double lhs, double rhs){ return std::less<double>()(std::abs(lhs), std::abs(rhs)); };
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), comp);
const std::vector<int> expected{1, -3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( different_type_inputs_default_compare )
{
const std::vector<int> primary{1, 3, 4, 5, 6};
const std::list<double> secondary{1.1, 2, 4.0, 4.6};
std::vector<int> output;
/*! For the default compare between an int and a double, the int will be
* promoted to double first, so for example 1 will be considered different
* to 1.1, in which case none of them will be reported to the output
* iterator. */
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected{4};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( different_type_inputs_custom_compare )
{
const std::vector<int> primary{1, 3, 4, 5, 6};
const std::list<double> secondary{1.1, 2, 3.9, 4.6};
std::vector<int> output;
auto comp = [](int lhs, double rhs){ return std::less<double>()(static_cast<double>(lhs), std::floor(rhs)); };
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), comp);
const std::vector<int> expected{1, 3, 4};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( repeated_elements_default_compare )
{
const std::vector<int> primary{1, 1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 5, 6};
const std::list<int> secondary{1, 1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected{1, 1, 2, 3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_SUITE_END( /* set_intersection_test_suite */ )
<commit_msg>Adds two interesting cases for set_intersection.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN set_intersection tests
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <cmath>
#include <functional>
#include <iterator>
#include <list>
#include <vector>
BOOST_AUTO_TEST_SUITE( set_intersection_test_suite )
BOOST_AUTO_TEST_CASE( empty_primary_input_default_compare )
{
const std::vector<int> primary;
const std::list<int> secondary{1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected;
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( empty_primary_input_custom_compare )
{
const std::vector<int> primary;
const std::list<int> secondary{3, 2, 1};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), std::greater<int>());
const std::vector<int> expected;
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( empty_primary_input_conversion_compare )
{
const std::vector<int> primary;
const std::list<int> secondary{1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), std::less<double>());
const std::vector<int> expected;
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( same_type_inputs_default_compare )
{
const std::vector<int> primary{1, 3, 4, 5, 6};
const std::list<int> secondary{1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected{1, 3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( same_type_inputs_custom_compare )
{
const std::vector<int> primary{1, -3, -4, 5, -6};
const std::list<int> secondary{1, -2, 3};
std::vector<int> output;
auto comp = [](int lhs, int rhs){ return std::less<int>()(std::abs(lhs), std::abs(rhs)); };
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), comp);
const std::vector<int> expected{1, -3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( same_type_inputs_conversion_compare )
{
const std::vector<int> primary{1, -3, -4, 5, -6};
const std::list<int> secondary{1, -2, 3};
std::vector<int> output;
auto comp = [](double lhs, double rhs){ return std::less<double>()(std::abs(lhs), std::abs(rhs)); };
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), comp);
const std::vector<int> expected{1, -3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( different_type_inputs_default_compare )
{
const std::vector<int> primary{1, 3, 4, 5, 6};
const std::list<double> secondary{1.1, 2, 4.0, 4.6};
std::vector<int> output;
/*! For the default compare between an int and a double, the int will be
* promoted to double first, so for example 1 will be considered different
* to 1.1, in which case none of them will be reported to the output
* iterator. */
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected{4};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( different_type_inputs_custom_compare )
{
const std::vector<int> primary{1, 3, 4, 5, 6};
const std::list<double> secondary{1.1, 2, 3.9, 4.6};
std::vector<int> output;
auto comp = [](int lhs, double rhs){ return std::less<double>()(static_cast<double>(lhs), std::floor(rhs)); };
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), comp);
const std::vector<int> expected{1, 3, 4};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( repeated_elements_default_compare )
{
const std::vector<int> primary{1, 1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 5, 6};
const std::list<int> secondary{1, 1, 2, 3};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected{1, 1, 2, 3};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( different_output_type_default_compare )
{
const std::vector<double> primary{1, 3, 4.6, 5, 6};
const std::list<double> secondary{1.1, 2, 3.9, 4.6};
std::vector<int> output;
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output));
const std::vector<int> expected{4};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_CASE( different_output_type_custom_compare )
{
const std::vector<double> primary{-1.1, 1, -1, 3, 4.6, 5, 6};
const std::list<double> secondary{1.1, -2, 3.9, -4.6};
std::vector<int> output;
auto comp = [](double lhs, double rhs){ return std::less<double>()(std::abs(lhs), std::abs(rhs)); };
std::set_intersection(std::begin(primary), std::end(primary), std::begin(secondary), std::end(secondary), std::back_inserter(output), comp);
/*! Here is the interesting thing: -1.1 will be compared equal to 1.1 and
* reported to an output iterator that accepts ints. As the algorithm
* reports the element from the first collection, -1.1 will be cast to int,
* so the number in the output collection will be negative as well. */
const std::vector<int> expected{-1, 4};
BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(output), std::end(output), std::begin(expected), std::end(expected));
}
BOOST_AUTO_TEST_SUITE_END( /* set_intersection_test_suite */ )
<|endoftext|> |
<commit_before>/** Copyright (C) 2012 Aldebaran Robotics
*/
#ifndef _WIN32
#include <fnmatch.h>
#else
# include <shlwapi.h>
# pragma comment(lib, "shlwapi.lib")
#endif
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <qi/log.hpp>
#include <qi/application.hpp>
#include <qimessaging/session.hpp>
#include <qitype/jsoncodec.hpp>
#define foreach BOOST_FOREACH
const char* callType[] = {
"?", "C", "R", "E", "S"
};
typedef std::map<std::string, qi::AnyObject> ObjectMap;
ObjectMap objectMap;
bool numeric = false;
bool printMo = false;
bool disableTrace = false;
bool traceState = false;
bool cleaned = false;
std::string sdUrl;
std::vector<std::string> objectNames;
unsigned int maxServiceLength = 0;
qiLogCategory("qitrace");
void onTrace(ObjectMap::value_type ov, const qi::EventTrace& trace)
{
static unsigned int maxLen = 0;
std::string name = boost::lexical_cast<std::string>(trace.slotId);
if (!numeric)
{
qi::MetaObject mo = ov.second->metaObject();
qi::MetaMethod* m = mo.method(trace.slotId);
if (m)
name = m->name();
else
{
qi::MetaSignal* s = mo.signal(trace.slotId);
if (s)
name = s->name();
else
name = name + "(??" ")"; // trigraph protect mode on
}
}
maxLen = std::max(maxLen, (unsigned int)name.size());
unsigned int traceKind = trace.kind;
if (traceKind > 4)
traceKind = 0;
std::string spacing(maxLen + 8 - name.size(), ' ');
std::string spacing2(maxServiceLength + 8 - ov.first.size(), ' ');
std::cout << ov.first << spacing2 << trace.id << '\t' << callType[traceKind] << ' ' << name
<< spacing << trace.timestamp.tv_sec << '.' << trace.timestamp.tv_usec
<< "\t" << qi::encodeJSON(trace.arguments) << std::endl;
}
_QI_COMMAND_LINE_OPTIONS(
"Qitrace options",
("numeric,n", bool_switch(&numeric), "Do not resolve slot Ids to names")
("service-directory,s", value<std::string>(&sdUrl), "url to connect to")
("object,o", value<std::vector<std::string> >(&objectNames), "Object(s) to monitor, specify multiple times, comma-separate, use '*' for all, use '-globPattern' to remove from list")
("print,p", bool_switch(&printMo), "Print out the Metaobject and exit")
("disable,d", bool_switch(&disableTrace), "Disable trace on objects and exit")
("trace-status", bool_switch(&traceState), "Show trace status on objects and exit")
);
int main(int argc, char** argv)
{
qi::Application app(argc, argv);
if (std::find(argv + 1, argv + argc, std::string("-h"))-argv < argc
|| std::find(argv + 1, argv + argc, std::string("--help"))-argv < argc)
return 0; // Fixme have Application report that!
qi::Session s;
if (sdUrl.empty())
sdUrl = "localhost";
qi::Url url(sdUrl, "tcp", 9559);
qiLogVerbose() << "Connecting to sd";
s.connect(url);
qiLogVerbose() << "Resolving services";
// resolve target service names
std::vector<std::string> services;
for (unsigned i=0; i<objectNames.size(); ++i)
{
std::vector<std::string> split;
boost::split(split, objectNames[i], boost::algorithm::is_any_of(","));
for (unsigned i=0; i<split.size(); ++i)
{
if (split[i].empty())
continue;
else if (split[i] == "*")
{
std::vector<qi::ServiceInfo> si = s.services();
for (unsigned i=0; i<si.size(); ++i)
services.push_back(si[i].name());
}
else if (split[i][0] == '-')
{
std::string pattern = split[i].substr(1);
for (unsigned i=0; i<services.size(); ++i)
{
if (qi::os::fnmatch(pattern, services[i]))
{
services[i] = services[services.size() - 1];
services.pop_back();
--i; // don't forget to check the new element we juste swaped in
}
}
}
else
services.push_back(split[i]);
}
}
std::vector<std::string> servicesOk;
qiLogVerbose() << "Fetching services: " << boost::join(services, ",");
// access services
for (unsigned i=0; i<services.size(); ++i)
{
qi::AnyObject o;
try
{
o = s.service(services[i]);
}
catch (const std::exception& e)
{
qiLogError() << "Error fetching " << services[i] << " : " << e.what();
services[i] = "";
continue;
}
if (!o)
{
qiLogError() << "Error fetching " << services[i];
services[i] = "";
continue;
}
objectMap[services[i]] = o;
servicesOk.push_back(services[i]);
if (printMo)
{
std::cout << "\n\n" << services[i] << "\n";
qi::details::printMetaObject(std::cout, o->metaObject());
}
if (disableTrace)
{
try
{
o->call<void>("enableTrace", false);
}
catch(...)
{}
}
if (traceState)
{
try
{
bool s = o->call<bool>("isTraceEnabled");
std::cout << services[i] << ": " << s << std::endl;
}
catch(...)
{}
}
}
if (printMo || disableTrace || traceState || objectMap.empty())
return 0;
qiLogVerbose() << "Monitoring services: " << boost::join(servicesOk, ",");
foreach(ObjectMap::value_type& ov, objectMap)
{
maxServiceLength = std::max(maxServiceLength, (unsigned int)ov.first.size());
ov.second->connect("traceObject", (boost::function<void(qi::EventTrace)>)
boost::bind(&onTrace, ov, _1)).async();
}
app.run();
while (!cleaned)
qi::os::msleep(20);
return 0;
}
<commit_msg>qitrace: more compressed output, display call user/system time used.<commit_after>/** Copyright (C) 2012 Aldebaran Robotics
*/
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/foreach.hpp>
#include <qi/log.hpp>
#include <qi/os.hpp>
#include <qi/application.hpp>
#include <qimessaging/session.hpp>
#include <qitype/jsoncodec.hpp>
#define foreach BOOST_FOREACH
const char* callType[] = {
"?", "C", "R", "E", "S"
};
typedef std::map<std::string, qi::AnyObject> ObjectMap;
ObjectMap objectMap;
bool numeric = false;
bool printMo = false;
bool disableTrace = false;
bool traceState = false;
bool cleaned = false;
bool full = false;
std::string sdUrl;
std::vector<std::string> objectNames;
unsigned int maxServiceLength = 0;
qiLogCategory("qitrace");
void onTrace(ObjectMap::value_type ov, const qi::EventTrace& trace)
{
static qi::int64_t secStart = 0;
if (!secStart && !full)
secStart = trace.timestamp().tv_sec;
static unsigned int maxLen = 0;
std::string name = boost::lexical_cast<std::string>(trace.slotId());
if (!numeric)
{
qi::MetaObject mo = ov.second->metaObject();
qi::MetaMethod* m = mo.method(trace.slotId());
if (m)
name = m->name();
else
{
qi::MetaSignal* s = mo.signal(trace.slotId());
if (s)
name = s->name();
else
name = name + "(??" ")"; // trigraph protect mode on
}
}
if (!full && name.size() > 25)
{
name = name.substr(0, 22) + "...";
}
std::string serviceName = ov.first;
if (!full && serviceName.size() > 17)
serviceName = serviceName.substr(0, 14) + "...";
maxLen = std::max(maxLen, (unsigned int)name.size());
unsigned int traceKind = trace.kind();
if (traceKind > 4)
traceKind = 0;
std::string spacing(maxLen + 2 - name.size(), ' ');
std::string spacing2((full?maxServiceLength:17) + 2 - ov.first.size(), ' ');
if (trace.kind() == qi::EventTrace::Event_Result)
{
std::cout << serviceName << spacing2 << trace.id() << ' ' << callType[traceKind] << ' ' << name
<< spacing << (trace.timestamp().tv_sec - secStart) << '.' << trace.timestamp().tv_usec
<< ' ' << trace.userUsTime() << ' ' << trace.systemUsTime() << ' ' << qi::encodeJSON(trace.arguments()) << std::endl;
}
else
{
std::cout << serviceName << spacing2 << trace.id() << ' ' << callType[traceKind] << ' ' << name
<< spacing << (trace.timestamp().tv_sec - secStart) << '.' << trace.timestamp().tv_usec
<< ' ' << qi::encodeJSON(trace.arguments()) << std::endl;
}
}
_QI_COMMAND_LINE_OPTIONS(
"Qitrace options",
("numeric,n", bool_switch(&numeric), "Do not resolve slot Ids to names")
("full,f", bool_switch(&full), "Do not abreviate anything")
("service-directory,s", value<std::string>(&sdUrl), "url to connect to")
("object,o", value<std::vector<std::string> >(&objectNames), "Object(s) to monitor, specify multiple times, comma-separate, use '*' for all, use '-globPattern' to remove from list")
("print,p", bool_switch(&printMo), "Print out the Metaobject and exit")
("disable,d", bool_switch(&disableTrace), "Disable trace on objects and exit")
("trace-status", bool_switch(&traceState), "Show trace status on objects and exit")
);
int main(int argc, char** argv)
{
qi::Application app(argc, argv);
if (std::find(argv + 1, argv + argc, std::string("-h"))-argv < argc
|| std::find(argv + 1, argv + argc, std::string("--help"))-argv < argc)
return 0; // Fixme have Application report that!
qi::Session s;
if (sdUrl.empty())
sdUrl = "localhost";
qi::Url url(sdUrl, "tcp", 9559);
qiLogVerbose() << "Connecting to sd";
s.connect(url);
qiLogVerbose() << "Resolving services";
// resolve target service names
std::vector<std::string> services;
for (unsigned i=0; i<objectNames.size(); ++i)
{
std::vector<std::string> split;
boost::split(split, objectNames[i], boost::algorithm::is_any_of(","));
for (unsigned i=0; i<split.size(); ++i)
{
if (split[i].empty())
continue;
else if (split[i] == "*")
{
std::vector<qi::ServiceInfo> si = s.services();
for (unsigned i=0; i<si.size(); ++i)
services.push_back(si[i].name());
}
else if (split[i][0] == '-')
{
std::string pattern = split[i].substr(1);
for (unsigned i=0; i<services.size(); ++i)
{
if (qi::os::fnmatch(pattern, services[i]))
{
services[i] = services[services.size() - 1];
services.pop_back();
--i; // don't forget to check the new element we juste swaped in
}
}
}
else
services.push_back(split[i]);
}
}
std::vector<std::string> servicesOk;
qiLogVerbose() << "Fetching services: " << boost::join(services, ",");
// access services
for (unsigned i=0; i<services.size(); ++i)
{
qi::AnyObject o;
try
{
o = s.service(services[i]);
}
catch (const std::exception& e)
{
qiLogError() << "Error fetching " << services[i] << " : " << e.what();
services[i] = "";
continue;
}
if (!o)
{
qiLogError() << "Error fetching " << services[i];
services[i] = "";
continue;
}
objectMap[services[i]] = o;
servicesOk.push_back(services[i]);
if (printMo)
{
std::cout << "\n\n" << services[i] << "\n";
qi::details::printMetaObject(std::cout, o->metaObject());
}
if (disableTrace)
{
try
{
o->call<void>("enableTrace", false);
}
catch(...)
{}
}
if (traceState)
{
try
{
bool s = o->call<bool>("isTraceEnabled");
std::cout << services[i] << ": " << s << std::endl;
}
catch(...)
{}
}
}
if (printMo || disableTrace || traceState || objectMap.empty())
return 0;
qiLogVerbose() << "Monitoring services: " << boost::join(servicesOk, ",");
foreach(ObjectMap::value_type& ov, objectMap)
{
maxServiceLength = std::max(maxServiceLength, (unsigned int)ov.first.size());
ov.second->connect("traceObject", (boost::function<void(qi::EventTrace)>)
boost::bind(&onTrace, ov, _1)).async();
}
app.run();
while (!cleaned)
qi::os::msleep(20);
return 0;
}
<|endoftext|> |
<commit_before>/*
kmsc - Kurento Media Server C/C++ implementation
Copyright (C) 2012 Tikal Technologies
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "JoinableServiceHandler.h"
#include <log.h>
using ::com::kurento::kms::JoinableServiceHandler;
using ::com::kurento::kms::MediaSessionImpl;
using ::com::kurento::kms::JoinableImpl;
using ::com::kurento::commons::mediaspec::_Direction_VALUES_TO_NAMES;
using ::com::kurento::log::Log;
static Log l("JoinableServiceHandler");
#define i(...) aux_info(l, __VA_ARGS__);
#define d(...) aux_debug(l, __VA_ARGS__);
#define w(...) aux_warn(l, __VA_ARGS__);
#define e(...) aux_error(l, __VA_ARGS__);
JoinableServiceHandler::JoinableServiceHandler() {
manager = MediaSessionManager::getInstance();
}
JoinableServiceHandler::~JoinableServiceHandler() {
MediaSessionManager::releaseInstance(manager);
}
void
JoinableServiceHandler::getStreams(std::vector<StreamType::type> &_return,
const Joinable& joinable) {
i("getStreams from joinable: %lld", joinable.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(joinable.session);
JoinableImpl &j = session.getJoinable(joinable);
j.getStreams(_return);
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::join(const Joinable& from, const Joinable& to,
const Direction direction) {
if (_Direction_VALUES_TO_NAMES.find(direction) == _Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
i("join %lld and %lld with direction %s", from.object.id, to.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.join(t, direction);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::unjoin(const Joinable& from, const Joinable& to) {
i("unjoin %lld and %lld", from.object.id, to.object.id);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.unjoin(t);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::joinStream(const Joinable& from, const Joinable& to,
const StreamType::type stream,
const Direction direction) {
if (_Direction_VALUES_TO_NAMES.find(direction) ==
_Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
i("joinStream %s of %lld with %lld with direction %s",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id, to.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.join(t, stream, direction);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::unjoinStream(const Joinable& from, const Joinable& to,
const StreamType::type stream) {
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
i("unjoinStream %s of %lld with %lld",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id, to.object.id);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.unjoin(t, stream);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getJoinees(std::vector<Joinable> &_return,
const Joinable& from) {
i("getJoinees of %lld", from.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getDirectionJoinees(std::vector<Joinable> &_return,
const Joinable& from,
const Direction direction) {
if (_Direction_VALUES_TO_NAMES.find(direction) ==
_Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
i("getDirectionJoiness of %lld with direction %s", from.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return, direction);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getStreamJoinees(std::vector<Joinable> &_return,
const Joinable& from,
const StreamType::type stream) {
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
i("getStreamJoinees of stream %s from %lld",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return, stream);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getStreamDirectionJoinees(std::vector<Joinable> &_return,
const Joinable& from,
const StreamType::type stream,
const Direction direction) {
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
if (_Direction_VALUES_TO_NAMES.find(direction) ==
_Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
i("getStreamDirectionJoinees of stream %s from %lld with direction %s",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return, stream, direction);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::release(const Joinable& joinable) {
i("release joinable %lld", joinable.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(joinable.session);
session.deleteJoinable(joinable);
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
<commit_msg>Improve exceptions thrown by release method and print them<commit_after>/*
kmsc - Kurento Media Server C/C++ implementation
Copyright (C) 2012 Tikal Technologies
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "JoinableServiceHandler.h"
#include <log.h>
using ::com::kurento::kms::JoinableServiceHandler;
using ::com::kurento::kms::MediaSessionImpl;
using ::com::kurento::kms::JoinableImpl;
using ::com::kurento::commons::mediaspec::_Direction_VALUES_TO_NAMES;
using ::com::kurento::log::Log;
static Log l("JoinableServiceHandler");
#define i(...) aux_info(l, __VA_ARGS__);
#define d(...) aux_debug(l, __VA_ARGS__);
#define w(...) aux_warn(l, __VA_ARGS__);
#define e(...) aux_error(l, __VA_ARGS__);
JoinableServiceHandler::JoinableServiceHandler() {
manager = MediaSessionManager::getInstance();
}
JoinableServiceHandler::~JoinableServiceHandler() {
MediaSessionManager::releaseInstance(manager);
}
void
JoinableServiceHandler::getStreams(std::vector<StreamType::type> &_return,
const Joinable& joinable) {
i("getStreams from joinable: %lld", joinable.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(joinable.session);
JoinableImpl &j = session.getJoinable(joinable);
j.getStreams(_return);
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::join(const Joinable& from, const Joinable& to,
const Direction direction) {
if (_Direction_VALUES_TO_NAMES.find(direction) == _Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
i("join %lld and %lld with direction %s", from.object.id, to.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.join(t, direction);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::unjoin(const Joinable& from, const Joinable& to) {
i("unjoin %lld and %lld", from.object.id, to.object.id);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.unjoin(t);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::joinStream(const Joinable& from, const Joinable& to,
const StreamType::type stream,
const Direction direction) {
if (_Direction_VALUES_TO_NAMES.find(direction) ==
_Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
i("joinStream %s of %lld with %lld with direction %s",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id, to.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.join(t, stream, direction);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::unjoinStream(const Joinable& from, const Joinable& to,
const StreamType::type stream) {
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
i("unjoinStream %s of %lld with %lld",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id, to.object.id);
try {
if (from.session != to.session) {
JoinException ex;
ex.__set_description("Joinables are not in the same "
"session");
throw ex;
}
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
JoinableImpl &t = session.getJoinable(to);
f.unjoin(t, stream);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getJoinees(std::vector<Joinable> &_return,
const Joinable& from) {
i("getJoinees of %lld", from.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getDirectionJoinees(std::vector<Joinable> &_return,
const Joinable& from,
const Direction direction) {
if (_Direction_VALUES_TO_NAMES.find(direction) ==
_Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
i("getDirectionJoiness of %lld with direction %s", from.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return, direction);
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getStreamJoinees(std::vector<Joinable> &_return,
const Joinable& from,
const StreamType::type stream) {
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
i("getStreamJoinees of stream %s from %lld",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return, stream);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::getStreamDirectionJoinees(std::vector<Joinable> &_return,
const Joinable& from,
const StreamType::type stream,
const Direction direction) {
if (_StreamType_VALUES_TO_NAMES.find(stream) ==
_StreamType_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid stream");
throw ex;
}
if (_Direction_VALUES_TO_NAMES.find(direction) ==
_Direction_VALUES_TO_NAMES.end()) {
JoinException ex;
ex.__set_description("Invalid direction");
throw ex;
}
i("getStreamDirectionJoinees of stream %s from %lld with direction %s",
_StreamType_VALUES_TO_NAMES.find(stream)->second,
from.object.id,
_Direction_VALUES_TO_NAMES.find(direction)->second);
try {
MediaSessionImpl &session = manager->getMediaSession(from.session);
JoinableImpl &f = session.getJoinable(from);
f.getJoinees(_return, stream, direction);
} catch(StreamNotFoundException ex) {
throw ex;
} catch(JoinException ex){
throw ex;
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("MediaSession not found");
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
void
JoinableServiceHandler::release(const Joinable& joinable) {
i("release joinable %lld", joinable.object.id);
try {
MediaSessionImpl &session = manager->getMediaSession(joinable.session);
session.deleteJoinable(joinable);
} catch(JoinableNotFoundException ex) {
throw ex;
} catch (MediaSessionNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("Joinable not found");
w(e.description);
throw e;
} catch (MixerNotFoundException ex) {
JoinableNotFoundException e;
e.__set_description("Joinable not found");
w(e.description);
throw e;
} catch (MediaServerException ex) {
throw ex;
} catch (...) {
MediaServerException ex;
ex.__set_description("Unkown exception found");
ex.__set_code(ErrorCode::type::UNEXPECTED);
throw ex;
}
}
<|endoftext|> |
<commit_before>#include <Poco/Exception.h>
#include <Poco/DateTime.h>
#include <Poco/DateTimeFormat.h>
#include <Poco/DateTimeFormatter.h>
#include <Poco/Logger.h>
#include <Poco/Net/HTTPServerParams.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include "rest/PocoRestRequestHandler.h"
#include "rest/RestFlow.h"
#include "rest/RestRouter.h"
#include "rest/RestLinker.h"
#include "server/SessionVerifier.h"
using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;
PocoRestRequestHandler::PocoRestRequestHandler(
RestAction::Ptr action,
const MappedRestAction::Params ¶ms,
ExpirableSession::Ptr session,
RestLinker &linker):
m_action(action),
m_params(params),
m_session(session),
m_linker(linker)
{
}
bool PocoRestRequestHandler::expectedContentLength(
HTTPServerRequest &req,
HTTPServerResponse &res)
{
const string &method = req.getMethod();
if (method != "POST" && method != "PUT" && method != "PATCH")
return true;;
if (!req.hasContentLength()) {
res.setStatusAndReason(HTTPResponse::HTTP_LENGTH_REQUIRED);
return false;
}
int inputMaxSize = m_action->inputMaxSize();
if (inputMaxSize < 0)
return true;
auto contentLength = req.getContentLength();
if (contentLength > inputMaxSize) {
if (logger().warning()) {
logger().warning(
"too long input: "
+ to_string(contentLength)
+ " for "
+ m_action->fullName(),
__FILE__, __LINE__);
}
res.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
return false;
}
return true;
}
string PocoRestRequestHandler::asString(const MappedRestAction::Params ¶ms) const
{
string s("[");
auto it = params.begin();
for (; it != params.end(); ++it) {
if (it != params.begin())
s.append(", ");
s.append(it->first);
s.append(" => ");
s.append(it->second);
}
s.append("]");
return s;
}
void PocoRestRequestHandler::prepareInternalAction(
RestAction::Ptr action,
HTTPServerRequest &req,
HTTPServerResponse &res) const
{
req.set("Cache-Control", "public, no-cache");
}
void PocoRestRequestHandler::prepareMappedAction(
MappedRestAction::Ptr action,
HTTPServerRequest &req,
HTTPServerResponse &res) const
{
if (action->caching() == 0) {
req.set("Cache-Control", "public, no-cache");
}
else {
const Timespan shift(action->caching(), 0);
const DateTime now;
res.set("Expires",
DateTimeFormatter::format(now + shift, DateTimeFormat::HTTP_FORMAT));
res.set("Cache-Control",
"max-age=" + to_string(shift.totalSeconds()) + ", must-revalidate");
}
}
void PocoRestRequestHandler::handleRequest(
HTTPServerRequest &req,
HTTPServerResponse &res)
{
if (logger().debug()) {
logger().debug("serving request "
+ req.getMethod()
+ " "
+ req.getURI()
+ " via action "
+ m_action->fullName()
+ " "
+ asString(m_params),
__FILE__, __LINE__);
}
if (logger().trace()) {
for (const auto &pair : req) {
logger().trace(
pair.first
+ ": "
+ pair.second,
__FILE__, __LINE__);
}
}
if (!expectedContentLength(req, res)) {
res.send();
return;
}
Poco::URI uri(req.getURI());
RestFlow flow(
m_linker,
uri,
m_params,
PocoRequest(req),
PocoResponse(res)
);
MappedRestAction::Ptr mapped = m_action.cast<MappedRestAction>();
if (mapped.isNull())
prepareInternalAction(m_action, req, res);
else
prepareMappedAction(mapped, req, res);
const auto &call = m_action->call();
try {
flow.setSession(m_session);
call(flow);
return;
}
catch (const Exception &e) {
logger().log(e, __FILE__, __LINE__);
}
catch (const exception &e) {
logger().critical(e.what(), __FILE__, __LINE__);
}
catch (const char *m) {
logger().fatal(m, __FILE__, __LINE__);
}
catch (...) {
logger().fatal("unknown error occured", __FILE__, __LINE__);
}
if (res.sent())
return;
res.setStatusAndReason(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
PocoRestRequestFactory::PocoRestRequestFactory(
RestRouter &router,
SessionVerifier &verifier):
m_router(router),
m_sessionVerifier(verifier)
{
}
HTTPRequestHandler *PocoRestRequestFactory::handleNoRoute(const HTTPServerRequest &request)
{
if (logger().debug()) {
logger().debug("no action resolved for "
+ request.getMethod()
+ " "
+ request.getURI(),
__FILE__, __LINE__);
}
RestAction::Ptr target = m_router.lookup("builtin", "noroute");
if (target.isNull())
throw Exception("missing handler builtin.noroute");
return new PocoRestRequestHandler(
target,
{},
NULL,
static_cast<RestLinker &>(m_router)
);
}
HTTPRequestHandler *PocoRestRequestFactory::handleNoSession()
{
if (logger().debug()) {
logger().debug("missing session, redirecting...",
__FILE__, __LINE__);
}
RestAction::Ptr target = m_router.lookup("builtin", "unauthorized");
if (target.isNull())
throw Exception("missing handler builtin.unauthorized");
return new PocoRestRequestHandler(
target,
{},
NULL,
static_cast<RestLinker &>(m_router)
);
}
HTTPRequestHandler *PocoRestRequestFactory::createWithSession(
RestAction::Ptr action,
const MappedRestAction::Params ¶ms,
const HTTPServerRequest &request)
{
ExpirableSession::Ptr session;
if (action->sessionRequired()) {
try {
session = m_sessionVerifier.verifyAuthorized(request);
} catch (const NotAuthenticatedException &e) {
logger().log(e, __FILE__, __LINE__);
}
if (session.isNull())
return handleNoSession();
}
return new PocoRestRequestHandler(
action,
params,
session,
static_cast<RestLinker &>(m_router)
);
}
HTTPRequestHandler *PocoRestRequestFactory::createRequestHandler(
const HTTPServerRequest &request)
{
if (logger().debug()) {
logger().debug("handling request "
+ request.getMethod()
+ " "
+ request.getURI(),
__FILE__, __LINE__);
}
Poco::URI uri(request.getURI());
MappedRestAction::Params params;
try {
RestAction::Ptr action = m_router.route(
request.getMethod(), uri, params
);
if (action.isNull())
return handleNoRoute(request);
return createWithSession(
action,
params,
request
);
} catch (const Exception &e) {
logger().log(e, __FILE__, __LINE__);
e.rethrow();
} catch (const exception &e) {
logger().fatal(e.what(), __FILE__, __LINE__);
throw e;
} catch (...) {
logger().fatal("something is terribly wrong",
__FILE__, __LINE__);
throw;
}
logger().fatal("should ben ever reached", __FILE__, __LINE__);
return NULL;
}
<commit_msg>PocoRestRequestHandler: apply sanitization to request URIs<commit_after>#include <Poco/Exception.h>
#include <Poco/DateTime.h>
#include <Poco/DateTimeFormat.h>
#include <Poco/DateTimeFormatter.h>
#include <Poco/Logger.h>
#include <Poco/Net/HTTPServerParams.h>
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include "rest/PocoRestRequestHandler.h"
#include "rest/RestFlow.h"
#include "rest/RestRouter.h"
#include "rest/RestLinker.h"
#include "server/SessionVerifier.h"
#include "util/Sanitize.h"
using namespace std;
using namespace Poco;
using namespace Poco::Net;
using namespace BeeeOn;
PocoRestRequestHandler::PocoRestRequestHandler(
RestAction::Ptr action,
const MappedRestAction::Params ¶ms,
ExpirableSession::Ptr session,
RestLinker &linker):
m_action(action),
m_params(params),
m_session(session),
m_linker(linker)
{
}
bool PocoRestRequestHandler::expectedContentLength(
HTTPServerRequest &req,
HTTPServerResponse &res)
{
const string &method = req.getMethod();
if (method != "POST" && method != "PUT" && method != "PATCH")
return true;;
if (!req.hasContentLength()) {
res.setStatusAndReason(HTTPResponse::HTTP_LENGTH_REQUIRED);
return false;
}
int inputMaxSize = m_action->inputMaxSize();
if (inputMaxSize < 0)
return true;
auto contentLength = req.getContentLength();
if (contentLength > inputMaxSize) {
if (logger().warning()) {
logger().warning(
"too long input: "
+ to_string(contentLength)
+ " for "
+ m_action->fullName(),
__FILE__, __LINE__);
}
res.setStatusAndReason(HTTPResponse::HTTP_BAD_REQUEST);
return false;
}
return true;
}
string PocoRestRequestHandler::asString(const MappedRestAction::Params ¶ms) const
{
string s("[");
auto it = params.begin();
for (; it != params.end(); ++it) {
if (it != params.begin())
s.append(", ");
s.append(it->first);
s.append(" => ");
s.append(it->second);
}
s.append("]");
return s;
}
void PocoRestRequestHandler::prepareInternalAction(
RestAction::Ptr action,
HTTPServerRequest &req,
HTTPServerResponse &res) const
{
req.set("Cache-Control", "public, no-cache");
}
void PocoRestRequestHandler::prepareMappedAction(
MappedRestAction::Ptr action,
HTTPServerRequest &req,
HTTPServerResponse &res) const
{
if (action->caching() == 0) {
req.set("Cache-Control", "public, no-cache");
}
else {
const Timespan shift(action->caching(), 0);
const DateTime now;
res.set("Expires",
DateTimeFormatter::format(now + shift, DateTimeFormat::HTTP_FORMAT));
res.set("Cache-Control",
"max-age=" + to_string(shift.totalSeconds()) + ", must-revalidate");
}
}
void PocoRestRequestHandler::handleRequest(
HTTPServerRequest &req,
HTTPServerResponse &res)
{
if (logger().debug()) {
logger().debug("serving request "
+ req.getMethod()
+ " "
+ req.getURI()
+ " via action "
+ m_action->fullName()
+ " "
+ asString(m_params),
__FILE__, __LINE__);
}
if (logger().trace()) {
for (const auto &pair : req) {
logger().trace(
pair.first
+ ": "
+ pair.second,
__FILE__, __LINE__);
}
}
if (!expectedContentLength(req, res)) {
res.send();
return;
}
Poco::URI uri(req.getURI());
RestFlow flow(
m_linker,
uri,
m_params,
PocoRequest(req),
PocoResponse(res)
);
MappedRestAction::Ptr mapped = m_action.cast<MappedRestAction>();
if (mapped.isNull())
prepareInternalAction(m_action, req, res);
else
prepareMappedAction(mapped, req, res);
const auto &call = m_action->call();
try {
flow.setSession(m_session);
call(flow);
return;
}
catch (const Exception &e) {
logger().log(e, __FILE__, __LINE__);
}
catch (const exception &e) {
logger().critical(e.what(), __FILE__, __LINE__);
}
catch (const char *m) {
logger().fatal(m, __FILE__, __LINE__);
}
catch (...) {
logger().fatal("unknown error occured", __FILE__, __LINE__);
}
if (res.sent())
return;
res.setStatusAndReason(HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
PocoRestRequestFactory::PocoRestRequestFactory(
RestRouter &router,
SessionVerifier &verifier):
m_router(router),
m_sessionVerifier(verifier)
{
}
HTTPRequestHandler *PocoRestRequestFactory::handleNoRoute(const HTTPServerRequest &request)
{
if (logger().debug()) {
logger().debug("no action resolved for "
+ request.getMethod()
+ " "
+ request.getURI(),
__FILE__, __LINE__);
}
RestAction::Ptr target = m_router.lookup("builtin", "noroute");
if (target.isNull())
throw Exception("missing handler builtin.noroute");
return new PocoRestRequestHandler(
target,
{},
NULL,
static_cast<RestLinker &>(m_router)
);
}
HTTPRequestHandler *PocoRestRequestFactory::handleNoSession()
{
if (logger().debug()) {
logger().debug("missing session, redirecting...",
__FILE__, __LINE__);
}
RestAction::Ptr target = m_router.lookup("builtin", "unauthorized");
if (target.isNull())
throw Exception("missing handler builtin.unauthorized");
return new PocoRestRequestHandler(
target,
{},
NULL,
static_cast<RestLinker &>(m_router)
);
}
HTTPRequestHandler *PocoRestRequestFactory::createWithSession(
RestAction::Ptr action,
const MappedRestAction::Params ¶ms,
const HTTPServerRequest &request)
{
ExpirableSession::Ptr session;
if (action->sessionRequired()) {
try {
session = m_sessionVerifier.verifyAuthorized(request);
} catch (const NotAuthenticatedException &e) {
logger().log(e, __FILE__, __LINE__);
}
if (session.isNull())
return handleNoSession();
}
return new PocoRestRequestHandler(
action,
params,
session,
static_cast<RestLinker &>(m_router)
);
}
HTTPRequestHandler *PocoRestRequestFactory::createRequestHandler(
const HTTPServerRequest &request)
{
if (logger().debug()) {
logger().debug("handling request "
+ request.getMethod()
+ " "
+ request.getURI(),
__FILE__, __LINE__);
}
Poco::URI uri(Sanitize::uri(request.getURI()));
MappedRestAction::Params params;
try {
RestAction::Ptr action = m_router.route(
request.getMethod(), uri, params
);
if (action.isNull())
return handleNoRoute(request);
return createWithSession(
action,
params,
request
);
} catch (const Exception &e) {
logger().log(e, __FILE__, __LINE__);
e.rethrow();
} catch (const exception &e) {
logger().fatal(e.what(), __FILE__, __LINE__);
throw e;
} catch (...) {
logger().fatal("something is terribly wrong",
__FILE__, __LINE__);
throw;
}
logger().fatal("should ben ever reached", __FILE__, __LINE__);
return NULL;
}
<|endoftext|> |
<commit_before>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015-2018 Vladimir Menshakov
Android File Transfer For Linux 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.
Android File Transfer For Linux 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 Android File Transfer For Linux.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "utils.h"
#include <QApplication>
#include <QLibraryInfo>
#include <QLocale>
#include <QMessageBox>
#include <QTranslator>
namespace
{
class Application : public QApplication
{
public:
Application(int &argc, char **argv, int flags = ApplicationFlags):
QApplication(argc, argv, flags)
{ }
virtual bool notify ( QObject * receiver, QEvent * e )
{
try {
return QApplication::notify( receiver, e );
} catch ( const std::exception& e ) {
QMessageBox::warning(0, "Error", fromUtf8(e.what()));
return false;
}
}
};
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Q_INIT_RESOURCE(android_file_transfer);
QCoreApplication::setApplicationName("mtp-ng-qt");
QCoreApplication::setOrganizationDomain("whoozle.github.io");
QCoreApplication::setOrganizationName("whoozle.github.io");
QTranslator qtTranslator;
qtTranslator.load("qt_" + QLocale::system().name(),
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&qtTranslator);
QTranslator aTranslator;
aTranslator.load(":/translations/android-file-transfer-linux_" + QLocale::system().name());
app.installTranslator(&aTranslator);
MainWindow w;
w.show();
if (!w.started())
return 1;
return app.exec();
}
<commit_msg>renamed config file<commit_after>/*
This file is part of Android File Transfer For Linux.
Copyright (C) 2015-2018 Vladimir Menshakov
Android File Transfer For Linux 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.
Android File Transfer For Linux 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 Android File Transfer For Linux.
If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "utils.h"
#include <QApplication>
#include <QLibraryInfo>
#include <QLocale>
#include <QMessageBox>
#include <QTranslator>
namespace
{
class Application : public QApplication
{
public:
Application(int &argc, char **argv, int flags = ApplicationFlags):
QApplication(argc, argv, flags)
{ }
virtual bool notify ( QObject * receiver, QEvent * e )
{
try {
return QApplication::notify( receiver, e );
} catch ( const std::exception& e ) {
QMessageBox::warning(0, "Error", fromUtf8(e.what()));
return false;
}
}
};
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Q_INIT_RESOURCE(android_file_transfer);
QCoreApplication::setApplicationName("aft-linux-qt");
QCoreApplication::setOrganizationDomain("whoozle.github.io");
QCoreApplication::setOrganizationName("whoozle.github.io");
QTranslator qtTranslator;
qtTranslator.load("qt_" + QLocale::system().name(),
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
app.installTranslator(&qtTranslator);
QTranslator aTranslator;
aTranslator.load(":/translations/android-file-transfer-linux_" + QLocale::system().name());
app.installTranslator(&aTranslator);
MainWindow w;
w.show();
if (!w.started())
return 1;
return app.exec();
}
<|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 "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop_proxy.h"
#include "remoting/jingle_glue/mock_objects.h"
#include "remoting/host/capturer_fake.h"
#include "remoting/host/chromoting_host.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/host_mock_objects.h"
#include "remoting/host/it2me_host_user_interface.h"
#include "remoting/proto/video.pb.h"
#include "remoting/protocol/protocol_mock_objects.h"
#include "remoting/protocol/session_config.h"
#include "testing/gmock_mutant.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::remoting::protocol::MockClientStub;
using ::remoting::protocol::MockConnectionToClient;
using ::remoting::protocol::MockConnectionToClientEventHandler;
using ::remoting::protocol::MockHostStub;
using ::remoting::protocol::MockSession;
using ::remoting::protocol::MockVideoStub;
using ::remoting::protocol::SessionConfig;
using testing::_;
using testing::AnyNumber;
using testing::AtLeast;
using testing::CreateFunctor;
using testing::DeleteArg;
using testing::DoAll;
using testing::InSequence;
using testing::InvokeArgument;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::ReturnRef;
using testing::Sequence;
namespace remoting {
namespace {
void PostQuitTask(MessageLoop* message_loop) {
message_loop->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
// Run the task and delete it afterwards. This action is used to deal with
// done callbacks.
ACTION(RunDoneTask) {
arg1.Run();
}
} // namespace
class ChromotingHostTest : public testing::Test {
public:
ChromotingHostTest() {
}
virtual void SetUp() OVERRIDE {
message_loop_proxy_ = base::MessageLoopProxy::current();
ON_CALL(context_, main_message_loop())
.WillByDefault(Return(&message_loop_));
ON_CALL(context_, encode_message_loop())
.WillByDefault(Return(&message_loop_));
ON_CALL(context_, network_message_loop())
.WillByDefault(Return(message_loop_proxy_.get()));
ON_CALL(context_, ui_message_loop())
.WillByDefault(Return(message_loop_proxy_.get()));
EXPECT_CALL(context_, main_message_loop())
.Times(AnyNumber());
EXPECT_CALL(context_, encode_message_loop())
.Times(AnyNumber());
EXPECT_CALL(context_, network_message_loop())
.Times(AnyNumber());
EXPECT_CALL(context_, ui_message_loop())
.Times(AnyNumber());
scoped_ptr<Capturer> capturer(new CapturerFake());
event_executor_ = new MockEventExecutor();
desktop_environment_ = DesktopEnvironment::CreateFake(
&context_,
capturer.Pass(),
scoped_ptr<EventExecutor>(event_executor_));
session_manager_ = new protocol::MockSessionManager();
host_ = new ChromotingHost(
&context_, &signal_strategy_, desktop_environment_.get(),
scoped_ptr<protocol::SessionManager>(session_manager_));
disconnect_window_ = new MockDisconnectWindow();
continue_window_ = new MockContinueWindow();
local_input_monitor_ = new MockLocalInputMonitor();
it2me_host_user_interface_.reset(new It2MeHostUserInterface(&context_));
it2me_host_user_interface_->StartForTest(
host_,
base::Bind(&ChromotingHost::Shutdown, host_, base::Closure()),
scoped_ptr<DisconnectWindow>(disconnect_window_),
scoped_ptr<ContinueWindow>(continue_window_),
scoped_ptr<LocalInputMonitor>(local_input_monitor_));
session_ = new MockSession();
session2_ = new MockSession();
session_config_ = SessionConfig::GetDefault();
session_jid_ = "user@domain/rest-of-jid";
session_config2_ = SessionConfig::GetDefault();
session2_jid_ = "user2@domain/rest-of-jid";
EXPECT_CALL(*session_, jid())
.WillRepeatedly(ReturnRef(session_jid_));
EXPECT_CALL(*session2_, jid())
.WillRepeatedly(ReturnRef(session2_jid_));
EXPECT_CALL(*session_, SetStateChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session2_, SetStateChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session_, SetRouteChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session2_, SetRouteChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session_, config())
.WillRepeatedly(ReturnRef(session_config_));
EXPECT_CALL(*session2_, config())
.WillRepeatedly(ReturnRef(session_config2_));
EXPECT_CALL(*session_, Close())
.Times(AnyNumber());
EXPECT_CALL(*session2_, Close())
.Times(AnyNumber());
owned_connection_.reset(new MockConnectionToClient(
session_, &host_stub_, desktop_environment_->event_executor()));
connection_ = owned_connection_.get();
owned_connection2_.reset(new MockConnectionToClient(
session2_, &host_stub2_, desktop_environment_->event_executor()));
connection2_ = owned_connection2_.get();
ON_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.WillByDefault(DeleteArg<0>());
ON_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.WillByDefault(DeleteArg<0>());
ON_CALL(*connection_, video_stub())
.WillByDefault(Return(&video_stub_));
ON_CALL(*connection_, client_stub())
.WillByDefault(Return(&client_stub_));
ON_CALL(*connection_, session())
.WillByDefault(Return(session_));
ON_CALL(*connection2_, video_stub())
.WillByDefault(Return(&video_stub2_));
ON_CALL(*connection2_, client_stub())
.WillByDefault(Return(&client_stub2_));
ON_CALL(*connection2_, session())
.WillByDefault(Return(session2_));
EXPECT_CALL(*connection_, video_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection_, client_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection_, session())
.Times(AnyNumber());
EXPECT_CALL(*connection2_, video_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection2_, client_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection2_, session())
.Times(AnyNumber());
}
// Helper method to pretend a client is connected to ChromotingHost.
void SimulateClientConnection(int connection_index, bool authenticate) {
scoped_ptr<protocol::ConnectionToClient> connection =
((connection_index == 0) ? owned_connection_ : owned_connection2_).
PassAs<protocol::ConnectionToClient>();
protocol::ConnectionToClient* connection_ptr = connection.get();
ClientSession* client = new ClientSession(
host_.get(), connection.Pass(), desktop_environment_->event_executor(),
desktop_environment_->capturer());
connection_ptr->set_host_stub(client);
context_.network_message_loop()->PostTask(
FROM_HERE, base::Bind(&ChromotingHostTest::AddClientToHost,
host_, client));
if (authenticate) {
context_.network_message_loop()->PostTask(
FROM_HERE, base::Bind(&ClientSession::OnConnectionAuthenticated,
base::Unretained(client), connection_ptr));
context_.network_message_loop()->PostTask(
FROM_HERE,
base::Bind(&ClientSession::OnConnectionChannelsConnected,
base::Unretained(client), connection_ptr));
}
if (connection_index == 0) {
client_ = client;
} else {
client2_ = client;
}
}
// Helper method to remove a client connection from ChromotingHost.
void RemoveClientSession() {
client_->OnConnectionClosed(connection_, protocol::OK);
}
// Notify |host_| that |client_| has closed.
void ClientSessionClosed() {
host_->OnSessionClosed(client_);
}
// Notify |host_| that |client2_| has closed.
void ClientSession2Closed() {
host_->OnSessionClosed(client2_);
}
static void AddClientToHost(scoped_refptr<ChromotingHost> host,
ClientSession* session) {
host->clients_.push_back(session);
}
void ShutdownHost() {
message_loop_.PostTask(
FROM_HERE, base::Bind(&ChromotingHost::Shutdown, host_,
base::Bind(&PostQuitTask, &message_loop_)));
}
void QuitMainMessageLoop() {
PostQuitTask(&message_loop_);
}
protected:
MessageLoop message_loop_;
scoped_refptr<base::MessageLoopProxy> message_loop_proxy_;
MockConnectionToClientEventHandler handler_;
MockSignalStrategy signal_strategy_;
MockEventExecutor* event_executor_;
scoped_ptr<DesktopEnvironment> desktop_environment_;
scoped_ptr<It2MeHostUserInterface> it2me_host_user_interface_;
scoped_refptr<ChromotingHost> host_;
MockChromotingHostContext context_;
protocol::MockSessionManager* session_manager_;
MockConnectionToClient* connection_;
scoped_ptr<MockConnectionToClient> owned_connection_;
ClientSession* client_;
std::string session_jid_;
MockSession* session_; // Owned by |connection_|.
SessionConfig session_config_;
MockVideoStub video_stub_;
MockClientStub client_stub_;
MockHostStub host_stub_;
MockConnectionToClient* connection2_;
scoped_ptr<MockConnectionToClient> owned_connection2_;
ClientSession* client2_;
std::string session2_jid_;
MockSession* session2_; // Owned by |connection2_|.
SessionConfig session_config2_;
MockVideoStub video_stub2_;
MockClientStub client_stub2_;
MockHostStub host_stub2_;
// Owned by |host_|.
MockDisconnectWindow* disconnect_window_;
MockContinueWindow* continue_window_;
MockLocalInputMonitor* local_input_monitor_;
};
TEST_F(ChromotingHostTest, StartAndShutdown) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
message_loop_.PostTask(
FROM_HERE, base::Bind(
&ChromotingHost::Shutdown, host_.get(),
base::Bind(&PostQuitTask, &message_loop_)));
message_loop_.Run();
}
TEST_F(ChromotingHostTest, Connect) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
// When the video packet is received we first shut down ChromotingHost,
// then execute the done task.
{
InSequence s;
EXPECT_CALL(*disconnect_window_, Show(_, _, _))
.Times(0);
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(*connection_, Disconnect())
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSessionClosed))
.RetiresOnSaturation();
}
{
InSequence s;
EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
EXPECT_CALL(*event_executor_, OnSessionFinished());
}
SimulateClientConnection(0, true);
message_loop_.Run();
}
TEST_F(ChromotingHostTest, Reconnect) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
// When the video packet is received we first disconnect the mock
// connection, then run the done task, then quit the message loop.
{
InSequence s;
EXPECT_CALL(*disconnect_window_, Show(_, _, _))
.Times(0);
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::RemoveClientSession),
RunDoneTask(),
InvokeWithoutArgs(this, &ChromotingHostTest::QuitMainMessageLoop)))
.RetiresOnSaturation();
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.WillRepeatedly(RunDoneTask());
}
{
InSequence s;
EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
EXPECT_CALL(*event_executor_, OnSessionFinished());
}
SimulateClientConnection(0, true);
message_loop_.Run();
// Connect the second client.
{
InSequence s;
EXPECT_CALL(*disconnect_window_, Show(_, _, _))
.Times(0);
EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(*connection2_, Disconnect())
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSession2Closed))
.RetiresOnSaturation();
}
{
InSequence s;
EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
EXPECT_CALL(*event_executor_, OnSessionFinished());
}
SimulateClientConnection(1, true);
message_loop_.Run();
}
TEST_F(ChromotingHostTest, ConnectWhenAnotherClientIsConnected) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
// When a video packet is received we connect the second mock
// connection.
{
InSequence s;
EXPECT_CALL(*disconnect_window_, Show(_, _, _))
.Times(0);
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.WillOnce(DoAll(
InvokeWithoutArgs(
CreateFunctor(
this,
&ChromotingHostTest::SimulateClientConnection, 1, true)),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(*disconnect_window_, Show(_, _, _))
.Times(0);
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.WillRepeatedly(RunDoneTask());
}
{
InSequence s;
EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
EXPECT_CALL(*event_executor_, OnSessionFinished());
EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
EXPECT_CALL(*event_executor_, OnSessionFinished());
}
EXPECT_CALL(*connection_, Disconnect())
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSessionClosed))
.RetiresOnSaturation();
EXPECT_CALL(*connection2_, Disconnect())
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSession2Closed))
.RetiresOnSaturation();
SimulateClientConnection(0, true);
message_loop_.Run();
}
} // namespace remoting
<commit_msg>[Chromoting] Make the sequence expectations in the ChromotingHost unit tests more accurate.<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 "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop_proxy.h"
#include "remoting/jingle_glue/mock_objects.h"
#include "remoting/host/capturer_fake.h"
#include "remoting/host/chromoting_host.h"
#include "remoting/host/chromoting_host_context.h"
#include "remoting/host/host_mock_objects.h"
#include "remoting/host/it2me_host_user_interface.h"
#include "remoting/proto/video.pb.h"
#include "remoting/protocol/protocol_mock_objects.h"
#include "remoting/protocol/session_config.h"
#include "testing/gmock_mutant.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::remoting::protocol::MockClientStub;
using ::remoting::protocol::MockConnectionToClient;
using ::remoting::protocol::MockConnectionToClientEventHandler;
using ::remoting::protocol::MockHostStub;
using ::remoting::protocol::MockSession;
using ::remoting::protocol::MockVideoStub;
using ::remoting::protocol::SessionConfig;
using testing::_;
using testing::AnyNumber;
using testing::AtLeast;
using testing::CreateFunctor;
using testing::DeleteArg;
using testing::DoAll;
using testing::Expectation;
using testing::InSequence;
using testing::InvokeArgument;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::ReturnRef;
using testing::Sequence;
namespace remoting {
namespace {
void PostQuitTask(MessageLoop* message_loop) {
message_loop->PostTask(FROM_HERE, MessageLoop::QuitClosure());
}
// Run the task and delete it afterwards. This action is used to deal with
// done callbacks.
ACTION(RunDoneTask) {
arg1.Run();
}
} // namespace
class ChromotingHostTest : public testing::Test {
public:
ChromotingHostTest() {
}
virtual void SetUp() OVERRIDE {
message_loop_proxy_ = base::MessageLoopProxy::current();
ON_CALL(context_, main_message_loop())
.WillByDefault(Return(&message_loop_));
ON_CALL(context_, encode_message_loop())
.WillByDefault(Return(&message_loop_));
ON_CALL(context_, network_message_loop())
.WillByDefault(Return(message_loop_proxy_.get()));
ON_CALL(context_, ui_message_loop())
.WillByDefault(Return(message_loop_proxy_.get()));
EXPECT_CALL(context_, main_message_loop())
.Times(AnyNumber());
EXPECT_CALL(context_, encode_message_loop())
.Times(AnyNumber());
EXPECT_CALL(context_, network_message_loop())
.Times(AnyNumber());
EXPECT_CALL(context_, ui_message_loop())
.Times(AnyNumber());
scoped_ptr<Capturer> capturer(new CapturerFake());
event_executor_ = new MockEventExecutor();
desktop_environment_ = DesktopEnvironment::CreateFake(
&context_,
capturer.Pass(),
scoped_ptr<EventExecutor>(event_executor_));
session_manager_ = new protocol::MockSessionManager();
host_ = new ChromotingHost(
&context_, &signal_strategy_, desktop_environment_.get(),
scoped_ptr<protocol::SessionManager>(session_manager_));
disconnect_window_ = new MockDisconnectWindow();
continue_window_ = new MockContinueWindow();
local_input_monitor_ = new MockLocalInputMonitor();
it2me_host_user_interface_.reset(new It2MeHostUserInterface(&context_));
it2me_host_user_interface_->StartForTest(
host_,
base::Bind(&ChromotingHost::Shutdown, host_, base::Closure()),
scoped_ptr<DisconnectWindow>(disconnect_window_),
scoped_ptr<ContinueWindow>(continue_window_),
scoped_ptr<LocalInputMonitor>(local_input_monitor_));
session_ = new MockSession();
session2_ = new MockSession();
session_config_ = SessionConfig::GetDefault();
session_jid_ = "user@domain/rest-of-jid";
session_config2_ = SessionConfig::GetDefault();
session2_jid_ = "user2@domain/rest-of-jid";
EXPECT_CALL(*session_, jid())
.WillRepeatedly(ReturnRef(session_jid_));
EXPECT_CALL(*session2_, jid())
.WillRepeatedly(ReturnRef(session2_jid_));
EXPECT_CALL(*session_, SetStateChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session2_, SetStateChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session_, SetRouteChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session2_, SetRouteChangeCallback(_))
.Times(AnyNumber());
EXPECT_CALL(*session_, config())
.WillRepeatedly(ReturnRef(session_config_));
EXPECT_CALL(*session2_, config())
.WillRepeatedly(ReturnRef(session_config2_));
EXPECT_CALL(*session_, Close())
.Times(AnyNumber());
EXPECT_CALL(*session2_, Close())
.Times(AnyNumber());
owned_connection_.reset(new MockConnectionToClient(
session_, &host_stub_, desktop_environment_->event_executor()));
connection_ = owned_connection_.get();
owned_connection2_.reset(new MockConnectionToClient(
session2_, &host_stub2_, desktop_environment_->event_executor()));
connection2_ = owned_connection2_.get();
ON_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.WillByDefault(DeleteArg<0>());
ON_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.WillByDefault(DeleteArg<0>());
ON_CALL(*connection_, video_stub())
.WillByDefault(Return(&video_stub_));
ON_CALL(*connection_, client_stub())
.WillByDefault(Return(&client_stub_));
ON_CALL(*connection_, session())
.WillByDefault(Return(session_));
ON_CALL(*connection2_, video_stub())
.WillByDefault(Return(&video_stub2_));
ON_CALL(*connection2_, client_stub())
.WillByDefault(Return(&client_stub2_));
ON_CALL(*connection2_, session())
.WillByDefault(Return(session2_));
EXPECT_CALL(*connection_, video_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection_, client_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection_, session())
.Times(AnyNumber());
EXPECT_CALL(*connection2_, video_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection2_, client_stub())
.Times(AnyNumber());
EXPECT_CALL(*connection2_, session())
.Times(AnyNumber());
}
// Helper method to pretend a client is connected to ChromotingHost.
void SimulateClientConnection(int connection_index, bool authenticate) {
scoped_ptr<protocol::ConnectionToClient> connection =
((connection_index == 0) ? owned_connection_ : owned_connection2_).
PassAs<protocol::ConnectionToClient>();
protocol::ConnectionToClient* connection_ptr = connection.get();
ClientSession* client = new ClientSession(
host_.get(), connection.Pass(), desktop_environment_->event_executor(),
desktop_environment_->capturer());
connection_ptr->set_host_stub(client);
context_.network_message_loop()->PostTask(
FROM_HERE, base::Bind(&ChromotingHostTest::AddClientToHost,
host_, client));
if (authenticate) {
context_.network_message_loop()->PostTask(
FROM_HERE, base::Bind(&ClientSession::OnConnectionAuthenticated,
base::Unretained(client), connection_ptr));
context_.network_message_loop()->PostTask(
FROM_HERE,
base::Bind(&ClientSession::OnConnectionChannelsConnected,
base::Unretained(client), connection_ptr));
}
if (connection_index == 0) {
client_ = client;
} else {
client2_ = client;
}
}
// Helper method to remove a client connection from ChromotingHost.
void RemoveClientSession() {
client_->OnConnectionClosed(connection_, protocol::OK);
}
// Notify |host_| that |client_| has closed.
void ClientSessionClosed() {
host_->OnSessionClosed(client_);
}
// Notify |host_| that |client2_| has closed.
void ClientSession2Closed() {
host_->OnSessionClosed(client2_);
}
static void AddClientToHost(scoped_refptr<ChromotingHost> host,
ClientSession* session) {
host->clients_.push_back(session);
}
void ShutdownHost() {
message_loop_.PostTask(
FROM_HERE, base::Bind(&ChromotingHost::Shutdown, host_,
base::Bind(&PostQuitTask, &message_loop_)));
}
void QuitMainMessageLoop() {
PostQuitTask(&message_loop_);
}
protected:
MessageLoop message_loop_;
scoped_refptr<base::MessageLoopProxy> message_loop_proxy_;
MockConnectionToClientEventHandler handler_;
MockSignalStrategy signal_strategy_;
MockEventExecutor* event_executor_;
scoped_ptr<DesktopEnvironment> desktop_environment_;
scoped_ptr<It2MeHostUserInterface> it2me_host_user_interface_;
scoped_refptr<ChromotingHost> host_;
MockChromotingHostContext context_;
protocol::MockSessionManager* session_manager_;
MockConnectionToClient* connection_;
scoped_ptr<MockConnectionToClient> owned_connection_;
ClientSession* client_;
std::string session_jid_;
MockSession* session_; // Owned by |connection_|.
SessionConfig session_config_;
MockVideoStub video_stub_;
MockClientStub client_stub_;
MockHostStub host_stub_;
MockConnectionToClient* connection2_;
scoped_ptr<MockConnectionToClient> owned_connection2_;
ClientSession* client2_;
std::string session2_jid_;
MockSession* session2_; // Owned by |connection2_|.
SessionConfig session_config2_;
MockVideoStub video_stub2_;
MockClientStub client_stub2_;
MockHostStub host_stub2_;
// Owned by |host_|.
MockDisconnectWindow* disconnect_window_;
MockContinueWindow* continue_window_;
MockLocalInputMonitor* local_input_monitor_;
};
TEST_F(ChromotingHostTest, StartAndShutdown) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
message_loop_.PostTask(
FROM_HERE, base::Bind(
&ChromotingHost::Shutdown, host_.get(),
base::Bind(&PostQuitTask, &message_loop_)));
message_loop_.Run();
}
TEST_F(ChromotingHostTest, Connect) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
// When the video packet is received we first shut down ChromotingHost,
// then execute the done task.
Expectation start = EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
Expectation stop = EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.After(start)
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.After(stop)
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(*connection_, Disconnect())
.After(stop)
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSessionClosed))
.RetiresOnSaturation();
EXPECT_CALL(*event_executor_, OnSessionFinished())
.After(stop);
SimulateClientConnection(0, true);
message_loop_.Run();
}
TEST_F(ChromotingHostTest, Reconnect) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
// When the video packet is received we first disconnect the mock
// connection, then run the done task, then quit the message loop.
Expectation start1 = EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
Expectation stop1 = EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.After(start1)
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::RemoveClientSession),
RunDoneTask(),
InvokeWithoutArgs(this, &ChromotingHostTest::QuitMainMessageLoop)))
.RetiresOnSaturation();
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.After(stop1)
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(*event_executor_, OnSessionFinished())
.After(stop1);
SimulateClientConnection(0, true);
message_loop_.Run();
Expectation start2 = EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_))
.After(stop1);
Expectation stop2 = EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.After(start2)
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.After(stop2)
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(*connection2_, Disconnect())
.After(stop2)
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSession2Closed))
.RetiresOnSaturation();
EXPECT_CALL(*event_executor_, OnSessionFinished())
.After(stop2);
SimulateClientConnection(1, true);
message_loop_.Run();
}
TEST_F(ChromotingHostTest, ConnectWhenAnotherClientIsConnected) {
EXPECT_CALL(*session_manager_, Init(_, host_.get()));
EXPECT_CALL(*disconnect_window_, Hide());
EXPECT_CALL(*continue_window_, Hide());
host_->Start();
// When a video packet is received we connect the second mock
// connection.
Expectation start1 = EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_));
Expectation start2 = EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.After(start1)
.WillOnce(DoAll(
InvokeWithoutArgs(
CreateFunctor(
this,
&ChromotingHostTest::SimulateClientConnection, 1, true)),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.After(start2)
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(*event_executor_, OnSessionFinished()).After(start2);
EXPECT_CALL(*event_executor_, OnSessionStartedPtr(_)).After(start2);
EXPECT_CALL(*connection_, Disconnect())
.After(start2)
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSessionClosed))
.RetiresOnSaturation();
Expectation stop2 = EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.After(start2)
.WillOnce(DoAll(
InvokeWithoutArgs(this, &ChromotingHostTest::ShutdownHost),
RunDoneTask()))
.RetiresOnSaturation();
EXPECT_CALL(video_stub2_, ProcessVideoPacketPtr(_, _))
.Times(AnyNumber())
.After(stop2)
.WillRepeatedly(RunDoneTask());
EXPECT_CALL(*event_executor_, OnSessionFinished()).After(stop2);
EXPECT_CALL(*connection2_, Disconnect())
.After(stop2)
.WillOnce(
InvokeWithoutArgs(this, &ChromotingHostTest::ClientSession2Closed))
.RetiresOnSaturation();
SimulateClientConnection(0, true);
message_loop_.Run();
}
} // namespace remoting
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014-2015 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include "getModelIndex.hpp"
#include "desk_functions.hpp"
#include "IoView.hpp"
#include "GuiGame.hpp"
#include "GameOptions.hpp"
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow, IoView {
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = 0);
~MainWindow();
protected:
int getDeskSize_impl() const;
int getWinNumber_impl() const;
int getTimeNumber_impl() const;
void finish_impl(bool fail, int score,
int steps_number) const;
void sendHelpMessage_impl() const;
void startGame_impl(int row_number);
void errorHandling_impl(std::exception& e) const;
void resizeBoardsContent(int boards_size);
void resizeEvent(QResizeEvent* event);
private:
Ui::MainWindow* ui;
GuiGamePtr game_;
GameOptionsPtr go_;
void setBoardsModel();
void configureBoard(int row_number);
void preparingToPlay();
void finishActions(int steps_number);
bool endOfGame() const;
void tryToMove();
void settingOfScore();
void settingOfTime();
void settingOfSize();
void setInitialParameters();
private slots:
void on_quitButton_clicked();
void on_winButton_clicked();
void on_timeButton_clicked();
void on_scoreButton_clicked();
void on_startButton_clicked();
void on_playButton_clicked();
void on_playButton2_clicked();
void on_gameBoard_clicked(const QModelIndex& index);
void on_endButton_clicked();
void resizeBoardsContent_deferred();
};
#endif
<commit_msg>MainWindow::default_font_<commit_after>/*
* Copyright (C) 2014-2015 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#ifndef MAINWINDOW_HPP
#define MAINWINDOW_HPP
#include "getModelIndex.hpp"
#include "desk_functions.hpp"
#include "IoView.hpp"
#include "GuiGame.hpp"
#include "GameOptions.hpp"
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow, IoView {
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = 0);
~MainWindow();
protected:
int getDeskSize_impl() const;
int getWinNumber_impl() const;
int getTimeNumber_impl() const;
void finish_impl(bool fail, int score,
int steps_number) const;
void sendHelpMessage_impl() const;
void startGame_impl(int row_number);
void errorHandling_impl(std::exception& e) const;
void resizeBoardsContent(int boards_size);
void resizeEvent(QResizeEvent* event);
private:
Ui::MainWindow* ui;
GuiGamePtr game_;
GameOptionsPtr go_;
QFont default_font_;
void setBoardsModel();
void configureBoard(int row_number);
void preparingToPlay();
void finishActions(int steps_number);
bool endOfGame() const;
void tryToMove();
void settingOfScore();
void settingOfTime();
void settingOfSize();
void setInitialParameters();
private slots:
void on_quitButton_clicked();
void on_winButton_clicked();
void on_timeButton_clicked();
void on_scoreButton_clicked();
void on_startButton_clicked();
void on_playButton_clicked();
void on_playButton2_clicked();
void on_gameBoard_clicked(const QModelIndex& index);
void on_endButton_clicked();
void resizeBoardsContent_deferred();
};
#endif
<|endoftext|> |
<commit_before>//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This code simply runs the preprocessor on the input file and prints out the
// result. This is the traditional behavior of the -E option.
//
//===----------------------------------------------------------------------===//
#include "clang.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/Pragma.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/config.h"
#include <cstdio>
using namespace clang;
//===----------------------------------------------------------------------===//
// Simple buffered I/O
//===----------------------------------------------------------------------===//
//
// Empirically, iostream is over 30% slower than stdio for this workload, and
// stdio itself isn't very well suited. The problem with stdio is use of
// putchar_unlocked. We have many newline characters that need to be emitted,
// but stdio needs to do extra checks to handle line buffering mode. These
// extra checks make putchar_unlocked fall off its inlined code path, hitting
// slow system code. In practice, using 'write' directly makes 'clang -E -P'
// about 10% faster than using the stdio path on darwin.
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#else
#define USE_STDIO 1
#endif
static char *OutBufStart = 0, *OutBufEnd, *OutBufCur;
/// InitOutputBuffer - Initialize our output buffer.
///
static void InitOutputBuffer() {
#ifndef USE_STDIO
OutBufStart = new char[64*1024];
OutBufEnd = OutBufStart+64*1024;
OutBufCur = OutBufStart;
#endif
}
/// FlushBuffer - Write the accumulated bytes to the output stream.
///
static void FlushBuffer() {
#ifndef USE_STDIO
write(STDOUT_FILENO, OutBufStart, OutBufCur-OutBufStart);
OutBufCur = OutBufStart;
#endif
}
/// CleanupOutputBuffer - Finish up output.
///
static void CleanupOutputBuffer() {
#ifndef USE_STDIO
FlushBuffer();
delete [] OutBufStart;
#endif
}
static void OutputChar(char c) {
#ifdef USE_STDIO
putchar_unlocked(c);
#else
if (OutBufCur >= OutBufEnd)
FlushBuffer();
*OutBufCur++ = c;
#endif
}
static void OutputString(const char *Ptr, unsigned Size) {
#ifdef USE_STDIO
fwrite(Ptr, Size, 1, stdout);
#else
if (OutBufCur+Size >= OutBufEnd)
FlushBuffer();
memcpy(OutBufCur, Ptr, Size);
OutBufCur += Size;
#endif
}
//===----------------------------------------------------------------------===//
// Preprocessed token printer
//===----------------------------------------------------------------------===//
static llvm::cl::opt<bool>
DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
static llvm::cl::opt<bool>
EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
static llvm::cl::opt<bool>
EnableMacroCommentOutput("CC",
llvm::cl::desc("Enable comment output in -E mode, "
"even from macro expansions"));
namespace {
class PrintPPOutputPPCallbacks : public PPCallbacks {
Preprocessor &PP;
unsigned CurLine;
std::string CurFilename;
bool EmittedTokensOnThisLine;
DirectoryLookup::DirType FileType;
public:
PrintPPOutputPPCallbacks(Preprocessor &pp) : PP(pp) {
CurLine = 0;
CurFilename = "<uninit>";
EmittedTokensOnThisLine = false;
FileType = DirectoryLookup::NormalHeaderDir;
}
void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
DirectoryLookup::DirType FileType);
virtual void Ident(SourceLocation Loc, const std::string &str);
void HandleFirstTokOnLine(Token &Tok);
void MoveToLine(SourceLocation Loc);
bool AvoidConcat(const Token &PrevTok, const Token &Tok);
};
}
/// MoveToLine - Move the output to the source line specified by the location
/// object. We can do this by emitting some number of \n's, or be emitting a
/// #line directive.
void PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
if (DisableLineMarkers) {
if (EmittedTokensOnThisLine) {
OutputChar('\n');
EmittedTokensOnThisLine = false;
}
return;
}
unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
// If this line is "close enough" to the original line, just print newlines,
// otherwise print a #line directive.
if (LineNo-CurLine < 8) {
unsigned Line = CurLine;
for (; Line != LineNo; ++Line)
OutputChar('\n');
CurLine = Line;
} else {
if (EmittedTokensOnThisLine) {
OutputChar('\n');
EmittedTokensOnThisLine = false;
}
CurLine = LineNo;
OutputChar('#');
OutputChar(' ');
std::string Num = llvm::utostr_32(LineNo);
OutputString(&Num[0], Num.size());
OutputChar(' ');
OutputChar('"');
OutputString(&CurFilename[0], CurFilename.size());
OutputChar('"');
if (FileType == DirectoryLookup::SystemHeaderDir)
OutputString(" 3", 2);
else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
OutputString(" 3 4", 4);
OutputChar('\n');
}
}
/// FileChanged - Whenever the preprocessor enters or exits a #include file
/// it invokes this handler. Update our conception of the current source
/// position.
void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
FileChangeReason Reason,
DirectoryLookup::DirType FileType) {
if (DisableLineMarkers) return;
// Unless we are exiting a #include, make sure to skip ahead to the line the
// #include directive was at.
SourceManager &SourceMgr = PP.getSourceManager();
if (Reason == PPCallbacks::EnterFile) {
MoveToLine(SourceMgr.getIncludeLoc(Loc));
} else if (Reason == PPCallbacks::SystemHeaderPragma) {
MoveToLine(Loc);
// TODO GCC emits the # directive for this directive on the line AFTER the
// directive and emits a bunch of spaces that aren't needed. Emulate this
// strange behavior.
}
Loc = SourceMgr.getLogicalLoc(Loc);
CurLine = SourceMgr.getLineNumber(Loc);
CurFilename = Lexer::Stringify(SourceMgr.getSourceName(Loc));
FileType = FileType;
if (EmittedTokensOnThisLine) {
OutputChar('\n');
EmittedTokensOnThisLine = false;
}
OutputChar('#');
OutputChar(' ');
std::string Num = llvm::utostr_32(CurLine);
OutputString(&Num[0], Num.size());
OutputChar(' ');
OutputChar('"');
OutputString(&CurFilename[0], CurFilename.size());
OutputChar('"');
switch (Reason) {
case PPCallbacks::EnterFile:
OutputString(" 1", 2);
break;
case PPCallbacks::ExitFile:
OutputString(" 2", 2);
break;
case PPCallbacks::SystemHeaderPragma: break;
case PPCallbacks::RenameFile: break;
}
if (FileType == DirectoryLookup::SystemHeaderDir)
OutputString(" 3", 2);
else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
OutputString(" 3 4", 4);
OutputChar('\n');
}
/// HandleIdent - Handle #ident directives when read by the preprocessor.
///
void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
MoveToLine(Loc);
OutputString("#ident ", strlen("#ident "));
OutputString(&S[0], S.size());
EmittedTokensOnThisLine = true;
}
/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
/// is called for the first token on each new line.
void PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
// Figure out what line we went to and insert the appropriate number of
// newline characters.
MoveToLine(Tok.getLocation());
// Print out space characters so that the first token on a line is
// indented for easy reading.
const SourceManager &SourceMgr = PP.getSourceManager();
unsigned ColNo = SourceMgr.getLogicalColumnNumber(Tok.getLocation());
// This hack prevents stuff like:
// #define HASH #
// HASH define foo bar
// From having the # character end up at column 1, which makes it so it
// is not handled as a #define next time through the preprocessor if in
// -fpreprocessed mode.
if (ColNo <= 1 && Tok.getKind() == tok::hash)
OutputChar(' ');
// Otherwise, indent the appropriate number of spaces.
for (; ColNo > 1; --ColNo)
OutputChar(' ');
}
namespace {
struct UnknownPragmaHandler : public PragmaHandler {
const char *Prefix;
PrintPPOutputPPCallbacks *Callbacks;
UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
: PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
// Figure out what line we went to and insert the appropriate number of
// newline characters.
Callbacks->MoveToLine(PragmaTok.getLocation());
OutputString(Prefix, strlen(Prefix));
// Read and print all of the pragma tokens.
while (PragmaTok.getKind() != tok::eom) {
if (PragmaTok.hasLeadingSpace())
OutputChar(' ');
std::string TokSpell = PP.getSpelling(PragmaTok);
OutputString(&TokSpell[0], TokSpell.size());
PP.LexUnexpandedToken(PragmaTok);
}
OutputChar('\n');
}
};
} // end anonymous namespace
/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
/// the two individual tokens to be lexed as a single token, return true (which
/// causes a space to be printed between them). This allows the output of -E
/// mode to be lexed to the same token stream as lexing the input directly
/// would.
///
/// This code must conservatively return true if it doesn't want to be 100%
/// accurate. This will cause the output to include extra space characters, but
/// the resulting output won't have incorrect concatenations going on. Examples
/// include "..", which we print with a space between, because we don't want to
/// track enough to tell "x.." from "...".
bool PrintPPOutputPPCallbacks::AvoidConcat(const Token &PrevTok,
const Token &Tok) {
char Buffer[256];
// If we haven't emitted a token on this line yet, PrevTok isn't useful to
// look at and no concatenation could happen anyway.
if (!EmittedTokensOnThisLine)
return false;
// Basic algorithm: we look at the first character of the second token, and
// determine whether it, if appended to the first token, would form (or would
// contribute) to a larger token if concatenated.
char FirstChar;
if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
// Avoid spelling identifiers, the most common form of token.
FirstChar = II->getName()[0];
} else if (Tok.getLength() < 256) {
const char *TokPtr = Buffer;
PP.getSpelling(Tok, TokPtr);
FirstChar = TokPtr[0];
} else {
FirstChar = PP.getSpelling(Tok)[0];
}
tok::TokenKind PrevKind = PrevTok.getKind();
if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
PrevKind = tok::identifier;
switch (PrevKind) {
default: return false;
case tok::identifier: // id+id or id+number or id+L"foo".
return isalnum(FirstChar) || FirstChar == '_';
case tok::numeric_constant:
return isalnum(FirstChar) || Tok.getKind() == tok::numeric_constant ||
FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
case tok::period: // ..., .*, .1234
return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
case tok::amp: // &&, &=
return FirstChar == '&' || FirstChar == '=';
case tok::plus: // ++, +=
return FirstChar == '+' || FirstChar == '=';
case tok::minus: // --, ->, -=, ->*
return FirstChar == '-' || FirstChar == '>' || FirstChar == '=';
case tok::slash: // /=, /*, //
return FirstChar == '=' || FirstChar == '*' || FirstChar == '/';
case tok::less: // <<, <<=, <=, <?=, <?, <:, <%
return FirstChar == '<' || FirstChar == '?' || FirstChar == '=' ||
FirstChar == ':' || FirstChar == '%';
case tok::greater: // >>, >=, >>=, >?=, >?
return FirstChar == '>' || FirstChar == '?' || FirstChar == '=';
case tok::pipe: // ||, |=
return FirstChar == '|' || FirstChar == '=';
case tok::percent: // %=, %>, %:
return FirstChar == '=' || FirstChar == '>' || FirstChar == ':';
case tok::colon: // ::, :>
return FirstChar == ':' || FirstChar == '>';
case tok::hash: // ##, #@, %:%:
return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
case tok::arrow: // ->*
return FirstChar == '*';
case tok::star: // *=
case tok::exclaim: // !=
case tok::lessless: // <<=
case tok::greaterequal: // >>=
case tok::caret: // ^=
case tok::equal: // ==
// Cases that concatenate only if the next char is =.
return FirstChar == '=';
}
}
/// DoPrintPreprocessedInput - This implements -E mode.
///
void clang::DoPrintPreprocessedInput(unsigned MainFileID, Preprocessor &PP,
const LangOptions &Options) {
// Inform the preprocessor whether we want it to retain comments or not, due
// to -C or -CC.
PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
InitOutputBuffer();
Token Tok, PrevTok;
char Buffer[256];
PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP);
PP.setPPCallbacks(Callbacks);
PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
// After we have configured the preprocessor, enter the main file.
// Start parsing the specified input file.
PP.EnterSourceFile(MainFileID, 0, true);
do {
PrevTok = Tok;
PP.Lex(Tok);
// If this token is at the start of a line, emit newlines if needed.
if (Tok.isAtStartOfLine()) {
Callbacks->HandleFirstTokOnLine(Tok);
} else if (Tok.hasLeadingSpace() ||
// Don't print "-" next to "-", it would form "--".
Callbacks->AvoidConcat(PrevTok, Tok)) {
OutputChar(' ');
}
if (Tok.getLength() < 256) {
const char *TokPtr = Buffer;
unsigned Len = PP.getSpelling(Tok, TokPtr);
OutputString(TokPtr, Len);
} else {
std::string S = PP.getSpelling(Tok);
OutputString(&S[0], S.size());
}
Callbacks->SetEmittedTokensOnThisLine();
} while (Tok.getKind() != tok::eof);
OutputChar('\n');
CleanupOutputBuffer();
}
<commit_msg>A minor tweak to -E output, speeding up -E 1.5% on 447.dealII<commit_after>//===--- PrintPreprocessedOutput.cpp - Implement the -E mode --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This code simply runs the preprocessor on the input file and prints out the
// result. This is the traditional behavior of the -E option.
//
//===----------------------------------------------------------------------===//
#include "clang.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/Pragma.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/config.h"
#include <cstdio>
using namespace clang;
//===----------------------------------------------------------------------===//
// Simple buffered I/O
//===----------------------------------------------------------------------===//
//
// Empirically, iostream is over 30% slower than stdio for this workload, and
// stdio itself isn't very well suited. The problem with stdio is use of
// putchar_unlocked. We have many newline characters that need to be emitted,
// but stdio needs to do extra checks to handle line buffering mode. These
// extra checks make putchar_unlocked fall off its inlined code path, hitting
// slow system code. In practice, using 'write' directly makes 'clang -E -P'
// about 10% faster than using the stdio path on darwin.
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#else
#define USE_STDIO 1
#endif
static char *OutBufStart = 0, *OutBufEnd, *OutBufCur;
/// InitOutputBuffer - Initialize our output buffer.
///
static void InitOutputBuffer() {
#ifndef USE_STDIO
OutBufStart = new char[64*1024];
OutBufEnd = OutBufStart+64*1024;
OutBufCur = OutBufStart;
#endif
}
/// FlushBuffer - Write the accumulated bytes to the output stream.
///
static void FlushBuffer() {
#ifndef USE_STDIO
write(STDOUT_FILENO, OutBufStart, OutBufCur-OutBufStart);
OutBufCur = OutBufStart;
#endif
}
/// CleanupOutputBuffer - Finish up output.
///
static void CleanupOutputBuffer() {
#ifndef USE_STDIO
FlushBuffer();
delete [] OutBufStart;
#endif
}
static void OutputChar(char c) {
#ifdef USE_STDIO
putchar_unlocked(c);
#else
if (OutBufCur >= OutBufEnd)
FlushBuffer();
*OutBufCur++ = c;
#endif
}
static void OutputString(const char *Ptr, unsigned Size) {
#ifdef USE_STDIO
fwrite(Ptr, Size, 1, stdout);
#else
if (OutBufCur+Size >= OutBufEnd)
FlushBuffer();
memcpy(OutBufCur, Ptr, Size);
OutBufCur += Size;
#endif
}
//===----------------------------------------------------------------------===//
// Preprocessed token printer
//===----------------------------------------------------------------------===//
static llvm::cl::opt<bool>
DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
static llvm::cl::opt<bool>
EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
static llvm::cl::opt<bool>
EnableMacroCommentOutput("CC",
llvm::cl::desc("Enable comment output in -E mode, "
"even from macro expansions"));
namespace {
class PrintPPOutputPPCallbacks : public PPCallbacks {
Preprocessor &PP;
unsigned CurLine;
std::string CurFilename;
bool EmittedTokensOnThisLine;
DirectoryLookup::DirType FileType;
public:
PrintPPOutputPPCallbacks(Preprocessor &pp) : PP(pp) {
CurLine = 0;
CurFilename = "<uninit>";
EmittedTokensOnThisLine = false;
FileType = DirectoryLookup::NormalHeaderDir;
}
void SetEmittedTokensOnThisLine() { EmittedTokensOnThisLine = true; }
virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
DirectoryLookup::DirType FileType);
virtual void Ident(SourceLocation Loc, const std::string &str);
void HandleFirstTokOnLine(Token &Tok);
void MoveToLine(SourceLocation Loc);
bool AvoidConcat(const Token &PrevTok, const Token &Tok);
};
}
/// MoveToLine - Move the output to the source line specified by the location
/// object. We can do this by emitting some number of \n's, or be emitting a
/// #line directive.
void PrintPPOutputPPCallbacks::MoveToLine(SourceLocation Loc) {
if (DisableLineMarkers) {
if (EmittedTokensOnThisLine) {
OutputChar('\n');
EmittedTokensOnThisLine = false;
}
return;
}
unsigned LineNo = PP.getSourceManager().getLogicalLineNumber(Loc);
// If this line is "close enough" to the original line, just print newlines,
// otherwise print a #line directive.
if (LineNo-CurLine < 8) {
if (LineNo-CurLine == 1)
OutputChar('\n');
else {
const char *NewLines = "\n\n\n\n\n\n\n\n";
OutputString(NewLines, LineNo-CurLine);
CurLine = LineNo;
}
} else {
if (EmittedTokensOnThisLine) {
OutputChar('\n');
EmittedTokensOnThisLine = false;
}
CurLine = LineNo;
OutputChar('#');
OutputChar(' ');
std::string Num = llvm::utostr_32(LineNo);
OutputString(&Num[0], Num.size());
OutputChar(' ');
OutputChar('"');
OutputString(&CurFilename[0], CurFilename.size());
OutputChar('"');
if (FileType == DirectoryLookup::SystemHeaderDir)
OutputString(" 3", 2);
else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
OutputString(" 3 4", 4);
OutputChar('\n');
}
}
/// FileChanged - Whenever the preprocessor enters or exits a #include file
/// it invokes this handler. Update our conception of the current source
/// position.
void PrintPPOutputPPCallbacks::FileChanged(SourceLocation Loc,
FileChangeReason Reason,
DirectoryLookup::DirType FileType) {
if (DisableLineMarkers) return;
// Unless we are exiting a #include, make sure to skip ahead to the line the
// #include directive was at.
SourceManager &SourceMgr = PP.getSourceManager();
if (Reason == PPCallbacks::EnterFile) {
MoveToLine(SourceMgr.getIncludeLoc(Loc));
} else if (Reason == PPCallbacks::SystemHeaderPragma) {
MoveToLine(Loc);
// TODO GCC emits the # directive for this directive on the line AFTER the
// directive and emits a bunch of spaces that aren't needed. Emulate this
// strange behavior.
}
Loc = SourceMgr.getLogicalLoc(Loc);
CurLine = SourceMgr.getLineNumber(Loc);
CurFilename = Lexer::Stringify(SourceMgr.getSourceName(Loc));
FileType = FileType;
if (EmittedTokensOnThisLine) {
OutputChar('\n');
EmittedTokensOnThisLine = false;
}
OutputChar('#');
OutputChar(' ');
std::string Num = llvm::utostr_32(CurLine);
OutputString(&Num[0], Num.size());
OutputChar(' ');
OutputChar('"');
OutputString(&CurFilename[0], CurFilename.size());
OutputChar('"');
switch (Reason) {
case PPCallbacks::EnterFile:
OutputString(" 1", 2);
break;
case PPCallbacks::ExitFile:
OutputString(" 2", 2);
break;
case PPCallbacks::SystemHeaderPragma: break;
case PPCallbacks::RenameFile: break;
}
if (FileType == DirectoryLookup::SystemHeaderDir)
OutputString(" 3", 2);
else if (FileType == DirectoryLookup::ExternCSystemHeaderDir)
OutputString(" 3 4", 4);
OutputChar('\n');
}
/// HandleIdent - Handle #ident directives when read by the preprocessor.
///
void PrintPPOutputPPCallbacks::Ident(SourceLocation Loc, const std::string &S) {
MoveToLine(Loc);
OutputString("#ident ", strlen("#ident "));
OutputString(&S[0], S.size());
EmittedTokensOnThisLine = true;
}
/// HandleFirstTokOnLine - When emitting a preprocessed file in -E mode, this
/// is called for the first token on each new line.
void PrintPPOutputPPCallbacks::HandleFirstTokOnLine(Token &Tok) {
// Figure out what line we went to and insert the appropriate number of
// newline characters.
MoveToLine(Tok.getLocation());
// Print out space characters so that the first token on a line is
// indented for easy reading.
const SourceManager &SourceMgr = PP.getSourceManager();
unsigned ColNo = SourceMgr.getLogicalColumnNumber(Tok.getLocation());
// This hack prevents stuff like:
// #define HASH #
// HASH define foo bar
// From having the # character end up at column 1, which makes it so it
// is not handled as a #define next time through the preprocessor if in
// -fpreprocessed mode.
if (ColNo <= 1 && Tok.getKind() == tok::hash)
OutputChar(' ');
// Otherwise, indent the appropriate number of spaces.
for (; ColNo > 1; --ColNo)
OutputChar(' ');
}
namespace {
struct UnknownPragmaHandler : public PragmaHandler {
const char *Prefix;
PrintPPOutputPPCallbacks *Callbacks;
UnknownPragmaHandler(const char *prefix, PrintPPOutputPPCallbacks *callbacks)
: PragmaHandler(0), Prefix(prefix), Callbacks(callbacks) {}
virtual void HandlePragma(Preprocessor &PP, Token &PragmaTok) {
// Figure out what line we went to and insert the appropriate number of
// newline characters.
Callbacks->MoveToLine(PragmaTok.getLocation());
OutputString(Prefix, strlen(Prefix));
// Read and print all of the pragma tokens.
while (PragmaTok.getKind() != tok::eom) {
if (PragmaTok.hasLeadingSpace())
OutputChar(' ');
std::string TokSpell = PP.getSpelling(PragmaTok);
OutputString(&TokSpell[0], TokSpell.size());
PP.LexUnexpandedToken(PragmaTok);
}
OutputChar('\n');
}
};
} // end anonymous namespace
/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause
/// the two individual tokens to be lexed as a single token, return true (which
/// causes a space to be printed between them). This allows the output of -E
/// mode to be lexed to the same token stream as lexing the input directly
/// would.
///
/// This code must conservatively return true if it doesn't want to be 100%
/// accurate. This will cause the output to include extra space characters, but
/// the resulting output won't have incorrect concatenations going on. Examples
/// include "..", which we print with a space between, because we don't want to
/// track enough to tell "x.." from "...".
bool PrintPPOutputPPCallbacks::AvoidConcat(const Token &PrevTok,
const Token &Tok) {
char Buffer[256];
// If we haven't emitted a token on this line yet, PrevTok isn't useful to
// look at and no concatenation could happen anyway.
if (!EmittedTokensOnThisLine)
return false;
// Basic algorithm: we look at the first character of the second token, and
// determine whether it, if appended to the first token, would form (or would
// contribute) to a larger token if concatenated.
char FirstChar;
if (IdentifierInfo *II = Tok.getIdentifierInfo()) {
// Avoid spelling identifiers, the most common form of token.
FirstChar = II->getName()[0];
} else if (Tok.getLength() < 256) {
const char *TokPtr = Buffer;
PP.getSpelling(Tok, TokPtr);
FirstChar = TokPtr[0];
} else {
FirstChar = PP.getSpelling(Tok)[0];
}
tok::TokenKind PrevKind = PrevTok.getKind();
if (PrevTok.getIdentifierInfo()) // Language keyword or named operator.
PrevKind = tok::identifier;
switch (PrevKind) {
default: return false;
case tok::identifier: // id+id or id+number or id+L"foo".
return isalnum(FirstChar) || FirstChar == '_';
case tok::numeric_constant:
return isalnum(FirstChar) || Tok.getKind() == tok::numeric_constant ||
FirstChar == '+' || FirstChar == '-' || FirstChar == '.';
case tok::period: // ..., .*, .1234
return FirstChar == '.' || FirstChar == '*' || isdigit(FirstChar);
case tok::amp: // &&, &=
return FirstChar == '&' || FirstChar == '=';
case tok::plus: // ++, +=
return FirstChar == '+' || FirstChar == '=';
case tok::minus: // --, ->, -=, ->*
return FirstChar == '-' || FirstChar == '>' || FirstChar == '=';
case tok::slash: // /=, /*, //
return FirstChar == '=' || FirstChar == '*' || FirstChar == '/';
case tok::less: // <<, <<=, <=, <?=, <?, <:, <%
return FirstChar == '<' || FirstChar == '?' || FirstChar == '=' ||
FirstChar == ':' || FirstChar == '%';
case tok::greater: // >>, >=, >>=, >?=, >?
return FirstChar == '>' || FirstChar == '?' || FirstChar == '=';
case tok::pipe: // ||, |=
return FirstChar == '|' || FirstChar == '=';
case tok::percent: // %=, %>, %:
return FirstChar == '=' || FirstChar == '>' || FirstChar == ':';
case tok::colon: // ::, :>
return FirstChar == ':' || FirstChar == '>';
case tok::hash: // ##, #@, %:%:
return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';
case tok::arrow: // ->*
return FirstChar == '*';
case tok::star: // *=
case tok::exclaim: // !=
case tok::lessless: // <<=
case tok::greaterequal: // >>=
case tok::caret: // ^=
case tok::equal: // ==
// Cases that concatenate only if the next char is =.
return FirstChar == '=';
}
}
/// DoPrintPreprocessedInput - This implements -E mode.
///
void clang::DoPrintPreprocessedInput(unsigned MainFileID, Preprocessor &PP,
const LangOptions &Options) {
// Inform the preprocessor whether we want it to retain comments or not, due
// to -C or -CC.
PP.SetCommentRetentionState(EnableCommentOutput, EnableMacroCommentOutput);
InitOutputBuffer();
Token Tok, PrevTok;
char Buffer[256];
PrintPPOutputPPCallbacks *Callbacks = new PrintPPOutputPPCallbacks(PP);
PP.setPPCallbacks(Callbacks);
PP.AddPragmaHandler(0, new UnknownPragmaHandler("#pragma", Callbacks));
PP.AddPragmaHandler("GCC", new UnknownPragmaHandler("#pragma GCC",Callbacks));
// After we have configured the preprocessor, enter the main file.
// Start parsing the specified input file.
PP.EnterSourceFile(MainFileID, 0, true);
do {
PrevTok = Tok;
PP.Lex(Tok);
// If this token is at the start of a line, emit newlines if needed.
if (Tok.isAtStartOfLine()) {
Callbacks->HandleFirstTokOnLine(Tok);
} else if (Tok.hasLeadingSpace() ||
// Don't print "-" next to "-", it would form "--".
Callbacks->AvoidConcat(PrevTok, Tok)) {
OutputChar(' ');
}
if (Tok.getLength() < 256) {
const char *TokPtr = Buffer;
unsigned Len = PP.getSpelling(Tok, TokPtr);
OutputString(TokPtr, Len);
} else {
std::string S = PP.getSpelling(Tok);
OutputString(&S[0], S.size());
}
Callbacks->SetEmittedTokensOnThisLine();
} while (Tok.getKind() != tok::eof);
OutputChar('\n');
CleanupOutputBuffer();
}
<|endoftext|> |
<commit_before><commit_msg>gui: unregister timing cone if there are no cones selected<commit_after><|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH
#include <type_traits>
#include <memory>
#include <dune/common/version.hh>
#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //&& HAVE_TBB //EXADUNE
# include <dune/grid/utility/partitioning/seedlist.hh>
# include <dune/stuff/common/parallel/partitioner.hh>
#endif
#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/common/parallel/helper.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>
#include "local/codim0.hh"
#include "local/codim1.hh"
#include "wrapper.hh"
namespace Dune {
namespace GDT {
template< class TestSpaceImp,
class GridViewImp = typename TestSpaceImp::GridViewType,
class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
: public DSG::Walker< GridViewImp >
{
static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
"TestSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
"AnsatzSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_same< typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType >::value,
"Types do not match!");
typedef DSG::Walker< GridViewImp > BaseType;
typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp > ThisType;
public:
typedef TestSpaceImp TestSpaceType;
typedef AnsatzSpaceImp AnsatzSpaceType;
typedef typename TestSpaceType::RangeFieldType RangeFieldType;
typedef typename BaseType::GridViewType GridViewType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::IntersectionType IntersectionType;
typedef DSG::ApplyOn::WhichEntity< GridViewType > ApplyOnWhichEntity;
typedef DSG::ApplyOn::WhichIntersection< GridViewType > ApplyOnWhichIntersection;
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz, GridViewType grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(ansatz)
{}
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(ansatz)
{}
explicit SystemAssembler(TestSpaceType test)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(test)
{}
SystemAssembler(TestSpaceType test, GridViewType grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(test_space_)
{}
const TestSpaceType& test_space() const
{
return *test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return *ansatz_space_;
}
using BaseType::add;
template< class C, class M >
void add(Spaces::ConstraintsInterface< C, RangeFieldType >& constraints,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalMatrixConstraintsWrapper< TestSpaceType,
AnsatzSpaceType,
GridViewType,
typename C::derived_type,
typename M::derived_type > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_,
ansatz_space_,
where,
constraints.as_imp(),
matrix.as_imp()));
} // ... add(...)
/** \todo Investigate why the ConstraintsInterface is not used here! */
template< class ConstraintsType, class V >
void add(ConstraintsType& constraints,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = vector.as_imp();
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalVectorConstraintsWrapper< ThisType, ConstraintsType, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim0Matrix< L >, MatrixType >
WrapperType;
this->codim0_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class Codim0Assembler, class M >
void add_codim0_assembler(const Codim0Assembler& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, Codim0Assembler, MatrixType > WrapperType;
this->codim0_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class Codim0Assembler, class V >
void add_codim0_assembler(const Codim0Assembler& local_assembler,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = vector.as_imp();
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, Codim0Assembler, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim1CouplingMatrix< L >& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichIntersection* where
= new DSG::ApplyOn::AllIntersections< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1CouplingMatrix< L >, MatrixType >
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim1BoundaryMatrix< L >& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichIntersection* where
= new DSG::ApplyOn::AllIntersections< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1BoundaryMatrix< L >, MatrixType >
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichEntity* where
= new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = vector.as_imp();
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, LocalAssembler::Codim0Vector< L >, VectorType >
WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichIntersection* where
= new DSG::ApplyOn::AllIntersections< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalFaceVectorAssemblerWrapper< ThisType, LocalAssembler::Codim1Vector< L >, VectorType >
WrapperType;
this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
void assemble(const bool use_tbb = false)
{
#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE
if (use_tbb) {
Stuff::IndexSetPartitioner< GridViewType > partitioner(this->grid_view_.indexSet());
SeedListPartitioning< typename GridViewType::Grid, 0 > partitioning(this->grid_view_, partitioner);
this->walk(partitioning);
} else
#endif
{
const auto DUNE_UNUSED(no_warning_for_use_tbb) = use_tbb;
this->walk();
}
}
private:
const DS::PerThreadValue<const TestSpaceType> test_space_;
const DS::PerThreadValue<const AnsatzSpaceType> ansatz_space_;
}; // class SystemAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<commit_msg>[assembler] moves tbb stuff to walker completely<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH
#include <type_traits>
#include <memory>
#include <dune/common/version.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/common/parallel/helper.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>
#include "local/codim0.hh"
#include "local/codim1.hh"
#include "wrapper.hh"
namespace Dune {
namespace GDT {
template< class TestSpaceImp,
class GridViewImp = typename TestSpaceImp::GridViewType,
class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
: public DSG::Walker< GridViewImp >
{
static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
"TestSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
"AnsatzSpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_same< typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType >::value,
"Types do not match!");
typedef DSG::Walker< GridViewImp > BaseType;
typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp > ThisType;
public:
typedef TestSpaceImp TestSpaceType;
typedef AnsatzSpaceImp AnsatzSpaceType;
typedef typename TestSpaceType::RangeFieldType RangeFieldType;
typedef typename BaseType::GridViewType GridViewType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::IntersectionType IntersectionType;
typedef DSG::ApplyOn::WhichEntity< GridViewType > ApplyOnWhichEntity;
typedef DSG::ApplyOn::WhichIntersection< GridViewType > ApplyOnWhichIntersection;
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz, GridViewType grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(ansatz)
{}
SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(ansatz)
{}
explicit SystemAssembler(TestSpaceType test)
: BaseType(test.grid_view())
, test_space_(test)
, ansatz_space_(test)
{}
SystemAssembler(TestSpaceType test, GridViewType grid_view)
: BaseType(grid_view)
, test_space_(test)
, ansatz_space_(test_space_)
{}
const TestSpaceType& test_space() const
{
return *test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return *ansatz_space_;
}
using BaseType::add;
template< class C, class M >
void add(Spaces::ConstraintsInterface< C, RangeFieldType >& constraints,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
assert(matrix.rows() == test_space_->mapper().size());
assert(matrix.cols() == ansatz_space_->mapper().size());
typedef internal::LocalMatrixConstraintsWrapper< TestSpaceType,
AnsatzSpaceType,
GridViewType,
typename C::derived_type,
typename M::derived_type > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_,
ansatz_space_,
where,
constraints.as_imp(),
matrix.as_imp()));
} // ... add(...)
/** \todo Investigate why the ConstraintsInterface is not used here! */
template< class ConstraintsType, class V >
void add(ConstraintsType& constraints,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = vector.as_imp();
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalVectorConstraintsWrapper< ThisType, ConstraintsType, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim0Matrix< L >, MatrixType >
WrapperType;
this->codim0_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class Codim0Assembler, class M >
void add_codim0_assembler(const Codim0Assembler& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, Codim0Assembler, MatrixType > WrapperType;
this->codim0_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class Codim0Assembler, class V >
void add_codim0_assembler(const Codim0Assembler& local_assembler,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = vector.as_imp();
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, Codim0Assembler, VectorType > WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim1CouplingMatrix< L >& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichIntersection* where
= new DSG::ApplyOn::AllIntersections< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1CouplingMatrix< L >, MatrixType >
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class L, class M >
void add(const LocalAssembler::Codim1BoundaryMatrix< L >& local_assembler,
Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
const ApplyOnWhichIntersection* where
= new DSG::ApplyOn::AllIntersections< GridViewType >())
{
typedef typename M::derived_type MatrixType;
MatrixType& matrix_imp = matrix.as_imp();
assert(matrix_imp.rows() == test_space_->mapper().size());
assert(matrix_imp.cols() == ansatz_space_->mapper().size());
typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1BoundaryMatrix< L >, MatrixType >
WrapperType;
this->codim1_functors_.emplace_back(
new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichEntity* where
= new DSG::ApplyOn::AllEntities< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = vector.as_imp();
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, LocalAssembler::Codim0Vector< L >, VectorType >
WrapperType;
this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
template< class L, class V >
void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
const ApplyOnWhichIntersection* where
= new DSG::ApplyOn::AllIntersections< GridViewType >())
{
typedef typename V::derived_type VectorType;
VectorType& vector_imp = static_cast< VectorType& >(vector);
assert(vector_imp.size() == test_space_->mapper().size());
typedef internal::LocalFaceVectorAssemblerWrapper< ThisType, LocalAssembler::Codim1Vector< L >, VectorType >
WrapperType;
this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
} // ... add(...)
void assemble(const bool use_tbb = false)
{
this->walk(use_tbb);
}
private:
const DS::PerThreadValue<const TestSpaceType> test_space_;
const DS::PerThreadValue<const AnsatzSpaceType> ansatz_space_;
}; // class SystemAssembler
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2013 - 2017)
// Rene Milk (2014, 2016 - 2018)
// Sven Kaulmann (2014)
// Tobias Leibner (2014, 2016 - 2017)
#ifndef DUNE_GDT_SPACES_INTERFACE_HH
#define DUNE_GDT_SPACES_INTERFACE_HH
#include <dune/geometry/type.hh>
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/local/finite-elements/interfaces.hh>
#include <dune/gdt/spaces/basis/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
#include <dune/gdt/spaces/parallel/communication.hh>
#include <dune/gdt/type_traits.hh>
namespace Dune {
namespace GDT {
// forward
template <class V, class GV, size_t r, size_t rC, class R>
class ConstDiscreteFunction;
template <class GridView, size_t range_dim = 1, size_t range_dim_columns = 1, class RangeField = double>
class SpaceInterface
{
static_assert(XT::Grid::is_view<GridView>::value, "");
public:
using GridViewType = GridView;
using GV = GridViewType;
using D = typename GridViewType::ctype;
static const constexpr size_t d = GridViewType::dimension;
using R = RangeField;
static const constexpr size_t r = range_dim;
static const constexpr size_t rC = range_dim_columns;
using GlobalBasisType = GlobalBasisInterface<GridViewType, r, rC, R>;
using MapperType = MapperInterface<GridViewType>;
using FiniteElementType = LocalFiniteElementInterface<D, d, R, r, rC>;
using DofCommunicatorType = typename DofCommunicationChooser<GridViewType>::Type;
SpaceInterface()
: dof_communicator_(nullptr)
{
}
virtual ~SpaceInterface() = default;
/// \name These methods provide the actual functionality, they have to be implemented.
/// \{
virtual const GridViewType& grid_view() const = 0;
virtual const MapperType& mapper() const = 0;
virtual const GlobalBasisType& basis() const = 0;
virtual const FiniteElementType& finite_element(const GeometryType& geometry_type) const = 0;
/// \}
/// \name These methods help to identify the space, they have to be implemented.
/// \{
virtual SpaceType type() const = 0;
virtual int min_polorder() const = 0;
virtual int max_polorder() const = 0;
/**
* To query if elements of this space (functions) are continuous (i.e., in C^0), use `continuous(0)`.
*/
virtual bool continuous(const int diff_order) const = 0;
virtual bool continuous_normal_components() const = 0;
/**
* If this returns true, every finite_element() is expected to provide lagrange_points().
*/
virtual bool is_lagrangian() const = 0;
/// \}
/// \name These methods are required for MPI communication, they are provided.
/// \{
virtual const DofCommunicatorType& dof_communicator() const
{
if (!dof_communicator_)
DUNE_THROW(Exceptions::space_error,
"The actual space has to either implement its own dof_communicator() or call "
"create_communicator() in the ctor!");
return *dof_communicator_;
}
/// \}
/// \name These methods are provided for convenience.
/// \{
template <class V>
bool contains(const XT::LA::VectorInterface<V>& vector) const
{
return vector.size() == this->mapper().size();
}
/**
* \note A return value of true cannot be ultimately trusted yet.
*
* \sa https://github.com/dune-community/dune-gdt/issues/123
*/
template <class V>
bool contains(const ConstDiscreteFunction<V, GV, r, rC, R>& function) const
{
// this is the only case where we are sure^^
if (&function.space() == this)
return true;
if (function.space().type() != this->type())
return false;
if (function.space().mapper().size() != this->mapper().size())
return false;
// the spaces might still differ (different grid views of same size), but we have no means to check this
return true;
}
/// \}
protected:
void create_communicator()
{
if (!dof_communicator_) {
dof_communicator_ =
std::shared_ptr<DofCommunicatorType>(DofCommunicationChooser<GridViewType>::create(grid_view()));
DofCommunicationChooser<GridViewType>::prepare(*this, *dof_communicator_);
}
}
private:
std::shared_ptr<DofCommunicatorType> dof_communicator_;
}; // class SpaceInterface
template <class GV, size_t r, size_t rC, class R>
std::ostream& operator<<(std::ostream& out, const SpaceInterface<GV, r, rC, R>& space)
{
out << "Space(" << space.type() << ", " << space.mapper().size() << " DoFs)";
return out;
}
} // namespace GDT
} // namespace Dune
#include <dune/gdt/discretefunction/default.hh>
#endif // DUNE_GDT_SPACES_INTERFACE_HH
<commit_msg>[spaces.interface] drop include which lead to circular includes<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2013 - 2017)
// Rene Milk (2014, 2016 - 2018)
// Sven Kaulmann (2014)
// Tobias Leibner (2014, 2016 - 2017)
#ifndef DUNE_GDT_SPACES_INTERFACE_HH
#define DUNE_GDT_SPACES_INTERFACE_HH
#include <dune/geometry/type.hh>
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/local/finite-elements/interfaces.hh>
#include <dune/gdt/spaces/basis/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
#include <dune/gdt/spaces/parallel/communication.hh>
#include <dune/gdt/type_traits.hh>
namespace Dune {
namespace GDT {
// forward
template <class V, class GV, size_t r, size_t rC, class R>
class ConstDiscreteFunction;
template <class GridView, size_t range_dim = 1, size_t range_dim_columns = 1, class RangeField = double>
class SpaceInterface
{
static_assert(XT::Grid::is_view<GridView>::value, "");
public:
using GridViewType = GridView;
using GV = GridViewType;
using D = typename GridViewType::ctype;
static const constexpr size_t d = GridViewType::dimension;
using R = RangeField;
static const constexpr size_t r = range_dim;
static const constexpr size_t rC = range_dim_columns;
using GlobalBasisType = GlobalBasisInterface<GridViewType, r, rC, R>;
using MapperType = MapperInterface<GridViewType>;
using FiniteElementType = LocalFiniteElementInterface<D, d, R, r, rC>;
using DofCommunicatorType = typename DofCommunicationChooser<GridViewType>::Type;
SpaceInterface()
: dof_communicator_(nullptr)
{
}
virtual ~SpaceInterface() = default;
/// \name These methods provide the actual functionality, they have to be implemented.
/// \{
virtual const GridViewType& grid_view() const = 0;
virtual const MapperType& mapper() const = 0;
virtual const GlobalBasisType& basis() const = 0;
virtual const FiniteElementType& finite_element(const GeometryType& geometry_type) const = 0;
/// \}
/// \name These methods help to identify the space, they have to be implemented.
/// \{
virtual SpaceType type() const = 0;
virtual int min_polorder() const = 0;
virtual int max_polorder() const = 0;
/**
* To query if elements of this space (functions) are continuous (i.e., in C^0), use `continuous(0)`.
*/
virtual bool continuous(const int diff_order) const = 0;
virtual bool continuous_normal_components() const = 0;
/**
* If this returns true, every finite_element() is expected to provide lagrange_points().
*/
virtual bool is_lagrangian() const = 0;
/// \}
/// \name These methods are required for MPI communication, they are provided.
/// \{
virtual const DofCommunicatorType& dof_communicator() const
{
if (!dof_communicator_)
DUNE_THROW(Exceptions::space_error,
"The actual space has to either implement its own dof_communicator() or call "
"create_communicator() in the ctor!");
return *dof_communicator_;
}
/// \}
/// \name These methods are provided for convenience.
/// \{
template <class V>
bool contains(const XT::LA::VectorInterface<V>& vector) const
{
return vector.size() == this->mapper().size();
}
/**
* \note A return value of true cannot be ultimately trusted yet.
*
* \sa https://github.com/dune-community/dune-gdt/issues/123
*/
template <class V>
bool contains(const ConstDiscreteFunction<V, GV, r, rC, R>& function) const
{
// this is the only case where we are sure^^
if (&function.space() == this)
return true;
if (function.space().type() != this->type())
return false;
if (function.space().mapper().size() != this->mapper().size())
return false;
// the spaces might still differ (different grid views of same size), but we have no means to check this
return true;
}
/// \}
protected:
void create_communicator()
{
if (!dof_communicator_) {
dof_communicator_ =
std::shared_ptr<DofCommunicatorType>(DofCommunicationChooser<GridViewType>::create(grid_view()));
DofCommunicationChooser<GridViewType>::prepare(*this, *dof_communicator_);
}
}
private:
std::shared_ptr<DofCommunicatorType> dof_communicator_;
}; // class SpaceInterface
template <class GV, size_t r, size_t rC, class R>
std::ostream& operator<<(std::ostream& out, const SpaceInterface<GV, r, rC, R>& space)
{
out << "Space(" << space.type() << ", " << space.mapper().size() << " DoFs)";
return out;
}
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_INTERFACE_HH
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-2002, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//
//
// Hadron correction base class
//
//
//
//
#include "AliEMCALHadronCorrection.h"
ClassImp(AliEMCALHadronCorrection)
AliEMCALHadronCorrection::AliEMCALHadronCorrection(const char *name,const char *title)
:TNamed(name,title) { }
<commit_msg>Reduced violations<commit_after>/**************************************************************************
* Copyright(c) 1998-2002, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//--
//--
//-- Hadron correction base class
//--
//--
//--
#include "AliEMCALHadronCorrection.h"
ClassImp(AliEMCALHadronCorrection)
AliEMCALHadronCorrection::AliEMCALHadronCorrection(const char *name,const char *title)
:TNamed(name,title) { }
<|endoftext|> |
<commit_before>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Types.hpp"
/// <summary>
/// ライブラリのバージョン表示
/// Version text
/// </summary>
# define SIV3D_VERSION U"0.4.0"
namespace s3d
{
/// <summary>
/// バージョン ID
/// Version value
/// </summary>
inline constexpr uint32 Siv3DVersion = 200'004'003u;
}
<commit_msg>start 0.4.1<commit_after>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2019 Ryo Suzuki
// Copyright (c) 2016-2019 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Types.hpp"
/// <summary>
/// ライブラリのバージョン表示
/// Version text
/// </summary>
# define SIV3D_VERSION U"0.4.1dev"
namespace s3d
{
/// <summary>
/// バージョン ID
/// Version value
/// </summary>
inline constexpr uint32 Siv3DVersion = 200'004'010u;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <thread>
#include "DoryProcessSpawn.hpp"
using namespace std;
using namespace spawn;
void loop(uv_loop_t* uv_loop) {
uv_timer_t timer;
int r;
r = uv_timer_init(uv_loop, &timer);
ASSERT(r==0);
// repeat every 1000 millisec to make the loop lives forever
// later, it will be used as whatdog.
r = uv_timer_start(&timer, [](uv_timer_t* timer){
cout << "in timer" << endl;
}, 0, 1000);
ASSERT(r == 0);
uv_run(uv_loop, UV_RUN_DEFAULT);
}
int main() {
uv_loop_t* uv_loop = uv_default_loop();
char* args[3];
args[0] = (char*)"./child";
args[1] = (char*)"200";
args[2] = NULL;
DoryProcessSpawn process(uv_loop, args);
//process.timeout = 1000;
int r = process.on("timeout", []() {
cout << "timeout fired" << endl;
})
.on("stdout", [](char* buf, ssize_t nread) {
for(int i=0;i<nread;i++)
printf("%c", buf[i]);
})
.on("stderr", [](char* buf, ssize_t nread) {
for(int i=0;i<nread;i++)
printf("%c", buf[i]);
})
.on("exit", [](int64_t exitStatus, int termSignal) {
cout << "exit code : " << exitStatus << endl;
cout << "signal : " << termSignal << endl;
})
.spawn();
// check the result of spawn()
if (r != 0)
cout << uv_err_name(r) << " " << uv_strerror(r) << endl;
std::thread n(loop, uv_loop);
n.join();
return 0;
}<commit_msg>using random, and thread detach in example.<commit_after>#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <thread>
#include <unistd.h>
#include "DoryProcessSpawn.hpp"
using namespace std;
using namespace spawn;
std::thread *n;
uv_loop_t* uv_loop = uv_default_loop();
void loop(uv_loop_t* uv_loop) {
uv_timer_t timer;
int r;
r = uv_timer_init(uv_loop, &timer);
ASSERT(r==0);
// repeat every 1000 millisec to make the loop lives forever
// later, it will be used as whatdog.
r = uv_timer_start(&timer, [](uv_timer_t* timer){
cout << "in timer" << endl;
}, 0, 1000);
ASSERT(r == 0);
uv_run(uv_loop, UV_RUN_DEFAULT);
}
int main() {
//init
n = new std::thread(loop, uv_loop);
n->detach();
srand(time(NULL));
int i=0;
while(1) {
i++;
if (i > 10) {
usleep(10*1000);
continue;
}
char buf[10];
sprintf(buf,"%i",rand()%10000);
char* args[3];
args[0] = (char*)"./child";
args[1] = buf; // (char*)"2000";
args[2] = NULL;
// FIXME : leak
DoryProcessSpawn *process = new DoryProcessSpawn(uv_loop, args);
//process.timeout = 1000;
int r = process->on("timeout", []() {
cout << "timeout fired" << endl;
})
.on("stdout", [](char* buf, ssize_t nread) {
for(int i=0;i<nread;i++)
printf("%c", buf[i]);
})
.on("stderr", [](char* buf, ssize_t nread) {
for(int i=0;i<nread;i++)
printf("%c", buf[i]);
})
.on("exit", [](int64_t exitStatus, int termSignal) {
cout << "exit code : " << exitStatus << endl;
cout << "signal : " << termSignal << endl;
})
.spawn();
// check the result of spawn()
if (r != 0)
cout << uv_err_name(r) << " " << uv_strerror(r) << endl;
}
return 0;
}<|endoftext|> |
<commit_before>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* OTRadValve TempControl tests.
*/
#include <gtest/gtest.h>
#include "OTSIM900Link.h"
// Test for general sanity of OTSIM900Link.
// In particular, simulate some nominal REV7/DORM1/TRV1 numbers.
TEST(OTSIM900Link,basics)
{
class NULLSerialStream final : public Stream
{
public:
void begin(unsigned long) { }
void begin(unsigned long, uint8_t);
void end();
virtual size_t write(uint8_t) override { return(0); }
virtual int available() override { return(-1); }
virtual int read() override { return(-1); }
virtual int peek() override { return(-1); }
virtual void flush() override { }
};
OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0;
EXPECT_TRUE(l0.begin());
// Try to hang just by calling poll() repeatedly.
for(int i = 0; i < 1000; ++i) { l0.poll(); }
// ...
l0.end();
}
<commit_msg>TODO-1029: trying to set up SIM900 test harness<commit_after>/*
The OpenTRV project licenses this file to you
under the Apache Licence, Version 2.0 (the "Licence");
you may not use this file except in compliance
with the Licence. You may obtain a copy of the Licence at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the Licence is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the Licence for the
specific language governing permissions and limitations
under the Licence.
Author(s) / Copyright (s): Damon Hart-Davis 2016
*/
/*
* OTRadValve TempControl tests.
*/
#include <gtest/gtest.h>
#include "OTSIM900Link.h"
// Test for general sanity of OTSIM900Link.
// Make sure than an instance can be created and does not die horribly.
TEST(OTSIM900Link,basics)
{
class NULLSerialStream final : public Stream
{
public:
void begin(unsigned long) { }
void begin(unsigned long, uint8_t);
void end();
virtual size_t write(uint8_t) override { return(0); }
virtual int available() override { return(-1); }
virtual int read() override { return(-1); }
virtual int peek() override { return(-1); }
virtual void flush() override { }
};
OTSIM900Link::OTSIM900Link<0, 0, 0, NULLSerialStream> l0;
EXPECT_TRUE(l0.begin());
// Try to hang just by calling poll() repeatedly.
for(int i = 0; i < 1000; ++i) { l0.poll(); }
// ...
l0.end();
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "itkVariableLengthVector.h"
#include "otbChangeLabelImageFilter.h"
#include "otbStandardWriterWatcher.h"
#include "otbStatisticsXMLFileReader.h"
#include "otbShiftScaleVectorImageFilter.h"
#include "otbSVMImageClassificationFilter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbImageToVectorImageCastFilter.h"
namespace otb
{
namespace Wrapper
{
class ImageSVMClassifier : public Application
{
public:
/** Standard class typedefs. */
typedef ImageSVMClassifier Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ImageSVMClassifier, otb::Application);
/** Filters typedef */
typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType> MeasurementType;
typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader;
typedef otb::ShiftScaleVectorImageFilter<FloatVectorImageType, FloatVectorImageType> RescalerType;
typedef otb::SVMImageClassificationFilter<FloatVectorImageType, UInt8ImageType> ClassificationFilterType;
typedef ClassificationFilterType::Pointer ClassificationFilterPointerType;
typedef ClassificationFilterType::ModelType ModelType;
typedef ModelType::Pointer ModelPointerType;
private:
ImageSVMClassifier()
{
SetName("ImageSVMClassifier");
SetDescription("Perform SVM classification based on a previous computed SVM model");
// Documentation
SetDocName("Image SVM Classifier Application");
SetDocLongDescription("This application performs an image classification based on the SVM classifier. The image to classify and the SVM model are given in input, the application will generate the classified output image. Optionnally, the user can give an image statistics file (that contains min, max) to normalize the input image before the classification. Furthemore, the user can give a mask to define area of work (only pixel with value greater to 0 will be porceed), this no classify pixels will appear in the output image with the value 0.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("TrainSVMImagesClassifier application, ValidateSVMImagesClassifier");
SetDocCLExample("otbApplicationLauncherCommandLine ImageSVMClassifier ${OTB-BIN}/bin --in ${OTB-DATA}/Classification/QB_1_ortho.tif --imstat ${OTB-DATA}/Baseline/OTB-Applications/Files/clImageStatisticsQB1.xml --svn ${OTB-DATA}/Baseline/OTB-Applications/Files/clsvmModelQB1.svm --out otbConcatenateImages.png uchar");
AddDocTag("Classification");
AddDocTag("SVM");
}
virtual ~ImageSVMClassifier()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image to classify");
SetParameterDescription( "in", "Input Image to classify");
AddParameter(ParameterType_InputImage, "mask", "Input Mask to classify");
SetParameterDescription( "mask", "A mask associated with the new image to classify");
MandatoryOff("mask");
AddParameter(ParameterType_Filename, "imstat", "Image statistics file.");
SetParameterDescription("imstat", "a XML file containing mean and standard deviation of input images used to train svm model");
MandatoryOff("imstat");
AddParameter(ParameterType_Filename, "svm", "SVM Model.");
SetParameterDescription("svm", "An estimated SVM model previously computed");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription( "out", "Output labeled image");
SetParameterOutputImagePixelType( "out", ImagePixelType_uint8);
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
void DoExecute()
{
// Load input image
FloatVectorImageType::Pointer inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
// Load svm model
otbAppLogINFO("Loading SVM model");
m_ModelSVM = ModelType::New();
m_ModelSVM->LoadModel(GetParameterString("svm").c_str());
otbAppLogINFO("SVM model loaded");
// Normalize input image (optional)
StatisticsReader::Pointer statisticsReader = StatisticsReader::New();
MeasurementType meanMeasurementVector;
MeasurementType stddevMeasurementVector;
m_Rescaler = RescalerType::New();
// Classify
m_ClassificationFilter = ClassificationFilterType::New();
m_ClassificationFilter->SetModel(m_ModelSVM);
// Normalize input image if asked
if( HasValue("imstat") )
{
otbAppLogINFO("Input image normalization activated.");
// Load input image statistics
statisticsReader->SetFileName(GetParameterString("imstat"));
meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean");
stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev");
otbAppLogINFO( "mean used: " << meanMeasurementVector );
otbAppLogINFO( "standard deviation used: " << stddevMeasurementVector );
// Rescale vector image
m_Rescaler->SetScale(stddevMeasurementVector);
m_Rescaler->SetShift(meanMeasurementVector);
m_Rescaler->SetInput(inImage);
m_ClassificationFilter->SetInput(m_Rescaler->GetOutput());
}
else
{
otbAppLogINFO("Input image normalization deactivated.");
m_ClassificationFilter->SetInput(inImage);
}
if( HasValue("mask") )
{
otbAppLogINFO("Using input mask");
// Load mask image and cast into LabeledImageType
UInt8ImageType::Pointer inMask = GetParameterUInt8Image("mask");
m_ClassificationFilter->SetInputMask(inMask);
}
SetParameterOutputImage<UInt8ImageType>("out", m_ClassificationFilter->GetOutput());
}
ClassificationFilterType::Pointer m_ClassificationFilter;
ModelPointerType m_ModelSVM;
RescalerType::Pointer m_Rescaler;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ImageSVMClassifier)
<commit_msg>DOC: Images SVM Classifier Doc update.<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "itkVariableLengthVector.h"
#include "otbChangeLabelImageFilter.h"
#include "otbStandardWriterWatcher.h"
#include "otbStatisticsXMLFileReader.h"
#include "otbShiftScaleVectorImageFilter.h"
#include "otbSVMImageClassificationFilter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "otbImageToVectorImageCastFilter.h"
namespace otb
{
namespace Wrapper
{
class ImageSVMClassifier : public Application
{
public:
/** Standard class typedefs. */
typedef ImageSVMClassifier Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ImageSVMClassifier, otb::Application);
/** Filters typedef */
typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType> MeasurementType;
typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader;
typedef otb::ShiftScaleVectorImageFilter<FloatVectorImageType, FloatVectorImageType> RescalerType;
typedef otb::SVMImageClassificationFilter<FloatVectorImageType, UInt8ImageType> ClassificationFilterType;
typedef ClassificationFilterType::Pointer ClassificationFilterPointerType;
typedef ClassificationFilterType::ModelType ModelType;
typedef ModelType::Pointer ModelPointerType;
private:
ImageSVMClassifier()
{
SetName("ImageSVMClassifier");
SetDescription("Perform SVM classification based on a previous computed SVM model");
// Documentation
SetDocName("Image SVM Classifier Application");
SetDocLongDescription("This application performs an image classification based on the SVM classifier."
"The image to classify and the SVM model are given in input, the application will generate the classified output image. "
" Optionally, the user can give an image statistics file (that contains min, max) to normalize the input image before the classification."
" Furthemore, the user can give a mask to define area of work (only pixels with values greater to 0 will be proceed), "
"these no classify pixels will appear in the output image with the value 0.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("TrainSVMImagesClassifier, ValidateSVMImagesClassifier, EstimatesImagesStatistics");
SetDocCLExample("otbApplicationLauncherCommandLine ImageSVMClassifier ${OTB-BIN}/bin --in ${OTB-DATA}/Classification/QB_1_ortho.tif --imstat ${OTB-DATA}/Baseline/OTB-Applications/Files/clImageStatisticsQB1.xml --svn ${OTB-DATA}/Baseline/OTB-Applications/Files/clsvmModelQB1.svm --out otbConcatenateImages.png uchar");
AddDocTag("Classification");
AddDocTag("SVM");
}
virtual ~ImageSVMClassifier()
{
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image to classify");
SetParameterDescription( "in", "Input Image to classify");
AddParameter(ParameterType_InputImage, "mask", "Input Mask to classify");
SetParameterDescription( "mask", "A mask associated with the new image to classify");
MandatoryOff("mask");
AddParameter(ParameterType_Filename, "imstat", "Image statistics file.");
SetParameterDescription("imstat", "a XML file containing mean and standard deviation of input images used to train svm model");
MandatoryOff("imstat");
AddParameter(ParameterType_Filename, "svm", "SVM Model.");
SetParameterDescription("svm", "An estimated SVM model previously computed");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription( "out", "Output labeled image");
SetParameterOutputImagePixelType( "out", ImagePixelType_uint8);
}
void DoUpdateParameters()
{
// Nothing to do here : all parameters are independent
}
void DoExecute()
{
// Load input image
FloatVectorImageType::Pointer inImage = GetParameterImage("in");
inImage->UpdateOutputInformation();
// Load svm model
otbAppLogINFO("Loading SVM model");
m_ModelSVM = ModelType::New();
m_ModelSVM->LoadModel(GetParameterString("svm").c_str());
otbAppLogINFO("SVM model loaded");
// Normalize input image (optional)
StatisticsReader::Pointer statisticsReader = StatisticsReader::New();
MeasurementType meanMeasurementVector;
MeasurementType stddevMeasurementVector;
m_Rescaler = RescalerType::New();
// Classify
m_ClassificationFilter = ClassificationFilterType::New();
m_ClassificationFilter->SetModel(m_ModelSVM);
// Normalize input image if asked
if( HasValue("imstat") )
{
otbAppLogINFO("Input image normalization activated.");
// Load input image statistics
statisticsReader->SetFileName(GetParameterString("imstat"));
meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean");
stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev");
otbAppLogINFO( "mean used: " << meanMeasurementVector );
otbAppLogINFO( "standard deviation used: " << stddevMeasurementVector );
// Rescale vector image
m_Rescaler->SetScale(stddevMeasurementVector);
m_Rescaler->SetShift(meanMeasurementVector);
m_Rescaler->SetInput(inImage);
m_ClassificationFilter->SetInput(m_Rescaler->GetOutput());
}
else
{
otbAppLogINFO("Input image normalization deactivated.");
m_ClassificationFilter->SetInput(inImage);
}
if( HasValue("mask") )
{
otbAppLogINFO("Using input mask");
// Load mask image and cast into LabeledImageType
UInt8ImageType::Pointer inMask = GetParameterUInt8Image("mask");
m_ClassificationFilter->SetInputMask(inMask);
}
SetParameterOutputImage<UInt8ImageType>("out", m_ClassificationFilter->GetOutput());
}
ClassificationFilterType::Pointer m_ClassificationFilter;
ModelPointerType m_ModelSVM;
RescalerType::Pointer m_Rescaler;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ImageSVMClassifier)
<|endoftext|> |
<commit_before>#include "OniFrameManager.h"
#include <XnOSCpp.h>
ONI_NAMESPACE_IMPLEMENTATION_BEGIN
FrameManager::FrameManager()
{
}
FrameManager::~FrameManager()
{
}
OniFrameInternal* FrameManager::acquireFrame()
{
OniFrameInternal* pFrame = m_frames.Acquire();
xnOSMemSet(pFrame, 0, sizeof(OniFrameInternal);
pFrame->refCount = 1;
return pFrame;
}
void FrameManager::addRef(OniFrame* pFrame)
{
OniFrameInternal* pInternal = (OniFrameInternal*)pFrame;
m_frames.Lock();
++pInternal->refCount;
m_frames.Unlock();
}
void FrameManager::release(OniFrame* pFrame)
{
OniFrameInternal* pInternal = (OniFrameInternal*)pFrame;
m_frames.Lock();
if (--pInternal->refCount == 0)
{
// notify frame is back to pool
if (pInternal->backToPoolFunc != NULL)
{
pInternal->backToPoolFunc(pInternal, pInternal->backToPoolFuncCookie);
}
// and return frame to pool
m_frames.Release(pInternal);
}
m_frames.Unlock();
}
ONI_NAMESPACE_IMPLEMENTATION_END
<commit_msg>Fixed typo.<commit_after>#include "OniFrameManager.h"
#include <XnOSCpp.h>
ONI_NAMESPACE_IMPLEMENTATION_BEGIN
FrameManager::FrameManager()
{
}
FrameManager::~FrameManager()
{
}
OniFrameInternal* FrameManager::acquireFrame()
{
OniFrameInternal* pFrame = m_frames.Acquire();
xnOSMemSet(pFrame, 0, sizeof(OniFrameInternal));
pFrame->refCount = 1;
return pFrame;
}
void FrameManager::addRef(OniFrame* pFrame)
{
OniFrameInternal* pInternal = (OniFrameInternal*)pFrame;
m_frames.Lock();
++pInternal->refCount;
m_frames.Unlock();
}
void FrameManager::release(OniFrame* pFrame)
{
OniFrameInternal* pInternal = (OniFrameInternal*)pFrame;
m_frames.Lock();
if (--pInternal->refCount == 0)
{
// notify frame is back to pool
if (pInternal->backToPoolFunc != NULL)
{
pInternal->backToPoolFunc(pInternal, pInternal->backToPoolFuncCookie);
}
// and return frame to pool
m_frames.Release(pInternal);
}
m_frames.Unlock();
}
ONI_NAMESPACE_IMPLEMENTATION_END
<|endoftext|> |
<commit_before>/******************************************************************************\
* LuaValue.hpp *
* A class that somewhat mimics a Lua value. *
* Leandro Motta Barros *
\******************************************************************************/
#ifndef _DILUCULUM_LUA_VALUE_HPP_
#define _DILUCULUM_LUA_VALUE_HPP_
extern "C"
{
# include <lua.h>
}
#include <map>
#include <stdexcept>
#include <string>
#include <boost/any.hpp>
namespace Diluculum
{
// Just a forward declaration.
class LuaValue;
/** Type mapping from <tt>LuaValue</tt>s to <tt>LuaValue</tt>s. Think of it
* as a C++ approximation of a Lua table.
*/
typedef std::map<LuaValue, LuaValue> LuaValueMap;
/// A generic <tt>LuaValue</tt>-related error.
class LuaValueError: public std::runtime_error
{
public:
/** Constructs a \c LuaValueError object.
* @param what The message associated with the error.
*/
LuaValueError (const char* what)
: std::runtime_error (what)
{ }
};
/** An error in a \c LuaValueError that happens when a certain type is
* expected but another one is found.
*/
class TypeMismatchError: public LuaValueError
{
public:
/** Constructs a \c TypeMismatchError object.
* @param expectedType The type that was expected.
* @param expectedType The type that was actually found.
*/
TypeMismatchError (const std::string& expectedType,
const std::string& foundType);
/** Destroys a \c TypeMismatchError object.
* @note This was defined just to pretend that the destructor does not
* throw any exception. While this is something that I cannot
* guarantee (at least whit this implementation), I believe this
* not a very dangerous lie.
*/
~TypeMismatchError() throw() { };
/// Returns the type that was expected.
std::string getExpectedType() { return expectedType_; }
/// Returns the type that was actually found.
std::string getFoundType() { return foundType_; }
private:
/// The type that was expected.
std::string expectedType_;
/// The type that was actually found.
std::string foundType_;
};
/// A class that somewhat mimics a Lua value.
class LuaValue
{
public:
/// Constructs a \c LuaValue with a \c nil value.
LuaValue() { };
/// Constructs a \c LuaValue with boolean type and \c b value.
LuaValue (bool b)
: value_(b)
{ }
/// Constructs a \c LuaValue with number type and \c n value.
LuaValue (lua_Number n)
: value_(n)
{ }
/// Constructs a \c LuaValue with string type and \c s value.
LuaValue (const std::string& s)
: value_(s)
{ }
/// Constructs a \c LuaValue with string type and \c s value.
LuaValue (const char* s)
: value_(std::string(s))
{ }
/// Constructs a \c LuaValue with table type and \c t value.
LuaValue (const LuaValueMap& t)
: value_(t)
{ }
/** Returns one of the <tt>LUA_T*</tt> constants from <tt>lua.h</tt>,
* representing the type stored in this \c LuaValue.
*/
int type() const;
/** Returns the type of this \c LuaValue as a string, just like the Lua
* built-in function \c type().
* @return One of the following strings: <tt>"nil"</tt>,
* <tt>"boolean"</tt>, <tt>"number"</tt>, <tt>"string"</tt>,
* <tt>"table"</tt>. If the stored value is different than
* those for some reason, returns an empty string
* (<tt>""</tt>).
*/
std::string typeName() const;
/** Return the value as a number.
* @throw TypeMismatchError If the value is not a number (this is a
* strict check; no type conversion is performed).
*/
lua_Number asNumber() const;
/** Return the value as a string.
* @throw TypeMismatchError If the value is not a string (this is a
* strict check; no type conversion is performed).
*/
std::string asString() const;
/** Return the value as a boolean.
* @throw TypeMismatchError If the value is not a boolean (this is a
* strict check; no type conversion is performed).
*/
bool asBoolean() const;
/** Return the value as a table (\c LuaValueMap).
* @throw TypeMismatchError If the value is not a table (this is a
* strict check; no type conversion is performed).
*/
LuaValueMap asTable() const;
/** "Less than" operator for <tt>LuaValue</tt>s.
* @return The order relationship is quite arbitrary for
* <tt>LuaValue</tt>s, but this has to be defined in order to
* \c LuaValueMap work nicely. Anyway, here are the rules used
* to determine who is less than who:
* - First, \c typeName() is called for both
* <tt>LuaValue</tt>s and they are compared with the usual
* "less than" operator for strings.
* - If both type names are equal, but something different
* than <tt>"nil"</tt> or <tt>"table"</tt>, then the values
* contained in the <tt>LuaValue</tt>s are compared using
* the usual "less than" operator for that type.
* - If both type names are <tt>"nil"</tt>, the function
* returns \c false.
* - If both type names are <tt>"table"</tt>, then the number
* of elements in each table are compared. The shorter table
* is "less than" the larger table.
* - If both tables have the same size, then each entry is
* recursively compared (that is, using the rules described
* here). For each entry, the key is compared first, than
* the value. This is done until finding something "less
* than" the other thing.
* - If no differences are found, \c false is obviously
* returned.
*/
bool operator< (const LuaValue& rhs) const;
/** "Greater than" operator for <tt>LuaValue</tt>s.
* @return The rules for determining who is greater than who are
* similar to the ones described in \c operator<.
*/
bool operator> (const LuaValue& rhs) const;
// TODO: A shortcut for table-like access:
// LuaValue& operator[] (const LuaValue& key) { return ...; }
// TODO: Notice the reference return value above. Is this supported by
// 'boost::any'? If not, will have to use a more traditional
// design ('union' anyone?)
// TODO: 'operator==()' for all supported types:
// if (myLuaValue == "bl")
// ...;
// (perhaps also do this for '<', '>' and '!=')
// TODO: Replace those 'lua_Number's with 'double's and add explicit
// support for 'int's and friends. This makes the typical use
// much more natural. I don't think I'll ever compile Lua to use
// integers instead of floating point numbers...
// TODO: After doing the previous TODO, change the tests in
// 'TestLuaStateDoStringMultiRet()' to use integer indices, not
// those ugly floats.
private:
/// Stores the value (and the type) stored in this \c LuaValue.
boost::any value_;
};
/// A constant with the value of \c nil.
const LuaValue Nil;
/// A constant with value of an empty table.
const LuaValueMap EmptyLuaValueMap;
const LuaValue EmptyTable (EmptyLuaValueMap);
} // namespace Diluculum
#endif // _DILUCULUM_LUA_VALUE_HPP_
<commit_msg>Fixed two typos in 'LuaValue' documentation.<commit_after>/******************************************************************************\
* LuaValue.hpp *
* A class that somewhat mimics a Lua value. *
* Leandro Motta Barros *
\******************************************************************************/
#ifndef _DILUCULUM_LUA_VALUE_HPP_
#define _DILUCULUM_LUA_VALUE_HPP_
extern "C"
{
# include <lua.h>
}
#include <map>
#include <stdexcept>
#include <string>
#include <boost/any.hpp>
namespace Diluculum
{
// Just a forward declaration.
class LuaValue;
/** Type mapping from <tt>LuaValue</tt>s to <tt>LuaValue</tt>s. Think of it
* as a C++ approximation of a Lua table.
*/
typedef std::map<LuaValue, LuaValue> LuaValueMap;
/// A generic <tt>LuaValue</tt>-related error.
class LuaValueError: public std::runtime_error
{
public:
/** Constructs a \c LuaValueError object.
* @param what The message associated with the error.
*/
LuaValueError (const char* what)
: std::runtime_error (what)
{ }
};
/** An error in a \c LuaValue that happens when a certain type is expected
* but another one is found.
*/
class TypeMismatchError: public LuaValueError
{
public:
/** Constructs a \c TypeMismatchError object.
* @param expectedType The type that was expected.
* @param foundType The type that was actually found.
*/
TypeMismatchError (const std::string& expectedType,
const std::string& foundType);
/** Destroys a \c TypeMismatchError object.
* @note This was defined just to pretend that the destructor does not
* throw any exception. While this is something that I cannot
* guarantee (at least whit this implementation), I believe this
* not a very dangerous lie.
*/
~TypeMismatchError() throw() { };
/// Returns the type that was expected.
std::string getExpectedType() { return expectedType_; }
/// Returns the type that was actually found.
std::string getFoundType() { return foundType_; }
private:
/// The type that was expected.
std::string expectedType_;
/// The type that was actually found.
std::string foundType_;
};
/// A class that somewhat mimics a Lua value.
class LuaValue
{
public:
/// Constructs a \c LuaValue with a \c nil value.
LuaValue() { };
/// Constructs a \c LuaValue with boolean type and \c b value.
LuaValue (bool b)
: value_(b)
{ }
/// Constructs a \c LuaValue with number type and \c n value.
LuaValue (lua_Number n)
: value_(n)
{ }
/// Constructs a \c LuaValue with string type and \c s value.
LuaValue (const std::string& s)
: value_(s)
{ }
/// Constructs a \c LuaValue with string type and \c s value.
LuaValue (const char* s)
: value_(std::string(s))
{ }
/// Constructs a \c LuaValue with table type and \c t value.
LuaValue (const LuaValueMap& t)
: value_(t)
{ }
/** Returns one of the <tt>LUA_T*</tt> constants from <tt>lua.h</tt>,
* representing the type stored in this \c LuaValue.
*/
int type() const;
/** Returns the type of this \c LuaValue as a string, just like the Lua
* built-in function \c type().
* @return One of the following strings: <tt>"nil"</tt>,
* <tt>"boolean"</tt>, <tt>"number"</tt>, <tt>"string"</tt>,
* <tt>"table"</tt>. If the stored value is different than
* those for some reason, returns an empty string
* (<tt>""</tt>).
*/
std::string typeName() const;
/** Return the value as a number.
* @throw TypeMismatchError If the value is not a number (this is a
* strict check; no type conversion is performed).
*/
lua_Number asNumber() const;
/** Return the value as a string.
* @throw TypeMismatchError If the value is not a string (this is a
* strict check; no type conversion is performed).
*/
std::string asString() const;
/** Return the value as a boolean.
* @throw TypeMismatchError If the value is not a boolean (this is a
* strict check; no type conversion is performed).
*/
bool asBoolean() const;
/** Return the value as a table (\c LuaValueMap).
* @throw TypeMismatchError If the value is not a table (this is a
* strict check; no type conversion is performed).
*/
LuaValueMap asTable() const;
/** "Less than" operator for <tt>LuaValue</tt>s.
* @return The order relationship is quite arbitrary for
* <tt>LuaValue</tt>s, but this has to be defined in order to
* \c LuaValueMap work nicely. Anyway, here are the rules used
* to determine who is less than who:
* - First, \c typeName() is called for both
* <tt>LuaValue</tt>s and they are compared with the usual
* "less than" operator for strings.
* - If both type names are equal, but something different
* than <tt>"nil"</tt> or <tt>"table"</tt>, then the values
* contained in the <tt>LuaValue</tt>s are compared using
* the usual "less than" operator for that type.
* - If both type names are <tt>"nil"</tt>, the function
* returns \c false.
* - If both type names are <tt>"table"</tt>, then the number
* of elements in each table are compared. The shorter table
* is "less than" the larger table.
* - If both tables have the same size, then each entry is
* recursively compared (that is, using the rules described
* here). For each entry, the key is compared first, than
* the value. This is done until finding something "less
* than" the other thing.
* - If no differences are found, \c false is obviously
* returned.
*/
bool operator< (const LuaValue& rhs) const;
/** "Greater than" operator for <tt>LuaValue</tt>s.
* @return The rules for determining who is greater than who are
* similar to the ones described in \c operator<.
*/
bool operator> (const LuaValue& rhs) const;
// TODO: A shortcut for table-like access:
// LuaValue& operator[] (const LuaValue& key) { return ...; }
// TODO: Notice the reference return value above. Is this supported by
// 'boost::any'? If not, will have to use a more traditional
// design ('union' anyone?)
// TODO: 'operator==()' for all supported types:
// if (myLuaValue == "bl")
// ...;
// (perhaps also do this for '<', '>' and '!=')
// TODO: Replace those 'lua_Number's with 'double's and add explicit
// support for 'int's and friends. This makes the typical use
// much more natural. I don't think I'll ever compile Lua to use
// integers instead of floating point numbers...
// TODO: After doing the previous TODO, change the tests in
// 'TestLuaStateDoStringMultiRet()' to use integer indices, not
// those ugly floats.
private:
/// Stores the value (and the type) stored in this \c LuaValue.
boost::any value_;
};
/// A constant with the value of \c nil.
const LuaValue Nil;
/// A constant with value of an empty table.
const LuaValueMap EmptyLuaValueMap;
const LuaValue EmptyTable (EmptyLuaValueMap);
} // namespace Diluculum
#endif // _DILUCULUM_LUA_VALUE_HPP_
<|endoftext|> |
<commit_before>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef SUBGRIDLIST_HH
#define SUBGRIDLIST_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <boost/noncopyable.hpp>
#include <boost/multi_array.hpp>
#include <dune/common/fmatrix.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/stuff/grid/entity.hh>
#include <dune/multiscale/tools/subgrid_io.hh>
#include <dune/subgrid/subgrid.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>
#include <dune/fem/space/lagrange.hh>
//#include <dune/fem/function/adaptivefunction.hh>
#include <dune/fem/operator/2order/lagrangematrixsetup.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/msfem/msfem_grid_specifier.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
//! container for cell problem subgrids
class SubGridList : public boost::noncopyable
{
typedef typename CommonTraits::DiscreteFunctionType HostDiscreteFunctionImp;
typedef MsFEMTraits::SubGridType SubGridImp;
typedef MsFEMTraits::MacroMicroGridSpecifierType MacroMicroGridSpecifierImp;
public:
//! ---------------- typedefs for the HostDiscreteFunctionSpace -----------------------
typedef MacroMicroGridSpecifierImp MacroMicroGridSpecifierType;
typedef HostDiscreteFunctionImp HostDiscreteFunctionType;
//! type of discrete function space
typedef typename HostDiscreteFunctionType::DiscreteFunctionSpaceType HostDiscreteFunctionSpaceType;
//! type of grid partition
typedef typename HostDiscreteFunctionSpaceType::GridPartType HostGridPartType;
//! type of grid
private:
typedef typename HostDiscreteFunctionSpaceType::GridType HostGridType;
typedef typename HostGridType::Traits::LeafIndexSet HostGridLeafIndexSet;
typedef typename HostDiscreteFunctionSpaceType::IteratorType HostGridEntityIteratorType;
typedef typename HostGridEntityIteratorType::Entity HostEntityType;
typedef typename HostEntityType::EntityPointer HostEntityPointerType;
typedef typename HostEntityType::Codim< HostGridType::dimension >::EntityPointer HostNodePointer;
typedef typename HostGridPartType::IntersectionIteratorType HostIntersectionIterator;
typedef typename MsFEMTraits::CoarseEntityType CoarseEntityType;
//! type of (non-discrete )function space
typedef typename HostDiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;
//! type of domain
typedef typename FunctionSpaceType::DomainType DomainType;
public:
typedef std::vector< DomainType > CoarseNodeVectorType;
private:
typedef std::vector< CoarseNodeVectorType > CoarseGridNodeStorageType;
typedef boost::multi_array<bool, 3> EnrichmentMatrixType;
//! @todo this should eventually be changed to the type of the coarse space
typedef typename HostGridPartType::Codim<0>::EntityType::Geometry::LocalCoordinate LocalCoordinateType;
typedef GenericReferenceElements< typename LocalCoordinateType::value_type, LocalCoordinateType::dimension >
CoarseRefElementType;
typedef std::vector<std::vector<HostEntityPointerType>> EntityPointerCollectionType;
public:
//! ---------------- typedefs for the SubgridDiscreteFunctionSpace -----------------------
// ( typedefs for the local grid and the corresponding local ('sub') )discrete space )
//! type of grid
typedef SubGridImp SubGridType;
//! type of grid part
typedef Fem::LeafGridPart< SubGridType > SubGridPartType;
//! type of subgrid discrete function space
typedef Fem::LagrangeDiscreteFunctionSpace< FunctionSpaceType, SubGridPartType, 1/*=POLORDER*/ > SubGridDiscreteFunctionSpace;
//! type of subgrid discrete function
typedef Fem::AdaptiveDiscreteFunction< SubGridDiscreteFunctionSpace > SubGridDiscreteFunction;
SubGridList(MacroMicroGridSpecifierType& specifier, bool silent = true);
~SubGridList();
private:
SubGridType& getSubGrid(int i);
const SubGridType& getSubGrid(int i) const;
public:
const SubGridType& getSubGrid(const CoarseEntityType& entity) const;
SubGridType& getSubGrid(const CoarseEntityType& entity);
int getNumberOfSubGrids() const;
SubGridPartType gridPart(int i);
// given the index of a (codim 0) host grid entity, return the indices of the subgrids that contain the entity
const std::vector< int >& getSubgridIDs_that_contain_entity (int host_enitity_index) const;
// only required for oversampling strategies with constraints (e.g strategy 2 or 3):
const CoarseNodeVectorType& getCoarseNodeVector(int i) const;
/** Get the index of the coarse cell enclosing the barycentre of a given fine cell.
*
* Given a fine cell, this method computes its barycentre. Using a grid run on the coarse
* grid, it checks which (if any) coarse cell contains the barycentre.
*
* @param[in] hostEntity The host entity.
* @param[in,out] lastIterator The macro cell that was found in the last run. This should be set to
* coarseGrid.begin<0>() in the first run. This iterator will then be
* updated and set to the macro element used in this run.
* @param[in] coarseGridLeafIndexSet The index set of the coarse grid.
*
*/
int getEnclosingMacroCellIndex(const HostEntityPointerType& hostEntityPointer);
int getEnclosingMacroCellId(const HostEntityPointerType& hostEntityPointer);
/** Get the mapping from node number to codim 0 host entity.
* @return Returns the map.
* */
const EntityPointerCollectionType& getNodeEntityMap();
private:
typedef std::map<int, std::shared_ptr<SubGridType> > SubGridStorageType;
/**
* \note called in SubGridList constructor only
*/
void enrichment(const HostEntityPointerType& hit,
// const HostEntityPointerType& level_father_it,
const int& father_index, // father_index = index/number of current subgrid
shared_ptr<SubGridType> subGrid,
int& layer);
bool entityPatchInSubgrid(const HostEntityPointerType& hit,
const HostGridPartType& hostGridPart,
shared_ptr<const SubGridType> subGrid,
const EntityPointerCollectionType& entities_sharing_same_node) const;
void identifySubGrids();
void createSubGrids();
void finalizeSubGrids();
const HostDiscreteFunctionSpaceType& hostSpace_;
const HostDiscreteFunctionSpaceType& coarseSpace_;
MacroMicroGridSpecifierType& specifier_;
bool silent_;
SubGridStorageType subGridList_;
CoarseGridNodeStorageType coarse_node_store_;
const HostGridLeafIndexSet& coarseGridLeafIndexSet_;
const HostGridLeafIndexSet& hostGridLeafIndexSet_;
const HostGridPartType& hostGridPart_;
EntityPointerCollectionType entities_sharing_same_node_;
EnrichmentMatrixType enriched_;
std::vector<std::map<int, int> > fineToCoarseMap_;
std::map<int, int> fineToCoarseMapID_;
// given the id of a fine grid element, the vector returns the ids of all subgrids that share that element
std::vector < std::vector< int > > fine_id_to_subgrid_ids_;
};
} //namespace MsFEM {
} //namespace Multiscale {
} //namespace Dune {
#endif // #ifndef SUBGRIDLIST_HH
<commit_msg>Fixed deprecation warning<commit_after>// dune-multiscale
// Copyright Holders: Patrick Henning, Rene Milk
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef SUBGRIDLIST_HH
#define SUBGRIDLIST_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <boost/noncopyable.hpp>
#include <boost/multi_array.hpp>
#include <dune/common/fmatrix.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
#include <dune/stuff/grid/entity.hh>
#include <dune/multiscale/tools/subgrid_io.hh>
#include <dune/subgrid/subgrid.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/gridpart/adaptiveleafgridpart.hh>
#include <dune/fem/space/lagrange.hh>
//#include <dune/fem/function/adaptivefunction.hh>
#include <dune/fem/operator/2order/lagrangematrixsetup.hh>
#include <dune/multiscale/msfem/msfem_traits.hh>
#include <dune/multiscale/msfem/msfem_grid_specifier.hh>
namespace Dune {
namespace Multiscale {
namespace MsFEM {
//! container for cell problem subgrids
class SubGridList : public boost::noncopyable
{
typedef typename CommonTraits::DiscreteFunctionType HostDiscreteFunctionImp;
typedef MsFEMTraits::SubGridType SubGridImp;
typedef MsFEMTraits::MacroMicroGridSpecifierType MacroMicroGridSpecifierImp;
public:
//! ---------------- typedefs for the HostDiscreteFunctionSpace -----------------------
typedef MacroMicroGridSpecifierImp MacroMicroGridSpecifierType;
typedef HostDiscreteFunctionImp HostDiscreteFunctionType;
//! type of discrete function space
typedef typename HostDiscreteFunctionType::DiscreteFunctionSpaceType HostDiscreteFunctionSpaceType;
//! type of grid partition
typedef typename HostDiscreteFunctionSpaceType::GridPartType HostGridPartType;
//! type of grid
private:
typedef typename HostDiscreteFunctionSpaceType::GridType HostGridType;
typedef typename HostGridType::Traits::LeafIndexSet HostGridLeafIndexSet;
typedef typename HostDiscreteFunctionSpaceType::IteratorType HostGridEntityIteratorType;
typedef typename HostGridEntityIteratorType::Entity HostEntityType;
typedef typename HostEntityType::EntityPointer HostEntityPointerType;
typedef typename HostEntityType::Codim< HostGridType::dimension >::EntityPointer HostNodePointer;
typedef typename HostGridPartType::IntersectionIteratorType HostIntersectionIterator;
typedef typename MsFEMTraits::CoarseEntityType CoarseEntityType;
//! type of (non-discrete )function space
typedef typename HostDiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;
//! type of domain
typedef typename FunctionSpaceType::DomainType DomainType;
public:
typedef std::vector< DomainType > CoarseNodeVectorType;
private:
typedef std::vector< CoarseNodeVectorType > CoarseGridNodeStorageType;
typedef boost::multi_array<bool, 3> EnrichmentMatrixType;
//! @todo this should eventually be changed to the type of the coarse space
typedef typename HostGridPartType::Codim<0>::EntityType::Geometry::LocalCoordinate LocalCoordinateType;
typedef ReferenceElements< typename LocalCoordinateType::value_type, LocalCoordinateType::dimension >
CoarseRefElementType;
typedef std::vector<std::vector<HostEntityPointerType>> EntityPointerCollectionType;
public:
//! ---------------- typedefs for the SubgridDiscreteFunctionSpace -----------------------
// ( typedefs for the local grid and the corresponding local ('sub') )discrete space )
//! type of grid
typedef SubGridImp SubGridType;
//! type of grid part
typedef Fem::LeafGridPart< SubGridType > SubGridPartType;
//! type of subgrid discrete function space
typedef Fem::LagrangeDiscreteFunctionSpace< FunctionSpaceType, SubGridPartType, 1/*=POLORDER*/ > SubGridDiscreteFunctionSpace;
//! type of subgrid discrete function
typedef Fem::AdaptiveDiscreteFunction< SubGridDiscreteFunctionSpace > SubGridDiscreteFunction;
SubGridList(MacroMicroGridSpecifierType& specifier, bool silent = true);
~SubGridList();
private:
SubGridType& getSubGrid(int i);
const SubGridType& getSubGrid(int i) const;
public:
const SubGridType& getSubGrid(const CoarseEntityType& entity) const;
SubGridType& getSubGrid(const CoarseEntityType& entity);
int getNumberOfSubGrids() const;
SubGridPartType gridPart(int i);
// given the index of a (codim 0) host grid entity, return the indices of the subgrids that contain the entity
const std::vector< int >& getSubgridIDs_that_contain_entity (int host_enitity_index) const;
// only required for oversampling strategies with constraints (e.g strategy 2 or 3):
const CoarseNodeVectorType& getCoarseNodeVector(int i) const;
/** Get the index of the coarse cell enclosing the barycentre of a given fine cell.
*
* Given a fine cell, this method computes its barycentre. Using a grid run on the coarse
* grid, it checks which (if any) coarse cell contains the barycentre.
*
* @param[in] hostEntity The host entity.
* @param[in,out] lastIterator The macro cell that was found in the last run. This should be set to
* coarseGrid.begin<0>() in the first run. This iterator will then be
* updated and set to the macro element used in this run.
* @param[in] coarseGridLeafIndexSet The index set of the coarse grid.
*
*/
int getEnclosingMacroCellIndex(const HostEntityPointerType& hostEntityPointer);
int getEnclosingMacroCellId(const HostEntityPointerType& hostEntityPointer);
/** Get the mapping from node number to codim 0 host entity.
* @return Returns the map.
* */
const EntityPointerCollectionType& getNodeEntityMap();
private:
typedef std::map<int, std::shared_ptr<SubGridType> > SubGridStorageType;
/**
* \note called in SubGridList constructor only
*/
void enrichment(const HostEntityPointerType& hit,
// const HostEntityPointerType& level_father_it,
const int& father_index, // father_index = index/number of current subgrid
shared_ptr<SubGridType> subGrid,
int& layer);
bool entityPatchInSubgrid(const HostEntityPointerType& hit,
const HostGridPartType& hostGridPart,
shared_ptr<const SubGridType> subGrid,
const EntityPointerCollectionType& entities_sharing_same_node) const;
void identifySubGrids();
void createSubGrids();
void finalizeSubGrids();
const HostDiscreteFunctionSpaceType& hostSpace_;
const HostDiscreteFunctionSpaceType& coarseSpace_;
MacroMicroGridSpecifierType& specifier_;
bool silent_;
SubGridStorageType subGridList_;
CoarseGridNodeStorageType coarse_node_store_;
const HostGridLeafIndexSet& coarseGridLeafIndexSet_;
const HostGridLeafIndexSet& hostGridLeafIndexSet_;
const HostGridPartType& hostGridPart_;
EntityPointerCollectionType entities_sharing_same_node_;
EnrichmentMatrixType enriched_;
std::vector<std::map<int, int> > fineToCoarseMap_;
std::map<int, int> fineToCoarseMapID_;
// given the id of a fine grid element, the vector returns the ids of all subgrids that share that element
std::vector < std::vector< int > > fine_id_to_subgrid_ids_;
};
} //namespace MsFEM {
} //namespace Multiscale {
} //namespace Dune {
#endif // #ifndef SUBGRIDLIST_HH
<|endoftext|> |
<commit_before>/**
* PcapSearch application
* ======================
* This application searches all pcap files in a given directory and all its sub-directories (unless stated otherwise) and outputs how many and which
* packets in those files match a certain pattern given by the user. The pattern is given in Berkeley Packet Filter (BPF) syntax
* (http://biot.com/capstats/bpf.html). For example: if running the application with the following parameters:
* PcapSearch.exe -d C:\ -s "ip net 1.1.1.1" -r C:\report.txt
* The application will search all '.pcap' files in all directories under C drive and try to match packets that matches IP 1.1.1.1. The result will be
* printed to stdout and a more detailed report will be printed to c:\report.txt
* Output example:
* 1 packets found in 'C:\\path\example\Dns.pcap'
* 5 packets found in 'C:\\path\example\bla1\my_pcap2.pcap'
* 7299 packets found in 'C:\\path2\example\example2\big_pcap.pcap'
* 7435 packets found in 'C:\\path3\dir1\dir2\dir3\dir4\another.pcap'
* 435 packets found in 'C:\\path3\dirx\diry\dirz\ok.pcap'
* 4662 packets found in 'C:\\path4\gotit.pcap'
* 7299 packets found in 'C:\\enough.pcap'
*
* There are switches that allows the user to search only in the provided folder (without sub-directories), search user-defined file extensions (sometimes
* pcap files have an extension which is not '.pcap'), and output or not output the detailed report
*
* For more details about modes of operation and parameters please run PcapSearch -h
*/
#include <stdlib.h>
#include <getopt.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include <dirent.h>
#include <vector>
#include <map>
#include <Logger.h>
#include <RawPacket.h>
#include <Packet.h>
#include <PcapFileDevice.h>
using namespace pcpp;
static struct option PcapSearchOptions[] =
{
{"input-dir", required_argument, 0, 'd'},
{"not-include-sub-dir", no_argument, 0, 'n'},
{"search", required_argument, 0, 's'},
{"detailed-report", required_argument, 0, 'r'},
{"set-extensions", required_argument, 0, 'e'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
#define EXIT_WITH_ERROR(reason, ...) do { \
printf("\nError: " reason "\n\n", ## __VA_ARGS__); \
printUsage(); \
exit(1); \
} while(0)
#ifdef WIN32
#define DIR_SEPARATOR "\\"
#else
#define DIR_SEPARATOR "/"
#endif
#define ERROR_STRING_LEN 500
char errorString[ERROR_STRING_LEN];
/**
* Print application usage
*/
void printUsage()
{
printf("\nUsage:\n"
"-------\n"
"PcapPrinter [-h] [-n] [-r file_name] [-e extension_list] -d directory -s search_criteria\n"
"\nOptions:\n\n"
" -d directory : Input directory\n"
" -n : Don't include sub-directories (default is include them)\n"
" -s search_criteria : Criteria to search in Berkeley Packet Filter (BPF) syntax (http://biot.com/capstats/bpf.html) i.e: 'ip net 1.1.1.1'\n"
" -r file_name : Write a detailed search report to a file\n"
" -e extension_list : Set file extensions to search. The default is searching '.pcap' files only.\n"
" extnesions_list should be a comma-separated list of extensions, for example: pcap,net,dmp\n"
" -h : Displays this help message and exits\n");
exit(0);
}
/*
* Returns the extension of a given file name
*/
std::string getExtension(std::string fileName)
{
return fileName.substr(fileName.find_last_of(".") + 1);
}
/**
* Searches all packet in a given pcap file for a certain search criteria. Returns how many packets matched the seatch criteria
*/
int searchPcap(std::string pcapFilePath, std::string searchCriteria, std::ofstream* detailedReportFile)
{
// create the pcap reader
PcapFileReaderDevice reader(pcapFilePath.c_str());
// if the reader fails to open
if (!reader.open())
{
if (detailedReportFile != NULL)
{
// PcapPlusPlus writes the error to the error string variable we set it to write to
// write this error to the report file
(*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl;
(*detailedReportFile) << " ";
std::string errorStr = errorString;
(*detailedReportFile) << errorStr << std::endl;
}
return 0;
}
// set the filter for the file so only packets that match the search criteria will be read
if (!reader.setFilter(searchCriteria))
{
return 0;
}
if (detailedReportFile != NULL)
{
(*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl;
}
int packetCount = 0;
RawPacket rawPacket;
// read packets from the file. Since we already set the filter, only packets that matches the filter will be read
while (reader.getNextPacket(rawPacket))
{
// if a detailed report is required, parse the packet and print it to the report file
if (detailedReportFile != NULL)
{
// parse the packet
Packet parsedPacket(&rawPacket);
// print layer by layer by layer as we want to add a few spaces before each layer
std::vector<std::string> packetLayers;
parsedPacket.printToStringList(packetLayers);
for (std::vector<std::string>::iterator iter = packetLayers.begin(); iter != packetLayers.end(); iter++)
(*detailedReportFile) << "\n " << (*iter);
(*detailedReportFile) << std::endl;
}
// count the packet read
packetCount++;
}
// close the reader file
reader.close();
// finalize the report
if (detailedReportFile != NULL)
{
if (packetCount > 0)
(*detailedReportFile) << "\n";
(*detailedReportFile) << " ----> Found " << packetCount << " packets" << std::endl << std::endl;
}
// return how many packets matched the search criteria
return packetCount;
}
/**
* Searches all pcap files in given directory (and sub-directories if directed by the user) and output how many packets in each file matches a given
* search criteria. This method outputs how many directories were searched, how many files were searched and how many packets were matched
*/
void searchtDirectories(std::string directory, bool includeSubDirectories, std::string searchCriteria, std::ofstream* detailedReportFile,
std::map<std::string, bool> extensionsToSearch,
int& totalDirSearched, int& totalFilesSearched, int& totalPacketsFound)
{
// open the directory
DIR *dir = opendir(directory.c_str());
// dir is null usually when user has no access permissions
if (dir == NULL)
return;
struct dirent *entry = readdir(dir);
std::vector<std::string> pcapList;
// go over all files in this directory
while (entry != NULL)
{
std::string name(entry->d_name);
std::string dirPath = directory + DIR_SEPARATOR + name;
struct stat info;
// get file attributes
if (stat(dirPath.c_str(), &info) != 0)
{
entry = readdir(dir);
continue;
}
// if the file is not a directory
if (!(info.st_mode & S_IFDIR))
{
// check if the file extension matches the requested extensions to search. If it does, put the file name in a list of files
// that should be searched (don't do the search just yet)
if (extensionsToSearch.find(getExtension(name)) != extensionsToSearch.end())
pcapList.push_back(dirPath);
entry = readdir(dir);
continue;
}
// if the file is a '.' or '..' skip it
if (name == "." || name == "..")
{
entry = readdir(dir);
continue;
}
// if we got to here it means the file is actually a directory. If required to search sub-directories, call this method recursively to search
// inside this sub-directory
if (includeSubDirectories)
searchtDirectories(dirPath, true, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound);
// move to the next file
entry = readdir(dir);
}
// close dir
closedir(dir);
totalDirSearched++;
// when we get to here we already covered all sub-directories and collected all the files in this directory that are required for search
// go over each such file and search its packets to find the search criteria
for (std::vector<std::string>::iterator iter = pcapList.begin(); iter != pcapList.end(); iter++)
{
// do the actual search
int packetsFound = searchPcap(*iter, searchCriteria, detailedReportFile);
// add to total matched packets
totalFilesSearched++;
if (packetsFound > 0)
{
printf("%d packets found in '%s'\n", packetsFound, iter->c_str());
totalPacketsFound += packetsFound;
}
}
}
/**
* main method of this utility
*/
int main(int argc, char* argv[])
{
std::string inputDirectory = "";
std::string searchCriteria = "";
bool includeSubDirectories = true;
std::string detailedReportFileName = "";
std::map<std::string, bool> extensionsToSearch;
// the default (unless set otherwise) is to search in '.pcap' extension only
extensionsToSearch["pcap"] = true;
int optionIndex = 0;
char opt = 0;
while((opt = getopt_long (argc, argv, "d:s:r:e:hn", PcapSearchOptions, &optionIndex)) != -1)
{
switch (opt)
{
case 0:
break;
case 'd':
inputDirectory = optarg;
break;
case 'n':
includeSubDirectories = false;
break;
case 's':
searchCriteria = optarg;
break;
case 'r':
detailedReportFileName = optarg;
break;
case 'e':
{
// read the extension list into the map
extensionsToSearch.clear();
std::string extensionsListAsString = std::string(optarg);
std::stringstream stream(extensionsListAsString);
std::string extension;
// break comma-separated string into string list
while(std::getline(stream, extension, ','))
{
// add the extension into the map if it doesn't already exist
if (extensionsToSearch.find(extension) == extensionsToSearch.end())
extensionsToSearch[extension] = true;
}
// verify list is not empty
if (extensionsToSearch.empty())
{
EXIT_WITH_ERROR("Couldn't parse extensions list");
}
break;
}
case 'h':
printUsage();
break;
default:
printUsage();
exit(-1);
}
}
if (inputDirectory == "")
{
EXIT_WITH_ERROR("Input directory was not given");
}
if (searchCriteria == "")
{
EXIT_WITH_ERROR("Search criteria was not given");
}
DIR *dir = opendir(inputDirectory.c_str());
if (dir == NULL)
{
EXIT_WITH_ERROR("Cannot find or open input directory");
}
// verify the search criteria is a valid BPF filter
if (!pcpp::IPcapDevice::verifyFilter(searchCriteria))
{
EXIT_WITH_ERROR("Search criteria isn't valid");
}
// open the detailed report file if requested by the user
std::ofstream* detailedReportFile = NULL;
if (detailedReportFileName != "")
{
detailedReportFile = new std::ofstream();
detailedReportFile->open(detailedReportFileName.c_str());
if (detailedReportFile->fail())
{
EXIT_WITH_ERROR("Couldn't open detailed report file '%s' for writing", detailedReportFileName.c_str());
}
// in cases where the user requests a detailed report, all errors will be written to the report also. That's why we need to save the error messages
// to a variable and write them to the report file later
pcpp::LoggerPP::getInstance().setErrorString(errorString, ERROR_STRING_LEN);
}
printf("Searching...\n");
int totalDirSearched = 0;
int totalFilesSearched = 0;
int totalPacketsFound = 0;
// if input dir contains a directory separator at the end, remove it
std::string dirSep = DIR_SEPARATOR;
if (0 == inputDirectory.compare(inputDirectory.length() - dirSep.length(), dirSep.length(), dirSep))
{
inputDirectory = inputDirectory.substr(0, inputDirectory.size()-1);
}
// the main call - start searching!
searchtDirectories(inputDirectory, includeSubDirectories, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound);
// after search is done, close the report file and delete its instance
printf("\n\nDone! Searched %d files in %d directories, %d packets were matched to search criteria\n", totalFilesSearched, totalDirSearched, totalPacketsFound);
if (detailedReportFile != NULL)
{
if (detailedReportFile->is_open())
detailedReportFile->close();
delete detailedReportFile;
printf("Detailed report written to '%s'\n", detailedReportFileName.c_str());
}
return 0;
}
<commit_msg>Another bugfix in PcapSearch<commit_after>/**
* PcapSearch application
* ======================
* This application searches all pcap files in a given directory and all its sub-directories (unless stated otherwise) and outputs how many and which
* packets in those files match a certain pattern given by the user. The pattern is given in Berkeley Packet Filter (BPF) syntax
* (http://biot.com/capstats/bpf.html). For example: if running the application with the following parameters:
* PcapSearch.exe -d C:\ -s "ip net 1.1.1.1" -r C:\report.txt
* The application will search all '.pcap' files in all directories under C drive and try to match packets that matches IP 1.1.1.1. The result will be
* printed to stdout and a more detailed report will be printed to c:\report.txt
* Output example:
* 1 packets found in 'C:\\path\example\Dns.pcap'
* 5 packets found in 'C:\\path\example\bla1\my_pcap2.pcap'
* 7299 packets found in 'C:\\path2\example\example2\big_pcap.pcap'
* 7435 packets found in 'C:\\path3\dir1\dir2\dir3\dir4\another.pcap'
* 435 packets found in 'C:\\path3\dirx\diry\dirz\ok.pcap'
* 4662 packets found in 'C:\\path4\gotit.pcap'
* 7299 packets found in 'C:\\enough.pcap'
*
* There are switches that allows the user to search only in the provided folder (without sub-directories), search user-defined file extensions (sometimes
* pcap files have an extension which is not '.pcap'), and output or not output the detailed report
*
* For more details about modes of operation and parameters please run PcapSearch -h
*/
#include <stdlib.h>
#include <getopt.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <sys/stat.h>
#include <dirent.h>
#include <vector>
#include <map>
#include <Logger.h>
#include <RawPacket.h>
#include <Packet.h>
#include <PcapFileDevice.h>
using namespace pcpp;
static struct option PcapSearchOptions[] =
{
{"input-dir", required_argument, 0, 'd'},
{"not-include-sub-dir", no_argument, 0, 'n'},
{"search", required_argument, 0, 's'},
{"detailed-report", required_argument, 0, 'r'},
{"set-extensions", required_argument, 0, 'e'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
#define EXIT_WITH_ERROR(reason, ...) do { \
printf("\nError: " reason "\n\n", ## __VA_ARGS__); \
printUsage(); \
exit(1); \
} while(0)
#ifdef WIN32
#define DIR_SEPARATOR "\\"
#else
#define DIR_SEPARATOR "/"
#endif
#define ERROR_STRING_LEN 500
char errorString[ERROR_STRING_LEN];
/**
* Print application usage
*/
void printUsage()
{
printf("\nUsage:\n"
"-------\n"
"PcapPrinter [-h] [-n] [-r file_name] [-e extension_list] -d directory -s search_criteria\n"
"\nOptions:\n\n"
" -d directory : Input directory\n"
" -n : Don't include sub-directories (default is include them)\n"
" -s search_criteria : Criteria to search in Berkeley Packet Filter (BPF) syntax (http://biot.com/capstats/bpf.html) i.e: 'ip net 1.1.1.1'\n"
" -r file_name : Write a detailed search report to a file\n"
" -e extension_list : Set file extensions to search. The default is searching '.pcap' files only.\n"
" extnesions_list should be a comma-separated list of extensions, for example: pcap,net,dmp\n"
" -h : Displays this help message and exits\n");
exit(0);
}
/*
* Returns the extension of a given file name
*/
std::string getExtension(std::string fileName)
{
return fileName.substr(fileName.find_last_of(".") + 1);
}
/**
* Searches all packet in a given pcap file for a certain search criteria. Returns how many packets matched the seatch criteria
*/
int searchPcap(std::string pcapFilePath, std::string searchCriteria, std::ofstream* detailedReportFile)
{
// create the pcap reader
PcapFileReaderDevice reader(pcapFilePath.c_str());
// if the reader fails to open
if (!reader.open())
{
if (detailedReportFile != NULL)
{
// PcapPlusPlus writes the error to the error string variable we set it to write to
// write this error to the report file
(*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl;
(*detailedReportFile) << " ";
std::string errorStr = errorString;
(*detailedReportFile) << errorStr << std::endl;
}
return 0;
}
// set the filter for the file so only packets that match the search criteria will be read
if (!reader.setFilter(searchCriteria))
{
return 0;
}
if (detailedReportFile != NULL)
{
(*detailedReportFile) << "File '" << pcapFilePath << "':" << std::endl;
}
int packetCount = 0;
RawPacket rawPacket;
// read packets from the file. Since we already set the filter, only packets that matches the filter will be read
while (reader.getNextPacket(rawPacket))
{
// if a detailed report is required, parse the packet and print it to the report file
if (detailedReportFile != NULL)
{
// parse the packet
Packet parsedPacket(&rawPacket);
// print layer by layer by layer as we want to add a few spaces before each layer
std::vector<std::string> packetLayers;
parsedPacket.printToStringList(packetLayers);
for (std::vector<std::string>::iterator iter = packetLayers.begin(); iter != packetLayers.end(); iter++)
(*detailedReportFile) << "\n " << (*iter);
(*detailedReportFile) << std::endl;
}
// count the packet read
packetCount++;
}
// close the reader file
reader.close();
// finalize the report
if (detailedReportFile != NULL)
{
if (packetCount > 0)
(*detailedReportFile) << "\n";
(*detailedReportFile) << " ----> Found " << packetCount << " packets" << std::endl << std::endl;
}
// return how many packets matched the search criteria
return packetCount;
}
/**
* Searches all pcap files in given directory (and sub-directories if directed by the user) and output how many packets in each file matches a given
* search criteria. This method outputs how many directories were searched, how many files were searched and how many packets were matched
*/
void searchtDirectories(std::string directory, bool includeSubDirectories, std::string searchCriteria, std::ofstream* detailedReportFile,
std::map<std::string, bool> extensionsToSearch,
int& totalDirSearched, int& totalFilesSearched, int& totalPacketsFound)
{
// open the directory
DIR *dir = opendir(directory.c_str());
// dir is null usually when user has no access permissions
if (dir == NULL)
return;
struct dirent *entry = readdir(dir);
std::vector<std::string> pcapList;
// go over all files in this directory
while (entry != NULL)
{
std::string name(entry->d_name);
// construct directory full path
std::string dirPath = directory;
std::string dirSep = DIR_SEPARATOR;
if (0 != directory.compare(directory.length() - dirSep.length(), dirSep.length(), dirSep)) // directory doesn't contain separator in the end
dirPath += DIR_SEPARATOR;
dirPath += name;
struct stat info;
// get file attributes
if (stat(dirPath.c_str(), &info) != 0)
{
entry = readdir(dir);
continue;
}
// if the file is not a directory
if (!(info.st_mode & S_IFDIR))
{
// check if the file extension matches the requested extensions to search. If it does, put the file name in a list of files
// that should be searched (don't do the search just yet)
if (extensionsToSearch.find(getExtension(name)) != extensionsToSearch.end())
pcapList.push_back(dirPath);
entry = readdir(dir);
continue;
}
// if the file is a '.' or '..' skip it
if (name == "." || name == "..")
{
entry = readdir(dir);
continue;
}
// if we got to here it means the file is actually a directory. If required to search sub-directories, call this method recursively to search
// inside this sub-directory
if (includeSubDirectories)
searchtDirectories(dirPath, true, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound);
// move to the next file
entry = readdir(dir);
}
// close dir
closedir(dir);
totalDirSearched++;
// when we get to here we already covered all sub-directories and collected all the files in this directory that are required for search
// go over each such file and search its packets to find the search criteria
for (std::vector<std::string>::iterator iter = pcapList.begin(); iter != pcapList.end(); iter++)
{
// do the actual search
int packetsFound = searchPcap(*iter, searchCriteria, detailedReportFile);
// add to total matched packets
totalFilesSearched++;
if (packetsFound > 0)
{
printf("%d packets found in '%s'\n", packetsFound, iter->c_str());
totalPacketsFound += packetsFound;
}
}
}
/**
* main method of this utility
*/
int main(int argc, char* argv[])
{
std::string inputDirectory = "";
std::string searchCriteria = "";
bool includeSubDirectories = true;
std::string detailedReportFileName = "";
std::map<std::string, bool> extensionsToSearch;
// the default (unless set otherwise) is to search in '.pcap' extension only
extensionsToSearch["pcap"] = true;
int optionIndex = 0;
char opt = 0;
while((opt = getopt_long (argc, argv, "d:s:r:e:hn", PcapSearchOptions, &optionIndex)) != -1)
{
switch (opt)
{
case 0:
break;
case 'd':
inputDirectory = optarg;
break;
case 'n':
includeSubDirectories = false;
break;
case 's':
searchCriteria = optarg;
break;
case 'r':
detailedReportFileName = optarg;
break;
case 'e':
{
// read the extension list into the map
extensionsToSearch.clear();
std::string extensionsListAsString = std::string(optarg);
std::stringstream stream(extensionsListAsString);
std::string extension;
// break comma-separated string into string list
while(std::getline(stream, extension, ','))
{
// add the extension into the map if it doesn't already exist
if (extensionsToSearch.find(extension) == extensionsToSearch.end())
extensionsToSearch[extension] = true;
}
// verify list is not empty
if (extensionsToSearch.empty())
{
EXIT_WITH_ERROR("Couldn't parse extensions list");
}
break;
}
case 'h':
printUsage();
break;
default:
printUsage();
exit(-1);
}
}
if (inputDirectory == "")
{
EXIT_WITH_ERROR("Input directory was not given");
}
if (searchCriteria == "")
{
EXIT_WITH_ERROR("Search criteria was not given");
}
DIR *dir = opendir(inputDirectory.c_str());
if (dir == NULL)
{
EXIT_WITH_ERROR("Cannot find or open input directory");
}
// verify the search criteria is a valid BPF filter
if (!pcpp::IPcapDevice::verifyFilter(searchCriteria))
{
EXIT_WITH_ERROR("Search criteria isn't valid");
}
// open the detailed report file if requested by the user
std::ofstream* detailedReportFile = NULL;
if (detailedReportFileName != "")
{
detailedReportFile = new std::ofstream();
detailedReportFile->open(detailedReportFileName.c_str());
if (detailedReportFile->fail())
{
EXIT_WITH_ERROR("Couldn't open detailed report file '%s' for writing", detailedReportFileName.c_str());
}
// in cases where the user requests a detailed report, all errors will be written to the report also. That's why we need to save the error messages
// to a variable and write them to the report file later
pcpp::LoggerPP::getInstance().setErrorString(errorString, ERROR_STRING_LEN);
}
printf("Searching...\n");
int totalDirSearched = 0;
int totalFilesSearched = 0;
int totalPacketsFound = 0;
// the main call - start searching!
searchtDirectories(inputDirectory, includeSubDirectories, searchCriteria, detailedReportFile, extensionsToSearch, totalDirSearched, totalFilesSearched, totalPacketsFound);
// after search is done, close the report file and delete its instance
printf("\n\nDone! Searched %d files in %d directories, %d packets were matched to search criteria\n", totalFilesSearched, totalDirSearched, totalPacketsFound);
if (detailedReportFile != NULL)
{
if (detailedReportFile->is_open())
detailedReportFile->close();
delete detailedReportFile;
printf("Detailed report written to '%s'\n", detailedReportFileName.c_str());
}
return 0;
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief DS3231 RTC のテスト
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include<cstring>
#include "G13/system.hpp"
#include "G13/port.hpp"
#include "common/uart_io.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/iica_io.hpp"
#include "common/delay.hpp"
#include "common/itimer.hpp"
#include "common/command.hpp"
#include "common/time.h"
#include "chip/DS3231.hpp"
namespace {
typedef device::iica_io<device::IICA0> IICA;
IICA iica0_;
chip::DS3231<IICA> rtc_(iica0_);
typedef utils::fifo<128> buffer;
device::uart_io<device::SAU00, device::SAU01, buffer, buffer> uart0_;
device::itimer<uint8_t> itm_;
utils::command<64> command_;
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ reinterpret_cast<void*>(uart0_.send_task),
/* 14 */ reinterpret_cast<void*>(uart0_.recv_task),
/* 15 */ reinterpret_cast<void*>(uart0_.error_task),
/* 16 */ nullptr,
/* 17 */ nullptr,
/* 18 */ nullptr,
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart0_.putch(ch);
}
void sci_puts(const char* str)
{
uart0_.puts(str);
}
char sci_getch(void)
{
return uart0_.getch();
}
uint16_t sci_length()
{
return uart0_.recv_length();
}
};
static const char* wday_[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char* mon_[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
namespace {
time_t get_time_()
{
time_t t = 0;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(iica0_.get_last_error());
}
return t;
}
void disp_time_(time_t t) {
struct tm *m = gmtime(&t);
utils::format("%s %s %d %02d:%02d:%02d %4d\n")
% wday_[m->tm_wday]
% mon_[m->tm_mon]
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec)
% static_cast<uint32_t>(m->tm_year + 1900);
}
bool check_key_word_(uint8_t idx, const char* key)
{
char buff[12];
if(command_.get_word(idx, sizeof(buff), buff)) {
if(std::strcmp(buff, key) == 0) {
return true;
}
}
return false;
}
const char* get_dec_(const char* p, char tmch, int& value) {
int v = 0;
char ch;
while((ch = *p) != 0) {
++p;
if(ch == tmch) {
break;
} else if(ch >= '0' && ch <= '9') {
v *= 10;
v += ch - '0';
} else {
return nullptr;
}
}
value = v;
return p;
}
void set_time_date_()
{
time_t t = get_time_();
if(t == 0) return;
struct tm *m = gmtime(&t);
bool err = false;
if(command_.get_words() == 3) {
char buff[12];
if(command_.get_word(1, sizeof(buff), buff)) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, '/', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && i == 3) {
if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900;
if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1;
if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2];
} else {
err = true;
}
}
if(command_.get_word(2, sizeof(buff), buff)) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, ':', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) {
if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0];
if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1];
if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2];
else m->tm_sec = 0;
} else {
err = true;
}
}
}
if(err) {
sci_puts("Can't analize Time/Date input.\n");
return;
}
time_t tt = mktime(m);
if(!rtc_.set_time(tt)) {
sci_puts("Stall RTC write...\n");
}
}
}
int main(int argc, char* argv[])
{
using namespace device;
PM4.B3 = 0; // output
// itimer の開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART0 の開始
{
uint8_t intr_level = 1;
uart0_.start(115200, intr_level);
}
// IICA(I2C) の開始
{
uint8_t intr_level = 0;
if(!iica0_.start(IICA::speed::fast, intr_level)) {
// if(!iica0_.start(IICA::speed::standard, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(iica0_.get_last_error());
}
}
sci_puts("Start RL78/G13 DS3231(I2C-RTC) sample\n");
// DS3231(RTC) の開始
if(!rtc_.start()) {
utils::format("Stall RTC start (%d)\n") % static_cast<uint32_t>(iica0_.get_last_error());
}
command_.set_prompt("# ");
uint8_t cnt = 0;
while(1) {
itm_.sync();
if(cnt >= 20) {
cnt = 0;
}
if(cnt < 10) P4.B3 = 1;
else P4.B3 = 0;
++cnt;
// コマンド入力と、コマンド解析
if(command_.service()) {
uint8_t cmdn = command_.get_words();
if(cmdn >= 1) {
if(check_key_word_(0, "date")) {
if(cmdn == 1) {
time_t t = get_time_();
if(t != 0) {
disp_time_(t);
}
} else {
set_time_date_();
}
} else if(check_key_word_(0, "help")) {
sci_puts("date\n");
sci_puts("date yyyy/mm/dd hh:mm[:ss]\n");
} else {
char buff[12];
if(command_.get_word(0, sizeof(buff), buff)) {
sci_puts("Command error: ");
sci_puts(buff);
sci_putch('\n');
}
}
}
}
}
}
<commit_msg>change UART1<commit_after>//=====================================================================//
/*! @file
@brief DS3231 RTC のテスト
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include<cstring>
#include "G13/system.hpp"
#include "G13/port.hpp"
#include "common/uart_io.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/iica_io.hpp"
#include "common/delay.hpp"
#include "common/itimer.hpp"
#include "common/command.hpp"
#include "common/time.h"
#include "chip/DS3231.hpp"
// どれか一つだけ有効にする。
// #define UART0
#define UART1
namespace {
typedef device::iica_io<device::IICA0> IICA;
IICA iica0_;
chip::DS3231<IICA> rtc_(iica0_);
typedef utils::fifo<128> buffer;
#ifdef UART0
// UART0 の定義(SAU0、SAU1)
device::uart_io<device::SAU00, device::SAU01, buffer, buffer> uart_;
#endif
#ifdef UART1
// UART1 の定義(SAU2、SAU3)
device::uart_io<device::SAU02, device::SAU03, buffer, buffer> uart_;
#endif
device::itimer<uint8_t> itm_;
utils::command<64> command_;
}
const void* ivec_[] __attribute__ ((section (".ivec"))) = {
/* 0 */ nullptr,
/* 1 */ nullptr,
/* 2 */ nullptr,
/* 3 */ nullptr,
/* 4 */ nullptr,
/* 5 */ nullptr,
/* 6 */ nullptr,
/* 7 */ nullptr,
/* 8 */ nullptr,
/* 9 */ nullptr,
/* 10 */ nullptr,
/* 11 */ nullptr,
/* 12 */ nullptr,
/* 13 */ reinterpret_cast<void*>(uart_.send_task), // UART0-TX
/* 14 */ reinterpret_cast<void*>(uart_.recv_task), // UART0-RX
/* 15 */ reinterpret_cast<void*>(uart_.error_task), // UART0-ER
/* 16 */ reinterpret_cast<void*>(uart_.send_task), // UART1-TX
/* 17 */ reinterpret_cast<void*>(uart_.recv_task), // UART1-RX
/* 18 */ reinterpret_cast<void*>(uart_.error_task), // UART1-ER
/* 19 */ nullptr,
/* 20 */ nullptr,
/* 21 */ nullptr,
/* 22 */ nullptr,
/* 23 */ nullptr,
/* 24 */ nullptr,
/* 25 */ nullptr,
/* 26 */ reinterpret_cast<void*>(itm_.task),
};
extern "C" {
void sci_putch(char ch)
{
uart_.putch(ch);
}
void sci_puts(const char* str)
{
uart_.puts(str);
}
char sci_getch(void)
{
return uart_.getch();
}
uint16_t sci_length()
{
return uart_.recv_length();
}
};
static const char* wday_[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
};
static const char* mon_[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
namespace {
time_t get_time_()
{
time_t t = 0;
if(!rtc_.get_time(t)) {
utils::format("Stall RTC read (%d)\n") % static_cast<uint32_t>(iica0_.get_last_error());
}
return t;
}
void disp_time_(time_t t) {
struct tm *m = gmtime(&t);
utils::format("%s %s %d %02d:%02d:%02d %4d\n")
% wday_[m->tm_wday]
% mon_[m->tm_mon]
% static_cast<uint32_t>(m->tm_mday)
% static_cast<uint32_t>(m->tm_hour)
% static_cast<uint32_t>(m->tm_min)
% static_cast<uint32_t>(m->tm_sec)
% static_cast<uint32_t>(m->tm_year + 1900);
}
bool check_key_word_(uint8_t idx, const char* key)
{
char buff[12];
if(command_.get_word(idx, sizeof(buff), buff)) {
if(std::strcmp(buff, key) == 0) {
return true;
}
}
return false;
}
const char* get_dec_(const char* p, char tmch, int& value) {
int v = 0;
char ch;
while((ch = *p) != 0) {
++p;
if(ch == tmch) {
break;
} else if(ch >= '0' && ch <= '9') {
v *= 10;
v += ch - '0';
} else {
return nullptr;
}
}
value = v;
return p;
}
void set_time_date_()
{
time_t t = get_time_();
if(t == 0) return;
struct tm *m = gmtime(&t);
bool err = false;
if(command_.get_words() == 3) {
char buff[12];
if(command_.get_word(1, sizeof(buff), buff)) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, '/', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && i == 3) {
if(vs[0] >= 1900 && vs[0] < 2100) m->tm_year = vs[0] - 1900;
if(vs[1] >= 1 && vs[1] <= 12) m->tm_mon = vs[1] - 1;
if(vs[2] >= 1 && vs[2] <= 31) m->tm_mday = vs[2];
} else {
err = true;
}
}
if(command_.get_word(2, sizeof(buff), buff)) {
const char* p = buff;
int vs[3];
uint8_t i;
for(i = 0; i < 3; ++i) {
p = get_dec_(p, ':', vs[i]);
if(p == nullptr) {
break;
}
}
if(p != nullptr && p[0] == 0 && (i == 2 || i == 3)) {
if(vs[0] >= 0 && vs[0] < 24) m->tm_hour = vs[0];
if(vs[1] >= 0 && vs[1] < 60) m->tm_min = vs[1];
if(i == 3 && vs[2] >= 0 && vs[2] < 60) m->tm_sec = vs[2];
else m->tm_sec = 0;
} else {
err = true;
}
}
}
if(err) {
sci_puts("Can't analize Time/Date input.\n");
return;
}
time_t tt = mktime(m);
if(!rtc_.set_time(tt)) {
sci_puts("Stall RTC write...\n");
}
}
}
int main(int argc, char* argv[])
{
using namespace device;
PM4.B3 = 0; // output
// itimer の開始
{
uint8_t intr_level = 1;
itm_.start(60, intr_level);
}
// UART の開始
{
uint8_t intr_level = 1;
uart_.start(115200, intr_level);
}
// IICA(I2C) の開始
{
uint8_t intr_level = 0;
if(!iica0_.start(IICA::speed::fast, intr_level)) {
// if(!iica0_.start(IICA::speed::standard, intr_level)) {
utils::format("IICA start error (%d)\n") % static_cast<uint32_t>(iica0_.get_last_error());
}
}
sci_puts("Start RL78/G13 DS3231(I2C-RTC) sample\n");
// DS3231(RTC) の開始
if(!rtc_.start()) {
utils::format("Stall RTC start (%d)\n") % static_cast<uint32_t>(iica0_.get_last_error());
}
command_.set_prompt("# ");
uint8_t cnt = 0;
while(1) {
itm_.sync();
if(cnt >= 20) {
cnt = 0;
}
if(cnt < 10) P4.B3 = 1;
else P4.B3 = 0;
++cnt;
// コマンド入力と、コマンド解析
if(command_.service()) {
uint8_t cmdn = command_.get_words();
if(cmdn >= 1) {
if(check_key_word_(0, "date")) {
if(cmdn == 1) {
time_t t = get_time_();
if(t != 0) {
disp_time_(t);
}
} else {
set_time_date_();
}
} else if(check_key_word_(0, "help")) {
sci_puts("date\n");
sci_puts("date yyyy/mm/dd hh:mm[:ss]\n");
} else {
char buff[12];
if(command_.get_word(0, sizeof(buff), buff)) {
sci_puts("Command error: ");
sci_puts(buff);
sci_putch('\n');
}
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
线段树
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lson root<<1
#define rson root<<1|1
const int maxn = (65535<<1) + 3;
static struct {
int left;
int right;
int lbd;
int rbd;
int cover;
int mask;
int flag;
} tree[maxn*4+11];
void build(int root, int left, int right) {
tree[root].left = left;
tree[root].right = right;
tree[root].cover = 0;
tree[root].mask = 0;
tree[root].flag = 1;
tree[root].lbd = left-1;
tree[root].rbd = right+1;
if (left >= right) {
return;
}
int mid = (left + right) >> 1;
build(lson, left, mid);
build(rson, mid+1, right);
}
#define line(x)\
if (c == 1) {\
x = 1;\
} else if (c == -1) {\
x = 0;\
} else if (c == 2) {\
x = not x;\
}\
void push_down(int root) {
int c = tree[root].mask;
if (c) {
tree[lson].cover = tree[root].cover;
tree[rson].cover = tree[root].cover;
tree[lson].mask = c;
tree[rson].mask = c;
if (tree[root].cover) {
tree[lson].lbd = tree[lson].right;
tree[lson].rbd = tree[lson].left;
tree[rson].lbd = tree[rson].right;
tree[rson].rbd = tree[rson].left;
} else {
tree[lson].lbd = -1;
tree[lson].rbd = -1;
tree[rson].lbd = -1;
tree[rson].rbd = -1;
}
tree[lson].flag = 1;
tree[rson].flag = 1;
tree[root].mask = 0;
}
}
void update(int root) {
if (tree[lson].cover == tree[rson].cover and tree[lson].flag and tree[rson].flag) {
tree[root].cover = tree[lson].cover;
tree[root].flag = 1;
} else {
tree[root].flag = 0;
}
tree[root].lbd = tree[lson].lbd;
if (tree[rson].lbd != -1 and tree[lson].lbd == tree[lson].right) {
tree[root].lbd = tree[rson].lbd;
}
tree[root].rbd = tree[rson].rbd;
if (tree[lson].rbd != -1 and tree[rson].rbd == tree[rson].left) {
tree[root].rbd = tree[lson].rbd;
}
}
void insert(int root, int left, int right, int c) {
tree[root].flag = 0;
if (left <= tree[root].left and tree[root].right <= right) {
line(tree[root].cover);
tree[root].mask = c;
tree[root].flag = 1;
if (tree[root].cover) {
tree[root].lbd = tree[root].right;
tree[root].rbd = tree[root].left;
} else {
tree[root].lbd = -1;
tree[root].rbd = -1;
}
return;
} else if (left > tree[root].right or right < tree[root].left) {
return;
}
push_down(root);
insert(lson, left, right, c);
insert(rson, left, right, c);
update(root);
}
void (*f[256]) (int root, int left, int right);
void U(int root, int left, int right) {
insert(root, left, right, 1);
}
void I(int root, int left, int right) {
insert(root, -1, left-1, -1);
insert(root, right+1, maxn+1, -1);
}
void D(int root, int left, int right) {
insert(root, left, right, -1);
}
void C(int root, int left, int right) {
insert(root, -1, left-1, -1);
insert(root, right+1, maxn+1, -1);
insert(root, left, right, 2);
}
void S(int root, int left, int right) {
insert(root, left, right, 2);
}
void query(int root) {
if (tree[root].left == tree[root].right) {
return;
}
query(lson);
l = tree[lson].rbd;
query(rson);
}
void solve() {
f['U'] = U, f['I'] = I, f['D'] = D, f['C'] = C, f['S'] = S;
char order, l, r;
int a, b;
build(1, -1, maxn+1);
while (scanf("%c %c%d,%d%c\n", &order, &l, &a, &b, &r) != EOF) {
//printf("%c %c%d,%d%c\n", order, l, a,b,r);
f[(int)order](1, (a<<1)+(l=='('), (b<<1)-(r==')'));
}
query(1);
}
int main() {
solve();
return 0;
}
<commit_msg> update<commit_after>/*
线段树
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lson root<<1
#define rson root<<1|1
const int maxn = (65535<<1) + 3;
static struct {
int left;
int right;
int lbd;
int rbd;
int cover;
int mask;
} tree[maxn*4+11];
void build(int root, int left, int right) {
tree[root].left = left;
tree[root].right = right;
tree[root].cover = 0;
tree[root].mask = 0;
tree[root].lbd = left-1;
tree[root].rbd = right+1;
if (left >= right) {
return;
}
int mid = (left + right) >> 1;
build(lson, left, mid);
build(rson, mid+1, right);
}
#define line(x)\
if (c == 1) {\
x = 1;\
} else if (c == -1) {\
x = 0;\
} else if (c == 2) {\
x = not x;\
}\
void push_down(int root) {
int c = tree[root].mask;
if (c) {
tree[lson].cover = tree[root].cover;
tree[rson].cover = tree[root].cover;
tree[lson].mask = c;
tree[rson].mask = c;
if (tree[root].cover) {
tree[lson].lbd = tree[lson].right;
tree[lson].rbd = tree[lson].left;
tree[rson].lbd = tree[rson].right;
tree[rson].rbd = tree[rson].left;
} else {
tree[lson].lbd = tree[lson].left - 1;
tree[lson].rbd = tree[lson].right + 1;
tree[rson].lbd = tree[rson].left - 1;
tree[rson].rbd = tree[rson].right + 1;
}
tree[root].mask = 0;
}
}
void update(int root) {
tree[root].lbd = tree[lson].lbd;
if (tree[lson].lbd == tree[lson].right) {
tree[root].lbd = tree[rson].lbd;
}
tree[root].rbd = tree[rson].rbd;
if (tree[rson].rbd == tree[rson].left) {
tree[root].rbd = tree[lson].rbd;
}
}
void insert(int root, int left, int right, int c) {
if (left <= tree[root].left and tree[root].right <= right) {
line(tree[root].cover);
tree[root].mask = c;
if (tree[root].cover) {
tree[root].lbd = tree[root].right;
tree[root].rbd = tree[root].left;
} else {
tree[root].lbd = tree[root].left - 1;
tree[root].rbd = tree[root].right + 1;
}
return;
} else if (left > tree[root].right or right < tree[root].left) {
return;
}
push_down(root);
insert(lson, left, right, c);
insert(rson, left, right, c);
update(root);
}
void (*f[256]) (int root, int left, int right);
void U(int root, int left, int right) {
insert(root, left, right, 1);
}
void I(int root, int left, int right) {
insert(root, -1, left-1, -1);
insert(root, right+1, maxn+1, -1);
}
void D(int root, int left, int right) {
insert(root, left, right, -1);
}
void C(int root, int left, int right) {
insert(root, -1, left-1, -1);
insert(root, right+1, maxn+1, -1);
insert(root, left, right, 2);
}
void S(int root, int left, int right) {
insert(root, left, right, 2);
}
void query(int root, int left, int right) {
if (tree[root].left == tree[root].right) {
return;
}
if (tree[root].)
query(lson);
if (tree[lson].rbd <= tree[rson].lbd) {
printf("(%d, %d) ", tree[lson].rbd, tree[rson].lbd);
}
query(rson);
}
void solve() {
f['U'] = U, f['I'] = I, f['D'] = D, f['C'] = C, f['S'] = S;
char order, l, r;
int a, b;
build(1, -1, maxn+1);
while (scanf("%c %c%d,%d%c\n", &order, &l, &a, &b, &r) != EOF) {
//printf("%c %c%d,%d%c\n", order, l, a,b,r);
f[(int)order](1, (a<<1)+(l=='('), (b<<1)-(r==')'));
}
query(1, -1, maxn+1);
}
int main() {
solve();
return 0;
}
<|endoftext|> |
<commit_before>/*
* File: Signal.hpp
* Author: Barath Kannan
* Signal/Slots C++14 implementation
* Created on May 10, 2016, 5:57 PM
*/
#ifndef SIGNAL_HPP
#define SIGNAL_HPP
#include <functional>
#include <map>
#include <unordered_map>
#include <atomic>
#include <mutex>
#include <shared_mutex>
#include <condition_variable>
#include <thread>
#include <utility>
#include <type_traits>
#include "BSignals/details/SafeQueue.hpp"
#include "BSignals/details/WheeledThreadPool.h"
#include "BSignals/details/Semaphore.h"
//These connection schemes determine how message emission to a connection occurs
// SYNCHRONOUS CONNECTION:
// Emission occurs synchronously.
// When emit returns, all connected signals have returned.
// This method is preferred when connected functions have short execution
// time, quick emission is required, and/or when it is necessary to know
// that the function has returned before proceeding.
// ASYNCHRONOUS CONNECTION:
// Emission occurs asynchronously. A detached thread is spawned on emission.
// When emit returns, the thread has been spawned. The thread automatically
// destructs when the connected function returns.
// This method is recommended when connected functions have long execution
// time and are independent.
// ASYNCHRONOUS ENQUEUED CONNECTION:
// Emission occurs asynchronously.
// On connection a dedicated thread is spawned to wait for new messages.
// Emitted parameters are bound to the mapped function and enqueued on the
// waiting thread. These messages are then processed synchronously in the
// spawned thread.
// This method is recommended when quick emission is required, connected
// functions have longer execution time, and/or connected functions need to
// be processed in order of arrival (FIFO).
// THREAD POOLED:
// Emission occurs asynchronously.
// On connection, if it is the first thread pooled function by any signal,
// the thread pool is initialized with 8 threads, all listening for queued
// emissions. The number of threads in the pool is not currently run-time
// configurable but may be in the future.
// Emitted parameters are bound to the mapped function and enqueued on the
// one of the waiting threads - acquisition of a thread is wait-free and
// lock free. These messages are then processed when the relevant queue
// is consumed by the mapped thread pool.
// This method is recommended when quick emission is required, connected
// functions have longer execution time, and order is irrelevant. This method
//
namespace BSignals{
enum class SignalConnectionScheme{
SYNCHRONOUS,
ASYNCHRONOUS,
ASYNCHRONOUS_ENQUEUE,
THREAD_POOLED
};
template <typename... Args>
class Signal {
public:
Signal() = default;
Signal(bool enforceThreadSafety)
: enableEmissionGuard{enforceThreadSafety} {}
Signal(uint32_t maxAsyncThreads)
: sem{maxAsyncThreads} {}
Signal(bool enforceThreadSafety, uint32_t maxAsyncThreads)
: enableEmissionGuard{enforceThreadSafety}, sem{maxAsyncThreads} {}
~Signal(){
disconnectAllSlots();
}
template<typename F, typename C>
int connectMemberSlot(const SignalConnectionScheme &scheme, F&& function, C&& instance) const {
//type check assertions
static_assert(std::is_member_function_pointer<F>::value, "function is not a member function");
static_assert(std::is_object<std::remove_reference<C>>::value, "instance is not a class object");
//Construct a bound function from the function pointer and object
auto boundFunc = objectBind(function, instance);
return connectSlot(scheme, boundFunc);
}
int connectSlot(const SignalConnectionScheme &scheme, std::function<void(Args...)> slot) const {
std::unique_lock<std::shared_timed_mutex> lock(signalLock);
uint32_t id = currentId.fetch_add(1);
auto *slotMap = getSlotMap(scheme);
slotMap->emplace(id, slot);
if (scheme == SignalConnectionScheme::ASYNCHRONOUS_ENQUEUE){
asyncQueues[id];
asyncQueueThreads.emplace(id, std::thread(&Signal::queueListener, this, id));
}
else if (scheme == SignalConnectionScheme::THREAD_POOLED){
BSignals::details::WheeledThreadPool::startup();
}
return (int)id;
}
void disconnectSlot(const uint32_t &id) const {
std::unique_lock<std::shared_timed_mutex> lock(signalLock);
std::map<uint32_t, std::function<void(Args...)>> *slotMap = findSlotMapWithId(id);
if (slotMap == nullptr) return;
if (slotMap == &asynchronousEnqueueSlots){
asyncQueues[id].stop();
asyncQueueThreads[id].join();
asyncQueueThreads.erase(id);
asyncQueues.erase(id);
}
slotMap->erase(id);
}
void disconnectAllSlots() const {
std::unique_lock<std::shared_timed_mutex> lock(signalLock);
for (auto &q : asyncQueues){
q.second.stop();
}
for (auto &t : asyncQueueThreads){
t.second.join();
}
asyncQueueThreads.clear();
asyncQueues.clear();
synchronousSlots.clear();
asynchronousSlots.clear();
asynchronousEnqueueSlots.clear();
threadPooledSlots.clear();
}
void emitSignal(const Args &... p) const {
return enableEmissionGuard ? emitSignalThreadSafe(p...) : emitSignalUnsafe(p...);
}
private:
inline void emitSignalUnsafe(const Args &... p) const {
for (auto const &slot : synchronousSlots){
runSynchronous(slot.second, p...);
}
for (auto const &slot : asynchronousSlots){
runAsynchronous(slot.second, p...);
}
for (auto const &slot : asynchronousEnqueueSlots){
runAsynchronousEnqueued(slot.first, slot.second, p...);
}
for (auto const &slot : threadPooledSlots){
runThreadPooled(slot.second, p...);
}
}
inline void emitSignalThreadSafe(const Args &... p) const {
std::shared_lock<std::shared_timed_mutex> lock(signalLock);
emitSignalUnsafe(p...);
}
inline void runThreadPooled(const std::function<void(Args...)> &function, const Args &... p) const {
BSignals::details::WheeledThreadPool::run([&function, p...](){function(p...);});
}
inline void runAsynchronous(const std::function<void(Args...)> &function, const Args &... p) const {
sem.acquire();
std::thread slotThread([this, function, p...](){
function(p...);
sem.release();
});
slotThread.detach();
}
inline void runAsynchronousEnqueued(uint32_t asyncQueueId, const std::function<void(Args...)> &function, const Args &... p) const{
//bind the function arguments to the function using a lambda and store
//the newly bound function. This changes the function signature in the
//resultant map, there are no longer any parameters in the bound function
asyncQueues[asyncQueueId].enqueue([&function, p...](){function(p...);});
}
inline void runSynchronous(const std::function<void(Args...)> &function, const Args &... p) const{
function(p...);
}
//Reference to instance
template<typename F, typename I>
std::function<void(Args...)> objectBind(F&& function, I&& instance) const {
return[=, &instance](Args... args){
(instance.*function)(args...);
};
}
//Pointer to instance
template<typename F, typename I>
std::function<void(Args...)> objectBind(F&& function, I* instance) const {
return objectBind(function, *instance);
}
std::map<uint32_t, std::function<void(Args...)>> *getSlotMap(const SignalConnectionScheme &scheme) const{
switch(scheme){
case (SignalConnectionScheme::ASYNCHRONOUS):
return &asynchronousSlots;
case (SignalConnectionScheme::ASYNCHRONOUS_ENQUEUE):
return &asynchronousEnqueueSlots;
case (SignalConnectionScheme::THREAD_POOLED):
return &threadPooledSlots;
default:
case (SignalConnectionScheme::SYNCHRONOUS):
return &synchronousSlots;
}
}
std::map<uint32_t, std::function<void(Args...)>> *findSlotMapWithId(const uint32_t &id) const{
if (synchronousSlots.count(id))
return &synchronousSlots;
if (asynchronousSlots.count(id))
return &asynchronousSlots;
if (asynchronousEnqueueSlots.count(id))
return &asynchronousEnqueueSlots;
if (threadPooledSlots.count(id))
return &threadPooledSlots;
return nullptr;
}
void queueListener(const uint32_t &id) const{
auto &q = asyncQueues[id];
while (!q.isStopped()){
auto func = q.dequeue();
if (q.isStopped())
break;
func();
}
}
//shared mutex for thread safety
//emit acquires shared lock, connect/disconnect acquires unique lock
mutable std::shared_timed_mutex signalLock;
//atomically incremented slotId
mutable std::atomic<uint32_t> currentId {0};
//Async Emit Semaphore
mutable BSignals::details::Semaphore sem {128};
//emissionGuard determines if it is necessary to guard emission with a shared mutex
//this is only required if connection/disconnection could be interleaved with emission
const bool enableEmissionGuard {false};
//Async Enqueue Queues and Threads
mutable std::map<uint32_t, BSignals::details::SafeQueue<std::function<void()>>> asyncQueues;
mutable std::map<uint32_t, std::thread> asyncQueueThreads;
//Slot Maps
mutable std::map<uint32_t, std::function<void(Args...)>> synchronousSlots;
mutable std::map<uint32_t, std::function<void(Args...)>> asynchronousSlots;
mutable std::map<uint32_t, std::function<void(Args...)>> asynchronousEnqueueSlots;
mutable std::map<uint32_t, std::function<void(Args...)>> threadPooledSlots;
};
} /* namespace BSignals */
#endif /* SIGNAL_HPP */
<commit_msg>thread pooled documentation clean up<commit_after>/*
* File: Signal.hpp
* Author: Barath Kannan
* Signal/Slots C++14 implementation
* Created on May 10, 2016, 5:57 PM
*/
#ifndef SIGNAL_HPP
#define SIGNAL_HPP
#include <functional>
#include <map>
#include <unordered_map>
#include <atomic>
#include <mutex>
#include <shared_mutex>
#include <condition_variable>
#include <thread>
#include <utility>
#include <type_traits>
#include "BSignals/details/SafeQueue.hpp"
#include "BSignals/details/WheeledThreadPool.h"
#include "BSignals/details/Semaphore.h"
//These connection schemes determine how message emission to a connection occurs
// SYNCHRONOUS CONNECTION:
// Emission occurs synchronously.
// When emit returns, all connected signals have returned.
// This method is preferred when connected functions have short execution
// time, quick emission is required, and/or when it is necessary to know
// that the function has returned before proceeding.
// ASYNCHRONOUS CONNECTION:
// Emission occurs asynchronously. A detached thread is spawned on emission.
// When emit returns, the thread has been spawned. The thread automatically
// destructs when the connected function returns.
// This method is recommended when connected functions have long execution
// time and are independent.
// ASYNCHRONOUS ENQUEUED CONNECTION:
// Emission occurs asynchronously.
// On connection a dedicated thread is spawned to wait for new messages.
// Emitted parameters are bound to the mapped function and enqueued on the
// waiting thread. These messages are then processed synchronously in the
// spawned thread.
// This method is recommended when connected functions have longer execution
// time, the overhead of creating/destroying a thread for each slot would be
// unperformant, and/or connected functions need to be processed in order
// of arrival (FIFO).
// THREAD POOLED:
// Emission occurs asynchronously.
// On connection, if it is the first thread pooled function by any signal,
// the thread pool is initialized with 8 threads, all listening for queued
// emissions. The number of threads in the pool is not currently run-time
// configurable but may be in the future.
// Emitted parameters are bound to the mapped function and enqueued on the
// one of the waiting threads - acquisition of a thread is wait-free and
// lock free. These messages are then processed when the relevant queue
// is consumed by the mapped thread pool.
// This method is recommended when connected functions have longer execution
// time, the overhead of creating/destroying a thread for each slot would be
// unperformant, the overhead of a waiting thread for each slot is
// unnecessary, and/or connected functions do NOT need to be processed in
// order of arrival.
//
namespace BSignals{
enum class SignalConnectionScheme{
SYNCHRONOUS,
ASYNCHRONOUS,
ASYNCHRONOUS_ENQUEUE,
THREAD_POOLED
};
template <typename... Args>
class Signal {
public:
Signal() = default;
Signal(bool enforceThreadSafety)
: enableEmissionGuard{enforceThreadSafety} {}
Signal(uint32_t maxAsyncThreads)
: sem{maxAsyncThreads} {}
Signal(bool enforceThreadSafety, uint32_t maxAsyncThreads)
: enableEmissionGuard{enforceThreadSafety}, sem{maxAsyncThreads} {}
~Signal(){
disconnectAllSlots();
}
template<typename F, typename C>
int connectMemberSlot(const SignalConnectionScheme &scheme, F&& function, C&& instance) const {
//type check assertions
static_assert(std::is_member_function_pointer<F>::value, "function is not a member function");
static_assert(std::is_object<std::remove_reference<C>>::value, "instance is not a class object");
//Construct a bound function from the function pointer and object
auto boundFunc = objectBind(function, instance);
return connectSlot(scheme, boundFunc);
}
int connectSlot(const SignalConnectionScheme &scheme, std::function<void(Args...)> slot) const {
std::unique_lock<std::shared_timed_mutex> lock(signalLock);
uint32_t id = currentId.fetch_add(1);
auto *slotMap = getSlotMap(scheme);
slotMap->emplace(id, slot);
if (scheme == SignalConnectionScheme::ASYNCHRONOUS_ENQUEUE){
asyncQueues[id];
asyncQueueThreads.emplace(id, std::thread(&Signal::queueListener, this, id));
}
else if (scheme == SignalConnectionScheme::THREAD_POOLED){
BSignals::details::WheeledThreadPool::startup();
}
return (int)id;
}
void disconnectSlot(const uint32_t &id) const {
std::unique_lock<std::shared_timed_mutex> lock(signalLock);
std::map<uint32_t, std::function<void(Args...)>> *slotMap = findSlotMapWithId(id);
if (slotMap == nullptr) return;
if (slotMap == &asynchronousEnqueueSlots){
asyncQueues[id].stop();
asyncQueueThreads[id].join();
asyncQueueThreads.erase(id);
asyncQueues.erase(id);
}
slotMap->erase(id);
}
void disconnectAllSlots() const {
std::unique_lock<std::shared_timed_mutex> lock(signalLock);
for (auto &q : asyncQueues){
q.second.stop();
}
for (auto &t : asyncQueueThreads){
t.second.join();
}
asyncQueueThreads.clear();
asyncQueues.clear();
synchronousSlots.clear();
asynchronousSlots.clear();
asynchronousEnqueueSlots.clear();
threadPooledSlots.clear();
}
void emitSignal(const Args &... p) const {
return enableEmissionGuard ? emitSignalThreadSafe(p...) : emitSignalUnsafe(p...);
}
private:
inline void emitSignalUnsafe(const Args &... p) const {
for (auto const &slot : synchronousSlots){
runSynchronous(slot.second, p...);
}
for (auto const &slot : asynchronousSlots){
runAsynchronous(slot.second, p...);
}
for (auto const &slot : asynchronousEnqueueSlots){
runAsynchronousEnqueued(slot.first, slot.second, p...);
}
for (auto const &slot : threadPooledSlots){
runThreadPooled(slot.second, p...);
}
}
inline void emitSignalThreadSafe(const Args &... p) const {
std::shared_lock<std::shared_timed_mutex> lock(signalLock);
emitSignalUnsafe(p...);
}
inline void runThreadPooled(const std::function<void(Args...)> &function, const Args &... p) const {
BSignals::details::WheeledThreadPool::run([&function, p...](){function(p...);});
}
inline void runAsynchronous(const std::function<void(Args...)> &function, const Args &... p) const {
sem.acquire();
std::thread slotThread([this, function, p...](){
function(p...);
sem.release();
});
slotThread.detach();
}
inline void runAsynchronousEnqueued(uint32_t asyncQueueId, const std::function<void(Args...)> &function, const Args &... p) const{
//bind the function arguments to the function using a lambda and store
//the newly bound function. This changes the function signature in the
//resultant map, there are no longer any parameters in the bound function
asyncQueues[asyncQueueId].enqueue([&function, p...](){function(p...);});
}
inline void runSynchronous(const std::function<void(Args...)> &function, const Args &... p) const{
function(p...);
}
//Reference to instance
template<typename F, typename I>
std::function<void(Args...)> objectBind(F&& function, I&& instance) const {
return[=, &instance](Args... args){
(instance.*function)(args...);
};
}
//Pointer to instance
template<typename F, typename I>
std::function<void(Args...)> objectBind(F&& function, I* instance) const {
return objectBind(function, *instance);
}
std::map<uint32_t, std::function<void(Args...)>> *getSlotMap(const SignalConnectionScheme &scheme) const{
switch(scheme){
case (SignalConnectionScheme::ASYNCHRONOUS):
return &asynchronousSlots;
case (SignalConnectionScheme::ASYNCHRONOUS_ENQUEUE):
return &asynchronousEnqueueSlots;
case (SignalConnectionScheme::THREAD_POOLED):
return &threadPooledSlots;
default:
case (SignalConnectionScheme::SYNCHRONOUS):
return &synchronousSlots;
}
}
std::map<uint32_t, std::function<void(Args...)>> *findSlotMapWithId(const uint32_t &id) const{
if (synchronousSlots.count(id))
return &synchronousSlots;
if (asynchronousSlots.count(id))
return &asynchronousSlots;
if (asynchronousEnqueueSlots.count(id))
return &asynchronousEnqueueSlots;
if (threadPooledSlots.count(id))
return &threadPooledSlots;
return nullptr;
}
void queueListener(const uint32_t &id) const{
auto &q = asyncQueues[id];
while (!q.isStopped()){
auto func = q.dequeue();
if (q.isStopped())
break;
func();
}
}
//shared mutex for thread safety
//emit acquires shared lock, connect/disconnect acquires unique lock
mutable std::shared_timed_mutex signalLock;
//atomically incremented slotId
mutable std::atomic<uint32_t> currentId {0};
//Async Emit Semaphore
mutable BSignals::details::Semaphore sem {128};
//emissionGuard determines if it is necessary to guard emission with a shared mutex
//this is only required if connection/disconnection could be interleaved with emission
const bool enableEmissionGuard {false};
//Async Enqueue Queues and Threads
mutable std::map<uint32_t, BSignals::details::SafeQueue<std::function<void()>>> asyncQueues;
mutable std::map<uint32_t, std::thread> asyncQueueThreads;
//Slot Maps
mutable std::map<uint32_t, std::function<void(Args...)>> synchronousSlots;
mutable std::map<uint32_t, std::function<void(Args...)>> asynchronousSlots;
mutable std::map<uint32_t, std::function<void(Args...)>> asynchronousEnqueueSlots;
mutable std::map<uint32_t, std::function<void(Args...)>> threadPooledSlots;
};
} /* namespace BSignals */
#endif /* SIGNAL_HPP */
<|endoftext|> |
<commit_before>#include <iostream>
#include <chrono>
#include <vector>
#include <numeric>
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/compiler/tf2tensorrt/trt_convert_api.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/public/session.h"
using tensorflow::Status;
using tensorflow::string;
using tensorflow::Tensor;
using tensorflow::Flag;
#define TFTRT_ENSURE_OK(x) \
do { \
Status s = x; \
if (!s.ok()) { \
std::cerr << __FILE__ << ":" << __LINE__ << " " << s.error_message() \
<< std::endl; \
return 1; \
} \
} while (0)
// Get the name of the GPU.
const string getDeviceName(std::unique_ptr<tensorflow::Session>& session) {
string device_name = "";
std::vector<tensorflow::DeviceAttributes> devices;
Status status = session->ListDevices(&devices);
if (!status.ok()) { return device_name; }
for (const auto& d : devices) {
if (d.device_type() == "GPU" || d.device_type() == "gpu") {
device_name = d.name();
}
}
return device_name;
}
// Move from the host to the device with `device_name`.
Status moveToDevice(const string& device_name,
Tensor& tensor_host,
Tensor* tensor_device) {
// Create identity graph
tensorflow::Scope root = tensorflow::Scope::NewRootScope();
auto x = tensorflow::ops::Placeholder(root, tensor_host.dtype());
auto y = tensorflow::ops::Identity(root, x);
tensorflow::GraphDef graphDef;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graphDef));
// Create session with identity graph
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions())
);
TF_RETURN_IF_ERROR(session->Create(graphDef));
// Configure to return output on device
tensorflow::Session::CallableHandle handle;
tensorflow::CallableOptions opts;
opts.add_feed("Placeholder:0");
opts.add_fetch("Identity:0");
opts.mutable_fetch_devices()->insert({"Identity:0", device_name});
opts.set_fetch_skip_sync(true);
TF_RETURN_IF_ERROR(session->MakeCallable(opts, &handle));
// Execute graph
std::vector<Tensor> tensors_device;
Status status = session->RunCallable(handle, {tensor_host}, &tensors_device, nullptr);
*tensor_device = tensors_device.front();
session->ReleaseCallable(handle);
return status;
}
// Returns info for nodes listed in the signature definition.
std::vector<tensorflow::TensorInfo> getNodeInfo(
const google::protobuf::Map<std::string, tensorflow::TensorInfo>& signature) {
std::vector<tensorflow::TensorInfo> info;
for (const auto& item : signature) {
info.push_back(item.second);
}
return info;
}
// Load the `SavedModel` located at `model_dir`.
Status loadModel(const std::string& model_dir,
tensorflow::SavedModelBundle* bundle,
std::vector<tensorflow::TensorInfo>* input_info,
std::vector<tensorflow::TensorInfo>* output_info) {
tensorflow::RunOptions run_options;
tensorflow::SessionOptions sess_options;
sess_options.config.mutable_gpu_options()->force_gpu_compatible();
TF_RETURN_IF_ERROR(tensorflow::LoadSavedModel(sess_options, run_options, model_dir, {"serve"}, bundle));
// Get input and output names
auto signature_map = bundle->GetSignatures();
const tensorflow::SignatureDef& signature = signature_map["serving_default"];
*input_info = getNodeInfo(signature.inputs());
*output_info = getNodeInfo(signature.outputs());
return Status::OK();
}
// Create arbitrary inputs matching `input_info` and load them on the device.
Status setupInputs(const string& device_name,
int32_t batch_size,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<Tensor>* inputs) {
std::vector<Tensor> inputs_device;
for (const auto& info : input_info) {
auto shape = info.tensor_shape();
shape.mutable_dim(0)->set_size(batch_size);
Tensor input_host(info.dtype(), shape);
Tensor input_device;
TF_RETURN_IF_ERROR(moveToDevice(device_name, input_host, &input_device));
inputs_device.push_back(input_device);
}
*inputs = inputs_device;
return Status::OK();
}
// Configure a `CallableHandle` that feeds from and fetches to a device.
Status setupCallable(std::unique_ptr<tensorflow::Session>& session,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<tensorflow::TensorInfo>& output_info,
const string& device_name,
tensorflow::Session::CallableHandle* handle) {
tensorflow::CallableOptions opts;
for (const auto& info : input_info) {
const string& name = info.name();
opts.add_feed(name);
opts.mutable_feed_devices()->insert({name, device_name});
}
for (const auto& info : output_info) {
const string& name = info.name();
opts.add_fetch(name);
opts.mutable_fetch_devices()->insert({name, device_name});
}
opts.set_fetch_skip_sync(true);
return session->MakeCallable(opts, handle);
}
int main(int argc, char* argv[]) {
// Parse arguments
string model_path = "/path/to/model/";
int32_t batch_size = 64;
int32_t warmup_iters = 50;
int32_t eval_iters = 1000;
std::vector<Flag> flag_list = {
Flag("model_path", &model_path, "graph to be executed"),
Flag("batch_size", &batch_size, "batch size to use for inference"),
Flag("warmup_iters", &warmup_iters, "number of warmup iterations to run"),
Flag("eval_iters", &eval_iters, "number of timed iterations to run"),
};
string usage = tensorflow::Flags::Usage(argv[0], flag_list);
const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
// We need to call this to set up global state for TensorFlow.
tensorflow::port::InitMain(argv[0], &argc, &argv);
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
return -1;
}
// Setup session
tensorflow::SavedModelBundle bundle;
std::vector<tensorflow::TensorInfo> input_info;
std::vector<tensorflow::TensorInfo> output_info;
TFTRT_ENSURE_OK(loadModel(model_path, &bundle, &input_info, &output_info));
// Create inputs and move to device
const string device_name = getDeviceName(bundle.session);
std::vector<Tensor> inputs_device;
TFTRT_ENSURE_OK(setupInputs(device_name, batch_size, input_info, &inputs_device));
// Configure to feed and fetch from device
tensorflow::Session::CallableHandle handle;
TFTRT_ENSURE_OK(setupCallable(bundle.session, input_info, output_info, device_name, &handle));
// Run benchmarking
std::vector<Tensor> outputs;
std::vector<double> infer_time;
std::chrono::steady_clock::time_point eval_start_time;
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point end_time;
for (int i = 0; i < warmup_iters + eval_iters; i++) {
if (i == warmup_iters) {
LOG(INFO) << "Warmup done";
eval_start_time = std::chrono::steady_clock::now();
}
start_time = std::chrono::steady_clock::now();
Status status = bundle.session->RunCallable(handle, inputs_device, &outputs, nullptr);
end_time = std::chrono::steady_clock::now();
TFTRT_ENSURE_OK(status);
double duration = (end_time - start_time).count() / 1e6;
infer_time.push_back(duration);
}
TFTRT_ENSURE_OK(bundle.session->ReleaseCallable(handle));
// Print results
std::sort(infer_time.begin() + warmup_iters, infer_time.end());
double total_compute_time = std::accumulate(infer_time.begin() + warmup_iters, infer_time.end(), 0.0);
double total_wall_time = (end_time - eval_start_time).count() / 1e6;
int32_t m = eval_iters / 2;
LOG(INFO) << "Total wall time (s): " << total_wall_time / 1e3;
LOG(INFO) << "Total GPU compute time (s): " << total_compute_time / 1e3;
LOG(INFO) << "Mean GPU compute time (ms): " << total_compute_time / eval_iters;
LOG(INFO) << "Median GPU compute time (ms): " << (eval_iters % 2 ? infer_time[m]
: (infer_time[m - 1] + infer_time[m]) / 2);
LOG(INFO) << "Throughput (ims/s): " << 1e3 * eval_iters * batch_size / total_compute_time;
LOG(INFO) << "First inference latency (ms): " << infer_time.front();
return 0;
}<commit_msg>Address PR comments<commit_after>#include <iostream>
#include <chrono>
#include <vector>
#include <numeric>
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/compiler/tf2tensorrt/trt_convert_api.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/public/session.h"
using tensorflow::Status;
using tensorflow::string;
using tensorflow::Tensor;
using tensorflow::Flag;
#define TFTRT_ENSURE_OK(x) \
do { \
Status s = x; \
if (!s.ok()) { \
std::cerr << __FILE__ << ":" << __LINE__ << " " << s.error_message() \
<< std::endl; \
return 1; \
} \
} while (0)
// Get the name of the GPU.
const string getDeviceName(std::unique_ptr<tensorflow::Session>& session) {
string device_name = "";
std::vector<tensorflow::DeviceAttributes> devices;
Status status = session->ListDevices(&devices);
if (!status.ok()) { return device_name; }
for (const auto& d : devices) {
if (d.device_type() == "GPU" || d.device_type() == "gpu") {
device_name = d.name();
}
}
return device_name;
}
// Move from the host to the device with `device_name`.
Status moveToDevice(const string& device_name,
Tensor& tensor_host,
Tensor* tensor_device) {
// Create identity graph
tensorflow::Scope root = tensorflow::Scope::NewRootScope();
auto x = tensorflow::ops::Placeholder(root, tensor_host.dtype());
auto y = tensorflow::ops::Identity(root, x);
tensorflow::GraphDef graphDef;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graphDef));
// Create session with identity graph
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions())
);
TF_RETURN_IF_ERROR(session->Create(graphDef));
// Configure to return output on device
tensorflow::Session::CallableHandle handle;
tensorflow::CallableOptions opts;
opts.add_feed("Placeholder:0");
opts.add_fetch("Identity:0");
opts.mutable_fetch_devices()->insert({"Identity:0", device_name});
opts.set_fetch_skip_sync(true);
TF_RETURN_IF_ERROR(session->MakeCallable(opts, &handle));
// Execute graph
std::vector<Tensor> tensors_device;
Status status = session->RunCallable(handle, {tensor_host}, &tensors_device, nullptr);
*tensor_device = tensors_device.front();
session->ReleaseCallable(handle);
return status;
}
// Returns info for nodes listed in the signature definition.
std::vector<tensorflow::TensorInfo> getNodeInfo(
const google::protobuf::Map<string, tensorflow::TensorInfo>& signature) {
std::vector<tensorflow::TensorInfo> info;
for (const auto& item : signature) {
info.push_back(item.second);
}
return info;
}
// Load the `SavedModel` located at `model_dir`.
Status loadModel(const string& model_dir,
const string& signature_key,
tensorflow::SavedModelBundle* bundle,
std::vector<tensorflow::TensorInfo>* input_info,
std::vector<tensorflow::TensorInfo>* output_info) {
tensorflow::RunOptions run_options;
tensorflow::SessionOptions sess_options;
sess_options.config.mutable_gpu_options()->force_gpu_compatible();
TF_RETURN_IF_ERROR(tensorflow::LoadSavedModel(sess_options, run_options, model_dir, {"serve"}, bundle));
// Get input and output names
auto signature_map = bundle->GetSignatures();
const tensorflow::SignatureDef& signature = signature_map[signature_key];
*input_info = getNodeInfo(signature.inputs());
*output_info = getNodeInfo(signature.outputs());
return Status::OK();
}
// Create arbitrary inputs matching `input_info` and load them on the device.
Status setupInputs(const string& device_name,
int32_t batch_size,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<Tensor>* inputs) {
std::vector<Tensor> inputs_device;
for (const auto& info : input_info) {
auto shape = info.tensor_shape();
shape.mutable_dim(0)->set_size(batch_size);
Tensor input_host(info.dtype(), shape);
Tensor input_device;
TF_RETURN_IF_ERROR(moveToDevice(device_name, input_host, &input_device));
inputs_device.push_back(input_device);
}
*inputs = inputs_device;
return Status::OK();
}
// Configure a `CallableHandle` that feeds from and fetches to a device.
Status setupCallable(std::unique_ptr<tensorflow::Session>& session,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<tensorflow::TensorInfo>& output_info,
const string& device_name,
tensorflow::Session::CallableHandle* handle) {
tensorflow::CallableOptions opts;
for (const auto& info : input_info) {
const string& name = info.name();
opts.add_feed(name);
opts.mutable_feed_devices()->insert({name, device_name});
}
for (const auto& info : output_info) {
const string& name = info.name();
opts.add_fetch(name);
opts.mutable_fetch_devices()->insert({name, device_name});
}
opts.set_fetch_skip_sync(true);
return session->MakeCallable(opts, handle);
}
int main(int argc, char* argv[]) {
// Parse arguments
string model_path = "/path/to/model/";
string signature_key = "serving_default";
int32_t batch_size = 64;
int32_t warmup_iters = 50;
int32_t eval_iters = 1000;
std::vector<Flag> flag_list = {
Flag("model_path", &model_path, "graph to be executed"),
Flag("signature_key", &signature_key, "the serving signature to use"),
Flag("batch_size", &batch_size, "batch size to use for inference"),
Flag("warmup_iters", &warmup_iters, "number of warmup iterations to run"),
Flag("eval_iters", &eval_iters, "number of timed iterations to run"),
};
string usage = tensorflow::Flags::Usage(argv[0], flag_list);
const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
// We need to call this to set up global state for TensorFlow.
tensorflow::port::InitMain(argv[0], &argc, &argv);
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
return -1;
}
// Setup session
tensorflow::SavedModelBundle bundle;
std::vector<tensorflow::TensorInfo> input_info;
std::vector<tensorflow::TensorInfo> output_info;
TFTRT_ENSURE_OK(loadModel(model_path, signature_key, &bundle, &input_info, &output_info));
// Create inputs and move to device
const string device_name = getDeviceName(bundle.session);
std::vector<Tensor> inputs_device;
TFTRT_ENSURE_OK(setupInputs(device_name, batch_size, input_info, &inputs_device));
// Configure to feed and fetch from device
tensorflow::Session::CallableHandle handle;
TFTRT_ENSURE_OK(setupCallable(bundle.session, input_info, output_info, device_name, &handle));
// Run benchmarking
std::vector<Tensor> outputs;
std::vector<double> infer_time;
std::chrono::steady_clock::time_point eval_start_time;
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point end_time;
for (int i = 0; i < warmup_iters + eval_iters; i++) {
if (i == warmup_iters) {
LOG(INFO) << "Warmup done";
eval_start_time = std::chrono::steady_clock::now();
}
start_time = std::chrono::steady_clock::now();
Status status = bundle.session->RunCallable(handle, inputs_device, &outputs, nullptr);
end_time = std::chrono::steady_clock::now();
TFTRT_ENSURE_OK(status);
double duration = (end_time - start_time).count() / 1e6;
infer_time.push_back(duration);
}
TFTRT_ENSURE_OK(bundle.session->ReleaseCallable(handle));
// Print results
std::sort(infer_time.begin() + warmup_iters, infer_time.end());
double total_compute_time = std::accumulate(infer_time.begin() + warmup_iters, infer_time.end(), 0.0);
double total_wall_time = (end_time - eval_start_time).count() / 1e6;
int32_t m = warmup_iters + eval_iters / 2;
LOG(INFO) << "Total wall time (s): " << total_wall_time / 1e3;
LOG(INFO) << "Total GPU compute time (s): " << total_compute_time / 1e3;
LOG(INFO) << "Mean GPU compute time (ms): " << total_compute_time / eval_iters;
LOG(INFO) << "Median GPU compute time (ms): " << (eval_iters % 2 ? infer_time[m]
: (infer_time[m - 1] + infer_time[m]) / 2);
// Note: Throughput using GPU inference time, rather than wall time
LOG(INFO) << "Throughput (samples/s): " << 1e3 * eval_iters * batch_size / total_compute_time;
LOG(INFO) << "First inference latency (ms): " << infer_time.front();
return 0;
}<|endoftext|> |
<commit_before>#ifndef RESULT_ALL_HPP_
#define RESULT_ALL_HPP_
#include "result_benchmark.hpp"
#include "traits.hpp"
#include "types.hpp"
#include <sstream>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
namespace gearshifft {
template<int T_NumberRuns, // runs per benchmark including warmup
int T_NumberWarmups,
int T_NumberValues // recorded values per run
>
class ResultAll {
public:
using ResultBenchmarkT = ResultBenchmark<T_NumberRuns, T_NumberValues>;
void add(const ResultBenchmarkT& result) {
results_.push_back(result);
}
/*
* sort order: fftkind -> dimkind -> dim -> nx*ny*nz
*/
void sort() {
std::stable_sort(
results_.begin( ), results_.end( ),
[ ]( const ResultBenchmarkT& lhs, const ResultBenchmarkT& rhs )
{
if(lhs.getPrecision()==rhs.getPrecision())
if(lhs.isInplace()==rhs.isInplace())
if(lhs.isComplex()==rhs.isComplex())
return lhs.getDimKind()<rhs.getDimKind() ||
lhs.getDimKind()==rhs.getDimKind() &&
(
lhs.getDim()<rhs.getDim() ||
lhs.getDim()==rhs.getDim() &&
lhs.getExtentsTotal()<rhs.getExtentsTotal()
);
else
return lhs.isComplex();
else
return lhs.isInplace();
else
return false;
});
}
void print(std::ostream& stream,
const std::string& apptitle,
const std::string& dev_infos,
double timerContextCreate,
double timerContextDestroy) {
std::stringstream ss;
ss << "; " << dev_infos << "\n"
<< "; \"Time_ContextCreate [ms]\", " << timerContextCreate << "\n"
<< "; \"Time_ContextDestroy [ms]\", " << timerContextDestroy << "\n";
ss << apptitle
<< ", RunsPerBenchmark="<<T_NumberRuns
<< "\n";
for(auto& result : results_) {
int nruns = T_NumberRuns;
std::string inplace = result.isInplace() ? "Inplace" : "Outplace";
std::string complex = result.isComplex() ? "Complex" : "Real";
ss << std::setfill('-') << std::setw(70) <<"-"<< "\n";
ss << inplace
<< ", "<<complex
<< ", "<<result.getPrecision()
<< ", Dim="<<result.getDim()
<< ", Kind="<<result.getDimKindStr()<<" ("<<result.getDimKind()<<")"
<< ", Ext="<<result.getExtents()
<< "\n";
if(result.hasError()) {
ss << " Error at run="<<result.getErrorRun()
<< ": "<<result.getError()
<< "\n";
nruns = result.getErrorRun()+1;
}
ss << std::setfill('-') << std::setw(70) <<"-"<< "\n";
ss << std::setfill(' ');
double sum;
for(int ival=0; ival<T_NumberValues; ++ival) {
sum = 0.0;
for(int run=T_NumberWarmups; run<nruns; ++run) {
result.setRun(run);
sum += result.getValue(ival);
}
ss << std::setw(28)
<< static_cast<RecordType>(ival)
<< ": " << std::setw(16) << sum/nruns
<< " [avg]"
<< "\n";
}
}
stream << ss.str() << std::endl; // "\n" with flush
}
/**
* Store results in csv file.
* If verbosity flag is set, then std::cout receives result view.
*/
void saveCSV(const std::string& fname,
const std::string& apptitle,
const std::string& meta_information,
double timerContextCreate,
double timerContextDestroy) {
std::ofstream fs;
const char sep=',';
fs.open(fname, std::ofstream::out);
fs.precision(11);
fs << "; " << meta_information <<"\n"
<< "; \"Time_ContextCreate [ms]\", " << timerContextCreate << "\n"
<< "; \"Time_ContextDestroy [ms]\", " << timerContextDestroy << "\n";
// header
fs << "\"library\",\"inplace\",\"complex\",\"precision\",\"dim\",\"kind\""
<< ",\"nx\",\"ny\",\"nz\",\"run\",\"id\",\"success\"";
for(auto ival=0; ival<T_NumberValues; ++ival) {
fs << sep << '"' << static_cast<RecordType>(ival) << '"';
}
fs << "\n";
// data
for(auto& result : results_) {
std::string inplace = result.isInplace() ? "Inplace" : "Outplace";
std::string complex = result.isComplex() ? "Complex" : "Real";
for(auto run=0; run<T_NumberRuns; ++run) {
result.setRun(run);
fs << "\"" << apptitle << "\"" << sep
<< "\"" << inplace << "\"" << sep
<< "\"" << complex << "\"" << sep
<< "\"" << result.getPrecision() << "\"" << sep
<< result.getDim() << sep
<< "\"" << result.getDimKindStr() << "\"" << sep
<< result.getExtents()[0] << sep
<< result.getExtents()[1] << sep
<< result.getExtents()[2] << sep
<< run << sep
<< result.getID();
// was run successfull?
if(result.hasError() && result.getErrorRun()<=run) {
if(result.getErrorRun()==run)
fs << sep << "\"" <<result.getError() << "\"";
else
fs << sep << "\"Skipped\""; // subsequent runs did not run
} else {
if(run<T_NumberWarmups)
fs << sep << "\"" << "Warmup" << "\"";
else
fs << sep << "\"" << "Success" << "\"";
}
// measured time and size values
for(auto ival=0; ival<T_NumberValues; ++ival) {
fs << sep << result.getValue(ival);
}
fs << "\n";
} // run
} // result
fs.close();
} // write
private:
std::vector< ResultBenchmarkT > results_;
};
}
#endif
<commit_msg>fixes wrong avg computation in verbose mode.<commit_after>#ifndef RESULT_ALL_HPP_
#define RESULT_ALL_HPP_
#include "result_benchmark.hpp"
#include "traits.hpp"
#include "types.hpp"
#include <sstream>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
namespace gearshifft {
template<int T_NumberRuns, // runs per benchmark including warmup
int T_NumberWarmups,
int T_NumberValues // recorded values per run
>
class ResultAll {
public:
using ResultBenchmarkT = ResultBenchmark<T_NumberRuns, T_NumberValues>;
void add(const ResultBenchmarkT& result) {
results_.push_back(result);
}
/*
* sort order: fftkind -> dimkind -> dim -> nx*ny*nz
*/
void sort() {
std::stable_sort(
results_.begin( ), results_.end( ),
[ ]( const ResultBenchmarkT& lhs, const ResultBenchmarkT& rhs )
{
if(lhs.getPrecision()==rhs.getPrecision())
if(lhs.isInplace()==rhs.isInplace())
if(lhs.isComplex()==rhs.isComplex())
return lhs.getDimKind()<rhs.getDimKind() ||
lhs.getDimKind()==rhs.getDimKind() &&
(
lhs.getDim()<rhs.getDim() ||
lhs.getDim()==rhs.getDim() &&
lhs.getExtentsTotal()<rhs.getExtentsTotal()
);
else
return lhs.isComplex();
else
return lhs.isInplace();
else
return false;
});
}
void print(std::ostream& stream,
const std::string& apptitle,
const std::string& dev_infos,
double timerContextCreate,
double timerContextDestroy) {
std::stringstream ss;
ss << "; " << dev_infos << "\n"
<< "; \"Time_ContextCreate [ms]\", " << timerContextCreate << "\n"
<< "; \"Time_ContextDestroy [ms]\", " << timerContextDestroy << "\n";
ss << apptitle
<< ", RunsPerBenchmark="<<T_NumberRuns
<< "\n";
for(auto& result : results_) {
int nruns = T_NumberRuns;
std::string inplace = result.isInplace() ? "Inplace" : "Outplace";
std::string complex = result.isComplex() ? "Complex" : "Real";
ss << std::setfill('-') << std::setw(70) <<"-"<< "\n";
ss << inplace
<< ", "<<complex
<< ", "<<result.getPrecision()
<< ", Dim="<<result.getDim()
<< ", Kind="<<result.getDimKindStr()<<" ("<<result.getDimKind()<<")"
<< ", Ext="<<result.getExtents()
<< "\n";
if(result.hasError()) {
ss << " Error at run="<<result.getErrorRun()
<< ": "<<result.getError()
<< "\n";
nruns = result.getErrorRun()+1;
}
ss << std::setfill('-') << std::setw(70) <<"-"<< "\n";
ss << std::setfill(' ');
double sum;
for(int ival=0; ival<T_NumberValues; ++ival) {
sum = 0.0;
for(int run=T_NumberWarmups; run<nruns; ++run) {
result.setRun(run);
sum += result.getValue(ival);
}
ss << std::setw(28)
<< static_cast<RecordType>(ival)
<< ": " << std::setw(16) << sum/(T_NumberRuns-T_NumberWarmups)
<< " [avg]"
<< "\n";
}
}
stream << ss.str() << std::endl; // "\n" with flush
}
/**
* Store results in csv file.
* If verbosity flag is set, then std::cout receives result view.
*/
void saveCSV(const std::string& fname,
const std::string& apptitle,
const std::string& meta_information,
double timerContextCreate,
double timerContextDestroy) {
std::ofstream fs;
const char sep=',';
fs.open(fname, std::ofstream::out);
fs.precision(11);
fs << "; " << meta_information <<"\n"
<< "; \"Time_ContextCreate [ms]\", " << timerContextCreate << "\n"
<< "; \"Time_ContextDestroy [ms]\", " << timerContextDestroy << "\n";
// header
fs << "\"library\",\"inplace\",\"complex\",\"precision\",\"dim\",\"kind\""
<< ",\"nx\",\"ny\",\"nz\",\"run\",\"id\",\"success\"";
for(auto ival=0; ival<T_NumberValues; ++ival) {
fs << sep << '"' << static_cast<RecordType>(ival) << '"';
}
fs << "\n";
// data
for(auto& result : results_) {
std::string inplace = result.isInplace() ? "Inplace" : "Outplace";
std::string complex = result.isComplex() ? "Complex" : "Real";
for(auto run=0; run<T_NumberRuns; ++run) {
result.setRun(run);
fs << "\"" << apptitle << "\"" << sep
<< "\"" << inplace << "\"" << sep
<< "\"" << complex << "\"" << sep
<< "\"" << result.getPrecision() << "\"" << sep
<< result.getDim() << sep
<< "\"" << result.getDimKindStr() << "\"" << sep
<< result.getExtents()[0] << sep
<< result.getExtents()[1] << sep
<< result.getExtents()[2] << sep
<< run << sep
<< result.getID();
// was run successfull?
if(result.hasError() && result.getErrorRun()<=run) {
if(result.getErrorRun()==run)
fs << sep << "\"" <<result.getError() << "\"";
else
fs << sep << "\"Skipped\""; // subsequent runs did not run
} else {
if(run<T_NumberWarmups)
fs << sep << "\"" << "Warmup" << "\"";
else
fs << sep << "\"" << "Success" << "\"";
}
// measured time and size values
for(auto ival=0; ival<T_NumberValues; ++ival) {
fs << sep << result.getValue(ival);
}
fs << "\n";
} // run
} // result
fs.close();
} // write
private:
std::vector< ResultBenchmarkT > results_;
};
}
#endif
<|endoftext|> |
<commit_before>// SPDX-License-Identifier: MIT
/**
Copyright (c) 2021 - 2022 Beckhoff Automation GmbH & Co. KG
*/
#include "RouterAccess.h"
#include "Log.h"
#include "wrap_endian.h"
#include <array>
#include <iostream>
namespace bhf
{
namespace ads
{
struct SearchPciBusReq {
SearchPciBusReq(const uint64_t quad)
: leVendorID(bhf::ads::htole<uint16_t>(quad >> 48))
, leDeviceID(bhf::ads::htole<uint16_t>(quad >> 32))
, leSubVendorID(bhf::ads::htole<uint16_t>(quad >> 16))
, leSubSystemID(bhf::ads::htole<uint16_t>(quad))
{}
private:
const uint16_t leVendorID;
const uint16_t leDeviceID;
const uint16_t leSubVendorID;
const uint16_t leSubSystemID;
};
struct SearchPciSlotResNew {
static constexpr size_t MAXBASEADDRESSES = 6;
std::array<uint32_t, MAXBASEADDRESSES> leBaseAddresses;
uint32_t leSize[MAXBASEADDRESSES];
uint32_t leBusNumber;
uint32_t leSlotNumber;
uint16_t leBoardIrq;
uint16_t lePciRegViaPorts;
};
struct SearchPciBusResNew {
static constexpr size_t MAXSLOTRESPONSE = 64;
uint32_t leFound;
std::array<SearchPciSlotResNew, MAXSLOTRESPONSE> slot;
uint32_t nFound() const
{
return bhf::ads::letoh(leFound);
}
};
std::ostream& operator<<(std::ostream& os, const SearchPciSlotResNew& slot)
{
return os << std::dec << bhf::ads::letoh(slot.leBusNumber) << ':' <<
bhf::ads::letoh(slot.leSlotNumber) << " @ 0x" <<
bhf::ads::letoh(slot.leBaseAddresses[0]);
}
RouterAccess::RouterAccess(const std::string& gw, const AmsNetId netid, const uint16_t port)
: device(gw, netid, port ? port : 1)
{}
bool RouterAccess::PciScan(const uint64_t pci_id, std::ostream& os) const
{
#define ROUTERADSGRP_ACCESS_HARDWARE 0x00000005
#define ROUTERADSOFFS_A_HW_SEARCHPCIBUS 0x00000003
SearchPciBusResNew res {};
uint32_t bytesRead;
const auto req = SearchPciBusReq {pci_id};
const auto status = device.ReadWriteReqEx2(
ROUTERADSGRP_ACCESS_HARDWARE,
ROUTERADSOFFS_A_HW_SEARCHPCIBUS,
sizeof(res), &res,
sizeof(req), &req,
&bytesRead
);
if (ADSERR_NOERR != status) {
LOG_ERROR(__FUNCTION__ << "(): failed with: 0x" << std::hex << status << '\n');
return false;
}
if (res.slot.size() < res.nFound()) {
LOG_WARN(__FUNCTION__
<< "(): data seems corrupt. Slot count 0x" << std::hex << res.nFound() << " exceeds maximum 0x" << res.slot.size() <<
" -> truncating\n");
}
auto limit = std::min<size_t>(res.slot.size(), res.nFound());
os << "PCI devices found: " << std::dec << limit << '\n';
for (const auto& slot: res.slot) {
if (!limit--) {
break;
}
os << slot << '\n';
}
return !os.good();
}
}
}
<commit_msg>RouterAccess: please MSVC even more<commit_after>// SPDX-License-Identifier: MIT
/**
Copyright (c) 2021 - 2022 Beckhoff Automation GmbH & Co. KG
*/
#include "RouterAccess.h"
#include "Log.h"
#include "wrap_endian.h"
#include <array>
#include <iostream>
namespace bhf
{
namespace ads
{
struct SearchPciBusReq {
SearchPciBusReq(const uint64_t quad)
: leVendorID(bhf::ads::htole<uint16_t>(static_cast<uint16_t>(quad >> 48)))
, leDeviceID(bhf::ads::htole<uint16_t>(static_cast<uint16_t>(quad >> 32)))
, leSubVendorID(bhf::ads::htole<uint16_t>(static_cast<uint16_t>(quad >> 16)))
, leSubSystemID(bhf::ads::htole<uint16_t>(static_cast<uint16_t>(quad)))
{}
private:
const uint16_t leVendorID;
const uint16_t leDeviceID;
const uint16_t leSubVendorID;
const uint16_t leSubSystemID;
};
struct SearchPciSlotResNew {
static constexpr size_t MAXBASEADDRESSES = 6;
std::array<uint32_t, MAXBASEADDRESSES> leBaseAddresses;
uint32_t leSize[MAXBASEADDRESSES];
uint32_t leBusNumber;
uint32_t leSlotNumber;
uint16_t leBoardIrq;
uint16_t lePciRegViaPorts;
};
struct SearchPciBusResNew {
static constexpr size_t MAXSLOTRESPONSE = 64;
uint32_t leFound;
std::array<SearchPciSlotResNew, MAXSLOTRESPONSE> slot;
uint32_t nFound() const
{
return bhf::ads::letoh(leFound);
}
};
std::ostream& operator<<(std::ostream& os, const SearchPciSlotResNew& slot)
{
return os << std::dec << bhf::ads::letoh(slot.leBusNumber) << ':' <<
bhf::ads::letoh(slot.leSlotNumber) << " @ 0x" <<
bhf::ads::letoh(slot.leBaseAddresses[0]);
}
RouterAccess::RouterAccess(const std::string& gw, const AmsNetId netid, const uint16_t port)
: device(gw, netid, port ? port : 1)
{}
bool RouterAccess::PciScan(const uint64_t pci_id, std::ostream& os) const
{
#define ROUTERADSGRP_ACCESS_HARDWARE 0x00000005
#define ROUTERADSOFFS_A_HW_SEARCHPCIBUS 0x00000003
SearchPciBusResNew res {};
uint32_t bytesRead;
const auto req = SearchPciBusReq {pci_id};
const auto status = device.ReadWriteReqEx2(
ROUTERADSGRP_ACCESS_HARDWARE,
ROUTERADSOFFS_A_HW_SEARCHPCIBUS,
sizeof(res), &res,
sizeof(req), &req,
&bytesRead
);
if (ADSERR_NOERR != status) {
LOG_ERROR(__FUNCTION__ << "(): failed with: 0x" << std::hex << status << '\n');
return false;
}
if (res.slot.size() < res.nFound()) {
LOG_WARN(__FUNCTION__
<< "(): data seems corrupt. Slot count 0x" << std::hex << res.nFound() << " exceeds maximum 0x" << res.slot.size() <<
" -> truncating\n");
}
auto limit = std::min<size_t>(res.slot.size(), res.nFound());
os << "PCI devices found: " << std::dec << limit << '\n';
for (const auto& slot: res.slot) {
if (!limit--) {
break;
}
os << slot << '\n';
}
return !os.good();
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/numeric_traits.h>
#include <thrust/detail/device/dereference.h>
namespace thrust
{
// forward declaration of counting_iterator
template <typename Incrementable, typename Space, typename Traversal, typename Difference>
class counting_iterator;
namespace detail
{
template <typename Incrementable, typename Space, typename Traversal, typename Difference>
struct counting_iterator_base
{
typedef typename thrust::experimental::detail::ia_dflt_help<
Space,
thrust::detail::identity_<thrust::any_space_tag>
>::type space;
typedef typename thrust::experimental::detail::ia_dflt_help<
Traversal,
thrust::detail::eval_if<
thrust::detail::is_numeric<Incrementable>::value,
thrust::detail::identity_<random_access_traversal_tag>,
thrust::iterator_traversal<Incrementable>
>
>::type traversal;
// XXX this is equivalent to Boost's implementation
//typedef typename detail::ia_dflt_help<
// Difference,
// eval_if<
// is_numeric<Incrementable>::value,
// numeric_difference<Incrementable>,
// iterator_difference<Incrementable>
// >
//>::type difference;
typedef typename thrust::experimental::detail::ia_dflt_help<
Difference,
thrust::detail::eval_if<
thrust::detail::is_numeric<Incrementable>::value,
thrust::detail::identity_<std::ptrdiff_t>,
thrust::iterator_difference<Incrementable>
>
>::type difference;
typedef thrust::experimental::iterator_adaptor<
counting_iterator<Incrementable, Space, Traversal, Difference>, // self
Incrementable, // Base
Incrementable *, // Pointer -- maybe we should make this device_ptr when memory space category is device?
Incrementable, // Value
space,
traversal,
Incrementable const &,
difference
> type;
}; // end counting_iterator_base
namespace device
{
// specialize dereference_result for counting_iterator
// transform_iterator returns the same reference on the device as on the host
template <typename Incrementable, typename Space, typename Traversal, typename Difference>
struct dereference_result<
thrust::counting_iterator<
Incrementable, Space, Traversal, Difference
>
>
{
typedef typename thrust::iterator_traits< thrust::counting_iterator<Incrementable,Space,Traversal,Difference> >::reference type;
}; // end dereference_result
template<typename Incrementable, typename Space, typename Traversal, typename Difference>
inline __host__ __device__
typename dereference_result< thrust::counting_iterator<Incrementable,Space,Traversal,Difference> >::type
dereference(const thrust::counting_iterator<Incrementable,Space,Traversal,Difference> &iter)
{
return *iter;
} // end dereference()
template<typename Incrementable, typename Space, typename Traversal, typename Difference, typename IndexType>
inline __host__ __device__
typename dereference_result< thrust::counting_iterator<Incrementable,Space,Traversal,Difference> >::type
dereference(const thrust::counting_iterator<Incrementable,Space,Traversal,Difference> &iter, IndexType n)
{
return iter[n];
} // end dereference()
} // end device
template<typename Difference, typename Incrementable1, typename Incrementable2>
struct iterator_distance
{
__host__ __device__
static Difference distance(Incrementable1 x, Incrementable2 y)
{
return y - x;
}
};
template<typename Difference, typename Incrementable1, typename Incrementable2>
struct number_distance
{
__host__ __device__
static Difference distance(Incrementable1 x, Incrementable2 y)
{
return numeric_distance(x,y);
}
};
} // end detail
} // end thrust
<commit_msg>When counting_iterator is given device_space_tag for its Space parameter, it needs to convert it to default_backend_space_tag<commit_after>/*
* Copyright 2008-2009 NVIDIA Corporation
*
* 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
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/iterator_traits.h>
#include <thrust/detail/numeric_traits.h>
#include <thrust/detail/device/dereference.h>
#include <thrust/iterator/detail/backend_iterator_spaces.h>
namespace thrust
{
// forward declaration of counting_iterator
template <typename Incrementable, typename Space, typename Traversal, typename Difference>
class counting_iterator;
namespace detail
{
template <typename Incrementable, typename Space, typename Traversal, typename Difference>
struct counting_iterator_base
{
typedef typename thrust::detail::eval_if<
// use any_space_tag if we are given use_default
thrust::detail::is_same<Space,use_default>::value,
thrust::detail::identity_<thrust::any_space_tag>,
thrust::detail::eval_if<
// use the default backend space if we are given device_space_tag
thrust::detail::is_same<Space,thrust::device_space_tag>::value,
thrust::detail::identity_<thrust::detail::default_device_space_tag>,
thrust::detail::identity_<Space>
>
>::type space;
typedef typename thrust::experimental::detail::ia_dflt_help<
Traversal,
thrust::detail::eval_if<
thrust::detail::is_numeric<Incrementable>::value,
thrust::detail::identity_<random_access_traversal_tag>,
thrust::iterator_traversal<Incrementable>
>
>::type traversal;
// XXX this is equivalent to Boost's implementation
//typedef typename detail::ia_dflt_help<
// Difference,
// eval_if<
// is_numeric<Incrementable>::value,
// numeric_difference<Incrementable>,
// iterator_difference<Incrementable>
// >
//>::type difference;
typedef typename thrust::experimental::detail::ia_dflt_help<
Difference,
thrust::detail::eval_if<
thrust::detail::is_numeric<Incrementable>::value,
thrust::detail::identity_<std::ptrdiff_t>,
thrust::iterator_difference<Incrementable>
>
>::type difference;
typedef thrust::experimental::iterator_adaptor<
counting_iterator<Incrementable, Space, Traversal, Difference>, // self
Incrementable, // Base
Incrementable *, // Pointer -- maybe we should make this device_ptr when memory space category is device?
Incrementable, // Value
space,
traversal,
Incrementable const &,
difference
> type;
}; // end counting_iterator_base
namespace device
{
// specialize dereference_result for counting_iterator
// transform_iterator returns the same reference on the device as on the host
template <typename Incrementable, typename Space, typename Traversal, typename Difference>
struct dereference_result<
thrust::counting_iterator<
Incrementable, Space, Traversal, Difference
>
>
{
typedef typename thrust::iterator_traits< thrust::counting_iterator<Incrementable,Space,Traversal,Difference> >::reference type;
}; // end dereference_result
template<typename Incrementable, typename Space, typename Traversal, typename Difference>
inline __host__ __device__
typename dereference_result< thrust::counting_iterator<Incrementable,Space,Traversal,Difference> >::type
dereference(const thrust::counting_iterator<Incrementable,Space,Traversal,Difference> &iter)
{
return *iter;
} // end dereference()
template<typename Incrementable, typename Space, typename Traversal, typename Difference, typename IndexType>
inline __host__ __device__
typename dereference_result< thrust::counting_iterator<Incrementable,Space,Traversal,Difference> >::type
dereference(const thrust::counting_iterator<Incrementable,Space,Traversal,Difference> &iter, IndexType n)
{
return iter[n];
} // end dereference()
} // end device
template<typename Difference, typename Incrementable1, typename Incrementable2>
struct iterator_distance
{
__host__ __device__
static Difference distance(Incrementable1 x, Incrementable2 y)
{
return y - x;
}
};
template<typename Difference, typename Incrementable1, typename Incrementable2>
struct number_distance
{
__host__ __device__
static Difference distance(Incrementable1 x, Incrementable2 y)
{
return numeric_distance(x,y);
}
};
} // end detail
} // end thrust
<|endoftext|> |
<commit_before>#include "tidyup_actions/stateCreatorRobotPose.h"
#include <pluginlib/class_list_macros.h>
#include <visualization_msgs/MarkerArray.h>
#include <angles/angles.h>
PLUGINLIB_DECLARE_CLASS(tidyup_actions, state_creator_robot_pose,
tidyup_actions::StateCreatorRobotPose, continual_planning_executive::StateCreator)
namespace tidyup_actions
{
StateCreatorRobotPose::StateCreatorRobotPose()
{
ros::NodeHandle nhPriv("~");
nhPriv.param("nav_target_tolerance_xy", _goalToleranceXY, 0.5);
nhPriv.param("nav_target_tolerance_yaw", _goalToleranceYaw, 0.26); //15deg
bool relative;
nhPriv.param("nav_target_tolerance_relative_to_move_base", relative, false);
if(relative) {
// relative mode: 1. get the namespace for base_local_planner
std::string base_local_planner_ns;
if(!nhPriv.getParam("nav_base_local_planner_ns", base_local_planner_ns)) {
// TODO can we estimate this?
ROS_ERROR("nav_target_tolerance_relative_to_move_base was true, but nav_base_local_planner_ns is not set - falling back to absolute mode.");
} else { // success: 2. get the xy_goal_tolerance
double move_base_tol_xy;
ros::NodeHandle nh;
if(!nh.getParam(base_local_planner_ns + "/xy_goal_tolerance", move_base_tol_xy)) {
ROS_ERROR_STREAM("nav_target_tolerance_relative_to_move_base was true, but "
<< (base_local_planner_ns + "/xy_goal_tolerance") << " was not set"
<< " - falling back to absolute mode");
} else { // 2. add move_base's tolerance to our relative tolerance
_goalToleranceXY += move_base_tol_xy;
}
double move_base_tol_yaw;
if(!nh.getParam(base_local_planner_ns + "/yaw_goal_tolerance", move_base_tol_yaw)) {
ROS_ERROR_STREAM("nav_target_tolerance_relative_to_move_base was true, but "
<< (base_local_planner_ns + "/yaw_goal_tolerance") << " was not set"
<< " - falling back to absolute mode");
} else { // 2. add move_base's tolerance to our relative tolerance
_goalToleranceYaw += move_base_tol_yaw;
}
}
}
ROS_INFO("Tolerance for accepting nav goals set to %f m, %f deg.",
_goalToleranceXY, angles::to_degrees(_goalToleranceYaw));
if(s_PublishLocationsAsMarkers) {
_markerPub = nhPriv.advertise<visualization_msgs::MarkerArray>("robot_pose_markers", 5, true);
ROS_INFO("marker topic: %s", _markerPub.getTopic().c_str());
}
}
StateCreatorRobotPose::~StateCreatorRobotPose()
{
}
void StateCreatorRobotPose::initialize(const std::deque<std::string> & arguments)
{
ROS_ASSERT(arguments.size() == 4);
_robotPoseObject = arguments[0];
_robotPoseType = arguments[1];
_atPredicate = arguments[2];
_locationType = arguments[3];
if(_robotPoseObject == "-")
_robotPoseObject = "";
if(_robotPoseType == "-")
_robotPoseType = "";
if(_atPredicate == "-")
_atPredicate = "";
if(_locationType == "-")
_locationType = "";
}
bool StateCreatorRobotPose::fillState(SymbolicState & state)
{
tf::StampedTransform transform;
try{
_tf.lookupTransform("/map", "/base_link", ros::Time(0), transform);
}
catch (tf::TransformException ex){
ROS_ERROR("%s",ex.what());
return false;
}
// 1. Real robot location
if(!_robotPoseObject.empty()) {
ROS_ASSERT(!_robotPoseType.empty());
state.addObject(_robotPoseObject, _robotPoseType);
state.setNumericalFluent("x", _robotPoseObject, transform.getOrigin().x());
state.setNumericalFluent("y", _robotPoseObject, transform.getOrigin().y());
state.setNumericalFluent("z", _robotPoseObject, transform.getOrigin().z());
state.setNumericalFluent("qx", _robotPoseObject, transform.getRotation().x());
state.setNumericalFluent("qy", _robotPoseObject, transform.getRotation().y());
state.setNumericalFluent("qz", _robotPoseObject, transform.getRotation().z());
state.setNumericalFluent("qw", _robotPoseObject, transform.getRotation().w());
state.setNumericalFluent("timestamp", _robotPoseObject, ros::Time::now().toSec());
state.addObject("/map", "frameid");
state.setObjectFluent("frame-id", _robotPoseObject, "/map");
}
// 2.b check if we are at any _locations
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> targets =
state.getTypedObjects().equal_range(_locationType);
vector<string> paramList;
paramList.push_back("dummy");
double minDist = HUGE_VAL;
string nearestTarget = "";
int atLocations = 0;
for(SymbolicState::TypedObjectConstIterator it = targets.first; it != targets.second; it++) {
string target = it->second;
if(target == _robotPoseObject) // skip current robot location
continue;
// first get xyz, qxyzw from state
Predicate p;
paramList[0] = target;
p.parameters = paramList;
p.name = "x";
double posX;
if(!state.hasNumericalFluent(p, &posX)) {
ROS_ERROR("%s: target object: %s - no x-location in state.", __func__, target.c_str());
continue;
}
double posY;
p.name = "y";
if(!state.hasNumericalFluent(p, &posY)) {
ROS_ERROR("%s: target object: %s - no y-location in state.", __func__, target.c_str());
continue;
}
double qx;
p.name = "qx";
if(!state.hasNumericalFluent(p, &qx)) {
ROS_ERROR("%s: target object: %s - no qx in state.", __func__, target.c_str());
continue;
}
double qy;
p.name = "qy";
if(!state.hasNumericalFluent(p, &qy)) {
ROS_ERROR("%s: target object: %s - no qy in state.", __func__, target.c_str());
continue;
}
double qz;
p.name = "qz";
if(!state.hasNumericalFluent(p, &qz)) {
ROS_ERROR("%s: target object: %s - no qz in state.", __func__, target.c_str());
continue;
}
double qw;
p.name = "qw";
if(!state.hasNumericalFluent(p, &qw)) {
ROS_ERROR("%s: target object: %s - no qw in state.", __func__, target.c_str());
continue;
}
// compute dXY, dYaw between current pose and target
tf::Transform targetTransform(btQuaternion(qx, qy, qz, qw), btVector3(posX, posY, 0.0));
tf::Transform deltaTransform = targetTransform.inverseTimes(transform);
double dDist = hypot(deltaTransform.getOrigin().x(), deltaTransform.getOrigin().y());
double dAng = tf::getYaw(deltaTransform.getRotation());
ROS_INFO("Target %s dist: %f m ang: %f deg", target.c_str(), dDist, angles::to_degrees(dAng));
if(!_atPredicate.empty()) {
// Found a target - update state!
if(dDist < _goalToleranceXY && fabs(dAng) < _goalToleranceYaw) {
ROS_INFO("(at) target %s !", target.c_str());
state.setBooleanPredicate(_atPredicate, target, true);
atLocations++;
} else {
state.setBooleanPredicate(_atPredicate, target, false);
}
if(dDist < minDist) {
minDist = dDist;
nearestTarget = target;
}
}
}
ROS_INFO("Nearest target is %s (%f m).", nearestTarget.c_str(), minDist);
// 2.a Set the robot pose, if we are not already at another pose
if(!_atPredicate.empty() && !_robotPoseObject.empty()) {
if(atLocations == 0) {
state.setBooleanPredicate(_atPredicate, _robotPoseObject, true);
} else {
state.setBooleanPredicate(_atPredicate, _robotPoseObject, false);
if(atLocations > 1) {
ROS_WARN("We are at %d locations at the same time!.", atLocations);
}
}
}
if(s_PublishLocationsAsMarkers)
publishLocationsAsMarkers(state);
return true;
}
/**
* Publish markers for locations:
* target locations are yellow or green if the robot is at the location
* the robot location is white or blue if the robot is at the location
*/
void StateCreatorRobotPose::publishLocationsAsMarkers(const SymbolicState & state)
{
if(!_markerPub) {
ROS_WARN("%s: _markerPub invalid.", __func__);
return;
}
visualization_msgs::MarkerArray ma;
if(!_locationType.empty()) {
// Check if we are at any grasp_locations
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> targets =
state.getTypedObjects().equal_range(_locationType);
vector<string> paramList;
paramList.push_back("dummy");
unsigned int count = 0;
for(SymbolicState::TypedObjectConstIterator it = targets.first; it != targets.second; it++) {
string target = it->second;
Predicate p;
paramList[0] = target;
p.parameters = paramList;
p.name = "x";
double valueX;
if(!state.hasNumericalFluent(p, &valueX)) {
ROS_ERROR("%s: target object: %s - no x-location.", __func__, target.c_str());
continue;
}
double valueY;
p.name = "y";
if(!state.hasNumericalFluent(p, &valueY)) {
ROS_ERROR("%s: target object: %s - no y-location.", __func__, target.c_str());
continue;
}
p.name = _atPredicate;
bool at = false;
if(!state.hasBooleanPredicate(p, &at)) {
ROS_ERROR("%s: state has at-base not set for %s.", __func__, target.c_str());
continue;
}
// we now know for this target it's x/y coords and if the robot is at this target
visualization_msgs::Marker mark;
mark.header.frame_id = "/map";
mark.ns = "target_locations";
mark.id = count;
count++;
mark.type = visualization_msgs::Marker::SPHERE;
mark.action = visualization_msgs::Marker::ADD;
mark.pose.position.x = valueX;
mark.pose.position.y = valueY;
mark.pose.position.z = 0.15;
mark.pose.orientation.w = 1.0;
mark.scale.x = 0.3;
mark.scale.y = 0.3;
mark.scale.z = 0.3;
mark.color.a = 1.0;
if(at) {
mark.color.g = 1.0;
} else {
mark.color.r = 1.0;
mark.color.g = 1.0;
}
mark.text = target;
ma.markers.push_back(mark);
}
// all should be overwritten as #targets is const, but to be safe
for(unsigned int i = count; i < 100; i++) {
visualization_msgs::Marker mark;
mark.header.frame_id = "/map";
mark.ns = "target_locations";
mark.id = i;
mark.type = visualization_msgs::Marker::SPHERE;
mark.action = visualization_msgs::Marker::DELETE;
ma.markers.push_back(mark);
}
}
// finally robot location marker
if(!_robotPoseObject.empty()) {
bool l0ok = true;
visualization_msgs::Marker mark;
mark.header.frame_id = "/map";
mark.ns = "robot_location";
mark.id = 0;
mark.type = visualization_msgs::Marker::SPHERE;
mark.action = visualization_msgs::Marker::ADD;
Predicate p;
vector<string> paramList;
paramList[0] = _robotPoseObject;
p.parameters = paramList;
p.name = "x";
double valueX;
if(!state.hasNumericalFluent(p, &valueX)) {
ROS_ERROR("%s: %s - no x-location.", __func__, _robotPoseObject.c_str());
l0ok = false;
}
double valueY;
p.name = "y";
if(!state.hasNumericalFluent(p, &valueY)) {
ROS_ERROR("%s: %s - no y-location.", __func__, _robotPoseObject.c_str());
l0ok = false;
}
p.name = _atPredicate;
bool at = false;
if(!state.hasBooleanPredicate(p, &at)) {
ROS_ERROR("%s: state has %s not set for %s.", __func__,
_atPredicate.c_str(), _robotPoseObject.c_str());
l0ok = false;
}
if(l0ok) {
mark.pose.position.x = valueX;
mark.pose.position.y = valueY;
mark.pose.position.z = 0.15;
mark.pose.orientation.w = 1.0;
mark.scale.x = 0.3;
mark.scale.y = 0.3;
mark.scale.z = 0.3;
mark.color.a = 1.0;
if(at) {
mark.color.b = 1.0;
} else {
mark.color.r = 1.0;
mark.color.g = 1.0;
mark.color.b = 1.0;
}
mark.text = _robotPoseObject;
} else {
mark.action = visualization_msgs::Marker::DELETE;
}
ma.markers.push_back(mark);
}
_markerPub.publish(ma);
}
};
<commit_msg>stateCreatorRobotPose tries to estimate the namespace for local planner params<commit_after>#include "tidyup_actions/stateCreatorRobotPose.h"
#include <pluginlib/class_list_macros.h>
#include <visualization_msgs/MarkerArray.h>
#include <angles/angles.h>
PLUGINLIB_DECLARE_CLASS(tidyup_actions, state_creator_robot_pose,
tidyup_actions::StateCreatorRobotPose, continual_planning_executive::StateCreator)
namespace tidyup_actions
{
StateCreatorRobotPose::StateCreatorRobotPose()
{
ros::NodeHandle nhPriv("~");
ros::NodeHandle nh;
nhPriv.param("nav_target_tolerance_xy", _goalToleranceXY, 0.5);
nhPriv.param("nav_target_tolerance_yaw", _goalToleranceYaw, 0.26); //15deg
bool relative;
nhPriv.param("nav_target_tolerance_relative_to_move_base", relative, false);
if(relative) {
// relative mode: 1. get the namespace for base_local_planner
std::string base_local_planner_ns;
if(!nhPriv.getParam("nav_base_local_planner_ns", base_local_planner_ns)) {
ROS_WARN("nav_target_tolerance_relative_to_move_base set, but nav_base_local_planner_ns not set - trying to estimate");
std::string local_planner;
if(!nh.getParam("move_base_node/base_local_planner", local_planner)) {
ROS_ERROR("move_base_node/base_local_planner not set - falling back to absolute mode.");
} else {
// dwa_local_planner/DWAPlannerROS -> DWAPlannerROS
std::string::size_type x = local_planner.find_last_of("/");
if(x == std::string::npos)
base_local_planner_ns = local_planner;
else
base_local_planner_ns = local_planner.substr(x + 1);
ROS_INFO("Estimated base_local_planner_ns to %s.", base_local_planner_ns.c_str());
}
}
if(!base_local_planner_ns.empty()) { // success: 2. get the xy_goal_tolerance
double move_base_tol_xy;
if(!nh.getParam(base_local_planner_ns + "/xy_goal_tolerance", move_base_tol_xy)) {
ROS_ERROR_STREAM("nav_target_tolerance_relative_to_move_base was true, but "
<< (base_local_planner_ns + "/xy_goal_tolerance") << " was not set"
<< " - falling back to absolute mode");
} else { // 2. add move_base's tolerance to our relative tolerance
_goalToleranceXY += move_base_tol_xy;
}
double move_base_tol_yaw;
if(!nh.getParam(base_local_planner_ns + "/yaw_goal_tolerance", move_base_tol_yaw)) {
ROS_ERROR_STREAM("nav_target_tolerance_relative_to_move_base was true, but "
<< (base_local_planner_ns + "/yaw_goal_tolerance") << " was not set"
<< " - falling back to absolute mode");
} else { // 2. add move_base's tolerance to our relative tolerance
_goalToleranceYaw += move_base_tol_yaw;
}
}
}
ROS_INFO("Tolerance for accepting nav goals set to %f m, %f deg.",
_goalToleranceXY, angles::to_degrees(_goalToleranceYaw));
if(s_PublishLocationsAsMarkers) {
_markerPub = nhPriv.advertise<visualization_msgs::MarkerArray>("robot_pose_markers", 5, true);
ROS_INFO("marker topic: %s", _markerPub.getTopic().c_str());
}
}
StateCreatorRobotPose::~StateCreatorRobotPose()
{
}
void StateCreatorRobotPose::initialize(const std::deque<std::string> & arguments)
{
ROS_ASSERT(arguments.size() == 4);
_robotPoseObject = arguments[0];
_robotPoseType = arguments[1];
_atPredicate = arguments[2];
_locationType = arguments[3];
if(_robotPoseObject == "-")
_robotPoseObject = "";
if(_robotPoseType == "-")
_robotPoseType = "";
if(_atPredicate == "-")
_atPredicate = "";
if(_locationType == "-")
_locationType = "";
}
bool StateCreatorRobotPose::fillState(SymbolicState & state)
{
tf::StampedTransform transform;
try{
_tf.lookupTransform("/map", "/base_link", ros::Time(0), transform);
}
catch (tf::TransformException ex){
ROS_ERROR("%s",ex.what());
return false;
}
// 1. Real robot location
if(!_robotPoseObject.empty()) {
ROS_ASSERT(!_robotPoseType.empty());
state.addObject(_robotPoseObject, _robotPoseType);
state.setNumericalFluent("x", _robotPoseObject, transform.getOrigin().x());
state.setNumericalFluent("y", _robotPoseObject, transform.getOrigin().y());
state.setNumericalFluent("z", _robotPoseObject, transform.getOrigin().z());
state.setNumericalFluent("qx", _robotPoseObject, transform.getRotation().x());
state.setNumericalFluent("qy", _robotPoseObject, transform.getRotation().y());
state.setNumericalFluent("qz", _robotPoseObject, transform.getRotation().z());
state.setNumericalFluent("qw", _robotPoseObject, transform.getRotation().w());
state.setNumericalFluent("timestamp", _robotPoseObject, ros::Time::now().toSec());
state.addObject("/map", "frameid");
state.setObjectFluent("frame-id", _robotPoseObject, "/map");
}
// 2.b check if we are at any _locations
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> targets =
state.getTypedObjects().equal_range(_locationType);
vector<string> paramList;
paramList.push_back("dummy");
double minDist = HUGE_VAL;
string nearestTarget = "";
int atLocations = 0;
for(SymbolicState::TypedObjectConstIterator it = targets.first; it != targets.second; it++) {
string target = it->second;
if(target == _robotPoseObject) // skip current robot location
continue;
// first get xyz, qxyzw from state
Predicate p;
paramList[0] = target;
p.parameters = paramList;
p.name = "x";
double posX;
if(!state.hasNumericalFluent(p, &posX)) {
ROS_ERROR("%s: target object: %s - no x-location in state.", __func__, target.c_str());
continue;
}
double posY;
p.name = "y";
if(!state.hasNumericalFluent(p, &posY)) {
ROS_ERROR("%s: target object: %s - no y-location in state.", __func__, target.c_str());
continue;
}
double qx;
p.name = "qx";
if(!state.hasNumericalFluent(p, &qx)) {
ROS_ERROR("%s: target object: %s - no qx in state.", __func__, target.c_str());
continue;
}
double qy;
p.name = "qy";
if(!state.hasNumericalFluent(p, &qy)) {
ROS_ERROR("%s: target object: %s - no qy in state.", __func__, target.c_str());
continue;
}
double qz;
p.name = "qz";
if(!state.hasNumericalFluent(p, &qz)) {
ROS_ERROR("%s: target object: %s - no qz in state.", __func__, target.c_str());
continue;
}
double qw;
p.name = "qw";
if(!state.hasNumericalFluent(p, &qw)) {
ROS_ERROR("%s: target object: %s - no qw in state.", __func__, target.c_str());
continue;
}
// compute dXY, dYaw between current pose and target
tf::Transform targetTransform(btQuaternion(qx, qy, qz, qw), btVector3(posX, posY, 0.0));
tf::Transform deltaTransform = targetTransform.inverseTimes(transform);
double dDist = hypot(deltaTransform.getOrigin().x(), deltaTransform.getOrigin().y());
double dAng = tf::getYaw(deltaTransform.getRotation());
ROS_INFO("Target %s dist: %f m ang: %f deg", target.c_str(), dDist, angles::to_degrees(dAng));
if(!_atPredicate.empty()) {
// Found a target - update state!
if(dDist < _goalToleranceXY && fabs(dAng) < _goalToleranceYaw) {
ROS_INFO("(at) target %s !", target.c_str());
state.setBooleanPredicate(_atPredicate, target, true);
atLocations++;
} else {
state.setBooleanPredicate(_atPredicate, target, false);
}
if(dDist < minDist) {
minDist = dDist;
nearestTarget = target;
}
}
}
ROS_INFO("Nearest target is %s (%f m).", nearestTarget.c_str(), minDist);
// 2.a Set the robot pose, if we are not already at another pose
if(!_atPredicate.empty() && !_robotPoseObject.empty()) {
if(atLocations == 0) {
state.setBooleanPredicate(_atPredicate, _robotPoseObject, true);
} else {
state.setBooleanPredicate(_atPredicate, _robotPoseObject, false);
if(atLocations > 1) {
ROS_WARN("We are at %d locations at the same time!.", atLocations);
}
}
}
if(s_PublishLocationsAsMarkers)
publishLocationsAsMarkers(state);
return true;
}
/**
* Publish markers for locations:
* target locations are yellow or green if the robot is at the location
* the robot location is white or blue if the robot is at the location
*/
void StateCreatorRobotPose::publishLocationsAsMarkers(const SymbolicState & state)
{
if(!_markerPub) {
ROS_WARN("%s: _markerPub invalid.", __func__);
return;
}
visualization_msgs::MarkerArray ma;
if(!_locationType.empty()) {
// Check if we are at any grasp_locations
pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> targets =
state.getTypedObjects().equal_range(_locationType);
vector<string> paramList;
paramList.push_back("dummy");
unsigned int count = 0;
for(SymbolicState::TypedObjectConstIterator it = targets.first; it != targets.second; it++) {
string target = it->second;
Predicate p;
paramList[0] = target;
p.parameters = paramList;
p.name = "x";
double valueX;
if(!state.hasNumericalFluent(p, &valueX)) {
ROS_ERROR("%s: target object: %s - no x-location.", __func__, target.c_str());
continue;
}
double valueY;
p.name = "y";
if(!state.hasNumericalFluent(p, &valueY)) {
ROS_ERROR("%s: target object: %s - no y-location.", __func__, target.c_str());
continue;
}
p.name = _atPredicate;
bool at = false;
if(!state.hasBooleanPredicate(p, &at)) {
ROS_ERROR("%s: state has at-base not set for %s.", __func__, target.c_str());
continue;
}
// we now know for this target it's x/y coords and if the robot is at this target
visualization_msgs::Marker mark;
mark.header.frame_id = "/map";
mark.ns = "target_locations";
mark.id = count;
count++;
mark.type = visualization_msgs::Marker::SPHERE;
mark.action = visualization_msgs::Marker::ADD;
mark.pose.position.x = valueX;
mark.pose.position.y = valueY;
mark.pose.position.z = 0.15;
mark.pose.orientation.w = 1.0;
mark.scale.x = 0.3;
mark.scale.y = 0.3;
mark.scale.z = 0.3;
mark.color.a = 1.0;
if(at) {
mark.color.g = 1.0;
} else {
mark.color.r = 1.0;
mark.color.g = 1.0;
}
mark.text = target;
ma.markers.push_back(mark);
}
// all should be overwritten as #targets is const, but to be safe
for(unsigned int i = count; i < 100; i++) {
visualization_msgs::Marker mark;
mark.header.frame_id = "/map";
mark.ns = "target_locations";
mark.id = i;
mark.type = visualization_msgs::Marker::SPHERE;
mark.action = visualization_msgs::Marker::DELETE;
ma.markers.push_back(mark);
}
}
// finally robot location marker
if(!_robotPoseObject.empty()) {
bool l0ok = true;
visualization_msgs::Marker mark;
mark.header.frame_id = "/map";
mark.ns = "robot_location";
mark.id = 0;
mark.type = visualization_msgs::Marker::SPHERE;
mark.action = visualization_msgs::Marker::ADD;
Predicate p;
vector<string> paramList;
paramList[0] = _robotPoseObject;
p.parameters = paramList;
p.name = "x";
double valueX;
if(!state.hasNumericalFluent(p, &valueX)) {
ROS_ERROR("%s: %s - no x-location.", __func__, _robotPoseObject.c_str());
l0ok = false;
}
double valueY;
p.name = "y";
if(!state.hasNumericalFluent(p, &valueY)) {
ROS_ERROR("%s: %s - no y-location.", __func__, _robotPoseObject.c_str());
l0ok = false;
}
p.name = _atPredicate;
bool at = false;
if(!state.hasBooleanPredicate(p, &at)) {
ROS_ERROR("%s: state has %s not set for %s.", __func__,
_atPredicate.c_str(), _robotPoseObject.c_str());
l0ok = false;
}
if(l0ok) {
mark.pose.position.x = valueX;
mark.pose.position.y = valueY;
mark.pose.position.z = 0.15;
mark.pose.orientation.w = 1.0;
mark.scale.x = 0.3;
mark.scale.y = 0.3;
mark.scale.z = 0.3;
mark.color.a = 1.0;
if(at) {
mark.color.b = 1.0;
} else {
mark.color.r = 1.0;
mark.color.g = 1.0;
mark.color.b = 1.0;
}
mark.text = _robotPoseObject;
} else {
mark.action = visualization_msgs::Marker::DELETE;
}
ma.markers.push_back(mark);
}
_markerPub.publish(ma);
}
};
<|endoftext|> |
<commit_before>
#include "CGlyphNodeManager.h"
#include <ionWindow.h>
#include "CProgramContext.h"
#include "CDataSet.h"
vec3f CGlyph::GetPosition() const
{
return Position;
}
color3f CGlyph::GetColor() const
{
return Color;
}
void CGlyphNodeManager::Init()
{
SingletonPointer<CSceneManager> SceneManager;
Node = SceneManager->GetFactory()->AddSceneNode("Glyph");
}
void CGlyphNodeManager::LoadSceneElements()
{
size_t const MaxParticles = Glyphs.size();
PositionBuffer = new ion::GL::VertexBuffer;
PositionBuffer->Data<f32>(MaxParticles * sizeof(f32), nullptr, 3);
ColorBuffer = new ion::GL::VertexBuffer;
ColorBuffer->Data<f32>(MaxParticles * sizeof(f32), nullptr, 3);
if (Node)
{
Node->SetVertexBuffer("vPosition", PositionBuffer);
Node->SetVertexBuffer("vColor", ColorBuffer);
Node->SetUniform("Model", & Node->GetTransformationUniform());
Node->SetPrimitiveType(ion::GL::EPrimitiveType::Points);
}
Positions.clear();
Colors.clear();
size_t const FloatsNeeded = Glyphs.size() * 3;
if (Positions.size() < FloatsNeeded)
{
Positions.resize(FloatsNeeded);
Colors.resize(FloatsNeeded);
}
for (uint i = 0; i < Glyphs.size(); ++ i)
{
Positions[i*3 + 0] = Glyphs[i]->Position.X;
Positions[i*3 + 1] = Glyphs[i]->Position.Y;
Positions[i*3 + 2] = Glyphs[i]->Position.Z;
Colors[i*3 + 0] = Glyphs[i]->Color.Red;
Colors[i*3 + 1] = Glyphs[i]->Color.Green;
Colors[i*3 + 2] = Glyphs[i]->Color.Blue;
}
PositionBuffer->SubData(Positions);
ColorBuffer->SubData(Colors);
if (Node)
{
Node->SetElementCount((uint) Glyphs.size());
Node->SetVisible(Glyphs.size() != 0);
}
}
void CGlyphNodeManager::LoadGlyphs(CDataSet * DataSet, IColorMapper * ColorMapper)
{
Glyphs.clear();
ColorMapper->PreProcessValues(DataSet->Points);
SRange<f64> XRange = DataSet->Points.GetFieldRange(DataSet->Traits.PositionXField, 15.0);
SRange<f64> YRange = DataSet->Points.GetFieldRange(DataSet->Traits.PositionYField, 15.0);
SRange<f64> ZRange = DataSet->Points.GetFieldRange(DataSet->Traits.PositionZField, 15.0);
if (XRange.IsEmpty())
XRange = SRange<f64>(-1, 1);
if (YRange.IsEmpty())
YRange = SRange<f64>(-1, 1);
if (ZRange.IsEmpty())
ZRange = SRange<f64>(-1, 1);
printf("built in data range is %g %g to %g %g long lat\n", XRange.Minimum, ZRange.Minimum, XRange.Maximum, ZRange.Maximum);
printf("depth varies from %g to %g\n", YRange.Minimum, YRange.Maximum);
for (auto Point : DataSet->Points.GetValues())
{
CGlyph * Glyph = new CGlyph();
f32 X = (f32) XRange.Normalize(Point.GetField(DataSet->Traits.PositionXField));
if (XRange.IsEmpty())
X = 0.f;
f32 Y = (f32) YRange.Normalize(Point.GetField(DataSet->Traits.PositionYField));
if (DataSet->Traits.InvertY)
Y = 1.f - Y;
if (YRange.IsEmpty())
Y = 0.f;
f32 Z = (f32) ZRange.Normalize(Point.GetField(DataSet->Traits.PositionZField));
if (ZRange.IsEmpty())
Z = 0.f;
/*
f64 v = it->GetField(FloorLabel);
if (v != 0)
{
f32 Depth = (f32) v / (f32) YRange.second;
Glyph.FloorHeight = 1.f - Depth;
}
*/
Glyph->Position = vec3f(X, Y, Z) - 0.5f;
Glyph->Color = ColorMapper->GetColor(Point);
Glyphs.push_back(Glyph);
}
//Context->Scene.Glyphs->BuildLines();
LoadSceneElements();
}
CSceneNode * CGlyphNodeManager::GetNode()
{
return Node;
}
CSceneNode const * CGlyphNodeManager::GetNode() const
{
return Node;
}
<commit_msg>Fix glyph count<commit_after>
#include "CGlyphNodeManager.h"
#include <ionWindow.h>
#include "CProgramContext.h"
#include "CDataSet.h"
vec3f CGlyph::GetPosition() const
{
return Position;
}
color3f CGlyph::GetColor() const
{
return Color;
}
void CGlyphNodeManager::Init()
{
SingletonPointer<CSceneManager> SceneManager;
Node = SceneManager->GetFactory()->AddSceneNode("Glyph");
}
void CGlyphNodeManager::LoadSceneElements()
{
size_t const FloatsNeeded = Glyphs.size() * 3;
PositionBuffer = new ion::GL::VertexBuffer;
PositionBuffer->Data<f32>(FloatsNeeded * sizeof(f32), nullptr, 3);
ColorBuffer = new ion::GL::VertexBuffer;
ColorBuffer->Data<f32>(FloatsNeeded * sizeof(f32), nullptr, 3);
if (Node)
{
Node->SetVertexBuffer("vPosition", PositionBuffer);
Node->SetVertexBuffer("vColor", ColorBuffer);
Node->SetUniform("Model", & Node->GetTransformationUniform());
Node->SetPrimitiveType(ion::GL::EPrimitiveType::Points);
}
Positions.clear();
Colors.clear();
if (Positions.size() < FloatsNeeded)
{
Positions.resize(FloatsNeeded);
Colors.resize(FloatsNeeded);
}
for (uint i = 0; i < Glyphs.size(); ++ i)
{
Positions[i*3 + 0] = Glyphs[i]->Position.X;
Positions[i*3 + 1] = Glyphs[i]->Position.Y;
Positions[i*3 + 2] = Glyphs[i]->Position.Z;
Colors[i*3 + 0] = Glyphs[i]->Color.Red;
Colors[i*3 + 1] = Glyphs[i]->Color.Green;
Colors[i*3 + 2] = Glyphs[i]->Color.Blue;
}
PositionBuffer->SubData(Positions);
ColorBuffer->SubData(Colors);
if (Node)
{
Node->SetElementCount((uint) Glyphs.size());
Node->SetVisible(Glyphs.size() != 0);
}
}
void CGlyphNodeManager::LoadGlyphs(CDataSet * DataSet, IColorMapper * ColorMapper)
{
Glyphs.clear();
ColorMapper->PreProcessValues(DataSet->Points);
SRange<f64> XRange = DataSet->Points.GetFieldRange(DataSet->Traits.PositionXField, 15.0);
SRange<f64> YRange = DataSet->Points.GetFieldRange(DataSet->Traits.PositionYField, 15.0);
SRange<f64> ZRange = DataSet->Points.GetFieldRange(DataSet->Traits.PositionZField, 15.0);
if (XRange.IsEmpty())
XRange = SRange<f64>(-1, 1);
if (YRange.IsEmpty())
YRange = SRange<f64>(-1, 1);
if (ZRange.IsEmpty())
ZRange = SRange<f64>(-1, 1);
printf("built in data range is %g %g to %g %g long lat\n", XRange.Minimum, ZRange.Minimum, XRange.Maximum, ZRange.Maximum);
printf("depth varies from %g to %g\n", YRange.Minimum, YRange.Maximum);
for (auto Point : DataSet->Points.GetValues())
{
CGlyph * Glyph = new CGlyph();
f32 X = (f32) XRange.Normalize(Point.GetField(DataSet->Traits.PositionXField));
if (XRange.IsEmpty())
X = 0.f;
f32 Y = (f32) YRange.Normalize(Point.GetField(DataSet->Traits.PositionYField));
if (DataSet->Traits.InvertY)
Y = 1.f - Y;
if (YRange.IsEmpty())
Y = 0.f;
f32 Z = (f32) ZRange.Normalize(Point.GetField(DataSet->Traits.PositionZField));
if (ZRange.IsEmpty())
Z = 0.f;
/*
f64 v = it->GetField(FloorLabel);
if (v != 0)
{
f32 Depth = (f32) v / (f32) YRange.second;
Glyph.FloorHeight = 1.f - Depth;
}
*/
Glyph->Position = vec3f(X, Y, Z) - 0.5f;
Glyph->Color = ColorMapper->GetColor(Point);
Glyphs.push_back(Glyph);
}
LoadSceneElements();
}
CSceneNode * CGlyphNodeManager::GetNode()
{
return Node;
}
CSceneNode const * CGlyphNodeManager::GetNode() const
{
return Node;
}
<|endoftext|> |
<commit_before>//
// kern_audio.cpp
// AppleALC
//
// Copyright © 2018 vit9696. All rights reserved.
//
#include <Headers/kern_iokit.hpp>
#include <Headers/plugin_start.hpp>
#include "kern_audio.hpp"
OSDefineMetaClassAndStructors(AppleALCAudio, IOService)
IOService *AppleALCAudio::probe(IOService *hdaService, SInt32 *score) {
if (!ADDPR(startSuccess))
return nullptr;
if (!hdaService) {
DBGLOG("audio", "received null digitial audio device");
return nullptr;
}
uint32_t hdaVen, hdaDev;
if (!WIOKit::getOSDataValue(hdaService, "vendor-id", hdaVen) ||
!WIOKit::getOSDataValue(hdaService, "device-id", hdaDev)) {
SYSLOG("audio", "found an unknown device");
return nullptr;
}
auto hdaPlaneName = hdaService->getName();
DBGLOG("audio", "corrects analog audio for hdef at %s with %04X:%04X",
safeString(hdaPlaneName), hdaVen, hdaDev);
if (hdaVen != WIOKit::VendorID::Intel) {
DBGLOG("audio", "unsupported hdef vendor");
return nullptr;
}
// HDEF device is always named and is not named as B0D3 or HDAU.
bool isAnalog = hdaPlaneName && strcmp(hdaPlaneName, "B0D3") && strcmp(hdaPlaneName, "HDAU");
if (!isAnalog) {
DBGLOG("audio", "found digital audio, ignoring.");
return nullptr;
}
// AppleHDAController only recognises HDEF and HDAU.
if (strcmp(hdaPlaneName, "HDEF")) {
DBGLOG("audio", "fixing audio plane name to HDEF");
WIOKit::renameDevice(hdaService, "HDEF");
}
// Firstly parse our own ID.
// alcid=X has highest priority and overrides any other value.
// alc-layout-id has normal priority and is expected to be used.
// layout-id will be used if both alcid and alc-layout-id are not set.
uint32_t layout = 0;
if (PE_parse_boot_argn("alcid", &layout, sizeof(layout))) {
DBGLOG("audio", "found alc-layout-id override %d", layout);
hdaService->setProperty("alc-layout-id", &layout, sizeof(layout));
} else {
auto alcId = OSDynamicCast(OSData, hdaService->getProperty("alc-layout-id"));
if (alcId && alcId->getLength() == sizeof(uint32_t)) {
DBGLOG("audio", "found normal alc-layout-id %d",
*static_cast<const uint32_t *>(alcId->getBytesNoCopy()));
} else {
auto legacyId = OSDynamicCast(OSData, hdaService->getProperty("layout-id"));
if (legacyId && legacyId->getLength() == sizeof(uint32_t)) {
DBGLOG("audio", "found legacy alc-layout-id (from layout-id) %d",
*static_cast<const uint32_t *>(alcId->getBytesNoCopy()));
hdaService->setProperty("alc-layout-id", legacyId);
}
}
}
// Next parse the ID we will return to AppleHDA.
// alcapplid has highest priority and overrides any other value.
// apple-layout-id has normal priority, you may use it if you need.
// default value (7) will be used if both of the above are not set.
if (PE_parse_boot_argn("alcaaplid", &layout, sizeof(layout))) {
DBGLOG("audio", "found apple-layout-id override %d", layout);
hdaService->setProperty("apple-layout-id", &layout, sizeof(layout));
}
auto appleId = OSDynamicCast(OSData, hdaService->getProperty("apple-layout-id"));
if (appleId && appleId->getLength() == sizeof(uint32_t)) {
DBGLOG("audio", "found apple-layout-id %d",
*static_cast<const uint32_t *>(appleId->getBytesNoCopy()));
hdaService->setProperty("layout-id", appleId);
} else {
DBGLOG("audiop", "defaulting apple-layout-id to 7");
layout = 7;
hdaService->setProperty("layout-id", &layout, sizeof(layout));
hdaService->setProperty("apple-layout-id", &layout, sizeof(layout));
}
if (!hdaService->getProperty("built-in")) {
DBGLOG("audio", "fixing built-in in hdef");
uint8_t builtBytes[] { 0x00 };
hdaService->setProperty("built-in", builtBytes, sizeof(builtBytes));
} else {
DBGLOG("audio", "found existing built-in in hdef");
}
// These seem to fix AppleHDA warnings, perhaps research them later.
// They are probably related to the current volume of the boot bell sound.
if (!hdaService->getProperty("MaximumBootBeepVolume")) {
DBGLOG("audio", "fixing MaximumBootBeepVolume in hdef");
uint8_t bootBeepBytes[] { 0xEE };
hdaService->setProperty("MaximumBootBeepVolume", bootBeepBytes, sizeof(bootBeepBytes));
}
if (!hdaService->getProperty("MaximumBootBeepVolumeAlt")) {
DBGLOG("audio", "fixing MaximumBootBeepVolumeAlt in hdef");
uint8_t bootBeepBytes[] { 0xEE };
hdaService->setProperty("MaximumBootBeepVolumeAlt", bootBeepBytes, sizeof(bootBeepBytes));
}
if (!hdaService->getProperty("PinConfigurations")) {
DBGLOG("audio", "fixing PinConfigurations in hdef");
uint8_t pinBytes[] { 0x00 };
hdaService->setProperty("PinConfigurations", pinBytes, sizeof(pinBytes));
}
return nullptr;
}
<commit_msg>Avoid a possible null pointer dereference with -alcdbg<commit_after>//
// kern_audio.cpp
// AppleALC
//
// Copyright © 2018 vit9696. All rights reserved.
//
#include <Headers/kern_iokit.hpp>
#include <Headers/plugin_start.hpp>
#include "kern_audio.hpp"
OSDefineMetaClassAndStructors(AppleALCAudio, IOService)
IOService *AppleALCAudio::probe(IOService *hdaService, SInt32 *score) {
if (!ADDPR(startSuccess))
return nullptr;
if (!hdaService) {
DBGLOG("audio", "received null digitial audio device");
return nullptr;
}
uint32_t hdaVen, hdaDev;
if (!WIOKit::getOSDataValue(hdaService, "vendor-id", hdaVen) ||
!WIOKit::getOSDataValue(hdaService, "device-id", hdaDev)) {
SYSLOG("audio", "found an unknown device");
return nullptr;
}
auto hdaPlaneName = hdaService->getName();
DBGLOG("audio", "corrects analog audio for hdef at %s with %04X:%04X",
safeString(hdaPlaneName), hdaVen, hdaDev);
if (hdaVen != WIOKit::VendorID::Intel) {
DBGLOG("audio", "unsupported hdef vendor");
return nullptr;
}
// HDEF device is always named and is not named as B0D3 or HDAU.
bool isAnalog = hdaPlaneName && strcmp(hdaPlaneName, "B0D3") && strcmp(hdaPlaneName, "HDAU");
if (!isAnalog) {
DBGLOG("audio", "found digital audio, ignoring.");
return nullptr;
}
// AppleHDAController only recognises HDEF and HDAU.
if (strcmp(hdaPlaneName, "HDEF")) {
DBGLOG("audio", "fixing audio plane name to HDEF");
WIOKit::renameDevice(hdaService, "HDEF");
}
// Firstly parse our own ID.
// alcid=X has highest priority and overrides any other value.
// alc-layout-id has normal priority and is expected to be used.
// layout-id will be used if both alcid and alc-layout-id are not set.
uint32_t layout = 0;
if (PE_parse_boot_argn("alcid", &layout, sizeof(layout))) {
DBGLOG("audio", "found alc-layout-id override %d", layout);
hdaService->setProperty("alc-layout-id", &layout, sizeof(layout));
} else {
auto alcId = OSDynamicCast(OSData, hdaService->getProperty("alc-layout-id"));
if (alcId && alcId->getLength() == sizeof(uint32_t)) {
DBGLOG("audio", "found normal alc-layout-id %d",
*static_cast<const uint32_t *>(alcId->getBytesNoCopy()));
} else {
auto legacyId = OSDynamicCast(OSData, hdaService->getProperty("layout-id"));
if (legacyId && legacyId->getLength() == sizeof(uint32_t)) {
DBGLOG("audio", "found legacy alc-layout-id (from layout-id) %d",
*static_cast<const uint32_t *>(legacyId->getBytesNoCopy()));
hdaService->setProperty("alc-layout-id", legacyId);
}
}
}
// Next parse the ID we will return to AppleHDA.
// alcapplid has highest priority and overrides any other value.
// apple-layout-id has normal priority, you may use it if you need.
// default value (7) will be used if both of the above are not set.
if (PE_parse_boot_argn("alcaaplid", &layout, sizeof(layout))) {
DBGLOG("audio", "found apple-layout-id override %d", layout);
hdaService->setProperty("apple-layout-id", &layout, sizeof(layout));
}
auto appleId = OSDynamicCast(OSData, hdaService->getProperty("apple-layout-id"));
if (appleId && appleId->getLength() == sizeof(uint32_t)) {
DBGLOG("audio", "found apple-layout-id %d",
*static_cast<const uint32_t *>(appleId->getBytesNoCopy()));
hdaService->setProperty("layout-id", appleId);
} else {
DBGLOG("audiop", "defaulting apple-layout-id to 7");
layout = 7;
hdaService->setProperty("layout-id", &layout, sizeof(layout));
hdaService->setProperty("apple-layout-id", &layout, sizeof(layout));
}
if (!hdaService->getProperty("built-in")) {
DBGLOG("audio", "fixing built-in in hdef");
uint8_t builtBytes[] { 0x00 };
hdaService->setProperty("built-in", builtBytes, sizeof(builtBytes));
} else {
DBGLOG("audio", "found existing built-in in hdef");
}
// These seem to fix AppleHDA warnings, perhaps research them later.
// They are probably related to the current volume of the boot bell sound.
if (!hdaService->getProperty("MaximumBootBeepVolume")) {
DBGLOG("audio", "fixing MaximumBootBeepVolume in hdef");
uint8_t bootBeepBytes[] { 0xEE };
hdaService->setProperty("MaximumBootBeepVolume", bootBeepBytes, sizeof(bootBeepBytes));
}
if (!hdaService->getProperty("MaximumBootBeepVolumeAlt")) {
DBGLOG("audio", "fixing MaximumBootBeepVolumeAlt in hdef");
uint8_t bootBeepBytes[] { 0xEE };
hdaService->setProperty("MaximumBootBeepVolumeAlt", bootBeepBytes, sizeof(bootBeepBytes));
}
if (!hdaService->getProperty("PinConfigurations")) {
DBGLOG("audio", "fixing PinConfigurations in hdef");
uint8_t pinBytes[] { 0x00 };
hdaService->setProperty("PinConfigurations", pinBytes, sizeof(pinBytes));
}
return nullptr;
}
<|endoftext|> |
<commit_before><commit_msg>-Fixed viewer launching issue on MacOS when passing in Chrome switches<commit_after><|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef SYMBOL_TABLE_H
#define SYMBOL_TABLE_H
#include <memory>
#include <string>
#include <unordered_map>
#include "Variable.hpp"
#include "Function.hpp"
#include "Struct.hpp"
namespace eddic {
typedef std::unordered_map<std::string, std::shared_ptr<Function>> FunctionMap;
typedef std::unordered_map<std::string, std::shared_ptr<Struct>> StructMap;
/*!
* \class SymbolTable
* \brief The global symbol table.
*
* This class is responsible for managing all the functions and the structs declarations of the current program.
* It's also responsible of managing the reference count for the functions.
*/
class SymbolTable {
private:
FunctionMap functions;
StructMap structs;
void addPrintFunction(const std::string& function, BaseType parameterType);
void defineStandardFunctions();
public:
SymbolTable();
SymbolTable(const SymbolTable& rhs) = delete;
/*!
* Reset the symbol table.
*/
void reset();
/*!
* Add the given function to the symbol table.
* \param function The function to add to the symbol table.
*/
void addFunction(std::shared_ptr<Function> function);
/*!
* Returns the function with the given name.
* \param function The function to search for.
* \return A pointer to the function with the given name.
*/
std::shared_ptr<Function> getFunction(const std::string& function);
/*!
* Indicates if a function with the given name exists.
* \param function The function to search for.
* \return true if a function with the given name exists, otherwise false.
*/
bool exists(const std::string& function);
/*!
* Add the given structure to the symbol table.
* \param struct_ The structure to add to the symbol table.
*/
void add_struct(std::shared_ptr<Struct> struct_);
/*!
* Returns the structure with the given name.
* \param struct_ The structure to search for.
* \return A pointer to the structure with the given name.
*/
std::shared_ptr<Struct> get_struct(const std::string& struct_
/*!
* Indicates if a structure with the given name exists.
* \param struct_ The structure to search for.
* \return true if a structure with the given name exists, otherwise false.
*/
bool struct_exists(const std::string& struct_);
int member_offset(std::shared_ptr<Struct> struct_, const std::string& member);
int member_offset_reverse(std::shared_ptr<Struct> struct_, const std::string& member);
int size_of_struct(const std::string& struct_);
/*!
* Returns an iterator to the first function.
* \return An iterator to the first function.
*/
FunctionMap::const_iterator begin();
/*!
* Returns an iterator past the last function.
* \return An iterator past the last function.
*/
FunctionMap::const_iterator end();
/*!
* Add a reference to the function with the given name.
* \param function The function to add a reference to.
*/
void addReference(const std::string& function);
/*!
* Get the reference counter of the given function.
* \param function The function to add a reference to.
* \return The reference counter of the given function.
*/
int referenceCount(const std::string& function);
};
/*!
* The global symbol table.
*/
extern SymbolTable symbols;
} //end of eddic
#endif
<commit_msg>Fix typo<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#ifndef SYMBOL_TABLE_H
#define SYMBOL_TABLE_H
#include <memory>
#include <string>
#include <unordered_map>
#include "Variable.hpp"
#include "Function.hpp"
#include "Struct.hpp"
namespace eddic {
typedef std::unordered_map<std::string, std::shared_ptr<Function>> FunctionMap;
typedef std::unordered_map<std::string, std::shared_ptr<Struct>> StructMap;
/*!
* \class SymbolTable
* \brief The global symbol table.
*
* This class is responsible for managing all the functions and the structs declarations of the current program.
* It's also responsible of managing the reference count for the functions.
*/
class SymbolTable {
private:
FunctionMap functions;
StructMap structs;
void addPrintFunction(const std::string& function, BaseType parameterType);
void defineStandardFunctions();
public:
SymbolTable();
SymbolTable(const SymbolTable& rhs) = delete;
/*!
* Reset the symbol table.
*/
void reset();
/*!
* Add the given function to the symbol table.
* \param function The function to add to the symbol table.
*/
void addFunction(std::shared_ptr<Function> function);
/*!
* Returns the function with the given name.
* \param function The function to search for.
* \return A pointer to the function with the given name.
*/
std::shared_ptr<Function> getFunction(const std::string& function);
/*!
* Indicates if a function with the given name exists.
* \param function The function to search for.
* \return true if a function with the given name exists, otherwise false.
*/
bool exists(const std::string& function);
/*!
* Add the given structure to the symbol table.
* \param struct_ The structure to add to the symbol table.
*/
void add_struct(std::shared_ptr<Struct> struct_);
/*!
* Returns the structure with the given name.
* \param struct_ The structure to search for.
* \return A pointer to the structure with the given name.
*/
std::shared_ptr<Struct> get_struct(const std::string& struct_);
/*!
* Indicates if a structure with the given name exists.
* \param struct_ The structure to search for.
* \return true if a structure with the given name exists, otherwise false.
*/
bool struct_exists(const std::string& struct_);
int member_offset(std::shared_ptr<Struct> struct_, const std::string& member);
int member_offset_reverse(std::shared_ptr<Struct> struct_, const std::string& member);
int size_of_struct(const std::string& struct_);
/*!
* Returns an iterator to the first function.
* \return An iterator to the first function.
*/
FunctionMap::const_iterator begin();
/*!
* Returns an iterator past the last function.
* \return An iterator past the last function.
*/
FunctionMap::const_iterator end();
/*!
* Add a reference to the function with the given name.
* \param function The function to add a reference to.
*/
void addReference(const std::string& function);
/*!
* Get the reference counter of the given function.
* \param function The function to add a reference to.
* \return The reference counter of the given function.
*/
int referenceCount(const std::string& function);
};
/*!
* The global symbol table.
*/
extern SymbolTable symbols;
} //end of eddic
#endif
<|endoftext|> |
<commit_before>#pragma once
#include <algorithm>
#include <iterator>
namespace aid {
// worst case: n^2
// average case: n^2
// best case: n^2
// space complexity: 1
template<typename It>
void bubble_sort(It first, It last) {
for (auto it = std::prev(last); it != first; --it)
for (auto it2 = first; it2 != it; ++it2)
if (*it2 > *std::next(it2))
std::iter_swap(it2, std::next(it2));
}
}
<commit_msg>Added insertion sort<commit_after>#pragma once
#include <algorithm>
#include <iterator>
namespace aid {
// worst case: n^2
// average case: n^2
// best case: n^2
// space complexity: 1
template<typename It>
void bubble_sort(It first, It last) {
for (auto it = std::prev(last); it != first; --it)
for (auto it2 = first; it2 != it; ++it2)
if (*it2 > *std::next(it2))
std::iter_swap(it2, std::next(it2));
}
// worst case: n^2
// average case: n^2
// best case: n
// space complexity: 1
template<typename It>
void insertion_sort(It first, It last) {
for (auto it = std::next(first); it != last; ++it)
for (auto it2 = it; it2 != first && *std::prev(it2) > *it2; --it2)
std::iter_swap(std::prev(it2), it2);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010-2012 frankee zhou (frankee.zhou at gmail dot com)
*
* Distributed under 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 <cetty/shuttle/ShuttleBackend.h>
#include <cetty/handler/codec/LengthFieldBasedFrameDecoder.h>
#include <cetty/handler/codec/LengthFieldPrepender.h>
#include <cetty/service/builder/ClientBuilder.h>
#include <cetty/protobuf/service/ProtobufUtil.h>
#include <cetty/protobuf/service/ProtobufServicePtr.h>
#include <cetty/shuttle/protobuf/ProtobufProxyCodec.h>
#include <cetty/shuttle/protobuf/ProtobufProxyMessage.h>
namespace cetty {
namespace shuttle {
using namespace cetty::handler::codec;
using namespace cetty::service::builder;
using namespace cetty::protobuf::service;
using namespace cetty::shuttle::protobuf;
cetty::channel::ChannelPtr ShuttleBackend::emptyChannel_;
std::map<ThreadId, ShuttleBackendPtr> ShuttleBackend::backends_;
bool ShuttleBackend::initializeChannel(ChannelPipeline& pipeline) {
pipeline.addLast<LengthFieldBasedFrameDecoder::Handler>(
"frameDecoder",
LengthFieldBasedFrameDecoder::HandlerPtr(new LengthFieldBasedFrameDecoder(
16 * 1024 * 1024,
0,
4,
0,
4,
4,
ProtobufUtil::adler32Checksum)));
pipeline.addLast<LengthFieldPrepender::Handler>(
"frameEncoder",
LengthFieldPrepender::HandlerPtr(new LengthFieldPrepender(
4,
4,
ProtobufUtil::adler32Checksum)));
pipeline.addLast<ProtobufProxyCodec::Handler>(
"protobufCodec",
ProtobufProxyCodec::HandlerPtr(new ProtobufProxyCodec));
return true;
}
void ShuttleBackend::configure(const std::map<std::string, Backend*>& config, const EventLoopPoolPtr& pool) {
EventLoopPool::Iterator itr = pool->begin();
for (; itr != pool->end(); ++itr) {
ShuttleBackendPtr backend = ShuttleBackendPtr(new ShuttleBackend(*itr));
backend->configure(config);
backends_.insert(std::make_pair((*itr)->threadId(), backend));
}
}
void ShuttleBackend::configure(const std::map<std::string, Backend*>& config) {
std::map<std::string, Backend*>::const_iterator itr;
for (itr = config.begin(); itr != config.end(); ++itr) {
channels_.insert(std::make_pair(itr->first,
builder_.build(itr->second->servers)));
}
}
const ChannelPtr& ShuttleBackend::getChannel(const std::string& method) {
std::map<ThreadId, ShuttleBackendPtr>::const_iterator itr =
backends_.find(CurrentThread::id());
if (itr != backends_.end()) {
return itr->second->channel(method);
}
else {
return emptyChannel_;
}
}
const ChannelPtr& ShuttleBackend::channel(const std::string& method) const {
std::map<std::string, ChannelPtr>::const_iterator itr =
channels_.find(method);
if (itr != channels_.end()) {
return itr->second;
}
return emptyChannel_;
}
ShuttleBackend::ShuttleBackend(const EventLoopPtr& loop)
: builder_(loop) {
init();
}
void ShuttleBackend::init() {
builder_.setClientInitializer(
boost::bind(&ShuttleBackend::initializeChannel, this, _1));
}
}
}
<commit_msg>添加debug日志<commit_after>/*
* Copyright (c) 2010-2012 frankee zhou (frankee.zhou at gmail dot com)
*
* Distributed under 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 <cetty/shuttle/ShuttleBackend.h>
#include <cetty/handler/codec/LengthFieldBasedFrameDecoder.h>
#include <cetty/handler/codec/LengthFieldPrepender.h>
#include <cetty/service/builder/ClientBuilder.h>
#include <cetty/protobuf/service/ProtobufUtil.h>
#include <cetty/protobuf/service/ProtobufServicePtr.h>
#include <cetty/shuttle/protobuf/ProtobufProxyCodec.h>
#include <cetty/shuttle/protobuf/ProtobufProxyMessage.h>
namespace cetty {
namespace shuttle {
using namespace cetty::handler::codec;
using namespace cetty::service::builder;
using namespace cetty::protobuf::service;
using namespace cetty::shuttle::protobuf;
cetty::channel::ChannelPtr ShuttleBackend::emptyChannel_;
std::map<ThreadId, ShuttleBackendPtr> ShuttleBackend::backends_;
bool ShuttleBackend::initializeChannel(ChannelPipeline& pipeline) {
pipeline.addLast<LengthFieldBasedFrameDecoder::Handler>(
"frameDecoder",
LengthFieldBasedFrameDecoder::HandlerPtr(new LengthFieldBasedFrameDecoder(
16 * 1024 * 1024,
0,
4,
0,
4,
4,
ProtobufUtil::adler32Checksum)));
pipeline.addLast<LengthFieldPrepender::Handler>(
"frameEncoder",
LengthFieldPrepender::HandlerPtr(new LengthFieldPrepender(
4,
4,
ProtobufUtil::adler32Checksum)));
pipeline.addLast<ProtobufProxyCodec::Handler>(
"protobufCodec",
ProtobufProxyCodec::HandlerPtr(new ProtobufProxyCodec));
return true;
}
void ShuttleBackend::configure(const std::map<std::string, Backend*>& config,
const EventLoopPoolPtr& pool) {
EventLoopPool::Iterator itr = pool->begin();
for (; itr != pool->end(); ++itr) {
ShuttleBackendPtr backend = ShuttleBackendPtr(new ShuttleBackend(*itr));
backend->configure(config);
ThreadId id = (*itr)->threadId();
backends_.insert(std::make_pair(id, backend));
LOG_DEBUG << "config backend for " << id;
}
}
void ShuttleBackend::configure(const std::map<std::string, Backend*>& config) {
std::map<std::string, Backend*>::const_iterator itr;
for (itr = config.begin(); itr != config.end(); ++itr) {
channels_.insert(std::make_pair(itr->first,
builder_.build(itr->second->servers)));
LOG_DEBUG << "config the channel in backend for " << itr->first;
}
}
const ChannelPtr& ShuttleBackend::getChannel(const std::string& method) {
ThreadId id = CurrentThread::id();
std::map<ThreadId, ShuttleBackendPtr>::const_iterator itr =
backends_.find(id);
if (itr != backends_.end()) {
return itr->second->channel(method);
}
else {
LOG_WARN << "failed to found the channel for " << method
<< " in " << id;
return emptyChannel_;
}
}
const ChannelPtr& ShuttleBackend::channel(const std::string& method) const {
std::map<std::string, ChannelPtr>::const_iterator itr =
channels_.find(method);
if (itr != channels_.end()) {
return itr->second;
}
else {
LOG_WARN << "failed to found the channel for " << method;
return emptyChannel_;
}
}
ShuttleBackend::ShuttleBackend(const EventLoopPtr& loop)
: builder_(loop) {
init();
}
void ShuttleBackend::init() {
builder_.setClientInitializer(
boost::bind(&ShuttleBackend::initializeChannel, this, _1));
}
}
}
<|endoftext|> |
<commit_before>/*
* This file is part of `et engine`
* Copyright 2009-2013 by Sergey Reznik
* Please, do not modify content without approval.
*
*/
#include <et/geometry/geometry.h>
#include <et/app/application.h>
#include <et/input/gestures.h>
using namespace et;
const float GesturesRecognizer::defaultClickTemporalThreshold = 0.25f;
const float GesturesRecognizer::defaultClickSpatialTreshold = 0.015f;
const float GesturesRecognizer::defaultHoldTemporalThreshold = 1.0f;
GesturesRecognizer::GesturesRecognizer(bool automaticMode) : InputHandler(automaticMode),
_clickTemporalThreshold(defaultClickTemporalThreshold),
_clickSpatialThreshold(defaultClickSpatialTreshold),
_holdTemporalThreshold(defaultHoldTemporalThreshold)
{
}
void GesturesRecognizer::handlePointersMovement()
{
if (_pointers.size() == 2)
{
vec2 currentPositions[2];
vec2 previousPositions[2];
size_t index = 0;
for (auto& i : _pointers)
{
currentPositions[index] = i.second.current.normalizedPos;
previousPositions[index] = i.second.previous.normalizedPos;
i.second.moved = false;
++index;
}
vec2 dir0 = currentPositions[0] - previousPositions[0];
vec2 dir1 = currentPositions[1] - previousPositions[1];
vec2 center = 0.5f * (previousPositions[0] + previousPositions[1]);
RecognizedGesture gesture = _gesture;
if (gesture == RecognizedGesture_NoGesture)
{
vec2 nDir0 = normalize(dir0);
vec2 nDir1 = normalize(dir1);
float direction = dot(nDir0, nDir1);
if (direction < -0.5f)
{
bool catchZoom = (_recognizedGestures & RecognizedGesture_Zoom) == RecognizedGesture_Zoom;
bool catchRotate = (_recognizedGestures & RecognizedGesture_Rotate) == RecognizedGesture_Rotate;
if (catchZoom && catchRotate)
{
float aspect = std::abs(dot(nDir0, normalize(previousPositions[0] - center))) +
std::abs(dot(nDir1, normalize(previousPositions[1] - center)));
gesture = (aspect > SQRT_3) ? RecognizedGesture_Zoom : RecognizedGesture_Rotate;
}
else if (catchZoom)
{
gesture = RecognizedGesture_Zoom;
}
else if (catchRotate)
{
gesture = RecognizedGesture_Rotate;
}
}
else if ((direction > 0.5f) && (_recognizedGestures & RecognizedGesture_Swipe))
{
gesture = RecognizedGesture_Swipe;
}
}
switch (gesture)
{
case RecognizedGesture_Zoom:
{
float zoomValue = (currentPositions[0] - currentPositions[1]).length() /
(previousPositions[0] - previousPositions[1]).length();
zoomAroundPoint.invoke(zoomValue, center);
zoom.invoke(zoomValue);
break;
}
case RecognizedGesture_Rotate:
{
vec2 centerToCurrent0 = currentPositions[0] - center;
vec2 centerToCurrent1 = currentPositions[1] - center;
float angle0 = std::atan2(dir0.length(), centerToCurrent0.length());
float angle1 = std::atan2(dir1.length(), centerToCurrent1.length());
float angleValue = (outerProduct(centerToCurrent0, dir0) < 0.0f ? 0.5f : -0.5f) * (angle0 + angle1);
rotate.invoke(angleValue);
break;
}
case RecognizedGesture_Swipe:
{
swipe.invoke(0.5f * (dir0 + dir1), 2);
break;
}
default:
break;
}
if (_lockGestures)
_gesture = gesture;
}
}
void GesturesRecognizer::cancelWaitingForClicks()
{
_shouldPerformClick = false;
_shouldPerformDoubleClick = false;
_singlePointer = PointerInputInfo();
cancelUpdates();
}
void GesturesRecognizer::update(float t)
{
if (t - _singlePointer.timestamp >= _clickTemporalThreshold)
{
click.invoke(_singlePointer);
cancelWaitingForClicks();
}
}
void GesturesRecognizer::onPointerPressed(et::PointerInputInfo pi)
{
pointerPressed.invoke(pi);
_pointers[pi.id] = PointersInputDelta(pi, pi);
pressed.invoke(pi.normalizedPos, pi.type);
if (_pointers.size() == 1)
{
if (_shouldPerformClick)
{
float dp = (pi.normalizedPos - _singlePointer.normalizedPos).dotSelf();
if (dp <= sqr(_clickSpatialThreshold))
{
_shouldPerformClick = false;
_shouldPerformDoubleClick = true;
}
else
{
click.invoke(_singlePointer);
_singlePointer = pi;
_shouldPerformClick = true;
_shouldPerformDoubleClick = false;
}
}
else
{
_shouldPerformClick = true;
_singlePointer = pi;
}
_singlePointer.id = pi.id;
}
else
{
_singlePointer = PointerInputInfo();
cancelWaitingForClicks();
}
}
void GesturesRecognizer::onPointerMoved(et::PointerInputInfo pi)
{
pointerMoved.invoke(pi);
if ((pi.id == 0) || (_pointers.count(pi.id) == 0)) return;
if (_pointers.size() == 1)
{
bool hasPressedPointer = (_singlePointer.id != 0);
bool shouldPerformMovement = !hasPressedPointer;
if (hasPressedPointer && (pi.id == _singlePointer.id))
{
float len = (pi.normalizedPos - _singlePointer.normalizedPos).dotSelf();
shouldPerformMovement = (len >= sqr(_clickSpatialThreshold));
}
if (shouldPerformMovement)
{
if (hasPressedPointer)
{
cancelWaitingForClicks();
clickCancelled.invoke();
}
_pointers[pi.id].moved = true;
_pointers[pi.id].previous = _pointers[pi.id].current;
_pointers[pi.id].current = pi;
const PointerInputInfo& pPrev = _pointers[pi.id].previous;
const PointerInputInfo& pCurr = _pointers[pi.id].current;
vec2 offset = pCurr.normalizedPos - pPrev.normalizedPos;
vec2 speed = offset / etMax(0.01f, pCurr.timestamp - pPrev.timestamp);
moved.invoke(pi.normalizedPos, pi.type);
if (pCurr.type == PointerType_General)
dragWithGeneralPointer.invokeInMainRunLoop(speed, offset);
drag.invoke(speed, pi.type);
}
}
else
{
cancelWaitingForClicks();
_pointers[pi.id].moved = true;
_pointers[pi.id].previous = _pointers[pi.id].current;
_pointers[pi.id].current = pi;
bool allMoved = true;
for (auto& p : _pointers)
{
if (!p.second.moved)
{
allMoved = false;
break;
}
};
if (allMoved)
handlePointersMovement();
}
}
void GesturesRecognizer::onPointerReleased(et::PointerInputInfo pi)
{
pointerReleased.invoke(pi);
_gesture = RecognizedGesture_NoGesture;
_pointers.erase(pi.id);
released.invoke(pi.normalizedPos, pi.type);
if (pi.id == _singlePointer.id)
{
if ((pi.normalizedPos - _singlePointer.normalizedPos).dotSelf() > sqr(_clickSpatialThreshold))
{
cancelWaitingForClicks();
}
else if (_shouldPerformClick)
{
float dt = pi.timestamp - _singlePointer.timestamp;
if ((dt > _clickTemporalThreshold))
{
click.invoke(_singlePointer);
cancelWaitingForClicks();
}
else
{
startUpdates();
}
}
else if (_shouldPerformDoubleClick)
{
doubleClick.invoke(_singlePointer);
cancelWaitingForClicks();
}
}
}
void GesturesRecognizer::onPointerCancelled(et::PointerInputInfo pi)
{
pointerCancelled.invoke(pi);
_pointers.erase(pi.id);
cancelled.invoke(pi.normalizedPos, pi.type);
if (pi.id == _singlePointer.id)
cancelWaitingForClicks();
}
void GesturesRecognizer::onPointerScrolled(et::PointerInputInfo i)
{
pointerScrolled.invoke(i);
scroll.invoke(i.scroll, i.origin);
}
void GesturesRecognizer::onGesturePerformed(GestureInputInfo i)
{
if (i.mask & GestureTypeMask_Zoom)
zoom.invoke(1.0f - i.values.z);
if (i.mask & GestureTypeMask_Swipe)
drag.invoke(i.values.xy(), PointerType_None);
if (i.mask & GestureTypeMask_Rotate)
rotate.invokeInMainRunLoop(i.values.w);
}
void GesturesRecognizer::setRecognizedGestures(size_t values)
{
_recognizedGestures = values;
if ((values & _gesture) == 0)
_gesture = RecognizedGesture_NoGesture;
}
<commit_msg>gestures default threshold changed<commit_after>/*
* This file is part of `et engine`
* Copyright 2009-2013 by Sergey Reznik
* Please, do not modify content without approval.
*
*/
#include <et/geometry/geometry.h>
#include <et/app/application.h>
#include <et/input/gestures.h>
using namespace et;
const float GesturesRecognizer::defaultClickTemporalThreshold = 0.25f;
const float GesturesRecognizer::defaultClickSpatialTreshold = std::sqrt(50.0f);
const float GesturesRecognizer::defaultHoldTemporalThreshold = 1.0f;
GesturesRecognizer::GesturesRecognizer(bool automaticMode) : InputHandler(automaticMode),
_clickTemporalThreshold(defaultClickTemporalThreshold),
_clickSpatialThreshold(defaultClickSpatialTreshold),
_holdTemporalThreshold(defaultHoldTemporalThreshold)
{
}
void GesturesRecognizer::handlePointersMovement()
{
if (_pointers.size() == 2)
{
vec2 currentPositions[2];
vec2 previousPositions[2];
size_t index = 0;
for (auto& i : _pointers)
{
currentPositions[index] = i.second.current.normalizedPos;
previousPositions[index] = i.second.previous.normalizedPos;
i.second.moved = false;
++index;
}
vec2 dir0 = currentPositions[0] - previousPositions[0];
vec2 dir1 = currentPositions[1] - previousPositions[1];
vec2 center = 0.5f * (previousPositions[0] + previousPositions[1]);
RecognizedGesture gesture = _gesture;
if (gesture == RecognizedGesture_NoGesture)
{
vec2 nDir0 = normalize(dir0);
vec2 nDir1 = normalize(dir1);
float direction = dot(nDir0, nDir1);
if (direction < -0.5f)
{
bool catchZoom = (_recognizedGestures & RecognizedGesture_Zoom) == RecognizedGesture_Zoom;
bool catchRotate = (_recognizedGestures & RecognizedGesture_Rotate) == RecognizedGesture_Rotate;
if (catchZoom && catchRotate)
{
float aspect = std::abs(dot(nDir0, normalize(previousPositions[0] - center))) +
std::abs(dot(nDir1, normalize(previousPositions[1] - center)));
gesture = (aspect > SQRT_3) ? RecognizedGesture_Zoom : RecognizedGesture_Rotate;
}
else if (catchZoom)
{
gesture = RecognizedGesture_Zoom;
}
else if (catchRotate)
{
gesture = RecognizedGesture_Rotate;
}
}
else if ((direction > 0.5f) && (_recognizedGestures & RecognizedGesture_Swipe))
{
gesture = RecognizedGesture_Swipe;
}
}
switch (gesture)
{
case RecognizedGesture_Zoom:
{
float zoomValue = (currentPositions[0] - currentPositions[1]).length() /
(previousPositions[0] - previousPositions[1]).length();
zoomAroundPoint.invoke(zoomValue, center);
zoom.invoke(zoomValue);
break;
}
case RecognizedGesture_Rotate:
{
vec2 centerToCurrent0 = currentPositions[0] - center;
vec2 centerToCurrent1 = currentPositions[1] - center;
float angle0 = std::atan2(dir0.length(), centerToCurrent0.length());
float angle1 = std::atan2(dir1.length(), centerToCurrent1.length());
float angleValue = (outerProduct(centerToCurrent0, dir0) < 0.0f ? 0.5f : -0.5f) * (angle0 + angle1);
rotate.invoke(angleValue);
break;
}
case RecognizedGesture_Swipe:
{
swipe.invoke(0.5f * (dir0 + dir1), 2);
break;
}
default:
break;
}
if (_lockGestures)
_gesture = gesture;
}
}
void GesturesRecognizer::cancelWaitingForClicks()
{
_shouldPerformClick = false;
_shouldPerformDoubleClick = false;
_singlePointer = PointerInputInfo();
cancelUpdates();
}
void GesturesRecognizer::update(float t)
{
if (t - _singlePointer.timestamp >= _clickTemporalThreshold)
{
click.invoke(_singlePointer);
cancelWaitingForClicks();
}
}
void GesturesRecognizer::onPointerPressed(et::PointerInputInfo pi)
{
pointerPressed.invoke(pi);
_pointers[pi.id] = PointersInputDelta(pi, pi);
pressed.invoke(pi.normalizedPos, pi.type);
if (_pointers.size() == 1)
{
if (_shouldPerformClick)
{
if ((pi.pos - _singlePointer.pos).dotSelf() <= sqr(_clickSpatialThreshold))
{
_shouldPerformClick = false;
_shouldPerformDoubleClick = true;
}
else
{
click.invoke(_singlePointer);
_singlePointer = pi;
_shouldPerformClick = true;
_shouldPerformDoubleClick = false;
}
}
else
{
_shouldPerformClick = true;
_singlePointer = pi;
}
_singlePointer.id = pi.id;
}
else
{
_singlePointer = PointerInputInfo();
cancelWaitingForClicks();
}
}
void GesturesRecognizer::onPointerMoved(et::PointerInputInfo pi)
{
pointerMoved.invoke(pi);
if ((pi.id == 0) || (_pointers.count(pi.id) == 0)) return;
if (_pointers.size() == 1)
{
bool hasPressedPointer = (_singlePointer.id != 0);
bool shouldPerformMovement = !hasPressedPointer;
if (hasPressedPointer && (pi.id == _singlePointer.id))
{
float len = (pi.pos - _singlePointer.pos).dotSelf();
shouldPerformMovement = (len >= sqr(_clickSpatialThreshold));
}
if (shouldPerformMovement)
{
if (hasPressedPointer)
{
cancelWaitingForClicks();
clickCancelled.invoke();
}
_pointers[pi.id].moved = true;
_pointers[pi.id].previous = _pointers[pi.id].current;
_pointers[pi.id].current = pi;
const PointerInputInfo& pPrev = _pointers[pi.id].previous;
const PointerInputInfo& pCurr = _pointers[pi.id].current;
vec2 offset = pCurr.normalizedPos - pPrev.normalizedPos;
vec2 speed = offset / etMax(0.01f, pCurr.timestamp - pPrev.timestamp);
moved.invoke(pi.normalizedPos, pi.type);
if (pCurr.type == PointerType_General)
dragWithGeneralPointer.invokeInMainRunLoop(speed, offset);
drag.invoke(speed, pi.type);
}
}
else
{
cancelWaitingForClicks();
_pointers[pi.id].moved = true;
_pointers[pi.id].previous = _pointers[pi.id].current;
_pointers[pi.id].current = pi;
bool allMoved = true;
for (auto& p : _pointers)
{
if (!p.second.moved)
{
allMoved = false;
break;
}
};
if (allMoved)
handlePointersMovement();
}
}
void GesturesRecognizer::onPointerReleased(et::PointerInputInfo pi)
{
pointerReleased.invoke(pi);
_gesture = RecognizedGesture_NoGesture;
_pointers.erase(pi.id);
released.invoke(pi.normalizedPos, pi.type);
if (pi.id == _singlePointer.id)
{
if ((pi.normalizedPos - _singlePointer.normalizedPos).dotSelf() > sqr(_clickSpatialThreshold))
{
cancelWaitingForClicks();
}
else if (_shouldPerformClick)
{
float dt = pi.timestamp - _singlePointer.timestamp;
if ((dt > _clickTemporalThreshold))
{
click.invoke(_singlePointer);
cancelWaitingForClicks();
}
else
{
startUpdates();
}
}
else if (_shouldPerformDoubleClick)
{
doubleClick.invoke(_singlePointer);
cancelWaitingForClicks();
}
}
}
void GesturesRecognizer::onPointerCancelled(et::PointerInputInfo pi)
{
pointerCancelled.invoke(pi);
_pointers.erase(pi.id);
cancelled.invoke(pi.normalizedPos, pi.type);
if (pi.id == _singlePointer.id)
cancelWaitingForClicks();
}
void GesturesRecognizer::onPointerScrolled(et::PointerInputInfo i)
{
pointerScrolled.invoke(i);
scroll.invoke(i.scroll, i.origin);
}
void GesturesRecognizer::onGesturePerformed(GestureInputInfo i)
{
if (i.mask & GestureTypeMask_Zoom)
zoom.invoke(1.0f - i.values.z);
if (i.mask & GestureTypeMask_Swipe)
drag.invoke(i.values.xy(), PointerType_None);
if (i.mask & GestureTypeMask_Rotate)
rotate.invokeInMainRunLoop(i.values.w);
}
void GesturesRecognizer::setRecognizedGestures(size_t values)
{
_recognizedGestures = values;
if ((values & _gesture) == 0)
_gesture = RecognizedGesture_NoGesture;
}
<|endoftext|> |
<commit_before>#include "BasicTexture.h"
BasicTexture::BasicTexture(const std::string& file)
{
loadFromFile(file);
}
void BasicTexture::loadFromImage(const sf::Image& i)
{
glGenTextures(1, &m_id);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, i.getSize().x, i.getSize().y,
0, GL_RGBA, GL_UNSIGNED_BYTE, i.getPixelsPtr());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
}
void BasicTexture::loadFromFile(const std::string& file)
{
sf::Image i;
if(!i.loadFromFile("Res/Textures/" + file + ".png"))
{
throw std::runtime_error("Unable to load BasicTexture: " + file);
}
loadFromImage(i);
}
BasicTexture::~BasicTexture()
{
glDeleteTextures(1, &m_id);
}
void BasicTexture::bindTexture() const
{
glBindTexture(GL_TEXTURE_2D, m_id);
}
<commit_msg>Modified texture mapping.<commit_after>#include "BasicTexture.h"
BasicTexture::BasicTexture(const std::string& file)
{
loadFromFile(file);
}
void BasicTexture::loadFromImage(const sf::Image& i)
{
glGenTextures(1, &m_id);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, m_id);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, i.getSize().x, i.getSize().y,
0, GL_RGBA, GL_UNSIGNED_BYTE, i.getPixelsPtr());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1);
}
void BasicTexture::loadFromFile(const std::string& file)
{
sf::Image i;
if(!i.loadFromFile("Res/Textures/" + file + ".png"))
{
throw std::runtime_error("Unable to load BasicTexture: " + file);
}
loadFromImage(i);
}
BasicTexture::~BasicTexture()
{
glDeleteTextures(1, &m_id);
}
void BasicTexture::bindTexture() const
{
glBindTexture(GL_TEXTURE_2D, m_id);
}
<|endoftext|> |
<commit_before>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// needed for IDE
#include "DistrhoPluginInfo.h"
#include "DistrhoUI.hpp"
#if defined(DISTRHO_OS_MAC)
# import <Cocoa/Cocoa.h>
#elif defined(DISTRHO_OS_WINDOWS)
#else
# include <sys/types.h>
# include <X11/Xatom.h>
# include <X11/Xlib.h>
# include <X11/Xutil.h>
# define X11Key_Escape 9
#endif
START_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------------------------------------------
class EmbedExternalExampleUI : public UI
{
#if defined(DISTRHO_OS_MAC)
NSView* fView;
id fWindow;
#elif defined(DISTRHO_OS_WINDOWS)
#else
::Display* fDisplay;
::Window fWindow;
#endif
public:
EmbedExternalExampleUI()
: UI(512, 256),
#if defined(DISTRHO_OS_MAC)
fView(nullptr),
fWindow(nil),
#elif defined(DISTRHO_OS_WINDOWS)
#else
fDisplay(nullptr),
fWindow(0),
#endif
fValue(0.0f)
{
#if defined(DISTRHO_OS_MAC)
NSAutoreleasePool* const pool = [[NSAutoreleasePool alloc] init];
[NSApplication sharedApplication];
if (isEmbed())
{
// [fView retain];
// [(NSView*)getParentWindowHandle() fView];
}
else
{
fWindow = [[NSWindow new]retain];
DISTRHO_SAFE_ASSERT_RETURN(fWindow != nil,);
[fWindow setIsVisible:NO];
if (NSString* const nsTitle = [[NSString alloc]
initWithBytes:getTitle()
length:strlen(getTitle())
encoding:NSUTF8StringEncoding])
[fWindow setTitle:nsTitle];
// [fWindow setContentView:impl->view];
// [fWindow makeFirstResponder:impl->view];
[fWindow makeKeyAndOrderFront:fWindow];
}
[pool release];
#elif defined(DISTRHO_OS_WINDOWS)
#else
fDisplay = XOpenDisplay(nullptr);
DISTRHO_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
const int screen = DefaultScreen(fDisplay);
const ::Window root = RootWindow(fDisplay, screen);
const ::Window parent = isEmbed() ? (::Window)getParentWindowHandle() : root;
fWindow = XCreateSimpleWindow(fDisplay, parent, 0, 0, getWidth(), getHeight(), 0, 0, 0);
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
XSizeHints sizeHints = {};
sizeHints.flags = PMinSize;
sizeHints.min_width = getWidth();
sizeHints.min_height = getHeight();
XSetNormalHints(fDisplay, fWindow, &sizeHints);
XStoreName(fDisplay, fWindow, getTitle());
if (parent == root)
{
// grab Esc key for auto-close
XGrabKey(fDisplay, X11Key_Escape, AnyModifier, fWindow, 1, GrabModeAsync, GrabModeAsync);
// destroy window on close
Atom wmDelete = XInternAtom(fDisplay, "WM_DELETE_WINDOW", True);
XSetWMProtocols(fDisplay, fWindow, &wmDelete, 1);
// set pid WM hint
const pid_t pid = getpid();
const Atom _nwp = XInternAtom(fDisplay, "_NET_WM_PID", False);
XChangeProperty(fDisplay, fWindow, _nwp, XA_CARDINAL, 32, PropModeReplace, (const uchar*)&pid, 1);
// set the window to both dialog and normal to produce a decorated floating dialog
// order is important: DIALOG needs to come before NORMAL
const Atom _wt = XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE", False);
const Atom _wts[2] = {
XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE_DIALOG", False),
XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE_NORMAL", False)
};
XChangeProperty(fDisplay, fWindow, _wt, XA_ATOM, 32, PropModeReplace, (const uchar*)&_wts, 2);
}
#endif
}
~EmbedExternalExampleUI()
{
#if defined(DISTRHO_OS_MAC)
if (fWindow != nil)
[fWindow close];
if (fView != nullptr)
[fView release];
if (fWindow != nil)
[fWindow release];
#elif defined(DISTRHO_OS_WINDOWS)
#else
if (fDisplay == nullptr)
return;
if (fWindow != 0)
XDestroyWindow(fDisplay, fWindow);
XCloseDisplay(fDisplay);
#endif
}
protected:
/* --------------------------------------------------------------------------------------------------------
* DSP/Plugin Callbacks */
/**
A parameter has changed on the plugin side.
This is called by the host to inform the UI about parameter changes.
*/
void parameterChanged(uint32_t index, float value) override
{
if (index != 0)
return;
fValue = value;
}
/* --------------------------------------------------------------------------------------------------------
* External Window overrides */
uintptr_t getNativeWindowHandle() const noexcept override
{
#if defined(DISTRHO_OS_MAC)
return (uintptr_t)fView;
#elif defined(DISTRHO_OS_WINDOWS)
#else
return (uintptr_t)fWindow;
#endif
return 0;
}
void titleChanged(const char* const title) override
{
d_stdout("visibilityChanged %s", title);
#if defined(DISTRHO_OS_MAC)
if (fWindow != nil)
{
if (NSString* const nsTitle = [[NSString alloc]
initWithBytes:title
length:strlen(title)
encoding:NSUTF8StringEncoding])
{
[fWindow setTitle:nsTitle];
}
}
#elif defined(DISTRHO_OS_WINDOWS)
#else
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
XStoreName(fDisplay, fWindow, title);
#endif
}
void transientParentWindowChanged(const uintptr_t winId) override
{
d_stdout("transientParentWindowChanged %lu", winId);
#if defined(DISTRHO_OS_MAC)
#elif defined(DISTRHO_OS_WINDOWS)
#else
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
XSetTransientForHint(fDisplay, fWindow, (::Window)winId);
#endif
}
void visibilityChanged(const bool visible) override
{
d_stdout("visibilityChanged %d", visible);
#if defined(DISTRHO_OS_MAC)
if (fWindow != nil)
[fWindow setIsVisible:(visible ? YES : NO)];
else if (fView != nullptr)
[fView setHidden:(visible ? NO : YES)];
#elif defined(DISTRHO_OS_WINDOWS)
#else
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
if (visible)
XMapRaised(fDisplay, fWindow);
else
XUnmapWindow(fDisplay, fWindow);
#endif
}
void uiIdle() override
{
// d_stdout("uiIdle");
#if defined(DISTRHO_OS_MAC)
NSAutoreleasePool* const pool = [[NSAutoreleasePool alloc] init];
NSDate* const date = [NSDate distantPast];
for (NSEvent* event;;)
{
event = [NSApp
nextEventMatchingMask:NSAnyEventMask
untilDate:date
inMode:NSDefaultRunLoopMode
dequeue:YES];
if (event == nil)
break;
[NSApp sendEvent: event];
}
[pool release];
#elif defined(DISTRHO_OS_WINDOWS)
MSG msg;
if (! ::PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE))
return true;
if (::GetMessage(&msg, nullptr, 0, 0) >= 0)
{
if (msg.message == WM_QUIT)
return false;
//TranslateMessage(&msg);
DispatchMessage(&msg);
}
#else
if (fDisplay == nullptr)
return;
for (XEvent event; XPending(fDisplay) > 0;)
{
XNextEvent(fDisplay, &event);
if (! isVisible())
continue;
switch (event.type)
{
case ClientMessage:
if (char* const type = XGetAtomName(fDisplay, event.xclient.message_type))
{
if (std::strcmp(type, "WM_PROTOCOLS") == 0)
hide();
}
break;
case KeyRelease:
if (event.xkey.keycode == X11Key_Escape)
hide();
break;
}
}
#endif
}
// -------------------------------------------------------------------------------------------------------
private:
// Current value, cached for when UI becomes visible
float fValue;
/**
Set our UI class as non-copyable and add a leak detector just in case.
*/
DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(EmbedExternalExampleUI)
};
/* ------------------------------------------------------------------------------------------------------------
* UI entry point, called by DPF to create a new UI instance. */
UI* createUI()
{
return new EmbedExternalExampleUI();
}
// -----------------------------------------------------------------------------------------------------------
END_NAMESPACE_DISTRHO
<commit_msg>More embed-external-ui example macOS code, but still no window :(<commit_after>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// needed for IDE
#include "DistrhoPluginInfo.h"
#include "DistrhoUI.hpp"
#if defined(DISTRHO_OS_MAC)
# import <Cocoa/Cocoa.h>
#elif defined(DISTRHO_OS_WINDOWS)
#else
# include <sys/types.h>
# include <X11/Xatom.h>
# include <X11/Xlib.h>
# include <X11/Xutil.h>
# define X11Key_Escape 9
#endif
#if defined(DISTRHO_OS_MAC)
@interface NSExternalWindow : NSWindow
@end
@implementation NSExternalWindow
- (id)initWithContentRect:(NSRect)contentRect
styleMask:(unsigned long)aStyle
backing:(NSBackingStoreType)bufferingType
defer:(BOOL)flag
{
NSWindow* result = [super initWithContentRect:contentRect
styleMask:aStyle
backing:bufferingType
defer:flag];
[result setAcceptsMouseMovedEvents:YES];
return (NSExternalWindow*)result;
}
- (BOOL)canBecomeKeyWindow
{
return YES;
}
- (BOOL)canBecomeMainWindow
{
return NO;
}
@end
#endif
START_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------------------------------------------
class EmbedExternalExampleUI : public UI
{
#if defined(DISTRHO_OS_MAC)
NSView* fView;
NSExternalWindow* fWindow;
#elif defined(DISTRHO_OS_WINDOWS)
#else
::Display* fDisplay;
::Window fWindow;
#endif
public:
EmbedExternalExampleUI()
: UI(512, 256),
#if defined(DISTRHO_OS_MAC)
fView(nullptr),
fWindow(nullptr),
#elif defined(DISTRHO_OS_WINDOWS)
#else
fDisplay(nullptr),
fWindow(0),
#endif
fValue(0.0f)
{
#if defined(DISTRHO_OS_MAC)
if (isStandalone())
{
[[NSApplication sharedApplication]new];
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
[NSApp activateIgnoringOtherApps:YES];
}
NSAutoreleasePool* const pool = [[NSAutoreleasePool alloc] init];
[NSApplication sharedApplication];
fView = [NSView new];
DISTRHO_SAFE_ASSERT_RETURN(fView != nullptr,);
[fView initWithFrame:NSMakeRect(0, 0, getWidth(), getHeight())];
[fView setAutoresizesSubviews:YES];
[fView setFrame:NSMakeRect(0, 0, getWidth(), getHeight())];
[fView setHidden:NO];
[fView setNeedsDisplay:YES];
if (isEmbed())
{
[fView retain];
[(NSView*)getParentWindowHandle() addSubview:fView];
}
else
{
fWindow = [[[NSExternalWindow alloc]
initWithContentRect:[fView frame]
styleMask:(NSWindowStyleMaskClosable | NSWindowStyleMaskTitled | NSWindowStyleMaskResizable)
backing:NSBackingStoreBuffered
defer:NO]retain];
DISTRHO_SAFE_ASSERT_RETURN(fWindow != nullptr,);
// [fWindow setIsVisible:NO];
if (NSString* const nsTitle = [[NSString alloc]
initWithBytes:getTitle()
length:strlen(getTitle())
encoding:NSUTF8StringEncoding])
[fWindow setTitle:nsTitle];
[fWindow setContentView:fView];
[fWindow setContentSize:NSMakeSize(getWidth(), getHeight())];
[fWindow makeFirstResponder:fView];
[fWindow makeKeyAndOrderFront:fWindow];
d_stdout("created window with size %u %u", getWidth(), getHeight());
}
[pool release];
#elif defined(DISTRHO_OS_WINDOWS)
#else
fDisplay = XOpenDisplay(nullptr);
DISTRHO_SAFE_ASSERT_RETURN(fDisplay != nullptr,);
const int screen = DefaultScreen(fDisplay);
const ::Window root = RootWindow(fDisplay, screen);
const ::Window parent = isEmbed() ? (::Window)getParentWindowHandle() : root;
fWindow = XCreateSimpleWindow(fDisplay, parent, 0, 0, getWidth(), getHeight(), 0, 0, 0);
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
XSizeHints sizeHints = {};
sizeHints.flags = PMinSize;
sizeHints.min_width = getWidth();
sizeHints.min_height = getHeight();
XSetNormalHints(fDisplay, fWindow, &sizeHints);
XStoreName(fDisplay, fWindow, getTitle());
if (parent == root)
{
// grab Esc key for auto-close
XGrabKey(fDisplay, X11Key_Escape, AnyModifier, fWindow, 1, GrabModeAsync, GrabModeAsync);
// destroy window on close
Atom wmDelete = XInternAtom(fDisplay, "WM_DELETE_WINDOW", True);
XSetWMProtocols(fDisplay, fWindow, &wmDelete, 1);
// set pid WM hint
const pid_t pid = getpid();
const Atom _nwp = XInternAtom(fDisplay, "_NET_WM_PID", False);
XChangeProperty(fDisplay, fWindow, _nwp, XA_CARDINAL, 32, PropModeReplace, (const uchar*)&pid, 1);
// set the window to both dialog and normal to produce a decorated floating dialog
// order is important: DIALOG needs to come before NORMAL
const Atom _wt = XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE", False);
const Atom _wts[2] = {
XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE_DIALOG", False),
XInternAtom(fDisplay, "_NET_WM_WINDOW_TYPE_NORMAL", False)
};
XChangeProperty(fDisplay, fWindow, _wt, XA_ATOM, 32, PropModeReplace, (const uchar*)&_wts, 2);
}
#endif
}
~EmbedExternalExampleUI()
{
#if defined(DISTRHO_OS_MAC)
if (fView == nullptr)
return;
if (fWindow != nil)
[fWindow close];
[fView release];
if (fWindow != nil)
[fWindow release];
#elif defined(DISTRHO_OS_WINDOWS)
#else
if (fDisplay == nullptr)
return;
if (fWindow != 0)
XDestroyWindow(fDisplay, fWindow);
XCloseDisplay(fDisplay);
#endif
}
protected:
/* --------------------------------------------------------------------------------------------------------
* DSP/Plugin Callbacks */
/**
A parameter has changed on the plugin side.
This is called by the host to inform the UI about parameter changes.
*/
void parameterChanged(uint32_t index, float value) override
{
if (index != 0)
return;
fValue = value;
}
/* --------------------------------------------------------------------------------------------------------
* External Window overrides */
void focus() override
{
d_stdout("focus");
#if defined(DISTRHO_OS_MAC)
DISTRHO_SAFE_ASSERT_RETURN(fWindow != nil,);
[fWindow orderFrontRegardless];
#elif defined(DISTRHO_OS_WINDOWS)
#else
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
XRaiseWindow(fDisplay, fWindow);
#endif
}
uintptr_t getNativeWindowHandle() const noexcept override
{
#if defined(DISTRHO_OS_MAC)
return (uintptr_t)fView;
#elif defined(DISTRHO_OS_WINDOWS)
#else
return (uintptr_t)fWindow;
#endif
return 0;
}
void titleChanged(const char* const title) override
{
d_stdout("titleChanged %s", title);
#if defined(DISTRHO_OS_MAC)
if (fWindow != nil)
{
if (NSString* const nsTitle = [[NSString alloc]
initWithBytes:title
length:strlen(title)
encoding:NSUTF8StringEncoding])
{
[fWindow setTitle:nsTitle];
[nsTitle release];
}
}
#elif defined(DISTRHO_OS_WINDOWS)
#else
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
XStoreName(fDisplay, fWindow, title);
#endif
}
void transientParentWindowChanged(const uintptr_t winId) override
{
d_stdout("transientParentWindowChanged %lu", winId);
#if defined(DISTRHO_OS_MAC)
#elif defined(DISTRHO_OS_WINDOWS)
#else
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
XSetTransientForHint(fDisplay, fWindow, (::Window)winId);
#endif
}
void visibilityChanged(const bool visible) override
{
d_stdout("visibilityChanged %d", visible);
#if defined(DISTRHO_OS_MAC)
DISTRHO_SAFE_ASSERT_RETURN(fView != nullptr,);
if (fWindow != nil)
[fWindow setIsVisible:(visible ? YES : NO)];
else
[fView setHidden:(visible ? NO : YES)];
#elif defined(DISTRHO_OS_WINDOWS)
#else
DISTRHO_SAFE_ASSERT_RETURN(fWindow != 0,);
if (visible)
XMapRaised(fDisplay, fWindow);
else
XUnmapWindow(fDisplay, fWindow);
#endif
}
void uiIdle() override
{
// d_stdout("uiIdle");
#if defined(DISTRHO_OS_MAC)
NSAutoreleasePool* const pool = [[NSAutoreleasePool alloc] init];
NSDate* const date = [NSDate distantPast];
for (NSEvent* event;;)
{
event = [NSApp
nextEventMatchingMask:NSAnyEventMask
untilDate:date
inMode:NSDefaultRunLoopMode
dequeue:YES];
if (event == nil)
break;
d_stdout("uiIdle with event %p", event);
[NSApp sendEvent:event];
}
[pool release];
#elif defined(DISTRHO_OS_WINDOWS)
MSG msg;
if (! ::PeekMessage(&msg, nullptr, 0, 0, PM_NOREMOVE))
return true;
if (::GetMessage(&msg, nullptr, 0, 0) >= 0)
{
if (msg.message == WM_QUIT)
return false;
//TranslateMessage(&msg);
DispatchMessage(&msg);
}
#else
if (fDisplay == nullptr)
return;
for (XEvent event; XPending(fDisplay) > 0;)
{
XNextEvent(fDisplay, &event);
if (! isVisible())
continue;
switch (event.type)
{
case ClientMessage:
if (char* const type = XGetAtomName(fDisplay, event.xclient.message_type))
{
if (std::strcmp(type, "WM_PROTOCOLS") == 0)
hide();
}
break;
case KeyRelease:
if (event.xkey.keycode == X11Key_Escape)
hide();
break;
}
}
#endif
}
// -------------------------------------------------------------------------------------------------------
private:
// Current value, cached for when UI becomes visible
float fValue;
/**
Set our UI class as non-copyable and add a leak detector just in case.
*/
DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(EmbedExternalExampleUI)
};
/* ------------------------------------------------------------------------------------------------------------
* UI entry point, called by DPF to create a new UI instance. */
UI* createUI()
{
return new EmbedExternalExampleUI();
}
// -----------------------------------------------------------------------------------------------------------
END_NAMESPACE_DISTRHO
<|endoftext|> |
<commit_before>// Class for kernels, llvm::Functions that represent OpenCL C kernels.
//
// Copyright (c) 2011 Universidad Rey Juan Carlos and
// 2012 Pekka Jääskeläinen / TUT
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "Kernel.h"
#include "Barrier.h"
#include <iostream>
#include "config.h"
#ifdef LLVM_3_1
#include "llvm/Support/IRBuilder.h"
#elif defined LLVM_3_2
#include "llvm/IRBuilder.h"
#include "llvm/InlineAsm.h"
#else
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#endif
//#define DEBUG_PR_CREATION
using namespace llvm;
using namespace pocl;
static void add_predecessors(SmallVectorImpl<BasicBlock *> &v,
BasicBlock *b);
static bool verify_no_barriers(const BasicBlock *B);
void
Kernel::getExitBlocks(SmallVectorImpl<BarrierBlock *> &B)
{
for (iterator i = begin(), e = end(); i != e; ++i) {
const TerminatorInst *t = i->getTerminator();
if (t->getNumSuccessors() == 0) {
// All exits must be barrier blocks.
B.push_back(cast<BarrierBlock>(i));
}
}
}
ParallelRegion *
Kernel::createParallelRegionBefore(BarrierBlock *B)
{
SmallVector<BasicBlock *, 4> pending_blocks;
SmallPtrSet<BasicBlock *, 8> blocks_in_region;
BarrierBlock *region_entry_barrier = NULL;
llvm::BasicBlock *entry = NULL;
llvm::BasicBlock *exit = B->getSinglePredecessor();
add_predecessors(pending_blocks, B);
#ifdef DEBUG_PR_CREATION
std::cerr << "createParallelRegionBefore " << B->getName().str() << std::endl;
#endif
while (!pending_blocks.empty()) {
BasicBlock *current = pending_blocks.back();
pending_blocks.pop_back();
#ifdef DEBUG_PR_CREATION
std::cerr << "considering " << current->getName().str() << std::endl;
#endif
// avoid infinite recursion of loops
if (blocks_in_region.count(current) != 0)
{
#ifdef DEBUG_PR_CREATION
std::cerr << "already in the region!" << std::endl;
#endif
continue;
}
// If we reach another barrier this must be the
// parallel region entry.
if (isa<BarrierBlock>(current)) {
if (region_entry_barrier == NULL)
region_entry_barrier = cast<BarrierBlock>(current);
#ifdef DEBUG_PR_CREATION
std::cerr << "### it's a barrier!" << std::endl;
#endif
continue;
}
if (!verify_no_barriers(current))
{
assert(verify_no_barriers(current) &&
"Barrier found in a non-barrier block! (forgot barrier canonicalization?)");
}
#ifdef DEBUG_PR_CREATION
std::cerr << "added it to the region" << std::endl;
#endif
// Non-barrier block, this must be on the region.
blocks_in_region.insert(current);
// Add predecessors to pending queue.
add_predecessors(pending_blocks, current);
}
if (blocks_in_region.empty())
return NULL;
// Find the entry node.
assert (region_entry_barrier != NULL);
for (unsigned suc = 0, num = region_entry_barrier->getTerminator()->getNumSuccessors();
suc < num; ++suc)
{
llvm::BasicBlock *entryCandidate =
region_entry_barrier->getTerminator()->getSuccessor(suc);
if (blocks_in_region.count(entryCandidate) == 0)
continue;
entry = entryCandidate;
break;
}
assert (blocks_in_region.count(entry) != 0);
// We got all the blocks in a region, create it.
return ParallelRegion::Create(blocks_in_region, entry, exit);
}
static void
add_predecessors(SmallVectorImpl<BasicBlock *> &v, BasicBlock *b)
{
for (pred_iterator i = pred_begin(b), e = pred_end(b);
i != e; ++i) {
if ((isa<BarrierBlock> (*i)) && isa<BarrierBlock> (b)) {
// Ignore barrier-to-barrier edges * Why? --Pekka
add_predecessors(v, *i);
continue;
}
v.push_back(*i);
}
}
static bool
verify_no_barriers(const BasicBlock *B)
{
for (BasicBlock::const_iterator i = B->begin(), e = B->end(); i != e; ++i) {
if (isa<Barrier>(i))
return false;
}
return true;
}
ParallelRegion::ParallelRegionVector *
Kernel::getParallelRegions(llvm::LoopInfo *LI) {
ParallelRegion::ParallelRegionVector *parallel_regions =
new ParallelRegion::ParallelRegionVector;
SmallVector<BarrierBlock *, 4> exit_blocks;
getExitBlocks(exit_blocks);
// We need to keep track of traversed barriers to detect back edges.
SmallPtrSet<BarrierBlock *, 8> found_barriers;
// First find all the ParallelRegions in the Function.
while (!exit_blocks.empty()) {
// We start on an exit block and process the parallel regions upwards
// (finding an execution trace).
BarrierBlock *exit = exit_blocks.back();
exit_blocks.pop_back();
while (ParallelRegion *PR = createParallelRegionBefore(exit)) {
assert(PR != NULL && !PR->empty() &&
"Empty parallel region in kernel (contiguous barriers)!");
found_barriers.insert(exit);
exit = NULL;
parallel_regions->push_back(PR);
BasicBlock *entry = PR->entryBB();
int found_predecessors = 0;
BarrierBlock *loop_barrier = NULL;
for (pred_iterator i = pred_begin(entry), e = pred_end(entry);
i != e; ++i) {
BarrierBlock *barrier = cast<BarrierBlock> (*i);
if (!found_barriers.count(barrier)) {
/* If this is a loop header block we might have edges from two
unprocessed barriers. The one inside the loop (coming from a
computation block after a branch block) should be processed
first. */
std::string bbName = "";
const bool IS_IN_THE_SAME_LOOP =
LI->getLoopFor(barrier) != NULL &&
LI->getLoopFor(entry) != NULL &&
LI->getLoopFor(entry) == LI->getLoopFor(barrier);
if (IS_IN_THE_SAME_LOOP)
{
#ifdef DEBUG_PR_CREATION
std::cout << "### found a barrier inside the loop:" << std::endl;
std::cout << barrier->getName().str() << std::endl;
#endif
if (loop_barrier != NULL) {
// there can be multiple latches and each have their barrier,
// save the previously found inner loop barrier
exit_blocks.push_back(loop_barrier);
}
loop_barrier = barrier;
}
else
{
#ifdef DEBUG_PR_CREATION
std::cout << "### found a barrier:" << std::endl;
std::cout << barrier->getName().str() << std::endl;
#endif
exit = barrier;
}
++found_predecessors;
}
}
if (loop_barrier != NULL)
{
/* The secondary barrier to process in case it was a loop
header. Push it for later processing. */
if (exit != NULL)
exit_blocks.push_back(exit);
/* always process the inner loop regions first */
if (!found_barriers.count(loop_barrier))
exit = loop_barrier;
}
#ifdef DEBUG_PR_CREATION
std::cout << "### created a ParallelRegion:" << std::endl;
PR->dumpNames();
std::cout << std::endl;
#endif
if (found_predecessors == 0)
{
/* This path has been traversed and we encountered no more
unprocessed regions. It means we have either traversed all
paths from the exit or have transformed a loop and thus
encountered only a barrier that was seen (and thus
processed) before. */
break;
}
assert ((exit != NULL) && "Parallel region without entry barrier!");
}
}
return parallel_regions;
}
void
Kernel::addLocalSizeInitCode(size_t LocalSizeX, size_t LocalSizeY, size_t LocalSizeZ) {
IRBuilder<> builder(getEntryBlock().getFirstNonPHI());
GlobalVariable *gv;
llvm::Module* M = getParent();
int size_t_width = 32;
if (M->getPointerSize() == llvm::Module::Pointer64)
size_t_width = 64;
gv = M->getGlobalVariable("_local_size_x");
if (gv != NULL)
builder.CreateStore
(ConstantInt::get
(IntegerType::get(M->getContext(), size_t_width),
LocalSizeX), gv);
gv = M->getGlobalVariable("_local_size_y");
if (gv != NULL)
builder.CreateStore
(ConstantInt::get
(IntegerType::get(M->getContext(), size_t_width),
LocalSizeY), gv);
gv = M->getGlobalVariable("_local_size_z");
if (gv != NULL)
builder.CreateStore
(ConstantInt::get
(IntegerType::get(M->getContext(), size_t_width),
LocalSizeZ), gv);
}
<commit_msg>Add documentation.<commit_after>// Class for kernels, llvm::Functions that represent OpenCL C kernels.
//
// Copyright (c) 2011 Universidad Rey Juan Carlos and
// 2012 Pekka Jääskeläinen / TUT
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "Kernel.h"
#include "Barrier.h"
#include <iostream>
#include "config.h"
#ifdef LLVM_3_1
#include "llvm/Support/IRBuilder.h"
#elif defined LLVM_3_2
#include "llvm/IRBuilder.h"
#include "llvm/InlineAsm.h"
#else
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InlineAsm.h"
#endif
//#define DEBUG_PR_CREATION
using namespace llvm;
using namespace pocl;
static void add_predecessors(SmallVectorImpl<BasicBlock *> &v,
BasicBlock *b);
static bool verify_no_barriers(const BasicBlock *B);
void
Kernel::getExitBlocks(SmallVectorImpl<BarrierBlock *> &B)
{
for (iterator i = begin(), e = end(); i != e; ++i) {
const TerminatorInst *t = i->getTerminator();
if (t->getNumSuccessors() == 0) {
// All exits must be barrier blocks.
B.push_back(cast<BarrierBlock>(i));
}
}
}
ParallelRegion *
Kernel::createParallelRegionBefore(BarrierBlock *B)
{
SmallVector<BasicBlock *, 4> pending_blocks;
SmallPtrSet<BasicBlock *, 8> blocks_in_region;
BarrierBlock *region_entry_barrier = NULL;
llvm::BasicBlock *entry = NULL;
llvm::BasicBlock *exit = B->getSinglePredecessor();
add_predecessors(pending_blocks, B);
#ifdef DEBUG_PR_CREATION
std::cerr << "createParallelRegionBefore " << B->getName().str() << std::endl;
#endif
while (!pending_blocks.empty()) {
BasicBlock *current = pending_blocks.back();
pending_blocks.pop_back();
#ifdef DEBUG_PR_CREATION
std::cerr << "considering " << current->getName().str() << std::endl;
#endif
// avoid infinite recursion of loops
if (blocks_in_region.count(current) != 0)
{
#ifdef DEBUG_PR_CREATION
std::cerr << "already in the region!" << std::endl;
#endif
continue;
}
// If we reach another barrier this must be the
// parallel region entry.
if (isa<BarrierBlock>(current)) {
if (region_entry_barrier == NULL)
region_entry_barrier = cast<BarrierBlock>(current);
#ifdef DEBUG_PR_CREATION
std::cerr << "### it's a barrier!" << std::endl;
#endif
continue;
}
if (!verify_no_barriers(current))
{
assert(verify_no_barriers(current) &&
"Barrier found in a non-barrier block! (forgot barrier canonicalization?)");
}
#ifdef DEBUG_PR_CREATION
std::cerr << "added it to the region" << std::endl;
#endif
// Non-barrier block, this must be on the region.
blocks_in_region.insert(current);
// Add predecessors to pending queue.
add_predecessors(pending_blocks, current);
}
if (blocks_in_region.empty())
return NULL;
// Find the entry node.
assert (region_entry_barrier != NULL);
for (unsigned suc = 0, num = region_entry_barrier->getTerminator()->getNumSuccessors();
suc < num; ++suc)
{
llvm::BasicBlock *entryCandidate =
region_entry_barrier->getTerminator()->getSuccessor(suc);
if (blocks_in_region.count(entryCandidate) == 0)
continue;
entry = entryCandidate;
break;
}
assert (blocks_in_region.count(entry) != 0);
// We got all the blocks in a region, create it.
return ParallelRegion::Create(blocks_in_region, entry, exit);
}
static void
add_predecessors(SmallVectorImpl<BasicBlock *> &v, BasicBlock *b)
{
for (pred_iterator i = pred_begin(b), e = pred_end(b);
i != e; ++i) {
if ((isa<BarrierBlock> (*i)) && isa<BarrierBlock> (b)) {
// Ignore barrier-to-barrier edges * Why? --Pekka
add_predecessors(v, *i);
continue;
}
v.push_back(*i);
}
}
static bool
verify_no_barriers(const BasicBlock *B)
{
for (BasicBlock::const_iterator i = B->begin(), e = B->end(); i != e; ++i) {
if (isa<Barrier>(i))
return false;
}
return true;
}
/**
* The main entry to the "parallel region formation", phase which search
* for the regions between barriers that can be freely parallelized
* across work-items in the work-group.
*/
ParallelRegion::ParallelRegionVector *
Kernel::getParallelRegions(llvm::LoopInfo *LI) {
ParallelRegion::ParallelRegionVector *parallel_regions =
new ParallelRegion::ParallelRegionVector;
SmallVector<BarrierBlock *, 4> exit_blocks;
getExitBlocks(exit_blocks);
// We need to keep track of traversed barriers to detect back edges.
SmallPtrSet<BarrierBlock *, 8> found_barriers;
// First find all the ParallelRegions in the Function.
while (!exit_blocks.empty()) {
// We start on an exit block and process the parallel regions upwards
// (finding an execution trace).
BarrierBlock *exit = exit_blocks.back();
exit_blocks.pop_back();
while (ParallelRegion *PR = createParallelRegionBefore(exit)) {
assert(PR != NULL && !PR->empty() &&
"Empty parallel region in kernel (contiguous barriers)!");
found_barriers.insert(exit);
exit = NULL;
parallel_regions->push_back(PR);
BasicBlock *entry = PR->entryBB();
int found_predecessors = 0;
BarrierBlock *loop_barrier = NULL;
for (pred_iterator i = pred_begin(entry), e = pred_end(entry);
i != e; ++i) {
BarrierBlock *barrier = cast<BarrierBlock> (*i);
if (!found_barriers.count(barrier)) {
/* If this is a loop header block we might have edges from two
unprocessed barriers. The one inside the loop (coming from a
computation block after a branch block) should be processed
first. */
std::string bbName = "";
const bool IS_IN_THE_SAME_LOOP =
LI->getLoopFor(barrier) != NULL &&
LI->getLoopFor(entry) != NULL &&
LI->getLoopFor(entry) == LI->getLoopFor(barrier);
if (IS_IN_THE_SAME_LOOP)
{
#ifdef DEBUG_PR_CREATION
std::cout << "### found a barrier inside the loop:" << std::endl;
std::cout << barrier->getName().str() << std::endl;
#endif
if (loop_barrier != NULL) {
// there can be multiple latches and each have their barrier,
// save the previously found inner loop barrier
exit_blocks.push_back(loop_barrier);
}
loop_barrier = barrier;
}
else
{
#ifdef DEBUG_PR_CREATION
std::cout << "### found a barrier:" << std::endl;
std::cout << barrier->getName().str() << std::endl;
#endif
exit = barrier;
}
++found_predecessors;
}
}
if (loop_barrier != NULL)
{
/* The secondary barrier to process in case it was a loop
header. Push it for later processing. */
if (exit != NULL)
exit_blocks.push_back(exit);
/* always process the inner loop regions first */
if (!found_barriers.count(loop_barrier))
exit = loop_barrier;
}
#ifdef DEBUG_PR_CREATION
std::cout << "### created a ParallelRegion:" << std::endl;
PR->dumpNames();
std::cout << std::endl;
#endif
if (found_predecessors == 0)
{
/* This path has been traversed and we encountered no more
unprocessed regions. It means we have either traversed all
paths from the exit or have transformed a loop and thus
encountered only a barrier that was seen (and thus
processed) before. */
break;
}
assert ((exit != NULL) && "Parallel region without entry barrier!");
}
}
return parallel_regions;
}
void
Kernel::addLocalSizeInitCode(size_t LocalSizeX, size_t LocalSizeY, size_t LocalSizeZ) {
IRBuilder<> builder(getEntryBlock().getFirstNonPHI());
GlobalVariable *gv;
llvm::Module* M = getParent();
int size_t_width = 32;
if (M->getPointerSize() == llvm::Module::Pointer64)
size_t_width = 64;
gv = M->getGlobalVariable("_local_size_x");
if (gv != NULL)
builder.CreateStore
(ConstantInt::get
(IntegerType::get(M->getContext(), size_t_width),
LocalSizeX), gv);
gv = M->getGlobalVariable("_local_size_y");
if (gv != NULL)
builder.CreateStore
(ConstantInt::get
(IntegerType::get(M->getContext(), size_t_width),
LocalSizeY), gv);
gv = M->getGlobalVariable("_local_size_z");
if (gv != NULL)
builder.CreateStore
(ConstantInt::get
(IntegerType::get(M->getContext(), size_t_width),
LocalSizeZ), gv);
}
<|endoftext|> |
<commit_before>/*
* statereader.cpp
*
* Created on: 05.08.2014
* Author: Ralph
*/
#include "statereader.h"
#include "loader.h"
#include "../data/globalpropertymodel.h"
#include "../data/models.h"
#include "../data/roiarea.h"
#include "../data/roibox.h"
#include "../data/vptr.h"
#include "../data/datasets/datasetguides.h"
#include "../data/datasets/datasetlabel.h"
#include "../data/datasets/datasetplane.h"
#include "../data/datasets/datasetscalar.h"
#include "../gui/gl/colormapfunctions.h"
#include "../gui/gl/glfunctions.h"
#include <QDebug>
#include <QFile>
StateReader::StateReader()
{
}
StateReader::~StateReader()
{
}
void StateReader::load( QString fileName )
{
m_fileInfo = QFileInfo( fileName );
QFile file(fileName);
if ( !file.open( QFile::ReadOnly | QFile::Text ) )
{
qCritical() << "StateReader: Cannot read file " << fileName << " : " << file.errorString();
return;
}
xml.read( &file );
if ( xml.getHeaderValue( "appName" ) != "brainGL" )
{
qCritical() << "Not a brainGL xml file";
return;
}
if ( xml.getHeaderValue( "content" ).toString() == "scene" )
{
loadScene();
}
if ( xml.getHeaderValue( "content" ).toString() == "colormaps" )
{
loadColormaps();
}
file.close();
}
void StateReader::loadScene()
{
bool packAndGo = xml.getHeaderValue( "packAndGo" ).toBool();
QList<QVariant>globals = xml.getGlobals();
dynamic_cast<GlobalPropertyModel*>( Models::g() )->setState( globals );
m_cameras = xml.getCameras();
QList< QList<QVariant> >datasets = xml.getDatasets();
for ( int i = 0; i < datasets.size(); ++i )
{
QList<QVariant> state = datasets[i];
int type = getFromStateList( Fn::Property::D_TYPE, state ).toInt();
if ( type == (int)Fn::DatasetType::GUIDE )
{
DatasetGuides* g = new DatasetGuides();
g->properties().setState( state );
Models::addDataset( g );
}
else if ( type == (int)Fn::DatasetType::PLANE )
{
DatasetPlane* plane = new DatasetPlane();
plane->properties().setState( state );
Models::addDataset( plane );
}
else if ( type == (int)Fn::DatasetType::LABEL )
{
DatasetLabel* label = new DatasetLabel();
label->properties().setState( state );
Models::addDataset( label );
}
else
{
QString fn = getFromStateList( Fn::Property::D_FILENAME, state ).toString();
if ( packAndGo )
{
QFileInfo fi( fn );
QString fn = fi.fileName();
loadDataset( m_fileInfo.path() + QDir::separator() + fn, state );
}
else
{
loadDataset( fn, state );
}
}
}
int numBranches = Models::r()->rowCount( QModelIndex() );
QList< QList< QList<QVariant> > > rois = xml.getRois();
for ( int i = 0; i < rois.size(); ++i )
{
QList< QList<QVariant> >branch = rois[i];
QList<QVariant>roiState = branch[0];
int shape = getFromStateList( Fn::Property::D_SHAPE, roiState ).toInt();
if ( shape == 10 )
{
if ( packAndGo )
{
QFileInfo fi( getFromStateList( Fn::Property::D_FILENAME, roiState ).toString() );
QString fn = fi.fileName();
GLFunctions::roi = loadRoi( m_fileInfo.path() + QDir::separator() + fn );
}
else
{
QString fn = getFromStateList( Fn::Property::D_FILENAME, roiState ).toString();
GLFunctions::roi = loadRoi( fn );
GLFunctions::roi->properties()->setState( roiState );
}
}
else
{
GLFunctions::roi = new ROIBox();
GLFunctions::roi->properties()->setState( roiState );
}
for ( int l = 0; l < roiState.size() / 2; ++l )
{
if ( (Fn::Property)( roiState[l*2].toInt() ) == Fn::Property::D_COLOR )
{
GLFunctions::roi->properties()->set( (Fn::Property)( roiState[l*2].toInt() ), roiState[l*2+1] );
}
}
Models::r()->insertRows( 0, 0, QModelIndex() );
if ( branch.size() > 1 )
{
for ( int k = 1; k < branch.size(); ++k )
{
QList<QVariant>roiState = branch[k];
int shape = getFromStateList( Fn::Property::D_SHAPE, roiState ).toInt();
if ( shape == 10 )
{
if ( packAndGo )
{
QFileInfo fi( getFromStateList( Fn::Property::D_FILENAME, roiState ).toString() );
QString fn = fi.fileName();
GLFunctions::roi = loadRoi( fi.path() + QDir::separator() + fn );
}
else
{
QString fn = getFromStateList( Fn::Property::D_FILENAME, roiState ).toString();
GLFunctions::roi = loadRoi( fn );
GLFunctions::roi->properties()->setState( roiState );
}
Models::r()->insertRows( 0, 0, Models::createRoiIndex( numBranches + i, 0, 0 ) );
}
else
{
GLFunctions::roi = new ROIBox();
GLFunctions::roi->properties()->setState( roiState );
Models::r()->insertRows( 0, 0, Models::createRoiIndex( numBranches + i, 0, 0 ) );
}
for ( int l = 0; l < roiState.size() / 2; ++l )
{
if ( (Fn::Property)( roiState[l*2].toInt() ) == Fn::Property::D_COLOR )
{
GLFunctions::roi->properties()->set( (Fn::Property)( roiState[l*2].toInt() ), roiState[l*2+1] );
}
}
}
}
}
}
QVariant StateReader::getFromStateList( Fn::Property prop, QList<QVariant>& state )
{
for ( int i = 0; i < state.size() / 2; ++i )
{
if ( (Fn::Property)( state[i*2].toInt() ) == prop )
{
return state[i*2+1];
}
}
return QVariant();
}
void StateReader::loadDataset( QString fileName, QList<QVariant> state )
{
Loader loader;
loader.setFilename( QDir( fileName ) );
if ( loader.load() )
{
for ( int k = 0; k < loader.getNumDatasets(); ++k )
{
loader.getDataset( k )->properties().setState( state );
Models::d()->setData( Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET ), VPtr<Dataset>::asQVariant( loader.getDataset( k ) ), Qt::DisplayRole );
}
QFileInfo fi( fileName );
QDir dir = fi.absoluteDir();
QString lastPath = dir.absolutePath();
Models::g()->setData( Models::g()->index( (int)Fn::Property::G_LAST_PATH, 0 ), lastPath );
}
}
ROIArea* StateReader::loadRoi( QString fileName )
{
Loader loader;
loader.setFilename( QDir( fileName ) );
if ( loader.load() )
{
DatasetScalar* dss = static_cast<DatasetScalar*>( loader.getDataset( 0 ) );
std::vector<float>* data = dss->getData();
std::vector<float> out( data->size(), 0.0 );
for ( unsigned int i = 0; i < data->size(); ++i )
{
out[i] = data->at( i );
}
ROIArea* roiOut = new ROIArea( out, dss->properties() );
QFileInfo fi( fileName );
QDir dir = fi.absoluteDir();
QString lastPath = dir.absolutePath();
Models::g()->setData( Models::g()->index( (int)Fn::Property::G_LAST_PATH, 0 ), lastPath );
return roiOut;
}
return NULL;
}
void StateReader::loadColormaps()
{
QList< QList<QVariant> >cms = xml.getColormaps();
for ( int i = 0; i < cms.size(); ++i )
{
ColormapBase cm( cms[i] );
ColormapFunctions::addColormap( cm );
}
}
<commit_msg>when loading a scene set the globals last<commit_after>/*
* statereader.cpp
*
* Created on: 05.08.2014
* Author: Ralph
*/
#include "statereader.h"
#include "loader.h"
#include "../data/globalpropertymodel.h"
#include "../data/models.h"
#include "../data/roiarea.h"
#include "../data/roibox.h"
#include "../data/vptr.h"
#include "../data/datasets/datasetguides.h"
#include "../data/datasets/datasetlabel.h"
#include "../data/datasets/datasetplane.h"
#include "../data/datasets/datasetscalar.h"
#include "../gui/gl/colormapfunctions.h"
#include "../gui/gl/glfunctions.h"
#include <QDebug>
#include <QFile>
StateReader::StateReader()
{
}
StateReader::~StateReader()
{
}
void StateReader::load( QString fileName )
{
m_fileInfo = QFileInfo( fileName );
QFile file(fileName);
if ( !file.open( QFile::ReadOnly | QFile::Text ) )
{
qCritical() << "StateReader: Cannot read file " << fileName << " : " << file.errorString();
return;
}
xml.read( &file );
if ( xml.getHeaderValue( "appName" ) != "brainGL" )
{
qCritical() << "Not a brainGL xml file";
return;
}
if ( xml.getHeaderValue( "content" ).toString() == "scene" )
{
loadScene();
}
if ( xml.getHeaderValue( "content" ).toString() == "colormaps" )
{
loadColormaps();
}
file.close();
}
void StateReader::loadScene()
{
bool packAndGo = xml.getHeaderValue( "packAndGo" ).toBool();
QList<QVariant>globals = xml.getGlobals();
m_cameras = xml.getCameras();
QList< QList<QVariant> >datasets = xml.getDatasets();
for ( int i = 0; i < datasets.size(); ++i )
{
QList<QVariant> state = datasets[i];
int type = getFromStateList( Fn::Property::D_TYPE, state ).toInt();
if ( type == (int)Fn::DatasetType::GUIDE )
{
DatasetGuides* g = new DatasetGuides();
g->properties().setState( state );
Models::addDataset( g );
}
else if ( type == (int)Fn::DatasetType::PLANE )
{
DatasetPlane* plane = new DatasetPlane();
plane->properties().setState( state );
Models::addDataset( plane );
}
else if ( type == (int)Fn::DatasetType::LABEL )
{
DatasetLabel* label = new DatasetLabel();
label->properties().setState( state );
Models::addDataset( label );
}
else
{
QString fn = getFromStateList( Fn::Property::D_FILENAME, state ).toString();
if ( packAndGo )
{
QFileInfo fi( fn );
QString fn = fi.fileName();
loadDataset( m_fileInfo.path() + QDir::separator() + fn, state );
}
else
{
loadDataset( fn, state );
}
}
}
int numBranches = Models::r()->rowCount( QModelIndex() );
QList< QList< QList<QVariant> > > rois = xml.getRois();
for ( int i = 0; i < rois.size(); ++i )
{
QList< QList<QVariant> >branch = rois[i];
QList<QVariant>roiState = branch[0];
int shape = getFromStateList( Fn::Property::D_SHAPE, roiState ).toInt();
if ( shape == 10 )
{
if ( packAndGo )
{
QFileInfo fi( getFromStateList( Fn::Property::D_FILENAME, roiState ).toString() );
QString fn = fi.fileName();
GLFunctions::roi = loadRoi( m_fileInfo.path() + QDir::separator() + fn );
}
else
{
QString fn = getFromStateList( Fn::Property::D_FILENAME, roiState ).toString();
GLFunctions::roi = loadRoi( fn );
GLFunctions::roi->properties()->setState( roiState );
}
}
else
{
GLFunctions::roi = new ROIBox();
GLFunctions::roi->properties()->setState( roiState );
}
for ( int l = 0; l < roiState.size() / 2; ++l )
{
if ( (Fn::Property)( roiState[l*2].toInt() ) == Fn::Property::D_COLOR )
{
GLFunctions::roi->properties()->set( (Fn::Property)( roiState[l*2].toInt() ), roiState[l*2+1] );
}
}
Models::r()->insertRows( 0, 0, QModelIndex() );
if ( branch.size() > 1 )
{
for ( int k = 1; k < branch.size(); ++k )
{
QList<QVariant>roiState = branch[k];
int shape = getFromStateList( Fn::Property::D_SHAPE, roiState ).toInt();
if ( shape == 10 )
{
if ( packAndGo )
{
QFileInfo fi( getFromStateList( Fn::Property::D_FILENAME, roiState ).toString() );
QString fn = fi.fileName();
GLFunctions::roi = loadRoi( fi.path() + QDir::separator() + fn );
}
else
{
QString fn = getFromStateList( Fn::Property::D_FILENAME, roiState ).toString();
GLFunctions::roi = loadRoi( fn );
GLFunctions::roi->properties()->setState( roiState );
}
Models::r()->insertRows( 0, 0, Models::createRoiIndex( numBranches + i, 0, 0 ) );
}
else
{
GLFunctions::roi = new ROIBox();
GLFunctions::roi->properties()->setState( roiState );
Models::r()->insertRows( 0, 0, Models::createRoiIndex( numBranches + i, 0, 0 ) );
}
for ( int l = 0; l < roiState.size() / 2; ++l )
{
if ( (Fn::Property)( roiState[l*2].toInt() ) == Fn::Property::D_COLOR )
{
GLFunctions::roi->properties()->set( (Fn::Property)( roiState[l*2].toInt() ), roiState[l*2+1] );
}
}
}
}
}
dynamic_cast<GlobalPropertyModel*>( Models::g() )->setState( globals );
}
QVariant StateReader::getFromStateList( Fn::Property prop, QList<QVariant>& state )
{
for ( int i = 0; i < state.size() / 2; ++i )
{
if ( (Fn::Property)( state[i*2].toInt() ) == prop )
{
return state[i*2+1];
}
}
return QVariant();
}
void StateReader::loadDataset( QString fileName, QList<QVariant> state )
{
Loader loader;
loader.setFilename( QDir( fileName ) );
if ( loader.load() )
{
for ( int k = 0; k < loader.getNumDatasets(); ++k )
{
loader.getDataset( k )->properties().setState( state );
Models::d()->setData( Models::d()->index( Models::d()->rowCount(), (int)Fn::Property::D_NEW_DATASET ), VPtr<Dataset>::asQVariant( loader.getDataset( k ) ), Qt::DisplayRole );
}
QFileInfo fi( fileName );
QDir dir = fi.absoluteDir();
QString lastPath = dir.absolutePath();
Models::g()->setData( Models::g()->index( (int)Fn::Property::G_LAST_PATH, 0 ), lastPath );
}
}
ROIArea* StateReader::loadRoi( QString fileName )
{
Loader loader;
loader.setFilename( QDir( fileName ) );
if ( loader.load() )
{
DatasetScalar* dss = static_cast<DatasetScalar*>( loader.getDataset( 0 ) );
std::vector<float>* data = dss->getData();
std::vector<float> out( data->size(), 0.0 );
for ( unsigned int i = 0; i < data->size(); ++i )
{
out[i] = data->at( i );
}
ROIArea* roiOut = new ROIArea( out, dss->properties() );
QFileInfo fi( fileName );
QDir dir = fi.absoluteDir();
QString lastPath = dir.absolutePath();
Models::g()->setData( Models::g()->index( (int)Fn::Property::G_LAST_PATH, 0 ), lastPath );
return roiOut;
}
return NULL;
}
void StateReader::loadColormaps()
{
QList< QList<QVariant> >cms = xml.getColormaps();
for ( int i = 0; i < cms.size(); ++i )
{
ColormapBase cm( cms[i] );
ColormapFunctions::addColormap( cm );
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include <iostream>
#include <map>
#include <math.h>
typedef unsigned int ruint;
class Uniform01
{
protected:
Uniform01(ruint seed): m_seed(seed)
{}
double generate01()
{
m_seed = m_seed * 69069 + 1;
return m_seed / 4294967296.0;
}
private:
ruint m_seed;
};
class Triang: public Uniform01
{
public:
Triang(const double& mean, const int& min, const int& max, ruint seed)
: Uniform01(seed )
, m_mean (mean )
, m_min (min )
, m_max (max )
{}
double generate()
{
double result;
double u01 = generate01();
double h = 2/(m_max-m_min);
double a1 = h/(m_mean-m_min);
double b1 = h;
double a2 = -h/(m_max-m_mean);
double b2 = h;
if ( u01 >= (m_mean-m_min)/(m_max-m_min))
{
result = -(m_max-m_mean)*(sqrt(generate01()) - 1);
}
else
{
result = (m_mean-m_min)*(sqrt(generate01()) - 1);
}
return result + m_mean;
}
private:
double m_mean;
double m_min;
double m_max;
};
void main()
{
Triang triang (4, 0, 5, 2345236);
double step = 0.1;
typedef std::map<int, ruint> Histogram;
Histogram m_histogram;
for (ruint i = 0; i < 100000; i++)
{
double value = triang.generate();
ruint index = static_cast<ruint>(value / step);
std::pair<Histogram::iterator, bool> result =
m_histogram.insert(Histogram::value_type(index, 0));
if (!result.second)
{
++result.first->second;
}
}
Histogram::const_iterator it = m_histogram.begin();
while (it != m_histogram.end())
{
std::cout
<< it->first
<< ";"
<< it->second
<< std::endl;
++it;
}
int i = 1;
}
<commit_msg> - убрал лишнее<commit_after>#include "stdafx.h"
#include <iostream>
#include <map>
#include <math.h>
typedef unsigned int ruint;
class Uniform01
{
protected:
Uniform01(ruint seed): m_seed(seed)
{}
double generate01()
{
m_seed = m_seed * 69069 + 1;
return m_seed / 4294967296.0;
}
private:
ruint m_seed;
};
class Triang: public Uniform01
{
public:
Triang(const double& mean, const int& min, const int& max, ruint seed)
: Uniform01(seed )
, m_mean (mean )
, m_min (min )
, m_max (max )
{}
double generate()
{
double result;
double u01 = generate01();
if ( u01 >= (m_mean-m_min)/(m_max-m_min))
{
result = -(m_max-m_mean)*(sqrt(u01) - 1);
}
else
{
result = (m_mean-m_min)*(sqrt(u01) - 1);
}
return result + m_mean;
}
private:
double m_mean;
double m_min;
double m_max;
};
void main()
{
Triang triang (3, 0, 5, 2345236);
double step = 0.1;
typedef std::map<int, ruint> Histogram;
Histogram m_histogram;
for (ruint i = 0; i < 100000; i++)
{
double value = triang.generate();
ruint index = static_cast<ruint>(value / step);
std::pair<Histogram::iterator, bool> result =
m_histogram.insert(Histogram::value_type(index, 0));
if (!result.second)
{
++result.first->second;
}
}
Histogram::const_iterator it = m_histogram.begin();
while (it != m_histogram.end())
{
std::cout
<< it->first
<< ";"
<< it->second
<< std::endl;
++it;
}
int i = 1;
}
<|endoftext|> |
<commit_before>#include "iotsa.h"
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
// Tiny http server which forwards to https
class TinyForwardServer {
public:
ESP8266WebServer server;
TinyForwardServer()
: server(80)
{
server.onNotFound(std::bind(&TinyForwardServer::notFound, this));
server.begin();
}
void notFound() {
String newLoc = "https://";
if (iotsaConfig.wifiPrivateNetworkMode) {
newLoc += "192.168.4.1";
} else {
newLoc += iotsaConfig.hostName;
newLoc += ".local";
}
newLoc += server.uri();
IFDEBUG IotsaSerial.print("HTTP 301 to ");
IFDEBUG IotsaSerial.println(newLoc);
server.sendHeader("Location", newLoc);
server.uri();
server.send(301, "", "");
}
};
static TinyForwardServer *singletonTFS;
#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
IotsaWebServerMixin::IotsaWebServerMixin(IotsaApplication* _app)
:
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
server(new IotsaWebServer(IOTSA_WEBSERVER_PORT)),
#endif
app(_app)
{
}
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
void
IotsaWebServerMixin::webServerSetup() {
if (!iotsaConfig.wifiEnabled) return;
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
if (singletonTFS == NULL)
singletonTFS = new TinyForwardServer();
#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
server->onNotFound(std::bind(&IotsaWebServerMixin::webServerNotFoundHandler, this));
#endif
#ifdef IOTSA_WITH_WEB
server->on("/", std::bind(&IotsaWebServerMixin::webServerRootHandler, this));
#endif
#ifdef IOTSA_WITH_HTTPS
IFDEBUG IotsaSerial.print("Using https key len=");
IFDEBUG IotsaSerial.print(iotsaConfig.httpsKeyLength);
IFDEBUG IotsaSerial.print(", cert len=");
IFDEBUG IotsaSerial.println(iotsaConfig.httpsCertificateLength);
server->getServer().setServerKeyAndCert_P(
iotsaConfig.httpsKey,
iotsaConfig.httpsKeyLength,
iotsaConfig.httpsCertificate,
iotsaConfig.httpsCertificateLength
);
#endif
server->begin();
#ifdef IOTSA_WITH_HTTPS
IFDEBUG IotsaSerial.println("HTTPS server started");
#else
IFDEBUG IotsaSerial.println("HTTP server started");
#endif
}
void
IotsaWebServerMixin::webServerLoop() {
if (!iotsaConfig.wifiEnabled) return;
server->handleClient();
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
singletonTFS->server.handleClient();
#endif
}
void
IotsaWebServerMixin::webServerNotFoundHandler() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server->uri();
message += "\nMethod: ";
message += (server->method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server->args();
message += "\n";
for (uint8_t i=0; i<server->args(); i++){
message += " " + server->argName(i) + ": " + server->arg(i) + "\n";
}
server->send(404, "text/plain", message);
}
#endif // IOTSA_WITH_HTTP_OR_HTTPS
#ifdef IOTSA_WITH_WEB
void
IotsaWebServerMixin::webServerRootHandler() {
String message = "<html><head><title>" + app->title + "</title></head><body><h1>" + app->title + "</h1>";
IotsaBaseMod *m;
for (m=app->firstModule; m; m=m->nextModule) {
message += m->info();
}
for (m=app->firstEarlyModule; m; m=m->nextModule) {
message += m->info();
}
message += "</body></html>";
server->send(200, "text/html", message);
}
#endif // IOTSA_WITH_WEB<commit_msg>Fixed bug when building without any webserver<commit_after>#include "iotsa.h"
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
// Tiny http server which forwards to https
class TinyForwardServer {
public:
ESP8266WebServer server;
TinyForwardServer()
: server(80)
{
server.onNotFound(std::bind(&TinyForwardServer::notFound, this));
server.begin();
}
void notFound() {
String newLoc = "https://";
if (iotsaConfig.wifiPrivateNetworkMode) {
newLoc += "192.168.4.1";
} else {
newLoc += iotsaConfig.hostName;
newLoc += ".local";
}
newLoc += server.uri();
IFDEBUG IotsaSerial.print("HTTP 301 to ");
IFDEBUG IotsaSerial.println(newLoc);
server.sendHeader("Location", newLoc);
server.uri();
server.send(301, "", "");
}
};
static TinyForwardServer *singletonTFS;
#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
IotsaWebServerMixin::IotsaWebServerMixin(IotsaApplication* _app)
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
:
server(new IotsaWebServer(IOTSA_WEBSERVER_PORT)),
app(_app)
#endif
{
}
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
void
IotsaWebServerMixin::webServerSetup() {
if (!iotsaConfig.wifiEnabled) return;
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
if (singletonTFS == NULL)
singletonTFS = new TinyForwardServer();
#endif // defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
#ifdef IOTSA_WITH_HTTP_OR_HTTPS
server->onNotFound(std::bind(&IotsaWebServerMixin::webServerNotFoundHandler, this));
#endif
#ifdef IOTSA_WITH_WEB
server->on("/", std::bind(&IotsaWebServerMixin::webServerRootHandler, this));
#endif
#ifdef IOTSA_WITH_HTTPS
IFDEBUG IotsaSerial.print("Using https key len=");
IFDEBUG IotsaSerial.print(iotsaConfig.httpsKeyLength);
IFDEBUG IotsaSerial.print(", cert len=");
IFDEBUG IotsaSerial.println(iotsaConfig.httpsCertificateLength);
server->getServer().setServerKeyAndCert_P(
iotsaConfig.httpsKey,
iotsaConfig.httpsKeyLength,
iotsaConfig.httpsCertificate,
iotsaConfig.httpsCertificateLength
);
#endif
server->begin();
#ifdef IOTSA_WITH_HTTPS
IFDEBUG IotsaSerial.println("HTTPS server started");
#else
IFDEBUG IotsaSerial.println("HTTP server started");
#endif
}
void
IotsaWebServerMixin::webServerLoop() {
if (!iotsaConfig.wifiEnabled) return;
server->handleClient();
#if defined(IOTSA_WITH_HTTPS) && defined(IOTSA_WITH_HTTP)
singletonTFS->server.handleClient();
#endif
}
void
IotsaWebServerMixin::webServerNotFoundHandler() {
String message = "File Not Found\n\n";
message += "URI: ";
message += server->uri();
message += "\nMethod: ";
message += (server->method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server->args();
message += "\n";
for (uint8_t i=0; i<server->args(); i++){
message += " " + server->argName(i) + ": " + server->arg(i) + "\n";
}
server->send(404, "text/plain", message);
}
#endif // IOTSA_WITH_HTTP_OR_HTTPS
#ifdef IOTSA_WITH_WEB
void
IotsaWebServerMixin::webServerRootHandler() {
String message = "<html><head><title>" + app->title + "</title></head><body><h1>" + app->title + "</h1>";
IotsaBaseMod *m;
for (m=app->firstModule; m; m=m->nextModule) {
message += m->info();
}
for (m=app->firstEarlyModule; m; m=m->nextModule) {
message += m->info();
}
message += "</body></html>";
server->send(200, "text/html", message);
}
#endif // IOTSA_WITH_WEB<|endoftext|> |
<commit_before>#pragma once
#include "GeneNode.hpp"
/*
* This simple class encapsulates all of an Individual's genetic information,
* including the gene pools it uses, with the goal of easing the sharing of
* this information between classes.
*/
class Genome {
private:
protected:
int * gene;
int genomeLength;
GeneNode ** genePools;
public:
Genome(int * newGene, int newGenomeLength, GeneNode ** newGeneNodes);
~Genome();
int * getGenome();
int getGenomeLength();
GeneNode ** getGeneNodes();
int getDifference(Genome * otherGenome);
};
<commit_msg>[Genome]: Tweaked Genome to use vectors<commit_after>#pragma once
#include "Locus.hpp"
#include <vector>
class Genome {
private:
protected:
std::vector<int> genes;
std::vector<Locus*> loci;
public:
Genome(std::vector<Locus*> loci);
Genome(std::vector<int> genes, std::vector<Locus*> loci);
~Genome();
std::vector<int> getGenome();
int getGenomeLength();
std::vector<Locus*> getLoci();
int getDifference(Genome * otherGenome);
};
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vp9_rtcd.h"
#include "./vpx_config.h"
#include "./vpx_dsp_rtcd.h"
#include "test/acm_random.h"
#include "test/bench.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "vp9/common/vp9_blockd.h"
#include "vpx_mem/vpx_mem.h"
typedef void (*SubtractFunc)(int rows, int cols, int16_t *diff_ptr,
ptrdiff_t diff_stride, const uint8_t *src_ptr,
ptrdiff_t src_stride, const uint8_t *pred_ptr,
ptrdiff_t pred_stride);
namespace vp9 {
class VP9SubtractBlockTest : public AbstractBench,
public ::testing::TestWithParam<SubtractFunc> {
public:
virtual void TearDown() { libvpx_test::ClearSystemState(); }
protected:
int block_width_;
int block_height_;
int16_t *diff_;
uint8_t *pred_;
uint8_t *src_;
virtual void Run() {
GetParam()(block_height_, block_width_, diff_, block_width_, src_,
block_width_, pred_, block_width_);
}
void SetupBlocks(BLOCK_SIZE bsize) {
block_width_ = 4 * num_4x4_blocks_wide_lookup[bsize];
block_height_ = 4 * num_4x4_blocks_high_lookup[bsize];
diff_ = reinterpret_cast<int16_t *>(
vpx_memalign(16, sizeof(*diff_) * block_width_ * block_height_ * 2));
pred_ = reinterpret_cast<uint8_t *>(
vpx_memalign(16, block_width_ * block_height_ * 2));
src_ = reinterpret_cast<uint8_t *>(
vpx_memalign(16, block_width_ * block_height_ * 2));
}
};
using libvpx_test::ACMRandom;
TEST_P(VP9SubtractBlockTest, DISABLED_Speed) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
SetupBlocks(bsize);
RunNTimes(100000000 / (block_height_ * block_width_));
char block_size[16];
snprintf(block_size, sizeof(block_size), "%dx%d", block_height_,
block_width_);
char title[100];
snprintf(title, sizeof(title), "%8s ", block_size);
PrintMedian(title);
vpx_free(diff_);
vpx_free(pred_);
vpx_free(src_);
}
}
TEST_P(VP9SubtractBlockTest, SimpleSubtract) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
// FIXME(rbultje) split in its own file
for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
SetupBlocks(bsize);
for (int n = 0; n < 100; n++) {
for (int r = 0; r < block_height_; ++r) {
for (int c = 0; c < block_width_ * 2; ++c) {
src_[r * block_width_ * 2 + c] = rnd.Rand8();
pred_[r * block_width_ * 2 + c] = rnd.Rand8();
}
}
GetParam()(block_height_, block_width_, diff_, block_width_, src_,
block_width_, pred_, block_width_);
for (int r = 0; r < block_height_; ++r) {
for (int c = 0; c < block_width_; ++c) {
EXPECT_EQ(diff_[r * block_width_ + c],
(src_[r * block_width_ + c] - pred_[r * block_width_ + c]))
<< "r = " << r << ", c = " << c << ", bs = " << bsize;
}
}
GetParam()(block_height_, block_width_, diff_, block_width_ * 2, src_,
block_width_ * 2, pred_, block_width_ * 2);
for (int r = 0; r < block_height_; ++r) {
for (int c = 0; c < block_width_; ++c) {
EXPECT_EQ(diff_[r * block_width_ * 2 + c],
(src_[r * block_width_ * 2 + c] -
pred_[r * block_width_ * 2 + c]))
<< "r = " << r << ", c = " << c << ", bs = " << bsize;
}
}
}
vpx_free(diff_);
vpx_free(pred_);
vpx_free(src_);
}
}
INSTANTIATE_TEST_CASE_P(C, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_c));
#if HAVE_SSE2
INSTANTIATE_TEST_CASE_P(SSE2, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_sse2));
#endif
#if HAVE_NEON
INSTANTIATE_TEST_CASE_P(NEON, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_neon));
#endif
#if HAVE_MSA
INSTANTIATE_TEST_CASE_P(MSA, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_msa));
#endif
#if HAVE_MMI
INSTANTIATE_TEST_CASE_P(MMI, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_mmi));
#endif
} // namespace vp9
<commit_msg>Cast bsize as int to print a meaninful debug info<commit_after>/*
* Copyright (c) 2012 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vp9_rtcd.h"
#include "./vpx_config.h"
#include "./vpx_dsp_rtcd.h"
#include "test/acm_random.h"
#include "test/bench.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "vp9/common/vp9_blockd.h"
#include "vpx_mem/vpx_mem.h"
typedef void (*SubtractFunc)(int rows, int cols, int16_t *diff_ptr,
ptrdiff_t diff_stride, const uint8_t *src_ptr,
ptrdiff_t src_stride, const uint8_t *pred_ptr,
ptrdiff_t pred_stride);
namespace vp9 {
class VP9SubtractBlockTest : public AbstractBench,
public ::testing::TestWithParam<SubtractFunc> {
public:
virtual void TearDown() { libvpx_test::ClearSystemState(); }
protected:
int block_width_;
int block_height_;
int16_t *diff_;
uint8_t *pred_;
uint8_t *src_;
virtual void Run() {
GetParam()(block_height_, block_width_, diff_, block_width_, src_,
block_width_, pred_, block_width_);
}
void SetupBlocks(BLOCK_SIZE bsize) {
block_width_ = 4 * num_4x4_blocks_wide_lookup[bsize];
block_height_ = 4 * num_4x4_blocks_high_lookup[bsize];
diff_ = reinterpret_cast<int16_t *>(
vpx_memalign(16, sizeof(*diff_) * block_width_ * block_height_ * 2));
pred_ = reinterpret_cast<uint8_t *>(
vpx_memalign(16, block_width_ * block_height_ * 2));
src_ = reinterpret_cast<uint8_t *>(
vpx_memalign(16, block_width_ * block_height_ * 2));
}
};
using libvpx_test::ACMRandom;
TEST_P(VP9SubtractBlockTest, DISABLED_Speed) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
SetupBlocks(bsize);
RunNTimes(100000000 / (block_height_ * block_width_));
char block_size[16];
snprintf(block_size, sizeof(block_size), "%dx%d", block_height_,
block_width_);
char title[100];
snprintf(title, sizeof(title), "%8s ", block_size);
PrintMedian(title);
vpx_free(diff_);
vpx_free(pred_);
vpx_free(src_);
}
}
TEST_P(VP9SubtractBlockTest, SimpleSubtract) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
// FIXME(rbultje) split in its own file
for (BLOCK_SIZE bsize = BLOCK_4X4; bsize < BLOCK_SIZES;
bsize = static_cast<BLOCK_SIZE>(static_cast<int>(bsize) + 1)) {
SetupBlocks(bsize);
for (int n = 0; n < 100; n++) {
for (int r = 0; r < block_height_; ++r) {
for (int c = 0; c < block_width_ * 2; ++c) {
src_[r * block_width_ * 2 + c] = rnd.Rand8();
pred_[r * block_width_ * 2 + c] = rnd.Rand8();
}
}
GetParam()(block_height_, block_width_, diff_, block_width_, src_,
block_width_, pred_, block_width_);
for (int r = 0; r < block_height_; ++r) {
for (int c = 0; c < block_width_; ++c) {
EXPECT_EQ(diff_[r * block_width_ + c],
(src_[r * block_width_ + c] - pred_[r * block_width_ + c]))
<< "r = " << r << ", c = " << c << ", bs = " << (int)bsize;
}
}
GetParam()(block_height_, block_width_, diff_, block_width_ * 2, src_,
block_width_ * 2, pred_, block_width_ * 2);
for (int r = 0; r < block_height_; ++r) {
for (int c = 0; c < block_width_; ++c) {
EXPECT_EQ(diff_[r * block_width_ * 2 + c],
(src_[r * block_width_ * 2 + c] -
pred_[r * block_width_ * 2 + c]))
<< "r = " << r << ", c = " << c << ", bs = " << (int)bsize;
}
}
}
vpx_free(diff_);
vpx_free(pred_);
vpx_free(src_);
}
}
INSTANTIATE_TEST_CASE_P(C, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_c));
#if HAVE_SSE2
INSTANTIATE_TEST_CASE_P(SSE2, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_sse2));
#endif
#if HAVE_NEON
INSTANTIATE_TEST_CASE_P(NEON, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_neon));
#endif
#if HAVE_MSA
INSTANTIATE_TEST_CASE_P(MSA, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_msa));
#endif
#if HAVE_MMI
INSTANTIATE_TEST_CASE_P(MMI, VP9SubtractBlockTest,
::testing::Values(vpx_subtract_block_mmi));
#endif
} // namespace vp9
<|endoftext|> |
<commit_before>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"
#include <EMULATOR.H>
#include <LIBETC.H>
#include "GAMEFLOW.H"
#if PSXPC_VERSION || PSXPC_TEST
#include <stdint.h>
#endif
#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif
void S_MemSet(char* p, int value, int length)
{
int size;
if (length != 0)
{
if (length > 3)
{
value |= value << 8;
value |= value << 16;
if (((uintptr_t)p) & 3)
{
size = 4 - (((uintptr_t)p) & 3);
length -= 4 - (((uintptr_t)p) & 3);
//loc_5E918
while (size--)
*p++ = value;
}
//loc_5E928
size = length >> 2;
if ((length >> 2))
{
length &= 3;
//loc_5E934
while (size--)
{
((int*)p)[0] = value;
p += 4;
}
}
}
//loc_5E94C
while (length-- != 0)
*p++ = value;
}
}
void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size) //5E964(<), ? (F)
{
int i;
if (size > 0)
{
for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
{
//loc_5E974
pDest[0] = pSrc[0];
pDest[1] = pSrc[1];
pDest[2] = pSrc[2];
pDest[3] = pSrc[3];
}
//loc_5E9AC
for (i = size & 3; i > 0; i--)
{
*pDest++ = *pSrc++;
}
}
}
void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2) //5EDF8
{
UNIMPLEMENTED();
}
void DrawTPage(unsigned char a0, unsigned char a1) //5EE78(<), 5FB58(<)
{
UNIMPLEMENTED();
}
void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5) //5EECC(<)
{
UNIMPLEMENTED();
}
void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5) //5EF84(<),
{
UNIMPLEMENTED();
}
void LOAD_VSyncHandler() //5F074(<), 5FD54(<) (F)
{
int a0, a1, a2;
if (!LtLoadingBarEnabled)
{
return;
}
//loc_5F08C
GPU_BeginScene();
a0 = 440; //x?
a1 = 200; //y?
a2 = 64; //cd width or height?
if (_first_time_ever)
{
a0 += 24;
a1 += 8;
a2 = 48;
}
//loc_5F0B4
draw_rotate_sprite(a0, a1, a2);
db.current_buffer ^= 1;
GnLastFrameCount = 0;
DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
return;
}
void LOAD_DrawEnable(unsigned char isEnabled) //5F2C8, 5FFA8
{
LtLoadingBarEnabled = isEnabled;
}
void GPU_BeginScene() //5F0F0(<), 5FDD0(<)
{
db.ot = db.order_table[db.current_buffer];
db.polyptr = (char*)db.poly_buffer[db.current_buffer];
db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer] + 26000);
db.pickup_ot = db.pickup_order_table[db.current_buffer];
ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);
Emulator_BeginScene();
}
void draw_rotate_sprite(long a0, long a1, long a2) //5F134, 5FE14 (F)
{
long t0;
short* r_cossinptr;
long t6;
long t5;
long t1;
long t4;
DelRotAng = (DelRotAng - 52) & 0xFFF;
r_cossinptr = &rcossin_tbl[DelRotAng * 2];
t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;
*(long*)&db.polyptr[4] = 0x2C808080;
*(long*)&db.polyptr[12] = 0;
*(long*)&db.polyptr[20] = 0x1303F00;
t0 = t6 - t5;
a2 = -t6;
t4 = a2 - t5;
a2 += t5;
t1 = t6 + t5;
*(short*)&db.polyptr[8] = t0 + (t0 / 2) + a0;
*(short*)&db.polyptr[10] = t5 + t6 + a1;
*(short*)&db.polyptr[16] = t4 + (t4 / 2) + a0;
*(short*)&db.polyptr[18] = -t5 + t6 + a1;
*(short*)&db.polyptr[24] = t1 + (t1 / 2) + a0;
*(short*)&db.polyptr[26] = (t5 - t6) + a1;
*(short*)&db.polyptr[28] = 0x3F; //width/height of loading cd?
*(short*)&db.polyptr[36] = 0x3F3F;
*(short*)&db.polyptr[32] = a2 + (a2 / 2) + a0;
*(short*)&db.polyptr[34] = a1 + (-t5 - t6);
*(long*)&db.polyptr[0] = db.ot[0] | 0x09000000;
db.ot[0] = (unsigned long)&db.polyptr[0];
db.polyptr += 0x28; //sizeof(POLY_F3); * 2?
*(long*)&db.polyptr[4] = 0x2C808080;
*(long*)&db.polyptr[8] = 0x780100;
*(long*)&db.polyptr[12] = 0x6800;
*(long*)&db.polyptr[16] = 0x7801FF;
*(long*)&db.polyptr[20] = 0x13468FF;
*(long*)&db.polyptr[24] = 0xEF0100;
*(short*)&db.polyptr[28] = 0xDF00;
*(long*)&db.polyptr[32] = 0xEF01FF;
*(short*)&db.polyptr[36] = 0xDFFF;
*(long*)&db.polyptr[0] = db.ot[0] | 0x9000000;
db.ot[0] = (unsigned long)db.polyptr;
//sizeof(POLY_G3);
db.polyptr += 0x28;
return;
}
/* PSX VRAM (H)
* ----------- 1024px
* | TL | TR | |
* ----------- v
* | BL | BR |
* -----------
*(W)1024px-->
*
*/
void GPU_ClearVRAM() //5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
RECT16 r;
//Clear TL
r.x = 0;
r.y = 0;
r.w = 512;
r.h = 256;
clear_a_rect(&r);
//Clear BL
r.y = 256;
clear_a_rect(&r);
//Clear BR
r.x = 512;
clear_a_rect(&r);
//Clear TR
r.y = 0;
clear_a_rect(&r);
return;
}
void clear_a_rect(RECT16* r) //5F334(<), 60014(<) (F) (D) (ND)
{
ClearImage(r, 0, 48, 0);
return;
}
void GPU_GetScreenPosition(short* x, short* y) //5F34C, ? (*) (F) (D) (ND)
{
*x = db.disp[0].screen.x;
*y = db.disp[0].screen.y;
return;
}
void GPU_SetScreenPosition(short x, short y) //5F360(<), 60040(<)
{
db.disp[0].screen.x = x;
db.disp[0].screen.y = y;
db.disp[1].screen.x = x;
db.disp[1].screen.y = y;
return;
}
void GPU_SyncBothScreens() //5F374(<), 60054(<)
{
DrawSync(0);
db.current_buffer ^= 1;
if (db.current_buffer != 0)
{
MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
}
else
{
//loc_5F3A8
MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
}
DrawSync(0);
return;
}
///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index) //5F3C8(<), 600A8(<) (F) (D) (ND)
{
DrawSync(0);
VSync(0);
if (buffer_index & 1)
{
PutDispEnv(&db.disp[1]);
}
else
{
PutDispEnv(&db.disp[0]);
}
if (buffer_index & 1)
{
PutDrawEnv(&db.draw[1]);
}
else
{
PutDrawEnv(&db.draw[0]);
}
db.current_buffer = buffer_index & 1 ^ 1;
return;
}
void frig_with_monitor_screen(int a0)
{
UNIMPLEMENTED();
}
void S_AnimateTextures(long nFrames)
{
AnimComp += nFrames;
while (AnimComp > 5)
{
uint16_t* ptr = AnimTextureRanges;
for (uint16_t i = *(ptr++); i > 0; i--, ptr++)
{
MMTEXTURE tmp = RoomTextInfo[*(ptr + 1)];
for (uint16_t j = *ptr++; j > 0; j--, ptr++)
{
RoomTextInfo[*ptr] = RoomTextInfo[*(ptr + 1)];
}
RoomTextInfo[*ptr] = tmp;
}
AnimComp -= 5;
}
if (gfUVRotate) // 19d8
{
uint16_t* t3 = AnimTextureRanges;
AnimatingTexturesVOffset = (AnimatingTexturesVOffset - gfUVRotate * (nFrames / 2)) & 0x1f;
if (nAnimUVRanges > 0)
{
short (*t2)[8][3] = AnimatingTexturesV;
for (int i = 0; i < nAnimUVRanges; i++, t2++)
{
unsigned short num = *t3++;
if (num > 0)
{
short* t1 = t2[i][num];
for (int j = 0; j <= num; j++, t1-=3, t3++)
{
int t0 = 32;
int a2 = AnimatingTexturesVOffset;
MMTEXTURE* a0tm = &RoomTextInfo[*t3];
for (int a3 = 0; a3 < 3; a3++, a2 >>= 1, t0 >>= 1)
{
auto v0__ = (uint8_t)(t1[a3] >> 8);
a0tm->t[a3].v0 = v0__ + a2;
a0tm->t[a3].v1 = v0__ + a2;
a0tm->t[a3].v2 = v0__ + a2 + t0;
a0tm->t[a3].v3 = v0__ + a2 + t0;
}
}
}
}
}
}
frig_with_monitor_screen(0);
}
void PrintGauge(int x, int y, int length)
{
UNIMPLEMENTED();
}
long GetRandomControl() //5E9F0, 926F8 (F)
{
rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
return (rand_1 >> 16) & 0x7FFF;
}
void SeedRandomControl(long seed) //(F)
{
rand_1 = seed;
}
long GetRandomDraw() //5EA18, 5F6F8 (F)
{
rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
return (rand_2 >> 16) * 0x7FFF;
}
void SeedRandomDraw(long seed) //(F)
{
rand_2 = seed;
}
void S_MemCpy(char* pSrc, char* pDest, int size)
{
if (size > 0)
{
while (size-- > 0)
*pSrc++ = *pDest++;
}
}
<commit_msg>specify type<commit_after>#include "MISC.H"
#include "CONTROL.H"
#include "CAMERA.H"
#include "GPU.H"
#include "LOAD_LEV.H"
#include "SPECIFIC.H"
#include "TEXT_S.H"
#include <EMULATOR.H>
#include <LIBETC.H>
#include "GAMEFLOW.H"
#if PSXPC_VERSION || PSXPC_TEST
#include <stdint.h>
#endif
#if PSX_VERSION && !PSXPC_TEST
typedef unsigned int uintptr_t;
#endif
void S_MemSet(char* p, int value, int length)
{
int size;
if (length != 0)
{
if (length > 3)
{
value |= value << 8;
value |= value << 16;
if (((uintptr_t)p) & 3)
{
size = 4 - (((uintptr_t)p) & 3);
length -= 4 - (((uintptr_t)p) & 3);
//loc_5E918
while (size--)
*p++ = value;
}
//loc_5E928
size = length >> 2;
if ((length >> 2))
{
length &= 3;
//loc_5E934
while (size--)
{
((int*)p)[0] = value;
p += 4;
}
}
}
//loc_5E94C
while (length-- != 0)
*p++ = value;
}
}
void S_LongMemCpy(unsigned long* pDest, unsigned long* pSrc, unsigned long size) //5E964(<), ? (F)
{
int i;
if (size > 0)
{
for (i = size / sizeof(unsigned long); i > 0; i--, pDest += 4, pSrc += 4)
{
//loc_5E974
pDest[0] = pSrc[0];
pDest[1] = pSrc[1];
pDest[2] = pSrc[2];
pDest[3] = pSrc[3];
}
//loc_5E9AC
for (i = size & 3; i > 0; i--)
{
*pDest++ = *pSrc++;
}
}
}
void DrawF4(unsigned short x, unsigned short y, unsigned short w, unsigned short h, int unk, int unk2) //5EDF8
{
UNIMPLEMENTED();
}
void DrawTPage(unsigned char a0, unsigned char a1) //5EE78(<), 5FB58(<)
{
UNIMPLEMENTED();
}
void DrawLineH(long a0, long a1, long a2, long a3, long a4, long a5) //5EECC(<)
{
UNIMPLEMENTED();
}
void DrawLineV(long a0, long a1, long a2, long a3, long a4, long a5) //5EF84(<),
{
UNIMPLEMENTED();
}
void LOAD_VSyncHandler() //5F074(<), 5FD54(<) (F)
{
int a0, a1, a2;
if (!LtLoadingBarEnabled)
{
return;
}
//loc_5F08C
GPU_BeginScene();
a0 = 440; //x?
a1 = 200; //y?
a2 = 64; //cd width or height?
if (_first_time_ever)
{
a0 += 24;
a1 += 8;
a2 = 48;
}
//loc_5F0B4
draw_rotate_sprite(a0, a1, a2);
db.current_buffer ^= 1;
GnLastFrameCount = 0;
DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[0]);
return;
}
void LOAD_DrawEnable(unsigned char isEnabled) //5F2C8, 5FFA8
{
LtLoadingBarEnabled = isEnabled;
}
void GPU_BeginScene() //5F0F0(<), 5FDD0(<)
{
db.ot = db.order_table[db.current_buffer];
db.polyptr = (char*)db.poly_buffer[db.current_buffer];
db.curpolybuf = (char*)db.poly_buffer[db.current_buffer];
db.polybuf_limit = (char*)(db.poly_buffer[db.current_buffer] + 26000);
db.pickup_ot = db.pickup_order_table[db.current_buffer];
ClearOTagR(db.order_table[db.current_buffer], db.nOTSize);
Emulator_BeginScene();
}
void draw_rotate_sprite(long a0, long a1, long a2) //5F134, 5FE14 (F)
{
long t0;
short* r_cossinptr;
long t6;
long t5;
long t1;
long t4;
DelRotAng = (DelRotAng - 52) & 0xFFF;
r_cossinptr = &rcossin_tbl[DelRotAng * 2];
t6 = ((-a2 / 2) * r_cossinptr[0]) / 4096;
t5 = ((-a2 / 2) * r_cossinptr[1]) / 4096;
*(long*)&db.polyptr[4] = 0x2C808080;
*(long*)&db.polyptr[12] = 0;
*(long*)&db.polyptr[20] = 0x1303F00;
t0 = t6 - t5;
a2 = -t6;
t4 = a2 - t5;
a2 += t5;
t1 = t6 + t5;
*(short*)&db.polyptr[8] = t0 + (t0 / 2) + a0;
*(short*)&db.polyptr[10] = t5 + t6 + a1;
*(short*)&db.polyptr[16] = t4 + (t4 / 2) + a0;
*(short*)&db.polyptr[18] = -t5 + t6 + a1;
*(short*)&db.polyptr[24] = t1 + (t1 / 2) + a0;
*(short*)&db.polyptr[26] = (t5 - t6) + a1;
*(short*)&db.polyptr[28] = 0x3F; //width/height of loading cd?
*(short*)&db.polyptr[36] = 0x3F3F;
*(short*)&db.polyptr[32] = a2 + (a2 / 2) + a0;
*(short*)&db.polyptr[34] = a1 + (-t5 - t6);
*(long*)&db.polyptr[0] = db.ot[0] | 0x09000000;
db.ot[0] = (unsigned long)&db.polyptr[0];
db.polyptr += 0x28; //sizeof(POLY_F3); * 2?
*(long*)&db.polyptr[4] = 0x2C808080;
*(long*)&db.polyptr[8] = 0x780100;
*(long*)&db.polyptr[12] = 0x6800;
*(long*)&db.polyptr[16] = 0x7801FF;
*(long*)&db.polyptr[20] = 0x13468FF;
*(long*)&db.polyptr[24] = 0xEF0100;
*(short*)&db.polyptr[28] = 0xDF00;
*(long*)&db.polyptr[32] = 0xEF01FF;
*(short*)&db.polyptr[36] = 0xDFFF;
*(long*)&db.polyptr[0] = db.ot[0] | 0x9000000;
db.ot[0] = (unsigned long)db.polyptr;
//sizeof(POLY_G3);
db.polyptr += 0x28;
return;
}
/* PSX VRAM (H)
* ----------- 1024px
* | TL | TR | |
* ----------- v
* | BL | BR |
* -----------
*(W)1024px-->
*
*/
void GPU_ClearVRAM() //5F2D0(<), 5FFB0(<) (F) (D) (ND)
{
RECT16 r;
//Clear TL
r.x = 0;
r.y = 0;
r.w = 512;
r.h = 256;
clear_a_rect(&r);
//Clear BL
r.y = 256;
clear_a_rect(&r);
//Clear BR
r.x = 512;
clear_a_rect(&r);
//Clear TR
r.y = 0;
clear_a_rect(&r);
return;
}
void clear_a_rect(RECT16* r) //5F334(<), 60014(<) (F) (D) (ND)
{
ClearImage(r, 0, 48, 0);
return;
}
void GPU_GetScreenPosition(short* x, short* y) //5F34C, ? (*) (F) (D) (ND)
{
*x = db.disp[0].screen.x;
*y = db.disp[0].screen.y;
return;
}
void GPU_SetScreenPosition(short x, short y) //5F360(<), 60040(<)
{
db.disp[0].screen.x = x;
db.disp[0].screen.y = y;
db.disp[1].screen.x = x;
db.disp[1].screen.y = y;
return;
}
void GPU_SyncBothScreens() //5F374(<), 60054(<)
{
DrawSync(0);
db.current_buffer ^= 1;
if (db.current_buffer != 0)
{
MoveImage(&db.disp[1].disp, db.disp[0].disp.x, db.disp[0].disp.y);
}
else
{
//loc_5F3A8
MoveImage(&db.disp[0].disp, db.disp[1].disp.x, db.disp[1].disp.y);
}
DrawSync(0);
return;
}
///@Gh0stblade - Not sure why this is so unoptimal, we can basically &disp[db.current_buffer]... double check code.
void GPU_FlipToBuffer(int buffer_index) //5F3C8(<), 600A8(<) (F) (D) (ND)
{
DrawSync(0);
VSync(0);
if (buffer_index & 1)
{
PutDispEnv(&db.disp[1]);
}
else
{
PutDispEnv(&db.disp[0]);
}
if (buffer_index & 1)
{
PutDrawEnv(&db.draw[1]);
}
else
{
PutDrawEnv(&db.draw[0]);
}
db.current_buffer = buffer_index & 1 ^ 1;
return;
}
void frig_with_monitor_screen(int a0)
{
UNIMPLEMENTED();
}
void S_AnimateTextures(long nFrames)
{
AnimComp += nFrames;
while (AnimComp > 5)
{
uint16_t* ptr = AnimTextureRanges;
for (uint16_t i = *(ptr++); i > 0; i--, ptr++)
{
MMTEXTURE tmp = RoomTextInfo[*(ptr + 1)];
for (uint16_t j = *ptr++; j > 0; j--, ptr++)
{
RoomTextInfo[*ptr] = RoomTextInfo[*(ptr + 1)];
}
RoomTextInfo[*ptr] = tmp;
}
AnimComp -= 5;
}
if (gfUVRotate) // 19d8
{
uint16_t* t3 = AnimTextureRanges;
AnimatingTexturesVOffset = (AnimatingTexturesVOffset - gfUVRotate * (nFrames / 2)) & 0x1f;
if (nAnimUVRanges > 0)
{
short (*t2)[8][3] = AnimatingTexturesV;
for (int i = 0; i < nAnimUVRanges; i++, t2++)
{
unsigned short num = *t3++;
if (num > 0)
{
short* t1 = t2[i][num];
for (int j = 0; j <= num; j++, t1-=3, t3++)
{
int t0 = 32;
int a2 = AnimatingTexturesVOffset;
MMTEXTURE* a0tm = &RoomTextInfo[*t3];
for (int a3 = 0; a3 < 3; a3++, a2 >>= 1, t0 >>= 1)
{
uint8_t v0__ = (uint8_t)(t1[a3] >> 8);
a0tm->t[a3].v0 = v0__ + a2;
a0tm->t[a3].v1 = v0__ + a2;
a0tm->t[a3].v2 = v0__ + a2 + t0;
a0tm->t[a3].v3 = v0__ + a2 + t0;
}
}
}
}
}
}
frig_with_monitor_screen(0);
}
void PrintGauge(int x, int y, int length)
{
UNIMPLEMENTED();
}
long GetRandomControl() //5E9F0, 926F8 (F)
{
rand_1 = (rand_1 * 0x41C64E6D) + 0x3039;
return (rand_1 >> 16) & 0x7FFF;
}
void SeedRandomControl(long seed) //(F)
{
rand_1 = seed;
}
long GetRandomDraw() //5EA18, 5F6F8 (F)
{
rand_2 = (rand_2 * 0x41C64E6D) + 0x3039;
return (rand_2 >> 16) * 0x7FFF;
}
void SeedRandomDraw(long seed) //(F)
{
rand_2 = seed;
}
void S_MemCpy(char* pSrc, char* pDest, int size)
{
if (size > 0)
{
while (size-- > 0)
*pSrc++ = *pDest++;
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_browser_view_views.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/background.h"
#include "ui/views/view.h"
namespace electron {
NativeBrowserViewViews::NativeBrowserViewViews(
InspectableWebContents* inspectable_web_contents)
: NativeBrowserView(inspectable_web_contents) {}
NativeBrowserViewViews::~NativeBrowserViewViews() = default;
void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) {
auto_resize_flags_ = flags;
ResetAutoResizeProportions();
}
void NativeBrowserViewViews::SetAutoResizeProportions(
const gfx::Size& window_size) {
if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) &&
!auto_horizontal_proportion_set_) {
auto* iwc_view = GetInspectableWebContentsView();
if (iwc_view)
return;
auto* view = iwc_view->GetView();
auto view_bounds = view->bounds();
auto_horizontal_proportion_width_ =
static_cast<float>(window_size.width()) /
static_cast<float>(view_bounds.width());
auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) /
static_cast<float>(view_bounds.x());
auto_horizontal_proportion_set_ = true;
}
if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) &&
!auto_vertical_proportion_set_) {
auto* iwc_view = GetInspectableWebContentsView();
if (iwc_view)
return;
auto* view = iwc_view->GetView();
auto view_bounds = view->bounds();
auto_vertical_proportion_height_ =
static_cast<float>(window_size.height()) /
static_cast<float>(view_bounds.height());
auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) /
static_cast<float>(view_bounds.y());
auto_vertical_proportion_set_ = true;
}
}
void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window,
int width_delta,
int height_delta) {
auto* iwc_view = GetInspectableWebContentsView();
if (iwc_view)
return;
auto* view = iwc_view->GetView();
const auto flags = GetAutoResizeFlags();
if (!(flags & kAutoResizeWidth)) {
width_delta = 0;
}
if (!(flags & kAutoResizeHeight)) {
height_delta = 0;
}
if (height_delta || width_delta) {
auto new_view_size = view->size();
new_view_size.set_width(new_view_size.width() + width_delta);
new_view_size.set_height(new_view_size.height() + height_delta);
view->SetSize(new_view_size);
}
auto new_view_bounds = view->bounds();
if (flags & kAutoResizeHorizontal) {
new_view_bounds.set_width(new_window.width() /
auto_horizontal_proportion_width_);
new_view_bounds.set_x(new_window.width() /
auto_horizontal_proportion_left_);
}
if (flags & kAutoResizeVertical) {
new_view_bounds.set_height(new_window.height() /
auto_vertical_proportion_height_);
new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_);
}
if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) {
view->SetBoundsRect(new_view_bounds);
}
}
void NativeBrowserViewViews::ResetAutoResizeProportions() {
if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) {
auto_horizontal_proportion_set_ = false;
}
if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) {
auto_vertical_proportion_set_ = false;
}
}
void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetView();
view->SetBoundsRect(bounds);
ResetAutoResizeProportions();
}
gfx::Rect NativeBrowserViewViews::GetBounds() {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return gfx::Rect();
return iwc_view->GetView()->bounds();
}
void NativeBrowserViewViews::SetBackgroundColor(SkColor color) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetView();
view->SetBackground(views::CreateSolidBackground(color));
view->SchedulePaint();
}
// static
NativeBrowserView* NativeBrowserView::Create(
InspectableWebContents* inspectable_web_contents) {
return new NativeBrowserViewViews(inspectable_web_contents);
}
} // namespace electron
<commit_msg>fix: correct null pointer checks in autoresizing browser views (#25951)<commit_after>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/native_browser_view_views.h"
#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/background.h"
#include "ui/views/view.h"
namespace electron {
NativeBrowserViewViews::NativeBrowserViewViews(
InspectableWebContents* inspectable_web_contents)
: NativeBrowserView(inspectable_web_contents) {}
NativeBrowserViewViews::~NativeBrowserViewViews() = default;
void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) {
auto_resize_flags_ = flags;
ResetAutoResizeProportions();
}
void NativeBrowserViewViews::SetAutoResizeProportions(
const gfx::Size& window_size) {
if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) &&
!auto_horizontal_proportion_set_) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetView();
auto view_bounds = view->bounds();
auto_horizontal_proportion_width_ =
static_cast<float>(window_size.width()) /
static_cast<float>(view_bounds.width());
auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) /
static_cast<float>(view_bounds.x());
auto_horizontal_proportion_set_ = true;
}
if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) &&
!auto_vertical_proportion_set_) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetView();
auto view_bounds = view->bounds();
auto_vertical_proportion_height_ =
static_cast<float>(window_size.height()) /
static_cast<float>(view_bounds.height());
auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) /
static_cast<float>(view_bounds.y());
auto_vertical_proportion_set_ = true;
}
}
void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window,
int width_delta,
int height_delta) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetView();
const auto flags = GetAutoResizeFlags();
if (!(flags & kAutoResizeWidth)) {
width_delta = 0;
}
if (!(flags & kAutoResizeHeight)) {
height_delta = 0;
}
if (height_delta || width_delta) {
auto new_view_size = view->size();
new_view_size.set_width(new_view_size.width() + width_delta);
new_view_size.set_height(new_view_size.height() + height_delta);
view->SetSize(new_view_size);
}
auto new_view_bounds = view->bounds();
if (flags & kAutoResizeHorizontal) {
new_view_bounds.set_width(new_window.width() /
auto_horizontal_proportion_width_);
new_view_bounds.set_x(new_window.width() /
auto_horizontal_proportion_left_);
}
if (flags & kAutoResizeVertical) {
new_view_bounds.set_height(new_window.height() /
auto_vertical_proportion_height_);
new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_);
}
if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) {
view->SetBoundsRect(new_view_bounds);
}
}
void NativeBrowserViewViews::ResetAutoResizeProportions() {
if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) {
auto_horizontal_proportion_set_ = false;
}
if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) {
auto_vertical_proportion_set_ = false;
}
}
void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetView();
view->SetBoundsRect(bounds);
ResetAutoResizeProportions();
}
gfx::Rect NativeBrowserViewViews::GetBounds() {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return gfx::Rect();
return iwc_view->GetView()->bounds();
}
void NativeBrowserViewViews::SetBackgroundColor(SkColor color) {
auto* iwc_view = GetInspectableWebContentsView();
if (!iwc_view)
return;
auto* view = iwc_view->GetView();
view->SetBackground(views::CreateSolidBackground(color));
view->SchedulePaint();
}
// static
NativeBrowserView* NativeBrowserView::Create(
InspectableWebContents* inspectable_web_contents) {
return new NativeBrowserViewViews(inspectable_web_contents);
}
} // namespace electron
<|endoftext|> |
<commit_before>/**
* This file defines the core graph analysis algorithm.
*/
#ifndef D2_ANALYSIS_HPP
#define D2_ANALYSIS_HPP
#include <d2/detail/all_cycles.hpp>
#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
namespace d2 {
namespace detail {
/**
* Return whether two unordered containers have a non-empty intersection.
*/
template <typename Unordered1, typename Unordered2>
bool unordered_intersects(Unordered1 const& a, Unordered2 const& b) {
typedef typename Unordered1::const_iterator Iterator;
typename Unordered2::const_iterator not_found(boost::end(b));
Iterator elem(boost::begin(a)), last(boost::end(a));
for (; elem != last; ++elem)
if (b.find(*elem) == not_found)
return false;
return true;
}
/**
* Wrap a `BinaryFunction` to implement a visitor for the goodlock algorithm.
*
* @internal If we use an adjacency_matrix to store the segmentation graph, we
* should compute its transitive closure to reduce the complexity of
* the happens-before relation.
*/
template <typename LockGraph, typename SegmentationGraph, typename Function>
class CycleVisitor {
typedef boost::graph_traits<LockGraph> GraphTraits;
typedef typename GraphTraits::edge_descriptor LockGraphEdgeDescriptor;
// Property map to access the edge labels of the lock graph.
typedef typename boost::property_map<
LockGraph, boost::edge_bundle_t
>::const_type EdgeLabelMap;
SegmentationGraph const& sg_;
Function f_;
public:
CycleVisitor(SegmentationGraph const& sg, Function const& f)
: sg_(sg), f_(f)
{ }
/**
* Method called whenever a cycle is found.
*
* If the cycle respects certain conditions, calls the wrapped
* `BinaryFunction` with a sequence of unspecified type containing the
* edges in the cycle and a constant reference to the lock graph.
*
* @note The conditions are those that make a cycle a potential deadlock
* in the lock graph.
*/
template <typename EdgePath>
void cycle(EdgePath const& edge_path, LockGraph const& graph) const {
// These are the conditions for a cycle to be a valid
// potential deadlock:
// For any given pair of edges (e1, e2)
EdgeLabelMap labels = get(boost::edge_bundle, graph);
BOOST_FOREACH(LockGraphEdgeDescriptor e1, edge_path) {
BOOST_FOREACH(LockGraphEdgeDescriptor e2, edge_path) {
if (e1 == e2) continue;
else if (!(
// The threads must differ.
labels[e1].t != labels[e2].t &&
// The guard sets must not overlap.
!unordered_intersects(labels[e1].g, labels[e2].g) &&
// The segments must not be ordered.
!happens_before(labels[e1].s2, labels[e2].s1, sg_)
)) return;
}
}
f_(edge_path, graph);
}
};
} // end namespace detail
/**
* Analyze the lock graph and the segmentation graph to determine whether the
* program execution represented by them contains a deadlock. `f` is called
* whenever a potential deadlock is detected.
*
* @see `detail::CycleVisitor` for more details.
*/
template <typename LockGraph, typename SegmentationGraph, typename Function>
void analyze(LockGraph const& lg, SegmentationGraph const& sg,
Function const& f) {
detail::CycleVisitor<LockGraph, SegmentationGraph, Function> vis(sg, f);
detail::all_cycles(lg, vis);
}
} // end namespace d2
#endif // !D2_ANALYSIS_HPP
<commit_msg>Strip constness of a functor in the analysis to allow for non-const wrapped functors.<commit_after>/**
* This file defines the core graph analysis algorithm.
*/
#ifndef D2_ANALYSIS_HPP
#define D2_ANALYSIS_HPP
#include <d2/detail/all_cycles.hpp>
#include <boost/foreach.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
namespace d2 {
namespace detail {
/**
* Return whether two unordered containers have a non-empty intersection.
*/
template <typename Unordered1, typename Unordered2>
bool unordered_intersects(Unordered1 const& a, Unordered2 const& b) {
typedef typename Unordered1::const_iterator Iterator;
typename Unordered2::const_iterator not_found(boost::end(b));
Iterator elem(boost::begin(a)), last(boost::end(a));
for (; elem != last; ++elem)
if (b.find(*elem) == not_found)
return false;
return true;
}
/**
* Wrap a `BinaryFunction` to implement a visitor for the goodlock algorithm.
*
* @internal If we use an adjacency_matrix to store the segmentation graph, we
* should compute its transitive closure to reduce the complexity of
* the happens-before relation.
*/
template <typename LockGraph, typename SegmentationGraph, typename Function>
class CycleVisitor {
typedef boost::graph_traits<LockGraph> GraphTraits;
typedef typename GraphTraits::edge_descriptor LockGraphEdgeDescriptor;
// Property map to access the edge labels of the lock graph.
typedef typename boost::property_map<
LockGraph, boost::edge_bundle_t
>::const_type EdgeLabelMap;
SegmentationGraph const& sg_;
Function f_;
public:
CycleVisitor(SegmentationGraph const& sg, Function const& f)
: sg_(sg), f_(f)
{ }
/**
* Method called whenever a cycle is found.
*
* If the cycle respects certain conditions, calls the wrapped
* `BinaryFunction` with a sequence of unspecified type containing the
* edges in the cycle and a constant reference to the lock graph.
*
* @note The conditions are those that make a cycle a potential deadlock
* in the lock graph.
* @internal This must not be const in order to allow non-const functors
* to be called.
*/
template <typename EdgePath>
void cycle(EdgePath const& edge_path, LockGraph const& graph) {
// These are the conditions for a cycle to be a valid
// potential deadlock:
// For any given pair of edges (e1, e2)
EdgeLabelMap labels = get(boost::edge_bundle, graph);
BOOST_FOREACH(LockGraphEdgeDescriptor e1, edge_path) {
BOOST_FOREACH(LockGraphEdgeDescriptor e2, edge_path) {
if (e1 == e2) continue;
else if (!(
// The threads must differ.
labels[e1].t != labels[e2].t &&
// The guard sets must not overlap.
!unordered_intersects(labels[e1].g, labels[e2].g) &&
// The segments must not be ordered.
!happens_before(labels[e1].s2, labels[e2].s1, sg_)
)) return;
}
}
f_(edge_path, graph);
}
};
} // end namespace detail
/**
* Analyze the lock graph and the segmentation graph to determine whether the
* program execution represented by them contains a deadlock. `f` is called
* whenever a potential deadlock is detected.
*
* @see `detail::CycleVisitor` for more details.
*/
template <typename LockGraph, typename SegmentationGraph, typename Function>
void analyze(LockGraph const& lg, SegmentationGraph const& sg,
Function const& f) {
detail::CycleVisitor<LockGraph, SegmentationGraph, Function> vis(sg, f);
detail::all_cycles(lg, vis);
}
} // end namespace d2
#endif // !D2_ANALYSIS_HPP
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "surfaceextraction.h"
#include <inviwo/core/properties/propertysemantics.h>
#include <modules/base/algorithm/volume/marchingtetrahedron.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <numeric>
#define TETRA 1
namespace inviwo {
ProcessorClassIdentifier(SurfaceExtraction, "org.inviwo.SurfaceExtraction");
ProcessorDisplayName(SurfaceExtraction, "Surface Extraction");
ProcessorTags(SurfaceExtraction, Tags::CPU);
ProcessorCategory(SurfaceExtraction, "Geometry Creation");
ProcessorCodeState(SurfaceExtraction, CODE_STATE_EXPERIMENTAL);
// TODO make changing color not rerun extraction but only change the color, (and run only
// extraction when volume change or iso change)
SurfaceExtraction::SurfaceExtraction()
: Processor()
, volume_("volume")
, outport_("mesh")
, isoValue_("iso", "ISO Value", 0.5f, 0.0f, 1.0f, 0.01f)
, method_("method", "Method")
, colors_("meshColors", "Mesh Colors")
, dirty_(false) {
addPort(volume_);
addPort(outport_);
addProperty(method_);
addProperty(isoValue_);
addProperty(colors_);
getProgressBar().hide();
method_.addOption("marchingtetrahedra", "Marching Tetrahedra", TETRA);
volume_.onChange(this, &SurfaceExtraction::updateColors);
volume_.onChange(this, &SurfaceExtraction::setMinMax);
method_.setCurrentStateAsDefault();
}
SurfaceExtraction::~SurfaceExtraction() {}
void SurfaceExtraction::process() {
if (!meshes_) {
meshes_ = std::make_shared<std::vector<std::shared_ptr<Mesh>>>();
outport_.setData(meshes_);
}
auto data = volume_.getSourceVectorData();
auto changed = volume_.getChangedOutports();
result_.resize(data.size());
meshes_->resize(data.size());
for (size_t i = 0; i < data.size(); ++i) {
const VolumeRAM* vol = data[i].second->getRepresentation<VolumeRAM>();
switch (method_.get()) {
case TETRA: {
if (result_[i].result.valid() &&
result_[i].result.wait_for(std::chrono::duration<int, std::milli>(0)) ==
std::future_status::ready) {
(*meshes_)[i] = std::move(result_[i].result.get());
result_[i].status = 1.0f;
dirty_ = false;
}
float iso = isoValue_.get();
vec4 color = static_cast<FloatVec4Property*>(colors_[i])->get();
if (!result_[i].result.valid() && (util::contains(changed, data[i].first) ||
result_[i].iso != iso || result_[i].color != color)) {
result_[i].iso = iso;
result_[i].color = color;
result_[i].status = 0.0f;
result_[i].result =
dispatchPool([this, vol, iso, color, i]() -> std::shared_ptr<Mesh> {
auto m = std::shared_ptr<Mesh>(
MarchingTetrahedron::apply(vol, iso, color, [this, i](float s) {
this->result_[i].status = s;
float status = 0;
for (const auto& e : this->result_) status += e.status;
status /= result_.size();
dispatchFront([status](ProgressBar& pb) {
pb.updateProgress(status);
if (status < 1.0f) pb.show();
else pb.hide();
}, std::ref(this->getProgressBar()));
}));
dispatchFront([this]() {
dirty_=true;
invalidate(INVALID_OUTPUT);
});
return std::move(m);
});
}
break;
}
default:
break;
}
}
}
void SurfaceExtraction::setMinMax() {
if (volume_.hasData()) {
auto minmax = std::make_pair(std::numeric_limits<double>::max(),
std::numeric_limits<double>::lowest());
minmax = std::accumulate(volume_.begin(), volume_.end(), minmax,
[](decltype(minmax) mm, std::shared_ptr<const Volume> v) {
return std::make_pair(std::min(mm.first, v->dataMap_.dataRange.x),
std::max(mm.second, v->dataMap_.dataRange.y));
});
isoValue_.setMinValue(static_cast<const float>(minmax.first));
isoValue_.setMaxValue(static_cast<const float>(minmax.second));
}
}
void SurfaceExtraction::updateColors() {
const static vec4 defaultColor[11] = {vec4(1.0f),
vec4(0x1f, 0x77, 0xb4, 255) / vec4(255, 255, 255, 255),
vec4(0xff, 0x7f, 0x0e, 255) / vec4(255, 255, 255, 255),
vec4(0x2c, 0xa0, 0x2c, 255) / vec4(255, 255, 255, 255),
vec4(0xd6, 0x27, 0x28, 255) / vec4(255, 255, 255, 255),
vec4(0x94, 0x67, 0xbd, 255) / vec4(255, 255, 255, 255),
vec4(0x8c, 0x56, 0x4b, 255) / vec4(255, 255, 255, 255),
vec4(0xe3, 0x77, 0xc2, 255) / vec4(255, 255, 255, 255),
vec4(0x7f, 0x7f, 0x7f, 255) / vec4(255, 255, 255, 255),
vec4(0xbc, 0xbd, 0x22, 255) / vec4(255, 255, 255, 255),
vec4(0x17, 0xbe, 0xcf, 255) / vec4(255, 255, 255, 255)};
size_t count = 0;
for (const auto& data : volume_) {
count++;
if (colors_.size() < count) {
const static std::string color = "color";
const static std::string dispName = "Color for Volume ";
FloatVec4Property* colorProp = new FloatVec4Property(
color + toString(count-1), dispName + toString(count), defaultColor[(count-1) % 11]);
colorProp->setCurrentStateAsDefault();
colorProp->setSemantics(PropertySemantics::Color);
colorProp->setSerializationMode(PropertySerializationMode::ALL);
colors_.addProperty(colorProp);
}
colors_[count-1]->setVisible(true);
}
for (size_t i = count; i < colors_.size(); i++) {
colors_[i]->setVisible(false);
}
}
// This will stop the invalidation of the network unless the dirty flag is set.
void SurfaceExtraction::invalidate(InvalidationLevel invalidationLevel,
Property* modifiedProperty) {
notifyObserversInvalidationBegin(this);
PropertyOwner::invalidate(invalidationLevel, modifiedProperty);
if (dirty_ || volume_.isChanged()) outport_.invalidate(INVALID_OUTPUT);
notifyObserversInvalidationEnd(this);
}
SurfaceExtraction::task::task(task&& rhs)
: result(std::move(rhs.result))
, iso(rhs.iso)
, color(std::move(rhs.color))
, status(rhs.status) {
}
SurfaceExtraction::task& SurfaceExtraction::task::operator=(task&& that) {
if (this != &that) {
result = std::move(that.result);
iso = that.iso;
color = std::move(that.color);
status = that.status;
}
return *this;
}
} // namespace
<commit_msg>Base: SurfaceExtraction minor update<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include "surfaceextraction.h"
#include <inviwo/core/properties/propertysemantics.h>
#include <modules/base/algorithm/volume/marchingtetrahedron.h>
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/stdextensions.h>
#include <numeric>
#define TETRA 1
namespace inviwo {
ProcessorClassIdentifier(SurfaceExtraction, "org.inviwo.SurfaceExtraction");
ProcessorDisplayName(SurfaceExtraction, "Surface Extraction");
ProcessorTags(SurfaceExtraction, Tags::CPU);
ProcessorCategory(SurfaceExtraction, "Geometry Creation");
ProcessorCodeState(SurfaceExtraction, CODE_STATE_EXPERIMENTAL);
// TODO make changing color not rerun extraction but only change the color, (and run only
// extraction when volume change or iso change)
SurfaceExtraction::SurfaceExtraction()
: Processor()
, volume_("volume")
, outport_("mesh")
, isoValue_("iso", "ISO Value", 0.5f, 0.0f, 1.0f, 0.01f)
, method_("method", "Method")
, colors_("meshColors", "Mesh Colors")
, dirty_(false) {
addPort(volume_);
addPort(outport_);
addProperty(method_);
addProperty(isoValue_);
addProperty(colors_);
getProgressBar().hide();
method_.addOption("marchingtetrahedra", "Marching Tetrahedra", TETRA);
volume_.onChange(this, &SurfaceExtraction::updateColors);
volume_.onChange(this, &SurfaceExtraction::setMinMax);
method_.setCurrentStateAsDefault();
}
SurfaceExtraction::~SurfaceExtraction() {}
void SurfaceExtraction::process() {
if (!meshes_) {
meshes_ = std::make_shared<std::vector<std::shared_ptr<Mesh>>>();
outport_.setData(meshes_);
}
auto data = volume_.getSourceVectorData();
auto changed = volume_.getChangedOutports();
result_.resize(data.size());
meshes_->resize(data.size());
for (size_t i = 0; i < data.size(); ++i) {
const VolumeRAM* vol = data[i].second->getRepresentation<VolumeRAM>();
switch (method_.get()) {
case TETRA: {
if (util::is_future_ready(result_[i].result)) {
(*meshes_)[i] = std::move(result_[i].result.get());
result_[i].status = 1.0f;
dirty_ = false;
}
float iso = isoValue_.get();
vec4 color = static_cast<FloatVec4Property*>(colors_[i])->get();
if (!result_[i].result.valid() && (util::contains(changed, data[i].first) ||
result_[i].iso != iso || result_[i].color != color)) {
result_[i].iso = iso;
result_[i].color = color;
result_[i].status = 0.0f;
result_[i].result =
dispatchPool([this, vol, iso, color, i]() -> std::shared_ptr<Mesh> {
auto m = std::shared_ptr<Mesh>(
MarchingTetrahedron::apply(vol, iso, color, [this, i](float s) {
this->result_[i].status = s;
float status = 0;
for (const auto& e : this->result_) status += e.status;
status /= result_.size();
dispatchFront([status](ProgressBar& pb) {
pb.updateProgress(status);
if (status < 1.0f) pb.show();
else pb.hide();
}, std::ref(this->getProgressBar()));
}));
dispatchFront([this]() {
dirty_=true;
invalidate(INVALID_OUTPUT);
});
return std::move(m);
});
}
break;
}
default:
break;
}
}
}
void SurfaceExtraction::setMinMax() {
if (volume_.hasData()) {
auto minmax = std::make_pair(std::numeric_limits<double>::max(),
std::numeric_limits<double>::lowest());
minmax = std::accumulate(volume_.begin(), volume_.end(), minmax,
[](decltype(minmax) mm, std::shared_ptr<const Volume> v) {
return std::make_pair(std::min(mm.first, v->dataMap_.dataRange.x),
std::max(mm.second, v->dataMap_.dataRange.y));
});
isoValue_.setMinValue(static_cast<const float>(minmax.first));
isoValue_.setMaxValue(static_cast<const float>(minmax.second));
}
}
void SurfaceExtraction::updateColors() {
const static vec4 defaultColor[11] = {vec4(1.0f),
vec4(0x1f, 0x77, 0xb4, 255) / vec4(255, 255, 255, 255),
vec4(0xff, 0x7f, 0x0e, 255) / vec4(255, 255, 255, 255),
vec4(0x2c, 0xa0, 0x2c, 255) / vec4(255, 255, 255, 255),
vec4(0xd6, 0x27, 0x28, 255) / vec4(255, 255, 255, 255),
vec4(0x94, 0x67, 0xbd, 255) / vec4(255, 255, 255, 255),
vec4(0x8c, 0x56, 0x4b, 255) / vec4(255, 255, 255, 255),
vec4(0xe3, 0x77, 0xc2, 255) / vec4(255, 255, 255, 255),
vec4(0x7f, 0x7f, 0x7f, 255) / vec4(255, 255, 255, 255),
vec4(0xbc, 0xbd, 0x22, 255) / vec4(255, 255, 255, 255),
vec4(0x17, 0xbe, 0xcf, 255) / vec4(255, 255, 255, 255)};
size_t count = 0;
for (const auto& data : volume_) {
count++;
if (colors_.size() < count) {
const static std::string color = "color";
const static std::string dispName = "Color for Volume ";
FloatVec4Property* colorProp = new FloatVec4Property(
color + toString(count-1), dispName + toString(count), defaultColor[(count-1) % 11]);
colorProp->setCurrentStateAsDefault();
colorProp->setSemantics(PropertySemantics::Color);
colorProp->setSerializationMode(PropertySerializationMode::ALL);
colors_.addProperty(colorProp);
}
colors_[count-1]->setVisible(true);
}
for (size_t i = count; i < colors_.size(); i++) {
colors_[i]->setVisible(false);
}
}
// This will stop the invalidation of the network unless the dirty flag is set.
void SurfaceExtraction::invalidate(InvalidationLevel invalidationLevel,
Property* modifiedProperty) {
notifyObserversInvalidationBegin(this);
PropertyOwner::invalidate(invalidationLevel, modifiedProperty);
if (dirty_ || volume_.isChanged()) outport_.invalidate(INVALID_OUTPUT);
notifyObserversInvalidationEnd(this);
}
SurfaceExtraction::task::task(task&& rhs)
: result(std::move(rhs.result))
, iso(rhs.iso)
, color(std::move(rhs.color))
, status(rhs.status) {
}
SurfaceExtraction::task& SurfaceExtraction::task::operator=(task&& that) {
if (this != &that) {
result = std::move(that.result);
iso = that.iso;
color = std::move(that.color);
status = that.status;
}
return *this;
}
} // namespace
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef ETL_FAST_OP_HPP
#define ETL_FAST_OP_HPP
#include <random>
#include <functional>
#include <ctime>
#include "math.hpp"
namespace etl {
template<typename T>
struct scalar {
const T value;
explicit constexpr scalar(T v) : value(v) {}
constexpr const T operator[](std::size_t) const {
return value;
}
constexpr const T operator()(std::size_t) const {
return value;
}
constexpr const T operator()(std::size_t, std::size_t) const {
return value;
}
};
template<typename T>
struct hflip_transformer {
using sub_type = T;
const T& sub;
explicit hflip_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[size(sub) - 1 - i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(size(sub) - 1 - i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(i, columns(sub) - 1 - j);
}
};
template<typename T>
struct vflip_transformer {
using sub_type = T;
const T& sub;
explicit vflip_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(rows(sub) - 1 - i, j);
}
};
template<typename T>
struct fflip_transformer {
using sub_type = T;
const T& sub;
explicit fflip_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(rows(sub) - 1 - i, columns(sub) - 1 - j);
}
};
template<typename T>
struct transpose_transformer {
using sub_type = T;
const T& sub;
explicit transpose_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(j, i);
}
};
template<typename T, std::size_t D>
struct dim_view {
static_assert(D > 0 || D < 3, "Invalid dimension");
using sub_type = T;
const T& sub;
const std::size_t i;
dim_view(const T& vec, std::size_t i) : sub(vec), i(i) {}
typename T::value_type operator[](std::size_t j) const {
if(D == 1){
return sub(i, j);
} else if(D == 2){
return sub(j, i);
}
}
typename T::value_type operator()(std::size_t j) const {
if(D == 1){
return sub(i, j);
} else if(D == 2){
return sub(j, i);
}
}
};
template<typename T>
struct sub_view {
using parent_type = T;
const T& parent;
const std::size_t i;
sub_view(const T& parent, std::size_t i) : parent(parent), i(i) {}
typename T::value_type operator[](std::size_t j) const {
return parent[i * subsize(parent) + j];
}
template<typename... S>
typename T::value_type operator()(S... args) const {
return parent(i, static_cast<size_t>(args)...);
}
};
template<typename T, std::size_t Rows, std::size_t Columns>
struct fast_matrix_view {
static_assert(Rows > 0 && Columns > 0 , "Invalid dimensions");
using value_type = typename T::value_type;
const T& sub;
explicit fast_matrix_view(const T& sub) : sub(sub) {}
value_type operator[](std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t i, std::size_t j) const {
return sub(i * Columns + j);
}
};
template<typename T>
struct dyn_matrix_view {
using value_type = typename T::value_type;
const T& sub;
std::size_t rows;
std::size_t columns;
dyn_matrix_view(const T& sub, std::size_t rows, std::size_t columns) : sub(sub), rows(rows), columns(columns) {}
value_type operator[](std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t i, std::size_t j) const {
return sub(i * columns + j);
}
};
template<typename T>
struct plus_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs + rhs;
}
};
template<typename T>
struct minus_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs - rhs;
}
};
template<typename T>
struct mul_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs * rhs;
}
};
template<typename T>
struct div_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs / rhs;
}
};
template<typename T>
struct mod_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs % rhs;
}
};
template<typename T>
struct abs_unary_op {
static constexpr T apply(const T& x){
return std::abs(x);
}
};
template<typename T>
struct log_unary_op {
static constexpr T apply(const T& x){
return std::log(x);
}
};
template<typename T>
struct exp_unary_op {
static constexpr T apply(const T& x){
return std::exp(x);
}
};
template<typename T>
struct sign_unary_op {
static constexpr T apply(const T& x){
return sign(x);
}
};
template<typename T>
struct sigmoid_unary_op {
static constexpr T apply(const T& x){
return logistic_sigmoid(x);
}
};
template<typename T>
struct softplus_unary_op {
static constexpr T apply(const T& x){
return softplus(x);
}
};
template<typename T>
struct minus_unary_op {
static constexpr T apply(const T& x){
return -x;
}
};
template<typename T>
struct plus_unary_op {
static constexpr T apply(const T& x){
return +x;
}
};
template<typename T>
struct identity_unary_op {
static constexpr T apply(const T& x){
return x;
}
};
template<typename T>
struct bernoulli_unary_op {
static T apply(const T& x){
static std::default_random_engine rand_engine(std::time(nullptr));
static std::uniform_real_distribution<double> normal_distribution(0.0, 1.0);
static auto normal_generator = std::bind(normal_distribution, rand_engine);
return x > normal_generator() ? 1.0 : 0.0;
}
};
template<typename T>
struct uniform_noise_unary_op {
static T apply(const T& x){
static std::default_random_engine rand_engine(std::time(nullptr));
static std::uniform_real_distribution<double> real_distribution(0.0, 1.0);
static auto noise = std::bind(real_distribution, rand_engine);
return x + noise();
}
};
template<typename T>
struct normal_noise_unary_op {
static T apply(const T& x){
static std::default_random_engine rand_engine(std::time(nullptr));
static std::normal_distribution<double> normal_distribution(0.0, 1.0);
static auto noise = std::bind(normal_distribution, rand_engine);
return x + noise();
}
};
template<typename T>
struct logistic_noise_unary_op {
static T apply(const T& x){
static std::default_random_engine rand_engine(std::time(nullptr));
std::normal_distribution<double> noise_distribution(0.0, logistic_sigmoid(x));
auto noise = std::bind(noise_distribution, rand_engine);
return x + noise();
}
};
template<typename T, typename E>
struct ranged_noise_binary_op {
static T apply(const T& x, E value){
static std::default_random_engine rand_engine(std::time(nullptr));
static std::normal_distribution<double> normal_distribution(0.0, 1.0);
static auto noise = std::bind(normal_distribution, rand_engine);
if(x == 0.0 || x == value){
return x;
} else {
return x + noise();
}
}
};
template<typename T, typename E>
struct max_binary_op {
static constexpr T apply(const T& x, E value){
return std::max(x, value);
}
};
template<typename T, typename E>
struct min_binary_op {
static constexpr T apply(const T& x, E value){
return std::min(x, value);
}
};
} //end of namespace etl
#endif
<commit_msg>Use Mersenne Twister method<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef ETL_FAST_OP_HPP
#define ETL_FAST_OP_HPP
#include <random>
#include <functional>
#include <ctime>
#include "math.hpp"
namespace etl {
using random_engine = std::mt19937_64;
template<typename T>
struct scalar {
const T value;
explicit constexpr scalar(T v) : value(v) {}
constexpr const T operator[](std::size_t) const {
return value;
}
constexpr const T operator()(std::size_t) const {
return value;
}
constexpr const T operator()(std::size_t, std::size_t) const {
return value;
}
};
template<typename T>
struct hflip_transformer {
using sub_type = T;
const T& sub;
explicit hflip_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[size(sub) - 1 - i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(size(sub) - 1 - i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(i, columns(sub) - 1 - j);
}
};
template<typename T>
struct vflip_transformer {
using sub_type = T;
const T& sub;
explicit vflip_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(rows(sub) - 1 - i, j);
}
};
template<typename T>
struct fflip_transformer {
using sub_type = T;
const T& sub;
explicit fflip_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(rows(sub) - 1 - i, columns(sub) - 1 - j);
}
};
template<typename T>
struct transpose_transformer {
using sub_type = T;
const T& sub;
explicit transpose_transformer(const T& vec) : sub(vec) {}
typename T::value_type operator[](std::size_t i) const {
return sub[i];
}
typename T::value_type operator()(std::size_t i) const {
return sub(i);
}
typename T::value_type operator()(std::size_t i, std::size_t j) const {
return sub(j, i);
}
};
template<typename T, std::size_t D>
struct dim_view {
static_assert(D > 0 || D < 3, "Invalid dimension");
using sub_type = T;
const T& sub;
const std::size_t i;
dim_view(const T& vec, std::size_t i) : sub(vec), i(i) {}
typename T::value_type operator[](std::size_t j) const {
if(D == 1){
return sub(i, j);
} else if(D == 2){
return sub(j, i);
}
}
typename T::value_type operator()(std::size_t j) const {
if(D == 1){
return sub(i, j);
} else if(D == 2){
return sub(j, i);
}
}
};
template<typename T>
struct sub_view {
using parent_type = T;
const T& parent;
const std::size_t i;
sub_view(const T& parent, std::size_t i) : parent(parent), i(i) {}
typename T::value_type operator[](std::size_t j) const {
return parent[i * subsize(parent) + j];
}
template<typename... S>
typename T::value_type operator()(S... args) const {
return parent(i, static_cast<size_t>(args)...);
}
};
template<typename T, std::size_t Rows, std::size_t Columns>
struct fast_matrix_view {
static_assert(Rows > 0 && Columns > 0 , "Invalid dimensions");
using value_type = typename T::value_type;
const T& sub;
explicit fast_matrix_view(const T& sub) : sub(sub) {}
value_type operator[](std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t i, std::size_t j) const {
return sub(i * Columns + j);
}
};
template<typename T>
struct dyn_matrix_view {
using value_type = typename T::value_type;
const T& sub;
std::size_t rows;
std::size_t columns;
dyn_matrix_view(const T& sub, std::size_t rows, std::size_t columns) : sub(sub), rows(rows), columns(columns) {}
value_type operator[](std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t j) const {
return sub(j);
}
value_type operator()(std::size_t i, std::size_t j) const {
return sub(i * columns + j);
}
};
template<typename T>
struct plus_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs + rhs;
}
};
template<typename T>
struct minus_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs - rhs;
}
};
template<typename T>
struct mul_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs * rhs;
}
};
template<typename T>
struct div_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs / rhs;
}
};
template<typename T>
struct mod_binary_op {
static constexpr T apply(const T& lhs, const T& rhs){
return lhs % rhs;
}
};
template<typename T>
struct abs_unary_op {
static constexpr T apply(const T& x){
return std::abs(x);
}
};
template<typename T>
struct log_unary_op {
static constexpr T apply(const T& x){
return std::log(x);
}
};
template<typename T>
struct exp_unary_op {
static constexpr T apply(const T& x){
return std::exp(x);
}
};
template<typename T>
struct sign_unary_op {
static constexpr T apply(const T& x){
return sign(x);
}
};
template<typename T>
struct sigmoid_unary_op {
static constexpr T apply(const T& x){
return logistic_sigmoid(x);
}
};
template<typename T>
struct softplus_unary_op {
static constexpr T apply(const T& x){
return softplus(x);
}
};
template<typename T>
struct minus_unary_op {
static constexpr T apply(const T& x){
return -x;
}
};
template<typename T>
struct plus_unary_op {
static constexpr T apply(const T& x){
return +x;
}
};
template<typename T>
struct identity_unary_op {
static constexpr T apply(const T& x){
return x;
}
};
template<typename T>
struct bernoulli_unary_op {
static T apply(const T& x){
static random_engine rand_engine(std::time(nullptr));
static std::uniform_real_distribution<double> normal_distribution(0.0, 1.0);
static auto normal_generator = std::bind(normal_distribution, rand_engine);
return x > normal_generator() ? 1.0 : 0.0;
}
};
template<typename T>
struct uniform_noise_unary_op {
static T apply(const T& x){
static random_engine rand_engine(std::time(nullptr));
static std::uniform_real_distribution<double> real_distribution(0.0, 1.0);
static auto noise = std::bind(real_distribution, rand_engine);
return x + noise();
}
};
template<typename T>
struct normal_noise_unary_op {
static T apply(const T& x){
static random_engine rand_engine(std::time(nullptr));
static std::normal_distribution<double> normal_distribution(0.0, 1.0);
static auto noise = std::bind(normal_distribution, rand_engine);
return x + noise();
}
};
template<typename T>
struct logistic_noise_unary_op {
static T apply(const T& x){
static random_engine rand_engine(std::time(nullptr));
std::normal_distribution<double> noise_distribution(0.0, logistic_sigmoid(x));
auto noise = std::bind(noise_distribution, rand_engine);
return x + noise();
}
};
template<typename T, typename E>
struct ranged_noise_binary_op {
static T apply(const T& x, E value){
static random_engine rand_engine(std::time(nullptr));
static std::normal_distribution<double> normal_distribution(0.0, 1.0);
static auto noise = std::bind(normal_distribution, rand_engine);
if(x == 0.0 || x == value){
return x;
} else {
return x + noise();
}
}
};
template<typename T, typename E>
struct max_binary_op {
static constexpr T apply(const T& x, E value){
return std::max(x, value);
}
};
template<typename T, typename E>
struct min_binary_op {
static constexpr T apply(const T& x, E value){
return std::min(x, value);
}
};
} //end of namespace etl
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/common/monitor/monitor_buffer.h"
#include <string>
#include "gtest/gtest.h"
#include "modules/common/monitor/monitor.h"
namespace apollo {
namespace common {
namespace monitor {
class MonitorBufferTest : public ::testing::Test {
protected:
void SetUp() override { buffer_ = new MonitorBuffer(nullptr); }
void TearDown() override { delete buffer_; }
MonitorBuffer *buffer_ = nullptr;
};
TEST_F(MonitorBufferTest, PrintLog) {
FLAGS_logtostderr = true;
FLAGS_v = 4;
{
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_TRUE(testing::internal::GetCapturedStderr().empty());
}
{
buffer_->INFO("INFO_msg");
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_NE(std::string::npos,
testing::internal::GetCapturedStderr().find("INFO_msg"));
}
{
buffer_->ERROR("ERROR_msg");
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_NE(std::string::npos,
testing::internal::GetCapturedStderr().find("ERROR_msg"));
}
{
buffer_->WARN("WARN_msg");
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_NE(std::string::npos,
testing::internal::GetCapturedStderr().find("WARN_msg"));
}
{
buffer_->FATAL("FATAL_msg");
EXPECT_DEATH(buffer_->PrintLog(), "");
}
}
TEST_F(MonitorBufferTest, RegisterMacro) {
{
buffer_->INFO("Info");
EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
const auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::INFO, item.first);
EXPECT_EQ("Info", item.second);
}
{
buffer_->ERROR("Error");
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
const auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("Error", item.second);
}
}
TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
buffer_->AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
const auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("TestError", item.second);
}
TEST_F(MonitorBufferTest, Operator) {
buffer_->ERROR() << "Hi";
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("Hi", item.second);
(*buffer_) << " How"
<< " are"
<< " you";
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("Hi How are you", item.second);
buffer_->INFO() << 3 << "pieces";
EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::INFO, item.first);
EXPECT_EQ("3pieces", item.second);
const char *fake_input = nullptr;
EXPECT_TRUE(&(buffer_->INFO() << fake_input) == buffer_);
}
} // namespace monitor
} // namespace common
} // namespace apollo
<commit_msg>security: fix security report problem.<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/common/monitor/monitor_buffer.h"
#include <string>
#include "gtest/gtest.h"
#include "modules/common/monitor/monitor.h"
namespace apollo {
namespace common {
namespace monitor {
class MonitorBufferTest : public ::testing::Test {
protected:
void SetUp() override { buffer_ = new MonitorBuffer(nullptr); }
void TearDown() override { delete buffer_; }
MonitorBuffer *buffer_ = nullptr;
};
TEST_F(MonitorBufferTest, PrintLog) {
FLAGS_logtostderr = true;
FLAGS_v = 4;
{
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_TRUE(testing::internal::GetCapturedStderr().empty());
}
{
buffer_->INFO("INFO_msg");
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_NE(std::string::npos,
testing::internal::GetCapturedStderr().find("INFO_msg"));
}
{
buffer_->ERROR("ERROR_msg");
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_NE(std::string::npos,
testing::internal::GetCapturedStderr().find("ERROR_msg"));
}
{
buffer_->WARN("WARN_msg");
testing::internal::CaptureStderr();
buffer_->PrintLog();
EXPECT_NE(std::string::npos,
testing::internal::GetCapturedStderr().find("WARN_msg"));
}
{
buffer_->FATAL("FATAL_msg");
EXPECT_DEATH(buffer_->PrintLog(), "");
}
}
TEST_F(MonitorBufferTest, RegisterMacro) {
{
buffer_->INFO("Info");
EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
const auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::INFO, item.first);
EXPECT_EQ("Info", item.second);
}
{
buffer_->ERROR("Error");
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
const auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("Error", item.second);
}
}
TEST_F(MonitorBufferTest, AddMonitorMsgItem) {
buffer_->AddMonitorMsgItem(MonitorMessageItem::ERROR, "TestError");
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
const auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("TestError", item.second);
}
TEST_F(MonitorBufferTest, Operator) {
buffer_->ERROR() << "Hi";
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
auto &item = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("Hi", item.second);
(*buffer_) << " How"
<< " are"
<< " you";
EXPECT_EQ(MonitorMessageItem::ERROR, buffer_->level_);
ASSERT_EQ(1, buffer_->monitor_msg_items_.size());
EXPECT_EQ(MonitorMessageItem::ERROR, item.first);
EXPECT_EQ("Hi How are you", item.second);
buffer_->INFO() << 3 << "pieces";
EXPECT_EQ(MonitorMessageItem::INFO, buffer_->level_);
ASSERT_EQ(2, buffer_->monitor_msg_items_.size());
auto item2 = buffer_->monitor_msg_items_.back();
EXPECT_EQ(MonitorMessageItem::INFO, item2.first);
EXPECT_EQ("3pieces", item2.second);
const char *fake_input = nullptr;
EXPECT_TRUE(&(buffer_->INFO() << fake_input) == buffer_);
}
} // namespace monitor
} // namespace common
} // namespace apollo
<|endoftext|> |
<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_VERSION_HPP
#define OPENCV_VERSION_HPP
#define CV_VERSION_MAJOR 4
#define CV_VERSION_MINOR 4
#define CV_VERSION_REVISION 0
#define CV_VERSION_STATUS "-pre"
#define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)
#define CVAUX_STRW_EXP(__A) L ## #__A
#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A)
#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS
/* old style version constants*/
#define CV_MAJOR_VERSION CV_VERSION_MAJOR
#define CV_MINOR_VERSION CV_VERSION_MINOR
#define CV_SUBMINOR_VERSION CV_VERSION_REVISION
#endif // OPENCV_VERSION_HPP
<commit_msg>release: OpenCV 4.4.0<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef OPENCV_VERSION_HPP
#define OPENCV_VERSION_HPP
#define CV_VERSION_MAJOR 4
#define CV_VERSION_MINOR 4
#define CV_VERSION_REVISION 0
#define CV_VERSION_STATUS ""
#define CVAUX_STR_EXP(__A) #__A
#define CVAUX_STR(__A) CVAUX_STR_EXP(__A)
#define CVAUX_STRW_EXP(__A) L ## #__A
#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A)
#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS
/* old style version constants*/
#define CV_MAJOR_VERSION CV_VERSION_MAJOR
#define CV_MINOR_VERSION CV_VERSION_MINOR
#define CV_SUBMINOR_VERSION CV_VERSION_REVISION
#endif // OPENCV_VERSION_HPP
<|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/command_line.h"
#include "base/time.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_cryptohome_library.h"
#include "chrome/browser/chromeos/cros/mock_library_loader.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/chromeos/cros/mock_power_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Return;
class LoginTestBase : public CrosInProcessBrowserTest {
public:
LoginTestBase() : mock_cryptohome_library_(NULL),
mock_screen_lock_library_(NULL) {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
cros_mock_->InitStatusAreaMocks();
cros_mock_->SetStatusAreaMocksExpectations();
cros_mock_->InitMockCryptohomeLibrary();
cros_mock_->InitMockScreenLockLibrary();
mock_cryptohome_library_ = cros_mock_->mock_cryptohome_library();
mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
EXPECT_CALL(*mock_cryptohome_library_, IsMounted())
.WillRepeatedly(Return(true));
}
MockCryptohomeLibrary* mock_cryptohome_library_;
MockScreenLockLibrary* mock_screen_lock_library_;
private:
DISALLOW_COPY_AND_ASSIGN(LoginTestBase);
};
class LoginUserTest : public LoginTestBase {
protected:
virtual void SetUpInProcessBrowserTestFixture() {
LoginTestBase::SetUpInProcessBrowserTestFixture();
// TODO(nkostylev): Remove this once Aura build includes ScreenLocker.
#if !defined(USE_AURA)
EXPECT_CALL(*mock_screen_lock_library_, AddObserver(_))
.Times(AtLeast(1))
.WillRepeatedly(Return());
EXPECT_CALL(*mock_screen_lock_library_, RemoveObserver(_))
.Times(AtLeast(1))
.WillRepeatedly(Return());
#endif
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginUser, "[email protected]");
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
class LoginProfileTest : public LoginUserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
// After a chrome crash, the session manager will restart chrome with
// the -login-user flag indicating that the user is already logged in.
// This profile should NOT be an OTR profile.
IN_PROC_BROWSER_TEST_F(LoginUserTest, UserPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("user", profile->GetPath().BaseName().value());
EXPECT_FALSE(profile->IsOffTheRecord());
}
// On initial launch, we should get the OTR default profile.
IN_PROC_BROWSER_TEST_F(LoginProfileTest, UserNotPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("Default", profile->GetPath().BaseName().value());
EXPECT_TRUE(profile->IsOffTheRecord());
// Ensure there's extension service for this profile.
EXPECT_TRUE(profile->GetExtensionService());
}
} // namespace chromeos
<commit_msg>Remove obsolete ifdef in login browsertests.<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/command_line.h"
#include "base/time.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_cryptohome_library.h"
#include "chrome/browser/chromeos/cros/mock_library_loader.h"
#include "chrome/browser/chromeos/cros/mock_network_library.h"
#include "chrome/browser/chromeos/cros/mock_power_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Return;
class LoginTestBase : public CrosInProcessBrowserTest {
public:
LoginTestBase() : mock_cryptohome_library_(NULL),
mock_screen_lock_library_(NULL) {
}
protected:
virtual void SetUpInProcessBrowserTestFixture() {
cros_mock_->InitStatusAreaMocks();
cros_mock_->SetStatusAreaMocksExpectations();
cros_mock_->InitMockCryptohomeLibrary();
cros_mock_->InitMockScreenLockLibrary();
mock_cryptohome_library_ = cros_mock_->mock_cryptohome_library();
mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
EXPECT_CALL(*mock_cryptohome_library_, IsMounted())
.WillRepeatedly(Return(true));
}
MockCryptohomeLibrary* mock_cryptohome_library_;
MockScreenLockLibrary* mock_screen_lock_library_;
private:
DISALLOW_COPY_AND_ASSIGN(LoginTestBase);
};
class LoginUserTest : public LoginTestBase {
protected:
virtual void SetUpInProcessBrowserTestFixture() {
LoginTestBase::SetUpInProcessBrowserTestFixture();
EXPECT_CALL(*mock_screen_lock_library_, AddObserver(_))
.Times(AtLeast(1))
.WillRepeatedly(Return());
EXPECT_CALL(*mock_screen_lock_library_, RemoveObserver(_))
.Times(AtLeast(1))
.WillRepeatedly(Return());
}
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginUser, "[email protected]");
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
class LoginProfileTest : public LoginUserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) {
command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
command_line->AppendSwitch(switches::kNoFirstRun);
}
};
// After a chrome crash, the session manager will restart chrome with
// the -login-user flag indicating that the user is already logged in.
// This profile should NOT be an OTR profile.
IN_PROC_BROWSER_TEST_F(LoginUserTest, UserPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("user", profile->GetPath().BaseName().value());
EXPECT_FALSE(profile->IsOffTheRecord());
}
// On initial launch, we should get the OTR default profile.
IN_PROC_BROWSER_TEST_F(LoginProfileTest, UserNotPassed) {
Profile* profile = browser()->profile();
EXPECT_EQ("Default", profile->GetPath().BaseName().value());
EXPECT_TRUE(profile->IsOffTheRecord());
// Ensure there's extension service for this profile.
EXPECT_TRUE(profile->GetExtensionService());
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macro_expander.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 09:27:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <rtl/bootstrap.hxx>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implbase3.hxx>
#include <cppuhelper/compbase3.hxx>
#include <cppuhelper/component_context.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include "com/sun/star/uno/RuntimeException.hpp"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
#define SERVICE_NAME_A "com.sun.star.lang.MacroExpander"
#define SERVICE_NAME_B "com.sun.star.lang.BootstrapMacroExpander"
#define IMPL_NAME "com.sun.star.lang.comp.cppuhelper.BootstrapMacroExpander"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace cppu
{
//---- private forward -----------------------------------------------------------------------------
Bootstrap const & get_unorc() SAL_THROW( () );
}
namespace
{
inline OUString s_impl_name() { return OUSTR(IMPL_NAME); }
static Sequence< OUString > const & s_get_service_names()
{
static Sequence< OUString > const * s_pnames = 0;
if (! s_pnames)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_pnames)
{
static Sequence< OUString > s_names( 2 );
s_names[ 0 ] = OUSTR(SERVICE_NAME_A);
s_names[ 1 ] = OUSTR(SERVICE_NAME_B);
s_pnames = &s_names;
}
}
return *s_pnames;
}
typedef ::cppu::WeakComponentImplHelper3<
util::XMacroExpander, lang::XServiceInfo, lang::XInitialization > t_uno_impl;
struct mutex_holder
{
Mutex m_mutex;
};
class Bootstrap_MacroExpander : public mutex_holder, public t_uno_impl
{
rtlBootstrapHandle m_bstrap;
OUString m_rc_path;
protected:
virtual void SAL_CALL disposing();
public:
inline Bootstrap_MacroExpander( Reference< XComponentContext > const & ) SAL_THROW( () )
: t_uno_impl( m_mutex ),
m_bstrap( 0 )
{}
virtual ~Bootstrap_MacroExpander()
SAL_THROW( () );
// XMacroExpander impl
virtual OUString SAL_CALL expandMacros( OUString const & exp )
throw (lang::IllegalArgumentException);
// XInitialization impl
virtual void SAL_CALL initialize(
Sequence< Any > const & arguments )
throw (Exception);
// XServiceInfo impl
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName )
throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
throw (RuntimeException);
};
//__________________________________________________________________________________________________
void Bootstrap_MacroExpander::disposing()
{
if (m_bstrap)
{
rtl_bootstrap_args_close( m_bstrap );
m_bstrap = 0;
}
}
//__________________________________________________________________________________________________
Bootstrap_MacroExpander::~Bootstrap_MacroExpander() SAL_THROW( () )
{
if (m_bstrap)
{
rtl_bootstrap_args_close( m_bstrap );
m_bstrap = 0;
}
}
// XServiceInfo impl
//__________________________________________________________________________________________________
OUString Bootstrap_MacroExpander::getImplementationName()
throw (RuntimeException)
{
return s_impl_name();
}
//__________________________________________________________________________________________________
sal_Bool Bootstrap_MacroExpander::supportsService( OUString const & serviceName )
throw (RuntimeException)
{
Sequence< OUString > const & service_names = s_get_service_names();
OUString const * p = service_names.getConstArray();
for ( sal_Int32 nPos = service_names.getLength(); nPos--; )
{
if (p[ nPos ].equals( serviceName ))
return sal_True;
}
return sal_False;
}
//__________________________________________________________________________________________________
Sequence< OUString > Bootstrap_MacroExpander::getSupportedServiceNames()
throw (RuntimeException)
{
return s_get_service_names();
}
// XInitialization impl
//__________________________________________________________________________________________________
void SAL_CALL Bootstrap_MacroExpander::initialize(
Sequence< Any > const & arguments )
throw (Exception)
{
if (m_bstrap)
{
throw RuntimeException(
OUSTR("already initialized!"),
Reference< XInterface >() );
}
if (1 != arguments.getLength())
{
throw lang::IllegalArgumentException(
OUSTR("invalid number of args given! give single file url!"),
Reference< XInterface >(),
0 );
}
if (! (arguments[ 0 ] >>= m_rc_path))
{
throw lang::IllegalArgumentException(
OUSTR("give file url!"),
Reference< XInterface >(),
0 );
}
}
// XMacroExpander impl
//__________________________________________________________________________________________________
OUString Bootstrap_MacroExpander::expandMacros( OUString const & exp )
throw (lang::IllegalArgumentException)
{
// determine bootstrap handle
rtlBootstrapHandle bstrap;
if (m_rc_path.getLength())
{
// late init
if (! m_bstrap)
{
rtlBootstrapHandle bstrap = rtl_bootstrap_args_open( m_rc_path.pData );
ClearableMutexGuard guard( Mutex::getGlobalMutex() );
if (m_bstrap)
{
guard.clear();
rtl_bootstrap_args_close( bstrap );
}
else
{
m_bstrap = bstrap;
}
}
bstrap = m_bstrap;
}
else
{
bstrap = ::cppu::get_unorc().getHandle();
}
// expand
OUString ret( exp );
rtl_bootstrap_expandMacros_from_handle( bstrap, &ret.pData );
return ret;
}
//==================================================================================================
Reference< XInterface > SAL_CALL service_create(
Reference< XComponentContext > const & xComponentContext )
SAL_THROW( (RuntimeException) )
{
return static_cast< ::cppu::OWeakObject * >( new Bootstrap_MacroExpander( xComponentContext ) );
}
}
namespace cppu
{
//##################################################################################################
Reference< lang::XSingleComponentFactory > create_boostrap_macro_expander_factory() SAL_THROW( () )
{
return ::cppu::createSingleComponentFactory(
service_create,
s_impl_name(),
s_get_service_names() );
}
}
<commit_msg>INTEGRATION: CWS warnings01 (1.7.42); FILE MERGED 2005/09/22 15:38:58 sb 1.7.42.2: RESYNC: (1.7-1.8); FILE MERGED 2005/09/07 11:05:30 sb 1.7.42.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: macro_expander.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-06-19 10:34: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
*
************************************************************************/
#include <rtl/bootstrap.hxx>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implbase3.hxx>
#include <cppuhelper/compbase3.hxx>
#include <cppuhelper/component_context.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/util/XMacroExpander.hpp>
#include "com/sun/star/uno/RuntimeException.hpp"
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
#define SERVICE_NAME_A "com.sun.star.lang.MacroExpander"
#define SERVICE_NAME_B "com.sun.star.lang.BootstrapMacroExpander"
#define IMPL_NAME "com.sun.star.lang.comp.cppuhelper.BootstrapMacroExpander"
using namespace ::rtl;
using namespace ::osl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace cppu
{
//---- private forward -----------------------------------------------------------------------------
Bootstrap const & get_unorc() SAL_THROW( () );
}
namespace
{
inline OUString s_impl_name() { return OUSTR(IMPL_NAME); }
static Sequence< OUString > const & s_get_service_names()
{
static Sequence< OUString > const * s_pnames = 0;
if (! s_pnames)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_pnames)
{
static Sequence< OUString > s_names( 2 );
s_names[ 0 ] = OUSTR(SERVICE_NAME_A);
s_names[ 1 ] = OUSTR(SERVICE_NAME_B);
s_pnames = &s_names;
}
}
return *s_pnames;
}
typedef ::cppu::WeakComponentImplHelper3<
util::XMacroExpander, lang::XServiceInfo, lang::XInitialization > t_uno_impl;
struct mutex_holder
{
Mutex m_mutex;
};
class Bootstrap_MacroExpander : public mutex_holder, public t_uno_impl
{
rtlBootstrapHandle m_bstrap;
OUString m_rc_path;
protected:
virtual void SAL_CALL disposing();
public:
inline Bootstrap_MacroExpander( Reference< XComponentContext > const & ) SAL_THROW( () )
: t_uno_impl( m_mutex ),
m_bstrap( 0 )
{}
virtual ~Bootstrap_MacroExpander()
SAL_THROW( () );
// XMacroExpander impl
virtual OUString SAL_CALL expandMacros( OUString const & exp )
throw (lang::IllegalArgumentException);
// XInitialization impl
virtual void SAL_CALL initialize(
Sequence< Any > const & arguments )
throw (Exception);
// XServiceInfo impl
virtual OUString SAL_CALL getImplementationName()
throw (RuntimeException);
virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName )
throw (RuntimeException);
virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
throw (RuntimeException);
};
//__________________________________________________________________________________________________
void Bootstrap_MacroExpander::disposing()
{
rtlBootstrapHandle h;
{
osl::MutexGuard g(m_mutex);
h = m_bstrap;
m_bstrap = 0;
}
if (h) {
rtl_bootstrap_args_close(h);
}
}
//__________________________________________________________________________________________________
Bootstrap_MacroExpander::~Bootstrap_MacroExpander() SAL_THROW( () )
{
disposing();
}
// XServiceInfo impl
//__________________________________________________________________________________________________
OUString Bootstrap_MacroExpander::getImplementationName()
throw (RuntimeException)
{
return s_impl_name();
}
//__________________________________________________________________________________________________
sal_Bool Bootstrap_MacroExpander::supportsService( OUString const & serviceName )
throw (RuntimeException)
{
Sequence< OUString > const & service_names = s_get_service_names();
OUString const * p = service_names.getConstArray();
for ( sal_Int32 nPos = service_names.getLength(); nPos--; )
{
if (p[ nPos ].equals( serviceName ))
return sal_True;
}
return sal_False;
}
//__________________________________________________________________________________________________
Sequence< OUString > Bootstrap_MacroExpander::getSupportedServiceNames()
throw (RuntimeException)
{
return s_get_service_names();
}
// XInitialization impl
//__________________________________________________________________________________________________
void SAL_CALL Bootstrap_MacroExpander::initialize(
Sequence< Any > const & arguments )
throw (Exception)
{
if (m_bstrap)
{
throw RuntimeException(
OUSTR("already initialized!"),
Reference< XInterface >() );
}
if (1 != arguments.getLength())
{
throw lang::IllegalArgumentException(
OUSTR("invalid number of args given! give single file url!"),
Reference< XInterface >(),
0 );
}
if (! (arguments[ 0 ] >>= m_rc_path))
{
throw lang::IllegalArgumentException(
OUSTR("give file url!"),
Reference< XInterface >(),
0 );
}
}
// XMacroExpander impl
//__________________________________________________________________________________________________
OUString Bootstrap_MacroExpander::expandMacros( OUString const & exp )
throw (lang::IllegalArgumentException)
{
rtlBootstrapHandle h;
if (m_rc_path.getLength() != 0) {
osl::MutexGuard g(m_mutex);
if (!m_bstrap) {
m_bstrap = rtl_bootstrap_args_open(m_rc_path.pData);
}
h = m_bstrap;
} else {
h = cppu::get_unorc().getHandle();
}
OUString ret( exp );
rtl_bootstrap_expandMacros_from_handle( h, &ret.pData );
return ret;
}
//==================================================================================================
Reference< XInterface > SAL_CALL service_create(
Reference< XComponentContext > const & xComponentContext )
SAL_THROW( (RuntimeException) )
{
return static_cast< ::cppu::OWeakObject * >( new Bootstrap_MacroExpander( xComponentContext ) );
}
}
namespace cppu
{
//##################################################################################################
Reference< lang::XSingleComponentFactory > create_boostrap_macro_expander_factory() SAL_THROW( () )
{
return ::cppu::createSingleComponentFactory(
service_create,
s_impl_name(),
s_get_service_names() );
}
}
<|endoftext|> |
<commit_before>#include "chrome/browser/extensions/extension_browsertest.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Amount of time to wait to load an extension. This is purposely obscenely
// long because it will only get used in the case of failure and we want to
// minimize false positives.
static const int kTimeoutMs = 60 * 1000; // 1 minute
};
// Base class for extension browser tests. Provides utilities for loading,
// unloading, and installing extensions.
void ExtensionBrowserTest::SetUpCommandLine(CommandLine* command_line) {
// This enables DOM automation for tab contentses.
EnableDOMAutomation();
// This enables it for extension hosts.
ExtensionHost::EnableDOMAutomation();
command_line->AppendSwitch(switches::kEnableExtensions);
PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
test_data_dir_ = test_data_dir_.AppendASCII("extensions");
}
bool ExtensionBrowserTest::LoadExtension(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
service->LoadExtension(path);
MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
kTimeoutMs);
ui_test_utils::RunMessageLoop();
registrar_.Remove(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool ExtensionBrowserTest::InstallExtension(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
service->set_show_extensions_prompts(false);
size_t num_before = service->extensions()->size();
registrar_.Add(this, NotificationType::EXTENSION_INSTALLED,
NotificationService::AllSources());
service->InstallExtension(path);
MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
kTimeoutMs);
ui_test_utils::RunMessageLoop();
registrar_.Remove(this, NotificationType::EXTENSION_INSTALLED,
NotificationService::AllSources());
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1)) {
std::cout << "Num extensions before: " << IntToString(num_before)
<< "num after: " << IntToString(num_after)
<< "Installed extensions are:\n";
for (size_t i = 0; i < service->extensions()->size(); ++i)
std::cout << " " << service->extensions()->at(i)->id() << "\n";
return false;
}
return WaitForExtensionHostsToLoad();
}
void ExtensionBrowserTest::UninstallExtension(const std::string& extension_id) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
service->UninstallExtension(extension_id, false);
}
bool ExtensionBrowserTest::WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
base::Time start_time = base::Time::Now();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end(); ++iter) {
while (!(*iter)->did_stop_loading()) {
if ((base::Time::Now() - start_time).InMilliseconds() > kTimeoutMs) {
std::cout << "Extension host did not load for URL: "
<< (*iter)->GetURL().spec();
return false;
}
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, 200);
ui_test_utils::RunMessageLoop();
}
}
return true;
}
void ExtensionBrowserTest::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_INSTALLED:
case NotificationType::EXTENSIONS_LOADED:
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
<commit_msg>Add some more logging. Still trying to figure out flakey test.<commit_after>#include "chrome/browser/extensions/extension_browsertest.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension_error_reporter.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/ui_test_utils.h"
namespace {
// Amount of time to wait to load an extension. This is purposely obscenely
// long because it will only get used in the case of failure and we want to
// minimize false positives.
static const int kTimeoutMs = 60 * 1000; // 1 minute
};
// Base class for extension browser tests. Provides utilities for loading,
// unloading, and installing extensions.
void ExtensionBrowserTest::SetUpCommandLine(CommandLine* command_line) {
// This enables DOM automation for tab contentses.
EnableDOMAutomation();
// This enables it for extension hosts.
ExtensionHost::EnableDOMAutomation();
command_line->AppendSwitch(switches::kEnableExtensions);
PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir_);
test_data_dir_ = test_data_dir_.AppendASCII("extensions");
}
bool ExtensionBrowserTest::LoadExtension(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
size_t num_before = service->extensions()->size();
registrar_.Add(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
service->LoadExtension(path);
MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
kTimeoutMs);
ui_test_utils::RunMessageLoop();
registrar_.Remove(this, NotificationType::EXTENSIONS_LOADED,
NotificationService::AllSources());
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1))
return false;
return WaitForExtensionHostsToLoad();
}
bool ExtensionBrowserTest::InstallExtension(const FilePath& path) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
service->set_show_extensions_prompts(false);
size_t num_before = service->extensions()->size();
registrar_.Add(this, NotificationType::EXTENSION_INSTALLED,
NotificationService::AllSources());
service->InstallExtension(path);
MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
kTimeoutMs);
ui_test_utils::RunMessageLoop();
registrar_.Remove(this, NotificationType::EXTENSION_INSTALLED,
NotificationService::AllSources());
size_t num_after = service->extensions()->size();
if (num_after != (num_before + 1)) {
std::cout << "Num extensions before: " << IntToString(num_before) << " "
<< "num after: " << IntToString(num_after) << " "
<< "Installed extensions follow:\n";
for (size_t i = 0; i < service->extensions()->size(); ++i)
std::cout << " " << service->extensions()->at(i)->id() << "\n";
std::cout << "Errors follow:\n";
const std::vector<std::string>* errors =
ExtensionErrorReporter::GetInstance()->GetErrors();
for (std::vector<std::string>::const_iterator iter = errors->begin();
iter != errors->end(); ++iter) {
std::cout << *iter << "\n";
}
return false;
}
return WaitForExtensionHostsToLoad();
}
void ExtensionBrowserTest::UninstallExtension(const std::string& extension_id) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
service->UninstallExtension(extension_id, false);
}
bool ExtensionBrowserTest::WaitForExtensionHostsToLoad() {
// Wait for all the extension hosts that exist to finish loading.
// NOTE: This assumes that the extension host list is not changing while
// this method is running.
ExtensionProcessManager* manager =
browser()->profile()->GetExtensionProcessManager();
base::Time start_time = base::Time::Now();
for (ExtensionProcessManager::const_iterator iter = manager->begin();
iter != manager->end(); ++iter) {
while (!(*iter)->did_stop_loading()) {
if ((base::Time::Now() - start_time).InMilliseconds() > kTimeoutMs) {
std::cout << "Extension host did not load for URL: "
<< (*iter)->GetURL().spec();
return false;
}
MessageLoop::current()->PostDelayedTask(FROM_HERE,
new MessageLoop::QuitTask, 200);
ui_test_utils::RunMessageLoop();
}
}
return true;
}
void ExtensionBrowserTest::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
switch (type.value) {
case NotificationType::EXTENSION_INSTALLED:
std::cout << "Got EXTENSION_INSTALLED notification.\n";
MessageLoopForUI::current()->Quit();
break;
case NotificationType::EXTENSIONS_LOADED:
std::cout << "Got EXTENSION_LOADED notification.\n";
MessageLoopForUI::current()->Quit();
break;
default:
NOTREACHED();
break;
}
}
<|endoftext|> |
<commit_before>#ifndef GCN_SDL_HPP
#define GCN_SDL_HPP
#include <guichan/sdl/sdlgraphics.hpp>
#include <guichan/sdl/sdlimage.hpp>
#include <guichan/sdl/sdlinput.hpp>
#endif // end GCN_SDL_HPP
<commit_msg>Removed sdlimage.hpp added sdlimageloader.hpp<commit_after>#ifndef GCN_SDL_HPP
#define GCN_SDL_HPP
#include <guichan/sdl/sdlgraphics.hpp>
#include <guichan/sdl/sdlimageloader.hpp>
#include <guichan/sdl/sdlinput.hpp>
#endif // end GCN_SDL_HPP
<|endoftext|> |
<commit_before>#ifndef __ENVIRE_CORE_ITEM_BASE__
#define __ENVIRE_CORE_ITEM_BASE__
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/nvp.hpp>
#include <base/Time.hpp>
#include <string>
#include <type_traits>
#include <typeindex>
#include <envire_core/serialization/BoostTypes.hpp>
namespace envire { namespace core
{
using FrameId = std::string;
/**@class ItemBase
*
* ItemBase class
*/
class ItemBase
{
public:
template<class T>
using PtrType = boost::shared_ptr<T>;
typedef PtrType<ItemBase> Ptr;
protected:
base::Time time; /** Timestamp */
boost::uuids::uuid uuid; /** Unique Identifier */
FrameId frame_name; /** Frame name in which the Item is located */
// TBD: do we want/need this pointer?
void* user_data_ptr; /** Pointer to the user data */
public:
ItemBase();
ItemBase(const ItemBase& item);
ItemBase(ItemBase&& item);
virtual ~ItemBase() {}
ItemBase& operator=(const ItemBase& item);
ItemBase& operator=(ItemBase&& item);
/**@brief setTime
*
* Sets the timestamp of the item
*
*/
void setTime(const base::Time& time) { this->time = time; }
/**@brief getTime
*
* Returns the timestamp of the item
*
*/
const base::Time& getTime() const { return this->time; }
/**@brief setID
*
* Sets the unique identifier of the item
*
*/
void setID(const boost::uuids::uuid& id) { this->uuid = id; }
/**@brief getID
*TARGET
* Returns the unique identifier of the item
*
*/
const boost::uuids::uuid getID() const { return this->uuid; }
const std::string getIDString() const { return boost::uuids::to_string(this->uuid); }
/**@brief setFrame
*
* Sets the frame name of the item
*
*/
void setFrame(const std::string& frame_name) { this->frame_name = frame_name; }
/**@brief getFrame
*
* Returns the frame name of the item
*
*/
const std::string& getFrame() const { return this->frame_name; }
/**@brief getClassName
*
* Returns the class name of the item
*
*/
virtual std::string getClassName() const { return "UnknownItem"; }
virtual std::type_index getTypeIndex() const = 0;
void* getRawData() const { return user_data_ptr; }
private:
/**Grands access to boost serialization */
friend class boost::serialization::access;
/**Serializes the members of this class*/
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::make_nvp("time", time.microseconds);
ar & BOOST_SERIALIZATION_NVP(uuid);
ar & BOOST_SERIALIZATION_NVP(frame_name);
}
};
/**Mark this class as abstract class */
BOOST_SERIALIZATION_ASSUME_ABSTRACT(envire::core::ItemBase);
template <class TARGET>
struct ItemBaseCaster
{
ItemBase::PtrType<TARGET> operator()(const ItemBase::Ptr p) const
{
//FIXME static_assert that TARGET is ItemBase::PtrType<X>
return boost::dynamic_pointer_cast<TARGET>(p);
}
};
}}
#endif
<commit_msg>fixed missing reference on return type<commit_after>#ifndef __ENVIRE_CORE_ITEM_BASE__
#define __ENVIRE_CORE_ITEM_BASE__
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/nvp.hpp>
#include <base/Time.hpp>
#include <string>
#include <type_traits>
#include <typeindex>
#include <envire_core/serialization/BoostTypes.hpp>
namespace envire { namespace core
{
using FrameId = std::string;
/**@class ItemBase
*
* ItemBase class
*/
class ItemBase
{
public:
template<class T>
using PtrType = boost::shared_ptr<T>;
typedef PtrType<ItemBase> Ptr;
protected:
base::Time time; /** Timestamp */
boost::uuids::uuid uuid; /** Unique Identifier */
FrameId frame_name; /** Frame name in which the Item is located */
// TBD: do we want/need this pointer?
void* user_data_ptr; /** Pointer to the user data */
public:
ItemBase();
ItemBase(const ItemBase& item);
ItemBase(ItemBase&& item);
virtual ~ItemBase() {}
ItemBase& operator=(const ItemBase& item);
ItemBase& operator=(ItemBase&& item);
/**@brief setTime
*
* Sets the timestamp of the item
*
*/
void setTime(const base::Time& time) { this->time = time; }
/**@brief getTime
*
* Returns the timestamp of the item
*
*/
const base::Time& getTime() const { return this->time; }
/**@brief setID
*
* Sets the unique identifier of the item
*
*/
void setID(const boost::uuids::uuid& id) { this->uuid = id; }
/**@brief getID
*TARGET
* Returns the unique identifier of the item
*
*/
const boost::uuids::uuid& getID() const { return this->uuid; }
const std::string getIDString() const { return boost::uuids::to_string(this->uuid); }
/**@brief setFrame
*
* Sets the frame name of the item
*
*/
void setFrame(const std::string& frame_name) { this->frame_name = frame_name; }
/**@brief getFrame
*
* Returns the frame name of the item
*
*/
const std::string& getFrame() const { return this->frame_name; }
/**@brief getClassName
*
* Returns the class name of the item
*
*/
virtual std::string getClassName() const { return "UnknownItem"; }
virtual std::type_index getTypeIndex() const = 0;
void* getRawData() const { return user_data_ptr; }
private:
/**Grands access to boost serialization */
friend class boost::serialization::access;
/**Serializes the members of this class*/
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::make_nvp("time", time.microseconds);
ar & BOOST_SERIALIZATION_NVP(uuid);
ar & BOOST_SERIALIZATION_NVP(frame_name);
}
};
/**Mark this class as abstract class */
BOOST_SERIALIZATION_ASSUME_ABSTRACT(envire::core::ItemBase);
template <class TARGET>
struct ItemBaseCaster
{
ItemBase::PtrType<TARGET> operator()(const ItemBase::Ptr p) const
{
//FIXME static_assert that TARGET is ItemBase::PtrType<X>
return boost::dynamic_pointer_cast<TARGET>(p);
}
};
}}
#endif
<|endoftext|> |
<commit_before><commit_msg>Fix some issues with bookmark bar folder menu.<commit_after><|endoftext|> |
<commit_before>//
// Enterprise.cpp
// Clock Signal
//
// Created by Thomas Harte on 10/06/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "Enterprise.hpp"
#include "../MachineTypes.hpp"
#include "../../Processors/Z80/Z80.hpp"
#include "../../Analyser/Static/Enterprise/Target.hpp"
namespace Enterprise {
class ConcreteMachine:
public CPU::Z80::BusHandler,
public Machine,
public MachineTypes::ScanProducer,
public MachineTypes::TimedMachine {
public:
ConcreteMachine([[maybe_unused]] const Analyser::Static::Enterprise::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) :
z80_(*this) {
// Request a clock of 4Mhz; this'll be mapped upwards for Nick and Dave elsewhere.
set_clock_rate(4'000'000);
const auto request = ROM::Request(ROM::Name::EnterpriseEXOS);
auto roms = rom_fetcher(request);
if(!request.validate(roms)) {
throw ROMMachine::Error::MissingROMs;
}
// Take a reasonable guess at the initial memory configuration.
page<0>(0x00);
page<1>(0x01);
page<2>(0xfe);
page<3>(0xff);
}
// MARK: - Z80::BusHandler.
forceinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {
using PartialMachineCycle = CPU::Z80::PartialMachineCycle;
const uint16_t address = cycle.address ? *cycle.address : 0x0000;
// TODO: possibly apply an access penalty.
switch(cycle.operation) {
default: break;
case CPU::Z80::PartialMachineCycle::Input:
case CPU::Z80::PartialMachineCycle::Output:
assert(false);
break;
case CPU::Z80::PartialMachineCycle::Read:
case CPU::Z80::PartialMachineCycle::ReadOpcode:
if(read_pointers_[address >> 14]) {
*cycle.value = read_pointers_[address >> 14][address];
} else {
*cycle.value = 0xff;
}
break;
case CPU::Z80::PartialMachineCycle::Write:
if(write_pointers_[address >> 14]) {
write_pointers_[address >> 14][address] = *cycle.value;
}
break;
}
return HalfCycles(0);
}
private:
CPU::Z80::Processor<ConcreteMachine, false, false> z80_;
std::array<uint8_t, 32 * 1024> exos_;
std::array<uint8_t, 256 * 1024> ram_;
const uint8_t min_ram_slot_ = 0xff - 3;
const uint8_t *read_pointers_[4];
uint8_t *write_pointers_[4];
uint8_t pages_[4];
template <size_t slot> void page(uint8_t offset) {
pages_[slot] = offset;
if(offset < 2) {
page<slot>(&exos_[offset * 0x4000], nullptr);
return;
}
if(offset >= min_ram_slot_) {
const size_t address = (offset - min_ram_slot_) * 0x4000;
page<slot>(&ram_[address], &ram_[address]);
return;
}
page<slot>(nullptr, nullptr);
}
template <size_t slot> void page(const uint8_t *read, uint8_t *write) {
read_pointers_[slot] = read ? read - (slot * 0x4000) : nullptr;
write_pointers_[slot] = write ? write - (slot * 0x4000) : nullptr;
}
// MARK: - ScanProducer
void set_scan_target(Outputs::Display::ScanTarget *scan_target) override {
(void)scan_target;
}
Outputs::Display::ScanStatus get_scaled_scan_status() const override {
return Outputs::Display::ScanStatus();
}
// MARK: - TimedMachine
void run_for(const Cycles cycles) override {
z80_.run_for(cycles);
}
};
}
using namespace Enterprise;
Machine *Machine::Enterprise(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) {
using Target = Analyser::Static::Enterprise::Target;
const Target *const enterprise_target = dynamic_cast<const Target *>(target);
return new Enterprise::ConcreteMachine(*enterprise_target, rom_fetcher);
}
Machine::~Machine() {}
<commit_msg>Revised guess; there's a jump to C02E almost immediately.<commit_after>//
// Enterprise.cpp
// Clock Signal
//
// Created by Thomas Harte on 10/06/2021.
// Copyright © 2021 Thomas Harte. All rights reserved.
//
#include "Enterprise.hpp"
#include "../MachineTypes.hpp"
#include "../../Processors/Z80/Z80.hpp"
#include "../../Analyser/Static/Enterprise/Target.hpp"
namespace Enterprise {
class ConcreteMachine:
public CPU::Z80::BusHandler,
public Machine,
public MachineTypes::ScanProducer,
public MachineTypes::TimedMachine {
public:
ConcreteMachine([[maybe_unused]] const Analyser::Static::Enterprise::Target &target, const ROMMachine::ROMFetcher &rom_fetcher) :
z80_(*this) {
// Request a clock of 4Mhz; this'll be mapped upwards for Nick and Dave elsewhere.
set_clock_rate(4'000'000);
constexpr ROM::Name exos_name = ROM::Name::EnterpriseEXOS;
const auto request = ROM::Request(exos_name);
auto roms = rom_fetcher(request);
if(!request.validate(roms)) {
throw ROMMachine::Error::MissingROMs;
}
const auto &exos = roms.find(exos_name)->second;
memcpy(exos_.data(), exos.data(), std::min(exos_.size(), exos.size()));
// Take a reasonable guess at the initial memory configuration.
page<0>(0x00);
page<1>(0x00);
page<2>(0x00);
page<3>(0x00);
}
// MARK: - Z80::BusHandler.
forceinline HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {
using PartialMachineCycle = CPU::Z80::PartialMachineCycle;
const uint16_t address = cycle.address ? *cycle.address : 0x0000;
// TODO: possibly apply an access penalty.
switch(cycle.operation) {
default: break;
case CPU::Z80::PartialMachineCycle::Input:
printf("Unhandled input: %04x\n", address);
assert(false);
break;
case CPU::Z80::PartialMachineCycle::Output:
printf("Unhandled output: %04x\n", address);
assert(false);
break;
case CPU::Z80::PartialMachineCycle::Read:
case CPU::Z80::PartialMachineCycle::ReadOpcode:
if(read_pointers_[address >> 14]) {
*cycle.value = read_pointers_[address >> 14][address];
} else {
*cycle.value = 0xff;
}
break;
case CPU::Z80::PartialMachineCycle::Write:
if(write_pointers_[address >> 14]) {
write_pointers_[address >> 14][address] = *cycle.value;
}
break;
}
return HalfCycles(0);
}
private:
CPU::Z80::Processor<ConcreteMachine, false, false> z80_;
std::array<uint8_t, 32 * 1024> exos_;
std::array<uint8_t, 256 * 1024> ram_;
const uint8_t min_ram_slot_ = 0xff - 3;
const uint8_t *read_pointers_[4];
uint8_t *write_pointers_[4];
uint8_t pages_[4];
template <size_t slot> void page(uint8_t offset) {
pages_[slot] = offset;
if(offset < 2) {
page<slot>(&exos_[offset * 0x4000], nullptr);
return;
}
if(offset >= min_ram_slot_) {
const size_t address = (offset - min_ram_slot_) * 0x4000;
page<slot>(&ram_[address], &ram_[address]);
return;
}
page<slot>(nullptr, nullptr);
}
template <size_t slot> void page(const uint8_t *read, uint8_t *write) {
read_pointers_[slot] = read ? read - (slot * 0x4000) : nullptr;
write_pointers_[slot] = write ? write - (slot * 0x4000) : nullptr;
}
// MARK: - ScanProducer
void set_scan_target(Outputs::Display::ScanTarget *scan_target) override {
(void)scan_target;
}
Outputs::Display::ScanStatus get_scaled_scan_status() const override {
return Outputs::Display::ScanStatus();
}
// MARK: - TimedMachine
void run_for(const Cycles cycles) override {
z80_.run_for(cycles);
}
};
}
using namespace Enterprise;
Machine *Machine::Enterprise(const Analyser::Static::Target *target, const ROMMachine::ROMFetcher &rom_fetcher) {
using Target = Analyser::Static::Enterprise::Target;
const Target *const enterprise_target = dynamic_cast<const Target *>(target);
return new Enterprise::ConcreteMachine(*enterprise_target, rom_fetcher);
}
Machine::~Machine() {}
<|endoftext|> |
<commit_before>#pragma once
#include <glm/glm.hpp>
namespace mos {
namespace gfx {
/** Visual bounding box. */
class Box final {
public:
Box() = default;
Box(const glm::mat4 &transform,
const glm::vec3 &extent);
glm::mat4 transform;
glm::vec3 extent;
glm::vec3 position() const;
glm::vec3 size() const;
glm::vec3 min() const;
glm::vec3 max() const;
bool inside(const glm::vec3 &point) const;
};
}
}
<commit_msg>Constructor fix.<commit_after>#pragma once
#include <glm/glm.hpp>
namespace mos {
namespace gfx {
/** Visual bounding box. */
class Box final {
public:
Box();
Box(const glm::mat4 &transform,
const glm::vec3 &extent);
glm::mat4 transform;
glm::vec3 extent;
glm::vec3 position() const;
glm::vec3 size() const;
glm::vec3 min() const;
glm::vec3 max() const;
bool inside(const glm::vec3 &point) const;
};
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "process_thread_impl.h"
#include "module.h"
#include "trace.h"
namespace webrtc {
ProcessThread::~ProcessThread()
{
}
ProcessThread* ProcessThread::CreateProcessThread()
{
return new ProcessThreadImpl();
}
void ProcessThread::DestroyProcessThread(ProcessThread* module)
{
delete module;
}
ProcessThreadImpl::ProcessThreadImpl()
: _timeEvent(*EventWrapper::Create()),
_critSectModules(CriticalSectionWrapper::CreateCriticalSection()),
_thread(NULL)
{
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s created", __FUNCTION__);
}
ProcessThreadImpl::~ProcessThreadImpl()
{
delete _critSectModules;
delete &_timeEvent;
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s deleted", __FUNCTION__);
}
WebRtc_Word32 ProcessThreadImpl::Start()
{
CriticalSectionScoped lock(_critSectModules);
if(_thread)
{
return -1;
}
_thread = ThreadWrapper::CreateThread(Run, this, kNormalPriority,
"ProcessThread");
unsigned int id;
WebRtc_Word32 retVal = _thread->Start(id);
if(retVal >= 0)
{
return 0;
}
delete _thread;
_thread = NULL;
return -1;
}
WebRtc_Word32 ProcessThreadImpl::Stop()
{
_critSectModules->Enter();
if(_thread)
{
_thread->SetNotAlive();
ThreadWrapper* thread = _thread;
_thread = NULL;
_timeEvent.Set();
_critSectModules->Leave();
if(thread->Stop())
{
delete thread;
} else {
return -1;
}
} else {
_critSectModules->Leave();
}
return 0;
}
WebRtc_Word32 ProcessThreadImpl::RegisterModule(const Module* module)
{
CriticalSectionScoped lock(_critSectModules);
// Only allow module to be registered once.
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
if(module == item->GetItem())
{
return -1;
}
item = _modules.Next(item);
}
_modules.PushFront(module);
WEBRTC_TRACE(kTraceInfo, kTraceUtility, -1,
"number of registered modules has increased to %d",
_modules.GetSize());
// Wake the thread calling ProcessThreadImpl::Process() to update the
// waiting time. The waiting time for the just registered module may be
// shorter than all other registered modules.
_timeEvent.Set();
return 0;
}
WebRtc_Word32 ProcessThreadImpl::DeRegisterModule(const Module* module)
{
CriticalSectionScoped lock(_critSectModules);
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
if(module == item->GetItem())
{
int res = _modules.Erase(item);
WEBRTC_TRACE(kTraceInfo, kTraceUtility, -1,
"number of registered modules has decreased to %d",
_modules.GetSize());
return res;
}
item = _modules.Next(item);
}
return -1;
}
bool ProcessThreadImpl::Run(void* obj)
{
return static_cast<ProcessThreadImpl*>(obj)->Process();
}
bool ProcessThreadImpl::Process()
{
// Wait for the module that should be called next, but don't block thread
// longer than 100 ms.
WebRtc_Word32 minTimeToNext = 100;
{
CriticalSectionScoped lock(_critSectModules);
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
WebRtc_Word32 timeToNext =
static_cast<Module*>(item->GetItem())->TimeUntilNextProcess();
if(minTimeToNext > timeToNext)
{
minTimeToNext = timeToNext;
}
item = _modules.Next(item);
}
}
if(minTimeToNext > 0)
{
if(kEventError == _timeEvent.Wait(minTimeToNext))
{
return true;
}
if(!_thread)
{
return false;
}
}
{
CriticalSectionScoped lock(_critSectModules);
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
WebRtc_Word32 timeToNext =
static_cast<Module*>(item->GetItem())->TimeUntilNextProcess();
if(timeToNext < 1)
{
static_cast<Module*>(item->GetItem())->Process();
}
item = _modules.Next(item);
}
}
return true;
}
} // namespace webrtc
<commit_msg>Fixes data race in WebRTCAudioDeviceTest.Construct reported by ThreadSanitizer<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "process_thread_impl.h"
#include "module.h"
#include "trace.h"
namespace webrtc {
ProcessThread::~ProcessThread()
{
}
ProcessThread* ProcessThread::CreateProcessThread()
{
return new ProcessThreadImpl();
}
void ProcessThread::DestroyProcessThread(ProcessThread* module)
{
delete module;
}
ProcessThreadImpl::ProcessThreadImpl()
: _timeEvent(*EventWrapper::Create()),
_critSectModules(CriticalSectionWrapper::CreateCriticalSection()),
_thread(NULL)
{
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s created", __FUNCTION__);
}
ProcessThreadImpl::~ProcessThreadImpl()
{
delete _critSectModules;
delete &_timeEvent;
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1, "%s deleted", __FUNCTION__);
}
WebRtc_Word32 ProcessThreadImpl::Start()
{
CriticalSectionScoped lock(_critSectModules);
if(_thread)
{
return -1;
}
_thread = ThreadWrapper::CreateThread(Run, this, kNormalPriority,
"ProcessThread");
unsigned int id;
WebRtc_Word32 retVal = _thread->Start(id);
if(retVal >= 0)
{
return 0;
}
delete _thread;
_thread = NULL;
return -1;
}
WebRtc_Word32 ProcessThreadImpl::Stop()
{
_critSectModules->Enter();
if(_thread)
{
_thread->SetNotAlive();
ThreadWrapper* thread = _thread;
_thread = NULL;
_timeEvent.Set();
_critSectModules->Leave();
if(thread->Stop())
{
delete thread;
} else {
return -1;
}
} else {
_critSectModules->Leave();
}
return 0;
}
WebRtc_Word32 ProcessThreadImpl::RegisterModule(const Module* module)
{
CriticalSectionScoped lock(_critSectModules);
// Only allow module to be registered once.
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
if(module == item->GetItem())
{
return -1;
}
item = _modules.Next(item);
}
_modules.PushFront(module);
WEBRTC_TRACE(kTraceInfo, kTraceUtility, -1,
"number of registered modules has increased to %d",
_modules.GetSize());
// Wake the thread calling ProcessThreadImpl::Process() to update the
// waiting time. The waiting time for the just registered module may be
// shorter than all other registered modules.
_timeEvent.Set();
return 0;
}
WebRtc_Word32 ProcessThreadImpl::DeRegisterModule(const Module* module)
{
CriticalSectionScoped lock(_critSectModules);
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
if(module == item->GetItem())
{
int res = _modules.Erase(item);
WEBRTC_TRACE(kTraceInfo, kTraceUtility, -1,
"number of registered modules has decreased to %d",
_modules.GetSize());
return res;
}
item = _modules.Next(item);
}
return -1;
}
bool ProcessThreadImpl::Run(void* obj)
{
return static_cast<ProcessThreadImpl*>(obj)->Process();
}
bool ProcessThreadImpl::Process()
{
// Wait for the module that should be called next, but don't block thread
// longer than 100 ms.
WebRtc_Word32 minTimeToNext = 100;
{
CriticalSectionScoped lock(_critSectModules);
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
WebRtc_Word32 timeToNext =
static_cast<Module*>(item->GetItem())->TimeUntilNextProcess();
if(minTimeToNext > timeToNext)
{
minTimeToNext = timeToNext;
}
item = _modules.Next(item);
}
}
if(minTimeToNext > 0)
{
if(kEventError == _timeEvent.Wait(minTimeToNext))
{
return true;
}
CriticalSectionScoped lock(_critSectModules);
if(!_thread)
{
return false;
}
}
{
CriticalSectionScoped lock(_critSectModules);
ListItem* item = _modules.First();
for(WebRtc_UWord32 i = 0; i < _modules.GetSize() && item; i++)
{
WebRtc_Word32 timeToNext =
static_cast<Module*>(item->GetItem())->TimeUntilNextProcess();
if(timeToNext < 1)
{
static_cast<Module*>(item->GetItem())->Process();
}
item = _modules.Next(item);
}
}
return true;
}
} // namespace webrtc
<|endoftext|> |
<commit_before>// This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
/** for_each_line.cc
Jeremy Barnes, 29 November 2013
Copyright (c) 2013 Datacratic Inc. All rights reserved.
*/
#include <atomic>
#include <exception>
#include <mutex>
#include "for_each_line.h"
#include "mldb/arch/threads.h"
#include <chrono>
#include <thread>
#include <cstring>
#include "mldb/jml/utils/ring_buffer.h"
#include "mldb/vfs/filter_streams.h"
#include "mldb/base/thread_pool.h"
#include "mldb/base/exc_assert.h"
#include "mldb/types/date.h"
using namespace std;
using namespace ML;
namespace {
struct Processing {
Processing()
: shutdown(false), hasException_(false),
excPtr(nullptr), decompressedLines(16000)
{
}
void takeLastException()
{
std::lock_guard<std::mutex> guard(excPtrLock);
excPtr = std::current_exception();
hasException_ = true;
}
bool hasException()
{
return hasException_;
}
atomic<bool> shutdown;
atomic<bool> hasException_;
std::mutex excPtrLock;
std::exception_ptr excPtr;
RingBufferSWMR<pair<int64_t, vector<string> > > decompressedLines;
};
}
namespace Datacratic {
/*****************************************************************************/
/* PARALLEL LINE PROCESSOR */
/*****************************************************************************/
static size_t
readStream(std::istream & stream,
Processing & processing,
bool ignoreStreamExceptions,
int64_t maxLines)
{
Date start = Date::now();
pair<int64_t, vector<string> > current;
current.second.reserve(1000);
Date lastCheck = start;
int64_t done = current.first = 0; // 32 bit not enough
try {
while (stream && !stream.eof() && (maxLines == -1 || done < maxLines)) {
if (processing.hasException()) {
break;
}
string line;
getline(stream, line);
current.second.emplace_back(std::move(line));
++done;
if (current.second.size() == 1000) {
processing.decompressedLines.push(std::move(current));
current.first = done;
current.second.clear();
//current.clear();
ExcAssertEqual(current.second.size(), 0);
current.second.reserve(1000);
}
if (done % 1000000 == 0) {
//cerr << "done " << done << " lines" << endl;
Date now = Date::now();
double elapsed = now.secondsSince(start);
double instElapsed = now.secondsSince(lastCheck);
cerr << ML::format("doing %.3fMlines/second total, %.3f instantaneous",
done / elapsed / 1000000.0,
1000000 / instElapsed / 1000000.0)
<< endl;
lastCheck = now;
}
}
} catch (const std::exception & exc) {
if (!ignoreStreamExceptions) {
processing.takeLastException();
}
else {
cerr << "stream threw ignored exception: " << exc.what() << endl;
}
}
if (!current.second.empty() && !processing.hasException()) {
processing.decompressedLines.push(std::move(current));
}
return done;
};
static void
parseLinesThreadStr(Processing & processing,
const std::function<void (const std::string &,
int64_t lineNum)> & processLine)
{
while (!processing.hasException()) {
std::pair<int64_t, vector<string> > lines;
if (!processing.decompressedLines.tryPop(lines)) {
if (processing.shutdown) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
for (unsigned i = 0; i < lines.second.size(); ++i) {
if (processing.hasException()) {
break;
}
const string & line = lines.second[i];
try {
processLine(line, lines.first + i);
} catch (const std::exception & exc) {
processing.takeLastException();
cerr << "error dealing with line " << line
<< ": " << exc.what() << endl;
} catch (...) {
processing.takeLastException();
}
}
}
};
size_t
forEachLine(std::istream & stream,
const std::function<void (const char *, size_t,
int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
auto onLineStr = [&] (const string & line, int64_t lineNum) {
processLine(line.c_str(), line.size(), lineNum);
};
return forEachLineStr(stream, onLineStr, numThreads,
ignoreStreamExceptions, maxLines);
}
size_t
forEachLineStr(std::istream & stream,
const std::function<void (const std::string &,
int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
Processing processing;
std::vector<std::thread> threads;
for (unsigned i = 0; i < numThreads; ++i)
threads.emplace_back(std::bind(parseLinesThreadStr,
std::ref(processing),
std::ref(processLine)));
size_t result = readStream(stream, processing,
ignoreStreamExceptions, maxLines);
processing.shutdown = true;
for (auto & t: threads)
t.join();
if (processing.hasException()) {
std::rethrow_exception(processing.excPtr);
}
return result;
}
size_t
forEachLine(const std::string & filename,
const std::function<void (const char *, size_t, int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
filter_istream stream(filename);
return forEachLine(stream, processLine, numThreads,
ignoreStreamExceptions, maxLines);
}
size_t
forEachLineStr(const std::string & filename,
const std::function<void (const std::string &, int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
filter_istream stream(filename);
return forEachLineStr(stream, processLine, numThreads,
ignoreStreamExceptions, maxLines);
}
/*****************************************************************************/
/* FOR EACH LINE BLOCK */
/*****************************************************************************/
void forEachLineBlock(std::istream & stream,
std::function<bool (const char * line,
size_t lineLength,
int64_t blockNumber,
int64_t lineNumber)> onLine,
int64_t maxLines,
int maxParallelism,
std::function<bool (int64_t blockNumber, int64_t lineNumber)> startBlock,
std::function<bool (int64_t blockNumber, int64_t lineNumber)> endBlock)
{
//static constexpr int64_t BLOCK_SIZE = 100000000; // 100MB blocks
static constexpr int64_t BLOCK_SIZE = 10000000; // 10MB blocks
static constexpr int64_t READ_SIZE = 200000; // read&scan 200kb to fit in cache
std::atomic<int64_t> doneLines(0); //number of lines processed but not yet returned
std::atomic<int64_t> returnedLines(0); //number of lines returned
std::atomic<int64_t> byteOffset(0);
std::atomic<int> chunkNumber(0);
ThreadPool tp(maxParallelism);
// Memory map if possible
const char * mapped = nullptr;
size_t mappedSize = 0;
filter_istream * fistream = dynamic_cast<filter_istream *>(&stream);
if (fistream) {
// Can we get a memory mapped version of our stream? It
// saves us having to copy data. mapped will be set to
// nullptr if it's not possible to memory map this stream.
std::tie(mapped, mappedSize) = fistream->mapped();
}
std::atomic<int> hasExc(false);
std::exception_ptr exc;
std::function<void ()> doBlock = [&] ()
{
//cerr << "block starting at line " << doneLines << endl;
std::shared_ptr<const char> blockOut;
int64_t startOffset = byteOffset;
int64_t startLine = doneLines;
vector<size_t> lineOffsets = {0};
bool lastBlock = false;
size_t myChunkNumber = 0;
try {
//MLDB-1426
if (mapped && false) {
const char * start = mapped + stream.tellg();
const char * current = start;
const char * end = mapped + mappedSize;
while (current && current < end && (current - start) < BLOCK_SIZE
&& (maxLines == -1 || doneLines < maxLines)) { //stop processing new line when we have enough)
current = (const char *)memchr(current, '\n', end - current);
if (current && current < end) {
ExcAssertEqual(*current, '\n');
lineOffsets.push_back(current - start);
++doneLines;
++current;
}
}
if (current)
stream.seekg(current - start, ios::cur);
else {
// Last line has no newline
lineOffsets.push_back(end - start);
++doneLines;
}
myChunkNumber = chunkNumber++;
if (current && current < end &&
(maxLines == -1 || doneLines < maxLines)) // don't schedule a new block if we have enough lines
{
// Ready for another chunk
tp.add(doBlock);
} else if (current == end) {
lastBlock = true;
}
blockOut = std::shared_ptr<const char>(start,
[] (const char *) {});
}
else {
// How far through our block are we?
size_t offset = 0;
// How much extra space to allocate for the last line?
static constexpr size_t EXTRA_SIZE = 10000;
std::shared_ptr<char> block(new char[BLOCK_SIZE + EXTRA_SIZE],
[] (char * c) { delete[] c; });
blockOut = block;
// First line starts at offset 0
while (stream && !stream.eof()
&& (maxLines == -1 || doneLines < maxLines) //stop processing new line when we have enough
&& (byteOffset - startOffset < BLOCK_SIZE)) {
stream.read((char *)block.get() + offset,
std::min<size_t>(READ_SIZE, BLOCK_SIZE - offset));
// Check how many bytes we actually read
size_t bytesRead = stream.gcount();
offset += bytesRead;
// Scan for end of line characters
const char * current = block.get() + lineOffsets.back();
const char * end = block.get() + offset;
while (current && current < end) {
current = (const char *)memchr(current, '\n', end - current);
if (current && current < end) {
ExcAssertEqual(*current, '\n');
if (lineOffsets.back() != current - block.get()) {
lineOffsets.push_back(current - block.get());
//cerr << "got line at offset " << lineOffsets.back() << endl;
++doneLines;
}
++current;
}
}
byteOffset += bytesRead;
}
if (stream.eof()) {
// If we are at the end of the stream
// make sure we include the last line
// if there was no newline
if (lineOffsets.back() != offset - 1) {
lineOffsets.push_back(offset);
++doneLines;
}
}
else {
// If we are not at the end of the stream
// get the last line, as we probably got just a partial
// line in the last one
std::string lastLine;
getline(stream, lastLine);
size_t cnt = stream.gcount();
if (cnt != 0) {
// Check for overflow on the buffer size
if (offset + lastLine.size() + 1 > BLOCK_SIZE + EXTRA_SIZE) {
// reallocate and copy
std::shared_ptr<char> newBlock(new char[offset + lastLine.size() + 1],
[] (char * c) { delete[] c; });
std::copy(block.get(), block.get() + offset,
newBlock.get());
block = newBlock;
blockOut = block;
}
std::copy(lastLine.data(), lastLine.data() + lastLine.length(),
block.get() + offset);
lineOffsets.emplace_back(offset + lastLine.length());
++doneLines;
offset += cnt;
}
}
myChunkNumber = chunkNumber++;
if (stream && !stream.eof() &&
(maxLines == -1 || doneLines < maxLines)) // don't schedule a new block if we have enough lines
{
// Ready for another chunk
tp.add(doBlock);
} else if (stream.eof()) {
lastBlock = true;
}
}
//cerr << "processing block of " << lineOffsets.size() - 1
// << " lines starting at " << startLine << endl;
int64_t chunkLineNumber = startLine;
size_t lastLineOffset = lineOffsets[0];
if (startBlock)
if (!startBlock(myChunkNumber, chunkLineNumber))
return;
for (unsigned i = 1; i < lineOffsets.size() && (maxLines == -1 || returnedLines++ < maxLines); ++i) {
if (hasExc.load(std::memory_order_relaxed))
return;
const char * line = blockOut.get() + lastLineOffset;
size_t len = lineOffsets[i] - lastLineOffset;
// Skip \r for DOS line endings
if (len > 0 && line[len - 1] == '\r')
--len;
// if we are not at the last line
if (!lastBlock || len != 0 || i != lineOffsets.size() - 1)
if (!onLine(line, len, chunkNumber, chunkLineNumber++))
return;
lastLineOffset = lineOffsets[i] + 1;
}
if (endBlock)
if (!endBlock(myChunkNumber, chunkLineNumber))
return;
} JML_CATCH_ALL {
if (hasExc.fetch_add(1) == 0) {
exc = std::current_exception();
}
}
};
tp.add(doBlock);
tp.waitForAll();
// If there was an exception, rethrow it rather than returning
// cleanly
if (hasExc) {
std::rethrow_exception(exc);
}
}
} // namespace Datacratic
<commit_msg>Use 20MB blocks (MLDB-1507)<commit_after>// This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
/** for_each_line.cc
Jeremy Barnes, 29 November 2013
Copyright (c) 2013 Datacratic Inc. All rights reserved.
*/
#include <atomic>
#include <exception>
#include <mutex>
#include "for_each_line.h"
#include "mldb/arch/threads.h"
#include <chrono>
#include <thread>
#include <cstring>
#include "mldb/jml/utils/ring_buffer.h"
#include "mldb/vfs/filter_streams.h"
#include "mldb/base/thread_pool.h"
#include "mldb/base/exc_assert.h"
#include "mldb/types/date.h"
using namespace std;
using namespace ML;
namespace {
struct Processing {
Processing()
: shutdown(false), hasException_(false),
excPtr(nullptr), decompressedLines(16000)
{
}
void takeLastException()
{
std::lock_guard<std::mutex> guard(excPtrLock);
excPtr = std::current_exception();
hasException_ = true;
}
bool hasException()
{
return hasException_;
}
atomic<bool> shutdown;
atomic<bool> hasException_;
std::mutex excPtrLock;
std::exception_ptr excPtr;
RingBufferSWMR<pair<int64_t, vector<string> > > decompressedLines;
};
}
namespace Datacratic {
/*****************************************************************************/
/* PARALLEL LINE PROCESSOR */
/*****************************************************************************/
static size_t
readStream(std::istream & stream,
Processing & processing,
bool ignoreStreamExceptions,
int64_t maxLines)
{
Date start = Date::now();
pair<int64_t, vector<string> > current;
current.second.reserve(1000);
Date lastCheck = start;
int64_t done = current.first = 0; // 32 bit not enough
try {
while (stream && !stream.eof() && (maxLines == -1 || done < maxLines)) {
if (processing.hasException()) {
break;
}
string line;
getline(stream, line);
current.second.emplace_back(std::move(line));
++done;
if (current.second.size() == 1000) {
processing.decompressedLines.push(std::move(current));
current.first = done;
current.second.clear();
//current.clear();
ExcAssertEqual(current.second.size(), 0);
current.second.reserve(1000);
}
if (done % 1000000 == 0) {
//cerr << "done " << done << " lines" << endl;
Date now = Date::now();
double elapsed = now.secondsSince(start);
double instElapsed = now.secondsSince(lastCheck);
cerr << ML::format("doing %.3fMlines/second total, %.3f instantaneous",
done / elapsed / 1000000.0,
1000000 / instElapsed / 1000000.0)
<< endl;
lastCheck = now;
}
}
} catch (const std::exception & exc) {
if (!ignoreStreamExceptions) {
processing.takeLastException();
}
else {
cerr << "stream threw ignored exception: " << exc.what() << endl;
}
}
if (!current.second.empty() && !processing.hasException()) {
processing.decompressedLines.push(std::move(current));
}
return done;
};
static void
parseLinesThreadStr(Processing & processing,
const std::function<void (const std::string &,
int64_t lineNum)> & processLine)
{
while (!processing.hasException()) {
std::pair<int64_t, vector<string> > lines;
if (!processing.decompressedLines.tryPop(lines)) {
if (processing.shutdown) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
for (unsigned i = 0; i < lines.second.size(); ++i) {
if (processing.hasException()) {
break;
}
const string & line = lines.second[i];
try {
processLine(line, lines.first + i);
} catch (const std::exception & exc) {
processing.takeLastException();
cerr << "error dealing with line " << line
<< ": " << exc.what() << endl;
} catch (...) {
processing.takeLastException();
}
}
}
};
size_t
forEachLine(std::istream & stream,
const std::function<void (const char *, size_t,
int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
auto onLineStr = [&] (const string & line, int64_t lineNum) {
processLine(line.c_str(), line.size(), lineNum);
};
return forEachLineStr(stream, onLineStr, numThreads,
ignoreStreamExceptions, maxLines);
}
size_t
forEachLineStr(std::istream & stream,
const std::function<void (const std::string &,
int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
Processing processing;
std::vector<std::thread> threads;
for (unsigned i = 0; i < numThreads; ++i)
threads.emplace_back(std::bind(parseLinesThreadStr,
std::ref(processing),
std::ref(processLine)));
size_t result = readStream(stream, processing,
ignoreStreamExceptions, maxLines);
processing.shutdown = true;
for (auto & t: threads)
t.join();
if (processing.hasException()) {
std::rethrow_exception(processing.excPtr);
}
return result;
}
size_t
forEachLine(const std::string & filename,
const std::function<void (const char *, size_t, int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
filter_istream stream(filename);
return forEachLine(stream, processLine, numThreads,
ignoreStreamExceptions, maxLines);
}
size_t
forEachLineStr(const std::string & filename,
const std::function<void (const std::string &, int64_t)> & processLine,
int numThreads,
bool ignoreStreamExceptions,
int64_t maxLines)
{
filter_istream stream(filename);
return forEachLineStr(stream, processLine, numThreads,
ignoreStreamExceptions, maxLines);
}
/*****************************************************************************/
/* FOR EACH LINE BLOCK */
/*****************************************************************************/
void forEachLineBlock(std::istream & stream,
std::function<bool (const char * line,
size_t lineLength,
int64_t blockNumber,
int64_t lineNumber)> onLine,
int64_t maxLines,
int maxParallelism,
std::function<bool (int64_t blockNumber, int64_t lineNumber)> startBlock,
std::function<bool (int64_t blockNumber, int64_t lineNumber)> endBlock)
{
//static constexpr int64_t BLOCK_SIZE = 100000000; // 100MB blocks
static constexpr int64_t BLOCK_SIZE = 20000000; // 20MB blocks
static constexpr int64_t READ_SIZE = 200000; // read&scan 200kb to fit in cache
std::atomic<int64_t> doneLines(0); //number of lines processed but not yet returned
std::atomic<int64_t> returnedLines(0); //number of lines returned
std::atomic<int64_t> byteOffset(0);
std::atomic<int> chunkNumber(0);
ThreadPool tp(maxParallelism);
// Memory map if possible
const char * mapped = nullptr;
size_t mappedSize = 0;
filter_istream * fistream = dynamic_cast<filter_istream *>(&stream);
if (fistream) {
// Can we get a memory mapped version of our stream? It
// saves us having to copy data. mapped will be set to
// nullptr if it's not possible to memory map this stream.
std::tie(mapped, mappedSize) = fistream->mapped();
}
std::atomic<int> hasExc(false);
std::exception_ptr exc;
std::function<void ()> doBlock = [&] ()
{
//cerr << "block starting at line " << doneLines << endl;
std::shared_ptr<const char> blockOut;
int64_t startOffset = byteOffset;
int64_t startLine = doneLines;
vector<size_t> lineOffsets = {0};
bool lastBlock = false;
size_t myChunkNumber = 0;
try {
//MLDB-1426
if (mapped && false) {
const char * start = mapped + stream.tellg();
const char * current = start;
const char * end = mapped + mappedSize;
while (current && current < end && (current - start) < BLOCK_SIZE
&& (maxLines == -1 || doneLines < maxLines)) { //stop processing new line when we have enough)
current = (const char *)memchr(current, '\n', end - current);
if (current && current < end) {
ExcAssertEqual(*current, '\n');
lineOffsets.push_back(current - start);
++doneLines;
++current;
}
}
if (current)
stream.seekg(current - start, ios::cur);
else {
// Last line has no newline
lineOffsets.push_back(end - start);
++doneLines;
}
myChunkNumber = chunkNumber++;
if (current && current < end &&
(maxLines == -1 || doneLines < maxLines)) // don't schedule a new block if we have enough lines
{
// Ready for another chunk
tp.add(doBlock);
} else if (current == end) {
lastBlock = true;
}
blockOut = std::shared_ptr<const char>(start,
[] (const char *) {});
}
else {
// How far through our block are we?
size_t offset = 0;
// How much extra space to allocate for the last line?
static constexpr size_t EXTRA_SIZE = 10000;
std::shared_ptr<char> block(new char[BLOCK_SIZE + EXTRA_SIZE],
[] (char * c) { delete[] c; });
blockOut = block;
// First line starts at offset 0
while (stream && !stream.eof()
&& (maxLines == -1 || doneLines < maxLines) //stop processing new line when we have enough
&& (byteOffset - startOffset < BLOCK_SIZE)) {
stream.read((char *)block.get() + offset,
std::min<size_t>(READ_SIZE, BLOCK_SIZE - offset));
// Check how many bytes we actually read
size_t bytesRead = stream.gcount();
offset += bytesRead;
// Scan for end of line characters
const char * current = block.get() + lineOffsets.back();
const char * end = block.get() + offset;
while (current && current < end) {
current = (const char *)memchr(current, '\n', end - current);
if (current && current < end) {
ExcAssertEqual(*current, '\n');
if (lineOffsets.back() != current - block.get()) {
lineOffsets.push_back(current - block.get());
//cerr << "got line at offset " << lineOffsets.back() << endl;
++doneLines;
}
++current;
}
}
byteOffset += bytesRead;
}
if (stream.eof()) {
// If we are at the end of the stream
// make sure we include the last line
// if there was no newline
if (lineOffsets.back() != offset - 1) {
lineOffsets.push_back(offset);
++doneLines;
}
}
else {
// If we are not at the end of the stream
// get the last line, as we probably got just a partial
// line in the last one
std::string lastLine;
getline(stream, lastLine);
size_t cnt = stream.gcount();
if (cnt != 0) {
// Check for overflow on the buffer size
if (offset + lastLine.size() + 1 > BLOCK_SIZE + EXTRA_SIZE) {
// reallocate and copy
std::shared_ptr<char> newBlock(new char[offset + lastLine.size() + 1],
[] (char * c) { delete[] c; });
std::copy(block.get(), block.get() + offset,
newBlock.get());
block = newBlock;
blockOut = block;
}
std::copy(lastLine.data(), lastLine.data() + lastLine.length(),
block.get() + offset);
lineOffsets.emplace_back(offset + lastLine.length());
++doneLines;
offset += cnt;
}
}
myChunkNumber = chunkNumber++;
if (stream && !stream.eof() &&
(maxLines == -1 || doneLines < maxLines)) // don't schedule a new block if we have enough lines
{
// Ready for another chunk
tp.add(doBlock);
} else if (stream.eof()) {
lastBlock = true;
}
}
//cerr << "processing block of " << lineOffsets.size() - 1
// << " lines starting at " << startLine << endl;
int64_t chunkLineNumber = startLine;
size_t lastLineOffset = lineOffsets[0];
if (startBlock)
if (!startBlock(myChunkNumber, chunkLineNumber))
return;
for (unsigned i = 1; i < lineOffsets.size() && (maxLines == -1 || returnedLines++ < maxLines); ++i) {
if (hasExc.load(std::memory_order_relaxed))
return;
const char * line = blockOut.get() + lastLineOffset;
size_t len = lineOffsets[i] - lastLineOffset;
// Skip \r for DOS line endings
if (len > 0 && line[len - 1] == '\r')
--len;
// if we are not at the last line
if (!lastBlock || len != 0 || i != lineOffsets.size() - 1)
if (!onLine(line, len, chunkNumber, chunkLineNumber++))
return;
lastLineOffset = lineOffsets[i] + 1;
}
if (endBlock)
if (!endBlock(myChunkNumber, chunkLineNumber))
return;
} JML_CATCH_ALL {
if (hasExc.fetch_add(1) == 0) {
exc = std::current_exception();
}
}
};
tp.add(doBlock);
tp.waitForAll();
// If there was an exception, rethrow it rather than returning
// cleanly
if (hasExc) {
std::rethrow_exception(exc);
}
}
} // namespace Datacratic
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "include/cef_runnable.h"
#include "ScriptCore.h"
#include "ScriptException.h"
namespace CefSharp
{
bool ScriptCore::TryGetMainFrame(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame>& frame)
{
if (browser != nullptr)
{
frame = browser->GetMainFrame();
return frame != nullptr;
}
else
{
return false;
}
}
void ScriptCore::UIT_Execute(CefRefPtr<CefBrowser> browser, CefString script)
{
CefRefPtr<CefFrame> mainFrame;
if (TryGetMainFrame(browser, mainFrame))
{
mainFrame->ExecuteJavaScript(script, "about:blank", 0);
}
}
void ScriptCore::UIT_Evaluate(CefRefPtr<CefBrowser> browser, CefString script)
{
CefRefPtr<CefFrame> mainFrame;
if (TryGetMainFrame(browser, mainFrame))
{
CefRefPtr<CefV8Context> context = mainFrame->GetV8Context();
if (context.get() && context->Enter())
{
CefRefPtr<CefV8Value> global = context->GetGlobal();
CefRefPtr<CefV8Value> eval = global->GetValue("eval");
CefRefPtr<CefV8Value> arg = CefV8Value::CreateString(script);
CefRefPtr<CefV8Value> result;
CefRefPtr<CefV8Exception> exception;
CefV8ValueList args;
args.push_back(arg);
result = eval->ExecuteFunctionWithContext(context, global, args);
if (result == nullptr)
{
// XXX
_exceptionMessage = "Error";
}
else
{
try
{
_result = convertFromCef(result);
}
catch (Exception^ ex)
{
_exceptionMessage = ex->Message;
}
}
context->Exit();
}
}
else
{
_exceptionMessage = "Failed to obtain reference to main frame";
}
SetEvent(_event);
}
void ScriptCore::Execute(CefRefPtr<CefBrowser> browser, CefString script)
{
if (CefCurrentlyOn(TID_UI))
{
UIT_Execute(browser, script);
}
else
{
CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Execute,
browser, script));
}
}
gcroot<Object^> ScriptCore::Evaluate(CefRefPtr<CefBrowser> browser, CefString script, double timeout)
{
AutoLock lock_scope(this);
_result = nullptr;
_exceptionMessage = nullptr;
if (CefCurrentlyOn(TID_UI))
{
UIT_Evaluate(browser, script);
}
else
{
CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Evaluate,
browser, script));
}
switch (WaitForSingleObject(_event, timeout))
{
case WAIT_TIMEOUT:
throw gcnew ScriptException("Script timed out");
case WAIT_ABANDONED:
case WAIT_FAILED:
throw gcnew ScriptException("Script error");
}
if (_exceptionMessage)
{
throw gcnew ScriptException(_exceptionMessage);
}
else
{
return _result;
}
}
}<commit_msg>ScriptCore::UIT_EvaluateScript: use CefV8Context::Eval()<commit_after>#include "stdafx.h"
#include "include/cef_runnable.h"
#include "ScriptCore.h"
#include "ScriptException.h"
namespace CefSharp
{
bool ScriptCore::TryGetMainFrame(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame>& frame)
{
if (browser != nullptr)
{
frame = browser->GetMainFrame();
return frame != nullptr;
}
else
{
return false;
}
}
void ScriptCore::UIT_Execute(CefRefPtr<CefBrowser> browser, CefString script)
{
CefRefPtr<CefFrame> mainFrame;
if (TryGetMainFrame(browser, mainFrame))
{
mainFrame->ExecuteJavaScript(script, "about:blank", 0);
}
}
void ScriptCore::UIT_Evaluate(CefRefPtr<CefBrowser> browser, CefString script)
{
CefRefPtr<CefFrame> mainFrame;
if (TryGetMainFrame(browser, mainFrame))
{
CefRefPtr<CefV8Context> context = mainFrame->GetV8Context();
if (context.get() && context->Enter())
{
CefRefPtr<CefV8Value> result;
CefRefPtr<CefV8Exception> exception;
bool success = context->Eval(script, result, exception);
if (success)
{
try
{
_result = convertFromCef(result);
}
catch (Exception^ ex)
{
_exceptionMessage = ex->Message;
}
}
else if (exception.get())
{
_exceptionMessage = toClr(exception->GetMessage());
}
else
{
_exceptionMessage = "Failed to evaluate script";
}
context->Exit();
}
}
else
{
_exceptionMessage = "Failed to obtain reference to main frame";
}
SetEvent(_event);
}
void ScriptCore::Execute(CefRefPtr<CefBrowser> browser, CefString script)
{
if (CefCurrentlyOn(TID_UI))
{
UIT_Execute(browser, script);
}
else
{
CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Execute,
browser, script));
}
}
gcroot<Object^> ScriptCore::Evaluate(CefRefPtr<CefBrowser> browser, CefString script, double timeout)
{
AutoLock lock_scope(this);
_result = nullptr;
_exceptionMessage = nullptr;
if (CefCurrentlyOn(TID_UI))
{
UIT_Evaluate(browser, script);
}
else
{
CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Evaluate,
browser, script));
}
switch (WaitForSingleObject(_event, timeout))
{
case WAIT_TIMEOUT:
throw gcnew ScriptException("Script timed out");
case WAIT_ABANDONED:
case WAIT_FAILED:
throw gcnew ScriptException("Script error");
}
if (_exceptionMessage)
{
throw gcnew ScriptException(_exceptionMessage);
}
else
{
return _result;
}
}
}<|endoftext|> |
<commit_before>#include <Cpp/Events.hpp>
#include <gtest/gtest.h>
class Sender
{
public:
void fire() { somethingHappened_.fire(); }
Cpp::EventRef<> somethingHappened() { return somethingHappened_; }
private:
Cpp::Event<> somethingHappened_;
};
class Reciever
{
public:
Reciever() : val_() {}
void increment() { ++val_; }
void decrement() { --val_; }
int value() const { return val_; }
void setValue(int v) { val_ = v; }
private:
int val_;
};
class SenderEx : public Sender
{
public:
SenderEx() : stage_() {}
int stage() const { return stage_; }
void runStage()
{
if(!stage_) stage_ = 1;
else stage_ *= 2;
fire();
}
private:
int stage_;
};
class RecieverEx
{
public:
RecieverEx()
: sender_()
, scope_()
, val_()
{}
int value() const { return val_; }
void connect(SenderEx * sender, Cpp::ConnectionScope * scope)
{
sender_ = sender;
scope_ = scope;
scope->connect(sender->somethingHappened(), this, &RecieverEx::work);
}
void work()
{
++val_;
int stage = sender_->stage();
if(stage < 4)
{
RecieverEx * next = this + stage;
next->connect(sender_, scope_);
}
}
private:
SenderEx * sender_;
Cpp::ConnectionScope * scope_;
int val_;
};
////////////////////////////////////////////////////////////////////////////////
// This test checks basic connection management
TEST(Test_ConnectDisconnect, ManualConnectDisconnect)
{
Sender sender;
Reciever r1, r2;
Cpp::ConnectionScope scope;
ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());
sender.fire();
ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());
scope.connect(sender.somethingHappened(), &r1, &Reciever::increment);
sender.fire(); // +1-0 +0-0
ASSERT_EQ(1, r1.value()); ASSERT_EQ(0, r2.value());
sender.fire(); // +1-0 +0-0
ASSERT_EQ(2, r1.value()); ASSERT_EQ(0, r2.value());
scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
sender.fire(); // +1-0 +1-0
ASSERT_EQ(3, r1.value()); ASSERT_EQ(1, r2.value());
scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
sender.fire(); // +1-1 +1-0
ASSERT_EQ(3, r1.value()); ASSERT_EQ(2, r2.value());
scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
sender.fire(); // +1-2 +1-0
ASSERT_EQ(2, r1.value()); ASSERT_EQ(3, r2.value());
scope.connect(sender.somethingHappened(), &r2, &Reciever::decrement);
sender.fire(); // +1-2 +1-1
ASSERT_EQ(1, r1.value()); ASSERT_EQ(3, r2.value());
scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
sender.fire(); // +1-2 +2-1
ASSERT_EQ(0, r1.value()); ASSERT_EQ(4, r2.value());
sender.somethingHappened().disconnectAll(&r2, &Reciever::decrement);
sender.fire(); // +1-2 +2-0
ASSERT_EQ(-1, r1.value()); ASSERT_EQ(6, r2.value());
sender.somethingHappened().disconnectOne(&r1, &Reciever::decrement);
sender.fire(); // +1-1 +2-0
ASSERT_EQ(-1, r1.value()); ASSERT_EQ(8, r2.value());
sender.somethingHappened().disconnectAll(&r1, &Reciever::increment);
sender.fire(); // +0-1 +2-0
ASSERT_EQ(-2, r1.value()); ASSERT_EQ(10, r2.value());
sender.somethingHappened().disconnectOne(&r2, &Reciever::increment);
sender.fire(); // +0-1 +1-0
ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());
sender.somethingHappened().disconnectAll();
sender.fire(); // +0-0 +0-0
ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());
}
////////////////////////////////////////////////////////////////////////////////
// This test checks automatic disconnection
TEST(Test_ConnectDisconnect, AutomaticDisconnect)
{
Cpp::ConnectionScope scope0;
Reciever r0;
{
Sender sender;
sender.fire();
{
Reciever r1;
{
Cpp::ConnectionScope scope1;
scope1.connect(sender.somethingHappened(), &r1, &Reciever::increment);
ASSERT_EQ(0, r1.value());
sender.fire();
ASSERT_EQ(1, r1.value());
}
sender.fire();
ASSERT_EQ(1, r1.value());
{
Cpp::ConnectionScope scope2;
scope2.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
ASSERT_EQ(1, r1.value());
sender.fire();
ASSERT_EQ(0, r1.value());
}
sender.fire();
ASSERT_EQ(0, r1.value());
{
scope0.connect(sender.somethingHappened(), &r0, &Reciever::setValue, 5);
sender.fire();
ASSERT_EQ(5, r0.value());
r0.setValue(-1);
sender.fire();
ASSERT_EQ(5, r0.value());
}
}
r0.setValue(-1);
sender.fire();
ASSERT_EQ(5, r0.value());
ASSERT_NE(0, scope0.connectionCount());
}
ASSERT_EQ(0, scope0.connectionCount());
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that adding connections inside delegate works fine.
TEST(Test_ConnectDisconnect, ConnectFromDelegate)
{
RecieverEx rcv[8];
Cpp::ConnectionScope scope;
SenderEx sender;
rcv[0].connect(&sender, &scope);
ASSERT_EQ(0, rcv[0].value());
ASSERT_EQ(0, rcv[1].value());
ASSERT_EQ(0, rcv[2].value());
ASSERT_EQ(0, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(1, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(1, rcv[0].value());
ASSERT_EQ(0, rcv[1].value());
ASSERT_EQ(0, rcv[2].value());
ASSERT_EQ(0, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(2, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(2, rcv[0].value());
ASSERT_EQ(1, rcv[1].value());
ASSERT_EQ(0, rcv[2].value());
ASSERT_EQ(0, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(4, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(3, rcv[0].value());
ASSERT_EQ(2, rcv[1].value());
ASSERT_EQ(1, rcv[2].value());
ASSERT_EQ(1, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(8, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(4, rcv[0].value());
ASSERT_EQ(3, rcv[1].value());
ASSERT_EQ(2, rcv[2].value());
ASSERT_EQ(2, rcv[3].value());
ASSERT_EQ(1, rcv[4].value());
ASSERT_EQ(1, rcv[5].value());
ASSERT_EQ(1, rcv[6].value());
ASSERT_EQ(1, rcv[7].value());
ASSERT_EQ(8, sender.somethingHappened().connectionCount());
}
<commit_msg>-: Fixed: Bug in Test_ConnectDisconnect.ConnectFromDelegate<commit_after>#include <Cpp/Events.hpp>
#include <gtest/gtest.h>
class Sender
{
public:
void fire() { somethingHappened_.fire(); }
Cpp::EventRef<> somethingHappened() { return somethingHappened_; }
private:
Cpp::Event<> somethingHappened_;
};
class Reciever
{
public:
Reciever() : val_() {}
void increment() { ++val_; }
void decrement() { --val_; }
int value() const { return val_; }
void setValue(int v) { val_ = v; }
private:
int val_;
};
class SenderEx : public Sender
{
public:
SenderEx()
{
stageNo_ = 0; // 1 2 3 4 ...
stageStep_ = 1; // 2 4 8 16 ...
}
int stageNo() const { return stageNo_; }
int stageStep() const { return stageStep_; }
void runStage()
{
fire();
++stageNo_;
stageStep_ *= 2;
}
private:
int stageNo_;
int stageStep_;
};
template<int ArraySize> class RecieverEx
{
public:
RecieverEx()
: sender_()
, scope_()
, index_(-1)
, val_()
{}
int index() const { return index_; }
int value() const { return val_; }
void connect(int ind, SenderEx * sender, Cpp::ConnectionScope * scope)
{
index_ = ind;
sender_ = sender;
scope_ = scope;
scope->connect(sender->somethingHappened(), this, &RecieverEx<ArraySize>::work);
}
void work()
{
++val_;
int step = sender_->stageStep();
int nextIndex = index_ + step;
if(nextIndex < ArraySize)
{
RecieverEx<ArraySize> * next = this + step;
next->connect(nextIndex, sender_, scope_);
}
}
private:
SenderEx * sender_;
Cpp::ConnectionScope * scope_;
int index_;
int val_;
};
////////////////////////////////////////////////////////////////////////////////
// This test checks basic connection management
TEST(Test_ConnectDisconnect, ManualConnectDisconnect)
{
Sender sender;
Reciever r1, r2;
Cpp::ConnectionScope scope;
ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());
sender.fire();
ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());
scope.connect(sender.somethingHappened(), &r1, &Reciever::increment);
sender.fire(); // +1-0 +0-0
ASSERT_EQ(1, r1.value()); ASSERT_EQ(0, r2.value());
sender.fire(); // +1-0 +0-0
ASSERT_EQ(2, r1.value()); ASSERT_EQ(0, r2.value());
scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
sender.fire(); // +1-0 +1-0
ASSERT_EQ(3, r1.value()); ASSERT_EQ(1, r2.value());
scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
sender.fire(); // +1-1 +1-0
ASSERT_EQ(3, r1.value()); ASSERT_EQ(2, r2.value());
scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
sender.fire(); // +1-2 +1-0
ASSERT_EQ(2, r1.value()); ASSERT_EQ(3, r2.value());
scope.connect(sender.somethingHappened(), &r2, &Reciever::decrement);
sender.fire(); // +1-2 +1-1
ASSERT_EQ(1, r1.value()); ASSERT_EQ(3, r2.value());
scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
sender.fire(); // +1-2 +2-1
ASSERT_EQ(0, r1.value()); ASSERT_EQ(4, r2.value());
sender.somethingHappened().disconnectAll(&r2, &Reciever::decrement);
sender.fire(); // +1-2 +2-0
ASSERT_EQ(-1, r1.value()); ASSERT_EQ(6, r2.value());
sender.somethingHappened().disconnectOne(&r1, &Reciever::decrement);
sender.fire(); // +1-1 +2-0
ASSERT_EQ(-1, r1.value()); ASSERT_EQ(8, r2.value());
sender.somethingHappened().disconnectAll(&r1, &Reciever::increment);
sender.fire(); // +0-1 +2-0
ASSERT_EQ(-2, r1.value()); ASSERT_EQ(10, r2.value());
sender.somethingHappened().disconnectOne(&r2, &Reciever::increment);
sender.fire(); // +0-1 +1-0
ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());
sender.somethingHappened().disconnectAll();
sender.fire(); // +0-0 +0-0
ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());
}
////////////////////////////////////////////////////////////////////////////////
// This test checks automatic disconnection
TEST(Test_ConnectDisconnect, AutomaticDisconnect)
{
Cpp::ConnectionScope scope0;
Reciever r0;
{
Sender sender;
sender.fire();
{
Reciever r1;
{
Cpp::ConnectionScope scope1;
scope1.connect(sender.somethingHappened(), &r1, &Reciever::increment);
ASSERT_EQ(0, r1.value());
sender.fire();
ASSERT_EQ(1, r1.value());
}
sender.fire();
ASSERT_EQ(1, r1.value());
{
Cpp::ConnectionScope scope2;
scope2.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
ASSERT_EQ(1, r1.value());
sender.fire();
ASSERT_EQ(0, r1.value());
}
sender.fire();
ASSERT_EQ(0, r1.value());
{
scope0.connect(sender.somethingHappened(), &r0, &Reciever::setValue, 5);
sender.fire();
ASSERT_EQ(5, r0.value());
r0.setValue(-1);
sender.fire();
ASSERT_EQ(5, r0.value());
}
}
r0.setValue(-1);
sender.fire();
ASSERT_EQ(5, r0.value());
ASSERT_NE(0, scope0.connectionCount());
}
ASSERT_EQ(0, scope0.connectionCount());
}
////////////////////////////////////////////////////////////////////////////////
// This test ensures that adding connections inside delegate works fine.
TEST(Test_ConnectDisconnect, ConnectFromDelegate)
{
RecieverEx<8> rcv[8];
Cpp::ConnectionScope scope;
SenderEx sender;
rcv[0].connect(0, &sender, &scope);
ASSERT_EQ(0, rcv[0].value());
ASSERT_EQ(0, rcv[1].value());
ASSERT_EQ(0, rcv[2].value());
ASSERT_EQ(0, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(1, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(1, rcv[0].value());
ASSERT_EQ(0, rcv[1].value());
ASSERT_EQ(0, rcv[2].value());
ASSERT_EQ(0, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(2, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(2, rcv[0].value());
ASSERT_EQ(1, rcv[1].value());
ASSERT_EQ(0, rcv[2].value());
ASSERT_EQ(0, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(4, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(3, rcv[0].value());
ASSERT_EQ(2, rcv[1].value());
ASSERT_EQ(1, rcv[2].value());
ASSERT_EQ(1, rcv[3].value());
ASSERT_EQ(0, rcv[4].value());
ASSERT_EQ(0, rcv[5].value());
ASSERT_EQ(0, rcv[6].value());
ASSERT_EQ(0, rcv[7].value());
ASSERT_EQ(8, sender.somethingHappened().connectionCount());
sender.runStage();
ASSERT_EQ(4, rcv[0].value());
ASSERT_EQ(3, rcv[1].value());
ASSERT_EQ(2, rcv[2].value());
ASSERT_EQ(2, rcv[3].value());
ASSERT_EQ(1, rcv[4].value());
ASSERT_EQ(1, rcv[5].value());
ASSERT_EQ(1, rcv[6].value());
ASSERT_EQ(1, rcv[7].value());
ASSERT_EQ(8, sender.somethingHappened().connectionCount());
}
<|endoftext|> |
<commit_before># include <Siv3D.hpp>
void Main()
{
//const Texture texture(L"example/siv3d-kun.png");
while (System::Update())
{
Texture texture(L"example/siv3d-kun.png");
}
}
<commit_msg>v0.1.2 リリース準備<commit_after>
# include <Siv3D.hpp>
void Main()
{
Graphics::SetBackground(Palette::White);
double t = 0.0;
while (System::Update())
{
Window::SetTitle(Profiler::FPS(), L"FPS");
t += System::DeltaTime();
for (auto i : step(36))
{
const double angle = i * 10_deg + t * 30_deg;
const Vec2 pos = Circular(200, angle) + Window::Center();
RectF(25).setCenter(pos).rotated(angle).draw(HSV(i * 10));
}
Circle(Cursor::Pos(), 40).draw(ColorF(1.0, 0.0, 0.0, 0.5));
}
}
<|endoftext|> |
<commit_before>#include "em.h"
EM::EM(std::function<long double(std::tuple<T...>)> q_function, std::function<std::tuple<T...>(std::tuple<T...>)> m_function, std::tuple<T...> theta) : q_function(q_function), m_function(m_function), likelihood(0), theta(theta){
}
long double EM::likelihood_diff(long double previous, long double current){
if (current < previous){
throw std::runtime_error("likelihood went down. previous value: " + std::to_string(previous) ", current value: " + std::to_string(current));
} else {
return current - previous;
}
}
std::vector EM::start(long double stop){
do{
long double currentlike = q_function(theta);
std::clog << "Theta: " << theta << "likelihood: " << currentlike << std::endl;
long double difference = likelihood_diff(likelihood, currentlike);
likelihood = currentlike;
theta = m_function(theta);
} while (difference < stop);
return theta;
}
long double EM::get_likelihood(){
return likelihood;
}
<commit_msg>make function generic<commit_after>#include "em.h"
EM::EM(std::function<long double(std::tuple<T...>)> q_function, std::function<std::tuple<T...>(std::tuple<T...>)> m_function, std::tuple<T...> theta) : q_function(q_function), m_function(m_function), likelihood(0), theta(theta){
}
long double EM::likelihood_diff(long double previous, long double current){
if (current < previous){
throw std::runtime_error("likelihood went down. previous value: " + std::to_string(previous) ", current value: " + std::to_string(current));
} else {
return current - previous;
}
}
std::tuple<T...> EM::start(long double stop){
do{
long double currentlike = q_function(theta);
std::clog << "Theta: " << theta << "likelihood: " << currentlike << std::endl;
long double difference = likelihood_diff(likelihood, currentlike);
likelihood = currentlike;
theta = m_function(theta);
} while (difference < stop);
return theta;
}
long double EM::get_likelihood(){
return likelihood;
}
<|endoftext|> |
<commit_before>#if !defined(_TSXX_SYSTEM_HPP_)
#define _TSXX_SYSTEM_HPP_
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <tsxx/exceptions.hpp>
#define LOG(x) (std::clog << __FILE__ << ":" << __LINE__ << ": " << (x) << std::endl)
#define FIXME() LOG("FIXME")
#define TODO() LOG("TODO")
#define XXX() LOG("XXX")
namespace tsxx
{
namespace system
{
class
file_descriptor
: private boost::noncopyable
{
public:
file_descriptor(int fd = -1);
~file_descriptor();
int get_value() const;
void close();
bool is_valid();
private:
int fd;
};
typedef boost::shared_ptr<file_descriptor> file_descriptor_ptr;
class
memory_region
: private boost::noncopyable
{
public:
memory_region(file_descriptor_ptr fd);
~memory_region();
bool map(std::size_t len, off_t offset);
void unmap();
void *get_pointer();
private:
file_descriptor_ptr fd;
void *pointer;
std::size_t length;
};
typedef boost::shared_ptr<memory_region> memory_region_ptr;
// CopyableMemoryRegion
class
memory_region_window
{
public:
memory_region_window(memory_region_ptr reg, off_t off);
void *get_pointer();
private:
memory_region_ptr region;
off_t offset;
};
class
memory
: private boost::noncopyable // XXX check if this is really needed
{
public:
memory();
std::size_t get_region_size() const;
bool is_opened();
bool open();
void try_close();
memory_region_window get_region(off_t address);
private:
file_descriptor_ptr fd;
std::map<off_t, memory_region_ptr> memory_regions;
std::size_t region_size;
};
// TODO Calibrate this function.
/**
* @warning This function hasn't been calibrated yet.
*/
inline void
nssleep(unsigned int ns)
{
volatile unsigned int loop = ns * 3;
asm volatile (
"1:\n"
"subs %1, %1, #1;\n"
"bne 1b;\n"
: "=r" ((loop)) : "r" ((loop))
);
}
}
}
#endif // !defined(_TSXX_SYSTEM_HPP_)
<commit_msg>Incremented delay in "nssleep".<commit_after>#if !defined(_TSXX_SYSTEM_HPP_)
#define _TSXX_SYSTEM_HPP_
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <tsxx/exceptions.hpp>
#define LOG(x) (std::clog << __FILE__ << ":" << __LINE__ << ": " << (x) << std::endl)
#define FIXME() LOG("FIXME")
#define TODO() LOG("TODO")
#define XXX() LOG("XXX")
namespace tsxx
{
namespace system
{
class
file_descriptor
: private boost::noncopyable
{
public:
file_descriptor(int fd = -1);
~file_descriptor();
int get_value() const;
void close();
bool is_valid();
private:
int fd;
};
typedef boost::shared_ptr<file_descriptor> file_descriptor_ptr;
class
memory_region
: private boost::noncopyable
{
public:
memory_region(file_descriptor_ptr fd);
~memory_region();
bool map(std::size_t len, off_t offset);
void unmap();
void *get_pointer();
private:
file_descriptor_ptr fd;
void *pointer;
std::size_t length;
};
typedef boost::shared_ptr<memory_region> memory_region_ptr;
class
memory_region_window
{
public:
memory_region_window(memory_region_ptr reg, off_t off);
void *get_pointer();
private:
memory_region_ptr region;
off_t offset;
};
class
memory
: private boost::noncopyable // XXX check if this is really needed
{
public:
memory();
std::size_t get_region_size() const;
bool is_opened();
bool open();
void try_close();
memory_region_window get_region(off_t address);
private:
file_descriptor_ptr fd;
std::map<off_t, memory_region_ptr> memory_regions;
std::size_t region_size;
};
// TODO Calibrate this function.
/**
* @warning This function hasn't been calibrated yet.
*/
inline void
nssleep(unsigned int ns)
{
volatile unsigned int loop = ns * 5;
asm volatile (
"1:\n"
"subs %1, %1, #1;\n"
"bne 1b;\n"
: "=r" ((loop)) : "r" ((loop))
);
}
}
}
#endif // !defined(_TSXX_SYSTEM_HPP_)
<|endoftext|> |
<commit_before>//----------------------------------------------------------------------------
/// \file bitmap.cpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Bitmap index suitable for indexing up to 64 or 4096 values on a
/// 64bit platform with fast iteration between adjacent items.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <[email protected]>
// Created: 2009-12-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2009 Serge Aleynikov <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_BITMAP_HPP_
#define _UTXX_BITMAP_HPP_
#include <boost/assert.hpp>
#include <utxx/meta.hpp>
#include <utxx/atomic.hpp>
#include <utxx/detail/bit_count.hpp>
#include <sstream>
#include <stdio.h>
namespace utxx {
template <int N, typename T = unsigned long>
class bitmap_low {
T m_data;
void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
typedef T value_type;
bitmap_low() : m_data(0) {
BOOST_STATIC_ASSERT(1 <= N && N <= sizeof(long)*8);
}
static const unsigned int max = N - 1;
static const unsigned int cend = N;
T value() const { return m_data; }
unsigned int end() const { return cend; }
bool empty() const { return m_data == 0; }
void clear() { m_data = 0; }
void set(unsigned int i) { valid(i); m_data |= 1ul << i; }
void clear(unsigned int i) { valid(i); m_data ^= m_data & (1ul << i); }
bool is_set(unsigned int i) const { valid(i); return m_data & (1ul << i); }
int first() const { return m_data ? atomic::bit_scan_forward(m_data) : end(); }
int last() const { return m_data ? atomic::bit_scan_reverse(m_data) : end(); }
int count() const { return bitcount(m_data); }
bool operator[] (unsigned int i) const { return is_set(i); }
void operator= (const bitmap_low<N>& rhs) { m_data = rhs.value(); }
/// @param <i> is the bit to search from in the forward direction.
/// Valid range [0 ... max-1].
/// @return position of next enabled bit or <end()> if not found.
int next(unsigned int i) const {
T val = m_data >> ++i;
return val && i <= max ? atomic::bit_scan_forward(val)+i : end();
}
/// @param <i> is the bit to search from in the reverse direction.
/// Valid range [1 ... max].
/// @return position of previous enabled bit or <end()> if not found.
int prev(unsigned int i) const {
BOOST_ASSERT(i <= max);
T val = m_data & ((1ul << i)-1);
return val && i >= 0 ? atomic::bit_scan_reverse(val) : end();
}
std::ostream& print(std::ostream& out) const {
std::stringstream s;
for(int i=max+1; i > 0; --i) {
if (i != max+1 && i%8 == 0) s << '-';
s << (is_set(i-1) ? '1' : '0');
}
return out << s.str();
}
};
template <int N, typename T = unsigned long>
class bitmap_high: protected bitmap_low<sizeof(long)*8, T> {
typedef bitmap_low<sizeof(long)*8, T> base;
public:
// the following static members are made public just for testing
static const int s_lo_dim = base::max + 1;
static const int s_hi_sft = log<s_lo_dim, 2>::value;
static const int s_lo_mask = base::max;
static const int s_hi_dim = N / (sizeof(long)*8) +
((N & (N - 1)) == 0 ? 0 : 1);
private:
base m_data[s_hi_dim];
void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
bitmap_high() {
BOOST_STATIC_ASSERT(sizeof(long)*8 < N && N <= sizeof(long)*sizeof(long)*64);
}
static const unsigned int max = N - 1;
unsigned int end() const { return max+1; }
bool empty() const { return base::value() == 0; }
void clear() {
for (int i=0; i < s_hi_dim; ++i) m_data[i].clear();
base::clear();
}
void set(unsigned int i) {
valid(i);
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
m_data[hi].set(lo);
base::set(m_data[hi].value() ? hi : 0);
}
void clear(unsigned int i) {
valid(i);
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
m_data[hi].clear(lo);
if (!m_data[hi].value())
base::clear(hi);
}
bool operator[] (unsigned int i) const { return is_set(i); }
void operator= (const bitmap_high<N>& rhs) {
for (int i=0; i < s_hi_dim; ++i) m_data[i] = rhs.value();
this->base::operator= (rhs.base::value());
}
bool is_set(unsigned int i) const {
valid(i);
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
return base::is_set(hi) && m_data[hi].is_set(lo);
}
int first() const {
int hi=base::first();
return base::value() ? (hi<<s_hi_sft | m_data[hi].first()):end();
}
int last() const {
int hi=base::last();
return base::value() ? (hi<<s_hi_sft | m_data[hi].last() ):end();
}
int count() const {
int sum = 0;
for (unsigned int i = base::first(); i != base::end(); i = base::next(i)) {
sum += bitcount(m_data[i].value());
}
return sum;
}
int next(unsigned int i) const {
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
if (lo < base::max) {
lo = m_data[hi].next(lo);
if (lo != base::end()) return (hi << s_hi_sft | lo);
}
if (hi == base::max) return end();
hi = base::next(hi);
return hi == base::end() ? end() : (hi << s_hi_sft | m_data[hi].first());
}
int prev(unsigned int i) const {
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
if (lo > 0) {
lo = m_data[hi].prev(lo);
if (lo != base::end()) return (hi << s_hi_sft | lo);
}
if (hi == 0) return end();
hi = base::prev(hi);
return m_data[hi].value() ? (hi << s_hi_sft | m_data[hi].last()) : end();
}
std::ostream& print(std::ostream& out, const char* sep = "\n") const {
std::stringstream s;
for(int i=s_hi_dim-1; i >= 0; --i) {
char buf[9];
if (i != s_lo_dim-1 && (i+1)%8 != 0 && i != s_hi_dim-1) s << '-';
if ((i+1)%8 == 0 || (s_hi_dim < 8 && i == (s_hi_dim-1))) {
sprintf(buf, "%s%02d: ", sep, i+1);
s << buf;
}
sprintf(buf, "%016lx", m_data[i].value());
s << buf;
}
return out << s.str();
}
};
typedef bitmap_low<16> bitmap16;
typedef bitmap_low<32> bitmap32;
typedef
boost::mpl::if_c<sizeof(long)==8,
bitmap_low<48>,
bitmap_high<48> >::type bitmap48;
typedef
boost::mpl::if_c<sizeof(long)==8,
bitmap_low<64>,
bitmap_high<64> >::type bitmap64;
typedef bitmap_high<128> bitmap128;
typedef bitmap_high<256> bitmap256;
typedef bitmap_high<512> bitmap512;
typedef bitmap_high<1024> bitmap1024;
typedef bitmap_high<4096> bitmap4096;
} // namespace utxx
#endif // _HPCL_BITMAP_HPP_
<commit_msg>Add fill method<commit_after>//----------------------------------------------------------------------------
/// \file bitmap.cpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Bitmap index suitable for indexing up to 64 or 4096 values on a
/// 64bit platform with fast iteration between adjacent items.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <[email protected]>
// Created: 2009-12-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project.
Copyright (C) 2009 Serge Aleynikov <[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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_BITMAP_HPP_
#define _UTXX_BITMAP_HPP_
#include <boost/assert.hpp>
#include <utxx/meta.hpp>
#include <utxx/atomic.hpp>
#include <utxx/detail/bit_count.hpp>
#include <sstream>
#include <stdio.h>
namespace utxx {
template <int N, typename T = unsigned long>
class bitmap_low {
T m_data;
void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
typedef T value_type;
bitmap_low() : m_data(0) {
BOOST_STATIC_ASSERT(1 <= N && N <= sizeof(long)*8);
}
static const unsigned int max = N - 1;
static const unsigned int cend = N;
T value() const { return m_data; }
unsigned int end() const { return cend; }
bool empty() const { return m_data == 0; }
void clear() { m_data = 0; }
void fill() { m_data = uint64_t(-1); }
void set(unsigned int i) { valid(i); m_data |= 1ul << i; }
void clear(unsigned int i) { valid(i); m_data ^= m_data & (1ul << i); }
bool is_set(unsigned int i) const { valid(i); return m_data & (1ul << i); }
int first() const { return m_data ? atomic::bit_scan_forward(m_data) : end(); }
int last() const { return m_data ? atomic::bit_scan_reverse(m_data) : end(); }
int count() const { return bitcount(m_data); }
bool operator[] (unsigned int i) const { return is_set(i); }
void operator= (const bitmap_low<N>& rhs) { m_data = rhs.value(); }
/// @param <i> is the bit to search from in the forward direction.
/// Valid range [0 ... max-1].
/// @return position of next enabled bit or <end()> if not found.
int next(unsigned int i) const {
T val = m_data >> ++i;
return val && i <= max ? atomic::bit_scan_forward(val)+i : end();
}
/// @param <i> is the bit to search from in the reverse direction.
/// Valid range [1 ... max].
/// @return position of previous enabled bit or <end()> if not found.
int prev(unsigned int i) const {
BOOST_ASSERT(i <= max);
T val = m_data & ((1ul << i)-1);
return val && i >= 0 ? atomic::bit_scan_reverse(val) : end();
}
std::ostream& print(std::ostream& out) const {
std::stringstream s;
for(int i=max+1; i > 0; --i) {
if (i != max+1 && i%8 == 0) s << '-';
s << (is_set(i-1) ? '1' : '0');
}
return out << s.str();
}
};
template <int N, typename T = unsigned long>
class bitmap_high: protected bitmap_low<sizeof(long)*8, T> {
typedef bitmap_low<sizeof(long)*8, T> base;
public:
// the following static members are made public just for testing
static const int s_lo_dim = base::max + 1;
static const int s_hi_sft = log<s_lo_dim, 2>::value;
static const int s_lo_mask = base::max;
static const int s_hi_dim = N / (sizeof(long)*8) +
((N & (N - 1)) == 0 ? 0 : 1);
private:
base m_data[s_hi_dim];
void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
bitmap_high() {
BOOST_STATIC_ASSERT(sizeof(long)*8 < N && N <= sizeof(long)*sizeof(long)*64);
}
static const unsigned int max = N - 1;
unsigned int end() const { return max+1; }
bool empty() const { return base::value() == 0; }
void fill() {
for (int i=0; i < s_hi_dim; ++i) m_data[i].fill();
base::fill();
}
void clear() {
for (int i=0; i < s_hi_dim; ++i) m_data[i].clear();
base::clear();
}
void set(unsigned int i) {
valid(i);
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
m_data[hi].set(lo);
base::set(m_data[hi].value() ? hi : 0);
}
void clear(unsigned int i) {
valid(i);
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
m_data[hi].clear(lo);
if (!m_data[hi].value())
base::clear(hi);
}
bool operator[] (unsigned int i) const { return is_set(i); }
void operator= (const bitmap_high<N>& rhs) {
for (int i=0; i < s_hi_dim; ++i) m_data[i] = rhs.value();
this->base::operator= (rhs.base::value());
}
bool is_set(unsigned int i) const {
valid(i);
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
return base::is_set(hi) && m_data[hi].is_set(lo);
}
int first() const {
int hi=base::first();
return base::value() ? (hi<<s_hi_sft | m_data[hi].first()):end();
}
int last() const {
int hi=base::last();
return base::value() ? (hi<<s_hi_sft | m_data[hi].last() ):end();
}
int count() const {
int sum = 0;
for (unsigned int i = base::first(); i != base::end(); i = base::next(i)) {
sum += bitcount(m_data[i].value());
}
return sum;
}
int next(unsigned int i) const {
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
if (lo < base::max) {
lo = m_data[hi].next(lo);
if (lo != base::end()) return (hi << s_hi_sft | lo);
}
if (hi == base::max) return end();
hi = base::next(hi);
return hi == base::end() ? end() : (hi << s_hi_sft | m_data[hi].first());
}
int prev(unsigned int i) const {
unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
if (lo > 0) {
lo = m_data[hi].prev(lo);
if (lo != base::end()) return (hi << s_hi_sft | lo);
}
if (hi == 0) return end();
hi = base::prev(hi);
return m_data[hi].value() ? (hi << s_hi_sft | m_data[hi].last()) : end();
}
std::ostream& print(std::ostream& out, const char* sep = "\n") const {
std::stringstream s;
for(int i=s_hi_dim-1; i >= 0; --i) {
char buf[9];
if (i != s_lo_dim-1 && (i+1)%8 != 0 && i != s_hi_dim-1) s << '-';
if ((i+1)%8 == 0 || (s_hi_dim < 8 && i == (s_hi_dim-1))) {
sprintf(buf, "%s%02d: ", sep, i+1);
s << buf;
}
sprintf(buf, "%016lx", m_data[i].value());
s << buf;
}
return out << s.str();
}
};
typedef bitmap_low<16> bitmap16;
typedef bitmap_low<32> bitmap32;
typedef
boost::mpl::if_c<sizeof(long)==8,
bitmap_low<48>,
bitmap_high<48> >::type bitmap48;
typedef
boost::mpl::if_c<sizeof(long)==8,
bitmap_low<64>,
bitmap_high<64> >::type bitmap64;
typedef bitmap_high<128> bitmap128;
typedef bitmap_high<256> bitmap256;
typedef bitmap_high<512> bitmap512;
typedef bitmap_high<1024> bitmap1024;
typedef bitmap_high<4096> bitmap4096;
} // namespace utxx
#endif // _HPCL_BITMAP_HPP_
<|endoftext|> |
<commit_before>#include "module_pressuresensor.h"
#include "pressure_form.h"
#include <Module_UID/module_uid.h>
#define REGISTER_CALIB 00 // 8 bytes
#define REGISTER_PRESSURE_RAW 8
#define REGISTER_TEMP_RAW 10
#define REGISTER_PRESSURE 12
#define REGISTER_TEMP 14
#define REGISTER_STATUS 17
#define REGISTER_COUNTER 20
// indicates problem between i2c-spi bridge and pressure sensor
#define STATUS_MAGIC_VALUE 0x55
#define CALIB_MAGIC_VALUE 224
// pressure range. everything outside this range will be regarded as
// a meassurement error
#define PRESSURE_MIN 900
#define PRESSURE_MAX 3000
Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid)
: RobotModule(id)
{
this->uid=uid;
setDefaultValue("i2cAddress", 0x50);
setDefaultValue("frequency", 1);
connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData()));
reset();
}
Module_PressureSensor::~Module_PressureSensor()
{
}
void Module_PressureSensor::terminate()
{
RobotModule::terminate();
timer.stop();
}
void Module_PressureSensor::reset()
{
RobotModule::reset();
int freq = 1000/getSettings().value("frequency").toInt();
if (freq>0)
timer.start(freq);
else
timer.stop();
if (!getSettings().value("enabled").toBool())
return;
readCalibWords();
}
void Module_PressureSensor::refreshData()
{
if (!getSettings().value("enabled").toBool())
return;
readPressure();
readTemperature();
readCounter();
readRawRegisters();
calc();
if (getHealthStatus().isHealthOk()) {
emit dataChanged(this);
emit newDepthData(getDepth());
}
}
void Module_PressureSensor::calc()
{
short D1 = data["pressureRaw"].toInt();
short D2 = data["tempRaw"].toInt();
short C1 = data["C1"].toInt();
short C2 = data["C2"].toInt();
short C3 = data["C3"].toInt();
short C4 = data["C4"].toInt();
short C5 = data["C5"].toInt();
short C6 = data["C6"].toInt();
int UT1, dT, OFF, SENS, P;
short int dT2;
// Calculate calibration temperature
UT1 = 8*C5+10000;
// Calculate actual temperature
dT = D2 - UT1;
// Second-order temperature compensation
if (dT < 0)
dT2 = dT - (dT/128*dT/128)/2;
else
dT2 = dT - (dT/128*dT/128)/8;
data["tempSW"] = 200+dT2*(C6+100)/2048;
// Calculate temperature compensated pressure
OFF = C2+((C4-250)*dT)/4096+10000;
SENS = C1/2 + ((C3+200)*dT)/8192 + 3000;
// Temperature compensated pressure in mbar
P = (SENS*(D1-OFF))/4096+1000;
data["pressureSW"] = P;
}
void Module_PressureSensor::readPressure()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the pressure in mBar
uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["pressure"] = pressure;
// 100 mBar == ca. 1m wassersäule - druck an der luft
data["depth"] = ((float)pressure-getSettings().value("airPressure").toFloat())/100;
if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) {
setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense.");
}
}
void Module_PressureSensor::readCounter()
{
unsigned char readBuffer[1];
if (!readRegister(REGISTER_COUNTER, 1, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
data["counter"] = readBuffer[0];
}
void Module_PressureSensor::readCalibWords()
{
unsigned char readBuffer[8];
if (!readRegister(0, 8, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
uint16_t pressure_CalibrationWords[4];
for(int i=0;i<4;i++) {
// this is the temperature in 10/degree celsius
uint16_t c = (int)readBuffer[i] << 8 | (int)readBuffer[i+1];
data["calib"+i] = c;
pressure_CalibrationWords[i]=c;
}
data["C1"] = ((pressure_CalibrationWords[0] & 0xFFF8) >> 3);
data["C2"] = ((pressure_CalibrationWords[0] & 0x0007) << 10) + ((pressure_CalibrationWords[1] & 0xFFC0) >> 6);
data["C3"] = ((pressure_CalibrationWords[2] & 0xFFC0) >> 6);
data["C4"] = ((pressure_CalibrationWords[3] & 0xFF80) >> 7);
data["C5"] = ((pressure_CalibrationWords[1] & 0x003F) << 6) + ((pressure_CalibrationWords[2] & 0x003F));
data["C6"] = (pressure_CalibrationWords[3] & 0x007F);
}
void Module_PressureSensor::readRawRegisters()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_TEMP_RAW, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["tempRaw"] = temp;
if (!readRegister(REGISTER_PRESSURE_RAW, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["pressureRaw"] = pressure;
}
void Module_PressureSensor::readTemperature()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_TEMP, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the temperature in 10/degree celsius
uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["temperature"] = ((float)temp)/10;
}
float Module_PressureSensor::getDepth()
{
float p = data["pressure"].toFloat();
if (p > 900 && p <= 2000) {
return data["depth"].toFloat();
} else {
setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense.");
return 0;
}
}
float Module_PressureSensor::getTemperature()
{
return data["temperature"].toFloat();
}
QList<RobotModule*> Module_PressureSensor::getDependencies()
{
QList<RobotModule*> ret;
ret.append(uid);
return ret;
}
QWidget* Module_PressureSensor::createView(QWidget* parent)
{
return new Pressure_Form(this, parent);
}
void Module_PressureSensor::doHealthCheck()
{
if (!getSettings().value("enabled").toBool())
return;
unsigned char readBuffer[1];
if (!readRegister(REGISTER_STATUS, 1, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
if (readBuffer[0] != STATUS_MAGIC_VALUE) {
setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0]));
return;
}
setHealthToOk();
}
bool Module_PressureSensor::readRegister2(unsigned char reg, int size, unsigned char *ret_buf)
{
unsigned char address = getSettings().value("i2cAddress").toInt();
if (!uid->I2C_Write(address, ®, 1)) {
setHealthToSick("UID reported error.");
return false;
}
if (!uid->I2C_Read(address, size, ret_buf)) {
setHealthToSick("UID reported error.");
return false;
}
return true;
}
bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf)
{
unsigned char address = getSettings().value("i2cAddress").toInt();
if (!uid->I2C_ReadRegisters(address, reg, size, ret_buf)) {
setHealthToSick("UID reported error.");
return false;
}
return true;
}
<commit_msg>- read out new calib words at each reset on the pressure controller - ui fix<commit_after>#include "module_pressuresensor.h"
#include "pressure_form.h"
#include <Module_UID/module_uid.h>
#define REGISTER_CALIB 00 // 8 bytes
#define REGISTER_PRESSURE_RAW 8
#define REGISTER_TEMP_RAW 10
#define REGISTER_PRESSURE 12
#define REGISTER_TEMP 14
#define REGISTER_STATUS 17
#define REGISTER_COUNTER 20
// indicates problem between i2c-spi bridge and pressure sensor
#define STATUS_MAGIC_VALUE 0x55
#define CALIB_MAGIC_VALUE 224
// pressure range. everything outside this range will be regarded as
// a meassurement error
#define PRESSURE_MIN 900
#define PRESSURE_MAX 3000
Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid)
: RobotModule(id)
{
this->uid=uid;
setDefaultValue("i2cAddress", 0x50);
setDefaultValue("frequency", 1);
connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData()));
reset();
}
Module_PressureSensor::~Module_PressureSensor()
{
}
void Module_PressureSensor::terminate()
{
RobotModule::terminate();
timer.stop();
}
void Module_PressureSensor::reset()
{
RobotModule::reset();
int freq = 1000/getSettings().value("frequency").toInt();
if (freq>0)
timer.start(freq);
else
timer.stop();
if (!getSettings().value("enabled").toBool())
return;
readCalibWords();
}
void Module_PressureSensor::refreshData()
{
if (!getSettings().value("enabled").toBool())
return;
readPressure();
readTemperature();
readCounter();
readRawRegisters();
calc();
if (getHealthStatus().isHealthOk()) {
emit dataChanged(this);
emit newDepthData(getDepth());
}
}
void Module_PressureSensor::calc()
{
short D1 = data["pressureRaw"].toInt();
short D2 = data["tempRaw"].toInt();
short C1 = data["C1"].toInt();
short C2 = data["C2"].toInt();
short C3 = data["C3"].toInt();
short C4 = data["C4"].toInt();
short C5 = data["C5"].toInt();
short C6 = data["C6"].toInt();
int UT1, dT, OFF, SENS, P;
short int dT2;
// Calculate calibration temperature
UT1 = 8*C5+10000;
// Calculate actual temperature
dT = D2 - UT1;
// Second-order temperature compensation
if (dT < 0)
dT2 = dT - (dT/128*dT/128)/2;
else
dT2 = dT - (dT/128*dT/128)/8;
data["tempSW"] = 200+dT2*(C6+100)/2048;
// Calculate temperature compensated pressure
OFF = C2+((C4-250)*dT)/4096+10000;
SENS = C1/2 + ((C3+200)*dT)/8192 + 3000;
// Temperature compensated pressure in mbar
P = (SENS*(D1-OFF))/4096+1000;
data["pressureSW"] = P;
}
void Module_PressureSensor::readPressure()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the pressure in mBar
uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["pressure"] = pressure;
// 100 mBar == ca. 1m wassersäule - druck an der luft
data["depth"] = ((float)pressure-getSettings().value("airPressure").toFloat())/100;
if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) {
setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense.");
}
}
void Module_PressureSensor::readCounter()
{
unsigned char readBuffer[1];
if (!readRegister(REGISTER_COUNTER, 1, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
data["counter"] = readBuffer[0];
}
void Module_PressureSensor::readCalibWords()
{
unsigned char address = getSettings().value("i2cAddress").toInt();
unsigned char cmd[] = { 0x12 };
if (!uid->I2C_Write(address, cmd, 1)) {
setHealthToSick("could not reread calib words.");
sleep(100);
return;
}
sleep(100);
unsigned char readBuffer[8];
if (!readRegister(0, 8, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
uint16_t pressure_CalibrationWords[4];
for(int i=0;i<4;i++) {
// this is the temperature in 10/degree celsius
uint16_t c = (int)readBuffer[2*i] << 8 | (int)readBuffer[2*i+1];
data["calib "+QString::number(i)] = "0x"+QString::number(c,16);
pressure_CalibrationWords[i]=c;
}
data["C1"] = ((pressure_CalibrationWords[0] & 0xFFF8) >> 3);
data["C2"] = ((pressure_CalibrationWords[0] & 0x0007) << 10) + ((pressure_CalibrationWords[1] & 0xFFC0) >> 6);
data["C3"] = ((pressure_CalibrationWords[2] & 0xFFC0) >> 6);
data["C4"] = ((pressure_CalibrationWords[3] & 0xFF80) >> 7);
data["C5"] = ((pressure_CalibrationWords[1] & 0x003F) << 6) + ((pressure_CalibrationWords[2] & 0x003F));
data["C6"] = (pressure_CalibrationWords[3] & 0x007F);
}
void Module_PressureSensor::readRawRegisters()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_TEMP_RAW, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["tempRaw"] = temp;
if (!readRegister(REGISTER_PRESSURE_RAW, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["pressureRaw"] = pressure;
}
void Module_PressureSensor::readTemperature()
{
unsigned char readBuffer[2];
if (!readRegister(REGISTER_TEMP, 2, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
// this is the temperature in 10/degree celsius
uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];
data["temperature"] = ((float)temp)/10;
}
float Module_PressureSensor::getDepth()
{
float p = data["pressure"].toFloat();
if (p > 900 && p <= 2000) {
return data["depth"].toFloat();
} else {
setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense.");
return 0;
}
}
float Module_PressureSensor::getTemperature()
{
return data["temperature"].toFloat();
}
QList<RobotModule*> Module_PressureSensor::getDependencies()
{
QList<RobotModule*> ret;
ret.append(uid);
return ret;
}
QWidget* Module_PressureSensor::createView(QWidget* parent)
{
return new Pressure_Form(this, parent);
}
void Module_PressureSensor::doHealthCheck()
{
if (!getSettings().value("enabled").toBool())
return;
unsigned char readBuffer[1];
if (!readRegister(REGISTER_STATUS, 1, readBuffer)) {
setHealthToSick("UID reported error.");
return;
}
if (readBuffer[0] != STATUS_MAGIC_VALUE) {
setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0]));
return;
}
setHealthToOk();
}
bool Module_PressureSensor::readRegister2(unsigned char reg, int size, unsigned char *ret_buf)
{
unsigned char address = getSettings().value("i2cAddress").toInt();
if (!uid->I2C_Write(address, ®, 1)) {
setHealthToSick("UID reported error.");
return false;
}
if (!uid->I2C_Read(address, size, ret_buf)) {
setHealthToSick("UID reported error.");
return false;
}
return true;
}
bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf)
{
unsigned char address = getSettings().value("i2cAddress").toInt();
if (!uid->I2C_ReadRegisters(address, reg, size, ret_buf)) {
setHealthToSick("UID reported error.");
return false;
}
return true;
}
<|endoftext|> |
<commit_before>#include "itkBSplineControlPointImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkN3MRIBiasFieldCorrectionImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkShrinkImageFilter.h"
template <unsigned int ImageDimension>
int N3BiasFieldCorrection( int argc, char *argv[] )
{
typedef float RealType;
typedef itk::Image<RealType, ImageDimension> ImageType;
typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkerType;
typename ShrinkerType::Pointer shrinker = ShrinkerType::New();
shrinker->SetInput( reader->GetOutput() );
shrinker->SetShrinkFactors( 1 );
typename MaskImageType::Pointer maskImage = NULL;
if( argc > 5 )
{
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
maskreader->SetFileName( argv[5] );
try
{
maskreader->Update();
maskImage = maskreader->GetOutput();
}
catch(...)
{
std::cout << "Mask file not read. Generating mask file using otsu"
<< " thresholding." << std::endl;
}
}
if( !maskImage )
{
typedef itk::OtsuThresholdImageFilter<ImageType, MaskImageType>
ThresholderType;
typename ThresholderType::Pointer otsu = ThresholderType::New();
otsu->SetInput( reader->GetOutput() );
otsu->SetNumberOfHistogramBins( 200 );
otsu->SetInsideValue( 0 );
otsu->SetOutsideValue( 1 );
otsu->Update();
maskImage = otsu->GetOutput();
}
typedef itk::ShrinkImageFilter<MaskImageType, MaskImageType> MaskShrinkerType;
typename MaskShrinkerType::Pointer maskshrinker = MaskShrinkerType::New();
maskshrinker->SetInput( maskImage );
maskshrinker->SetShrinkFactors( 1 );
if( argc > 4 )
{
shrinker->SetShrinkFactors( atoi( argv[4] ) );
maskshrinker->SetShrinkFactors( atoi( argv[4] ) );
}
shrinker->Update();
maskshrinker->Update();
typedef itk::N3MRIBiasFieldCorrectionImageFilter<ImageType, MaskImageType,
ImageType> CorrecterType;
typename CorrecterType::Pointer correcter = CorrecterType::New();
correcter->SetInput( shrinker->GetOutput() );
correcter->SetMaskImage( maskshrinker->GetOutput() );
if( argc > 6 )
{
correcter->SetMaximumNumberOfIterations( atoi( argv[6] ) );
}
if( argc > 7 )
{
correcter->SetNumberOfFittingLevels( atoi( argv[7] ) );
}
try
{
correcter->Update();
}
catch(...)
{
std::cerr << "Exception caught." << std::endl;
return EXIT_FAILURE;
}
// correcter->Print( std::cout, 3 );
/**
* Reconstruct the bias field at full image resolution. Divide
* the original input image by the bias field to get the final
* corrected image.
*/
typedef itk::BSplineControlPointImageFilter<typename
CorrecterType::BiasFieldControlPointLatticeType, typename
CorrecterType::ScalarImageType> BSplinerType;
typename BSplinerType::Pointer bspliner = BSplinerType::New();
bspliner->SetInput( correcter->GetBiasFieldControlPointLattice() );
bspliner->SetSplineOrder( correcter->GetSplineOrder() );
bspliner->SetSize(
reader->GetOutput()->GetLargestPossibleRegion().GetSize() );
bspliner->SetOrigin( reader->GetOutput()->GetOrigin() );
bspliner->SetDirection( reader->GetOutput()->GetDirection() );
bspliner->SetSpacing( reader->GetOutput()->GetSpacing() );
bspliner->Update();
typename ImageType::Pointer logField = ImageType::New();
logField->SetOrigin( bspliner->GetOutput()->GetOrigin() );
logField->SetSpacing( bspliner->GetOutput()->GetSpacing() );
logField->SetRegions(
bspliner->GetOutput()->GetLargestPossibleRegion().GetSize() );
logField->SetDirection( bspliner->GetOutput()->GetDirection() );
logField->Allocate();
itk::ImageRegionIterator<typename CorrecterType::ScalarImageType> ItB(
bspliner->GetOutput(),
bspliner->GetOutput()->GetLargestPossibleRegion() );
itk::ImageRegionIterator<ImageType> ItF( logField,
logField->GetLargestPossibleRegion() );
for( ItB.GoToBegin(), ItF.GoToBegin(); !ItB.IsAtEnd(); ++ItB, ++ItF )
{
ItF.Set( ItB.Get()[0] );
}
typedef itk::ExpImageFilter<ImageType, ImageType> ExpFilterType;
typename ExpFilterType::Pointer expFilter = ExpFilterType::New();
expFilter->SetInput( logField );
expFilter->Update();
typedef itk::DivideImageFilter<ImageType, ImageType, ImageType> DividerType;
typename DividerType::Pointer divider = DividerType::New();
divider->SetInput1( reader->GetOutput() );
divider->SetInput2( expFilter->GetOutput() );
divider->Update();
typedef itk::ImageFileWriter<ImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[3] );
writer->SetInput( divider->GetOutput() );
writer->Update();
if( argc > 8 )
{
typedef itk::ImageFileWriter<ImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[8] );
writer->SetInput( expFilter->GetOutput() );
writer->Update();
}
return EXIT_SUCCESS;
}
int main( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Usage: " << argv[0] << " imageDimension inputImage "
<< "outputImage [shrinkFactor] [maskImage] [numberOfIterations] "
<< "[numberOfFittingLevels] [outputBiasField] " << std::endl;
exit( EXIT_FAILURE );
}
switch( atoi( argv[1] ) )
{
case 2:
N3BiasFieldCorrection<2>( argc, argv );
break;
case 3:
N3BiasFieldCorrection<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
}
<commit_msg>STYLE: Changed N3 portion to accommodate recent (small) change to itkN3BiasFieldCorrectionImageFilter<commit_after>#include "itkBSplineControlPointImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkN3MRIBiasFieldCorrectionImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkShrinkImageFilter.h"
template <unsigned int ImageDimension>
int N3BiasFieldCorrection( int argc, char *argv[] )
{
typedef float RealType;
typedef itk::Image<RealType, ImageDimension> ImageType;
typedef itk::Image<unsigned char, ImageDimension> MaskImageType;
typedef itk::ImageFileReader<ImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[2] );
reader->Update();
typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkerType;
typename ShrinkerType::Pointer shrinker = ShrinkerType::New();
shrinker->SetInput( reader->GetOutput() );
shrinker->SetShrinkFactors( 1 );
typename MaskImageType::Pointer maskImage = NULL;
if( argc > 5 )
{
typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
maskreader->SetFileName( argv[5] );
try
{
maskreader->Update();
maskImage = maskreader->GetOutput();
}
catch(...)
{
std::cout << "Mask file not read. Generating mask file using otsu"
<< " thresholding." << std::endl;
}
}
if( !maskImage )
{
typedef itk::OtsuThresholdImageFilter<ImageType, MaskImageType>
ThresholderType;
typename ThresholderType::Pointer otsu = ThresholderType::New();
otsu->SetInput( reader->GetOutput() );
otsu->SetNumberOfHistogramBins( 200 );
otsu->SetInsideValue( 0 );
otsu->SetOutsideValue( 1 );
otsu->Update();
maskImage = otsu->GetOutput();
}
typedef itk::ShrinkImageFilter<MaskImageType, MaskImageType> MaskShrinkerType;
typename MaskShrinkerType::Pointer maskshrinker = MaskShrinkerType::New();
maskshrinker->SetInput( maskImage );
maskshrinker->SetShrinkFactors( 1 );
if( argc > 4 )
{
shrinker->SetShrinkFactors( atoi( argv[4] ) );
maskshrinker->SetShrinkFactors( atoi( argv[4] ) );
}
shrinker->Update();
maskshrinker->Update();
typedef itk::N3MRIBiasFieldCorrectionImageFilter<ImageType, MaskImageType,
ImageType> CorrecterType;
typename CorrecterType::Pointer correcter = CorrecterType::New();
correcter->SetInput( shrinker->GetOutput() );
correcter->SetMaskImage( maskshrinker->GetOutput() );
if( argc > 6 )
{
correcter->SetMaximumNumberOfIterations( atoi( argv[6] ) );
}
if( argc > 7 )
{
correcter->SetNumberOfFittingLevels( atoi( argv[7] ) );
}
try
{
correcter->Update();
}
catch(...)
{
std::cerr << "Exception caught." << std::endl;
return EXIT_FAILURE;
}
// correcter->Print( std::cout, 3 );
/**
* Reconstruct the bias field at full image resolution. Divide
* the original input image by the bias field to get the final
* corrected image.
*/
typedef itk::BSplineControlPointImageFilter<typename
CorrecterType::BiasFieldControlPointLatticeType, typename
CorrecterType::ScalarImageType> BSplinerType;
typename BSplinerType::Pointer bspliner = BSplinerType::New();
bspliner->SetInput( correcter->GetLogBiasFieldControlPointLattice() );
bspliner->SetSplineOrder( correcter->GetSplineOrder() );
bspliner->SetSize(
reader->GetOutput()->GetLargestPossibleRegion().GetSize() );
bspliner->SetOrigin( reader->GetOutput()->GetOrigin() );
bspliner->SetDirection( reader->GetOutput()->GetDirection() );
bspliner->SetSpacing( reader->GetOutput()->GetSpacing() );
bspliner->Update();
typename ImageType::Pointer logField = ImageType::New();
logField->SetOrigin( bspliner->GetOutput()->GetOrigin() );
logField->SetSpacing( bspliner->GetOutput()->GetSpacing() );
logField->SetRegions(
bspliner->GetOutput()->GetLargestPossibleRegion().GetSize() );
logField->SetDirection( bspliner->GetOutput()->GetDirection() );
logField->Allocate();
itk::ImageRegionIterator<typename CorrecterType::ScalarImageType> ItB(
bspliner->GetOutput(),
bspliner->GetOutput()->GetLargestPossibleRegion() );
itk::ImageRegionIterator<ImageType> ItF( logField,
logField->GetLargestPossibleRegion() );
for( ItB.GoToBegin(), ItF.GoToBegin(); !ItB.IsAtEnd(); ++ItB, ++ItF )
{
ItF.Set( ItB.Get()[0] );
}
typedef itk::ExpImageFilter<ImageType, ImageType> ExpFilterType;
typename ExpFilterType::Pointer expFilter = ExpFilterType::New();
expFilter->SetInput( logField );
expFilter->Update();
typedef itk::DivideImageFilter<ImageType, ImageType, ImageType> DividerType;
typename DividerType::Pointer divider = DividerType::New();
divider->SetInput1( reader->GetOutput() );
divider->SetInput2( expFilter->GetOutput() );
divider->Update();
typedef itk::ImageFileWriter<ImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[3] );
writer->SetInput( divider->GetOutput() );
writer->Update();
if( argc > 8 )
{
typedef itk::ImageFileWriter<ImageType> WriterType;
typename WriterType::Pointer writer = WriterType::New();
writer->SetFileName( argv[8] );
writer->SetInput( expFilter->GetOutput() );
writer->Update();
}
return EXIT_SUCCESS;
}
int main( int argc, char *argv[] )
{
if ( argc < 4 )
{
std::cerr << "Usage: " << argv[0] << " imageDimension inputImage "
<< "outputImage [shrinkFactor] [maskImage] [numberOfIterations] "
<< "[numberOfFittingLevels] [outputBiasField] " << std::endl;
exit( EXIT_FAILURE );
}
switch( atoi( argv[1] ) )
{
case 2:
N3BiasFieldCorrection<2>( argc, argv );
break;
case 3:
N3BiasFieldCorrection<3>( argc, argv );
break;
default:
std::cerr << "Unsupported dimension" << std::endl;
exit( EXIT_FAILURE );
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <QApplication>
#include <QDBusConnection>
#include <QDBusError>
#include <QDBusInterface>
#include <QDeclarativeEngine>
#include <QDeclarativeView>
#include <QGraphicsItem>
#include <QDeclarativeContext>
#include <QDeclarativeNetworkAccessManagerFactory>
#include <QDesktopWidget>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QGLFormat>
#include <QLibraryInfo>
#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QNetworkProxy>
#include <QResizeEvent>
#include <QSettings>
#include <QTimer>
#include <QTextStream>
#include <QTranslator>
#include <QVariant>
#include <QX11Info>
#include <MGConfItem>
#include <QInputContext>
#include "launcherwindow.h"
#include "launcheratoms.h"
#include "launcherapp.h"
#include "meegoqmllauncher.h"
#include <QX11Info>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <unistd.h>
class NetworkAccessManagerFactory : public QDeclarativeNetworkAccessManagerFactory
{
public:
virtual QNetworkAccessManager *create(QObject *parent);
};
QNetworkAccessManager *NetworkAccessManagerFactory::create(QObject *parent)
{
QUrl httpProxy(getenv("http_proxy"));
QNetworkAccessManager *nam = new QNetworkAccessManager(parent);
if (!httpProxy.isEmpty())
{
QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy,
httpProxy.host(),
httpProxy.port());
nam->setProxy(proxy);
}
QNetworkDiskCache *cache = new QNetworkDiskCache();
cache->setCacheDirectory(QDir::homePath() + "/.cache/" + qApp->applicationName());
nam->setCache(cache);
return nam;
}
LauncherWindow::LauncherWindow(bool fullscreen, int width, int height, bool opengl, bool doSetSource, QWidget *parent) :
QDeclarativeView(parent),
m_inhibitScreenSaver(false),
m_useOpenGl(opengl),
m_usingGl(false)
{
LauncherApp *app = static_cast<LauncherApp *>(qApp);
setAttribute(Qt::WA_OpaquePaintEvent);
setAttribute(Qt::WA_NoSystemBackground);
engine()->setNetworkAccessManagerFactory(new NetworkAccessManagerFactory);
connect(engine(), SIGNAL(quit()), qApp, SLOT(closeAllWindows()));
connect((const QObject*)qApp->inputContext(), SIGNAL(inputMethodAreaChanged(QRect)),
this, SLOT(handleInputMethodAreaChanged(QRect)));
connect(qApp, SIGNAL(dismissKeyboard()), this, SLOT(dismissKeyboard()));
QDeclarativeContext *context = rootContext();
context->setContextProperty("qApp", qApp);
context->setContextProperty("mainWindow", this);
context->setContextProperty("theme_name", MGConfItem("/meego/ux/theme").value().toString());
foreach (QString key, app->themeConfig->allKeys())
{
if (key.contains("Size") || key.contains("Padding") ||
key.contains("Width") ||key.contains("Height") ||
key.contains("Margin") || key.contains("Thickness"))
{
context->setContextProperty("theme_" + key, app->themeConfig->value(key).toInt());
}
else if (key.contains("Opacity"))
{
context->setContextProperty("theme_" + key, app->themeConfig->value(key).toDouble());
}
else
{
context->setContextProperty("theme_" + key, app->themeConfig->value(key));
}
}
loadCommonTranslators();
connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadCommonTranslators()));
// Qt will search each translator for a string translation, starting with
// the last translator installed working back to the first translator.
// The first translation found wins.
app->installTranslator(&qtTranslator); // General Qt translations
app->installTranslator(&commonTranslator); // Common Components translations
app->installTranslator(&mediaTranslator); // Common Media translations
if (app->applicationName() != MeeGoQMLLauncher::preinitialisedAppName)
{
init(fullscreen, width, height, opengl, doSetSource);
}
}
LauncherWindow::~LauncherWindow()
{
}
void LauncherWindow::init(bool fullscreen, int width, int height,
bool opengl, bool doSetSource)
{
m_useOpenGl = opengl;
LauncherApp *app = static_cast<LauncherApp *>(qApp);
setWindowTitle(app->applicationName());
setWindowIconText(app->applicationName());
int screenWidth;
int screenHeight;
if (fullscreen)
{
screenWidth = qApp->desktop()->rect().width();
screenHeight = qApp->desktop()->rect().height();
setWindowFlags(Qt::FramelessWindowHint);
}
else
{
screenWidth = width;
screenHeight = height;
}
QDeclarativeContext *context = rootContext();
context->setContextProperty("screenWidth", screenWidth);
context->setContextProperty("screenHeight", screenHeight);
if (doSetSource) {
sharePath = QString("/usr/share/") + app->applicationName() + "/";
if (!QFile::exists(sharePath + "main.qml"))
{
qFatal("%s does not exist!", sharePath.toUtf8().data());
}
}
loadAppTranslators();
connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadAppTranslators()));
app->installTranslator(&appTranslator); // App specific translations
// Switch to GL rendering if it's available
switchToGLRendering();
if (doSetSource)
{
setSource(QUrl(sharePath + "main.qml"));
}
setGeometry(QRect(0, 0, screenWidth, screenHeight));
connect(app, SIGNAL(foregroundWindowChanged()), this, SLOT(updateOrientationSensorOn()));
}
void LauncherWindow::keyPressEvent ( QKeyEvent * event )
{
if ((event->modifiers() & Qt::ControlModifier) && event->key() == Qt::Key_R)
{
QGraphicsObject* window = rootObject();
if (window)
{
QVariant orientation = window->property("orientation");
if(orientation.isValid())
{
int orient = orientation.toInt();
orient = ((orient + 1) % 4);
orientation.setValue(orient);
window->setProperty("orientation", orientation);
return;
}
}
}
QDeclarativeView::keyPressEvent(event);
}
void LauncherWindow::loadCommonTranslators()
{
qtTranslator.load("qt_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
commonTranslator.load("meegolabs-ux-components_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
mediaTranslator.load("meego-ux-media-qml_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}
void LauncherWindow::loadAppTranslators()
{
LauncherApp *app = static_cast<LauncherApp *>(qApp);
appTranslator.load(app->applicationName() + "_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}
void LauncherWindow::triggerSystemUIMenu()
{
QDBusInterface iface("com.nokia.systemui","/statusindicatormenu","com.meego.core.MStatusIndicatorMenu");
if(iface.isValid()) iface.call("open");
}
void LauncherWindow::goHome()
{
setWindowState(windowState() ^ Qt::WindowMinimized);
}
// Called by LauncherApplication when it wants to dismiss the
// keyboard. hideOnFocusOut() is a slot on MInputContext, that seems
// to be required, it doesn't get it right if you just drop the focus
// (bug in MInputContext?)
void LauncherWindow::dismissKeyboard()
{
if(scene() && scene()->focusItem())
{
if (QMetaObject::invokeMethod(qApp->inputContext(), "hideOnFocusOut"))
{
scene()->focusItem()->clearFocus();
}
}
}
void LauncherWindow::forwardCall(const QStringList& parameters)
{
m_call = parameters;
emit call(parameters);
emit callChanged();
}
void LauncherWindow::setActualOrientation(int orientation)
{
m_actualOrientation = orientation;
if (!winId())
{
return;
}
Atom orientationAtom = XInternAtom(QX11Info::display(), "_MEEGO_ORIENTATION", false);
XChangeProperty(QX11Info::display(), winId(), orientationAtom, XA_CARDINAL, 32,
PropModeReplace, (unsigned char*)&m_actualOrientation, 1);
}
bool LauncherWindow::event (QEvent * event)
{
if (event->type() == QEvent::Show)
{
setActualOrientation(m_actualOrientation);
}
return QWidget::event(event);
}
void LauncherWindow::setInhibitScreenSaver(bool inhibit)
{
m_inhibitScreenSaver = inhibit;
Atom inhibitAtom = XInternAtom(QX11Info::display(), "_MEEGO_INHIBIT_SCREENSAVER", false);
if (inhibit)
{
XChangeProperty(QX11Info::display(), winId(), inhibitAtom, XA_CARDINAL, 32,
PropModeReplace, (unsigned char*)&m_inhibitScreenSaver, 1);
}
else
{
XDeleteProperty(QX11Info::display(), winId(), inhibitAtom);
}
}
void LauncherWindow::updateOrientationSensorOn()
{
LauncherApp *app = static_cast<LauncherApp *>(qApp);
app->setOrientationSensorOn(app->getForegroundWindow() == winId());
}
void LauncherWindow::switchToGLRendering()
{
if (m_usingGl || !m_useOpenGl)
return;
//go once around event loop to avoid crash in egl
QTimer::singleShot(0, this, SLOT(doSwitchToGLRendering()));
}
void LauncherWindow::switchToSoftwareRendering()
{
// no need to change viewport unnecessarily
if (!m_usingGl)
return;
setViewport(0);
// each time we create a new viewport widget, we must redo our optimisations
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
viewport()->setAttribute(Qt::WA_NoSystemBackground);
m_usingGl = false;
}
void LauncherWindow::doSwitchToGLRendering()
{
QGLFormat format = QGLFormat::defaultFormat();
format.setSampleBuffers(false);
setViewport(new QGLWidget(format));
// each time we create a new viewport widget, we must redo our optimisations
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
viewport()->setAttribute(Qt::WA_NoSystemBackground);
m_usingGl = true;
}
<commit_msg>Stop crashing in chroot, call setAttribute via viewport()<commit_after>/*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#include <QApplication>
#include <QDBusConnection>
#include <QDBusError>
#include <QDBusInterface>
#include <QDeclarativeEngine>
#include <QDeclarativeView>
#include <QGraphicsItem>
#include <QDeclarativeContext>
#include <QDeclarativeNetworkAccessManagerFactory>
#include <QDesktopWidget>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QGLFormat>
#include <QLibraryInfo>
#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QNetworkProxy>
#include <QResizeEvent>
#include <QSettings>
#include <QTimer>
#include <QTextStream>
#include <QTranslator>
#include <QVariant>
#include <QX11Info>
#include <MGConfItem>
#include <QInputContext>
#include "launcherwindow.h"
#include "launcheratoms.h"
#include "launcherapp.h"
#include "meegoqmllauncher.h"
#include <QX11Info>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <unistd.h>
class NetworkAccessManagerFactory : public QDeclarativeNetworkAccessManagerFactory
{
public:
virtual QNetworkAccessManager *create(QObject *parent);
};
QNetworkAccessManager *NetworkAccessManagerFactory::create(QObject *parent)
{
QUrl httpProxy(getenv("http_proxy"));
QNetworkAccessManager *nam = new QNetworkAccessManager(parent);
if (!httpProxy.isEmpty())
{
QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy,
httpProxy.host(),
httpProxy.port());
nam->setProxy(proxy);
}
QNetworkDiskCache *cache = new QNetworkDiskCache();
cache->setCacheDirectory(QDir::homePath() + "/.cache/" + qApp->applicationName());
nam->setCache(cache);
return nam;
}
LauncherWindow::LauncherWindow(bool fullscreen, int width, int height, bool opengl, bool doSetSource, QWidget *parent) :
QDeclarativeView(parent),
m_inhibitScreenSaver(false),
m_useOpenGl(opengl),
m_usingGl(false)
{
LauncherApp *app = static_cast<LauncherApp *>(qApp);
viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
viewport()->setAttribute(Qt::WA_NoSystemBackground);
engine()->setNetworkAccessManagerFactory(new NetworkAccessManagerFactory);
connect(engine(), SIGNAL(quit()), qApp, SLOT(closeAllWindows()));
connect((const QObject*)qApp->inputContext(), SIGNAL(inputMethodAreaChanged(QRect)),
this, SLOT(handleInputMethodAreaChanged(QRect)));
connect(qApp, SIGNAL(dismissKeyboard()), this, SLOT(dismissKeyboard()));
QDeclarativeContext *context = rootContext();
context->setContextProperty("qApp", qApp);
context->setContextProperty("mainWindow", this);
context->setContextProperty("theme_name", MGConfItem("/meego/ux/theme").value().toString());
foreach (QString key, app->themeConfig->allKeys())
{
if (key.contains("Size") || key.contains("Padding") ||
key.contains("Width") ||key.contains("Height") ||
key.contains("Margin") || key.contains("Thickness"))
{
context->setContextProperty("theme_" + key, app->themeConfig->value(key).toInt());
}
else if (key.contains("Opacity"))
{
context->setContextProperty("theme_" + key, app->themeConfig->value(key).toDouble());
}
else
{
context->setContextProperty("theme_" + key, app->themeConfig->value(key));
}
}
loadCommonTranslators();
connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadCommonTranslators()));
// Qt will search each translator for a string translation, starting with
// the last translator installed working back to the first translator.
// The first translation found wins.
app->installTranslator(&qtTranslator); // General Qt translations
app->installTranslator(&commonTranslator); // Common Components translations
app->installTranslator(&mediaTranslator); // Common Media translations
if (app->applicationName() != MeeGoQMLLauncher::preinitialisedAppName)
{
init(fullscreen, width, height, opengl, doSetSource);
}
}
LauncherWindow::~LauncherWindow()
{
}
void LauncherWindow::init(bool fullscreen, int width, int height,
bool opengl, bool doSetSource)
{
m_useOpenGl = opengl;
LauncherApp *app = static_cast<LauncherApp *>(qApp);
setWindowTitle(app->applicationName());
setWindowIconText(app->applicationName());
int screenWidth;
int screenHeight;
if (fullscreen)
{
screenWidth = qApp->desktop()->rect().width();
screenHeight = qApp->desktop()->rect().height();
setWindowFlags(Qt::FramelessWindowHint);
}
else
{
screenWidth = width;
screenHeight = height;
}
QDeclarativeContext *context = rootContext();
context->setContextProperty("screenWidth", screenWidth);
context->setContextProperty("screenHeight", screenHeight);
if (doSetSource) {
sharePath = QString("/usr/share/") + app->applicationName() + "/";
if (!QFile::exists(sharePath + "main.qml"))
{
qFatal("%s does not exist!", sharePath.toUtf8().data());
}
}
loadAppTranslators();
connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadAppTranslators()));
app->installTranslator(&appTranslator); // App specific translations
// Switch to GL rendering if it's available
switchToGLRendering();
if (doSetSource)
{
setSource(QUrl(sharePath + "main.qml"));
}
setGeometry(QRect(0, 0, screenWidth, screenHeight));
connect(app, SIGNAL(foregroundWindowChanged()), this, SLOT(updateOrientationSensorOn()));
}
void LauncherWindow::keyPressEvent ( QKeyEvent * event )
{
if ((event->modifiers() & Qt::ControlModifier) && event->key() == Qt::Key_R)
{
QGraphicsObject* window = rootObject();
if (window)
{
QVariant orientation = window->property("orientation");
if(orientation.isValid())
{
int orient = orientation.toInt();
orient = ((orient + 1) % 4);
orientation.setValue(orient);
window->setProperty("orientation", orientation);
return;
}
}
}
QDeclarativeView::keyPressEvent(event);
}
void LauncherWindow::loadCommonTranslators()
{
qtTranslator.load("qt_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
commonTranslator.load("meegolabs-ux-components_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
mediaTranslator.load("meego-ux-media-qml_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}
void LauncherWindow::loadAppTranslators()
{
LauncherApp *app = static_cast<LauncherApp *>(qApp);
appTranslator.load(app->applicationName() + "_" + QLocale::system().name() + ".qm",
QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}
void LauncherWindow::triggerSystemUIMenu()
{
QDBusInterface iface("com.nokia.systemui","/statusindicatormenu","com.meego.core.MStatusIndicatorMenu");
if(iface.isValid()) iface.call("open");
}
void LauncherWindow::goHome()
{
setWindowState(windowState() ^ Qt::WindowMinimized);
}
// Called by LauncherApplication when it wants to dismiss the
// keyboard. hideOnFocusOut() is a slot on MInputContext, that seems
// to be required, it doesn't get it right if you just drop the focus
// (bug in MInputContext?)
void LauncherWindow::dismissKeyboard()
{
if(scene() && scene()->focusItem())
{
if (QMetaObject::invokeMethod(qApp->inputContext(), "hideOnFocusOut"))
{
scene()->focusItem()->clearFocus();
}
}
}
void LauncherWindow::forwardCall(const QStringList& parameters)
{
m_call = parameters;
emit call(parameters);
emit callChanged();
}
void LauncherWindow::setActualOrientation(int orientation)
{
m_actualOrientation = orientation;
if (!winId())
{
return;
}
Atom orientationAtom = XInternAtom(QX11Info::display(), "_MEEGO_ORIENTATION", false);
XChangeProperty(QX11Info::display(), winId(), orientationAtom, XA_CARDINAL, 32,
PropModeReplace, (unsigned char*)&m_actualOrientation, 1);
}
bool LauncherWindow::event (QEvent * event)
{
if (event->type() == QEvent::Show)
{
setActualOrientation(m_actualOrientation);
}
return QWidget::event(event);
}
void LauncherWindow::setInhibitScreenSaver(bool inhibit)
{
m_inhibitScreenSaver = inhibit;
Atom inhibitAtom = XInternAtom(QX11Info::display(), "_MEEGO_INHIBIT_SCREENSAVER", false);
if (inhibit)
{
XChangeProperty(QX11Info::display(), winId(), inhibitAtom, XA_CARDINAL, 32,
PropModeReplace, (unsigned char*)&m_inhibitScreenSaver, 1);
}
else
{
XDeleteProperty(QX11Info::display(), winId(), inhibitAtom);
}
}
void LauncherWindow::updateOrientationSensorOn()
{
LauncherApp *app = static_cast<LauncherApp *>(qApp);
app->setOrientationSensorOn(app->getForegroundWindow() == winId());
}
void LauncherWindow::switchToGLRendering()
{
if (m_usingGl || !m_useOpenGl)
return;
//go once around event loop to avoid crash in egl
QTimer::singleShot(0, this, SLOT(doSwitchToGLRendering()));
}
void LauncherWindow::switchToSoftwareRendering()
{
// no need to change viewport unnecessarily
if (!m_usingGl)
return;
setViewport(0);
// each time we create a new viewport widget, we must redo our optimisations
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
viewport()->setAttribute(Qt::WA_NoSystemBackground);
m_usingGl = false;
}
void LauncherWindow::doSwitchToGLRendering()
{
QGLFormat format = QGLFormat::defaultFormat();
format.setSampleBuffers(false);
setViewport(new QGLWidget(format));
// each time we create a new viewport widget, we must redo our optimisations
setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
viewport()->setAttribute(Qt::WA_NoSystemBackground);
m_usingGl = true;
}
<|endoftext|> |
<commit_before>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>
#include <stdlib.h>
using namespace std;
ClassUI::ClassUI()
{
}
void ClassUI::mainMenu()
{
if (firstRun == true)
{
cout << "\t" << "Welcome to the Amazing Database! " << endl;
cout << "--------------------------------------------------------------" << endl;
cout << "\t" << " *** Quote of the day ***" << endl;
cout << getQuotes() << endl;
firstRun = false;
}
string choice;
do
{
cout << "--------------------------------------------------------------" << endl;
cout << " (1) - " << "Add a scientist to the database." << endl;
cout << " (2) - " << "Remove a scientist from the database." << endl;
cout << " (3) - " << "View the entire database." << endl;
cout << " (4) - " << "Save the database." << endl;
cout << " (5) - " << "Search the database." << endl;
cout << " (6) - " << "Sort the database." << endl;
cout << " (7) - " << "Edit a scientist." << endl;
cout << " (8) - " << "Exit." << endl;
cout << "Enter your command (1 - 8): ";
cin >> choice;
if (choice != "8")
{
select(choice);
}
else
{
list.saveFile();
runOn = false;
}
}while(runOn == true);
cout << endl;
}
void ClassUI::select(string ch)
{
if(ch == "1")
{
cin.ignore(); // When using editPerson it will ignore the first letter unless this ignore is here rather then in addPerson
addPerson();
}
else if(ch == "2")
{
remove();
}
else if(ch == "3")
{
viewAll();
}
else if(ch == "4")
{
save();
}
else if(ch == "5")
{
searching();
}
else if(ch == "6")
{
sorting();
}
else if(ch == "7")
{
editPerson();
}
else if(ch == "yo")
{
yo();
}
else
{
cout << "Invalid input. Please enter a number between 1 - 7." << endl;
}
}
void ClassUI::view(int i)
{
cout << "--------------------------------------------------------------" << endl;
int nameSize = list.getNameSize(i);
cout << list.getName(i);
if(nameSize > 0 && nameSize <= 7)
{
cout << "\t" << "\t" << "\t" << "\t";
}
else if(nameSize > 7 && nameSize <= 15)
{
cout << "\t" << "\t" << "\t";
}
else if(nameSize > 15 && nameSize <= 23)
{
cout << "\t" << "\t";
}
else if(nameSize > 23 && nameSize <= 31)
{
cout << "\t";
}
if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
{
cout << "|Male" << "\t";
}
else
{
cout << "|Female" << "\t";
}
cout << "|" << list.getBirth(i);
if(list.getDeath(i) == 0)
{
cout << "\t" << "| n/a" << "\t" << "|" << list.getAge(i) << endl;
}
else
{
cout << "\t" << "|" << list.getDeath(i) << "\t" << "|" << list.getAge(i) << endl;
}
cout << list.getComment(i) << endl;
}
void ClassUI::viewAll()
{
cout << "--------------------------------------------------------------" << endl;
cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << "\t" << "|Age" << endl;
for(int i = 0; i < list.personsSize(); i++)
{
view(i);
}
}
void ClassUI::addPerson()
{
string name;
string comment;
char gender;
char yesOrNo;
int yearOfBirth = 0;
int yearOfDeath = 0;
cout << "--------------------------------------------------------------" << endl;
cout << "Enter name of the scientist: ";
std::getline(std::cin,name);
cout << "Enter a gender (M/F): ";
cin >> gender;
if (gender == 'm')
{
gender = 'M';
}
else if (gender == 'f')
{
gender = 'F';
}
if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
{
cout << "Enter a year of birth: ";
cin >> yearOfBirth;
if (yearOfBirth < 0 || yearOfBirth > 2016)
{
cout << "not a valid year of birth" << endl;
return mainMenu();
}
cout << "Is the individual deceased? (y/n) ";
cin >> yesOrNo;
if (yesOrNo == 'Y' || yesOrNo == 'y')
{
cout << "Enter a year of death: ";
cin >> yearOfDeath;
if(yearOfBirth > yearOfDeath)
{
cout << "Not a valid year of death" << endl;
return mainMenu();
}
}
cout << "Enter a comment about the scientist: ";
cin.ignore();
std::getline(std::cin,comment);
}
else
{
cout << "Invalid gender! Try again." << endl;
return mainMenu();
}
cout << "Are you sure that you want to add this scientist? (y/n) ";
string validatePerson;
cin >> validatePerson;
if(validatePerson == "y")
{
cout << "New scientist added!" << endl;
list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
}
else
{
cout << "scientist not added!" << endl;
}
}
void ClassUI::searching()
{
cout << "-------------Select any of the following commands-------------" << endl;
cout << "What do you want to search for?" << endl;
cout << " (1) - Search by name." << endl;
cout << " (2) - Search by gender." << endl;
cout << " (3) - Search by year of birth." << endl;
cout << " (4) - Search by age." << endl;
cout << " (5) - Return to main menu." << endl;
search();
}
void ClassUI::search()
{
string searchChoice;
cout << "Enter your command (1 - 5): ";
cin >> searchChoice;
cout << endl;
if (searchChoice == "1")
{
string namesearch;
cout << "--------------------------------------------------------------" << endl;
cout << "Enter a name you want to search for: ";
cin.ignore();
std::getline(std::cin,namesearch);
cout << "--------------------------------------------------------------" << endl;
for(int i = 0; i < list.personsSize();++i)
{
std::size_t found = list.getName(i).find(namesearch);
if (found!=std::string::npos)
{
view(i);
}
}
if(list.nameSearcher(namesearch) == false)
{
cout << "Sorry that name is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "2")
{
char gendersearch;
cout << "Enter a gender you want to search for: (M/F)";
cin >> gendersearch;
if(gendersearch == 'm')
{
gendersearch = 'M';
}
else if (gendersearch == 'f')
{
gendersearch = 'F';
}
for(int i = 0; i < list.personsSize();++i)
{
if(gendersearch == list.getGender(i))
{
gendersearch = list.getGender(i);
view(i);
}
}
if(list.genderSearcher(gendersearch) == false)
{
cout << "Sorry that gender is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "3")
{
int yearsearch;
cout << "Enter a year you want to search for: ";
cin >> yearsearch;
for(int i = 0; i < list.personsSize();++i)
{
if(yearsearch == list.getBirth(i))
{
yearsearch = list.getBirth(i);
view(i);
}
}
if(list.yearSearcher(yearsearch) == false)
{
cout << "Sorry that year is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "4")
{
int ageSearch;
cout << "Enter a age you want to search for: ";
cin >> ageSearch;
for(int i = 0; i < list.personsSize();++i)
{
if(ageSearch == list.getAge(i))
{
ageSearch = list.getAge(i);
view(i);
}
}
if(list.ageSearcher(ageSearch) == false)
{
cout << "Sorry that age is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "5")
{
mainMenu();
}
else
{
cout << "Error reading input. Please enter a number between 1- 3." << endl;
search();
}
}
void ClassUI::remove()
{
string name;
cout << "--------------------------------------------------------------" << endl;
cout << "Enter the full name of the scientist that you want to remove: ";
cin.ignore();
std::getline(std::cin,name);
if (list.removePersonFound(name) == true)
{
char validateRemove;
cout << "Scientist found!" << endl;
cout << "Are you sure you want to remove this scientist? (y/n): ";
cin >> validateRemove;
if(validateRemove == 'y' || validateRemove == 'Y')
{
if(list.removePerson(name) == true)
{
cout << "Scientist removed!" << endl;
}
else
{
cout << "Scientist not removed!" << endl;
}
}
else
{
cout << "Scientist not removed!" << endl;
}
}
else
{
cout << "Serson not found!" << endl;
}
}
void ClassUI::save()
{
list.saveFile();
cout << "Database saved." << endl;
}
void ClassUI::yo()
{
cout << "--------------------------------------------------------------" << endl;
cout << endl;
cout << "`8.`8888. ,8' ,o888888o. " << endl;
cout << " `8.`8888. ,8' . 8888 `88. " << endl;
cout << " `8.`8888. ,8' ,8 8888 `8b " << endl;
cout << " `8.`8888.,8' 88 8888 `8b " << endl;
cout << " `8.`88888' 88 8888 88 " << endl;
cout << " `8. 8888 88 8888 88 " << endl;
cout << " `8 8888 88 8888 ,8P " << endl;
cout << " 8 8888 `8 8888 ,8P " << endl;
cout << " 8 8888 ` 8888 ,88' " << endl;
cout << " 8 8888 `8888888P' " << endl;
cout << endl;
}
string ClassUI::getQuotes()
{
string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
"\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
"\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
"\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
"\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
};
int v1 = 0;
srand (time(NULL));
v1 = rand() % 5;
return quotes[v1];
}
void ClassUI::sorting()
{
string sortcho;
cout << "Enter a sort command:" << endl;
cout << "--------------------------------------------------------------" << endl;
cout << " (1) - Sort by alphabetical order." << endl;
cout << " (2) - Sort by chronological order." << endl;
cout << " (3) - Sort by gender." << endl;
cout << " (4) - Sort by age." << endl;
cout << " (5) - Return to main menu." << endl;
cout << "Enter your command (1 - 5): ";
cin >> sortcho;
cout << endl;
if(sortcho == "1")
{
list.sortNames();
viewAll();
}
else if(sortcho == "2")
{
list.sortBirth();
viewAll();
}
else if(sortcho == "3")
{
list.sortGender();
viewAll();
}
else if(sortcho == "4")
{
list.sortAge();
viewAll();
}
else if(sortcho == "5")
{
mainMenu();
}
else
{
cout << "That is not a valid command! Try again." << endl;
sorting();
}
}
void ClassUI::editPerson()
{
string name;
cout << "Enter the full name of the Scientist that you want to edit: ";
cin.ignore();
std::getline(std::cin,name);
if(list.removePersonFound(name))
{
list.removePerson(name);
addPerson();
}
else
{
cout << "Scientist not found!" << endl;
}
}
/*
void ClassUI::clearTheScreen() //A function that we wanted to use but had platform issues following it's use.
{
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
*/
<commit_msg>gender lagað í add person<commit_after>#include "classui.h"
#include "listworker.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <time.h>
#include <stdlib.h>
using namespace std;
ClassUI::ClassUI()
{
}
void ClassUI::mainMenu()
{
if (firstRun == true)
{
cout << "\t" << "Welcome to the Amazing Database! " << endl;
cout << "--------------------------------------------------------------" << endl;
cout << "\t" << " *** Quote of the day ***" << endl;
cout << getQuotes() << endl;
firstRun = false;
}
string choice;
do
{
cout << "--------------------------------------------------------------" << endl;
cout << " (1) - " << "Add a scientist to the database." << endl;
cout << " (2) - " << "Remove a scientist from the database." << endl;
cout << " (3) - " << "View the entire database." << endl;
cout << " (4) - " << "Save the database." << endl;
cout << " (5) - " << "Search the database." << endl;
cout << " (6) - " << "Sort the database." << endl;
cout << " (7) - " << "Edit a scientist." << endl;
cout << " (8) - " << "Exit." << endl;
cout << "Enter your command (1 - 8): ";
cin >> choice;
if (choice != "8")
{
select(choice);
}
else
{
list.saveFile();
runOn = false;
}
}while(runOn == true);
cout << endl;
}
void ClassUI::select(string ch)
{
if(ch == "1")
{
cin.ignore(); // When using editPerson it will ignore the first letter unless this ignore is here rather then in addPerson
addPerson();
}
else if(ch == "2")
{
remove();
}
else if(ch == "3")
{
viewAll();
}
else if(ch == "4")
{
save();
}
else if(ch == "5")
{
searching();
}
else if(ch == "6")
{
sorting();
}
else if(ch == "7")
{
editPerson();
}
else if(ch == "yo")
{
yo();
}
else
{
cout << "Invalid input. Please enter a number between 1 - 7." << endl;
}
}
void ClassUI::view(int i)
{
cout << "--------------------------------------------------------------" << endl;
int nameSize = list.getNameSize(i);
cout << list.getName(i);
if(nameSize > 0 && nameSize <= 7)
{
cout << "\t" << "\t" << "\t" << "\t";
}
else if(nameSize > 7 && nameSize <= 15)
{
cout << "\t" << "\t" << "\t";
}
else if(nameSize > 15 && nameSize <= 23)
{
cout << "\t" << "\t";
}
else if(nameSize > 23 && nameSize <= 31)
{
cout << "\t";
}
if(list.getGender(i) == 'M' || list.getGender(i) == 'm')
{
cout << "|Male" << "\t";
}
else
{
cout << "|Female" << "\t";
}
cout << "|" << list.getBirth(i);
if(list.getDeath(i) == 0)
{
cout << "\t" << "| n/a" << "\t" << "|" << list.getAge(i) << endl;
}
else
{
cout << "\t" << "|" << list.getDeath(i) << "\t" << "|" << list.getAge(i) << endl;
}
cout << list.getComment(i) << endl;
}
void ClassUI::viewAll()
{
cout << "--------------------------------------------------------------" << endl;
cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << "\t" << "|Age" << endl;
for(int i = 0; i < list.personsSize(); i++)
{
view(i);
}
}
void ClassUI::addPerson()
{
string name;
string comment;
char gender;
char yesOrNo;
int yearOfBirth = 0;
int yearOfDeath = 0;
cout << "--------------------------------------------------------------" << endl;
cout << "Enter name of the scientist: ";
std::getline(std::cin,name);
cout << "Enter a gender (M/F): ";
cin >> gender;
if (gender == 'm')
{
gender = 'M';
}
else if (gender == 'f')
{
gender = 'F';
}
if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F')
{
cout << "Enter a year of birth: ";
cin >> yearOfBirth;
if (yearOfBirth < 0 || yearOfBirth > 2016)
{
cout << "not a valid year of birth" << endl;
return mainMenu();
}
cout << "Is the individual deceased? (y/n) ";
cin >> yesOrNo;
if (yesOrNo == 'Y' || yesOrNo == 'y')
{
cout << "Enter a year of death: ";
cin >> yearOfDeath;
if(yearOfBirth > yearOfDeath)
{
cout << "Not a valid year of death" << endl;
return mainMenu();
}
}
cout << "Enter a comment about the scientist: ";
cin.ignore();
std::getline(std::cin,comment);
}
else
{
cout << "Invalid gender! Try again." << endl;
return mainMenu();
}
cout << "Are you sure that you want to add this scientist? (y/n) ";
string validatePerson;
cin >> validatePerson;
if(validatePerson == "y")
{
cout << "New scientist added!" << endl;
list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment);
}
else
{
cout << "scientist not added!" << endl;
}
}
void ClassUI::searching()
{
cout << "-------------Select any of the following commands-------------" << endl;
cout << "What do you want to search for?" << endl;
cout << " (1) - Search by name." << endl;
cout << " (2) - Search by gender." << endl;
cout << " (3) - Search by year of birth." << endl;
cout << " (4) - Search by age." << endl;
cout << " (5) - Return to main menu." << endl;
search();
}
void ClassUI::search()
{
string searchChoice;
cout << "Enter your command (1 - 5): ";
cin >> searchChoice;
cout << endl;
if (searchChoice == "1")
{
string namesearch;
cout << "--------------------------------------------------------------" << endl;
cout << "Enter a name you want to search for: ";
cin.ignore();
std::getline(std::cin,namesearch);
cout << "--------------------------------------------------------------" << endl;
for(int i = 0; i < list.personsSize();++i)
{
std::size_t found = list.getName(i).find(namesearch);
if (found!=std::string::npos)
{
view(i);
}
}
if(list.nameSearcher(namesearch) == false)
{
cout << "Sorry that name is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "2")
{
char gendersearch;
cout << "Enter a gender you want to search for: (M/F)";
cin >> gendersearch;
if(gendersearch == 'm')
{
gendersearch = 'M';
}
else if (gendersearch == 'f')
{
gendersearch = 'F';
}
for(int i = 0; i < list.personsSize();++i)
{
if(gendersearch == list.getGender(i))
{
gendersearch = list.getGender(i);
view(i);
}
}
if(list.genderSearcher(gendersearch) == false)
{
cout << "Sorry that gender is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "3")
{
int yearsearch;
cout << "Enter a year you want to search for: ";
cin >> yearsearch;
for(int i = 0; i < list.personsSize();++i)
{
if(yearsearch == list.getBirth(i))
{
yearsearch = list.getBirth(i);
view(i);
}
}
if(list.yearSearcher(yearsearch) == false)
{
cout << "Sorry that year is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "4")
{
int ageSearch;
cout << "Enter a age you want to search for: ";
cin >> ageSearch;
for(int i = 0; i < list.personsSize();++i)
{
if(ageSearch == list.getAge(i))
{
ageSearch = list.getAge(i);
view(i);
}
}
if(list.ageSearcher(ageSearch) == false)
{
cout << "Sorry that age is not in our database, but you can add a new scientist in the 'Add section' in the main menu." << endl;
searching();
}
}
else if (searchChoice == "5")
{
mainMenu();
}
else
{
cout << "Error reading input. Please enter a number between 1- 3." << endl;
search();
}
}
void ClassUI::remove()
{
string name;
cout << "--------------------------------------------------------------" << endl;
cout << "Enter the full name of the scientist that you want to remove: ";
cin.ignore();
std::getline(std::cin,name);
if (list.removePersonFound(name) == true)
{
char validateRemove;
cout << "Scientist found!" << endl;
cout << "Are you sure you want to remove this scientist? (y/n): ";
cin >> validateRemove;
if(validateRemove == 'y' || validateRemove == 'Y')
{
if(list.removePerson(name) == true)
{
cout << "Scientist removed!" << endl;
}
else
{
cout << "Scientist not removed!" << endl;
}
}
else
{
cout << "Scientist not removed!" << endl;
}
}
else
{
cout << "Serson not found!" << endl;
}
}
void ClassUI::save()
{
list.saveFile();
cout << "Database saved." << endl;
}
void ClassUI::yo()
{
cout << "--------------------------------------------------------------" << endl;
cout << endl;
cout << "`8.`8888. ,8' ,o888888o. " << endl;
cout << " `8.`8888. ,8' . 8888 `88. " << endl;
cout << " `8.`8888. ,8' ,8 8888 `8b " << endl;
cout << " `8.`8888.,8' 88 8888 `8b " << endl;
cout << " `8.`88888' 88 8888 88 " << endl;
cout << " `8. 8888 88 8888 88 " << endl;
cout << " `8 8888 88 8888 ,8P " << endl;
cout << " 8 8888 `8 8888 ,8P " << endl;
cout << " 8 8888 ` 8888 ,88' " << endl;
cout << " 8 8888 `8888888P' " << endl;
cout << endl;
}
string ClassUI::getQuotes()
{
string quotes[5] = {"\"A good programmer is someone who always looks both ways before crossing a one-way street.\" (Doug Linder)",
"\"Programming is like sex. One mistake and you have to support it for the rest of your life.\" (Michael Sinz)",
"\"Walking on water and developing software from a specification are easy if both are frozen.\" (Edward V Berard)",
"\"One man's crappy software is another man's full time job.\" (Jessica Gaston)",
"\"A C program is like a fast dance on a newly waxed dance floor by people carrying razors.\" (Waldi Ravens)"
};
int v1 = 0;
srand (time(NULL));
v1 = rand() % 5;
return quotes[v1];
}
void ClassUI::sorting()
{
string sortcho;
cout << "Enter a sort command:" << endl;
cout << "--------------------------------------------------------------" << endl;
cout << " (1) - Sort by alphabetical order." << endl;
cout << " (2) - Sort by chronological order." << endl;
cout << " (3) - Sort by gender." << endl;
cout << " (4) - Sort by age." << endl;
cout << " (5) - Return to main menu." << endl;
cout << "Enter your command (1 - 5): ";
cin >> sortcho;
cout << endl;
if(sortcho == "1")
{
list.sortNames();
viewAll();
}
else if(sortcho == "2")
{
list.sortBirth();
viewAll();
}
else if(sortcho == "3")
{
list.sortGender();
viewAll();
}
else if(sortcho == "4")
{
list.sortAge();
viewAll();
}
else if(sortcho == "5")
{
mainMenu();
}
else
{
cout << "That is not a valid command! Try again." << endl;
sorting();
}
}
void ClassUI::editPerson()
{
string name;
cout << "Enter the full name of the Scientist that you want to edit: ";
cin.ignore();
std::getline(std::cin,name);
if(list.removePersonFound(name))
{
list.removePerson(name);
addPerson();
}
else
{
cout << "Scientist not found!" << endl;
}
}
/*
void ClassUI::clearTheScreen() //A function that we wanted to use but had platform issues following it's use.
{
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
*/
/*
void ClassUI::editComputer()
{
string cmpname;
cout << "Enter the full name of the computer that you want to edit: ";
cin.ignore();
std::getline(std::cin,cmpname);
if(list.removePersonFound(cmpname))
{
list.removePerson(cmpname);
addPerson();
}
else
{
cout << "Computer not found!" << endl;
}
}
*/
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "sysinv.h"
#include "smbios.h"
LPTSTR CHASSIS_TYPE_STRINGS[] = {
_T("Unknown"), // 0x00 Invalid
_T("Other"), // 0x01
_T("Unknown"), // 0x02
_T("Desktop"), // 0x03
_T("Low Profile Desktop"), // 0x04
_T("Pizza Box"), // 0x05
_T("Mini Tower"), // 0x06
_T("Tower"), // 0x07
_T("Portable"), // 0x08
_T("Laptop"), // 0x09
_T("Notebook"), // 0x0A
_T("Hand Held"), // 0x0B
_T("Docking Station"), // 0x0C
_T("All in One"), // 0x0D
_T("Sub Notebook"), // 0x0E
_T("Space-saving"), // 0x0F
_T("Lunch Box"), // 0x10
_T("Main Server Chassis"), // 0x11
_T("Expansion Chassis"), // 0x12
_T("Sub Chassis"), // 0x13
_T("Bus Expansion Chassis"), // 0x14
_T("Peripheral Chassis"), // 0x15
_T("RAID Chassis"), // 0x16
_T("Rack Mount Chassis"), // 0x17
_T("Sealed-case PC"), // 0x18
_T("Multi-system Chassis"), // 0x19
_T("Compact PCI"), // 0x1A
_T("Advanced TCA") // 0x1B
_T("Blade") // 0x1C
_T("Blade Enclosure") // 0x1D
};
PNODE EnumChassis()
{
PNODE parentNode = node_alloc(_T("Chassis"), 0);
PNODE node = NULL;
PRAW_SMBIOS_DATA smbios = GetSmbiosData();
PSMBIOS_STRUCT_HEADER header = NULL;
PBYTE cursor = NULL;
LPTSTR unicode = NULL;
TCHAR buffer[MAX_PATH + 1];
while (NULL != (header = GetNextStructureOfType(header, SMB_TABLE_CHASSIS))) {
cursor = (PBYTE)header;
// v2.0+
if (2 <= smbios->SMBIOSMajorVersion) {
node = node_append_new(parentNode, _T("Chassis"), 0);
// 0x04 Manufacturer
unicode = GetSmbiosString(header, *(cursor + 0x04));
node_att_set(node, _T("Manufacturer"), unicode, 0);
LocalFree(unicode);
// 0x05 Chassis Type
node_att_set(node, _T("Type"), SAFE_INDEX(CHASSIS_TYPE_STRINGS, *(cursor + 0x05)), 0);
// 0x06 Version String
unicode = GetSmbiosString(header, *(cursor + 0x06));
node_att_set(node, _T("Version"), unicode, 0);
LocalFree(unicode);
// 0x07 Serial Number
unicode = GetSmbiosString(header, *(cursor + 0x06));
node_att_set(node, _T("SerialNumber"), unicode, 0);
LocalFree(unicode);
// 0x08 Asset Tag
unicode = GetSmbiosString(header, *(cursor + 0x08));
node_att_set(node, _T("AssetTag"), unicode, 0);
LocalFree(unicode);
}
}
return parentNode;
}<commit_msg>Improved SMBIOS v2.8 support for Chassis (type 3)<commit_after>#include "stdafx.h"
#include "sysinv.h"
#include "smbios.h"
// 7.4.1 System Enclosure or Chassis Types
LPTSTR CHASSIS_TYPES[] = {
_T("Unknown"), // 0x00 Invalid
_T("Other"), // 0x01
_T("Unknown"), // 0x02
_T("Desktop"), // 0x03
_T("Low Profile Desktop"), // 0x04
_T("Pizza Box"), // 0x05
_T("Mini Tower"), // 0x06
_T("Tower"), // 0x07
_T("Portable"), // 0x08
_T("Laptop"), // 0x09
_T("Notebook"), // 0x0A
_T("Hand Held"), // 0x0B
_T("Docking Station"), // 0x0C
_T("All in One"), // 0x0D
_T("Sub Notebook"), // 0x0E
_T("Space-saving"), // 0x0F
_T("Lunch Box"), // 0x10
_T("Main Server Chassis"), // 0x11
_T("Expansion Chassis"), // 0x12
_T("Sub Chassis"), // 0x13
_T("Bus Expansion Chassis"), // 0x14
_T("Peripheral Chassis"), // 0x15
_T("RAID Chassis"), // 0x16
_T("Rack Mount Chassis"), // 0x17
_T("Sealed-case PC"), // 0x18
_T("Multi-system Chassis"), // 0x19
_T("Compact PCI"), // 0x1A
_T("Advanced TCA") // 0x1B
_T("Blade") // 0x1C
_T("Blade Enclosure") // 0x1D
};
// 7.4.2 System Enclosure or Chassis States
LPCTSTR CHASSIS_STATES[] = {
_T("Unknown"), // 0x00 Invalid
_T("Other"), // 0x01 Other
_T("Unknown"), // 0x02 Unknown
_T("Safe"), // 0x03 Safe
_T("Warning"), // 0x04 Warning
_T("Critical"), // 0x05 Critical
_T("Non-recoverable") // 0x06 Non-recoverable
};
// 7.4.3 System Enclosure or Chassis Security Status
LPCTSTR CHASSIS_SECURITY_STATUS[] = {
_T("Unknown"), // 0x00 Invalid
_T("Other"), // 0x01 Other
_T("Unknown"), // 0x02 Unknown
_T("None"), // 0x03 None
_T("External interface locked out"), // 0x04 External interface locked out
_T("External interface enabled") // 0x05 External interface enabled
};
// 7.4 System Enclosure or Chassis (Type 3)
PNODE EnumChassis()
{
PNODE parentNode = node_alloc(_T("Chassis"), 0);
PNODE node = NULL;
PRAW_SMBIOS_DATA smbios = GetSmbiosData();
PSMBIOS_STRUCT_HEADER header = NULL;
LPTSTR unicode = NULL;
TCHAR buffer[MAX_PATH + 1];
while (NULL != (header = GetNextStructureOfType(header, SMB_TABLE_CHASSIS))) {
// v2.0+
if (2 <= smbios->SMBIOSMajorVersion) {
node = node_append_new(parentNode, _T("Chassis"), 0);
// 0x04 Manufacturer
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x04));
node_att_set(node, _T("Manufacturer"), unicode, 0);
LocalFree(unicode);
// 0x05 Chassis Type
node_att_set(node, _T("Type"), SAFE_INDEX(CHASSIS_TYPES, BYTE_AT_OFFSET(header, 0x05)), 0);
// 0x06 Version String
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x06));
node_att_set(node, _T("Version"), unicode, 0);
LocalFree(unicode);
// 0x07 Serial Number
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x06));
node_att_set(node, _T("SerialNumber"), unicode, 0);
LocalFree(unicode);
// 0x08 Asset Tag
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x08));
node_att_set(node, _T("AssetTag"), unicode, 0);
LocalFree(unicode);
// v2.1+
if (2 < smbios->SMBIOSMajorVersion || (2 == smbios->SMBIOSMajorVersion && 1 <= smbios->SMBIOSMinorVersion)) {
// 0x09 Boot-up state
node_att_set(node, _T("BootupState"), SAFE_INDEX(CHASSIS_STATES, BYTE_AT_OFFSET(header, 0x09)), 0);
// 0x0A Power supply state
node_att_set(node, _T("PowerSupplyState"), SAFE_INDEX(CHASSIS_STATES, BYTE_AT_OFFSET(header, 0x0A)), 0);
// 0x0B Thermal State
node_att_set(node, _T("ThermalState"), SAFE_INDEX(CHASSIS_STATES, BYTE_AT_OFFSET(header, 0x0B)), 0);
// 0x0C Security State
node_att_set(node, _T("SecurityState"), SAFE_INDEX(CHASSIS_SECURITY_STATUS, BYTE_AT_OFFSET(header, 0x0C)), 0);
}
// v2.3+
if (2 < smbios->SMBIOSMajorVersion || (2 == smbios->SMBIOSMajorVersion && 3 <= smbios->SMBIOSMinorVersion)) {
// 0x0D OEM Defined
swprintf(buffer, _T("0x%X"), DWORD_AT_OFFSET(header, 0x0D));
node_att_set(node, _T("OemInfo"), buffer, 0);
// 0x11 Height (U|1.75"|4.445cm)
if (0 != BYTE_AT_OFFSET(header, 0x11)) {
swprintf(buffer, _T("%u"), BYTE_AT_OFFSET(header, 0x11));
node_att_set(node, _T("HeightU"), buffer, 0);
}
// 0x12 Number of power cords
if (0 != BYTE_AT_OFFSET(header, 0x12)) {
swprintf(buffer, _T("%u"), BYTE_AT_OFFSET(header, 0x12));
node_att_set(node, _T("PowerCordCount"), buffer, 0);
}
}
// v2.7+
if (2 < smbios->SMBIOSMajorVersion || (2 == smbios->SMBIOSMajorVersion && 7 <= smbios->SMBIOSMinorVersion)) {
// 0x15 + n*m SKU Number
unicode = GetSmbiosString(header, BYTE_AT_OFFSET(header, 0x15 + BYTE_AT_OFFSET(header, 0x15)));
node_att_set(node, _T("SkuNumber"), unicode, 0);
LocalFree(unicode);
}
}
}
return parentNode;
}<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include <numeric>
#include <vector>
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/compiler/tf2tensorrt/trt_convert_api.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
using tensorflow::Flag;
using tensorflow::Status;
using tensorflow::string;
using tensorflow::Tensor;
#define TFTRT_ENSURE_OK(x) \
do { \
Status s = x; \
if (!s.ok()) { \
std::cerr << __FILE__ << ":" << __LINE__ << " " << s.error_message() \
<< std::endl; \
return 1; \
} \
} while (0)
// Get the name of the GPU.
const string GetDeviceName(std::unique_ptr<tensorflow::Session>& session) {
string device_name = "";
std::vector<tensorflow::DeviceAttributes> devices;
Status status = session->ListDevices(&devices);
if (!status.ok()) {
return device_name;
}
for (const auto& d : devices) {
if (d.device_type() == "GPU" || d.device_type() == "gpu") {
device_name = d.name();
}
}
return device_name;
}
// Move from the host to the device with `device_name`.
Status MoveToDevice(const string& device_name, Tensor& tensor_host,
Tensor* tensor_device) {
// Create identity graph
tensorflow::Scope root = tensorflow::Scope::NewRootScope();
auto x = tensorflow::ops::Placeholder(root, tensor_host.dtype());
auto y = tensorflow::ops::Identity(root, x);
tensorflow::GraphDef graphDef;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graphDef));
// Create session with identity graph
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions()));
TF_RETURN_IF_ERROR(session->Create(graphDef));
// Configure to return output on device
tensorflow::Session::CallableHandle handle;
tensorflow::CallableOptions opts;
opts.add_feed("Placeholder:0");
opts.add_fetch("Identity:0");
opts.mutable_fetch_devices()->insert({"Identity:0", device_name});
opts.set_fetch_skip_sync(true);
TF_RETURN_IF_ERROR(session->MakeCallable(opts, &handle));
// Execute graph
std::vector<Tensor> tensors_device;
Status status =
session->RunCallable(handle, {tensor_host}, &tensors_device, nullptr);
*tensor_device = tensors_device.front();
session->ReleaseCallable(handle);
return status;
}
// Returns info for nodes listed in the signature definition.
std::vector<tensorflow::TensorInfo> GetNodeInfo(
const google::protobuf::Map<string, tensorflow::TensorInfo>& signature) {
std::vector<tensorflow::TensorInfo> info;
for (const auto& item : signature) {
info.push_back(item.second);
}
return info;
}
// Load the `SavedModel` located at `model_dir`.
Status LoadModel(const string& model_dir, const string& signature_key,
tensorflow::SavedModelBundle* bundle,
std::vector<tensorflow::TensorInfo>* input_info,
std::vector<tensorflow::TensorInfo>* output_info) {
tensorflow::RunOptions run_options;
tensorflow::SessionOptions sess_options;
sess_options.config.mutable_gpu_options()->force_gpu_compatible();
TF_RETURN_IF_ERROR(tensorflow::LoadSavedModel(sess_options, run_options,
model_dir, {"serve"}, bundle));
// Get input and output names
auto signature_map = bundle->GetSignatures();
const tensorflow::SignatureDef& signature = signature_map[signature_key];
*input_info = GetNodeInfo(signature.inputs());
*output_info = GetNodeInfo(signature.outputs());
return Status::OK();
}
// Create arbitrary inputs matching `input_info` and load them on the device.
Status SetupInputs(const string& device_name, int32_t batch_size,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<Tensor>* inputs) {
std::vector<Tensor> inputs_device;
for (const auto& info : input_info) {
auto shape = info.tensor_shape();
shape.mutable_dim(0)->set_size(batch_size);
Tensor input_host(info.dtype(), shape);
Tensor input_device;
TF_RETURN_IF_ERROR(MoveToDevice(device_name, input_host, &input_device));
inputs_device.push_back(input_device);
}
*inputs = inputs_device;
return Status::OK();
}
// Configure a `CallableHandle` that feeds from and fetches to a device.
Status SetupCallable(std::unique_ptr<tensorflow::Session>& session,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<tensorflow::TensorInfo>& output_info,
const string& device_name,
tensorflow::Session::CallableHandle* handle) {
tensorflow::CallableOptions opts;
for (const auto& info : input_info) {
const string& name = info.name();
opts.add_feed(name);
opts.mutable_feed_devices()->insert({name, device_name});
}
for (const auto& info : output_info) {
const string& name = info.name();
opts.add_fetch(name);
opts.mutable_fetch_devices()->insert({name, device_name});
}
opts.set_fetch_skip_sync(true);
return session->MakeCallable(opts, handle);
}
int main(int argc, char* argv[]) {
// Parse arguments
string model_path = "/path/to/model/";
string signature_key = "serving_default";
int32_t batch_size = 64;
int32_t warmup_iters = 50;
int32_t eval_iters = 1000;
std::vector<Flag> flag_list = {
Flag("model_path", &model_path, "graph to be executed"),
Flag("signature_key", &signature_key, "the serving signature to use"),
Flag("batch_size", &batch_size, "batch size to use for inference"),
Flag("warmup_iters", &warmup_iters, "number of warmup iterations to run"),
Flag("eval_iters", &eval_iters, "number of timed iterations to run"),
};
string usage = tensorflow::Flags::Usage(argv[0], flag_list);
const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
// We need to call this to set up global state for TensorFlow.
tensorflow::port::InitMain(argv[0], &argc, &argv);
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
return -1;
}
// Setup session
tensorflow::SavedModelBundle bundle;
std::vector<tensorflow::TensorInfo> input_info;
std::vector<tensorflow::TensorInfo> output_info;
TFTRT_ENSURE_OK(
LoadModel(model_path, signature_key, &bundle, &input_info, &output_info));
// Create inputs and move to device
const string device_name = GetDeviceName(bundle.session);
std::vector<Tensor> inputs_device;
TFTRT_ENSURE_OK(
SetupInputs(device_name, batch_size, input_info, &inputs_device));
// Configure to feed and fetch from device
tensorflow::Session::CallableHandle handle;
TFTRT_ENSURE_OK(SetupCallable(bundle.session, input_info, output_info,
device_name, &handle));
// Run benchmarking
std::vector<Tensor> outputs;
std::vector<double> infer_time;
std::chrono::steady_clock::time_point eval_start_time;
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point end_time;
for (int i = 0; i < warmup_iters + eval_iters; i++) {
if (i == warmup_iters) {
LOG(INFO) << "Warmup done";
eval_start_time = std::chrono::steady_clock::now();
}
start_time = std::chrono::steady_clock::now();
Status status =
bundle.session->RunCallable(handle, inputs_device, &outputs, nullptr);
end_time = std::chrono::steady_clock::now();
TFTRT_ENSURE_OK(status);
double duration = (end_time - start_time).count() / 1e6;
infer_time.push_back(duration);
}
TFTRT_ENSURE_OK(bundle.session->ReleaseCallable(handle));
// Print results
std::sort(infer_time.begin() + warmup_iters, infer_time.end());
double total_compute_time =
std::accumulate(infer_time.begin() + warmup_iters, infer_time.end(), 0.0);
double total_wall_time = (end_time - eval_start_time).count() / 1e6;
int32_t m = warmup_iters + eval_iters / 2;
LOG(INFO) << "Total wall time (s): " << total_wall_time / 1e3;
LOG(INFO) << "Total GPU compute time (s): " << total_compute_time / 1e3;
LOG(INFO) << "Mean GPU compute time (ms): " << total_compute_time / eval_iters;
LOG(INFO) << "Median GPU compute time (ms): " << (eval_iters % 2 ? infer_time[m]
: (infer_time[m - 1] + infer_time[m]) / 2);
// Note: Throughput using GPU inference time, rather than wall time
LOG(INFO) << "Throughput (samples/s): " << 1e3 * eval_iters * batch_size / total_compute_time;
LOG(INFO) << "First inference latency (ms): " << infer_time.front();
return 0;
}<commit_msg>Add TODOs for remaining requested changes<commit_after>#include <chrono>
#include <iostream>
#include <numeric>
#include <vector>
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/saved_model/loader.h"
#include "tensorflow/compiler/tf2tensorrt/trt_convert_api.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
using tensorflow::Flag;
using tensorflow::Status;
using tensorflow::string;
using tensorflow::Tensor;
#define TFTRT_ENSURE_OK(x) \
do { \
Status s = x; \
if (!s.ok()) { \
std::cerr << __FILE__ << ":" << __LINE__ << " " << s.error_message() \
<< std::endl; \
return 1; \
} \
} while (0)
// Get the name of the GPU.
const string GetDeviceName(std::unique_ptr<tensorflow::Session>& session) {
string device_name = "";
std::vector<tensorflow::DeviceAttributes> devices;
Status status = session->ListDevices(&devices);
if (!status.ok()) {
return device_name;
}
for (const auto& d : devices) {
if (d.device_type() == "GPU" || d.device_type() == "gpu") {
device_name = d.name();
}
}
return device_name;
}
// Move from the host to the device with `device_name`.
Status MoveToDevice(const string& device_name, Tensor& tensor_host,
Tensor* tensor_device) {
// Create identity graph
tensorflow::Scope root = tensorflow::Scope::NewRootScope();
auto x = tensorflow::ops::Placeholder(root, tensor_host.dtype());
auto y = tensorflow::ops::Identity(root, x);
tensorflow::GraphDef graphDef;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graphDef));
// Create session with identity graph
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions()));
TF_RETURN_IF_ERROR(session->Create(graphDef));
// Configure to return output on device
tensorflow::Session::CallableHandle handle;
tensorflow::CallableOptions opts;
opts.add_feed("Placeholder:0");
opts.add_fetch("Identity:0");
opts.mutable_fetch_devices()->insert({"Identity:0", device_name});
opts.set_fetch_skip_sync(true);
TF_RETURN_IF_ERROR(session->MakeCallable(opts, &handle));
// Execute graph
std::vector<Tensor> tensors_device;
Status status =
session->RunCallable(handle, {tensor_host}, &tensors_device, nullptr);
*tensor_device = tensors_device.front();
session->ReleaseCallable(handle);
return status;
}
// Returns info for nodes listed in the signature definition.
std::vector<tensorflow::TensorInfo> GetNodeInfo(
const google::protobuf::Map<string, tensorflow::TensorInfo>& signature) {
std::vector<tensorflow::TensorInfo> info;
for (const auto& item : signature) {
info.push_back(item.second);
}
return info;
}
// Load the `SavedModel` located at `model_dir`.
Status LoadModel(const string& model_dir, const string& signature_key,
tensorflow::SavedModelBundle* bundle,
std::vector<tensorflow::TensorInfo>* input_info,
std::vector<tensorflow::TensorInfo>* output_info) {
tensorflow::RunOptions run_options;
tensorflow::SessionOptions sess_options;
sess_options.config.mutable_gpu_options()->force_gpu_compatible();
TF_RETURN_IF_ERROR(tensorflow::LoadSavedModel(sess_options, run_options,
model_dir, {"serve"}, bundle));
// Get input and output names
auto signature_map = bundle->GetSignatures();
const tensorflow::SignatureDef& signature = signature_map[signature_key];
*input_info = GetNodeInfo(signature.inputs());
*output_info = GetNodeInfo(signature.outputs());
return Status::OK();
}
// Create arbitrary inputs matching `input_info` and load them on the device.
Status SetupInputs(const string& device_name, int32_t batch_size,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<Tensor>* inputs) {
std::vector<Tensor> inputs_device;
for (const auto& info : input_info) {
auto shape = info.tensor_shape();
shape.mutable_dim(0)->set_size(batch_size);
Tensor input_host(info.dtype(), shape);
Tensor input_device;
TF_RETURN_IF_ERROR(MoveToDevice(device_name, input_host, &input_device));
inputs_device.push_back(input_device);
}
*inputs = inputs_device;
return Status::OK();
}
// Configure a `CallableHandle` that feeds from and fetches to a device.
Status SetupCallable(std::unique_ptr<tensorflow::Session>& session,
std::vector<tensorflow::TensorInfo>& input_info,
std::vector<tensorflow::TensorInfo>& output_info,
const string& device_name,
tensorflow::Session::CallableHandle* handle) {
tensorflow::CallableOptions opts;
for (const auto& info : input_info) {
const string& name = info.name();
opts.add_feed(name);
opts.mutable_feed_devices()->insert({name, device_name});
}
for (const auto& info : output_info) {
const string& name = info.name();
opts.add_fetch(name);
opts.mutable_fetch_devices()->insert({name, device_name});
}
opts.set_fetch_skip_sync(true);
return session->MakeCallable(opts, handle);
}
int main(int argc, char* argv[]) {
// Parse arguments
string model_path = "/path/to/model/";
string signature_key = "serving_default";
int32_t batch_size = 64;
int32_t warmup_iters = 50;
int32_t eval_iters = 1000;
std::vector<Flag> flag_list = {
Flag("model_path", &model_path, "graph to be executed"),
Flag("signature_key", &signature_key, "the serving signature to use"),
Flag("batch_size", &batch_size, "batch size to use for inference"),
Flag("warmup_iters", &warmup_iters, "number of warmup iterations to run"),
Flag("eval_iters", &eval_iters, "number of timed iterations to run"),
};
string usage = tensorflow::Flags::Usage(argv[0], flag_list);
const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
// We need to call this to set up global state for TensorFlow.
tensorflow::port::InitMain(argv[0], &argc, &argv);
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
return -1;
}
// Setup session
tensorflow::SavedModelBundle bundle;
std::vector<tensorflow::TensorInfo> input_info;
std::vector<tensorflow::TensorInfo> output_info;
TFTRT_ENSURE_OK(
LoadModel(model_path, signature_key, &bundle, &input_info, &output_info));
// TODO: Convert model w/ TRT and add flag for this behavior
// Create inputs and move to device
// TODO: Measure H2D times over repeated calls and report metrics
const string device_name = GetDeviceName(bundle.session);
std::vector<Tensor> inputs_device;
TFTRT_ENSURE_OK(
SetupInputs(device_name, batch_size, input_info, &inputs_device));
// Configure to feed and fetch from device
tensorflow::Session::CallableHandle handle;
TFTRT_ENSURE_OK(SetupCallable(bundle.session, input_info, output_info,
device_name, &handle));
// Run benchmarking
std::vector<Tensor> outputs;
std::vector<double> infer_time;
std::chrono::steady_clock::time_point eval_start_time;
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point end_time;
for (int i = 0; i < warmup_iters + eval_iters; i++) {
if (i == warmup_iters) {
LOG(INFO) << "Warmup done";
eval_start_time = std::chrono::steady_clock::now();
}
start_time = std::chrono::steady_clock::now();
Status status =
bundle.session->RunCallable(handle, inputs_device, &outputs, nullptr);
end_time = std::chrono::steady_clock::now();
TFTRT_ENSURE_OK(status);
double duration = (end_time - start_time).count() / 1e6;
infer_time.push_back(duration);
}
TFTRT_ENSURE_OK(bundle.session->ReleaseCallable(handle));
// Print results
std::sort(infer_time.begin() + warmup_iters, infer_time.end());
double total_compute_time =
std::accumulate(infer_time.begin() + warmup_iters, infer_time.end(), 0.0);
double total_wall_time = (end_time - eval_start_time).count() / 1e6;
int32_t m = warmup_iters + eval_iters / 2;
LOG(INFO) << "Total wall time (s): " << total_wall_time / 1e3;
LOG(INFO) << "Total GPU compute time (s): " << total_compute_time / 1e3;
LOG(INFO) << "Mean GPU compute time (ms): " << total_compute_time / eval_iters;
LOG(INFO) << "Median GPU compute time (ms): " << (eval_iters % 2 ? infer_time[m]
: (infer_time[m - 1] + infer_time[m]) / 2);
// Note: Throughput using GPU inference time, rather than wall time
LOG(INFO) << "Throughput (samples/s): " << 1e3 * eval_iters * batch_size / total_compute_time;
LOG(INFO) << "First inference latency (ms): " << infer_time.front();
return 0;
}<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/////////////////////////////////////////////////////////////////////////
// //
// Class for ITS RecPoint reconstruction //
// //
////////////////////////////////////////////////////////////////////////
#include <TString.h>
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliITSDetTypeRec.h"
#include "AliITSLoader.h"
#include "AliITSreconstruction.h"
#include "AliITSgeom.h"
ClassImp(AliITSreconstruction)
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction():
fInit(kFALSE),
fEnt(0),
fEnt0(0),
fDetTypeRec(0x0),
fDfArp(kFALSE),
fITSgeom(0x0),
fLoader(0x0),
fRunLoader(0x0)
{
// Default constructor.
// Inputs:
// none.
// Outputs:
// none.
// Return:
// A zero-ed constructed AliITSreconstruction class.
fDet[0] = fDet[1] = fDet[2] = kTRUE;
}
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction(AliRunLoader *rl):
fInit(kFALSE),
fEnt(0),
fEnt0(0),
fDetTypeRec(0x0),
fDfArp(kFALSE),
fITSgeom(0x0),
fLoader(0x0),
fRunLoader(rl)
{
fDet[0] = fDet[1] = fDet[2] = kTRUE;
}
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction(const char* filename):
fInit(kFALSE),
fEnt(0),
fEnt0(0),
fDetTypeRec(0x0),
fDfArp(kFALSE),
fITSgeom(0x0),
fLoader(0x0),
fRunLoader(0x0)
{
// Standard constructor.
// Inputs:
// const char* filename filename containing the digits to be
// reconstructed. If filename = 0 (nil)
// then no file is opened but a file is
// assumed to already be opened. This
// already opened file will be used.
// Outputs:
// none.
// Return:
// A standardly constructed AliITSreconstruction class.
fDet[0] = fDet[1] = fDet[2] = kTRUE;
fRunLoader = AliRunLoader::Open(filename);
if (fRunLoader == 0x0)
{
Error("AliITSreconstruction","Can not load the session",filename);
return;
}
}
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction(const AliITSreconstruction &rec):TTask(rec),
fInit(rec.fInit),
fEnt(rec.fEnt),
fEnt0(rec.fEnt0),
fDetTypeRec(rec.fDetTypeRec),
fDfArp(rec.fDfArp),
fITSgeom(rec.fITSgeom),
fLoader(rec.fLoader),
fRunLoader(rec.fRunLoader)
{
// Copy constructor.
}
//______________________________________________________________________
AliITSreconstruction& AliITSreconstruction::operator=(const AliITSreconstruction& source){
// Assignment operator.
this->~AliITSreconstruction();
new(this) AliITSreconstruction(source);
return *this;
}
//______________________________________________________________________
AliITSreconstruction::~AliITSreconstruction(){
// A destroyed AliITSreconstruction class.
//fITS = 0;
delete fRunLoader;
}
//______________________________________________________________________
Bool_t AliITSreconstruction::Init(){
// Class Initilizer.
// Inputs:
// none.
// Outputs:
// none.
// Return:
// kTRUE if no errors initilizing this class occurse else kFALSE
Info("Init","");
if (fRunLoader == 0x0)
{
Error("Init","Run Loader is NULL");
return kFALSE;
}
// fRunLoader->LoadgAlice();
// fRunLoader->LoadHeader();
fLoader = (AliITSLoader*) fRunLoader->GetLoader("ITSLoader");
if(!fLoader) {
Error("Init","ITS loader not found");
fInit = kFALSE;
}
// Now ready to init.
//fRunLoader->CdGAFile();
fITSgeom = fLoader->GetITSgeom();
fDetTypeRec = new AliITSDetTypeRec();
fDetTypeRec->SetITSgeom(fITSgeom);
fDetTypeRec->SetDefaults();
fDet[0] = fDet[1] = fDet[2] = kTRUE;
fEnt0 = 0;
//fEnt = gAlice->GetEventsPerRun();
fEnt = Int_t(fRunLoader->GetNumberOfEvents());
fLoader->LoadDigits("read");
fLoader->LoadRecPoints("recreate");
if (fLoader->TreeR() == 0x0) fLoader->MakeTree("R");
fDetTypeRec->SetTreeAddressD(fLoader->TreeD());
fDetTypeRec->MakeBranchR(fLoader->TreeR());
fDetTypeRec->SetTreeAddressR(fLoader->TreeR());
fInit = InitRec();
Info("Init"," Done\n\n\n");
return fInit;
}
//______________________________________________________________________
Bool_t AliITSreconstruction::InitRec(){
// Sets up Reconstruction part of AliITSDetType..
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
fDetTypeRec->SetDefaultClusterFindersV2();
Info("InitRec"," Done\n");
return kTRUE;
}
//______________________________________________________________________
void AliITSreconstruction::Exec(const Option_t *opt){
// Main reconstruction function.
// Inputs:
// Option_t * opt list of subdetector to digitize. =0 all.
// Outputs:
// none.
// Return:
// none.
Option_t *lopt;
Int_t evnt;
if(strstr(opt,"All")||strstr(opt,"ALL")||strstr(opt,"ITS")||opt==0){
fDet[0] = fDet[1] = fDet[2] = kTRUE;
lopt = "All";
}else{
fDet[0] = fDet[1] = fDet[2] = kFALSE;
if(strstr(opt,"SPD")) fDet[kSPD] = kTRUE;
if(strstr(opt,"SDD")) fDet[kSDD] = kTRUE;
if(strstr(opt,"SSD")) fDet[kSSD] = kTRUE;
if(fDet[kSPD] && fDet[kSDD] && fDet[kSSD]) lopt = "All";
else lopt = opt;
} // end if strstr(opt,...)
if(!fInit){
cout << "Initilization Failed, Can't run Exec." << endl;
return;
} // end if !fInit
for(evnt=0;evnt<fEnt;evnt++)
{
Info("Exec","");
Info("Exec","Processing Event %d",evnt);
Info("Exec","");
fRunLoader->GetEvent(evnt);
if (fLoader->TreeR() == 0x0) fLoader->MakeTree("R");
fDetTypeRec->MakeBranchR(0);
fDetTypeRec->SetTreeAddressR(fLoader->TreeR());
fDetTypeRec->SetTreeAddressD(fLoader->TreeD());
fDetTypeRec->DigitsToRecPoints(fLoader->TreeD(),fLoader->TreeR(),0,lopt);
} // end for evnt
}
//______________________________________________________________________
void AliITSreconstruction::SetOutputFile(TString filename){
// Set a new file name for recpoints.
// It must be called before Init()
if(!fLoader)fLoader = (AliITSLoader*) fRunLoader->GetLoader("ITSLoader");
if(fLoader){
Info("SetOutputFile","name for rec points is %s",filename.Data());
fLoader->SetRecPointsFileName(filename);
}
else {
Error("SetOutputFile",
"ITS loader not available. Not possible to set name: %s",filename.Data());
}
}
<commit_msg>Do not get main runloader from gAlice<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/////////////////////////////////////////////////////////////////////////
// //
// Class for ITS RecPoint reconstruction //
// //
////////////////////////////////////////////////////////////////////////
#include <TString.h>
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliITSDetTypeRec.h"
#include "AliITSLoader.h"
#include "AliITSreconstruction.h"
#include "AliITSgeom.h"
ClassImp(AliITSreconstruction)
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction():
fInit(kFALSE),
fEnt(0),
fEnt0(0),
fDetTypeRec(0x0),
fDfArp(kFALSE),
fITSgeom(0x0),
fLoader(0x0),
fRunLoader(0x0)
{
// Default constructor.
// Inputs:
// none.
// Outputs:
// none.
// Return:
// A zero-ed constructed AliITSreconstruction class.
fDet[0] = fDet[1] = fDet[2] = kTRUE;
}
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction(AliRunLoader *rl):
fInit(kFALSE),
fEnt(0),
fEnt0(0),
fDetTypeRec(0x0),
fDfArp(kFALSE),
fITSgeom(0x0),
fLoader(0x0),
fRunLoader(rl)
{
fDet[0] = fDet[1] = fDet[2] = kTRUE;
}
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction(const char* filename):
fInit(kFALSE),
fEnt(0),
fEnt0(0),
fDetTypeRec(0x0),
fDfArp(kFALSE),
fITSgeom(0x0),
fLoader(0x0),
fRunLoader(0x0)
{
// Standard constructor.
// Inputs:
// const char* filename filename containing the digits to be
// reconstructed. If filename = 0 (nil)
// then no file is opened but a file is
// assumed to already be opened. This
// already opened file will be used.
// Outputs:
// none.
// Return:
// A standardly constructed AliITSreconstruction class.
fDet[0] = fDet[1] = fDet[2] = kTRUE;
fRunLoader = AliRunLoader::Open(filename);
if (fRunLoader == 0x0)
{
Error("AliITSreconstruction","Can not load the session",filename);
return;
}
}
//______________________________________________________________________
AliITSreconstruction::AliITSreconstruction(const AliITSreconstruction &rec):TTask(rec),
fInit(rec.fInit),
fEnt(rec.fEnt),
fEnt0(rec.fEnt0),
fDetTypeRec(rec.fDetTypeRec),
fDfArp(rec.fDfArp),
fITSgeom(rec.fITSgeom),
fLoader(rec.fLoader),
fRunLoader(rec.fRunLoader)
{
// Copy constructor.
}
//______________________________________________________________________
AliITSreconstruction& AliITSreconstruction::operator=(const AliITSreconstruction& source){
// Assignment operator.
this->~AliITSreconstruction();
new(this) AliITSreconstruction(source);
return *this;
}
//______________________________________________________________________
AliITSreconstruction::~AliITSreconstruction(){
// A destroyed AliITSreconstruction class.
//fITS = 0;
delete fRunLoader;
}
//______________________________________________________________________
Bool_t AliITSreconstruction::Init(){
// Class Initilizer.
// Inputs:
// none.
// Outputs:
// none.
// Return:
// kTRUE if no errors initilizing this class occurse else kFALSE
Info("Init","");
if (fRunLoader == 0x0)
{
Error("Init","Run Loader is NULL");
return kFALSE;
}
// fRunLoader->LoadgAlice();
// fRunLoader->LoadHeader();
fLoader = (AliITSLoader*) fRunLoader->GetLoader("ITSLoader");
if(!fLoader) {
Error("Init","ITS loader not found");
fInit = kFALSE;
}
// Now ready to init.
//fRunLoader->CdGAFile();
fITSgeom = fLoader->GetITSgeom();
fDetTypeRec = new AliITSDetTypeRec();
fDetTypeRec->SetITSgeom(fITSgeom);
fDetTypeRec->SetDefaults();
fDet[0] = fDet[1] = fDet[2] = kTRUE;
fEnt0 = 0;
fEnt = Int_t(fRunLoader->GetNumberOfEvents());
fLoader->LoadDigits("read");
fLoader->LoadRecPoints("recreate");
if (fLoader->TreeR() == 0x0) fLoader->MakeTree("R");
fDetTypeRec->SetTreeAddressD(fLoader->TreeD());
fDetTypeRec->MakeBranchR(fLoader->TreeR());
fDetTypeRec->SetTreeAddressR(fLoader->TreeR());
fInit = InitRec();
Info("Init"," Done\n\n\n");
return fInit;
}
//______________________________________________________________________
Bool_t AliITSreconstruction::InitRec(){
// Sets up Reconstruction part of AliITSDetType..
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
fDetTypeRec->SetDefaultClusterFindersV2();
Info("InitRec"," Done\n");
return kTRUE;
}
//______________________________________________________________________
void AliITSreconstruction::Exec(const Option_t *opt){
// Main reconstruction function.
// Inputs:
// Option_t * opt list of subdetector to digitize. =0 all.
// Outputs:
// none.
// Return:
// none.
Option_t *lopt;
Int_t evnt;
if(strstr(opt,"All")||strstr(opt,"ALL")||strstr(opt,"ITS")||opt==0){
fDet[0] = fDet[1] = fDet[2] = kTRUE;
lopt = "All";
}else{
fDet[0] = fDet[1] = fDet[2] = kFALSE;
if(strstr(opt,"SPD")) fDet[kSPD] = kTRUE;
if(strstr(opt,"SDD")) fDet[kSDD] = kTRUE;
if(strstr(opt,"SSD")) fDet[kSSD] = kTRUE;
if(fDet[kSPD] && fDet[kSDD] && fDet[kSSD]) lopt = "All";
else lopt = opt;
} // end if strstr(opt,...)
if(!fInit){
cout << "Initilization Failed, Can't run Exec." << endl;
return;
} // end if !fInit
for(evnt=0;evnt<fEnt;evnt++)
{
Info("Exec","");
Info("Exec","Processing Event %d",evnt);
Info("Exec","");
fRunLoader->GetEvent(evnt);
if (fLoader->TreeR() == 0x0) fLoader->MakeTree("R");
fDetTypeRec->MakeBranchR(0);
fDetTypeRec->SetTreeAddressR(fLoader->TreeR());
fDetTypeRec->SetTreeAddressD(fLoader->TreeD());
fDetTypeRec->DigitsToRecPoints(fLoader->TreeD(),fLoader->TreeR(),0,lopt);
} // end for evnt
}
//______________________________________________________________________
void AliITSreconstruction::SetOutputFile(TString filename){
// Set a new file name for recpoints.
// It must be called before Init()
if(!fLoader)fLoader = (AliITSLoader*) fRunLoader->GetLoader("ITSLoader");
if(fLoader){
Info("SetOutputFile","name for rec points is %s",filename.Data());
fLoader->SetRecPointsFileName(filename);
}
else {
Error("SetOutputFile",
"ITS loader not available. Not possible to set name: %s",filename.Data());
}
}
<|endoftext|> |
<commit_before>#include "GameManager.h"
USING_NS_CC;
Scene *GameManager::createScene() {
auto scene = Scene::create();
auto layer = GameManager::create();
scene->addChild(layer);
return scene;
}
bool GameManager::init() {
if (!Layer::init()) {
return false;
}
loadCards();
arrangeCards();
// Touchアクションのイベントリスナー
auto listener = EventListenerTouchOneByOne::create();
// タッチ開始時の処理
listener->onTouchBegan = [this](Touch *touch, Event *event) {
CCLOG("TouchBegan");
auto loc = touch->getLocation();
switch (gameState) {
// 1枚目のカードを選択
case GameState::OpenFirstCard:
for (int i = 0; i < cards.size(); i++) {
// カードがクローズしているかつタッチポイントがカード内に存在する場合
if (!cards.at(i)->isOpen() && cards.at(i)->inside(loc)) {
cards.at(i)->open();
selectedFirstCardIndex = i;
gameState = GameState::OpenSecondCard;
break;
};
}
break;
// 2枚目のカードを選択
case GameState::OpenSecondCard:
for (int i = 0; i < cards.size(); i++) {
// カードがクローズしているかつタッチポイントがカード内に存在する場合
if (!cards.at(i)->isOpen() && cards.at(i)->inside(loc)) {
cards.at(i)->open();
selectedSecondCardIndex = i;
gameState = GameState::CheckPair;
break;
};
}
break;
// カードのペアチェック
case GameState::CheckPair:
if (cards.at(selectedFirstCardIndex)->getCardNumber() == cards.at(selectedSecondCardIndex)->getCardNumber()) {
cards.at(selectedFirstCardIndex)->invisible();
cards.at(selectedSecondCardIndex)->invisible();
// 残りのペア数を減らす
remainingNumberOfPairs--;
}
// ペアが成立しなかった場合
else {
cards.at(selectedFirstCardIndex)->close();
cards.at(selectedSecondCardIndex)->close();
}
// 残りのペアが無くなった場合、ゲームをリセットする
if (remainingNumberOfPairs == 0) {
gameState = GameState::ResetGame;
}
else {
gameState = GameState::OpenFirstCard;
}
break;
// ゲームをリセットする
case GameState::ResetGame:
remainingNumberOfPairs = MAX_CARD_NUMBER;
// カードの状態をリセットする
for (auto& card : cards) {
card->visible();
card->close();
}
// カードの再配置
arrangeCards();
// 新しいゲームを開始する
gameState = GameState::OpenFirstCard;
break;
}
return true;
};
// タッチイベントの登録
Director::getInstance()
->getEventDispatcher()
->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
// カードをロードする関数
void GameManager::loadCards() {
for (int i = 1; i <= MAX_CARD_NUMBER; i++) {
// ハート柄のカードをロードする
auto heart =
Card::create(i, StringUtils::format("h%d.png", i), "back_red.png");
heart->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
addChild(heart);
// 動的配列へ追加
cards.pushBack(heart);
// ダイヤ柄のカードをロードする
auto diamond =
Card::create(i, StringUtils::format("d%d.png", i), "back_red.png");
diamond->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
addChild(diamond);
// 動的配列へ追加
cards.pushBack(diamond);
}
}
// カードを配置する関数
void GameManager::arrangeCards() {
const Size windowSize = Director::getInstance()->getWinSize();
const Size cardSize = cards.back()->getCardSize(); // カードサイズは全て同じ
const Size margin((windowSize.width - cardSize.width * MAX_CARD_ROWS) / (MAX_CARD_ROWS + 1),
(windowSize.height - cardSize.height * MAX_CARD_COLS) / (MAX_CARD_COLS + 1));
int row = 0;
int col = 0;
for (auto &card : cards) {
card->setPosition((cardSize.width + margin.width) * row + margin.width,
(cardSize.height + margin.height) * col + margin.height);
row++;
if (row % MAX_CARD_ROWS == 0) {
row = 0;
col++;
}
}
}<commit_msg>簡易版カードシャッフル機能の追加<commit_after>#include "GameManager.h"
USING_NS_CC;
Scene *GameManager::createScene() {
auto scene = Scene::create();
auto layer = GameManager::create();
scene->addChild(layer);
return scene;
}
bool GameManager::init() {
if (!Layer::init()) {
return false;
}
loadCards();
arrangeCards();
// Touchアクションのイベントリスナー
auto listener = EventListenerTouchOneByOne::create();
// タッチ開始時の処理
listener->onTouchBegan = [this](Touch *touch, Event *event) {
CCLOG("TouchBegan");
auto loc = touch->getLocation();
switch (gameState) {
// 1枚目のカードを選択
case GameState::OpenFirstCard:
for (int i = 0; i < cards.size(); i++) {
// カードがクローズしているかつタッチポイントがカード内に存在する場合
if (!cards.at(i)->isOpen() && cards.at(i)->inside(loc)) {
cards.at(i)->open();
selectedFirstCardIndex = i;
gameState = GameState::OpenSecondCard;
break;
};
}
break;
// 2枚目のカードを選択
case GameState::OpenSecondCard:
for (int i = 0; i < cards.size(); i++) {
// カードがクローズしているかつタッチポイントがカード内に存在する場合
if (!cards.at(i)->isOpen() && cards.at(i)->inside(loc)) {
cards.at(i)->open();
selectedSecondCardIndex = i;
gameState = GameState::CheckPair;
break;
};
}
break;
// カードのペアチェック
case GameState::CheckPair:
if (cards.at(selectedFirstCardIndex)->getCardNumber() == cards.at(selectedSecondCardIndex)->getCardNumber()) {
cards.at(selectedFirstCardIndex)->invisible();
cards.at(selectedSecondCardIndex)->invisible();
// 残りのペア数を減らす
remainingNumberOfPairs--;
}
// ペアが成立しなかった場合
else {
cards.at(selectedFirstCardIndex)->close();
cards.at(selectedSecondCardIndex)->close();
}
// 残りのペアが無くなった場合、ゲームをリセットする
if (remainingNumberOfPairs == 0) {
gameState = GameState::ResetGame;
}
else {
gameState = GameState::OpenFirstCard;
}
break;
// ゲームをリセットする
case GameState::ResetGame:
remainingNumberOfPairs = MAX_CARD_NUMBER;
// カードの状態をリセットする
for (auto& card : cards) {
card->visible();
card->close();
}
// カードの再配置
arrangeCards();
// 新しいゲームを開始する
gameState = GameState::OpenFirstCard;
break;
}
return true;
};
// タッチイベントの登録
Director::getInstance()
->getEventDispatcher()
->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
// カードをロードする関数
void GameManager::loadCards() {
for (int i = 1; i <= MAX_CARD_NUMBER; i++) {
// ハート柄のカードをロードする
auto heart =
Card::create(i, StringUtils::format("h%d.png", i), "back_red.png");
heart->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
addChild(heart);
// 動的配列へ追加
cards.pushBack(heart);
// ダイヤ柄のカードをロードする
auto diamond =
Card::create(i, StringUtils::format("d%d.png", i), "back_red.png");
diamond->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
addChild(diamond);
// 動的配列へ追加
cards.pushBack(diamond);
}
}
// カードを配置する関数
void GameManager::arrangeCards() {
// カードのシャッフル(簡易版)
std::shuffle(cards.begin(), cards.end(), std::mt19937());
const Size windowSize = Director::getInstance()->getWinSize();
const Size cardSize = cards.back()->getCardSize(); // カードサイズは全て同じ
const Size margin((windowSize.width - cardSize.width * MAX_CARD_ROWS) / (MAX_CARD_ROWS + 1),
(windowSize.height - cardSize.height * MAX_CARD_COLS) / (MAX_CARD_COLS + 1));
int row = 0;
int col = 0;
for (auto &card : cards) {
card->setPosition((cardSize.width + margin.width) * row + margin.width,
(cardSize.height + margin.height) * col + margin.height);
row++;
if (row % MAX_CARD_ROWS == 0) {
row = 0;
col++;
}
}
}<|endoftext|> |
<commit_before>/*****************************************************************************
* CameraCalibration.cpp
*
* Set white balance for given lighting, write parameters to file
* https://web.stanford.edu/~sujason/ColorBalancing/robustawb.html
******************************************************************************/
#include "CameraCalibration.h"
using namespace cv;
using namespace std;
////////////////
// Parameters //
////////////////
#define EXPOSURE 200
#define ISO_VALUE 1
// Image Size
//#define FRAME_WIDTH 3280 // 8 megapixels
//#define FRAME_HEIGHT 2464 // 8 megapixels
#define FRAME_WIDTH 1280 // 720 HD
#define FRAME_HEIGHT 720 // 720 HD
// Balancing Region
#define BALANCE_WIDTH 0.2
#define BALANCE_HEIGHT 0.2
//////////////////////
// Global Variables //
//////////////////////
// Global Variables
string sourcewindow = "Current Image";
VideoCapture cap;
int redbalance = 1600;
int bluebalance = 1600;
int exposure = 5;
Mat bgrframe, yuvframe;
// V4L2 Global Device Object
V4L2Control picamctrl;
////////////////////////
// Callback Functions //
////////////////////////
/*******************************************************************************
* void mouseCallback(int event, int x, int y, int flags, void* userdata)
*
* Write HSV and RGB values of point clicked on to terminal
* Any mouse movement will call this function
******************************************************************************/
void mouseCallback(int event, int x, int y, int flags, void* userdata)
{
if ( event == EVENT_LBUTTONDOWN ) // Only run when left button is pressed
{
Vec3b bgr = bgrframe.at<Vec3b>(y, x);
int b = bgr.val[0];
int g = bgr.val[1];
int r = bgr.val[2];
// print out RGB values (sanity check)
cout << "B: " << b << ",\tG:" << g << ",\tR:" << r << endl;
Vec3b yuv = yuvframe.at<Vec3b>(y, x);
int y = yuv.val[0];
int u = yuv.val[1];
int v = yuv.val[2];
// print out YUV values (sanity check)
cout << "Y: " << y << ",\tU:" << u << ",\tV:" << v << endl;
}
}
//////////
// Main //
//////////
int main(int argc, char** argv)
{
// Open the camera!
cap.open(0); // opens first video device
picamctrl.open("/dev/video0");
// check to make sure device properly opened
if ( !cap.isOpened() )
{
cerr << "Error opening the camera (OpenCV)" << endl;
return -1;
}
// Set framerate (OpenCV capture property)
cap.set(CV_CAP_PROP_FPS,2);
// Set camera exposure control to manual (driver property)
picamctrl.set(V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
// Set camera autowhitebalance to manual
picamctrl.set(V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE,V4L2_WHITE_BALANCE_MANUAL);
// Disable scene mode
picamctrl.set(V4L2_CID_SCENE_MODE, V4L2_SCENE_MODE_NONE);
// Set camera iso to manual
picamctrl.set(V4L2_CID_ISO_SENSITIVITY_AUTO, 0);
// Initialize exposure, iso values
picamctrl.set(V4L2_CID_EXPOSURE_ABSOLUTE, BRIGHT_EXPOSURE);
picamctrl.set(V4L2_CID_ISO_SENSITIVITY, ISO_VALUE);
// Set capture camera size (resolution)
cap.set(CV_CAP_PROP_FRAME_WIDTH,FRAME_WIDTH);
cap.set(CV_CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT);
// Open window on your monitor
namedWindow( sourcewindow, CV_WINDOW_AUTOSIZE );
// Create trackbar for exposure setting
// createTrackbar( " Exposure:", source_window, &exposure, 100, NULL);
// set the callback function for any mouse event
setMouseCallback(sourcewindow, mouseCallback, NULL);
// set default white balance
picamctrl.set(V4L2_CID_RED_BALANCE, redbalance);
picamctrl.set(V4L2_CID_BLUE_BALANCE, bluebalance);
// Calculate region within which we will be balancing the image
int balanceh_2 = FRAME_HEIGHT * BALANCE_HEIGHT / 2; // half balance box height
int balancew_2 = FRAME_WIDTH * BALANCE_WIDTH / 2; // half balance box width
int framecentery = FRAME_HEIGHT / 2; // y coord of "center" of frame
int framecenterx = FRAME_WIDTH / 2; // x coord of "center" of frame
// Calculate coordinates of balancing box
int balancexmin = framecenterx - balancew_2;
int balancexmax = framecenterx + balancew_2 - 1;
int balanceymin = framecentery - balanceh_2;
int balanceymax = framecentery + balanceh_2 - 1;
// Generate points for bounds of balancing box
Point b1 = Point(balancexmin, balanceymin);
Point b2 = Point(balancexmax, balanceymax);
// Grab all 5 images from the frame buffer in order to clear the buffer
for(int i=0; i<5; i++)
{
cap.grab();
}
// Announce that we're done initializing
cout << "Done Initializing." << endl;
int key = 0;
// Loop quickly to pick up images as soon as they are taken
while(key != 27) // 27 is keycode for escape key
{
// 'Grab' frame from webcam's image buffer
cap.grab();
// Retrieve encodes image from grab buffer to 'frame' variable
cap.retrieve( bgrframe );
// Convert color spaces
cvtColor(bgrframe, yuvframe, CV_BGR2YCrCb);
// Obtain average YUV values over our balancing box area.
Scalar yuvmean = mean(yuvframe(Rect(b1, b2)));
float ubar = yuvmean[1]; // red
float vbar = yuvmean[2]; // blue
// Check whether red (u) or blue (v) is more off.
if ( abs(ubar) > abs(vbar) )
{
// If red is more wrong, adjust red balance
redbalance -= 1.0*ubar;
picamctrl.set(V4L2_CID_RED_BALANCE, redbalance);
}
else
{
// The blue is more wrong, so adjust blue balance
bluebalance -= 1.0*vbar;
picamctrl.set(V4L2_CID_BLUE_BALANCE, bluebalance);
}
// Draw rectangle in middle of image
rectangle(bgrframe, b1, b2 , Scalar(255, 255, 0));
// Display image on current open window
imshow( sourcewindow, bgrframe );
// wait 1 ms to check for press of escape key
key = waitKey(1);
} // end while
// close camera
cap.release();
picamctrl.close();
}// end main
<commit_msg>variable name error fix<commit_after>/*****************************************************************************
* CameraCalibration.cpp
*
* Set white balance for given lighting, write parameters to file
* https://web.stanford.edu/~sujason/ColorBalancing/robustawb.html
******************************************************************************/
#include "CameraCalibration.h"
using namespace cv;
using namespace std;
////////////////
// Parameters //
////////////////
#define EXPOSURE 200
#define ISO_VALUE 1
// Image Size
//#define FRAME_WIDTH 3280 // 8 megapixels
//#define FRAME_HEIGHT 2464 // 8 megapixels
#define FRAME_WIDTH 1280 // 720 HD
#define FRAME_HEIGHT 720 // 720 HD
// Balancing Region
#define BALANCE_WIDTH 0.2
#define BALANCE_HEIGHT 0.2
//////////////////////
// Global Variables //
//////////////////////
// Global Variables
string sourcewindow = "Current Image";
VideoCapture cap;
int redbalance = 1600;
int bluebalance = 1600;
int exposure = 5;
Mat bgrframe, yuvframe;
// V4L2 Global Device Object
V4L2Control picamctrl;
////////////////////////
// Callback Functions //
////////////////////////
/*******************************************************************************
* void mouseCallback(int event, int x, int y, int flags, void* userdata)
*
* Write HSV and RGB values of point clicked on to terminal
* Any mouse movement will call this function
******************************************************************************/
void mouseCallback(int event, int x, int y, int flags, void* userdata)
{
if ( event == EVENT_LBUTTONDOWN ) // Only run when left button is pressed
{
Vec3b bgr = bgrframe.at<Vec3b>(y, x);
int b = bgr.val[0];
int g = bgr.val[1];
int r = bgr.val[2];
// print out RGB values (sanity check)
cout << "B: " << b << ",\tG:" << g << ",\tR:" << r << endl;
Vec3b yuv = yuvframe.at<Vec3b>(y, x);
int y = yuv.val[0];
int u = yuv.val[1];
int v = yuv.val[2];
// print out YUV values (sanity check)
cout << "Y: " << y << ",\tU:" << u << ",\tV:" << v << endl;
}
}
//////////
// Main //
//////////
int main(int argc, char** argv)
{
// Open the camera!
cap.open(0); // opens first video device
picamctrl.open("/dev/video0");
// check to make sure device properly opened
if ( !cap.isOpened() )
{
cerr << "Error opening the camera (OpenCV)" << endl;
return -1;
}
// Set framerate (OpenCV capture property)
cap.set(CV_CAP_PROP_FPS,2);
// Set camera exposure control to manual (driver property)
picamctrl.set(V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);
// Set camera autowhitebalance to manual
picamctrl.set(V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE,V4L2_WHITE_BALANCE_MANUAL);
// Disable scene mode
picamctrl.set(V4L2_CID_SCENE_MODE, V4L2_SCENE_MODE_NONE);
// Set camera iso to manual
picamctrl.set(V4L2_CID_ISO_SENSITIVITY_AUTO, 0);
// Initialize exposure, iso values
picamctrl.set(V4L2_CID_EXPOSURE_ABSOLUTE, EXPOSURE);
picamctrl.set(V4L2_CID_ISO_SENSITIVITY, ISO_VALUE);
// Set capture camera size (resolution)
cap.set(CV_CAP_PROP_FRAME_WIDTH,FRAME_WIDTH);
cap.set(CV_CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT);
// Open window on your monitor
namedWindow( sourcewindow, CV_WINDOW_AUTOSIZE );
// Create trackbar for exposure setting
// createTrackbar( " Exposure:", source_window, &exposure, 100, NULL);
// set the callback function for any mouse event
setMouseCallback(sourcewindow, mouseCallback, NULL);
// set default white balance
picamctrl.set(V4L2_CID_RED_BALANCE, redbalance);
picamctrl.set(V4L2_CID_BLUE_BALANCE, bluebalance);
// Calculate region within which we will be balancing the image
int balanceh_2 = FRAME_HEIGHT * BALANCE_HEIGHT / 2; // half balance box height
int balancew_2 = FRAME_WIDTH * BALANCE_WIDTH / 2; // half balance box width
int framecentery = FRAME_HEIGHT / 2; // y coord of "center" of frame
int framecenterx = FRAME_WIDTH / 2; // x coord of "center" of frame
// Calculate coordinates of balancing box
int balancexmin = framecenterx - balancew_2;
int balancexmax = framecenterx + balancew_2 - 1;
int balanceymin = framecentery - balanceh_2;
int balanceymax = framecentery + balanceh_2 - 1;
// Generate points for bounds of balancing box
Point b1 = Point(balancexmin, balanceymin);
Point b2 = Point(balancexmax, balanceymax);
// Grab all 5 images from the frame buffer in order to clear the buffer
for(int i=0; i<5; i++)
{
cap.grab();
}
// Announce that we're done initializing
cout << "Done Initializing." << endl;
int key = 0;
// Loop quickly to pick up images as soon as they are taken
while(key != 27) // 27 is keycode for escape key
{
// 'Grab' frame from webcam's image buffer
cap.grab();
// Retrieve encodes image from grab buffer to 'frame' variable
cap.retrieve( bgrframe );
// Convert color spaces
cvtColor(bgrframe, yuvframe, CV_BGR2YCrCb);
// Obtain average YUV values over our balancing box area.
Scalar yuvmean = mean(yuvframe(Rect(b1, b2)));
float ubar = yuvmean[1]; // red
float vbar = yuvmean[2]; // blue
// Check whether red (u) or blue (v) is more off.
if ( abs(ubar) > abs(vbar) )
{
// If red is more wrong, adjust red balance
redbalance -= 1.0*ubar;
picamctrl.set(V4L2_CID_RED_BALANCE, redbalance);
}
else
{
// The blue is more wrong, so adjust blue balance
bluebalance -= 1.0*vbar;
picamctrl.set(V4L2_CID_BLUE_BALANCE, bluebalance);
}
// Draw rectangle in middle of image
rectangle(bgrframe, b1, b2 , Scalar(255, 255, 0));
// Display image on current open window
imshow( sourcewindow, bgrframe );
// wait 1 ms to check for press of escape key
key = waitKey(1);
} // end while
// close camera
cap.release();
picamctrl.close();
}// end main
<|endoftext|> |
<commit_before>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting descriptions of the calling
// conventions supported by this target.
//
//===----------------------------------------------------------------------===//
#include "CallingConvEmitter.h"
#include "Record.h"
#include "CodeGenTarget.h"
using namespace llvm;
void CallingConvEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Calling Convention Implementation Fragment", O);
std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv");
// Emit prototypes for all of the CC's so that they can forward ref each
// other.
for (unsigned i = 0, e = CCs.size(); i != e; ++i) {
O << "static bool " << CCs[i]->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT, MVT::ValueType LocVT,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "CCValAssign::LocInfo LocInfo, unsigned ArgFlags, CCState &State);\n";
}
// Emit each calling convention description in full.
for (unsigned i = 0, e = CCs.size(); i != e; ++i)
EmitCallingConv(CCs[i], O);
}
void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) {
ListInit *CCActions = CC->getValueAsListInit("Actions");
Counter = 0;
O << "\n\nstatic bool " << CC->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT, MVT::ValueType LocVT,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "CCValAssign::LocInfo LocInfo, "
<< "unsigned ArgFlags, CCState &State) {\n";
// Emit all of the actions, in order.
for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {
O << "\n";
EmitAction(CCActions->getElementAsRecord(i), 2, O);
}
O << "\n return true; // CC didn't match.\n";
O << "}\n";
}
void CallingConvEmitter::EmitAction(Record *Action,
unsigned Indent, std::ostream &O) {
std::string IndentStr = std::string(Indent, ' ');
if (Action->isSubClassOf("CCPredicateAction")) {
O << IndentStr << "if (";
if (Action->isSubClassOf("CCMatchType")) {
ListInit *VTs = Action->getValueAsListInit("VTs");
for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {
Record *VT = VTs->getElementAsRecord(i);
if (i != 0) O << " || \n " << IndentStr;
O << "LocVT == " << getEnumName(getValueType(VT));
}
} else if (Action->isSubClassOf("CCMatchIf")) {
O << Action->getValueAsString("Predicate");
} else {
Action->dump();
throw "Unknown CCPredicateAction!";
}
O << ") {\n";
EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O);
O << IndentStr << "}\n";
} else {
if (Action->isSubClassOf("CCDelegateTo")) {
Record *CC = Action->getValueAsDef("CC");
O << IndentStr << "if (!" << CC->getName()
<< "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n"
<< IndentStr << " return false;\n";
} else if (Action->isSubClassOf("CCAssignToReg")) {
ListInit *RegList = Action->getValueAsListInit("RegList");
if (RegList->getSize() == 1) {
O << IndentStr << "if (unsigned Reg = State.AllocateReg(";
O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n";
} else {
O << IndentStr << "static const unsigned RegList" << ++Counter
<< "[] = {\n";
O << IndentStr << " ";
for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {
if (i != 0) O << ", ";
O << getQualifiedName(RegList->getElementAsRecord(i));
}
O << "\n" << IndentStr << "};\n";
O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList"
<< Counter << ", " << RegList->getSize() << ")) {\n";
}
O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, "
<< "Reg, LocVT, LocInfo));\n";
O << IndentStr << " return false;\n";
O << IndentStr << "}\n";
} else if (Action->isSubClassOf("CCAssignToStack")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr << "unsigned Offset" << ++Counter
<< " = State.AllocateStack(" << Size << ", " << Align << ");\n";
O << IndentStr << "State.addLoc(CCValAssign::getMem(ValNo, ArgVT, Offset"
<< Counter << ", LocVT, LocInfo));\n";
O << IndentStr << "return false;\n";
} else if (Action->isSubClassOf("CCPromoteToType")) {
} else {
Action->dump();
throw "Unknown CCAction!";
}
}
}
<commit_msg>implement CCPromoteToType<commit_after>//===- CallingConvEmitter.cpp - Generate calling conventions --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting descriptions of the calling
// conventions supported by this target.
//
//===----------------------------------------------------------------------===//
#include "CallingConvEmitter.h"
#include "Record.h"
#include "CodeGenTarget.h"
using namespace llvm;
void CallingConvEmitter::run(std::ostream &O) {
EmitSourceFileHeader("Calling Convention Implementation Fragment", O);
std::vector<Record*> CCs = Records.getAllDerivedDefinitions("CallingConv");
// Emit prototypes for all of the CC's so that they can forward ref each
// other.
for (unsigned i = 0, e = CCs.size(); i != e; ++i) {
O << "static bool " << CCs[i]->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CCs[i]->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State);\n";
}
// Emit each calling convention description in full.
for (unsigned i = 0, e = CCs.size(); i != e; ++i)
EmitCallingConv(CCs[i], O);
}
void CallingConvEmitter::EmitCallingConv(Record *CC, std::ostream &O) {
ListInit *CCActions = CC->getValueAsListInit("Actions");
Counter = 0;
O << "\n\nstatic bool " << CC->getName()
<< "(unsigned ValNo, MVT::ValueType ValVT,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "MVT::ValueType LocVT, CCValAssign::LocInfo LocInfo,\n"
<< std::string(CC->getName().size()+13, ' ')
<< "unsigned ArgFlags, CCState &State) {\n";
// Emit all of the actions, in order.
for (unsigned i = 0, e = CCActions->getSize(); i != e; ++i) {
O << "\n";
EmitAction(CCActions->getElementAsRecord(i), 2, O);
}
O << "\n return true; // CC didn't match.\n";
O << "}\n";
}
void CallingConvEmitter::EmitAction(Record *Action,
unsigned Indent, std::ostream &O) {
std::string IndentStr = std::string(Indent, ' ');
if (Action->isSubClassOf("CCPredicateAction")) {
O << IndentStr << "if (";
if (Action->isSubClassOf("CCMatchType")) {
ListInit *VTs = Action->getValueAsListInit("VTs");
for (unsigned i = 0, e = VTs->getSize(); i != e; ++i) {
Record *VT = VTs->getElementAsRecord(i);
if (i != 0) O << " ||\n " << IndentStr;
O << "LocVT == " << getEnumName(getValueType(VT));
}
} else if (Action->isSubClassOf("CCMatchIf")) {
O << Action->getValueAsString("Predicate");
} else {
Action->dump();
throw "Unknown CCPredicateAction!";
}
O << ") {\n";
EmitAction(Action->getValueAsDef("SubAction"), Indent+2, O);
O << IndentStr << "}\n";
} else {
if (Action->isSubClassOf("CCDelegateTo")) {
Record *CC = Action->getValueAsDef("CC");
O << IndentStr << "if (!" << CC->getName()
<< "(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State))\n"
<< IndentStr << " return false;\n";
} else if (Action->isSubClassOf("CCAssignToReg")) {
ListInit *RegList = Action->getValueAsListInit("RegList");
if (RegList->getSize() == 1) {
O << IndentStr << "if (unsigned Reg = State.AllocateReg(";
O << getQualifiedName(RegList->getElementAsRecord(0)) << ")) {\n";
} else {
O << IndentStr << "static const unsigned RegList" << ++Counter
<< "[] = {\n";
O << IndentStr << " ";
for (unsigned i = 0, e = RegList->getSize(); i != e; ++i) {
if (i != 0) O << ", ";
O << getQualifiedName(RegList->getElementAsRecord(i));
}
O << "\n" << IndentStr << "};\n";
O << IndentStr << "if (unsigned Reg = State.AllocateReg(RegList"
<< Counter << ", " << RegList->getSize() << ")) {\n";
}
O << IndentStr << " State.addLoc(CCValAssign::getReg(ValNo, ValVT, "
<< "Reg, LocVT, LocInfo));\n";
O << IndentStr << " return false;\n";
O << IndentStr << "}\n";
} else if (Action->isSubClassOf("CCAssignToStack")) {
int Size = Action->getValueAsInt("Size");
int Align = Action->getValueAsInt("Align");
O << IndentStr << "unsigned Offset" << ++Counter
<< " = State.AllocateStack(" << Size << ", " << Align << ");\n";
O << IndentStr << "State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset"
<< Counter << ", LocVT, LocInfo));\n";
O << IndentStr << "return false;\n";
} else if (Action->isSubClassOf("CCPromoteToType")) {
Record *DestTy = Action->getValueAsDef("DestTy");
O << IndentStr << "LocVT = " << getEnumName(getValueType(DestTy)) <<";\n";
O << IndentStr << "LocInfo = (ArgFlags & 1) ? CCValAssign::SExt"
<< " : CCValAssign::ZExt;\n";
} else {
Action->dump();
throw "Unknown CCAction!";
}
}
}
<|endoftext|> |
<commit_before>/*
* INTEL CONFIDENTIAL
* Copyright © 2011 Intel
* Corporation All Rights Reserved.
*
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Intel Corporation or its suppliers
* or licensors. Title to the Material remains with Intel Corporation or its
* suppliers and licensors. The Material contains trade secrets and proprietary
* and confidential information of Intel or its suppliers and licensors. The
* Material is protected by worldwide copyright and trade secret laws and
* treaty provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed, or
* disclosed in any way without Intel’s prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Intel in writing.
*
* CREATED: 2012-03-29
* UPDATED: 2012-03-29
*/
#include "SubsystemLibrary.h"
#include "NamedElementBuilderTemplate.h"
#include "FSSubsystem.h"
extern "C"
{
void getFSSubsystemBuilder(CSubsystemLibrary* pSubsystemLibrary)
{
pSubsystemLibrary->addElementBuilder(new TNamedElementBuilderTemplate<CFSSubsystem>("FS"));
}
}
<commit_msg>Change the element builder semantic<commit_after>/*
* INTEL CONFIDENTIAL
* Copyright © 2011 Intel
* Corporation All Rights Reserved.
*
* The source code contained or described herein and all documents related to
* the source code ("Material") are owned by Intel Corporation or its suppliers
* or licensors. Title to the Material remains with Intel Corporation or its
* suppliers and licensors. The Material contains trade secrets and proprietary
* and confidential information of Intel or its suppliers and licensors. The
* Material is protected by worldwide copyright and trade secret laws and
* treaty provisions. No part of the Material may be used, copied, reproduced,
* modified, published, uploaded, posted, transmitted, distributed, or
* disclosed in any way without Intel’s prior express written permission.
*
* No license under any patent, copyright, trade secret or other intellectual
* property right is granted to or conferred upon you by disclosure or delivery
* of the Materials, either expressly, by implication, inducement, estoppel or
* otherwise. Any license under such intellectual property rights must be
* express and approved by Intel in writing.
*
* CREATED: 2012-03-29
* UPDATED: 2012-03-29
*/
#include "SubsystemLibrary.h"
#include "NamedElementBuilderTemplate.h"
#include "FSSubsystem.h"
extern "C"
{
void getFSSubsystemBuilder(CSubsystemLibrary* pSubsystemLibrary)
{
pSubsystemLibrary->addElementBuilder("FS", new TNamedElementBuilderTemplate<CFSSubsystem>());
}
}
<|endoftext|> |
<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
/// One implementation of GUPS. This does no load-balancing, and may
/// suffer from some load imbalance.
#include <Grappa.hpp>
#include "ForkJoin.hpp"
#include "GlobalAllocator.hpp"
#include <boost/test/unit_test.hpp>
DEFINE_int64( iterations, 1 << 30, "Iterations" );
DEFINE_int64( sizeA, 1000, "Size of array that gups increments" );
double wall_clock_time() {
const double nano = 1.0e-9;
timespec t;
clock_gettime( CLOCK_MONOTONIC, &t );
return nano * t.tv_nsec + t.tv_sec;
}
BOOST_AUTO_TEST_SUITE( Gups_tests );
LOOP_FUNCTION( func_start_profiling, index ) {
Grappa_start_profiling();
}
LOOP_FUNCTION( func_stop_profiling, index ) {
Grappa_stop_profiling();
}
/// Functor to execute one GUP.
LOOP_FUNCTOR( func_gups, index, ((GlobalAddress<int64_t>, Array)) ) {
const uint64_t LARGE_PRIME = 18446744073709551557UL;
uint64_t b = (index*LARGE_PRIME) % FLAGS_sizeA;
Grappa_delegate_fetch_and_add_word( Array + b, 1 );
}
void user_main( int * args ) {
func_start_profiling start_profiling;
func_stop_profiling stop_profiling;
GlobalAddress<int64_t> A = Grappa_typed_malloc<int64_t>(FLAGS_sizeA);
func_gups gups( A );
fork_join_custom( &start_profiling );
double start = wall_clock_time();
fork_join( &gups, 1, FLAGS_iterations );
double end = wall_clock_time();
fork_join_custom( &stop_profiling );
<<<<<<< HEAD
Grappa_merge_and_dump_stats();
=======
>>>>>>> change stats to dump a single JSON blob
double runtime = end - start;
double throughput = FLAGS_iterations / runtime;
int nnodes = atoi(getenv("SLURM_NNODES"));
double throughput_per_node = throughput/nnodes;
SoftXMT_add_profiling_value( &runtime, "runtime", "s", false, 0.0 );
SoftXMT_add_profiling_integer( &FLAGS_iterations, "iterations", "it", false, 0 );
SoftXMT_add_profiling_integer( &FLAGS_sizeA, "sizeA", "entries", false, 0 );
SoftXMT_add_profiling_value( &throughput, "updates_per_s", "up/s", false, 0.0 );
SoftXMT_add_profiling_value( &throughput_per_node, "updates_per_s_per_node", "up/s", false, 0.0 );
SoftXMT_merge_and_dump_stats();
LOG(INFO) << "GUPS: "
<< FLAGS_iterations << " updates at "
<< throughput << "updates/s ("
<< throughput/nnodes << " updates/s/node).";
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
Grappa_run_user_main( &user_main, (int*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Move gups user stats insertion before work<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.
/// One implementation of GUPS. This does no load-balancing, and may
/// suffer from some load imbalance.
#include <Grappa.hpp>
#include "ForkJoin.hpp"
#include "GlobalAllocator.hpp"
#include <boost/test/unit_test.hpp>
DEFINE_int64( iterations, 1 << 30, "Iterations" );
DEFINE_int64( sizeA, 1000, "Size of array that gups increments" );
double wall_clock_time() {
const double nano = 1.0e-9;
timespec t;
clock_gettime( CLOCK_MONOTONIC, &t );
return nano * t.tv_nsec + t.tv_sec;
}
BOOST_AUTO_TEST_SUITE( Gups_tests );
LOOP_FUNCTION( func_start_profiling, index ) {
Grappa_start_profiling();
}
LOOP_FUNCTION( func_stop_profiling, index ) {
Grappa_stop_profiling();
}
/// Functor to execute one GUP.
LOOP_FUNCTOR( func_gups, index, ((GlobalAddress<int64_t>, Array)) ) {
const uint64_t LARGE_PRIME = 18446744073709551557UL;
uint64_t b = (index*LARGE_PRIME) % FLAGS_sizeA;
Grappa_delegate_fetch_and_add_word( Array + b, 1 );
}
void user_main( int * args ) {
func_start_profiling start_profiling;
func_stop_profiling stop_profiling;
GlobalAddress<int64_t> A = Grappa_typed_malloc<int64_t>(FLAGS_sizeA);
func_gups gups( A );
double runtime = 0.0;
double throughput = 0.0;
int nnodes = atoi(getenv("SLURM_NNODES"));
double throughput_per_node = 0.0;
SoftXMT_add_profiling_value( &runtime, "runtime", "s", false, 0.0 );
SoftXMT_add_profiling_integer( &FLAGS_iterations, "iterations", "it", false, 0 );
SoftXMT_add_profiling_integer( &FLAGS_sizeA, "sizeA", "entries", false, 0 );
SoftXMT_add_profiling_value( &throughput, "updates_per_s", "up/s", false, 0.0 );
SoftXMT_add_profiling_value( &throughput_per_node, "updates_per_s_per_node", "up/s", false, 0.0 );
fork_join_custom( &start_profiling );
double start = wall_clock_time();
fork_join( &gups, 1, FLAGS_iterations );
double end = wall_clock_time();
fork_join_custom( &stop_profiling );
runtime = end - start;
throughput = FLAGS_iterations / runtime;
throughput_per_node = throughput/nnodes;
SoftXMT_merge_and_dump_stats();
LOG(INFO) << "GUPS: "
<< FLAGS_iterations << " updates at "
<< throughput << "updates/s ("
<< throughput/nnodes << " updates/s/node).";
}
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa_init( &(boost::unit_test::framework::master_test_suite().argc),
&(boost::unit_test::framework::master_test_suite().argv) );
Grappa_activate();
Grappa_run_user_main( &user_main, (int*)NULL );
Grappa_finish( 0 );
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, Project OSRM, Felix Guendling
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MULTI_TARGET_PLUGIN_H
#define MULTI_TARGET_PLUGIN_H
#include "./plugin_base.hpp"
#include "../algorithms/object_encoder.hpp"
#include "../data_structures/search_engine.hpp"
#include "../Util/json_renderer.hpp"
#include "../Util/timing_util.hpp"
template <class DataFacadeT, bool forward> class MultiTargetPlugin final : public BasePlugin
{
public:
explicit MultiTargetPlugin(DataFacadeT *facade)
: facade(facade), search_engine_ptr(std::make_shared<SearchEngine<DataFacadeT>>(facade))
{
}
virtual ~MultiTargetPlugin() {}
std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>>
HandleRequest(const RouteParameters &route_parameters,
unsigned &calctime_in_us)
{
// check number of parameters
if (2 > route_parameters.coordinates.size())
{
return nullptr;
}
if (std::any_of(begin(route_parameters.coordinates), end(route_parameters.coordinates),
[&](FixedPointCoordinate coordinate)
{
return !coordinate.is_valid();
}))
{
return nullptr;
}
const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum());
PhantomNodeArray phantom_node_vector(route_parameters.coordinates.size());
for (unsigned i = 0; i < route_parameters.coordinates.size(); ++i)
{
if (checksum_OK && i < route_parameters.hints.size() &&
!route_parameters.hints[i].empty())
{
PhantomNode current_phantom_node;
ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node);
if (current_phantom_node.is_valid(facade->GetNumberOfNodes()))
{
phantom_node_vector[i].emplace_back(std::move(current_phantom_node));
continue;
}
}
facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i],
phantom_node_vector[i],
1);
BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes()));
}
std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>> ret;
TIMER_START(multi_target);
if (forward)
{
ret = search_engine_ptr->multi_target(phantom_node_vector);
}
else
{
ret = search_engine_ptr->multi_source(phantom_node_vector);
}
TIMER_STOP(multi_target);
calctime_in_us = TIMER_USEC(multi_target);
return ret;
}
int HandleRequest(const RouteParameters &route_parameters,
osrm::json::Object &json_result)
{
unsigned calctime_in_ms = 0;
auto result_table = HandleRequest(route_parameters, calctime_in_ms);
if (!result_table)
{
return 400;
}
osrm::json::Array json_array;
for (unsigned column = 0; column < route_parameters.coordinates.size() - 1; ++column)
{
auto routing_result = result_table->operator[](column);
osrm::json::Object result;
result.values["time_cost"] = routing_result.first;
result.values["distance"] = routing_result.second;
json_array.values.emplace_back(result);
}
json_result.values["distances"] = json_array;
return 200;
}
const std::string GetDescriptor() const { return forward ? "multitarget" : "multisource"; }
private:
DataFacadeT *facade;
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
};
#endif // MULTI_TARGET_PLUGIN_H
<commit_msg>fix case for util include in plugins/multi_target.hpp<commit_after>/*
Copyright (c) 2014, Project OSRM, Felix Guendling
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MULTI_TARGET_PLUGIN_H
#define MULTI_TARGET_PLUGIN_H
#include "./plugin_base.hpp"
#include "../algorithms/object_encoder.hpp"
#include "../data_structures/search_engine.hpp"
#include "../util/json_renderer.hpp"
#include "../util/timing_util.hpp"
template <class DataFacadeT, bool forward> class MultiTargetPlugin final : public BasePlugin
{
public:
explicit MultiTargetPlugin(DataFacadeT *facade)
: facade(facade), search_engine_ptr(std::make_shared<SearchEngine<DataFacadeT>>(facade))
{
}
virtual ~MultiTargetPlugin() {}
std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>>
HandleRequest(const RouteParameters &route_parameters,
unsigned &calctime_in_us)
{
// check number of parameters
if (2 > route_parameters.coordinates.size())
{
return nullptr;
}
if (std::any_of(begin(route_parameters.coordinates), end(route_parameters.coordinates),
[&](FixedPointCoordinate coordinate)
{
return !coordinate.is_valid();
}))
{
return nullptr;
}
const bool checksum_OK = (route_parameters.check_sum == facade->GetCheckSum());
PhantomNodeArray phantom_node_vector(route_parameters.coordinates.size());
for (unsigned i = 0; i < route_parameters.coordinates.size(); ++i)
{
if (checksum_OK && i < route_parameters.hints.size() &&
!route_parameters.hints[i].empty())
{
PhantomNode current_phantom_node;
ObjectEncoder::DecodeFromBase64(route_parameters.hints[i], current_phantom_node);
if (current_phantom_node.is_valid(facade->GetNumberOfNodes()))
{
phantom_node_vector[i].emplace_back(std::move(current_phantom_node));
continue;
}
}
facade->IncrementalFindPhantomNodeForCoordinate(route_parameters.coordinates[i],
phantom_node_vector[i],
1);
BOOST_ASSERT(phantom_node_vector[i].front().is_valid(facade->GetNumberOfNodes()));
}
std::shared_ptr<std::vector<std::pair<EdgeWeight, double>>> ret;
TIMER_START(multi_target);
if (forward)
{
ret = search_engine_ptr->multi_target(phantom_node_vector);
}
else
{
ret = search_engine_ptr->multi_source(phantom_node_vector);
}
TIMER_STOP(multi_target);
calctime_in_us = TIMER_USEC(multi_target);
return ret;
}
int HandleRequest(const RouteParameters &route_parameters,
osrm::json::Object &json_result)
{
unsigned calctime_in_ms = 0;
auto result_table = HandleRequest(route_parameters, calctime_in_ms);
if (!result_table)
{
return 400;
}
osrm::json::Array json_array;
for (unsigned column = 0; column < route_parameters.coordinates.size() - 1; ++column)
{
auto routing_result = result_table->operator[](column);
osrm::json::Object result;
result.values["time_cost"] = routing_result.first;
result.values["distance"] = routing_result.second;
json_array.values.emplace_back(result);
}
json_result.values["distances"] = json_array;
return 200;
}
const std::string GetDescriptor() const { return forward ? "multitarget" : "multisource"; }
private:
DataFacadeT *facade;
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
};
#endif // MULTI_TARGET_PLUGIN_H
<|endoftext|> |
<commit_before>#include <clams/slam_calibrator.h>
using namespace std;
using namespace Eigen;
namespace clams
{
SlamCalibrator::SlamCalibrator(const FrameProjector& proj, double max_range, double vgsize) :
proj_(proj),
max_range_(max_range),
vgsize_(vgsize),
increment_(1)
{
}
void filterFringe(Frame* frame)
{
DepthMat& depth = *frame->depth_;
cv::Mat1b mask(depth.rows(), depth.cols()); // points to be removed.
mask = 0;
ushort threshold = 5000; // millimeters
for(int y = 1; y < depth.rows(); ++y) {
for(int x = 1; x < depth.cols(); ++x) {
if(depth(y, x) == 0 || depth(y-1, x) == 0 || depth(y, x-1) == 0 ||
fabs(depth(y, x) - depth(y-1, x)) > threshold ||
fabs(depth(y, x) - depth(y, x-1)) > threshold)
{
mask(y, x) = 255;
}
}
}
// cv::imshow("mask", mask);
// cv::imshow("depth", frame->depthImage());
// cv::waitKey();
cv::dilate(mask, mask, cv::Mat(), cv::Point(-1, -1), 8);
// cv::imshow("mask", mask);
// cv::waitKey();
for(int y = 1; y < depth.rows(); ++y)
for(int x = 1; x < depth.cols(); ++x)
if(mask(y, x))
depth(y, x) = 0;
// cv::imshow("depth", frame->depthImage());
// cv::waitKey();
}
Cloud::Ptr SlamCalibrator::buildMap(StreamSequenceBase::ConstPtr sseq, const Trajectory& traj, double max_range, double vgsize)
{
ROS_DEBUG_STREAM("Building slam calibration map using max range of " << max_range);
Cloud::Ptr map(new Cloud);
int num_used_frames = 0;
for(size_t i = 0; i < traj.size(); ++i) {
if(!traj.exists(i))
continue;
cout << "Using frame " << i << " / " << traj.size() << endl;
Frame frame;
sseq->readFrame(i, &frame);
filterFringe(&frame);
Cloud::Ptr tmp(new Cloud);
sseq->proj_.frameToCloud(frame, tmp.get(), max_range);
Cloud::Ptr nonans(new Cloud);
nonans->reserve(tmp->size());
for(size_t j = 0; j < tmp->size(); ++j)
if(isFinite(tmp->at(j)))
nonans->push_back(tmp->at(j));
pcl::transformPointCloud(*nonans, *nonans, traj.get(i).cast<float>());
*map += *nonans;
++num_used_frames;
// Added intermediate filtering to handle memory overload on huge maps
if(num_used_frames % 50 == 0)
{
cout << "Filtering..." << endl;
HighResTimer hrt("filtering");
hrt.start();
pcl::VoxelGrid<Point> vg;
vg.setLeafSize(vgsize, vgsize, vgsize);
Cloud::Ptr tmp(new Cloud);
vg.setInputCloud(map);
vg.filter(*tmp);
*map = *tmp;
hrt.stop();
}
}
cout << "Filtering..." << endl;
HighResTimer hrt("filtering");
hrt.start();
pcl::VoxelGrid<Point> vg;
vg.setLeafSize(vgsize, vgsize, vgsize);
Cloud::Ptr tmp(new Cloud);
vg.setInputCloud(map);
vg.filter(*tmp);
*map = *tmp;
hrt.stop();
cout << hrt.reportMilliseconds() << endl;
cout << "Filtered map has " << map->size() << " points." << endl;
return map;
}
Cloud::Ptr SlamCalibrator::buildMap(size_t idx) const
{
ROS_ASSERT(idx < trajectories_.size());
ROS_ASSERT(trajectories_.size() == sseqs_.size());
return buildMap(sseqs_[idx], trajectories_[idx], max_range_, vgsize_);
}
size_t SlamCalibrator::size() const
{
ROS_ASSERT(trajectories_.size() == sseqs_.size());
return trajectories_.size();
}
DiscreteDepthDistortionModel SlamCalibrator::calibrate() const
{
ROS_ASSERT(!sseqs_.empty());
DiscreteDepthDistortionModel model(sseqs_[0]->proj_.width_, sseqs_[0]->proj_.height_);
size_t total_num_training = 0;
for(size_t i = 0; i < size(); ++i) {
// -- Construct the map from the data and the trajectory.
StreamSequenceBase::ConstPtr sseq = sseqs_[i];
const Trajectory& traj = trajectories_[i];
Cloud::Ptr map = buildMap(i);
total_num_training += processMap(*sseq, traj, *map, &model);
}
cout << "Training new DiscreteDepthDistortionModel using "
<< total_num_training << " training examples." << endl;
return model;
}
size_t SlamCalibrator::processMap(const StreamSequenceBase& sseq,
const Trajectory& traj, const Cloud& map,
DiscreteDepthDistortionModel* model) const
{
// -- Select which frame indices from the sequence to use.
// Consider only those with a pose in the Trajectory,
// and apply downsampling based on increment_.
vector<size_t> indices;
indices.reserve(traj.numValid());
int num = 0;
for(size_t i = 0; i < traj.size(); ++i) {
if(traj.exists(i) && num % increment_ == 0) {
indices.push_back(i);
++num;
}
}
// -- For all selected frames, accumulate training examples
// in the distortion model.
VectorXi counts = VectorXi::Zero(indices.size());
#pragma omp parallel for
for(size_t i = 0; i < indices.size(); ++i) {
size_t idx = indices[i];
ROS_ASSERT(traj.exists(idx));
cout << "." << flush;
Frame measurement;
sseq.readFrame(idx, &measurement);
Frame mapframe;
mapframe.depth_ = DepthMatPtr(new DepthMat);
sseq.proj_.estimateMapDepth(map, traj.get(idx).inverse().cast<float>(),
measurement, mapframe.depth_.get());
counts[i] = model->accumulate(*mapframe.depth_, *measurement.depth_);
}
return counts.sum();
}
} // namespace clams
<commit_msg>Adding a quick and dirty way to inspect the distortion on a per-beam basis.<commit_after>#include <clams/slam_calibrator.h>
using namespace std;
using namespace Eigen;
namespace clams
{
SlamCalibrator::SlamCalibrator(const FrameProjector& proj, double max_range, double vgsize) :
proj_(proj),
max_range_(max_range),
vgsize_(vgsize),
increment_(1)
{
}
void filterFringe(Frame* frame)
{
DepthMat& depth = *frame->depth_;
cv::Mat1b mask(depth.rows(), depth.cols()); // points to be removed.
mask = 0;
ushort threshold = 5000; // millimeters
for(int y = 1; y < depth.rows(); ++y) {
for(int x = 1; x < depth.cols(); ++x) {
if(depth(y, x) == 0 || depth(y-1, x) == 0 || depth(y, x-1) == 0 ||
fabs(depth(y, x) - depth(y-1, x)) > threshold ||
fabs(depth(y, x) - depth(y, x-1)) > threshold)
{
mask(y, x) = 255;
}
}
}
// cv::imshow("mask", mask);
// cv::imshow("depth", frame->depthImage());
// cv::waitKey();
cv::dilate(mask, mask, cv::Mat(), cv::Point(-1, -1), 8);
// cv::imshow("mask", mask);
// cv::waitKey();
for(int y = 1; y < depth.rows(); ++y)
for(int x = 1; x < depth.cols(); ++x)
if(mask(y, x))
depth(y, x) = 0;
// cv::imshow("depth", frame->depthImage());
// cv::waitKey();
}
Cloud::Ptr SlamCalibrator::buildMap(StreamSequenceBase::ConstPtr sseq, const Trajectory& traj, double max_range, double vgsize)
{
ROS_DEBUG_STREAM("Building slam calibration map using max range of " << max_range);
Cloud::Ptr map(new Cloud);
int num_used_frames = 0;
for(size_t i = 0; i < traj.size(); ++i) {
if(!traj.exists(i))
continue;
cout << "Using frame " << i << " / " << traj.size() << endl;
Frame frame;
sseq->readFrame(i, &frame);
filterFringe(&frame);
Cloud::Ptr tmp(new Cloud);
sseq->proj_.frameToCloud(frame, tmp.get(), max_range);
Cloud::Ptr nonans(new Cloud);
nonans->reserve(tmp->size());
for(size_t j = 0; j < tmp->size(); ++j)
if(isFinite(tmp->at(j)))
nonans->push_back(tmp->at(j));
pcl::transformPointCloud(*nonans, *nonans, traj.get(i).cast<float>());
*map += *nonans;
++num_used_frames;
// Added intermediate filtering to handle memory overload on huge maps
if(num_used_frames % 50 == 0)
{
cout << "Filtering..." << endl;
HighResTimer hrt("filtering");
hrt.start();
pcl::VoxelGrid<Point> vg;
vg.setLeafSize(vgsize, vgsize, vgsize);
Cloud::Ptr tmp(new Cloud);
vg.setInputCloud(map);
vg.filter(*tmp);
*map = *tmp;
hrt.stop();
}
}
cout << "Filtering..." << endl;
HighResTimer hrt("filtering");
hrt.start();
pcl::VoxelGrid<Point> vg;
vg.setLeafSize(vgsize, vgsize, vgsize);
Cloud::Ptr tmp(new Cloud);
vg.setInputCloud(map);
vg.filter(*tmp);
*map = *tmp;
hrt.stop();
cout << hrt.reportMilliseconds() << endl;
cout << "Filtered map has " << map->size() << " points." << endl;
return map;
}
Cloud::Ptr SlamCalibrator::buildMap(size_t idx) const
{
ROS_ASSERT(idx < trajectories_.size());
ROS_ASSERT(trajectories_.size() == sseqs_.size());
return buildMap(sseqs_[idx], trajectories_[idx], max_range_, vgsize_);
}
size_t SlamCalibrator::size() const
{
ROS_ASSERT(trajectories_.size() == sseqs_.size());
return trajectories_.size();
}
DiscreteDepthDistortionModel SlamCalibrator::calibrate() const
{
ROS_ASSERT(!sseqs_.empty());
DiscreteDepthDistortionModel model(sseqs_[0]->proj_.width_, sseqs_[0]->proj_.height_);
size_t total_num_training = 0;
for(size_t i = 0; i < size(); ++i) {
// -- Construct the map from the data and the trajectory.
StreamSequenceBase::ConstPtr sseq = sseqs_[i];
const Trajectory& traj = trajectories_[i];
Cloud::Ptr map = buildMap(i);
total_num_training += processMap(*sseq, traj, *map, &model);
}
cout << "Training new DiscreteDepthDistortionModel using "
<< total_num_training << " training examples." << endl;
return model;
}
size_t SlamCalibrator::processMap(const StreamSequenceBase& sseq,
const Trajectory& traj, const Cloud& map,
DiscreteDepthDistortionModel* model) const
{
// -- Select which frame indices from the sequence to use.
// Consider only those with a pose in the Trajectory,
// and apply downsampling based on increment_.
vector<size_t> indices;
indices.reserve(traj.numValid());
int num = 0;
for(size_t i = 0; i < traj.size(); ++i) {
if(traj.exists(i) && num % increment_ == 0) {
indices.push_back(i);
++num;
}
}
// -- For all selected frames, accumulate training examples
// in the distortion model.
VectorXi counts = VectorXi::Zero(indices.size());
#pragma omp parallel for
for(size_t i = 0; i < indices.size(); ++i) {
size_t idx = indices[i];
ROS_ASSERT(traj.exists(idx));
cout << "." << flush;
Frame measurement;
sseq.readFrame(idx, &measurement);
Frame mapframe;
mapframe.depth_ = DepthMatPtr(new DepthMat);
sseq.proj_.estimateMapDepth(map, traj.get(idx).inverse().cast<float>(),
measurement, mapframe.depth_.get());
counts[i] = model->accumulate(*mapframe.depth_, *measurement.depth_);
// -- Quick and dirty option for data inspection.
if(getenv("U") && getenv("V")) {
int u_center = atoi(getenv("U"));
int v_center = atoi(getenv("V"));
int radius = 1;
for(int u = max(0, u_center - radius); u < min(640, u_center + radius + 1); ++u) {
for(int v = max(0, v_center - radius); v < min(480, v_center + radius + 1); ++v) {
if(mapframe.depth_->coeffRef(v, u) == 0)
continue;
if(measurement.depth_->coeffRef(v, u) == 0)
continue;
cerr << mapframe.depth_->coeffRef(v, u) * 0.001
<< " "
<< measurement.depth_->coeffRef(v, u) * 0.001
<< endl;
}
}
}
}
return counts.sum();
}
} // namespace clams
<|endoftext|> |
<commit_before>#include "testing/testing.hpp"
#include "routing/route.hpp"
#include "routing/router.hpp"
#include "routing/routing_session.hpp"
#include "geometry/point2d.hpp"
#include "base/logging.hpp"
#include "std/chrono.hpp"
#include "std/mutex.hpp"
#include "std/string.hpp"
#include "std/vector.hpp"
namespace routing
{
// Simple router. It returns route given to him on creation.
class DummyRouter : public IRouter
{
private:
Route & m_route;
ResultCode m_code;
size_t & m_buildCount;
public:
DummyRouter(Route & route, ResultCode code, size_t & buildCounter)
: m_route(route), m_code(code), m_buildCount(buildCounter)
{
}
string GetName() const override { return "dummy"; }
void ClearState() override {}
ResultCode CalculateRoute(m2::PointD const & /* startPoint */,
m2::PointD const & /* startDirection */,
m2::PointD const & /* finalPoint */,
RouterDelegate const & /* delegate */, Route & route) override
{
++m_buildCount;
route = m_route;
return m_code;
}
};
static vector<m2::PointD> kTestRoute = {{0., 1.}, {0., 2.}, {0., 3.}, {0., 4.}};
static auto kRouteBuildingMaxDuration = seconds(30);
UNIT_TEST(TestRouteBuilding)
{
RoutingSession session;
session.Init(nullptr, nullptr);
vector<m2::PointD> routePoints = kTestRoute;
Route masterRoute("dummy", routePoints.begin(), routePoints.end());
size_t counter = 0;
timed_mutex routeBuilded;
routeBuilded.lock();
unique_ptr<DummyRouter> router = make_unique<DummyRouter>(masterRoute, DummyRouter::NoError, counter);
session.SetRouter(move(router), nullptr);
session.BuildRoute(kTestRoute.front(), kTestRoute.back(),
[&routeBuilded](Route const &, IRouter::ResultCode)
{
routeBuilded.unlock();
},
nullptr, 0);
TEST(routeBuilded.try_lock_for(kRouteBuildingMaxDuration), ());
TEST_EQUAL(counter, 1, ());
}
UNIT_TEST(TestRouteRebuilding)
{
Index index;
RoutingSession session;
session.Init(nullptr, nullptr);
vector<m2::PointD> routePoints = kTestRoute;
Route masterRoute("dummy", routePoints.begin(), routePoints.end());
size_t counter = 0;
timed_mutex routeBuilded;
auto fn = [&routeBuilded](Route const &, IRouter::ResultCode)
{
routeBuilded.unlock();
};
routeBuilded.lock();
unique_ptr<DummyRouter> router = make_unique<DummyRouter>(masterRoute, DummyRouter::NoError, counter);
session.SetRouter(move(router), nullptr);
// Go along the route.
session.BuildRoute(kTestRoute.front(), kTestRoute.back(), fn, nullptr, 0);
TEST(routeBuilded.try_lock_for(kRouteBuildingMaxDuration), ());
location::GpsInfo info;
info.m_horizontalAccuracy = 0.01;
info.m_verticalAccuracy = 0.01;
info.m_longitude = 0.;
info.m_latitude = 1.;
RoutingSession::State code;
while (info.m_latitude < kTestRoute.back().y)
{
code = session.OnLocationPositionChanged(
MercatorBounds::FromLatLon(info.m_latitude, info.m_longitude), info, index);
TEST_EQUAL(code, RoutingSession::State::OnRoute, ());
info.m_latitude += 0.01;
}
TEST_EQUAL(counter, 1, ());
// Rebuild route and go in opposite direction. So initiate a route rebuilding flag.
counter = 0;
session.BuildRoute(kTestRoute.front(), kTestRoute.back(), fn, nullptr, 0);
TEST(routeBuilded.try_lock_for(kRouteBuildingMaxDuration), ());
info.m_longitude = 0.;
info.m_latitude = 1.;
for (size_t i = 0; i < 10; ++i)
{
code = session.OnLocationPositionChanged(
MercatorBounds::FromLatLon(info.m_latitude, info.m_longitude), info, index);
info.m_latitude -= 0.1;
}
TEST_EQUAL(code, RoutingSession::State::RouteNeedRebuild, ());
}
} // namespace routing
<commit_msg>Routing session tests UB fix.<commit_after>#include "testing/testing.hpp"
#include "routing/route.hpp"
#include "routing/router.hpp"
#include "routing/routing_session.hpp"
#include "geometry/point2d.hpp"
#include "base/logging.hpp"
#include "std/atomic.hpp"
#include "std/chrono.hpp"
#include "std/string.hpp"
#include "std/vector.hpp"
namespace routing
{
// Simple router. It returns route given to him on creation.
class DummyRouter : public IRouter
{
private:
Route & m_route;
ResultCode m_code;
size_t & m_buildCount;
public:
DummyRouter(Route & route, ResultCode code, size_t & buildCounter)
: m_route(route), m_code(code), m_buildCount(buildCounter)
{
}
string GetName() const override { return "dummy"; }
void ClearState() override {}
ResultCode CalculateRoute(m2::PointD const & /* startPoint */,
m2::PointD const & /* startDirection */,
m2::PointD const & /* finalPoint */,
RouterDelegate const & /* delegate */, Route & route) override
{
++m_buildCount;
route = m_route;
return m_code;
}
};
static vector<m2::PointD> kTestRoute = {{0., 1.}, {0., 2.}, {0., 3.}, {0., 4.}};
static auto kTestMaxDuration = seconds(30);
UNIT_TEST(TestRouteBuilding)
{
RoutingSession session;
session.Init(nullptr, nullptr);
vector<m2::PointD> routePoints = kTestRoute;
Route masterRoute("dummy", routePoints.begin(), routePoints.end());
size_t counter = 0;
atomic<bool> routeBuilded(false);
unique_ptr<DummyRouter> router = make_unique<DummyRouter>(masterRoute, DummyRouter::NoError, counter);
session.SetRouter(move(router), nullptr);
session.BuildRoute(kTestRoute.front(), kTestRoute.back(),
[&routeBuilded](Route const &, IRouter::ResultCode)
{
routeBuilded = true;
},
nullptr, 0);
// Manual check of the routeBuilded mutex to avoid spurious results.
auto time = steady_clock::now() + kTestMaxDuration;
while (steady_clock::now() < time && !routeBuilded)
{
}
TEST(routeBuilded, ("Route was not built."));
TEST_EQUAL(counter, 1, ());
}
UNIT_TEST(TestRouteRebuilding)
{
Index index;
RoutingSession session;
session.Init(nullptr, nullptr);
vector<m2::PointD> routePoints = kTestRoute;
Route masterRoute("dummy", routePoints.begin(), routePoints.end());
size_t counter = 0;
atomic<bool> routeBuilded(false);
auto fn = [&routeBuilded](Route const &, IRouter::ResultCode)
{
routeBuilded = true;
};
unique_ptr<DummyRouter> router = make_unique<DummyRouter>(masterRoute, DummyRouter::NoError, counter);
session.SetRouter(move(router), nullptr);
// Go along the route.
session.BuildRoute(kTestRoute.front(), kTestRoute.back(), fn, nullptr, 0);
// Manual check of the routeBuilded mutex to avoid spurious results.
auto time = steady_clock::now() + kTestMaxDuration;
while (steady_clock::now() < time && !routeBuilded)
{
}
TEST(routeBuilded, ("Route was not built."));
location::GpsInfo info;
info.m_horizontalAccuracy = 0.01;
info.m_verticalAccuracy = 0.01;
info.m_longitude = 0.;
info.m_latitude = 1.;
RoutingSession::State code;
while (info.m_latitude < kTestRoute.back().y)
{
code = session.OnLocationPositionChanged(
MercatorBounds::FromLatLon(info.m_latitude, info.m_longitude), info, index);
TEST_EQUAL(code, RoutingSession::State::OnRoute, ());
info.m_latitude += 0.01;
}
TEST_EQUAL(counter, 1, ());
// Rebuild route and go in opposite direction. So initiate a route rebuilding flag.
counter = 0;
routeBuilded = false;
session.BuildRoute(kTestRoute.front(), kTestRoute.back(), fn, nullptr, 0);
while (steady_clock::now() < time && !routeBuilded)
{
}
TEST(routeBuilded, ("Route was not built."));
info.m_longitude = 0.;
info.m_latitude = 1.;
for (size_t i = 0; i < 10; ++i)
{
code = session.OnLocationPositionChanged(
MercatorBounds::FromLatLon(info.m_latitude, info.m_longitude), info, index);
info.m_latitude -= 0.1;
}
TEST_EQUAL(code, RoutingSession::State::RouteNeedRebuild, ());
}
} // namespace routing
<|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#include <tchar.h>
#include <algorithm>
#include "libEGL/Surface.h"
#include "common/debug.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libGLESv2/main.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
namespace egl
{
Surface::Surface(Display *display, const Config *config, HWND window, EGLint postSubBufferSupported)
: mDisplay(display), mConfig(config), mWindow(window), mPostSubBufferSupported(postSubBufferSupported)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mShareHandle = NULL;
mTexture = NULL;
mTextureFormat = EGL_NO_TEXTURE;
mTextureTarget = EGL_NO_TEXTURE;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
mWidth = -1;
mHeight = -1;
setSwapInterval(1);
subclassWindow();
}
Surface::Surface(Display *display, const Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureType)
: mDisplay(display), mWindow(NULL), mConfig(config), mShareHandle(shareHandle), mWidth(width), mHeight(height), mPostSubBufferSupported(EGL_FALSE)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mWindowSubclassed = false;
mTexture = NULL;
mTextureFormat = textureFormat;
mTextureTarget = textureType;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
setSwapInterval(1);
}
Surface::~Surface()
{
unsubclassWindow();
release();
}
bool Surface::initialize()
{
if (!resetSwapChain())
return false;
return true;
}
void Surface::release()
{
delete mSwapChain;
mSwapChain = NULL;
if (mTexture)
{
mTexture->releaseTexImage();
mTexture = NULL;
}
}
bool Surface::resetSwapChain()
{
ASSERT(!mSwapChain);
int width;
int height;
if (mWindow)
{
RECT windowRect;
if (!GetClientRect(getWindowHandle(), &windowRect))
{
ASSERT(false);
ERR("Could not retrieve the window dimensions");
return error(EGL_BAD_SURFACE, false);
}
width = windowRect.right - windowRect.left;
height = windowRect.bottom - windowRect.top;
}
else
{
// non-window surface - size is determined at creation
width = mWidth;
height = mHeight;
}
mSwapChain = mRenderer->createSwapChain(mWindow, mShareHandle,
mConfig->mRenderTargetFormat,
mConfig->mDepthStencilFormat);
if (!mSwapChain)
{
return error(EGL_BAD_ALLOC, false);
}
if (!resetSwapChain(width, height))
{
delete mSwapChain;
mSwapChain = NULL;
return false;
}
return true;
}
bool Surface::resizeSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->resize(backbufferWidth, backbufferHeight);
if (status == EGL_CONTEXT_LOST)
{
mDisplay->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
return true;
}
bool Surface::resetSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->reset(backbufferWidth, backbufferHeight, mSwapInterval);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapIntervalDirty = false;
return true;
}
bool Surface::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return true;
}
if (x + width > mWidth)
{
width = mWidth - x;
}
if (y + height > mHeight)
{
height = mHeight - y;
}
if (width == 0 || height == 0)
{
return true;
}
EGLint status = mSwapChain->swapRect(x, y, width, height);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
checkForOutOfDateSwapChain();
return true;
}
HWND Surface::getWindowHandle()
{
return mWindow;
}
#define kSurfaceProperty _TEXT("Egl::SurfaceOwner")
#define kParentWndProc _TEXT("Egl::SurfaceParentWndProc")
static LRESULT CALLBACK SurfaceWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_SIZE)
{
Surface* surf = reinterpret_cast<Surface*>(GetProp(hwnd, kSurfaceProperty));
if(surf)
{
surf->checkForOutOfDateSwapChain();
}
}
WNDPROC prevWndFunc = reinterpret_cast<WNDPROC >(GetProp(hwnd, kParentWndProc));
return CallWindowProc(prevWndFunc, hwnd, message, wparam, lparam);
}
void Surface::subclassWindow()
{
if (!mWindow)
{
return;
}
DWORD processId;
DWORD threadId = GetWindowThreadProcessId(mWindow, &processId);
if (processId != GetCurrentProcessId() || threadId != GetCurrentThreadId())
{
return;
}
SetLastError(0);
LONG_PTR oldWndProc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
if(oldWndProc == 0 && GetLastError() != ERROR_SUCCESS)
{
mWindowSubclassed = false;
return;
}
SetProp(mWindow, kSurfaceProperty, reinterpret_cast<HANDLE>(this));
SetProp(mWindow, kParentWndProc, reinterpret_cast<HANDLE>(oldWndProc));
mWindowSubclassed = true;
}
void Surface::unsubclassWindow()
{
if(!mWindowSubclassed)
{
return;
}
// un-subclass
LONG_PTR parentWndFunc = reinterpret_cast<LONG_PTR>(GetProp(mWindow, kParentWndProc));
// Check the windowproc is still SurfaceWindowProc.
// If this assert fails, then it is likely the application has subclassed the
// hwnd as well and did not unsubclass before destroying its EGL context. The
// application should be modified to either subclass before initializing the
// EGL context, or to unsubclass before destroying the EGL context.
if(parentWndFunc)
{
LONG_PTR prevWndFunc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, parentWndFunc);
ASSERT(prevWndFunc == reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
}
RemoveProp(mWindow, kSurfaceProperty);
RemoveProp(mWindow, kParentWndProc);
mWindowSubclassed = false;
}
bool Surface::checkForOutOfDateSwapChain()
{
RECT client;
if (!GetClientRect(getWindowHandle(), &client))
{
ASSERT(false);
return false;
}
// Grow the buffer now, if the window has grown. We need to grow now to avoid losing information.
int clientWidth = client.right - client.left;
int clientHeight = client.bottom - client.top;
bool sizeDirty = clientWidth != getWidth() || clientHeight != getHeight();
if (mSwapIntervalDirty)
{
resetSwapChain(clientWidth, clientHeight);
}
else if (sizeDirty)
{
resizeSwapChain(clientWidth, clientHeight);
}
if (mSwapIntervalDirty || sizeDirty)
{
if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
{
glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
}
return true;
}
return false;
}
bool Surface::swap()
{
return swapRect(0, 0, mWidth, mHeight);
}
bool Surface::postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mPostSubBufferSupported)
{
// Spec is not clear about how this should be handled.
return true;
}
return swapRect(x, y, width, height);
}
EGLint Surface::getWidth() const
{
return mWidth;
}
EGLint Surface::getHeight() const
{
return mHeight;
}
EGLint Surface::isPostSubBufferSupported() const
{
return mPostSubBufferSupported;
}
rx::SwapChain *Surface::getSwapChain() const
{
return mSwapChain;
}
void Surface::setSwapInterval(EGLint interval)
{
if (mSwapInterval == interval)
{
return;
}
mSwapInterval = interval;
mSwapInterval = std::max(mSwapInterval, mRenderer->getMinSwapInterval());
mSwapInterval = std::min(mSwapInterval, mRenderer->getMaxSwapInterval());
mSwapIntervalDirty = true;
}
EGLenum Surface::getTextureFormat() const
{
return mTextureFormat;
}
EGLenum Surface::getTextureTarget() const
{
return mTextureTarget;
}
void Surface::setBoundTexture(gl::Texture2D *texture)
{
mTexture = texture;
}
gl::Texture2D *Surface::getBoundTexture() const
{
return mTexture;
}
EGLenum Surface::getFormat() const
{
return mConfig->mRenderTargetFormat;
}
}
<commit_msg>Disable automatically resizing swapchain if window is iconified<commit_after>//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#include <tchar.h>
#include <algorithm>
#include "libEGL/Surface.h"
#include "common/debug.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libGLESv2/main.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
namespace egl
{
Surface::Surface(Display *display, const Config *config, HWND window, EGLint postSubBufferSupported)
: mDisplay(display), mConfig(config), mWindow(window), mPostSubBufferSupported(postSubBufferSupported)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mShareHandle = NULL;
mTexture = NULL;
mTextureFormat = EGL_NO_TEXTURE;
mTextureTarget = EGL_NO_TEXTURE;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
mWidth = -1;
mHeight = -1;
setSwapInterval(1);
subclassWindow();
}
Surface::Surface(Display *display, const Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureType)
: mDisplay(display), mWindow(NULL), mConfig(config), mShareHandle(shareHandle), mWidth(width), mHeight(height), mPostSubBufferSupported(EGL_FALSE)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mWindowSubclassed = false;
mTexture = NULL;
mTextureFormat = textureFormat;
mTextureTarget = textureType;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
setSwapInterval(1);
}
Surface::~Surface()
{
unsubclassWindow();
release();
}
bool Surface::initialize()
{
if (!resetSwapChain())
return false;
return true;
}
void Surface::release()
{
delete mSwapChain;
mSwapChain = NULL;
if (mTexture)
{
mTexture->releaseTexImage();
mTexture = NULL;
}
}
bool Surface::resetSwapChain()
{
ASSERT(!mSwapChain);
int width;
int height;
if (mWindow)
{
RECT windowRect;
if (!GetClientRect(getWindowHandle(), &windowRect))
{
ASSERT(false);
ERR("Could not retrieve the window dimensions");
return error(EGL_BAD_SURFACE, false);
}
width = windowRect.right - windowRect.left;
height = windowRect.bottom - windowRect.top;
}
else
{
// non-window surface - size is determined at creation
width = mWidth;
height = mHeight;
}
mSwapChain = mRenderer->createSwapChain(mWindow, mShareHandle,
mConfig->mRenderTargetFormat,
mConfig->mDepthStencilFormat);
if (!mSwapChain)
{
return error(EGL_BAD_ALLOC, false);
}
if (!resetSwapChain(width, height))
{
delete mSwapChain;
mSwapChain = NULL;
return false;
}
return true;
}
bool Surface::resizeSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->resize(backbufferWidth, backbufferHeight);
if (status == EGL_CONTEXT_LOST)
{
mDisplay->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
return true;
}
bool Surface::resetSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->reset(backbufferWidth, backbufferHeight, mSwapInterval);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapIntervalDirty = false;
return true;
}
bool Surface::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return true;
}
if (x + width > mWidth)
{
width = mWidth - x;
}
if (y + height > mHeight)
{
height = mHeight - y;
}
if (width == 0 || height == 0)
{
return true;
}
EGLint status = mSwapChain->swapRect(x, y, width, height);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
checkForOutOfDateSwapChain();
return true;
}
HWND Surface::getWindowHandle()
{
return mWindow;
}
#define kSurfaceProperty _TEXT("Egl::SurfaceOwner")
#define kParentWndProc _TEXT("Egl::SurfaceParentWndProc")
static LRESULT CALLBACK SurfaceWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_SIZE)
{
Surface* surf = reinterpret_cast<Surface*>(GetProp(hwnd, kSurfaceProperty));
if(surf)
{
surf->checkForOutOfDateSwapChain();
}
}
WNDPROC prevWndFunc = reinterpret_cast<WNDPROC >(GetProp(hwnd, kParentWndProc));
return CallWindowProc(prevWndFunc, hwnd, message, wparam, lparam);
}
void Surface::subclassWindow()
{
if (!mWindow)
{
return;
}
DWORD processId;
DWORD threadId = GetWindowThreadProcessId(mWindow, &processId);
if (processId != GetCurrentProcessId() || threadId != GetCurrentThreadId())
{
return;
}
SetLastError(0);
LONG_PTR oldWndProc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
if(oldWndProc == 0 && GetLastError() != ERROR_SUCCESS)
{
mWindowSubclassed = false;
return;
}
SetProp(mWindow, kSurfaceProperty, reinterpret_cast<HANDLE>(this));
SetProp(mWindow, kParentWndProc, reinterpret_cast<HANDLE>(oldWndProc));
mWindowSubclassed = true;
}
void Surface::unsubclassWindow()
{
if(!mWindowSubclassed)
{
return;
}
// un-subclass
LONG_PTR parentWndFunc = reinterpret_cast<LONG_PTR>(GetProp(mWindow, kParentWndProc));
// Check the windowproc is still SurfaceWindowProc.
// If this assert fails, then it is likely the application has subclassed the
// hwnd as well and did not unsubclass before destroying its EGL context. The
// application should be modified to either subclass before initializing the
// EGL context, or to unsubclass before destroying the EGL context.
if(parentWndFunc)
{
LONG_PTR prevWndFunc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, parentWndFunc);
ASSERT(prevWndFunc == reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
}
RemoveProp(mWindow, kSurfaceProperty);
RemoveProp(mWindow, kParentWndProc);
mWindowSubclassed = false;
}
bool Surface::checkForOutOfDateSwapChain()
{
RECT client;
if (!GetClientRect(getWindowHandle(), &client))
{
ASSERT(false);
return false;
}
// Grow the buffer now, if the window has grown. We need to grow now to avoid losing information.
int clientWidth = client.right - client.left;
int clientHeight = client.bottom - client.top;
bool sizeDirty = clientWidth != getWidth() || clientHeight != getHeight();
if (IsIconic(getWindowHandle()))
{
// The window is automatically resized to 150x22 when it's minimized, but the swapchain shouldn't be resized
// because that's not a useful size to render to.
sizeDirty = false;
}
if (mSwapIntervalDirty)
{
resetSwapChain(clientWidth, clientHeight);
}
else if (sizeDirty)
{
resizeSwapChain(clientWidth, clientHeight);
}
if (mSwapIntervalDirty || sizeDirty)
{
if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
{
glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
}
return true;
}
return false;
}
bool Surface::swap()
{
return swapRect(0, 0, mWidth, mHeight);
}
bool Surface::postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mPostSubBufferSupported)
{
// Spec is not clear about how this should be handled.
return true;
}
return swapRect(x, y, width, height);
}
EGLint Surface::getWidth() const
{
return mWidth;
}
EGLint Surface::getHeight() const
{
return mHeight;
}
EGLint Surface::isPostSubBufferSupported() const
{
return mPostSubBufferSupported;
}
rx::SwapChain *Surface::getSwapChain() const
{
return mSwapChain;
}
void Surface::setSwapInterval(EGLint interval)
{
if (mSwapInterval == interval)
{
return;
}
mSwapInterval = interval;
mSwapInterval = std::max(mSwapInterval, mRenderer->getMinSwapInterval());
mSwapInterval = std::min(mSwapInterval, mRenderer->getMaxSwapInterval());
mSwapIntervalDirty = true;
}
EGLenum Surface::getTextureFormat() const
{
return mTextureFormat;
}
EGLenum Surface::getTextureTarget() const
{
return mTextureTarget;
}
void Surface::setBoundTexture(gl::Texture2D *texture)
{
mTexture = texture;
}
gl::Texture2D *Surface::getBoundTexture() const
{
return mTexture;
}
EGLenum Surface::getFormat() const
{
return mConfig->mRenderTargetFormat;
}
}
<|endoftext|> |
<commit_before>#ifndef ITER_CHUNKED_HPP_
#define ITER_CHUNKED_HPP_
#include "internal/iterbase.hpp"
#include "internal/iteratoriterator.hpp"
#include <vector>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <utility>
#include <iterator>
namespace iter {
namespace impl {
template <typename Container>
class Chunker;
using ChunkedFn = IterToolFnBindSizeTSecond<Chunker>;
}
constexpr impl::ChunkedFn chunked{};
}
template <typename Container>
class iter::impl::Chunker {
private:
Container container;
std::size_t chunk_size;
Chunker(Container&& c, std::size_t sz)
: container(std::forward<Container>(c)), chunk_size{sz} {}
friend ChunkedFn;
using IndexVector = std::vector<iterator_type<Container>>;
using DerefVec = IterIterWrapper<IndexVector>;
public:
Chunker(Chunker&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, DerefVec> {
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_end;
DerefVec chunk;
std::size_t chunk_size = 0;
bool done() const {
return this->chunk.empty();
}
void refill_chunk() {
this->chunk.get().clear();
std::size_t i{0};
while (i < chunk_size && this->sub_iter != this->sub_end) {
chunk.get().push_back(this->sub_iter);
++this->sub_iter;
++i;
}
}
public:
Iterator(iterator_type<Container>&& in_iter,
iterator_type<Container>&& in_end, std::size_t s)
: sub_iter{std::move(in_iter)},
sub_end{std::move(in_end)},
chunk_size{s} {
this->chunk.get().reserve(this->chunk_size);
this->refill_chunk();
}
Iterator& operator++() {
this->refill_chunk();
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->done() == other.done()
&& (this->done() || !(this->sub_iter != other.sub_iter));
}
DerefVec& operator*() {
return this->chunk;
}
DerefVec* operator->() {
return &this->chunk;
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container), chunk_size};
}
Iterator end() {
return {std::end(this->container), std::end(this->container), chunk_size};
}
};
#endif
<commit_msg>Supports different begin and end in chunked<commit_after>#ifndef ITER_CHUNKED_HPP_
#define ITER_CHUNKED_HPP_
#include "internal/iterbase.hpp"
#include "internal/iteratoriterator.hpp"
#include "internal/iterator_wrapper.hpp"
#include <vector>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <utility>
#include <iterator>
namespace iter {
namespace impl {
template <typename Container>
class Chunker;
using ChunkedFn = IterToolFnBindSizeTSecond<Chunker>;
}
constexpr impl::ChunkedFn chunked{};
}
template <typename Container>
class iter::impl::Chunker {
private:
Container container;
std::size_t chunk_size;
Chunker(Container&& c, std::size_t sz)
: container(std::forward<Container>(c)), chunk_size{sz} {}
friend ChunkedFn;
using IndexVector = std::vector<IteratorWrapper<Container>>;
using DerefVec = IterIterWrapper<IndexVector>;
public:
Chunker(Chunker&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, DerefVec> {
private:
IteratorWrapper<Container> sub_iter;
IteratorWrapper<Container> sub_end;
DerefVec chunk;
std::size_t chunk_size = 0;
bool done() const {
return this->chunk.empty();
}
void refill_chunk() {
this->chunk.get().clear();
std::size_t i{0};
while (i < chunk_size && this->sub_iter != this->sub_end) {
chunk.get().push_back(this->sub_iter);
++this->sub_iter;
++i;
}
}
public:
Iterator(IteratorWrapper<Container>&& in_iter,
IteratorWrapper<Container>&& in_end, std::size_t s)
: sub_iter{std::move(in_iter)},
sub_end{std::move(in_end)},
chunk_size{s} {
this->chunk.get().reserve(this->chunk_size);
this->refill_chunk();
}
Iterator& operator++() {
this->refill_chunk();
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return !(*this == other);
}
bool operator==(const Iterator& other) const {
return this->done() == other.done()
&& (this->done() || !(this->sub_iter != other.sub_iter));
}
DerefVec& operator*() {
return this->chunk;
}
DerefVec* operator->() {
return &this->chunk;
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container), chunk_size};
}
Iterator end() {
return {std::end(this->container), std::end(this->container), chunk_size};
}
};
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <RandomNumberGenerator.h>
#include "Sampler.h"
#include "MyModel.h"
using namespace std;
using namespace DNest3;
int main()
{
RandomNumberGenerator::initialise_instance();
Sampler<MyModel> s(100, 1000);
s.initialise();
for(int i=0; i<10000; i++)
s.update();
return 0;
}
<commit_msg>Seed with time<commit_after>#include <iostream>
#include <ctime>
#include <RandomNumberGenerator.h>
#include "Sampler.h"
#include "MyModel.h"
using namespace std;
using namespace DNest3;
int main()
{
// Initialise RNG and seed with time
RandomNumberGenerator::initialise_instance();
RandomNumberGenerator::get_instance().set_seed(time(0));
Sampler<MyModel> s(100, 1000);
s.initialise();
for(int i=0; i<1000; i++)
s.update();
return 0;
}
<|endoftext|> |
<commit_before>#include "config.h"
#include <cerrno>
#include <algorithm>
#include <vector>
#define _XOPEN_SOURCE 600
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include "archive.hh"
#include "util.hh"
namespace nix {
static string archiveVersion1 = "nix-archive-1";
PathFilter defaultPathFilter;
static void dump(const string & path, Sink & sink, PathFilter & filter);
static void dumpEntries(const Path & path, Sink & sink, PathFilter & filter)
{
Strings names = readDirectory(path);
vector<string> names2(names.begin(), names.end());
sort(names2.begin(), names2.end());
for (vector<string>::iterator i = names2.begin();
i != names2.end(); ++i)
{
Path entry = path + "/" + *i;
if (filter(entry)) {
writeString("entry", sink);
writeString("(", sink);
writeString("name", sink);
writeString(*i, sink);
writeString("node", sink);
dump(entry, sink, filter);
writeString(")", sink);
}
}
}
static void dumpContents(const Path & path, size_t size,
Sink & sink)
{
writeString("contents", sink);
writeLongLong(size, sink);
AutoCloseFD fd = open(path.c_str(), O_RDONLY);
if (fd == -1) throw SysError(format("opening file `%1%'") % path);
unsigned char buf[65536];
size_t left = size;
while (left > 0) {
size_t n = left > sizeof(buf) ? sizeof(buf) : left;
readFull(fd, buf, n);
left -= n;
sink(buf, n);
}
writePadding(size, sink);
}
static void dump(const Path & path, Sink & sink, PathFilter & filter)
{
struct stat st;
if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path);
writeString("(", sink);
if (S_ISREG(st.st_mode)) {
writeString("type", sink);
writeString("regular", sink);
if (st.st_mode & S_IXUSR) {
writeString("executable", sink);
writeString("", sink);
}
dumpContents(path, (size_t) st.st_size, sink);
}
else if (S_ISDIR(st.st_mode)) {
writeString("type", sink);
writeString("directory", sink);
dumpEntries(path, sink, filter);
}
else if (S_ISLNK(st.st_mode)) {
writeString("type", sink);
writeString("symlink", sink);
writeString("target", sink);
writeString(readLink(path), sink);
}
else throw Error(format("file `%1%' has an unknown type") % path);
writeString(")", sink);
}
void dumpPath(const Path & path, Sink & sink, PathFilter & filter)
{
writeString(archiveVersion1, sink);
dump(path, sink, filter);
}
static SerialisationError badArchive(string s)
{
return SerialisationError("bad archive: " + s);
}
static void skipGeneric(Source & source)
{
if (readString(source) == "(") {
while (readString(source) != ")")
skipGeneric(source);
}
}
static void parse(ParseSink & sink, Source & source, const Path & path);
static void parseEntry(ParseSink & sink, Source & source, const Path & path)
{
string s, name;
s = readString(source);
if (s != "(") throw badArchive("expected open tag");
while (1) {
checkInterrupt();
s = readString(source);
if (s == ")") {
break;
} else if (s == "name") {
name = readString(source);
} else if (s == "node") {
if (s == "") throw badArchive("entry name missing");
parse(sink, source, path + "/" + name);
} else {
throw badArchive("unknown field " + s);
skipGeneric(source);
}
}
}
static void parseContents(ParseSink & sink, Source & source, const Path & path)
{
unsigned long long size = readLongLong(source);
sink.preallocateContents(size);
unsigned long long left = size;
unsigned char buf[65536];
while (left) {
checkInterrupt();
unsigned int n = sizeof(buf);
if ((unsigned long long) n > left) n = left;
source(buf, n);
sink.receiveContents(buf, n);
left -= n;
}
readPadding(size, source);
}
static void parse(ParseSink & sink, Source & source, const Path & path)
{
string s;
s = readString(source);
if (s != "(") throw badArchive("expected open tag");
enum { tpUnknown, tpRegular, tpDirectory, tpSymlink } type = tpUnknown;
while (1) {
checkInterrupt();
s = readString(source);
if (s == ")") {
break;
}
else if (s == "type") {
if (type != tpUnknown)
throw badArchive("multiple type fields");
string t = readString(source);
if (t == "regular") {
type = tpRegular;
sink.createRegularFile(path);
}
else if (t == "directory") {
sink.createDirectory(path);
type = tpDirectory;
}
else if (t == "symlink") {
type = tpSymlink;
}
else throw badArchive("unknown file type " + t);
}
else if (s == "contents" && type == tpRegular) {
parseContents(sink, source, path);
}
else if (s == "executable" && type == tpRegular) {
readString(source);
sink.isExecutable();
}
else if (s == "entry" && type == tpDirectory) {
parseEntry(sink, source, path);
}
else if (s == "target" && type == tpSymlink) {
string target = readString(source);
sink.createSymlink(path, target);
}
else {
throw badArchive("unknown field " + s);
skipGeneric(source);
}
}
}
void parseDump(ParseSink & sink, Source & source)
{
string version;
try {
version = readString(source);
} catch (SerialisationError & e) {
/* This generally means the integer at the start couldn't be
decoded. Ignore and throw the exception below. */
}
if (version != archiveVersion1)
throw badArchive("input doesn't look like a Nix archive");
parse(sink, source, "");
}
struct RestoreSink : ParseSink
{
Path dstPath;
AutoCloseFD fd;
void createDirectory(const Path & path)
{
Path p = dstPath + path;
if (mkdir(p.c_str(), 0777) == -1)
throw SysError(format("creating directory `%1%'") % p);
};
void createRegularFile(const Path & path)
{
Path p = dstPath + path;
fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0666);
if (fd == -1) throw SysError(format("creating file `%1%'") % p);
}
void isExecutable()
{
struct stat st;
if (fstat(fd, &st) == -1)
throw SysError("fstat");
if (fchmod(fd, st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1)
throw SysError("fchmod");
}
void preallocateContents(unsigned long long len)
{
#if HAVE_POSIX_FALLOCATE
if (len) {
errno = posix_fallocate(fd, 0, len);
/* Note that EINVAL may indicate that the underlying
filesystem doesn't support preallocation (e.g. on
OpenSolaris). Since preallocation is just an
optimisation, ignore it. */
if (errno && errno != EINVAL)
throw SysError(format("preallocating file of %1% bytes") % len);
}
#endif
}
void receiveContents(unsigned char * data, unsigned int len)
{
writeFull(fd, data, len);
}
void createSymlink(const Path & path, const string & target)
{
Path p = dstPath + path;
if (symlink(target.c_str(), p.c_str()) == -1)
throw SysError(format("creating symlink `%1%'") % p);
}
};
void restorePath(const Path & path, Source & source)
{
RestoreSink sink;
sink.dstPath = path;
parseDump(sink, source);
}
}
<commit_msg>RestoreSink: Slightly reduce the number of concurrent FDs<commit_after>#include "config.h"
#include <cerrno>
#include <algorithm>
#include <vector>
#define _XOPEN_SOURCE 600
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include "archive.hh"
#include "util.hh"
namespace nix {
static string archiveVersion1 = "nix-archive-1";
PathFilter defaultPathFilter;
static void dump(const string & path, Sink & sink, PathFilter & filter);
static void dumpEntries(const Path & path, Sink & sink, PathFilter & filter)
{
Strings names = readDirectory(path);
vector<string> names2(names.begin(), names.end());
sort(names2.begin(), names2.end());
for (vector<string>::iterator i = names2.begin();
i != names2.end(); ++i)
{
Path entry = path + "/" + *i;
if (filter(entry)) {
writeString("entry", sink);
writeString("(", sink);
writeString("name", sink);
writeString(*i, sink);
writeString("node", sink);
dump(entry, sink, filter);
writeString(")", sink);
}
}
}
static void dumpContents(const Path & path, size_t size,
Sink & sink)
{
writeString("contents", sink);
writeLongLong(size, sink);
AutoCloseFD fd = open(path.c_str(), O_RDONLY);
if (fd == -1) throw SysError(format("opening file `%1%'") % path);
unsigned char buf[65536];
size_t left = size;
while (left > 0) {
size_t n = left > sizeof(buf) ? sizeof(buf) : left;
readFull(fd, buf, n);
left -= n;
sink(buf, n);
}
writePadding(size, sink);
}
static void dump(const Path & path, Sink & sink, PathFilter & filter)
{
struct stat st;
if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path);
writeString("(", sink);
if (S_ISREG(st.st_mode)) {
writeString("type", sink);
writeString("regular", sink);
if (st.st_mode & S_IXUSR) {
writeString("executable", sink);
writeString("", sink);
}
dumpContents(path, (size_t) st.st_size, sink);
}
else if (S_ISDIR(st.st_mode)) {
writeString("type", sink);
writeString("directory", sink);
dumpEntries(path, sink, filter);
}
else if (S_ISLNK(st.st_mode)) {
writeString("type", sink);
writeString("symlink", sink);
writeString("target", sink);
writeString(readLink(path), sink);
}
else throw Error(format("file `%1%' has an unknown type") % path);
writeString(")", sink);
}
void dumpPath(const Path & path, Sink & sink, PathFilter & filter)
{
writeString(archiveVersion1, sink);
dump(path, sink, filter);
}
static SerialisationError badArchive(string s)
{
return SerialisationError("bad archive: " + s);
}
static void skipGeneric(Source & source)
{
if (readString(source) == "(") {
while (readString(source) != ")")
skipGeneric(source);
}
}
static void parse(ParseSink & sink, Source & source, const Path & path);
static void parseEntry(ParseSink & sink, Source & source, const Path & path)
{
string s, name;
s = readString(source);
if (s != "(") throw badArchive("expected open tag");
while (1) {
checkInterrupt();
s = readString(source);
if (s == ")") {
break;
} else if (s == "name") {
name = readString(source);
} else if (s == "node") {
if (s == "") throw badArchive("entry name missing");
parse(sink, source, path + "/" + name);
} else {
throw badArchive("unknown field " + s);
skipGeneric(source);
}
}
}
static void parseContents(ParseSink & sink, Source & source, const Path & path)
{
unsigned long long size = readLongLong(source);
sink.preallocateContents(size);
unsigned long long left = size;
unsigned char buf[65536];
while (left) {
checkInterrupt();
unsigned int n = sizeof(buf);
if ((unsigned long long) n > left) n = left;
source(buf, n);
sink.receiveContents(buf, n);
left -= n;
}
readPadding(size, source);
}
static void parse(ParseSink & sink, Source & source, const Path & path)
{
string s;
s = readString(source);
if (s != "(") throw badArchive("expected open tag");
enum { tpUnknown, tpRegular, tpDirectory, tpSymlink } type = tpUnknown;
while (1) {
checkInterrupt();
s = readString(source);
if (s == ")") {
break;
}
else if (s == "type") {
if (type != tpUnknown)
throw badArchive("multiple type fields");
string t = readString(source);
if (t == "regular") {
type = tpRegular;
sink.createRegularFile(path);
}
else if (t == "directory") {
sink.createDirectory(path);
type = tpDirectory;
}
else if (t == "symlink") {
type = tpSymlink;
}
else throw badArchive("unknown file type " + t);
}
else if (s == "contents" && type == tpRegular) {
parseContents(sink, source, path);
}
else if (s == "executable" && type == tpRegular) {
readString(source);
sink.isExecutable();
}
else if (s == "entry" && type == tpDirectory) {
parseEntry(sink, source, path);
}
else if (s == "target" && type == tpSymlink) {
string target = readString(source);
sink.createSymlink(path, target);
}
else {
throw badArchive("unknown field " + s);
skipGeneric(source);
}
}
}
void parseDump(ParseSink & sink, Source & source)
{
string version;
try {
version = readString(source);
} catch (SerialisationError & e) {
/* This generally means the integer at the start couldn't be
decoded. Ignore and throw the exception below. */
}
if (version != archiveVersion1)
throw badArchive("input doesn't look like a Nix archive");
parse(sink, source, "");
}
struct RestoreSink : ParseSink
{
Path dstPath;
AutoCloseFD fd;
void createDirectory(const Path & path)
{
Path p = dstPath + path;
if (mkdir(p.c_str(), 0777) == -1)
throw SysError(format("creating directory `%1%'") % p);
};
void createRegularFile(const Path & path)
{
Path p = dstPath + path;
fd.close();
fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0666);
if (fd == -1) throw SysError(format("creating file `%1%'") % p);
}
void isExecutable()
{
struct stat st;
if (fstat(fd, &st) == -1)
throw SysError("fstat");
if (fchmod(fd, st.st_mode | (S_IXUSR | S_IXGRP | S_IXOTH)) == -1)
throw SysError("fchmod");
}
void preallocateContents(unsigned long long len)
{
#if HAVE_POSIX_FALLOCATE
if (len) {
errno = posix_fallocate(fd, 0, len);
/* Note that EINVAL may indicate that the underlying
filesystem doesn't support preallocation (e.g. on
OpenSolaris). Since preallocation is just an
optimisation, ignore it. */
if (errno && errno != EINVAL)
throw SysError(format("preallocating file of %1% bytes") % len);
}
#endif
}
void receiveContents(unsigned char * data, unsigned int len)
{
writeFull(fd, data, len);
}
void createSymlink(const Path & path, const string & target)
{
Path p = dstPath + path;
if (symlink(target.c_str(), p.c_str()) == -1)
throw SysError(format("creating symlink `%1%'") % p);
}
};
void restorePath(const Path & path, Source & source)
{
RestoreSink sink;
sink.dstPath = path;
parseDump(sink, source);
}
}
<|endoftext|> |
<commit_before>#ifndef line_and_column_hh_INCLUDED
#define line_and_column_hh_INCLUDED
namespace Kakoune
{
template<typename EffectiveType>
struct LineAndColumn
{
int line;
int column;
LineAndColumn(int line = 0, int column = 0)
: line(line), column(column) {}
EffectiveType operator+(const EffectiveType& other) const
{
return EffectiveType(line + other.line, column + other.column);
}
EffectiveType& operator+=(const EffectiveType& other)
{
line += other.line;
column += other.column;
return *static_cast<EffectiveType*>(this);
}
EffectiveType operator-(const EffectiveType& other) const
{
return EffectiveType(line + other.line, column + other.column);
}
EffectiveType& operator-=(const EffectiveType& other)
{
line += other.line;
column += other.column;
return *static_cast<EffectiveType*>(this);
}
};
}
#endif // line_and_column_hh_INCLUDED
<commit_msg>LineAndColumn: add comparison operators<commit_after>#ifndef line_and_column_hh_INCLUDED
#define line_and_column_hh_INCLUDED
namespace Kakoune
{
template<typename EffectiveType>
struct LineAndColumn
{
int line;
int column;
LineAndColumn(int line = 0, int column = 0)
: line(line), column(column) {}
EffectiveType operator+(const EffectiveType& other) const
{
return EffectiveType(line + other.line, column + other.column);
}
EffectiveType& operator+=(const EffectiveType& other)
{
line += other.line;
column += other.column;
return *static_cast<EffectiveType*>(this);
}
EffectiveType operator-(const EffectiveType& other) const
{
return EffectiveType(line - other.line, column - other.column);
}
EffectiveType& operator-=(const EffectiveType& other)
{
line -= other.line;
column -= other.column;
return *static_cast<EffectiveType*>(this);
}
bool operator< (const EffectiveType& other) const
{
if (line != other.line)
return line < other.line;
return column < other.column;
}
bool operator<= (const EffectiveType& other) const
{
if (line != other.line)
return line < other.line;
return column <= other.column;
}
bool operator== (const EffectiveType& other) const
{
return line == other.line and column == other.column;
}
};
}
#endif // line_and_column_hh_INCLUDED
<|endoftext|> |
<commit_before>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "InteractiveNotifications.h"
#include <NotificationActivationCallback.h>
#include <Shellapi.h>
#include <string>
#include <iostream>
#include <SDKDDKVer.h>
#include <Windows.h>
#include <Psapi.h>
#include <strsafe.h>
#include <ShObjIdl.h>
#include <Shlobj.h>
#include <Pathcch.h>
#include <propvarutil.h>
#include <propkey.h>
#include <wchar.h>
#include <wrl.h>
#include <wrl\wrappers\corewrappers.h>
#include <windows.ui.notifications.h>
// Correct flow
// RegisterAppForNotificationSupport()
// RegisterActivator()
// Name: System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID
// Type: Guid -- VT_CLSID
// FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26
//
// Used to CoCreate an INotificationActivationCallback interface to notify about toast activations.
EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 };
using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::UI::Notifications;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
struct CoTaskMemStringTraits
{
typedef PWSTR Type;
inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; }
inline static Type GetInvalidValue() throw() { return nullptr; }
};
typedef HandleT<CoTaskMemStringTraits> CoTaskMemString;
const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)";
#define __CSID "A23D2B18-8DD7-403A-B9B7-152B40A1478C"
// For the app to be activated from Action Center, it needs to provide a COM server to be called
// when the notification is activated. The CLSID of the object needs to be registered with the
// OS via its shortcut so that it knows who to call later.
class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal
: public RuntimeClass < RuntimeClassFlags<ClassicCom>,
INotificationActivationCallback >
{
public:
virtual HRESULT STDMETHODCALLTYPE Activate(
_In_ LPCWSTR appUserModelId,
_In_ LPCWSTR invokedArgs,
_In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data,
ULONG dataCount) override
{
std::string args;
for (int i = 0; i < dataCount; i++) {
LPCWSTR lvalue = data[i].Value;
LPCWSTR lkey = data[i].Key;
std::wstring wvalue(lvalue);
std::wstring wkey(lkey);
std::string value(wvalue.begin(), wvalue.end());
std::string key(wkey.begin(), wkey.end());
args = args + "\"key\":\"" + key + "\"";
args = args + ",\"value\":\"" + value + "\"";
}
std::string escapedArgs = "";
for (char ch : args) {
switch (ch) {
case ' ': escapedArgs += "%20"; break;
case '&': escapedArgs += "^&"; break;
case '\\': escapedArgs += "^\\"; break;
case '<': escapedArgs += "^<"; break;
case '>': escapedArgs += "^>"; break;
case '|': escapedArgs += "^|"; break;
case '^': escapedArgs += "^^"; break;
case '"': escapedArgs += "^%22"; break;
default: escapedArgs += ch; break;
}
}
std::wstring wToastArgs(invokedArgs);
std::string toastArgs(wToastArgs.begin(), wToastArgs.end());
// CMD needs stuff escaped, so we'll do that here
std::string escapedToastArgs = "";
for (char ch : toastArgs) {
switch (ch) {
case ' ': escapedToastArgs += "%20"; break;
case '&': escapedToastArgs += "^&"; break;
case '\\': escapedToastArgs += "^\\"; break;
case '<': escapedToastArgs += "^<"; break;
case '>': escapedToastArgs += "^>"; break;
case '|': escapedToastArgs += "^|"; break;
case '^': escapedToastArgs += "^^"; break;
case '"': escapedToastArgs += "%22"; break;
default: escapedToastArgs += ch; break;
}
}
std::string cmdLine = "cmd.exe \"start slack://" + escapedToastArgs + "^&userData=[{" + escapedArgs + "}]\"";
WinExec(cmdLine.c_str(), SW_HIDE);
return HRESULT();
}
};
CoCreatableClass(NotificationActivator);
namespace InteractiveNotifications
{
INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
{
CoTaskMemString appData;
auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf());
if (SUCCEEDED(hr))
{
wchar_t shortcutPath[MAX_PATH];
// Todo: Don't hardcode the path
hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut);
if (SUCCEEDED(hr))
{
DWORD attributes = ::GetFileAttributes(shortcutPath);
bool fileExists = attributes < 0xFFFFFFF;
if (!fileExists)
{
// Todo: This is probably the wrong path bc Squirrel
wchar_t exePath[MAX_PATH];
DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath));
hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError());
if (SUCCEEDED(hr))
{
hr = InstallShortcut(shortcutPath, exePath, appId);
if (SUCCEEDED(hr))
{
hr = RegisterComServer(exePath);
}
}
}
}
}
return hr;
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId)
{
ComPtr<IShellLink> shellLink;
HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));
if (!SUCCEEDED(hr)) return hr;
hr = shellLink->SetPath(exePath);
if (!SUCCEEDED(hr)) return hr;
ComPtr<IPropertyStore> propertyStore;
hr = shellLink.As(&propertyStore);
if (!SUCCEEDED(hr)) return hr;
PROPVARIANT propVar;
propVar.vt = VT_LPWSTR;
propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy
hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar);
if (!SUCCEEDED(hr)) return hr;
propVar.vt = VT_CLSID;
propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator));
hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar);
if (!SUCCEEDED(hr)) return hr;
hr = propertyStore->Commit();
if (!SUCCEEDED(hr)) return hr;
ComPtr<IPersistFile> persistFile;
hr = shellLink.As(&persistFile);
if (!SUCCEEDED(hr)) return hr;
hr = persistFile->Save(shortcutPath, TRUE);
return hr;
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath)
{
// We don't need to worry about overflow here as ::GetModuleFileName won't
// return anything bigger than the max file system path (much fewer than max of DWORD).
DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR));
auto key = LR"(SOFTWARE\Classes\CLSID\{A23D2B18-8DD7-403A-B9B7-152B40A1478C}\LocalServer32)";
return HRESULT_FROM_WIN32(::RegSetKeyValue(
HKEY_CURRENT_USER,
key,
nullptr,
REG_SZ,
reinterpret_cast<const BYTE*>(exePath),
dataSize));
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator()
{
// Module<OutOfProc> needs a callback registered before it can be used.
// Since we don't care about when it shuts down, we'll pass an empty lambda here.
// If we need to clean up, do it here (we probably don't have to)
Module<OutOfProc>::Create([] {});
// If a local server process only hosts the COM object then COM expects
// the COM server host to shutdown when the references drop to zero.
// Since the user might still be using the program after activating the notification,
// we don't want to shutdown immediately. Incrementing the object count tells COM that
// we aren't done yet.
Module<OutOfProc>::GetModule().IncrementObjectCount();
return Module<OutOfProc>::GetModule().RegisterObjects();
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API void UnregisterActivator()
{
Module<OutOfProc>::GetModule().UnregisterObjects();
Module<OutOfProc>::GetModule().DecrementObjectCount();
}
}
extern "C"
{
__declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
{
InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId);
}
__declspec(dllexport) void CRegisterActivator()
{
InteractiveNotifications::RegisterActivator();
}
__declspec(dllexport) void CUnregisterActivator()
{
InteractiveNotifications::UnregisterActivator();
}
}<commit_msg>:wrench: Ooops actually start<commit_after>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "InteractiveNotifications.h"
#include <NotificationActivationCallback.h>
#include <Shellapi.h>
#include <string>
#include <iostream>
#include <SDKDDKVer.h>
#include <Windows.h>
#include <Psapi.h>
#include <strsafe.h>
#include <ShObjIdl.h>
#include <Shlobj.h>
#include <Pathcch.h>
#include <propvarutil.h>
#include <propkey.h>
#include <wchar.h>
#include <wrl.h>
#include <wrl\wrappers\corewrappers.h>
#include <windows.ui.notifications.h>
// Correct flow
// RegisterAppForNotificationSupport()
// RegisterActivator()
// Name: System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID
// Type: Guid -- VT_CLSID
// FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26
//
// Used to CoCreate an INotificationActivationCallback interface to notify about toast activations.
EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 };
using namespace ABI::Windows::Data::Xml::Dom;
using namespace ABI::Windows::UI::Notifications;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
struct CoTaskMemStringTraits
{
typedef PWSTR Type;
inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; }
inline static Type GetInvalidValue() throw() { return nullptr; }
};
typedef HandleT<CoTaskMemStringTraits> CoTaskMemString;
const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)";
#define __CSID "A23D2B18-8DD7-403A-B9B7-152B40A1478C"
// For the app to be activated from Action Center, it needs to provide a COM server to be called
// when the notification is activated. The CLSID of the object needs to be registered with the
// OS via its shortcut so that it knows who to call later.
class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal
: public RuntimeClass < RuntimeClassFlags<ClassicCom>,
INotificationActivationCallback >
{
public:
virtual HRESULT STDMETHODCALLTYPE Activate(
_In_ LPCWSTR appUserModelId,
_In_ LPCWSTR invokedArgs,
_In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data,
ULONG dataCount) override
{
std::string args;
for (int i = 0; i < dataCount; i++) {
LPCWSTR lvalue = data[i].Value;
LPCWSTR lkey = data[i].Key;
std::wstring wvalue(lvalue);
std::wstring wkey(lkey);
std::string value(wvalue.begin(), wvalue.end());
std::string key(wkey.begin(), wkey.end());
args = args + "\"key\":\"" + key + "\"";
args = args + ",\"value\":\"" + value + "\"";
}
std::string escapedArgs = "";
for (char ch : args) {
switch (ch) {
case ' ': escapedArgs += "%20"; break;
case '&': escapedArgs += "^&"; break;
case '\\': escapedArgs += "^\\"; break;
case '<': escapedArgs += "^<"; break;
case '>': escapedArgs += "^>"; break;
case '|': escapedArgs += "^|"; break;
case '^': escapedArgs += "^^"; break;
case '"': escapedArgs += "^%22"; break;
default: escapedArgs += ch; break;
}
}
std::wstring wToastArgs(invokedArgs);
std::string toastArgs(wToastArgs.begin(), wToastArgs.end());
// CMD needs stuff escaped, so we'll do that here
std::string escapedToastArgs = "";
for (char ch : toastArgs) {
switch (ch) {
case ' ': escapedToastArgs += "%20"; break;
case '&': escapedToastArgs += "^&"; break;
case '\\': escapedToastArgs += "^\\"; break;
case '<': escapedToastArgs += "^<"; break;
case '>': escapedToastArgs += "^>"; break;
case '|': escapedToastArgs += "^|"; break;
case '^': escapedToastArgs += "^^"; break;
case '"': escapedToastArgs += "%22"; break;
default: escapedToastArgs += ch; break;
}
}
std::string cmdLine = "cmd.exe /C \"start slack://" + escapedToastArgs + "^&userData=[{" + escapedArgs + "}]\"";
WinExec(cmdLine.c_str(), SW_HIDE);
return HRESULT();
}
};
CoCreatableClass(NotificationActivator);
namespace InteractiveNotifications
{
INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
{
CoTaskMemString appData;
auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf());
if (SUCCEEDED(hr))
{
wchar_t shortcutPath[MAX_PATH];
// Todo: Don't hardcode the path
hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut);
if (SUCCEEDED(hr))
{
DWORD attributes = ::GetFileAttributes(shortcutPath);
bool fileExists = attributes < 0xFFFFFFF;
if (!fileExists)
{
// Todo: This is probably the wrong path bc Squirrel
wchar_t exePath[MAX_PATH];
DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath));
hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError());
if (SUCCEEDED(hr))
{
hr = InstallShortcut(shortcutPath, exePath, appId);
if (SUCCEEDED(hr))
{
hr = RegisterComServer(exePath);
}
}
}
}
}
return hr;
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId)
{
ComPtr<IShellLink> shellLink;
HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink));
if (!SUCCEEDED(hr)) return hr;
hr = shellLink->SetPath(exePath);
if (!SUCCEEDED(hr)) return hr;
ComPtr<IPropertyStore> propertyStore;
hr = shellLink.As(&propertyStore);
if (!SUCCEEDED(hr)) return hr;
PROPVARIANT propVar;
propVar.vt = VT_LPWSTR;
propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy
hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar);
if (!SUCCEEDED(hr)) return hr;
propVar.vt = VT_CLSID;
propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator));
hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar);
if (!SUCCEEDED(hr)) return hr;
hr = propertyStore->Commit();
if (!SUCCEEDED(hr)) return hr;
ComPtr<IPersistFile> persistFile;
hr = shellLink.As(&persistFile);
if (!SUCCEEDED(hr)) return hr;
hr = persistFile->Save(shortcutPath, TRUE);
return hr;
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath)
{
// We don't need to worry about overflow here as ::GetModuleFileName won't
// return anything bigger than the max file system path (much fewer than max of DWORD).
DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR));
auto key = LR"(SOFTWARE\Classes\CLSID\{A23D2B18-8DD7-403A-B9B7-152B40A1478C}\LocalServer32)";
return HRESULT_FROM_WIN32(::RegSetKeyValue(
HKEY_CURRENT_USER,
key,
nullptr,
REG_SZ,
reinterpret_cast<const BYTE*>(exePath),
dataSize));
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator()
{
// Module<OutOfProc> needs a callback registered before it can be used.
// Since we don't care about when it shuts down, we'll pass an empty lambda here.
// If we need to clean up, do it here (we probably don't have to)
Module<OutOfProc>::Create([] {});
// If a local server process only hosts the COM object then COM expects
// the COM server host to shutdown when the references drop to zero.
// Since the user might still be using the program after activating the notification,
// we don't want to shutdown immediately. Incrementing the object count tells COM that
// we aren't done yet.
Module<OutOfProc>::GetModule().IncrementObjectCount();
return Module<OutOfProc>::GetModule().RegisterObjects();
}
_Use_decl_annotations_
INTERACTIVENOTIFICATIONS_API void UnregisterActivator()
{
Module<OutOfProc>::GetModule().UnregisterObjects();
Module<OutOfProc>::GetModule().DecrementObjectCount();
}
}
extern "C"
{
__declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId)
{
InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId);
}
__declspec(dllexport) void CRegisterActivator()
{
InteractiveNotifications::RegisterActivator();
}
__declspec(dllexport) void CUnregisterActivator()
{
InteractiveNotifications::UnregisterActivator();
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: XmlFilterAdaptor.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2002-10-10 13:32:48 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _XMLFILTERADAPTOR_HXX
#define _XMLFILTERADAPTOR_HXX
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
enum FilterType
{
FILTER_IMPORT,
FILTER_EXPORT
};
/* This component will be instantiated for both import or export. Whether it calls
* setSourceDocument or setTargetDocument determines which Impl function the filter
* member calls */
class XmlFilterAdaptor : public cppu::WeakImplHelper5
<
com::sun::star::document::XFilter,
com::sun::star::document::XExporter,
com::sun::star::document::XImporter,
com::sun::star::lang::XInitialization,
com::sun::star::lang::XServiceInfo
>
{
protected:
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > mxDoc;
::rtl::OUString msFilterName;
::com::sun::star::uno::Sequence< ::rtl::OUString > msUserData;
::rtl::OUString msTemplateName;
FilterType meType;
sal_Bool SAL_CALL exportImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL importImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
throw (::com::sun::star::uno::RuntimeException);
public:
XmlFilterAdaptor( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &rxMSF)
: mxMSF( rxMSF ) {}
virtual ~XmlFilterAdaptor() {}
// XFilter
virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL cancel( )
throw (::com::sun::star::uno::RuntimeException);
// XExporter
virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XImporter
virtual void SAL_CALL setTargetDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
throw (::com::sun::star::uno::RuntimeException);
};
::rtl::OUString XmlFilterAdaptor_getImplementationName()
throw ( ::com::sun::star::uno::RuntimeException );
sal_Bool SAL_CALL XmlFilterAdaptor_supportsService( const ::rtl::OUString& ServiceName )
throw ( ::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL XmlFilterAdaptor_getSupportedServiceNames( )
throw ( ::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL XmlFilterAdaptor_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr)
throw ( ::com::sun::star::uno::Exception );
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.552); FILE MERGED 2005/09/05 14:31:13 rt 1.4.552.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XmlFilterAdaptor.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 21:57:58 $
*
* 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 _XMLFILTERADAPTOR_HXX
#define _XMLFILTERADAPTOR_HXX
#ifndef _COM_SUN_STAR_DOCUMENT_XFILTER_HPP_
#include <com/sun/star/document/XFilter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEXPORTER_HPP_
#include <com/sun/star/document/XExporter.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XIMPORTER_HPP_
#include <com/sun/star/document/XImporter.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE5_HXX_
#include <cppuhelper/implbase5.hxx>
#endif
enum FilterType
{
FILTER_IMPORT,
FILTER_EXPORT
};
/* This component will be instantiated for both import or export. Whether it calls
* setSourceDocument or setTargetDocument determines which Impl function the filter
* member calls */
class XmlFilterAdaptor : public cppu::WeakImplHelper5
<
com::sun::star::document::XFilter,
com::sun::star::document::XExporter,
com::sun::star::document::XImporter,
com::sun::star::lang::XInitialization,
com::sun::star::lang::XServiceInfo
>
{
protected:
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF;
::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > mxDoc;
::rtl::OUString msFilterName;
::com::sun::star::uno::Sequence< ::rtl::OUString > msUserData;
::rtl::OUString msTemplateName;
FilterType meType;
sal_Bool SAL_CALL exportImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
throw (::com::sun::star::uno::RuntimeException);
sal_Bool SAL_CALL importImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
throw (::com::sun::star::uno::RuntimeException);
public:
XmlFilterAdaptor( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &rxMSF)
: mxMSF( rxMSF ) {}
virtual ~XmlFilterAdaptor() {}
// XFilter
virtual sal_Bool SAL_CALL filter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor )
throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL cancel( )
throw (::com::sun::star::uno::RuntimeException);
// XExporter
virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XImporter
virtual void SAL_CALL setTargetDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc )
throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName( )
throw (::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
throw (::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
throw (::com::sun::star::uno::RuntimeException);
};
::rtl::OUString XmlFilterAdaptor_getImplementationName()
throw ( ::com::sun::star::uno::RuntimeException );
sal_Bool SAL_CALL XmlFilterAdaptor_supportsService( const ::rtl::OUString& ServiceName )
throw ( ::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL XmlFilterAdaptor_getSupportedServiceNames( )
throw ( ::com::sun::star::uno::RuntimeException );
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
SAL_CALL XmlFilterAdaptor_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr)
throw ( ::com::sun::star::uno::Exception );
#endif
<|endoftext|> |
<commit_before>//
// InstanceDlg.cpp
//
// Copyright (c) 2003-2006 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/filename.h>
#include "InstanceDlg.h"
#include "vtdata/Content.h"
#include "vtdata/FilePath.h"
#include "vtdata/vtLog.h"
#include "vtui/Helper.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// InstanceDlg
//----------------------------------------------------------------------------
// WDR: event table for InstanceDlg
BEGIN_EVENT_TABLE(InstanceDlg, AutoDialog)
EVT_INIT_DIALOG (InstanceDlg::OnInitDialog)
EVT_RADIOBUTTON( ID_RADIO_CONTENT, InstanceDlg::OnRadio )
EVT_RADIOBUTTON( ID_RADIO_MODEL, InstanceDlg::OnRadio )
EVT_CHOICE( ID_CHOICE_FILE, InstanceDlg::OnChoice )
EVT_CHOICE( ID_CHOICE_TYPE, InstanceDlg::OnChoice )
EVT_CHOICE( ID_CHOICE_ITEM, InstanceDlg::OnChoiceItem )
EVT_BUTTON( ID_BROWSE_MODEL_FILE, InstanceDlg::OnBrowseModelFile )
EVT_TEXT( ID_LOCATION, InstanceDlg::OnLocationText )
END_EVENT_TABLE()
InstanceDlg::InstanceDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
// WDR: dialog function InstanceDialogFunc for InstanceDlg
InstanceDialogFunc( this, TRUE );
m_bContent = true;
m_iManager = 0;
m_iItem = 0;
AddValidator(ID_RADIO_CONTENT, &m_bContent);
AddValidator(ID_CHOICE_FILE, &m_iManager);
AddValidator(ID_CHOICE_ITEM, &m_iItem);
}
void InstanceDlg::UpdateLoc()
{
LinearUnits lu = m_proj.GetUnits();
wxString str;
if (lu == LU_DEGREES)
str.Printf(_T("%lf, %lf"), m_pos.x, m_pos.y);
else
str.Printf(_T("%.2lf, %.2lf"), m_pos.x, m_pos.y);
GetLocation()->SetValue(str);
}
void InstanceDlg::SetLocation(const DPoint2 &pos)
{
m_pos = pos;
UpdateLoc();
}
vtTagArray *InstanceDlg::GetTagArray()
{
m_dummy.Clear();
// Return a description of the current content item
if (m_bContent)
{
vtContentManager *cman = Current();
if (!cman)
return NULL;
if (m_iItem >= (int) cman->NumItems())
return NULL;
vtItem *item = cman->GetItem(m_iItem);
if (!item)
return NULL;
m_dummy.SetValueString("itemname", item->m_name, true);
}
else
{
wxString str = GetModelFile()->GetValue();
m_dummy.SetValueString("filename", (const char *) str.mb_str(wxConvUTF8), true);
}
return &m_dummy;
}
void InstanceDlg::UpdateEnabling()
{
GetChoiceFile()->Enable(m_bContent);
GetChoiceType()->Enable(m_bContent);
GetChoiceItem()->Enable(m_bContent);
GetModelFile()->Enable(!m_bContent);
GetBrowseModelFile()->Enable(!m_bContent);
}
void InstanceDlg::UpdateContentItems()
{
GetChoiceItem()->Clear();
// for (int i = 0; i < m_contents.size(); i++)
// {
vtContentManager *mng = Current();
if (!mng)
return;
wxString str;
for (unsigned int j = 0; j < mng->NumItems(); j++)
{
vtItem *item = mng->GetItem(j);
str = wxString(item->m_name, wxConvUTF8);
// str += _T(" (");
// str += item->GetValue("filename");
// str += _T(")");
GetChoiceItem()->Append(str);
}
// }
GetChoiceItem()->SetSelection(0);
}
void InstanceDlg::ClearContent()
{
m_contents.clear();
}
void InstanceDlg::AddContent(vtContentManager *mng)
{
m_contents.push_back(mng);
}
// WDR: handler implementations for InstanceDlg
void InstanceDlg::OnInitDialog(wxInitDialogEvent& event)
{
GetChoiceFile()->Clear();
for (unsigned int i = 0; i < m_contents.size(); i++)
{
vtContentManager *mng = m_contents[i];
vtString str = mng->GetFilename();
wxString ws(str, wxConvUTF8);
GetChoiceFile()->Append(ws);
}
GetChoiceFile()->Select(0);
GetChoiceType()->Clear();
GetChoiceType()->Append(_("(All)"));
GetChoiceType()->Select(0);
UpdateLoc();
UpdateEnabling();
UpdateContentItems();
wxDialog::OnInitDialog(event);
}
void InstanceDlg::OnLocationText( wxCommandEvent &event )
{
// todo? only for edit
}
void InstanceDlg::OnBrowseModelFile( wxCommandEvent &event )
{
wxString filter;
filter += _("3D Model files");
filter += _T(" (*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive)|*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive|");
filter += _("All files");
filter += _T(" (*.*)|*.*");
wxFileDialog SelectFile(this, _T("Choose model file"),
_T(""), _T(""), filter, wxFD_OPEN);
if (SelectFile.ShowModal() != wxID_OK)
return;
// If model file can be found by mimicing the search strategy implemented by
// vtStructInstance3d::CreateNode then remove the directory part of the path
// so that paths are not stored unnecessarily
wxFileName TargetModel(SelectFile.GetPath());
TargetModel.SetPath(wxT("BuildingModels"));
vtString FoundModel = FindFileOnPaths(m_DataPaths, TargetModel.GetFullName().mb_str(wxConvUTF8));
if ("" == FoundModel)
FoundModel = FindFileOnPaths(m_DataPaths, wxString(TargetModel.GetPath(wxPATH_GET_SEPARATOR) + TargetModel.GetFullName()).mb_str(wxConvUTF8));
if ("" != FoundModel)
GetModelFile()->SetValue(TargetModel.GetFullName());
else
GetModelFile()->SetValue(TargetModel.GetFullPath());
}
void InstanceDlg::OnChoice( wxCommandEvent &event )
{
TransferDataFromWindow();
UpdateContentItems();
}
void InstanceDlg::OnChoiceItem( wxCommandEvent &event )
{
TransferDataFromWindow();
}
void InstanceDlg::OnRadio( wxCommandEvent &event )
{
TransferDataFromWindow();
UpdateEnabling();
}
vtContentManager *InstanceDlg::Current()
{
if (m_iManager < (int) m_contents.size())
return m_contents[m_iManager];
return NULL;
}
<commit_msg>added safety check<commit_after>//
// InstanceDlg.cpp
//
// Copyright (c) 2003-2007 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/filename.h>
#include "InstanceDlg.h"
#include "vtdata/Content.h"
#include "vtdata/FilePath.h"
#include "vtdata/vtLog.h"
#include "vtui/Helper.h"
// WDR: class implementations
//----------------------------------------------------------------------------
// InstanceDlg
//----------------------------------------------------------------------------
// WDR: event table for InstanceDlg
BEGIN_EVENT_TABLE(InstanceDlg, AutoDialog)
EVT_INIT_DIALOG (InstanceDlg::OnInitDialog)
EVT_RADIOBUTTON( ID_RADIO_CONTENT, InstanceDlg::OnRadio )
EVT_RADIOBUTTON( ID_RADIO_MODEL, InstanceDlg::OnRadio )
EVT_CHOICE( ID_CHOICE_FILE, InstanceDlg::OnChoice )
EVT_CHOICE( ID_CHOICE_TYPE, InstanceDlg::OnChoice )
EVT_CHOICE( ID_CHOICE_ITEM, InstanceDlg::OnChoiceItem )
EVT_BUTTON( ID_BROWSE_MODEL_FILE, InstanceDlg::OnBrowseModelFile )
EVT_TEXT( ID_LOCATION, InstanceDlg::OnLocationText )
END_EVENT_TABLE()
InstanceDlg::InstanceDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
// WDR: dialog function InstanceDialogFunc for InstanceDlg
InstanceDialogFunc( this, TRUE );
m_bContent = true;
m_iManager = 0;
m_iItem = 0;
AddValidator(ID_RADIO_CONTENT, &m_bContent);
AddValidator(ID_CHOICE_FILE, &m_iManager);
AddValidator(ID_CHOICE_ITEM, &m_iItem);
}
void InstanceDlg::UpdateLoc()
{
LinearUnits lu = m_proj.GetUnits();
wxString str;
if (lu == LU_DEGREES)
str.Printf(_T("%lf, %lf"), m_pos.x, m_pos.y);
else
str.Printf(_T("%.2lf, %.2lf"), m_pos.x, m_pos.y);
GetLocation()->SetValue(str);
}
void InstanceDlg::SetLocation(const DPoint2 &pos)
{
m_pos = pos;
UpdateLoc();
}
vtTagArray *InstanceDlg::GetTagArray()
{
if (m_iItem == -1)
return NULL;
m_dummy.Clear();
// Return a description of the current content item
if (m_bContent)
{
vtContentManager *cman = Current();
if (!cman)
return NULL;
if (m_iItem >= (int) cman->NumItems())
return NULL;
vtItem *item = cman->GetItem(m_iItem);
if (!item)
return NULL;
m_dummy.SetValueString("itemname", item->m_name, true);
}
else
{
wxString str = GetModelFile()->GetValue();
m_dummy.SetValueString("filename", (const char *) str.mb_str(wxConvUTF8), true);
}
return &m_dummy;
}
void InstanceDlg::UpdateEnabling()
{
GetChoiceFile()->Enable(m_bContent);
GetChoiceType()->Enable(m_bContent);
GetChoiceItem()->Enable(m_bContent);
GetModelFile()->Enable(!m_bContent);
GetBrowseModelFile()->Enable(!m_bContent);
}
void InstanceDlg::UpdateContentItems()
{
GetChoiceItem()->Clear();
// for (int i = 0; i < m_contents.size(); i++)
// {
vtContentManager *mng = Current();
if (!mng)
return;
wxString str;
for (unsigned int j = 0; j < mng->NumItems(); j++)
{
vtItem *item = mng->GetItem(j);
str = wxString(item->m_name, wxConvUTF8);
// str += _T(" (");
// str += item->GetValue("filename");
// str += _T(")");
GetChoiceItem()->Append(str);
}
// }
GetChoiceItem()->SetSelection(0);
}
void InstanceDlg::ClearContent()
{
m_contents.clear();
}
void InstanceDlg::AddContent(vtContentManager *mng)
{
m_contents.push_back(mng);
}
// WDR: handler implementations for InstanceDlg
void InstanceDlg::OnInitDialog(wxInitDialogEvent& event)
{
GetChoiceFile()->Clear();
for (unsigned int i = 0; i < m_contents.size(); i++)
{
vtContentManager *mng = m_contents[i];
vtString str = mng->GetFilename();
wxString ws(str, wxConvUTF8);
GetChoiceFile()->Append(ws);
}
GetChoiceFile()->Select(0);
GetChoiceType()->Clear();
GetChoiceType()->Append(_("(All)"));
GetChoiceType()->Select(0);
UpdateLoc();
UpdateEnabling();
UpdateContentItems();
wxDialog::OnInitDialog(event);
}
void InstanceDlg::OnLocationText( wxCommandEvent &event )
{
// todo? only for edit
}
void InstanceDlg::OnBrowseModelFile( wxCommandEvent &event )
{
wxString filter;
filter += _("3D Model files");
filter += _T(" (*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive)|*.3ds;*.obj;*.lwo;*.flt;*.osg;*.ive|");
filter += _("All files");
filter += _T(" (*.*)|*.*");
wxFileDialog SelectFile(this, _T("Choose model file"),
_T(""), _T(""), filter, wxFD_OPEN);
if (SelectFile.ShowModal() != wxID_OK)
return;
// If model file can be found by mimicing the search strategy implemented by
// vtStructInstance3d::CreateNode then remove the directory part of the path
// so that paths are not stored unnecessarily
wxFileName TargetModel(SelectFile.GetPath());
TargetModel.SetPath(wxT("BuildingModels"));
vtString FoundModel = FindFileOnPaths(m_DataPaths, TargetModel.GetFullName().mb_str(wxConvUTF8));
if ("" == FoundModel)
FoundModel = FindFileOnPaths(m_DataPaths, wxString(TargetModel.GetPath(wxPATH_GET_SEPARATOR) + TargetModel.GetFullName()).mb_str(wxConvUTF8));
if ("" != FoundModel)
GetModelFile()->SetValue(TargetModel.GetFullName());
else
GetModelFile()->SetValue(TargetModel.GetFullPath());
}
void InstanceDlg::OnChoice( wxCommandEvent &event )
{
TransferDataFromWindow();
UpdateContentItems();
}
void InstanceDlg::OnChoiceItem( wxCommandEvent &event )
{
TransferDataFromWindow();
}
void InstanceDlg::OnRadio( wxCommandEvent &event )
{
TransferDataFromWindow();
UpdateEnabling();
}
vtContentManager *InstanceDlg::Current()
{
if (m_iManager < (int) m_contents.size())
return m_contents[m_iManager];
return NULL;
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <deque>
#include <string>
#include <process/socket.hpp>
#include <stout/gtest.hpp>
#include "decoder.hpp"
using namespace process;
using namespace process::http;
using std::deque;
using std::string;
using process::network::Socket;
TEST(Decoder, Request)
{
Try<Socket> socket = Socket::create();
ASSERT_SOME(socket);
DataDecoder decoder = DataDecoder(socket.get());
const string& data =
"GET /path/file.json?key1=value1&key2=value2#fragment HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: close\r\n"
"Accept-Encoding: compress, gzip\r\n"
"\r\n";
deque<Request*> requests = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, requests.size());
Request* request = requests[0];
EXPECT_EQ("GET", request->method);
EXPECT_EQ("/path/file.json", request->path);
EXPECT_EQ("/path/file.json?key1=value1&key2=value2#fragment", request->url);
EXPECT_EQ("fragment", request->fragment);
EXPECT_TRUE(request->body.empty());
EXPECT_FALSE(request->keepAlive);
EXPECT_EQ(3, request->headers.size());
EXPECT_SOME_EQ("localhost", request->headers.get("Host"));
EXPECT_SOME_EQ("close", request->headers.get("Connection"));
EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));
EXPECT_EQ(2, request->query.size());
EXPECT_SOME_EQ("value1", request->query.get("key1"));
EXPECT_SOME_EQ("value2", request->query.get("key2"));
delete request;
}
TEST(Decoder, RequestHeaderContinuation)
{
Try<Socket> socket = Socket::create();
ASSERT_SOME(socket);
DataDecoder decoder = DataDecoder(socket.get());
const string& data =
"GET /path/file.json HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: close\r\n"
"Accept-Encoding: compress,"
" gzip\r\n"
"\r\n";
deque<Request*> requests = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, requests.size());
Request* request = requests[0];
EXPECT_SOME_EQ("compress, gzip",
request->headers.get("Accept-Encoding"));
delete request;
}
// This is expected to fail for now, see my TODO(bmahler) on http::Request.
TEST(Decoder, DISABLED_RequestHeaderCaseInsensitive)
{
Try<Socket> socket = Socket::create();
ASSERT_SOME(socket);
DataDecoder decoder = DataDecoder(socket.get());
const string& data =
"GET /path/file.json HTTP/1.1\r\n"
"Host: localhost\r\n"
"cOnnECtioN: close\r\n"
"accept-ENCODING: compress, gzip\r\n"
"\r\n";
deque<Request*> requests = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, requests.size());
Request* request = requests[0];
EXPECT_FALSE(request->keepAlive);
EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));
delete request;
}
TEST(Decoder, Response)
{
ResponseDecoder decoder;
const string& data =
"HTTP/1.1 200 OK\r\n"
"Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 2\r\n"
"\r\n"
"hi";
deque<Response*> requests = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, requests.size());
Response* response = requests[0];
EXPECT_EQ("200 OK", response->status);
EXPECT_EQ(Response::BODY, response->type);
EXPECT_EQ("hi", response->body);
EXPECT_EQ(3, response->headers.size());
delete response;
}
<commit_msg>Fixed a copy/paste naming mistake in decoder_tests.cpp.<commit_after>#include <gmock/gmock.h>
#include <deque>
#include <string>
#include <process/socket.hpp>
#include <stout/gtest.hpp>
#include "decoder.hpp"
using namespace process;
using namespace process::http;
using std::deque;
using std::string;
using process::network::Socket;
TEST(Decoder, Request)
{
Try<Socket> socket = Socket::create();
ASSERT_SOME(socket);
DataDecoder decoder = DataDecoder(socket.get());
const string& data =
"GET /path/file.json?key1=value1&key2=value2#fragment HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: close\r\n"
"Accept-Encoding: compress, gzip\r\n"
"\r\n";
deque<Request*> requests = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, requests.size());
Request* request = requests[0];
EXPECT_EQ("GET", request->method);
EXPECT_EQ("/path/file.json", request->path);
EXPECT_EQ("/path/file.json?key1=value1&key2=value2#fragment", request->url);
EXPECT_EQ("fragment", request->fragment);
EXPECT_TRUE(request->body.empty());
EXPECT_FALSE(request->keepAlive);
EXPECT_EQ(3, request->headers.size());
EXPECT_SOME_EQ("localhost", request->headers.get("Host"));
EXPECT_SOME_EQ("close", request->headers.get("Connection"));
EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));
EXPECT_EQ(2, request->query.size());
EXPECT_SOME_EQ("value1", request->query.get("key1"));
EXPECT_SOME_EQ("value2", request->query.get("key2"));
delete request;
}
TEST(Decoder, RequestHeaderContinuation)
{
Try<Socket> socket = Socket::create();
ASSERT_SOME(socket);
DataDecoder decoder = DataDecoder(socket.get());
const string& data =
"GET /path/file.json HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: close\r\n"
"Accept-Encoding: compress,"
" gzip\r\n"
"\r\n";
deque<Request*> requests = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, requests.size());
Request* request = requests[0];
EXPECT_SOME_EQ("compress, gzip",
request->headers.get("Accept-Encoding"));
delete request;
}
// This is expected to fail for now, see my TODO(bmahler) on http::Request.
TEST(Decoder, DISABLED_RequestHeaderCaseInsensitive)
{
Try<Socket> socket = Socket::create();
ASSERT_SOME(socket);
DataDecoder decoder = DataDecoder(socket.get());
const string& data =
"GET /path/file.json HTTP/1.1\r\n"
"Host: localhost\r\n"
"cOnnECtioN: close\r\n"
"accept-ENCODING: compress, gzip\r\n"
"\r\n";
deque<Request*> requests = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, requests.size());
Request* request = requests[0];
EXPECT_FALSE(request->keepAlive);
EXPECT_SOME_EQ("compress, gzip", request->headers.get("Accept-Encoding"));
delete request;
}
TEST(Decoder, Response)
{
ResponseDecoder decoder;
const string& data =
"HTTP/1.1 200 OK\r\n"
"Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 2\r\n"
"\r\n"
"hi";
deque<Response*> responses = decoder.decode(data.data(), data.length());
ASSERT_FALSE(decoder.failed());
ASSERT_EQ(1, responses.size());
Response* response = responses[0];
EXPECT_EQ("200 OK", response->status);
EXPECT_EQ(Response::BODY, response->type);
EXPECT_EQ("hi", response->body);
EXPECT_EQ(3, response->headers.size());
delete response;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTableSourceContext.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:48:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#ifndef _SC_XMLTABLESOURCECONTEXT_HXX
#include "XMLTableSourceContext.hxx"
#endif
#ifndef SC_XMLIMPRT_HXX
#include "xmlimprt.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_XMLSUBTI_HXX
#include "xmlsubti.hxx"
#endif
#ifndef SC_TABLINK_HXX
#include "tablink.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSHEETLINKABLE_HPP_
#include <com/sun/star/sheet/XSheetLinkable.hpp>
#endif
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLTableSourceContext::ScXMLTableSourceContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName ),
sLink(),
sTableName(),
sFilterName(),
sFilterOptions(),
nRefresh(0),
nMode(sheet::SheetLinkMode_NORMAL)
{
sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
for( sal_Int16 i=0; i < nAttrCount; ++i )
{
const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
rtl::OUString aLocalName;
sal_uInt16 nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName ));
const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
if(nPrefix == XML_NAMESPACE_XLINK)
{
if (IsXMLToken(aLocalName, XML_HREF))
sLink = GetScImport().GetAbsoluteReference(sValue);
}
else if (nPrefix == XML_NAMESPACE_TABLE)
{
if (IsXMLToken(aLocalName, XML_TABLE_NAME))
sTableName = sValue;
else if (IsXMLToken(aLocalName, XML_FILTER_NAME))
sFilterName = sValue;
else if (IsXMLToken(aLocalName, XML_FILTER_OPTIONS))
sFilterOptions = sValue;
else if (IsXMLToken(aLocalName, XML_MODE))
{
if (IsXMLToken(sValue, XML_COPY_RESULTS_ONLY))
nMode = sheet::SheetLinkMode_VALUE;
}
else if (IsXMLToken(aLocalName, XML_REFRESH_DELAY))
{
double fTime;
if( SvXMLUnitConverter::convertTime( fTime, sValue ) )
nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 );
}
}
}
}
ScXMLTableSourceContext::~ScXMLTableSourceContext()
{
}
SvXMLImportContext *ScXMLTableSourceContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ )
{
return new SvXMLImportContext( GetImport(), nPrefix, rLName );
}
void ScXMLTableSourceContext::EndElement()
{
if (sLink.getLength())
{
uno::Reference <sheet::XSheetLinkable> xLinkable (GetScImport().GetTables().GetCurrentXSheet(), uno::UNO_QUERY);
ScDocument* pDoc(GetScImport().GetDocument());
if (xLinkable.is() && pDoc)
{
GetScImport().LockSolarMutex();
if (pDoc->RenameTab( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
GetScImport().GetTables().GetCurrentSheetName(), sal_False, sal_True))
{
String aFileString(sLink);
String aFilterString(sFilterName);
String aOptString(sFilterOptions);
String aSheetString(sTableName);
aFileString = ScGlobal::GetAbsDocName( aFileString, pDoc->GetDocumentShell() );
if ( !aFilterString.Len() )
ScDocumentLoader::GetFilterName( aFileString, aFilterString, aOptString, FALSE );
BYTE nLinkMode = SC_LINK_NONE;
if ( nMode == sheet::SheetLinkMode_NORMAL )
nLinkMode = SC_LINK_NORMAL;
else if ( nMode == sheet::SheetLinkMode_VALUE )
nLinkMode = SC_LINK_VALUE;
pDoc->SetLink( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
nLinkMode, aFileString, aFilterString, aOptString,
aSheetString, nRefresh );
}
GetScImport().UnlockSolarMutex();
}
}
}
<commit_msg>INTEGRATION: CWS tl37 (1.13.168); FILE MERGED 2007/04/11 12:36:47 tl 1.13.168.2: RESYNC: (1.13-1.14); FILE MERGED 2007/02/06 19:22:49 nn 1.13.168.1: #i74099# UseInteractionHandler moved out of GuessFilter<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLTableSourceContext.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: hr $ $Date: 2007-06-27 12:44:54 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#ifndef _SC_XMLTABLESOURCECONTEXT_HXX
#include "XMLTableSourceContext.hxx"
#endif
#ifndef SC_XMLIMPRT_HXX
#include "xmlimprt.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_XMLSUBTI_HXX
#include "xmlsubti.hxx"
#endif
#ifndef SC_TABLINK_HXX
#include "tablink.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _COM_SUN_STAR_SHEET_XSHEETLINKABLE_HPP_
#include <com/sun/star/sheet/XSheetLinkable.hpp>
#endif
using namespace com::sun::star;
using namespace xmloff::token;
//------------------------------------------------------------------
ScXMLTableSourceContext::ScXMLTableSourceContext( ScXMLImport& rImport,
USHORT nPrfx,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& xAttrList) :
SvXMLImportContext( rImport, nPrfx, rLName ),
sLink(),
sTableName(),
sFilterName(),
sFilterOptions(),
nRefresh(0),
nMode(sheet::SheetLinkMode_NORMAL)
{
sal_Int16 nAttrCount(xAttrList.is() ? xAttrList->getLength() : 0);
for( sal_Int16 i=0; i < nAttrCount; ++i )
{
const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));
rtl::OUString aLocalName;
sal_uInt16 nPrefix(GetScImport().GetNamespaceMap().GetKeyByAttrName(
sAttrName, &aLocalName ));
const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));
if(nPrefix == XML_NAMESPACE_XLINK)
{
if (IsXMLToken(aLocalName, XML_HREF))
sLink = GetScImport().GetAbsoluteReference(sValue);
}
else if (nPrefix == XML_NAMESPACE_TABLE)
{
if (IsXMLToken(aLocalName, XML_TABLE_NAME))
sTableName = sValue;
else if (IsXMLToken(aLocalName, XML_FILTER_NAME))
sFilterName = sValue;
else if (IsXMLToken(aLocalName, XML_FILTER_OPTIONS))
sFilterOptions = sValue;
else if (IsXMLToken(aLocalName, XML_MODE))
{
if (IsXMLToken(sValue, XML_COPY_RESULTS_ONLY))
nMode = sheet::SheetLinkMode_VALUE;
}
else if (IsXMLToken(aLocalName, XML_REFRESH_DELAY))
{
double fTime;
if( SvXMLUnitConverter::convertTime( fTime, sValue ) )
nRefresh = Max( (sal_Int32)(fTime * 86400.0), (sal_Int32)0 );
}
}
}
}
ScXMLTableSourceContext::~ScXMLTableSourceContext()
{
}
SvXMLImportContext *ScXMLTableSourceContext::CreateChildContext( USHORT nPrefix,
const ::rtl::OUString& rLName,
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList>& /* xAttrList */ )
{
return new SvXMLImportContext( GetImport(), nPrefix, rLName );
}
void ScXMLTableSourceContext::EndElement()
{
if (sLink.getLength())
{
uno::Reference <sheet::XSheetLinkable> xLinkable (GetScImport().GetTables().GetCurrentXSheet(), uno::UNO_QUERY);
ScDocument* pDoc(GetScImport().GetDocument());
if (xLinkable.is() && pDoc)
{
GetScImport().LockSolarMutex();
if (pDoc->RenameTab( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
GetScImport().GetTables().GetCurrentSheetName(), sal_False, sal_True))
{
String aFileString(sLink);
String aFilterString(sFilterName);
String aOptString(sFilterOptions);
String aSheetString(sTableName);
aFileString = ScGlobal::GetAbsDocName( aFileString, pDoc->GetDocumentShell() );
if ( !aFilterString.Len() )
ScDocumentLoader::GetFilterName( aFileString, aFilterString, aOptString, FALSE, FALSE );
BYTE nLinkMode = SC_LINK_NONE;
if ( nMode == sheet::SheetLinkMode_NORMAL )
nLinkMode = SC_LINK_NORMAL;
else if ( nMode == sheet::SheetLinkMode_VALUE )
nLinkMode = SC_LINK_VALUE;
pDoc->SetLink( static_cast<SCTAB>(GetScImport().GetTables().GetCurrentSheet()),
nLinkMode, aFileString, aFilterString, aOptString,
aSheetString, nRefresh );
}
GetScImport().UnlockSolarMutex();
}
}
}
<|endoftext|> |
<commit_before>#include "Component.h"
std::vector<Component*>Component::components;
Component::Component()
: position(0.f, 0.f, 0.f)
, isVisible(true)
{
components.push_back(this);
}
Component::Component(float x, float y, float z)
: position(x, y, z)
{
components.push_back(this);
}
Component::~Component()
{
}
<commit_msg>IsVisible dans le deuxieme constructeur de Component<commit_after>#include "Component.h"
std::vector<Component*>Component::components;
Component::Component()
: position(0.f, 0.f, 0.f)
, isVisible(true)
{
components.push_back(this);
}
Component::Component(float x, float y, float z)
: position(x, y, z)
, isVisible(true)
{
components.push_back(this);
}
Component::~Component()
{
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief IP address 定義 @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "common/format.hpp"
#include "common/input.hpp"
namespace net {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ip_address クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class ip_address {
union address_t {
uint32_t dword;
uint8_t bytes[4]; // IPv4 address
address_t(uint32_t v = 0) : dword(v) { }
address_t(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3) {
bytes[0] = v0;
bytes[1] = v1;
bytes[2] = v2;
bytes[3] = v3;
}
};
address_t address_;
char str_[4*4+1];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] dword 32bits IP
*/
//-----------------------------------------------------------------//
ip_address(uint32_t dword = 0) : address_(dword), str_{ 0 } { }
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] first IP 1ST
@param[in] second IP 2ND
@param[in] third IP 3RD
@param[in] fourth IP 4TH
*/
//-----------------------------------------------------------------//
ip_address(uint8_t first, uint8_t second, uint8_t third, uint8_t fourth) :
address_(first, second, third, fourth) { }
//-----------------------------------------------------------------//
/*!
@brief 配列から設定
@param[in] address 配列
*/
//-----------------------------------------------------------------//
void set(const uint8_t* address) {
if(address == nullptr) {
address_ = 0;
return;
}
address_.bytes[0] = address[0];
address_.bytes[1] = address[1];
address_.bytes[2] = address[2];
address_.bytes[3] = address[3];
}
//-----------------------------------------------------------------//
/*!
@brief バイト列取得
@return バイト配列
*/
//-----------------------------------------------------------------//
const uint8_t* get() const { return address_.bytes; }
//-----------------------------------------------------------------//
/*!
@brief 文字列から設定
@param[in] address 配列
*/
//-----------------------------------------------------------------//
bool from_string(const char *address) {
if(address == nullptr) return false;
int a, b, c, d;
auto f = (utils::input("%d.%d.%d.%d", address) % a % b % c % d).status();
if(f) {
if(a >= 0 && a <= 255) address_.bytes[0] = a;
if(a >= 0 && b <= 255) address_.bytes[1] = b;
if(a >= 0 && c <= 255) address_.bytes[2] = c;
if(a >= 0 && d <= 255) address_.bytes[3] = d;
}
return f;
}
//-----------------------------------------------------------------//
/*!
@brief 型変換キャスト演算子(uint32_t 型)
*/
//-----------------------------------------------------------------//
operator uint32_t() const { return address_.dword; };
bool operator==(const ip_address& addr) const {
return address_.dword == addr.address_.dword;
}
bool operator == (const uint8_t* addr) const {
if(addr == nullptr) return false;
return (address_.bytes[0] == addr[0]
&& address_.bytes[1] == addr[1]
&& address_.bytes[2] == addr[2]
&& address_.bytes[3] == addr[3]);
}
uint8_t operator [] (int index) const { return address_.bytes[index]; };
uint8_t& operator [] (int index) { return address_.bytes[index]; };
ip_address& operator = (const uint8_t* address) {
address_.bytes[0] = address[0];
address_.bytes[1] = address[1];
address_.bytes[2] = address[2];
address_.bytes[3] = address[3];
return *this;
}
ip_address& operator = (uint32_t address) {
address_.dword = address;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字列で取得
@param[in] spch 分離キャラクター(通常「.」)
@return 文字列
*/
//-----------------------------------------------------------------//
const char* get_str(char spch = '.') {
utils::format("%d%c%d%c%d%c%d", str_, sizeof(str_))
% static_cast<int>(address_.bytes[0]) % spch
% static_cast<int>(address_.bytes[1]) % spch
% static_cast<int>(address_.bytes[2]) % spch
% static_cast<int>(address_.bytes[3]);
return str_;
}
};
}
<commit_msg>update api name<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief IP address 定義 @n
Copyright 2017 Kunihito Hiramatsu
@author 平松邦仁 ([email protected])
*/
//=====================================================================//
#include <cstdint>
#include "common/format.hpp"
#include "common/input.hpp"
namespace net {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ip_address クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class ip_address {
union address_t {
uint32_t dword;
uint8_t bytes[4]; // IPv4 address
address_t(uint32_t v = 0) : dword(v) { }
address_t(uint8_t v0, uint8_t v1, uint8_t v2, uint8_t v3) {
bytes[0] = v0;
bytes[1] = v1;
bytes[2] = v2;
bytes[3] = v3;
}
};
address_t address_;
char str_[4*4+1];
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] dword 32bits IP
*/
//-----------------------------------------------------------------//
ip_address(uint32_t dword = 0) : address_(dword), str_{ 0 } { }
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] first IP 1ST
@param[in] second IP 2ND
@param[in] third IP 3RD
@param[in] fourth IP 4TH
*/
//-----------------------------------------------------------------//
ip_address(uint8_t first, uint8_t second, uint8_t third, uint8_t fourth) :
address_(first, second, third, fourth) { }
//-----------------------------------------------------------------//
/*!
@brief 配列から設定
@param[in] address 配列
*/
//-----------------------------------------------------------------//
void set(const uint8_t* address) {
if(address == nullptr) {
address_ = 0;
return;
}
address_.bytes[0] = address[0];
address_.bytes[1] = address[1];
address_.bytes[2] = address[2];
address_.bytes[3] = address[3];
}
//-----------------------------------------------------------------//
/*!
@brief バイト列取得
@return バイト配列
*/
//-----------------------------------------------------------------//
const uint8_t* get() const { return address_.bytes; }
//-----------------------------------------------------------------//
/*!
@brief 文字列から設定
@param[in] address 配列
*/
//-----------------------------------------------------------------//
bool from_string(const char *address) {
if(address == nullptr) return false;
int a, b, c, d;
auto f = (utils::input("%d.%d.%d.%d", address) % a % b % c % d).status();
if(f) {
if(a >= 0 && a <= 255) address_.bytes[0] = a;
if(a >= 0 && b <= 255) address_.bytes[1] = b;
if(a >= 0 && c <= 255) address_.bytes[2] = c;
if(a >= 0 && d <= 255) address_.bytes[3] = d;
}
return f;
}
//-----------------------------------------------------------------//
/*!
@brief 型変換キャスト演算子(uint32_t 型)
*/
//-----------------------------------------------------------------//
operator uint32_t() const { return address_.dword; };
bool operator==(const ip_address& addr) const {
return address_.dword == addr.address_.dword;
}
bool operator == (const uint8_t* addr) const {
if(addr == nullptr) return false;
return (address_.bytes[0] == addr[0]
&& address_.bytes[1] == addr[1]
&& address_.bytes[2] == addr[2]
&& address_.bytes[3] == addr[3]);
}
uint8_t operator [] (int index) const { return address_.bytes[index]; };
uint8_t& operator [] (int index) { return address_.bytes[index]; };
ip_address& operator = (const uint8_t* address) {
address_.bytes[0] = address[0];
address_.bytes[1] = address[1];
address_.bytes[2] = address[2];
address_.bytes[3] = address[3];
return *this;
}
ip_address& operator = (uint32_t address) {
address_.dword = address;
return *this;
}
//-----------------------------------------------------------------//
/*!
@brief 文字列で取得
@param[in] spch 分離キャラクター(通常「.」)
@return 文字列
*/
//-----------------------------------------------------------------//
const char* c_str(char spch = '.') {
utils::format("%d%c%d%c%d%c%d", str_, sizeof(str_))
% static_cast<int>(address_.bytes[0]) % spch
% static_cast<int>(address_.bytes[1]) % spch
% static_cast<int>(address_.bytes[2]) % spch
% static_cast<int>(address_.bytes[3]);
return str_;
}
};
}
<|endoftext|> |
<commit_before>/*
* BuildingObjectImplementation.cpp
*
* Created on: 23/07/2009
* Author: TheAnswer
*/
#include "BuildingObject.h"
#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/cell/CellObject.h"
#include "server/zone/objects/player/PlayerCreature.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/templates/tangible/SharedBuildingObjectTemplate.h"
#include "server/zone/templates/appearance/PortalLayout.h"
#include "server/zone/objects/tangible/terminal/structure/StructureTerminal.h"
#include "server/zone/objects/player/sui/listbox/SuiListBox.h"
#include "server/zone/objects/player/sui/inputbox/SuiInputBox.h"
#include "server/zone/objects/tangible/sign/SignObject.h"
#include "server/zone/packets/tangible/TangibleObjectMessage3.h"
#include "server/zone/packets/tangible/TangibleObjectMessage6.h"
#include "server/zone/packets/cell/UpdateCellPermissionsMessage.h"
#include "server/zone/objects/scene/components/ContainerComponent.h"
#include "server/zone/managers/object/ObjectManager.h"
void BuildingObjectImplementation::initializeTransientMembers() {
StructureObjectImplementation::initializeTransientMembers();
setLoggingName("BuildingObject");
}
void BuildingObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) {
StructureObjectImplementation::loadTemplateData(templateData);
SharedBuildingObjectTemplate* buildingData = dynamic_cast<SharedBuildingObjectTemplate*>(templateData);
containerVolumeLimit = 0xFFFFFFFF;
containerType = 2;
totalCellNumber = buildingData->getTotalCellNumber();
PortalLayout* portalLayout = templateData->getPortalLayout();
if (portalLayout != NULL)
totalCellNumber = portalLayout->getFloorMeshNumber() - 1; //remove the exterior floor
optionsBitmask = 0x00000100;
publicStructure = buildingData->isPublicStructure();
}
void BuildingObjectImplementation::createContainerComponent() {
TangibleObjectImplementation::createContainerComponent();
}
void BuildingObjectImplementation::notifyLoadFromDatabase() {
SceneObjectImplementation::notifyLoadFromDatabase();
if (isInQuadTree()) {
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* containerObject = cell->getContainerObject(j);
containerObject->insertToZone(getZone());
}
}
}
}
int BuildingObjectImplementation::getCurrentNumerOfPlayerItems() {
int items = 0;
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
items += cell->getCurrentNumerOfPlayerItems();
}
return items;
}
void BuildingObjectImplementation::createCellObjects() {
for (int i = 0; i < totalCellNumber; ++i) {
SceneObject* newCell = getZoneServer()->createObject(0xAD431713, getPersistenceLevel());
if (!addObject(newCell, -1))
error("could not add cell");
}
updateToDatabase();
}
void BuildingObjectImplementation::sendContainerObjectsTo(SceneObject* player) {
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
if (cell->getParent() == NULL)
cell->setParent(_this);
cell->setCellNumber(i + 1);
cell->sendTo(player, true);
}
}
void BuildingObjectImplementation::sendTo(SceneObject* player, bool doClose) {
info("building sendto..");
if (!isStaticBuilding()) { // send Baselines etc..
info("sending building object create");
SceneObjectImplementation::sendTo(player, doClose);
} else { // just send the objects that are in the building, without the cells because they are static in the client
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* childStub = cell->getContainerObject(j);
if (!childStub->isInQuadTree())
childStub->sendTo(player, true);
}
}
}
}
Vector3 BuildingObjectImplementation::getEjectionPoint() {
/*
PortalLayout* portalLayout = templateObject->getPortalLayout();
if (portalLayout == NULL)
return;
FloorMesh* floorMesh = portalLayout->getFloorMesh(0);
if (floorMesh == NULL)
return;
*/
Vector3 ejectionPoint = getWorldPosition();
float x = ejectionPoint.getX();
float y = ejectionPoint.getY();
float halfLength = ((float) (length) * 8.0f) / 2.0f; //Half the length of the structure in meters.
float radians = getDirection()->getRadians() + Math::deg2rad(270); //Ejection point should be on south side of structure.
ejectionPoint.setX(x + (Math::cos(radians) * halfLength));
ejectionPoint.setY(y + (Math::sin(radians) * halfLength));
return ejectionPoint;
}
void BuildingObjectImplementation::removeFromZone() {
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
//cell->resetCurrentNumerOfPlayerItems();
while (cell->getContainerObjectsSize() > 0) {
ManagedReference<SceneObject*> obj = cell->getContainerObject(0);
obj->removeFromZone();
cell->removeObject(obj);
VectorMap<uint64, ManagedReference<SceneObject*> >* cont = cell->getContainerObjects();
//cont->drop(obj->getObjectID());
if (cont->size() > 0) {
SceneObject* test = cell->getContainerObject(0);
if (test == obj) {
cont->remove(0);
}
}
}
if (signObject != NULL) {
signObject->removeFromZone();
}
}
TangibleObjectImplementation::removeFromZone();
}
void BuildingObjectImplementation::sendDestroyTo(SceneObject* player) {
if (!isStaticBuilding()) {
info("sending building object destroy");
SceneObjectImplementation::destroy(player->getClient());
}
}
void BuildingObjectImplementation::sendBaselinesTo(SceneObject* player) {
//send buios here
info("sending building baselines");
BaseMessage* buio3 = new TangibleObjectMessage3(_this);
player->sendMessage(buio3);
BaseMessage* buio6 = new TangibleObjectMessage6(_this);
player->sendMessage(buio6);
}
void BuildingObjectImplementation::notifyInsertToZone(SceneObject* object) {
//info("BuildingObjectImplementation::notifyInsertToZone");
for (int i = 0; i < inRangeObjectCount(); ++i) {
QuadTreeEntry* obj = getInRangeObject(i);
object->addInRangeObject(obj, true);
obj->addInRangeObject(object, true);
}
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
if (isStaticBuilding()) {
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* child = cell->getContainerObject(j);
//if (childStub->isInRange(object, 128)) {
child->addInRangeObject(object, false);
if (child != object) {
object->notifyInsert(child);
//child->sendTo(object, true);
}
object->addInRangeObject(child, false);
if (child != object) {
//object->sendTo(childStub, true);
child->notifyInsert(object);
}
//}
}
}
}
object->addInRangeObject(_this, false);
addInRangeObject(object, false);
//this->sendTo(object, true);
}
void BuildingObjectImplementation::notifyInsert(QuadTreeEntry* obj) {
//info("BuildingObjectImplementation::notifyInsert");
SceneObject* scno = (SceneObject*) obj;
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* child = cell->getContainerObject(j);
/*if (childStub->isCreatureObject()
|| (scno->getRootParent() == _this) && (scno->isInRange(childStub, 128))) {*/
if (isStaticBuilding()) {
child->addInRangeObject(obj, false);
obj->addInRangeObject(child, false);
}
//}
}
}
}
void BuildingObjectImplementation::notifyDissapear(QuadTreeEntry* obj) {
SceneObject* scno = (SceneObject*) obj;
removeNotifiedSentObject(scno);
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* child = cell->getContainerObject(j);
child->removeInRangeObject(obj);
obj->removeInRangeObject(child);
}
}
}
void BuildingObjectImplementation::insert(QuadTreeEntry* entry) {
quadTree->insert(entry);
}
void BuildingObjectImplementation::remove(QuadTreeEntry* entry) {
if (entry->isInQuadTree())
quadTree->remove(entry);
}
void BuildingObjectImplementation::update(QuadTreeEntry* entry) {
quadTree->update(entry);
}
void BuildingObjectImplementation::inRange(QuadTreeEntry* entry, float range) {
quadTree->inRange(entry, range);
}
void BuildingObjectImplementation::addCell(CellObject* cell) {
cells.add(cell);
cell->setCellNumber(cells.size());
/*if (!addObject(cell, -1))
error("could not add cell");*/
}
void BuildingObjectImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
StructureObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);
if (!destroyContainedObjects)
return;
ManagedReference<SceneObject*> deed = getZoneServer()->getObject(deedObjectID);
if (deed != NULL)
deed->destroyObjectFromDatabase(true);
if (signObject != NULL)
signObject->destroyObjectFromDatabase(true);
//Loop through the cells and delete all objects from the database.
}
void BuildingObjectImplementation::updateCellPermissionsTo(SceneObject* player) {
/* if (!player->isInRange(_this, 256))
return;*/
bool allowEntry = true;
if (!isPublicStructure() && (!isOnEntryList(player) && !isOnAccessList(player)))
allowEntry = false;
if (isOnBanList(player))
allowEntry = false;
//If they don't have permission to be inside, kick them out.
if (!allowEntry && player->getParentRecursively(SceneObject::BUILDING) == _this) {
Vector3 ejectionPoint = getEjectionPoint();
player->teleport(ejectionPoint.getX(), getZone()->getHeight(ejectionPoint.getX(), ejectionPoint.getY()), ejectionPoint.getY(), 0);
}
//Always allow privileged players to enter any structure.
if (player->isPlayerCreature() && ((PlayerCreature*) player)->getPlayerObject()->isPrivileged())
allowEntry = true;
for (int i = 0; i < cells.size(); ++i) {
ManagedReference<CellObject*> cell = getCell(i);
if (cell == NULL)
continue;
BaseMessage* perm = new UpdateCellPermissionsMessage(cell->getObjectID(), allowEntry);
player->sendMessage(perm);
}
}
void BuildingObjectImplementation::onEnter(PlayerCreature* player) {
if (getZone() == NULL)
return;
if (isStaticObject())
return;
Vector3 ejectionPoint = getEjectionPoint();
float x = ejectionPoint.getX();
float y = ejectionPoint.getY();
if (isinf(x) || isnan(x) || isinf(y) || isnan(y))
return;
float z = getZone()->getHeight(x, y);
//Locker _locker(zone);
if (isOnBanList(player)) {
player->teleport(x, z, y, 0);
return;
}
if (!isPublicStructure()) {
if (!isOnEntryList(player))
player->teleport(x, z, y, 0);
} else {
if (getAccessFee() > 0 && !isOnAccessList(player)) {
//Send access fee popup menu.
//Kick the player out.
player->teleport(x, z, y, 0);
}
}
}
uint32 BuildingObjectImplementation::getMaximumNumberOfPlayerItems() {
SharedStructureObjectTemplate* ssot = dynamic_cast<SharedStructureObjectTemplate*>(templateObject.get());
if (ssot == NULL)
return 0;
uint8 lots = ssot->getLotSize();
//Buildings that don't cost lots have MAXPLAYERITEMS storage space.
if (lots == 0)
return MAXPLAYERITEMS;
return MIN(MAXPLAYERITEMS, lots * 100);
}
bool BuildingObjectImplementation::addObject(SceneObject* object, int containmentType, bool notifyClient) {
if (object->isCellObject()) {
addCell((CellObject*) object);
//return true;
}
return StructureObjectImplementation::addObject(object, containmentType, notifyClient);
}
<commit_msg>[fixed] zone loading<commit_after>/*
* BuildingObjectImplementation.cpp
*
* Created on: 23/07/2009
* Author: TheAnswer
*/
#include "BuildingObject.h"
#include "server/zone/Zone.h"
#include "server/zone/ZoneServer.h"
#include "server/zone/objects/cell/CellObject.h"
#include "server/zone/objects/player/PlayerCreature.h"
#include "server/zone/objects/structure/StructureObject.h"
#include "server/zone/templates/tangible/SharedBuildingObjectTemplate.h"
#include "server/zone/templates/appearance/PortalLayout.h"
#include "server/zone/objects/tangible/terminal/structure/StructureTerminal.h"
#include "server/zone/objects/player/sui/listbox/SuiListBox.h"
#include "server/zone/objects/player/sui/inputbox/SuiInputBox.h"
#include "server/zone/objects/tangible/sign/SignObject.h"
#include "server/zone/packets/tangible/TangibleObjectMessage3.h"
#include "server/zone/packets/tangible/TangibleObjectMessage6.h"
#include "server/zone/packets/cell/UpdateCellPermissionsMessage.h"
#include "server/zone/objects/scene/components/ContainerComponent.h"
#include "server/zone/managers/object/ObjectManager.h"
void BuildingObjectImplementation::initializeTransientMembers() {
StructureObjectImplementation::initializeTransientMembers();
setLoggingName("BuildingObject");
}
void BuildingObjectImplementation::loadTemplateData(SharedObjectTemplate* templateData) {
StructureObjectImplementation::loadTemplateData(templateData);
SharedBuildingObjectTemplate* buildingData = dynamic_cast<SharedBuildingObjectTemplate*>(templateData);
containerVolumeLimit = 0xFFFFFFFF;
containerType = 2;
totalCellNumber = buildingData->getTotalCellNumber();
PortalLayout* portalLayout = templateData->getPortalLayout();
if (portalLayout != NULL)
totalCellNumber = portalLayout->getFloorMeshNumber() - 1; //remove the exterior floor
optionsBitmask = 0x00000100;
publicStructure = buildingData->isPublicStructure();
}
void BuildingObjectImplementation::createContainerComponent() {
TangibleObjectImplementation::createContainerComponent();
}
void BuildingObjectImplementation::notifyLoadFromDatabase() {
SceneObjectImplementation::notifyLoadFromDatabase();
if (isInQuadTree()) {
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* containerObject = cell->getContainerObject(j);
containerObject->insertToZone(getZone());
}
}
}
}
int BuildingObjectImplementation::getCurrentNumerOfPlayerItems() {
int items = 0;
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
items += cell->getCurrentNumerOfPlayerItems();
}
return items;
}
void BuildingObjectImplementation::createCellObjects() {
for (int i = 0; i < totalCellNumber; ++i) {
SceneObject* newCell = getZoneServer()->createObject(0xAD431713, getPersistenceLevel());
if (!addObject(newCell, -1))
error("could not add cell");
}
updateToDatabase();
}
void BuildingObjectImplementation::sendContainerObjectsTo(SceneObject* player) {
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
if (cell->getParent() == NULL)
cell->setParent(_this);
cell->setCellNumber(i + 1);
cell->sendTo(player, true);
}
}
void BuildingObjectImplementation::sendTo(SceneObject* player, bool doClose) {
info("building sendto..");
if (!isStaticBuilding()) { // send Baselines etc..
info("sending building object create");
SceneObjectImplementation::sendTo(player, doClose);
} else { // just send the objects that are in the building, without the cells because they are static in the client
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* childStub = cell->getContainerObject(j);
if (!childStub->isInQuadTree())
childStub->sendTo(player, true);
}
}
}
}
Vector3 BuildingObjectImplementation::getEjectionPoint() {
/*
PortalLayout* portalLayout = templateObject->getPortalLayout();
if (portalLayout == NULL)
return;
FloorMesh* floorMesh = portalLayout->getFloorMesh(0);
if (floorMesh == NULL)
return;
*/
Vector3 ejectionPoint = getWorldPosition();
float x = ejectionPoint.getX();
float y = ejectionPoint.getY();
float halfLength = ((float) (length) * 8.0f) / 2.0f; //Half the length of the structure in meters.
float radians = getDirection()->getRadians() + Math::deg2rad(270); //Ejection point should be on south side of structure.
ejectionPoint.setX(x + (Math::cos(radians) * halfLength));
ejectionPoint.setY(y + (Math::sin(radians) * halfLength));
return ejectionPoint;
}
void BuildingObjectImplementation::removeFromZone() {
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
//cell->resetCurrentNumerOfPlayerItems();
while (cell->getContainerObjectsSize() > 0) {
ManagedReference<SceneObject*> obj = cell->getContainerObject(0);
obj->removeFromZone();
cell->removeObject(obj);
VectorMap<uint64, ManagedReference<SceneObject*> >* cont = cell->getContainerObjects();
//cont->drop(obj->getObjectID());
if (cont->size() > 0) {
SceneObject* test = cell->getContainerObject(0);
if (test == obj) {
cont->remove(0);
}
}
}
if (signObject != NULL) {
signObject->removeFromZone();
}
}
TangibleObjectImplementation::removeFromZone();
}
void BuildingObjectImplementation::sendDestroyTo(SceneObject* player) {
if (!isStaticBuilding()) {
info("sending building object destroy");
SceneObjectImplementation::destroy(player->getClient());
}
}
void BuildingObjectImplementation::sendBaselinesTo(SceneObject* player) {
//send buios here
info("sending building baselines");
BaseMessage* buio3 = new TangibleObjectMessage3(_this);
player->sendMessage(buio3);
BaseMessage* buio6 = new TangibleObjectMessage6(_this);
player->sendMessage(buio6);
}
void BuildingObjectImplementation::notifyInsertToZone(SceneObject* object) {
//info("BuildingObjectImplementation::notifyInsertToZone");
for (int i = 0; i < inRangeObjectCount(); ++i) {
QuadTreeEntry* obj = getInRangeObject(i);
object->addInRangeObject(obj, false);
obj->addInRangeObject(object, false);
}
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
if (isStaticBuilding()) {
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* child = cell->getContainerObject(j);
//if (childStub->isInRange(object, 128)) {
child->addInRangeObject(object, false);
if (child != object) {
object->notifyInsert(child);
//child->sendTo(object, true);
}
object->addInRangeObject(child, false);
if (child != object) {
//object->sendTo(childStub, true);
child->notifyInsert(object);
}
//}
}
}
}
object->addInRangeObject(_this, false);
addInRangeObject(object, false);
//this->sendTo(object, true);
}
void BuildingObjectImplementation::notifyInsert(QuadTreeEntry* obj) {
//info("BuildingObjectImplementation::notifyInsert");
SceneObject* scno = (SceneObject*) obj;
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* child = cell->getContainerObject(j);
/*if (childStub->isCreatureObject()
|| (scno->getRootParent() == _this) && (scno->isInRange(childStub, 128))) {*/
if (isStaticBuilding()) {
child->addInRangeObject(obj, false);
obj->addInRangeObject(child, false);
}
//}
}
}
}
void BuildingObjectImplementation::notifyDissapear(QuadTreeEntry* obj) {
SceneObject* scno = (SceneObject*) obj;
removeNotifiedSentObject(scno);
for (int i = 0; i < cells.size(); ++i) {
CellObject* cell = cells.get(i);
for (int j = 0; j < cell->getContainerObjectsSize(); ++j) {
SceneObject* child = cell->getContainerObject(j);
child->removeInRangeObject(obj);
obj->removeInRangeObject(child);
}
}
}
void BuildingObjectImplementation::insert(QuadTreeEntry* entry) {
quadTree->insert(entry);
}
void BuildingObjectImplementation::remove(QuadTreeEntry* entry) {
if (entry->isInQuadTree())
quadTree->remove(entry);
}
void BuildingObjectImplementation::update(QuadTreeEntry* entry) {
quadTree->update(entry);
}
void BuildingObjectImplementation::inRange(QuadTreeEntry* entry, float range) {
quadTree->inRange(entry, range);
}
void BuildingObjectImplementation::addCell(CellObject* cell) {
cells.add(cell);
cell->setCellNumber(cells.size());
/*if (!addObject(cell, -1))
error("could not add cell");*/
}
void BuildingObjectImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {
StructureObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);
if (!destroyContainedObjects)
return;
ManagedReference<SceneObject*> deed = getZoneServer()->getObject(deedObjectID);
if (deed != NULL)
deed->destroyObjectFromDatabase(true);
if (signObject != NULL)
signObject->destroyObjectFromDatabase(true);
//Loop through the cells and delete all objects from the database.
}
void BuildingObjectImplementation::updateCellPermissionsTo(SceneObject* player) {
/* if (!player->isInRange(_this, 256))
return;*/
bool allowEntry = true;
if (!isPublicStructure() && (!isOnEntryList(player) && !isOnAccessList(player)))
allowEntry = false;
if (isOnBanList(player))
allowEntry = false;
//If they don't have permission to be inside, kick them out.
if (!allowEntry && player->getParentRecursively(SceneObject::BUILDING) == _this) {
Vector3 ejectionPoint = getEjectionPoint();
player->teleport(ejectionPoint.getX(), getZone()->getHeight(ejectionPoint.getX(), ejectionPoint.getY()), ejectionPoint.getY(), 0);
}
//Always allow privileged players to enter any structure.
if (player->isPlayerCreature() && ((PlayerCreature*) player)->getPlayerObject()->isPrivileged())
allowEntry = true;
for (int i = 0; i < cells.size(); ++i) {
ManagedReference<CellObject*> cell = getCell(i);
if (cell == NULL)
continue;
BaseMessage* perm = new UpdateCellPermissionsMessage(cell->getObjectID(), allowEntry);
player->sendMessage(perm);
}
}
void BuildingObjectImplementation::onEnter(PlayerCreature* player) {
if (getZone() == NULL)
return;
if (isStaticObject())
return;
Vector3 ejectionPoint = getEjectionPoint();
float x = ejectionPoint.getX();
float y = ejectionPoint.getY();
if (isinf(x) || isnan(x) || isinf(y) || isnan(y))
return;
float z = getZone()->getHeight(x, y);
//Locker _locker(zone);
if (isOnBanList(player)) {
player->teleport(x, z, y, 0);
return;
}
if (!isPublicStructure()) {
if (!isOnEntryList(player))
player->teleport(x, z, y, 0);
} else {
if (getAccessFee() > 0 && !isOnAccessList(player)) {
//Send access fee popup menu.
//Kick the player out.
player->teleport(x, z, y, 0);
}
}
}
uint32 BuildingObjectImplementation::getMaximumNumberOfPlayerItems() {
SharedStructureObjectTemplate* ssot = dynamic_cast<SharedStructureObjectTemplate*>(templateObject.get());
if (ssot == NULL)
return 0;
uint8 lots = ssot->getLotSize();
//Buildings that don't cost lots have MAXPLAYERITEMS storage space.
if (lots == 0)
return MAXPLAYERITEMS;
return MIN(MAXPLAYERITEMS, lots * 100);
}
bool BuildingObjectImplementation::addObject(SceneObject* object, int containmentType, bool notifyClient) {
if (object->isCellObject()) {
addCell((CellObject*) object);
//return true;
}
return StructureObjectImplementation::addObject(object, containmentType, notifyClient);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 otbWrapperInputImageParameter_hxx
#define otbWrapperInputImageParameter_hxx
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperCastImage.h"
namespace otb
{
namespace Wrapper
{
#define CLAMP_IMAGE_IF( Out, In, image_base ) \
{ \
In * in_image = dynamic_cast< In * >( image_base ); \
\
if( in_image ) \
return Cast< Out, In >( in_image ); \
}
#define CLAMP_IMAGE_BASE( T, image_base ) \
{ \
CLAMP_IMAGE_IF( T, UInt8VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int16VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt16VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int32VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt32VectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, FloatVectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, DoubleVectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexInt16VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexInt32VectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexFloatVectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexDoubleVectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, UInt8RGBImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt8RGBAImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, UInt8ImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int16ImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt16ImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int32ImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt32ImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, FloatImageType, image_base ); \
CLAMP_IMAGE_IF( T, DoubleImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexInt16ImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexInt32ImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexFloatImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexDoubleImageType, image_base ); \
\
return nullptr; \
}
template< typename TOutputImage,
typename TInputImage >
TOutputImage *
InputImageParameter
::Cast( TInputImage * image )
{
details::CastImage< TOutputImage, TInputImage > clamp( image );
if( clamp.ocif )
clamp.ocif->UpdateOutputInformation();
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
return clamp.out;
}
template <class TImageType>
TImageType*
InputImageParameter::GetImage()
{
// Used m_PreviousFileName because if not, when the user call twice GetImage,
// it without changing the filename, it returns 2 different
// image pointers
// Only one image type can be used
// 2 cases : the user set a filename vs. the user set an image
if( m_UseFilename )
{
if( m_PreviousFileName!=m_FileName &&
!m_FileName.empty() )
{
//////////////////////// Filename case:
// A new valid filename has been given : a reader is created
typedef otb::ImageFileReader<TImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( m_FileName );
reader->UpdateOutputInformation();
m_Image = reader->GetOutput();
m_Reader = reader;
m_PreviousFileName = m_FileName;
// Pay attention, don't return m_Image because it is a ImageBase...
return reader->GetOutput();
}
else
{
// In this case, the reader and the image should already be there
if (m_Image.IsNull())
{
itkExceptionMacro("No input image or filename detected...");
}
else
{
// Check if the image type asked here is the same as the one used for the reader
if (dynamic_cast<TImageType*> (m_Image.GetPointer()))
{
return dynamic_cast<TImageType*> (m_Image.GetPointer());
}
else
{
itkExceptionMacro(
"GetImage() was already called with a different type, "
"probably due to two calls to GetParameter<Type>Image with different types in application code.");
}
}
}
}
else
{
//////////////////////// Image case:
if (m_Image.IsNull())
{
return nullptr;
}
// Check if the image type asked here is the same as m_image
else if ( dynamic_cast < TImageType* > ( m_Image.GetPointer() ) )
{
return dynamic_cast < TImageType* > ( m_Image.GetPointer() );
}
// check if we already done this cast
else if ( dynamic_cast <
ClampImageFilter < DoubleVectorImageType , TImageType >* >
( m_OutputCaster.GetPointer() ) )
{
return dynamic_cast <
ClampImageFilter < DoubleVectorImageType , TImageType >* >
( m_OutputCaster.GetPointer() )->GetOutput();
}
else
{
CLAMP_IMAGE_BASE( TImageType, m_Image.GetPointer() );
}
}
}
/** declare a specialization for ImageBaseType */
template <>
OTBApplicationEngine_EXPORT
ImageBaseType*
InputImageParameter::GetImage<ImageBaseType>();
} // End namespace Wrapper
} // End namespace otb
#endif
<commit_msg>BUG: InputImageParameter check for existing output caster<commit_after>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 otbWrapperInputImageParameter_hxx
#define otbWrapperInputImageParameter_hxx
#include "otbWrapperInputImageParameter.h"
#include "otbWrapperCastImage.h"
namespace otb
{
namespace Wrapper
{
#define CLAMP_IMAGE_IF( Out, In, image_base ) \
{ \
In * in_image = dynamic_cast< In * >( image_base ); \
\
if( in_image ) \
return Cast< Out, In >( in_image ); \
}
#define CLAMP_IMAGE_BASE( T, image_base ) \
{ \
CLAMP_IMAGE_IF( T, UInt8VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int16VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt16VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int32VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt32VectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, FloatVectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, DoubleVectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexInt16VectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexInt32VectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexFloatVectorImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexDoubleVectorImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, UInt8RGBImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt8RGBAImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, UInt8ImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int16ImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt16ImageType, image_base ); \
CLAMP_IMAGE_IF( T, Int32ImageType, image_base ); \
CLAMP_IMAGE_IF( T, UInt32ImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, FloatImageType, image_base ); \
CLAMP_IMAGE_IF( T, DoubleImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexInt16ImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexInt32ImageType, image_base ); \
\
CLAMP_IMAGE_IF( T, ComplexFloatImageType, image_base ); \
CLAMP_IMAGE_IF( T, ComplexDoubleImageType, image_base ); \
\
return nullptr; \
}
template< typename TOutputImage,
typename TInputImage >
TOutputImage *
InputImageParameter
::Cast( TInputImage * image )
{
details::CastImage< TOutputImage, TInputImage > clamp( image );
if( clamp.ocif )
clamp.ocif->UpdateOutputInformation();
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
return clamp.out;
}
template <class TImageType>
TImageType*
InputImageParameter::GetImage()
{
// Used m_PreviousFileName because if not, when the user call twice GetImage,
// it without changing the filename, it returns 2 different
// image pointers
// Only one image type can be used
// 2 cases : the user set a filename vs. the user set an image
if( m_UseFilename )
{
if( m_PreviousFileName!=m_FileName &&
!m_FileName.empty() )
{
//////////////////////// Filename case:
// A new valid filename has been given : a reader is created
typedef otb::ImageFileReader<TImageType> ReaderType;
typename ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( m_FileName );
reader->UpdateOutputInformation();
m_Image = reader->GetOutput();
m_Reader = reader;
m_PreviousFileName = m_FileName;
// Pay attention, don't return m_Image because it is a ImageBase...
return reader->GetOutput();
}
else
{
// In this case, the reader and the image should already be there
if (m_Image.IsNull())
{
itkExceptionMacro("No input image or filename detected...");
}
else
{
// Check if the image type asked here is the same as the one used for the reader
if (dynamic_cast<TImageType*> (m_Image.GetPointer()))
{
return dynamic_cast<TImageType*> (m_Image.GetPointer());
}
else
{
itkExceptionMacro(
"GetImage() was already called with a different type, "
"probably due to two calls to GetParameter<Type>Image with different types in application code.");
}
}
}
}
else
{
//////////////////////// Image case:
if (m_Image.IsNull())
{
return nullptr;
}
// Check if the image type asked here is the same as m_image
else if ( dynamic_cast < TImageType* > ( m_Image.GetPointer() ) )
{
return dynamic_cast < TImageType* > ( m_Image.GetPointer() );
}
// check if we already done this cast
else if ( dynamic_cast <
ClampImageFilter < DoubleVectorImageType , TImageType >* >
( m_OutputCaster.GetPointer() ) )
{
return dynamic_cast <
ClampImageFilter < DoubleVectorImageType , TImageType >* >
( m_OutputCaster.GetPointer() )->GetOutput();
}
else
{
if (m_OutputCaster.IsNotNull())
{
itkExceptionMacro(
"GetImage() was already called with a different type, "
"probably due to two calls to GetParameter<Type>Image with different types in application code.");
}
CLAMP_IMAGE_BASE( TImageType, m_Image.GetPointer() );
}
}
}
/** declare a specialization for ImageBaseType */
template <>
OTBApplicationEngine_EXPORT
ImageBaseType*
InputImageParameter::GetImage<ImageBaseType>();
} // End namespace Wrapper
} // End namespace otb
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ScriptingContext.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:31: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
*
************************************************************************/
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>
#include <util/scriptingconstants.hxx>
#include <util/util.hxx>
#include "ScriptingContext.hxx"
using namespace com::sun::star;
using namespace com::sun::star::uno;
#define DOC_REF_PROPID 1
#define DOC_STORAGE_ID_PROPID 2
#define DOC_URI_PROPID 3
#define RESOLVED_STORAGE_ID_PROPID 4
#define SCRIPT_INFO_PROPID 5
#define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS() beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID
namespace func_provider
{
//*************************************************************************
// XScriptingContext implementation
//
//*************************************************************************
ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()),
OPropertyContainer( GetBroadcastHelper() ),
m_xContext( xContext )
{
OSL_TRACE( "< ScriptingContext ctor called >\n" );
validateXRef( m_xContext,
"ScriptingContext::ScriptingContext: No context available\n" );
Any nullAny;
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType( (const Reference< css::frame::XModel >* ) NULL ), NULL ) ;
registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ) ;
registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const ::rtl::OUString* ) NULL ), NULL ) ;
registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL );
registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL );
}
ScriptingContext::~ScriptingContext()
{
OSL_TRACE( "< ScriptingContext dtor called >\n" );
}
// -----------------------------------------------------------------------------
// OPropertySetHelper
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper( )
{
return *getArrayHelper();
}
// -----------------------------------------------------------------------------
// OPropertyArrayUsageHelper
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper( ) const
{
Sequence< beans::Property > aProps;
describeProperties( aProps );
return new ::cppu::OPropertyArrayHelper( aProps );
}
// -----------------------------------------------------------------------------
// XPropertySet
// -----------------------------------------------------------------------------
Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo( ) throw (RuntimeException)
{
Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
// -----------------------------------------------------------------------------// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext )
css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes( ) throw (css::uno::RuntimeException)
{
return OPropertyContainer::getTypes();
}
} // namespace func_provider
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.36); FILE MERGED 2006/09/01 17:35:36 kaib 1.7.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ScriptingContext.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 12:29:15 $
*
* 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_scripting.hxx"
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>
#include <util/scriptingconstants.hxx>
#include <util/util.hxx>
#include "ScriptingContext.hxx"
using namespace com::sun::star;
using namespace com::sun::star::uno;
#define DOC_REF_PROPID 1
#define DOC_STORAGE_ID_PROPID 2
#define DOC_URI_PROPID 3
#define RESOLVED_STORAGE_ID_PROPID 4
#define SCRIPT_INFO_PROPID 5
#define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS() beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID
namespace func_provider
{
//*************************************************************************
// XScriptingContext implementation
//
//*************************************************************************
ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()),
OPropertyContainer( GetBroadcastHelper() ),
m_xContext( xContext )
{
OSL_TRACE( "< ScriptingContext ctor called >\n" );
validateXRef( m_xContext,
"ScriptingContext::ScriptingContext: No context available\n" );
Any nullAny;
scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
scripting_constants::ScriptingConstantsPool::instance();
registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType( (const Reference< css::frame::XModel >* ) NULL ), NULL ) ;
registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ) ;
registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const ::rtl::OUString* ) NULL ), NULL ) ;
registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL );
registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL );
}
ScriptingContext::~ScriptingContext()
{
OSL_TRACE( "< ScriptingContext dtor called >\n" );
}
// -----------------------------------------------------------------------------
// OPropertySetHelper
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper( )
{
return *getArrayHelper();
}
// -----------------------------------------------------------------------------
// OPropertyArrayUsageHelper
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper( ) const
{
Sequence< beans::Property > aProps;
describeProperties( aProps );
return new ::cppu::OPropertyArrayHelper( aProps );
}
// -----------------------------------------------------------------------------
// XPropertySet
// -----------------------------------------------------------------------------
Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo( ) throw (RuntimeException)
{
Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
return xInfo;
}
// -----------------------------------------------------------------------------// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext )
css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes( ) throw (css::uno::RuntimeException)
{
return OPropertyContainer::getTypes();
}
} // namespace func_provider
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: directsql.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2003-03-19 17:52:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBACCESS_UI_DIRECTSQL_HXX_
#define _DBACCESS_UI_DIRECTSQL_HXX_
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#include <deque>
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
//........................................................................
namespace dbaui
{
//........................................................................
//====================================================================
//= DirectSQLDialog
//====================================================================
class DirectSQLDialog
:public ModalDialog
,public ::utl::OEventListenerAdapter
{
protected:
::osl::Mutex m_aMutex;
FixedLine m_aFrame;
FixedText m_aSQLLabel;
MultiLineEdit m_aSQL;
PushButton m_aExecute;
FixedText m_aHistoryLabel;
ListBox* m_pSQLHistory;
FixedLine m_aStatusFrame;
MultiLineEdit m_aStatus;
FixedLine m_aButtonSeparator;
HelpButton m_aHelp;
PushButton m_aClose;
typedef ::std::deque< String > StringQueue;
StringQueue m_aStatementHistory; // previous statements
StringQueue m_aNormalizedHistory; // previous statements, normalized to be used in the list box
sal_Int32 m_nHistoryLimit;
sal_Int32 m_nStatusCount;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
m_xConnection;
public:
DirectSQLDialog(
Window* _pParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
~DirectSQLDialog();
/// add an history entry
void addHistoryEntry(const String& _rStatement);
/// set the limit for the history size
void setHistoryLimit(sal_Int32 _nMaxEntries);
/// number of history entries
sal_Int32 getHistorySize() const;
protected:
void executeCurrent();
void switchToHistory(sal_Int32 _nHistoryPos, sal_Bool _bUpdateListBox = sal_True);
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );
protected:
DECL_LINK( OnExecute, void* );
DECL_LINK( OnClose, void* );
DECL_LINK( OnListEntrySelected, void* );
DECL_LINK( OnStatementModified, void* );
private:
/// adds a statement to the statement history
void implAddToStatementHistory(const String& _rStatement);
/// ensures that our history has at most m_nHistoryLimit entries
void implEnsureHistoryLimit();
/// executes the statement given, adds the status to the status list
void implExecuteStatement(const String& _rStatement);
/// adds a status text to the status list
void addStatusText(const String& _rMessage);
#ifdef DBG_UTIL
const sal_Char* impl_CheckInvariants() const;
#endif
};
//====================================================================
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname) \
{ \
const sal_Char* pError = impl_CheckInvariants(); \
if (pError) \
OSL_ENSURE(sal_False, (ByteString(methodname) += ByteString(": ") += ByteString(pError)).GetBuffer()); \
}
#else
#define CHECK_INVARIANTS(methodname)
#endif
//........................................................................
} // namespace dbaui
//........................................................................
#endif // _DBACCESS_UI_DIRECTSQL_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.434); FILE MERGED 2005/09/05 17:34:49 rt 1.3.434.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: directsql.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-08 15:52:11 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBACCESS_UI_DIRECTSQL_HXX_
#define _DBACCESS_UI_DIRECTSQL_HXX_
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _SVEDIT_HXX
#include <svtools/svmedit.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#include <deque>
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
//........................................................................
namespace dbaui
{
//........................................................................
//====================================================================
//= DirectSQLDialog
//====================================================================
class DirectSQLDialog
:public ModalDialog
,public ::utl::OEventListenerAdapter
{
protected:
::osl::Mutex m_aMutex;
FixedLine m_aFrame;
FixedText m_aSQLLabel;
MultiLineEdit m_aSQL;
PushButton m_aExecute;
FixedText m_aHistoryLabel;
ListBox* m_pSQLHistory;
FixedLine m_aStatusFrame;
MultiLineEdit m_aStatus;
FixedLine m_aButtonSeparator;
HelpButton m_aHelp;
PushButton m_aClose;
typedef ::std::deque< String > StringQueue;
StringQueue m_aStatementHistory; // previous statements
StringQueue m_aNormalizedHistory; // previous statements, normalized to be used in the list box
sal_Int32 m_nHistoryLimit;
sal_Int32 m_nStatusCount;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
m_xConnection;
public:
DirectSQLDialog(
Window* _pParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
~DirectSQLDialog();
/// add an history entry
void addHistoryEntry(const String& _rStatement);
/// set the limit for the history size
void setHistoryLimit(sal_Int32 _nMaxEntries);
/// number of history entries
sal_Int32 getHistorySize() const;
protected:
void executeCurrent();
void switchToHistory(sal_Int32 _nHistoryPos, sal_Bool _bUpdateListBox = sal_True);
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );
protected:
DECL_LINK( OnExecute, void* );
DECL_LINK( OnClose, void* );
DECL_LINK( OnListEntrySelected, void* );
DECL_LINK( OnStatementModified, void* );
private:
/// adds a statement to the statement history
void implAddToStatementHistory(const String& _rStatement);
/// ensures that our history has at most m_nHistoryLimit entries
void implEnsureHistoryLimit();
/// executes the statement given, adds the status to the status list
void implExecuteStatement(const String& _rStatement);
/// adds a status text to the status list
void addStatusText(const String& _rMessage);
#ifdef DBG_UTIL
const sal_Char* impl_CheckInvariants() const;
#endif
};
//====================================================================
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname) \
{ \
const sal_Char* pError = impl_CheckInvariants(); \
if (pError) \
OSL_ENSURE(sal_False, (ByteString(methodname) += ByteString(": ") += ByteString(pError)).GetBuffer()); \
}
#else
#define CHECK_INVARIANTS(methodname)
#endif
//........................................................................
} // namespace dbaui
//........................................................................
#endif // _DBACCESS_UI_DIRECTSQL_HXX_
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charsets.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:11:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBAUI_CHARSETS_HXX_
#include "charsets.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DBU_MISCRES_HRC_
#include "dbumiscres.hrc"
#endif
#ifndef _DBU_MISC_HRC_
#include "dbu_misc.hrc"
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::dbtools;
//=========================================================================
//= OCharsetDisplay
//=========================================================================
//-------------------------------------------------------------------------
OCharsetDisplay::OCharsetDisplay()
:OCharsetMap()
,SvxTextEncodingTable()
{
{
OLocalResourceAccess aCharsetStrings( RSC_CHARSETS, RSC_RESOURCE );
m_aSystemDisplayName = String( ResId( 1 ) );
}
}
//-------------------------------------------------------------------------
sal_Bool OCharsetDisplay::approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const
{
if ( !OCharsetMap::approveEncoding( _eEncoding, _rInfo ) )
return sal_False;
if ( RTL_TEXTENCODING_DONTKNOW == _eEncoding )
return sal_True;
return 0 != GetTextString( _eEncoding ).Len();
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::begin() const
{
return const_iterator( this, OCharsetMap::begin() );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::end() const
{
return const_iterator( this, OCharsetMap::end() );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::find(const rtl_TextEncoding _eEncoding) const
{
OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_eEncoding);
return const_iterator( this, aBaseIter );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rIanaName, const IANA&) const
{
OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_rIanaName, OCharsetMap::IANA());
return const_iterator( this, aBaseIter );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rDisplayName, const Display&) const
{
rtl_TextEncoding eEncoding = RTL_TEXTENCODING_DONTKNOW;
if ( _rDisplayName != m_aSystemDisplayName )
{
eEncoding = GetTextEncoding( _rDisplayName );
OSL_ENSURE( RTL_TEXTENCODING_DONTKNOW != eEncoding,
"OCharsetDisplay::find: non-empty display name, but DONTKNOW!" );
}
return const_iterator( this, OCharsetMap::find( eEncoding ) );
}
//=========================================================================
//= CharsetDisplayDerefHelper
//=========================================================================
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource)
:CharsetDisplayDerefHelper_Base(_rSource)
,m_sDisplayName(m_sDisplayName)
{
}
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper_Base& _rBase, const ::rtl::OUString& _rDisplayName)
:CharsetDisplayDerefHelper_Base(_rBase)
,m_sDisplayName(_rDisplayName)
{
DBG_ASSERT( m_sDisplayName.getLength(), "CharsetDisplayDerefHelper::CharsetDisplayDerefHelper: invalid display name!" );
}
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper::CharsetDisplayDerefHelper()
{
}
//=========================================================================
//= OCharsetDisplay::ExtendedCharsetIterator
//=========================================================================
//-------------------------------------------------------------------------
OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition )
:m_pContainer(_pContainer)
,m_aPosition(_rPosition)
{
DBG_ASSERT(m_pContainer, "OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator : invalid container!");
}
//-------------------------------------------------------------------------
OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource)
:m_pContainer( _rSource.m_pContainer )
,m_aPosition( _rSource.m_aPosition )
{
}
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper OCharsetDisplay::ExtendedCharsetIterator::operator*() const
{
DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator* : invalid position!");
rtl_TextEncoding eEncoding = (*m_aPosition).getEncoding();
return CharsetDisplayDerefHelper(
*m_aPosition,
RTL_TEXTENCODING_DONTKNOW == eEncoding ? m_pContainer->m_aSystemDisplayName : (::rtl::OUString)m_pContainer->GetTextString( eEncoding )
);
}
//-------------------------------------------------------------------------
const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator++()
{
DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator++ : invalid position!");
if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::end() )
++m_aPosition;
return *this;
}
//-------------------------------------------------------------------------
const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator--()
{
DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin(), "OCharsetDisplay::ExtendedCharsetIterator::operator-- : invalid position!");
if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin() )
--m_aPosition;
return *this;
}
//-------------------------------------------------------------------------
bool operator==(const OCharsetDisplay::ExtendedCharsetIterator& lhs, const OCharsetDisplay::ExtendedCharsetIterator& rhs)
{
return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_aPosition == rhs.m_aPosition);
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS dba203c (1.8.110); FILE MERGED 2006/03/29 11:35:43 fs 1.8.110.1: #133638# renamed ambiguous ::dbui::OLocalResourceAccess to LocalresourceAccess<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: charsets.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2006-05-04 08:45:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBAUI_CHARSETS_HXX_
#include "charsets.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _DBU_MISCRES_HRC_
#include "dbumiscres.hrc"
#endif
#ifndef _DBU_MISC_HRC_
#include "dbu_misc.hrc"
#endif
#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::dbtools;
//=========================================================================
//= OCharsetDisplay
//=========================================================================
//-------------------------------------------------------------------------
OCharsetDisplay::OCharsetDisplay()
:OCharsetMap()
,SvxTextEncodingTable()
{
{
LocalResourceAccess aCharsetStrings( RSC_CHARSETS, RSC_RESOURCE );
m_aSystemDisplayName = String( ResId( 1 ) );
}
}
//-------------------------------------------------------------------------
sal_Bool OCharsetDisplay::approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const
{
if ( !OCharsetMap::approveEncoding( _eEncoding, _rInfo ) )
return sal_False;
if ( RTL_TEXTENCODING_DONTKNOW == _eEncoding )
return sal_True;
return 0 != GetTextString( _eEncoding ).Len();
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::begin() const
{
return const_iterator( this, OCharsetMap::begin() );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::end() const
{
return const_iterator( this, OCharsetMap::end() );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::find(const rtl_TextEncoding _eEncoding) const
{
OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_eEncoding);
return const_iterator( this, aBaseIter );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rIanaName, const IANA&) const
{
OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_rIanaName, OCharsetMap::IANA());
return const_iterator( this, aBaseIter );
}
//-------------------------------------------------------------------------
OCharsetDisplay::const_iterator OCharsetDisplay::find(const ::rtl::OUString& _rDisplayName, const Display&) const
{
rtl_TextEncoding eEncoding = RTL_TEXTENCODING_DONTKNOW;
if ( _rDisplayName != m_aSystemDisplayName )
{
eEncoding = GetTextEncoding( _rDisplayName );
OSL_ENSURE( RTL_TEXTENCODING_DONTKNOW != eEncoding,
"OCharsetDisplay::find: non-empty display name, but DONTKNOW!" );
}
return const_iterator( this, OCharsetMap::find( eEncoding ) );
}
//=========================================================================
//= CharsetDisplayDerefHelper
//=========================================================================
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource)
:CharsetDisplayDerefHelper_Base(_rSource)
,m_sDisplayName(m_sDisplayName)
{
}
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper_Base& _rBase, const ::rtl::OUString& _rDisplayName)
:CharsetDisplayDerefHelper_Base(_rBase)
,m_sDisplayName(_rDisplayName)
{
DBG_ASSERT( m_sDisplayName.getLength(), "CharsetDisplayDerefHelper::CharsetDisplayDerefHelper: invalid display name!" );
}
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper::CharsetDisplayDerefHelper()
{
}
//=========================================================================
//= OCharsetDisplay::ExtendedCharsetIterator
//=========================================================================
//-------------------------------------------------------------------------
OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition )
:m_pContainer(_pContainer)
,m_aPosition(_rPosition)
{
DBG_ASSERT(m_pContainer, "OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator : invalid container!");
}
//-------------------------------------------------------------------------
OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource)
:m_pContainer( _rSource.m_pContainer )
,m_aPosition( _rSource.m_aPosition )
{
}
//-------------------------------------------------------------------------
CharsetDisplayDerefHelper OCharsetDisplay::ExtendedCharsetIterator::operator*() const
{
DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator* : invalid position!");
rtl_TextEncoding eEncoding = (*m_aPosition).getEncoding();
return CharsetDisplayDerefHelper(
*m_aPosition,
RTL_TEXTENCODING_DONTKNOW == eEncoding ? m_pContainer->m_aSystemDisplayName : (::rtl::OUString)m_pContainer->GetTextString( eEncoding )
);
}
//-------------------------------------------------------------------------
const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator++()
{
DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator++ : invalid position!");
if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::end() )
++m_aPosition;
return *this;
}
//-------------------------------------------------------------------------
const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator--()
{
DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin(), "OCharsetDisplay::ExtendedCharsetIterator::operator-- : invalid position!");
if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin() )
--m_aPosition;
return *this;
}
//-------------------------------------------------------------------------
bool operator==(const OCharsetDisplay::ExtendedCharsetIterator& lhs, const OCharsetDisplay::ExtendedCharsetIterator& rhs)
{
return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_aPosition == rhs.m_aPosition);
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>
using namespace std;
#define HASHSIZE 32
string getCutHex(unsigned char hash[HASHSIZE]) {
string base64Index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#";
string output = "";
for (int i = 0; i < 12; i+=3) {
output += base64Index[hash[i+0]>>2];
output += base64Index[((hash[i+0]&0x03)<<4) + (hash[i+1]>>4)];
output += base64Index[((hash[i+1]&0x0F)<<2) + (hash[i+2]>>6)];
output += base64Index[hash[i+2] & 0x3F];
}
return output;
}
string getPassword(string masterpass, string domain) {
string prehash = masterpass+domain;
unsigned char hash[HASHSIZE];
SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);
getCutHex(hash);
//unsigned char hash[20];
return prehash;
}
void help() {
cout << "THIS IS THE HELP PAGE" << endl;
}
int main(int argc, char* argv[]) {
// check to make sure there are enough arguments
// if (argc < 3) {
// cout << "you must specify a username with -u" << endl;
// help();
// return 0;
// }
bool silent = false;
bool passwordFlag = false;
string domain = "";
string password = "";
string *pointer = NULL;
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "-p") { // password flag
pointer = &password;
}
else if (string(argv[i]) == "-d") { // domain flag
pointer = &domain;
}
else if (string(argv[i]) == "-s") { // silent flag
silent = true;
}
else if (string(argv[i]) == "-h") { // help flag
cout << "triggered on the help flag" << endl;
help();
return 0;
}
else {
if (pointer == NULL) {
cout << "triggered on bad argument " << argv[i] << endl;
help();
return 0;
}
}
}
if (passwordFlag && !silent) {
cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
}
getPassword ("harvy","dent");
cout << "DONE!" << endl;
}<commit_msg>tested support of domain input<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>
using namespace std;
#define HASHSIZE 32
string getCutHex(unsigned char hash[HASHSIZE]) {
string base64Index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#";
string output = "";
for (int i = 0; i < 12; i+=3) {
output += base64Index[hash[i+0]>>2];
output += base64Index[((hash[i+0]&0x03)<<4) + (hash[i+1]>>4)];
output += base64Index[((hash[i+1]&0x0F)<<2) + (hash[i+2]>>6)];
output += base64Index[hash[i+2] & 0x3F];
}
return output;
}
string getPassword(string masterpass, string domain) {
string prehash = masterpass+domain;
unsigned char hash[HASHSIZE];
SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);
getCutHex(hash);
//unsigned char hash[20];
return prehash;
}
void help() {
cout << "THIS IS THE HELP PAGE" << endl;
}
int main(int argc, char* argv[]) {
// check to make sure there are enough arguments
// if (argc < 3) {
// cout << "you must specify a username with -u" << endl;
// help();
// return 0;
// }
bool silent = false;
bool passwordFlag = false;
string domain = "";
string password = "";
string *pointer = NULL;
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "-p") { // password flag
pointer = &password;
}
else if (string(argv[i]) == "-d") { // domain flag
pointer = &domain;
}
else if (string(argv[i]) == "-s") { // silent flag
silent = true;
}
else if (string(argv[i]) == "-h") { // help flag
cout << "triggered on the help flag" << endl;
help();
return 0;
}
else {
if (pointer == NULL) {
cout << "triggered on bad argument " << argv[i] << endl;
help();
return 0;
}
else {
*pointer += argv[i];
}
}
}
if (passwordFlag && !silent) {
cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
}
cout << "domain is: " << domain << endl;
cout << "password is: " << password << endl;
getPassword ("harvy","dent");
cout << "DONE!" << endl;
}<|endoftext|> |
<commit_before>#ifndef RECURSE_REQUEST_HPP
#define RECURSE_REQUEST_HPP
#include <QTcpSocket>
#include <QHash>
#include <QUrl>
#include <QUrlQuery>
class Request
{
public:
//!
//! \brief data
//! client request buffer data
//!
QString data;
//!
//! \brief socket
//! underlying client socket
//!
QTcpSocket *socket;
//!
//! \brief body_parsed
//! Data to be filled by body parsing middleware
//!
QHash<QString, QVariant> body_parsed;
//!
//! \brief body
//!
QString body;
//!
//! \brief method
//! HTTP method, eg: GET
//!
QString method;
//!
//! \brief protocol
//! Request protocol, eg: HTTP
//!
QString protocol;
//!
//! \brief secure
//! Shorthand for protocol == "HTTPS" to check if a requet was issued via TLS
//!
bool secure = protocol == "HTTPS";
//!
//! \brief url
//! HTTP request url, eg: /helloworld
//!
QUrl url;
//!
//! \brief query
//! query strings
//!
QUrlQuery query;
//!
//! \brief params
//!r
//! request parameters that can be filled by router middlewares
//! it's easier to provide container here (which doesn't have to be used)
QHash<QString, QString> params;
//!
//! \brief length
//! HTTP request Content-Length
//!
qint64 length = 0;
//!
//! \brief ip
//! Client ip address
//!
QHostAddress ip;
//!
//! \brief cookies
//! HTTP cookies in key/value form
//!
QHash<QString, QString> cookies;
//!
//! \brief hostname
//! HTTP hostname from "Host" HTTP header
//!
QString hostname;
//!
//! \brief get
//! Return HTTP request header specified by the key
//!
//! \param QString case-insensitive key of the header
//! \return QString header value
//!
QString get(const QString &key)
{
return m_header[key.toLower()];
}
//!
//! \brief parse
//! parse data from request
//!
//! \param QString request
//! \return true on success, false otherwise, considered bad request
//!
bool parse(QString request);
private:
//!
//! \brief header
//! HTTP request headers, eg: header["content-type"] = "text/plain"
//!
QHash<QString, QString> m_header;
//!
//! \brief httpRx
//! match HTTP request line
//!
QRegExp httpRx = QRegExp("^(?=[A-Z]).* \\/.* HTTP\\/[0-9]\\.[0-9]\\r\\n");
};
inline bool Request::parse(QString request)
{
// buffer all data
this->data += request;
// Save client ip address
this->ip = this->socket->peerAddress();
// if no header is present, just append all data to request.body
if (!this->data.contains(httpRx))
{
this->body.append(this->data);
return true;
}
QStringList data_list = this->data.split("\r\n");
bool is_body = false;
for (int i = 0; i < data_list.size(); ++i)
{
if (is_body)
{
this->body.append(data_list.at(i));
this->length += this->body.size();
continue;
}
QStringList entity_item = data_list.at(i).split(":");
if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body)
{
is_body = true;
continue;
}
else if (i == 0 && entity_item.length() < 2)
{
QStringList first_line = entity_item.at(0).split(" ");
this->method = first_line.at(0);
this->url = first_line.at(1).trimmed();
this->query.setQuery(this->url.query());
this->protocol = first_line.at(2).trimmed();
continue;
}
m_header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed().toLower();
}
if (m_header.contains("host"))
this->hostname = m_header["host"];
// extract cookies
// eg: USER_TOKEN=Yes;test=val
if (m_header.contains("cookie"))
{
for (const QString &cookie : this->get("cookie").split(";"))
{
int split = cookie.trimmed().indexOf("=");
if (split == -1)
continue;
QString key = cookie.left(split).trimmed();
if (!key.size())
continue;
QString value = cookie.mid(split + 1).trimmed();
this->cookies[key.toLower()] = value.toLower();
}
}
return true;
}
#endif
<commit_msg>performance improvements<commit_after>#ifndef RECURSE_REQUEST_HPP
#define RECURSE_REQUEST_HPP
#include <QTcpSocket>
#include <QHash>
#include <QUrl>
#include <QUrlQuery>
class Request
{
public:
//!
//! \brief data
//! client request buffer data
//!
QString data;
//!
//! \brief socket
//! underlying client socket
//!
QTcpSocket *socket;
//!
//! \brief body_parsed
//! Data to be filled by body parsing middleware
//!
QHash<QString, QVariant> body_parsed;
//!
//! \brief body
//!
QString body;
//!
//! \brief method
//! HTTP method, eg: GET
//!
QString method;
//!
//! \brief protocol
//! Request protocol, eg: HTTP
//!
QString protocol;
//!
//! \brief secure
//! Shorthand for protocol == "HTTPS" to check if a requet was issued via TLS
//!
bool secure = protocol == "HTTPS";
//!
//! \brief url
//! HTTP request url, eg: /helloworld
//!
QUrl url;
//!
//! \brief query
//! query strings
//!
QUrlQuery query;
//!
//! \brief params
//!r
//! request parameters that can be filled by router middlewares
//! it's easier to provide container here (which doesn't have to be used)
QHash<QString, QString> params;
//!
//! \brief length
//! HTTP request Content-Length
//!
qint64 length = 0;
//!
//! \brief ip
//! Client ip address
//!
QHostAddress ip;
//!
//! \brief cookies
//! HTTP cookies in key/value form
//!
QHash<QString, QString> cookies;
//!
//! \brief hostname
//! HTTP hostname from "Host" HTTP header
//!
QString hostname;
//!
//! \brief get
//! Return HTTP request header specified by the key
//!
//! \param QString case-insensitive key of the header
//! \return QString header value
//!
QString get(const QString &key)
{
return m_header[key.toLower()];
}
//!
//! \brief parse
//! parse data from request
//!
//! \param QString request
//! \return true on success, false otherwise, considered bad request
//!
bool parse(QString request);
private:
//!
//! \brief header
//! HTTP request headers, eg: header["content-type"] = "text/plain"
//!
QHash<QString, QString> m_header;
//!
//! \brief httpRx
//! match HTTP request line
//!
QRegExp httpRx = QRegExp("^(?=[A-Z]).* \\/.* HTTP\\/[0-9]\\.[0-9]\\r\\n");
};
inline bool Request::parse(QString request)
{
// buffer all data
this->data += request;
// Save client ip address
this->ip = this->socket->peerAddress();
// if no header is present, just append all data to request.body
if (!this->data.contains(httpRx))
{
this->body.append(this->data);
return true;
}
auto data_list = this->data.splitRef("\r\n");
bool is_body = false;
for (int i = 0; i < data_list.size(); ++i)
{
if (is_body)
{
this->body.append(data_list.at(i));
this->length += this->body.size();
continue;
}
auto entity_item = data_list.at(i).split(":");
if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body)
{
is_body = true;
continue;
}
else if (i == 0 && entity_item.length() < 2)
{
auto first_line = entity_item.at(0).split(" ");
this->method = first_line.at(0).toString();
this->url = first_line.at(1).toString();
this->query.setQuery(this->url.query());
this->protocol = first_line.at(2).toString();
continue;
}
m_header[entity_item.at(0).toString()] = entity_item.at(1).toString();
}
if (m_header.contains("host"))
this->hostname = m_header["host"];
// extract cookies
// eg: USER_TOKEN=Yes;test=val
if (m_header.contains("cookie"))
{
for (const auto &cookie : this->get("cookie").splitRef(";"))
{
int split = cookie.indexOf("=");
if (split == -1)
continue;
auto key = cookie.left(split);
if (!key.size())
continue;
auto value = cookie.mid(split + 1);
this->cookies[key.toString().toLower()] = value.toString().toLower();
}
}
return true;
}
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.