text stringlengths 54 60.6k |
|---|
<commit_before>#include "pmesh.h"
using namespace std;
using namespace glm;
PMesh::PMesh()
{
}
//Load a default mesh
void PMesh::loadObject()
{
loadObject("cube.obj");
}
void PMesh::loadObject(string filename)
{
cout << "Loading " << filename << endl;
ifstream inFile ("models/" + filename);
string line;
if (inFile.is_open())
{
string ident;
vec3 point;
while (getline(inFile, line))
{
stringstream ss (stringstream::in | stringstream::out);
ss << line;
ss >> ident;
if (ident == "v")
{
//cout << line << endl;
ss >> point.x >> point.y >> point.z;
cout << "Loaded vertex " << point.x << " " << point.y << " " << point.z << endl;
m_vertices.push_back(point);
}
else if (ident == "f")
{
int c = 0;
int last;
int vert[4];
uvec3 face;
string cur = "plop";
string subcur;
cout << "loading face ";
while (cur != "" && c < 4)
{
cout << "*";
cur = "";
ss >> cur;
stringstream subss (stringstream::in | stringstream::out);
subss << cur;
getline(subss, subcur, '/');
vert[c] = stof(subcur);
c++;
}
cout << endl;
face.x = vert[0];
face.y = vert[1];
face.z = vert[2];
m_faces.push_back(face);
cout << "Loaded face " << face.x << " " << face.y << " " << face.z << endl;
if(c == 4)
{
face.y = face.z;
face.z = vert[3];
m_faces.push_back(face);
cout << "Loaded face " << face.x << " " << face.y << " " << face.z << endl;
}
}
}
}
}
const vector<glm::vec3>& PMesh::getVertices() const
{
return m_vertices;
}
const vector<glm::uvec3>& PMesh::getIndices() const
{
return m_faces;
}
PMesh::~PMesh()
{
}
<commit_msg>fix the cube<commit_after>#include "pmesh.h"
using namespace std;
using namespace glm;
PMesh::PMesh()
{
}
//Load a default mesh
void PMesh::loadObject()
{
loadObject("cube.obj");
}
void PMesh::loadObject(string filename)
{
cout << "Loading " << filename << endl;
ifstream inFile ("models/" + filename);
string line;
if (inFile.is_open())
{
string ident;
vec3 point;
while (getline(inFile, line))
{
stringstream ss (stringstream::in | stringstream::out);
ss << line;
ss >> ident;
if (ident == "v")
{
//cout << line << endl;
ss >> point.x >> point.y >> point.z;
cout << "Loaded vertex " << point.x << " " << point.y << " " << point.z << endl;
m_vertices.push_back(point);
}
else if (ident == "f")
{
int c = 0;
int last;
int vert[4];
uvec3 face;
string cur = "plop";
string subcur;
cout << "loading face ";
while (cur != "" && c < 4)
{
cout << "*";
cur = "";
ss >> cur;
stringstream subss (stringstream::in | stringstream::out);
subss << cur;
getline(subss, subcur, '/');
vert[c] = stof(subcur) - 1;
c++;
}
cout << endl;
face.x = vert[0];
face.y = vert[1];
face.z = vert[2];
m_faces.push_back(face);
cout << "Loaded face " << face.x << " " << face.y << " " << face.z << endl;
if(c == 4)
{
face.y = face.z;
face.z = vert[3];
m_faces.push_back(face);
cout << "Loaded face " << face.x << " " << face.y << " " << face.z << endl;
}
}
}
}
}
const vector<glm::vec3>& PMesh::getVertices() const
{
return m_vertices;
}
const vector<glm::uvec3>& PMesh::getIndices() const
{
return m_faces;
}
PMesh::~PMesh()
{
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include "ten/json.hh"
using namespace ten;
const char json_text[] =
"{ \"store\": {"
" \"book\": ["
" { \"category\": \"reference\","
" \"author\": \"Nigel Rees\","
" \"title\": \"Sayings of the Century\","
" \"price\": 8.95"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Evelyn Waugh\","
" \"title\": \"Sword of Honour\","
" \"price\": 12.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }"
" ],"
" \"bicycle\": {"
" \"color\": \"red\","
" \"price\": 19.95"
" }"
" }"
"}";
BOOST_AUTO_TEST_CASE(json_test_path1) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
json r1(o.path("/store/book/author"));
BOOST_CHECK_EQUAL(json::load(a1), r1);
json r2(o.path("//author"));
BOOST_CHECK_EQUAL(json::load(a1), r2);
// jansson hashtable uses size_t for hash
// we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
json r3(o.path("/store/*"));
json t3(json::load(a3));
BOOST_CHECK_EQUAL(t3, r3);
#if (__SIZEOF_SIZE_T__ == 4)
static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
json r4(o.path("/store//price"));
BOOST_CHECK_EQUAL(json::load(a4), r4);
static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
json r5(o.path("//book[3]"));
BOOST_CHECK_EQUAL(json::load(a5), r5);
static const char a6[] = "\"J. R. R. Tolkien\"";
json r6(o.path("/store/book[3]/author"));
BOOST_CHECK_EQUAL(json::load(a6), r6);
BOOST_CHECK(json::load(a6) == r6);
static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
json r7(o.path("/store/book[category=\"fiction\"]"));
BOOST_CHECK_EQUAL(json::load(a7), r7);
}
BOOST_AUTO_TEST_CASE(json_test_path2) {
json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}
BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a[] = "["
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }]";
json r(o.path("//book[isbn]"));
BOOST_CHECK_EQUAL(json::load(a), r);
json r1(o.path("//book[doesnotexist]"));
BOOST_REQUIRE(r1.is_array());
BOOST_CHECK_EQUAL(0, r1.asize());
}
BOOST_AUTO_TEST_CASE(json_test_truth) {
json o(json::object());
BOOST_CHECK(o.get("nothing").is_true() == false);
BOOST_CHECK(o.get("nothing").is_false() == false);
BOOST_CHECK(o.get("nothing").is_null() == false);
BOOST_CHECK(!o.get("nothing"));
}
BOOST_AUTO_TEST_CASE(json_test_path3) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
BOOST_CHECK_EQUAL(o, o.path("/"));
BOOST_CHECK_EQUAL("Sayings of the Century",
o.path("/store/book[category=\"reference\"]/title"));
static const char text[] = "["
"{\"type\":\"a\", \"value\":0},"
"{\"type\":\"b\", \"value\":1},"
"{\"type\":\"c\", \"value\":2},"
"{\"type\":\"c\", \"value\":3}"
"]";
BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
BOOST_AUTO_TEST_CASE(json_init_list) {
json meta{
{ "foo", 17 },
{ "bar", 23 },
{ "baz", true },
{ "corge", json::array({ 1, 3.14159 }) },
{ "grault", json::array({ "hello", string("world") }) },
};
BOOST_REQUIRE(meta);
BOOST_REQUIRE(meta.is_object());
BOOST_CHECK_EQUAL(meta.osize(), 5);
BOOST_CHECK_EQUAL(meta["foo"].integer(), 17);
BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1);
BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world");
}
template <class T>
inline void test_conv(T val, json j, json_type t) {
json j2 = to_json(val);
BOOST_CHECK_EQUAL(j2.type(), t);
BOOST_CHECK_EQUAL(j, j2);
T val2 = json_cast<T>(j2);
BOOST_CHECK_EQUAL(val, val2);
}
template <class T, json_type TYPE = JSON_INTEGER>
inline void test_conv_num() {
typedef numeric_limits<T> lim;
T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };
for (unsigned i = 0; i < 5; ++i)
test_conv<T>(range[i], json(range[i]), TYPE);
}
BOOST_AUTO_TEST_CASE(json_conversions) {
test_conv<string>(string("hello"), json::str("hello"), JSON_STRING);
BOOST_CHECK_EQUAL(to_json("world"), json::str("world"));
test_conv_num<short>();
test_conv_num<int>();
test_conv_num<long>();
test_conv_num<long long>();
test_conv_num<unsigned short>();
test_conv_num<unsigned>();
#if ULONG_MAX < LLONG_MAX
test_conv_num<unsigned long>();
#endif
test_conv_num<double, JSON_REAL>();
test_conv_num<float, JSON_REAL>();
test_conv<bool>(true, json::jtrue(), JSON_TRUE);
test_conv<bool>(false, json::jfalse(), JSON_FALSE);
}
<commit_msg>initial test of JSON serialization<commit_after>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include "ten/json.hh"
#include "ten/jserial.hh"
using namespace ten;
const char json_text[] =
"{ \"store\": {"
" \"book\": ["
" { \"category\": \"reference\","
" \"author\": \"Nigel Rees\","
" \"title\": \"Sayings of the Century\","
" \"price\": 8.95"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Evelyn Waugh\","
" \"title\": \"Sword of Honour\","
" \"price\": 12.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }"
" ],"
" \"bicycle\": {"
" \"color\": \"red\","
" \"price\": 19.95"
" }"
" }"
"}";
BOOST_AUTO_TEST_CASE(json_test_path1) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
json r1(o.path("/store/book/author"));
BOOST_CHECK_EQUAL(json::load(a1), r1);
json r2(o.path("//author"));
BOOST_CHECK_EQUAL(json::load(a1), r2);
// jansson hashtable uses size_t for hash
// we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
json r3(o.path("/store/*"));
json t3(json::load(a3));
BOOST_CHECK_EQUAL(t3, r3);
#if (__SIZEOF_SIZE_T__ == 4)
static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
json r4(o.path("/store//price"));
BOOST_CHECK_EQUAL(json::load(a4), r4);
static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
json r5(o.path("//book[3]"));
BOOST_CHECK_EQUAL(json::load(a5), r5);
static const char a6[] = "\"J. R. R. Tolkien\"";
json r6(o.path("/store/book[3]/author"));
BOOST_CHECK_EQUAL(json::load(a6), r6);
BOOST_CHECK(json::load(a6) == r6);
static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
json r7(o.path("/store/book[category=\"fiction\"]"));
BOOST_CHECK_EQUAL(json::load(a7), r7);
}
BOOST_AUTO_TEST_CASE(json_test_path2) {
json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}
BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
static const char a[] = "["
" { \"category\": \"fiction\","
" \"author\": \"Herman Melville\","
" \"title\": \"Moby Dick\","
" \"isbn\": \"0-553-21311-3\","
" \"price\": 8.99"
" },"
" { \"category\": \"fiction\","
" \"author\": \"J. R. R. Tolkien\","
" \"title\": \"The Lord of the Rings\","
" \"isbn\": \"0-395-19395-8\","
" \"price\": 22.99"
" }]";
json r(o.path("//book[isbn]"));
BOOST_CHECK_EQUAL(json::load(a), r);
json r1(o.path("//book[doesnotexist]"));
BOOST_REQUIRE(r1.is_array());
BOOST_CHECK_EQUAL(0, r1.asize());
}
BOOST_AUTO_TEST_CASE(json_test_truth) {
json o(json::object());
BOOST_CHECK(o.get("nothing").is_true() == false);
BOOST_CHECK(o.get("nothing").is_false() == false);
BOOST_CHECK(o.get("nothing").is_null() == false);
BOOST_CHECK(!o.get("nothing"));
}
BOOST_AUTO_TEST_CASE(json_test_path3) {
json o(json::load(json_text));
BOOST_REQUIRE(o.get());
BOOST_CHECK_EQUAL(o, o.path("/"));
BOOST_CHECK_EQUAL("Sayings of the Century",
o.path("/store/book[category=\"reference\"]/title"));
static const char text[] = "["
"{\"type\":\"a\", \"value\":0},"
"{\"type\":\"b\", \"value\":1},"
"{\"type\":\"c\", \"value\":2},"
"{\"type\":\"c\", \"value\":3}"
"]";
BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
BOOST_AUTO_TEST_CASE(json_init_list) {
json meta{
{ "foo", 17 },
{ "bar", 23 },
{ "baz", true },
{ "corge", json::array({ 1, 3.14159 }) },
{ "grault", json::array({ "hello", string("world") }) },
};
BOOST_REQUIRE(meta);
BOOST_REQUIRE(meta.is_object());
BOOST_CHECK_EQUAL(meta.osize(), 5);
BOOST_CHECK_EQUAL(meta["foo"].integer(), 17);
BOOST_CHECK_EQUAL(meta["corge"][0].integer(), 1);
BOOST_CHECK_EQUAL(meta["grault"][1].str(), "world");
}
template <class T>
inline void test_conv(T val, json j, json_type t) {
json j2 = to_json(val);
BOOST_CHECK_EQUAL(j2.type(), t);
BOOST_CHECK_EQUAL(j, j2);
T val2 = json_cast<T>(j2);
BOOST_CHECK_EQUAL(val, val2);
}
template <class T, json_type TYPE = JSON_INTEGER>
inline void test_conv_num() {
typedef numeric_limits<T> lim;
T range[5] = { lim::min(), T(-1), 0, T(1), lim::max() };
for (unsigned i = 0; i < 5; ++i)
test_conv<T>(range[i], json(range[i]), TYPE);
}
BOOST_AUTO_TEST_CASE(json_conversions) {
test_conv<string>(string("hello"), json::str("hello"), JSON_STRING);
BOOST_CHECK_EQUAL(to_json("world"), json::str("world"));
test_conv_num<short>();
test_conv_num<int>();
test_conv_num<long>();
test_conv_num<long long>();
test_conv_num<unsigned short>();
test_conv_num<unsigned>();
#if ULONG_MAX < LLONG_MAX
test_conv_num<unsigned long>();
#endif
test_conv_num<double, JSON_REAL>();
test_conv_num<float, JSON_REAL>();
test_conv<bool>(true, json::jtrue(), JSON_TRUE);
test_conv<bool>(false, json::jfalse(), JSON_FALSE);
}
struct corge {
int foo;
string bar;
corge() : foo(), bar() {}
corge(int foo_, string bar_) : foo(foo_), bar(bar_) {}
};
template <class AR>
inline AR & operator & (AR &ar, corge &c) {
return ar & kv("foo", c.foo) & kv("bar", c.bar);
}
inline bool operator == (const corge &a, const corge &b) {
return a.foo == b.foo && a.bar == b.bar;
}
BOOST_AUTO_TEST_CASE(json_serial) {
corge c1(42, "grault");
auto j = jsave_all(c1);
cout << "json: " << j.dump() << endl;
corge c2;
JLoad(j) >> c2;
BOOST_CHECK(c1 == c2);
#if 0
map<string, int> m;
JLoad(j) >> m;
cout << "map:";
for (auto v : m)
cout << " " << v.first << ":" << v.second;
cout << endl;
BOOST_CHECK_EQUAL(m.size(), 5);
BOOST_CHECK(m.find("bucks") != m.end());
BOOST_CHECK_EQUAL(m["bucks"], 1);
#endif
}
<|endoftext|> |
<commit_before>//===- Signals.cpp - Signal Handling support --------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occurring while your program is running.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Signals.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Options.h"
#include <vector>
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//=== independent code.
//===----------------------------------------------------------------------===//
using namespace llvm;
// Use explicit storage to avoid accessing cl::opt in a signal handler.
static bool DisableSymbolicationFlag = false;
static cl::opt<bool, true>
DisableSymbolication("disable-symbolication",
cl::desc("Disable symbolizing crash backtraces."),
cl::location(DisableSymbolicationFlag), cl::Hidden);
// Callbacks to run in signal handler must be lock-free because a signal handler
// could be running as we add new callbacks. We don't add unbounded numbers of
// callbacks, an array is therefore sufficient.
struct CallbackAndCookie {
sys::SignalHandlerCallback Callback;
void *Cookie;
enum class Status { Empty, Initializing, Initialized, Executing };
std::atomic<Status> Flag;
};
static constexpr size_t MaxSignalHandlerCallbacks = 8;
static CallbackAndCookie CallBacksToRun[MaxSignalHandlerCallbacks];
// Signal-safe.
void sys::RunSignalHandlers() {
for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
auto &RunMe = CallBacksToRun[I];
auto Expected = CallbackAndCookie::Status::Initialized;
auto Desired = CallbackAndCookie::Status::Executing;
if (!RunMe.Flag.compare_exchange_strong(Expected, Desired))
continue;
(*RunMe.Callback)(RunMe.Cookie);
RunMe.Callback = nullptr;
RunMe.Cookie = nullptr;
RunMe.Flag.store(CallbackAndCookie::Status::Empty);
}
}
// Signal-safe.
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr,
void *Cookie) {
for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
auto &SetMe = CallBacksToRun[I];
auto Expected = CallbackAndCookie::Status::Empty;
auto Desired = CallbackAndCookie::Status::Initializing;
if (!SetMe.Flag.compare_exchange_strong(Expected, Desired))
continue;
SetMe.Callback = FnPtr;
SetMe.Cookie = Cookie;
SetMe.Flag.store(CallbackAndCookie::Status::Initialized);
return;
}
report_fatal_error("too many signal callbacks already registered");
}
static bool findModulesAndOffsets(void **StackTrace, int Depth,
const char **Modules, intptr_t *Offsets,
const char *MainExecutableName,
StringSaver &StrPool);
/// Format a pointer value as hexadecimal. Zero pad it out so its always the
/// same width.
static FormattedNumber format_ptr(void *PC) {
// Each byte is two hex digits plus 2 for the 0x prefix.
unsigned PtrWidth = 2 + 2 * sizeof(void *);
return format_hex((uint64_t)PC, PtrWidth);
}
/// Helper that launches llvm-symbolizer and symbolizes a backtrace.
LLVM_ATTRIBUTE_USED
static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
int Depth, llvm::raw_ostream &OS) {
if (DisableSymbolicationFlag)
return false;
// Don't recursively invoke the llvm-symbolizer binary.
if (Argv0.find("llvm-symbolizer") != std::string::npos)
return false;
// FIXME: Subtract necessary number from StackTrace entries to turn return addresses
// into actual instruction addresses.
// Use llvm-symbolizer tool to symbolize the stack traces. First look for it
// alongside our binary, then in $PATH.
ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
if (!Argv0.empty()) {
StringRef Parent = llvm::sys::path::parent_path(Argv0);
if (!Parent.empty())
LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
}
if (!LLVMSymbolizerPathOrErr)
LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
if (!LLVMSymbolizerPathOrErr)
return false;
const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
// If we don't know argv0 or the address of main() at this point, try
// to guess it anyway (it's possible on some platforms).
std::string MainExecutableName =
Argv0.empty() ? sys::fs::getMainExecutable(nullptr, nullptr)
: (std::string)Argv0;
BumpPtrAllocator Allocator;
StringSaver StrPool(Allocator);
std::vector<const char *> Modules(Depth, nullptr);
std::vector<intptr_t> Offsets(Depth, 0);
if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
MainExecutableName.c_str(), StrPool))
return false;
int InputFD;
SmallString<32> InputFile, OutputFile;
sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
FileRemover InputRemover(InputFile.c_str());
FileRemover OutputRemover(OutputFile.c_str());
{
raw_fd_ostream Input(InputFD, true);
for (int i = 0; i < Depth; i++) {
if (Modules[i])
Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
}
}
Optional<StringRef> Redirects[] = {StringRef(InputFile),
StringRef(OutputFile), StringRef("")};
StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
#ifdef _WIN32
// Pass --relative-address on Windows so that we don't
// have to add ImageBase from PE file.
// FIXME: Make this the default for llvm-symbolizer.
"--relative-address",
#endif
"--demangle"};
int RunResult =
sys::ExecuteAndWait(LLVMSymbolizerPath, Args, None, Redirects);
if (RunResult != 0)
return false;
// This report format is based on the sanitizer stack trace printer. See
// sanitizer_stacktrace_printer.cc in compiler-rt.
auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
if (!OutputBuf)
return false;
StringRef Output = OutputBuf.get()->getBuffer();
SmallVector<StringRef, 32> Lines;
Output.split(Lines, "\n");
auto CurLine = Lines.begin();
int frame_no = 0;
for (int i = 0; i < Depth; i++) {
auto PrintLineHeader = [&]() {
OS << right_justify(formatv("#{0}", frame_no++).str(),
std::log10(Depth) + 2)
<< ' ' << format_ptr(StackTrace[i]) << ' ';
};
if (!Modules[i]) {
PrintLineHeader();
OS << '\n';
continue;
}
// Read pairs of lines (function name and file/line info) until we
// encounter empty line.
for (;;) {
if (CurLine == Lines.end())
return false;
StringRef FunctionName = *CurLine++;
if (FunctionName.empty())
break;
PrintLineHeader();
if (!FunctionName.startswith("??"))
OS << FunctionName << ' ';
if (CurLine == Lines.end())
return false;
StringRef FileLineInfo = *CurLine++;
if (!FileLineInfo.startswith("??"))
OS << FileLineInfo;
else
OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
OS << "\n";
}
}
return true;
}
// Include the platform-specific parts of this class.
#ifdef LLVM_ON_UNIX
#include "Unix/Signals.inc"
#endif
#ifdef _WIN32
#include "Windows/Signals.inc"
#endif
<commit_msg>Only use argv[0] as the main executable name if it exists.<commit_after>//===- Signals.cpp - Signal Handling support --------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occurring while your program is running.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/Signals.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/FormatAdapters.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/StringSaver.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Options.h"
#include <vector>
//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//=== independent code.
//===----------------------------------------------------------------------===//
using namespace llvm;
// Use explicit storage to avoid accessing cl::opt in a signal handler.
static bool DisableSymbolicationFlag = false;
static cl::opt<bool, true>
DisableSymbolication("disable-symbolication",
cl::desc("Disable symbolizing crash backtraces."),
cl::location(DisableSymbolicationFlag), cl::Hidden);
// Callbacks to run in signal handler must be lock-free because a signal handler
// could be running as we add new callbacks. We don't add unbounded numbers of
// callbacks, an array is therefore sufficient.
struct CallbackAndCookie {
sys::SignalHandlerCallback Callback;
void *Cookie;
enum class Status { Empty, Initializing, Initialized, Executing };
std::atomic<Status> Flag;
};
static constexpr size_t MaxSignalHandlerCallbacks = 8;
static CallbackAndCookie CallBacksToRun[MaxSignalHandlerCallbacks];
// Signal-safe.
void sys::RunSignalHandlers() {
for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
auto &RunMe = CallBacksToRun[I];
auto Expected = CallbackAndCookie::Status::Initialized;
auto Desired = CallbackAndCookie::Status::Executing;
if (!RunMe.Flag.compare_exchange_strong(Expected, Desired))
continue;
(*RunMe.Callback)(RunMe.Cookie);
RunMe.Callback = nullptr;
RunMe.Cookie = nullptr;
RunMe.Flag.store(CallbackAndCookie::Status::Empty);
}
}
// Signal-safe.
static void insertSignalHandler(sys::SignalHandlerCallback FnPtr,
void *Cookie) {
for (size_t I = 0; I < MaxSignalHandlerCallbacks; ++I) {
auto &SetMe = CallBacksToRun[I];
auto Expected = CallbackAndCookie::Status::Empty;
auto Desired = CallbackAndCookie::Status::Initializing;
if (!SetMe.Flag.compare_exchange_strong(Expected, Desired))
continue;
SetMe.Callback = FnPtr;
SetMe.Cookie = Cookie;
SetMe.Flag.store(CallbackAndCookie::Status::Initialized);
return;
}
report_fatal_error("too many signal callbacks already registered");
}
static bool findModulesAndOffsets(void **StackTrace, int Depth,
const char **Modules, intptr_t *Offsets,
const char *MainExecutableName,
StringSaver &StrPool);
/// Format a pointer value as hexadecimal. Zero pad it out so its always the
/// same width.
static FormattedNumber format_ptr(void *PC) {
// Each byte is two hex digits plus 2 for the 0x prefix.
unsigned PtrWidth = 2 + 2 * sizeof(void *);
return format_hex((uint64_t)PC, PtrWidth);
}
/// Helper that launches llvm-symbolizer and symbolizes a backtrace.
LLVM_ATTRIBUTE_USED
static bool printSymbolizedStackTrace(StringRef Argv0, void **StackTrace,
int Depth, llvm::raw_ostream &OS) {
if (DisableSymbolicationFlag)
return false;
// Don't recursively invoke the llvm-symbolizer binary.
if (Argv0.find("llvm-symbolizer") != std::string::npos)
return false;
// FIXME: Subtract necessary number from StackTrace entries to turn return addresses
// into actual instruction addresses.
// Use llvm-symbolizer tool to symbolize the stack traces. First look for it
// alongside our binary, then in $PATH.
ErrorOr<std::string> LLVMSymbolizerPathOrErr = std::error_code();
if (!Argv0.empty()) {
StringRef Parent = llvm::sys::path::parent_path(Argv0);
if (!Parent.empty())
LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer", Parent);
}
if (!LLVMSymbolizerPathOrErr)
LLVMSymbolizerPathOrErr = sys::findProgramByName("llvm-symbolizer");
if (!LLVMSymbolizerPathOrErr)
return false;
const std::string &LLVMSymbolizerPath = *LLVMSymbolizerPathOrErr;
// If we don't know argv0 or the address of main() at this point, try
// to guess it anyway (it's possible on some platforms).
std::string MainExecutableName =
sys::fs::exists(Argv0) ? (std::string)Argv0
: sys::fs::getMainExecutable(nullptr, nullptr);
BumpPtrAllocator Allocator;
StringSaver StrPool(Allocator);
std::vector<const char *> Modules(Depth, nullptr);
std::vector<intptr_t> Offsets(Depth, 0);
if (!findModulesAndOffsets(StackTrace, Depth, Modules.data(), Offsets.data(),
MainExecutableName.c_str(), StrPool))
return false;
int InputFD;
SmallString<32> InputFile, OutputFile;
sys::fs::createTemporaryFile("symbolizer-input", "", InputFD, InputFile);
sys::fs::createTemporaryFile("symbolizer-output", "", OutputFile);
FileRemover InputRemover(InputFile.c_str());
FileRemover OutputRemover(OutputFile.c_str());
{
raw_fd_ostream Input(InputFD, true);
for (int i = 0; i < Depth; i++) {
if (Modules[i])
Input << Modules[i] << " " << (void*)Offsets[i] << "\n";
}
}
Optional<StringRef> Redirects[] = {StringRef(InputFile),
StringRef(OutputFile), StringRef("")};
StringRef Args[] = {"llvm-symbolizer", "--functions=linkage", "--inlining",
#ifdef _WIN32
// Pass --relative-address on Windows so that we don't
// have to add ImageBase from PE file.
// FIXME: Make this the default for llvm-symbolizer.
"--relative-address",
#endif
"--demangle"};
int RunResult =
sys::ExecuteAndWait(LLVMSymbolizerPath, Args, None, Redirects);
if (RunResult != 0)
return false;
// This report format is based on the sanitizer stack trace printer. See
// sanitizer_stacktrace_printer.cc in compiler-rt.
auto OutputBuf = MemoryBuffer::getFile(OutputFile.c_str());
if (!OutputBuf)
return false;
StringRef Output = OutputBuf.get()->getBuffer();
SmallVector<StringRef, 32> Lines;
Output.split(Lines, "\n");
auto CurLine = Lines.begin();
int frame_no = 0;
for (int i = 0; i < Depth; i++) {
auto PrintLineHeader = [&]() {
OS << right_justify(formatv("#{0}", frame_no++).str(),
std::log10(Depth) + 2)
<< ' ' << format_ptr(StackTrace[i]) << ' ';
};
if (!Modules[i]) {
PrintLineHeader();
OS << '\n';
continue;
}
// Read pairs of lines (function name and file/line info) until we
// encounter empty line.
for (;;) {
if (CurLine == Lines.end())
return false;
StringRef FunctionName = *CurLine++;
if (FunctionName.empty())
break;
PrintLineHeader();
if (!FunctionName.startswith("??"))
OS << FunctionName << ' ';
if (CurLine == Lines.end())
return false;
StringRef FileLineInfo = *CurLine++;
if (!FileLineInfo.startswith("??"))
OS << FileLineInfo;
else
OS << "(" << Modules[i] << '+' << format_hex(Offsets[i], 0) << ")";
OS << "\n";
}
}
return true;
}
// Include the platform-specific parts of this class.
#ifdef LLVM_ON_UNIX
#include "Unix/Signals.inc"
#endif
#ifdef _WIN32
#include "Windows/Signals.inc"
#endif
<|endoftext|> |
<commit_before><commit_msg>Suppress more media timeupdate events when seeking<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: certificatechooser.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: mt $ $Date: 2004-07-12 13:15:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLSECURITY_CERTIFICATECHOOSER_HXX
#define _XMLSECURITY_CERTIFICATECHOOSER_HXX
#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <svx/simptabl.hxx>
namespace com {
namespace sun {
namespace star {
namespace security {
class XCertificate; }
namespace xml { namespace crypto {
class XSecurityEnvironment; }}
}}}
#include <com/sun/star/uno/Sequence.hxx>
#ifndef _SIGSTRUCT_HXX
#include <xmlsecurity/sigstruct.hxx>
#endif
namespace css = com::sun::star;
namespace cssu = com::sun::star::uno;
namespace dcss = ::com::sun::star;
class HeaderBar;
class CertificateChooser : public ModalDialog
{
private:
// XSecurityEnvironment is needed for building the certification path
cssu::Reference< dcss::xml::crypto::XSecurityEnvironment > mxSecurityEnvironment;
// Show info for this certificate
cssu::Sequence< cssu::Reference< dcss::security::XCertificate > > maCerts;
FixedText maHintFT;
SvxSimpleTable maCertLB;
PushButton maViewBtn;
FixedLine maBottomSepFL;
OKButton maOKBtn;
CancelButton maCancelBtn;
HelpButton maHelpBtn;
USHORT GetSelectedEntryPos( void ) const;
DECL_LINK( ViewButtonHdl, Button* );
DECL_LINK( CertificateHighlightHdl, void* );
DECL_LINK( CertificateSelectHdl, void* );
void ImplShowCertificateDetails();
public:
CertificateChooser( Window* pParent, cssu::Reference< dcss::xml::crypto::XSecurityEnvironment >& rxSecurityEnvironment, const SignatureInformations& rCertsToIgnore );
~CertificateChooser();
cssu::Reference< dcss::security::XCertificate > GetSelectedCertificate();
};
#endif // _XMLSECURITY_CERTIFICATECHOOSER_HXX
<commit_msg>INTEGRATION: CWS xmlsec12 (1.1.1.1.44); FILE MERGED 2005/05/09 12:30:27 mt 1.1.1.1.44.1: #i48432# Moved getPersonalCertificates...<commit_after>/*************************************************************************
*
* $RCSfile: certificatechooser.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-05-18 09:56:40 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLSECURITY_CERTIFICATECHOOSER_HXX
#define _XMLSECURITY_CERTIFICATECHOOSER_HXX
#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <svx/simptabl.hxx>
namespace com {
namespace sun {
namespace star {
namespace security {
class XCertificate; }
namespace xml { namespace crypto {
class XSecurityEnvironment; }}
}}}
#include <com/sun/star/uno/Sequence.hxx>
#ifndef _SIGSTRUCT_HXX
#include <xmlsecurity/sigstruct.hxx>
#endif
namespace css = com::sun::star;
namespace cssu = com::sun::star::uno;
namespace dcss = ::com::sun::star;
class HeaderBar;
class CertificateChooser : public ModalDialog
{
private:
cssu::Reference< dcss::xml::crypto::XSecurityEnvironment > mxSecurityEnvironment;
cssu::Sequence< cssu::Reference< dcss::security::XCertificate > > maCerts;
SignatureInformations maCertsToIgnore;
FixedText maHintFT;
SvxSimpleTable maCertLB;
PushButton maViewBtn;
FixedLine maBottomSepFL;
OKButton maOKBtn;
CancelButton maCancelBtn;
HelpButton maHelpBtn;
BOOL mbInitialized;
USHORT GetSelectedEntryPos( void ) const;
// DECL_LINK( Initialize, void* );
DECL_LINK( ViewButtonHdl, Button* );
DECL_LINK( CertificateHighlightHdl, void* );
DECL_LINK( CertificateSelectHdl, void* );
void ImplShowCertificateDetails();
void ImplInitialize();
public:
CertificateChooser( Window* pParent, cssu::Reference< dcss::xml::crypto::XSecurityEnvironment >& rxSecurityEnvironment, const SignatureInformations& rCertsToIgnore );
~CertificateChooser();
short Execute();
cssu::Reference< dcss::security::XCertificate > GetSelectedCertificate();
};
#endif // _XMLSECURITY_CERTIFICATECHOOSER_HXX
<|endoftext|> |
<commit_before><commit_msg>loplugin:deletedspecial<commit_after><|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
if (m_Options.RawInput)
m_Interp.declare(input);
else
m_Interp.process(input, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
if (CurPtr == MB->getBufferEnd()) {
// Already at end of the buffer, return just the zero byte at the end.
return StringRef(CurPtr, 0);
}
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
if(Str.empty())
return Str;
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
ends = begins + 1;
return llvm::StringRef(Str.c_str() + begins, ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t - Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
llvm::outs() << "function with signature ret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
llvm::outs() << "given - adds the path to the include paths\n";
llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t - Toggle wrapping and printing ";
llvm::outs() << "the execution results of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
llvm::outs() << "dynamic scopes and the late binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
llvm::outs() << "corresponding AST nodes\n";
llvm::outs() << ".help\t\t\t\t - Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
Interpreter::CompilationResult interpRes
= m_Interp.declare(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""));
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<commit_msg>Align the help message to 80. Fixes bug #95066<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------
#include "cling/MetaProcessor/MetaProcessor.h"
#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Support/Path.h"
using namespace clang;
namespace cling {
MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
m_InputValidator.reset(new InputValidator());
}
MetaProcessor::~MetaProcessor() {}
int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
if (!input_text) { // null pointer, nothing to do.
return 0;
}
if (!input_text[0]) { // empty string, nothing to do.
return m_InputValidator->getExpectedIndent();
}
std::string input_line(input_text);
if (input_line == "\n") { // just a blank line, nothing to do.
return 0;
}
// Check for and handle any '.' commands.
bool was_meta = false;
if ((input_line[0] == '.') && (input_line.size() > 1)) {
was_meta = ProcessMeta(input_line, result);
}
if (was_meta) {
return 0;
}
// Check if the current statement is now complete. If not, return to
// prompt for more.
if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
== InputValidator::kIncomplete) {
return m_InputValidator->getExpectedIndent();
}
// We have a complete statement, compile and execute it.
std::string input = m_InputValidator->TakeInput();
m_InputValidator->Reset();
if (m_Options.RawInput)
m_Interp.declare(input);
else
m_Interp.process(input, result);
return 0;
}
MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
// Take interpreter's state
m_Options.PrintingAST = m_Interp.isPrintingAST();
return m_Options;
}
bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){
llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
LangOptions LO;
LO.C99 = 1;
// necessary for the @ symbol
LO.ObjC1 = 1;
Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
MB->getBufferStart(), MB->getBufferEnd());
Token Tok;
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::period))
return false;
// Read the command
RawLexer.LexFromRawLexer(Tok);
if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
return false;
const std::string Command = GetRawTokenName(Tok);
std::string Param;
// .q //Quits
if (Command == "q") {
m_Options.Quitting = true;
return true;
}
// .L <filename> // Load code fragment.
else if (Command == "L") {
// TODO: Additional checks on params
bool success
= m_Interp.loadFile(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!success) {
llvm::errs() << "Load file failed.\n";
}
return true;
}
// .(x|X) <filename> // Execute function from file, function name is
// // filename without extension.
else if ((Command == "x") || (Command == "X")) {
// TODO: Additional checks on params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (!path.isValid())
return false;
bool success = executeFile(path.c_str(), result);
if (!success) {
llvm::errs()<< "Execute file failed.\n";
}
return true;
}
// .printAST [0|1] // Toggle the printing of the AST or if 1 or 0 is given
// // enable or disable it.
else if (Command == "printAST") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool print = !m_Interp.isPrintingAST();
m_Interp.enablePrintAST(print);
llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enablePrintAST(false);
else
m_Interp.enablePrintAST(true);
}
m_Options.PrintingAST = m_Interp.isPrintingAST();
return true;
}
// .rawInput [0|1] // Toggle the raw input or if 1 or 0 is given enable
// // or disable it.
else if (Command == "rawInput") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
m_Options.RawInput = !m_Options.RawInput;
llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Options.RawInput = false;
else
m_Options.RawInput = true;
}
return true;
}
//
// .U <filename>
//
// Unload code fragment.
//
//if (cmd_char == 'U') {
// llvm::sys::Path path(param);
// if (path.isDynamicLibrary()) {
// std::cerr << "[i] Failure: cannot unload shared libraries yet!"
// << std::endl;
// }
// bool success = m_Interp.unloadFile(param);
// if (!success) {
// //fprintf(stderr, "Unload file failed.\n");
// }
// return true;
//}
//
// Unrecognized command.
//
//fprintf(stderr, "Unrecognized command.\n");
else if (Command == "I") {
// Check for params
llvm::sys::Path path(SanitizeArg(ReadToEndOfBuffer(RawLexer, MB)));
if (path.isEmpty())
m_Interp.DumpIncludePath();
else {
// TODO: Additional checks on params
if (path.isValid())
m_Interp.AddIncludePath(path.c_str());
else
return false;
}
return true;
}
// Cancel the multiline input that has been requested
else if (Command == "@") {
m_InputValidator->Reset();
return true;
}
// Enable/Disable DynamicExprTransformer
else if (Command == "dynamicExtensions") {
// Check for params
RawLexer.LexFromRawLexer(Tok);
if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
return false;
if (Tok.is(tok::eof)) {
// toggle:
bool dynlookup = !m_Interp.isDynamicLookupEnabled();
m_Interp.enableDynamicLookup(dynlookup);
llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
} else {
Param = GetRawTokenName(Tok);
if (Param == "0")
m_Interp.enableDynamicLookup(false);
else
m_Interp.enableDynamicLookup(true);
}
return true;
}
// Print Help
else if (Command == "help") {
PrintCommandHelp();
return true;
}
// Print the loaded files
else if (Command == "file") {
PrintFileStats();
return true;
}
return false;
}
std::string MetaProcessor::GetRawTokenName(const Token& Tok) {
assert(!Tok.needsCleaning() && "Not implemented yet");
switch (Tok.getKind()) {
default:
assert("Unknown token");
return "";
case tok::at:
return "@";
case tok::l_paren:
return "(";
case tok::r_paren:
return ")";
case tok::period:
return ".";
case tok::slash:
return "/";
case tok::numeric_constant:
return StringRef(Tok.getLiteralData(), Tok.getLength()).str();
case tok::raw_identifier:
return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
}
}
llvm::StringRef MetaProcessor::ReadToEndOfBuffer(Lexer& RawLexer,
llvm::MemoryBuffer* MB) {
const char* CurPtr = RawLexer.getBufferLocation();
if (CurPtr == MB->getBufferEnd()) {
// Already at end of the buffer, return just the zero byte at the end.
return StringRef(CurPtr, 0);
}
Token TmpTok;
RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
return StringRef(CurPtr, MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
}
llvm::StringRef MetaProcessor::SanitizeArg(const std::string& Str) {
if(Str.empty())
return Str;
size_t begins = Str.find_first_not_of(" \t\n");
size_t ends = Str.find_last_not_of(" \t\n") + 1;
if (begins == std::string::npos)
ends = begins + 1;
return llvm::StringRef(Str.c_str() + begins, ends - begins);
}
void MetaProcessor::PrintCommandHelp() {
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << ".q\t\t\t\t- Exit the program\n";
llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
llvm::outs() << ".(x|X) <filename>[args]\t\t- Same as .L and runs a ";
llvm::outs() << "function with signature ";
llvm::outs() << "\t\t\t\tret_type filename(args)\n";
llvm::outs() << ".I [path]\t\t\t- Shows the include path. If a path is ";
llvm::outs() << "given - \n\t\t\t\tadds the path to the include paths\n";
llvm::outs() << ".@ \t\t\t\t- Cancels and ignores the multiline input\n";
llvm::outs() << ".rawInput [0|1]\t\t\t- Toggle wrapping and printing ";
llvm::outs() << "the execution\n\t\t\t\tresults of the input\n";
llvm::outs() << ".dynamicExtensions [0|1]\t- Toggles the use of the ";
llvm::outs() << "dynamic scopes and the \t\t\t\tlate binding\n";
llvm::outs() << ".printAST [0|1]\t\t\t- Toggles the printing of input's ";
llvm::outs() << "corresponding \t\t\t\tAST nodes\n";
llvm::outs() << ".help\t\t\t\t- Shows this information\n";
}
void MetaProcessor::PrintFileStats() {
const SourceManager& SM = m_Interp.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
// Run a file: .x file[(args)]
bool MetaProcessor::executeFile(const std::string& fileWithArgs,
Value* result) {
// Look for start of parameters:
typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;
StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
if (pairFileArgs.second.empty()) {
pairFileArgs.second = ")";
}
StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
if (pairPathFile.second.empty()) {
pairPathFile.second = pairPathFile.first;
}
StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');
Interpreter::CompilationResult interpRes
= m_Interp.declare(std::string("#include \"")
+ pairFileArgs.first.str()
+ std::string("\""));
if (interpRes != Interpreter::kFailure) {
std::string expression = pairFuncExt.first.str()
+ "(" + pairFileArgs.second.str();
interpRes = m_Interp.evaluate(expression, result);
}
return (interpRes != Interpreter::kFailure);
}
} // end namespace cling
<|endoftext|> |
<commit_before>//===-- sanitizer_suppressions.cc -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Suppression parsing/matching code.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_suppressions.h"
#include "sanitizer_allocator_internal.h"
#include "sanitizer_common.h"
#include "sanitizer_flags.h"
#include "sanitizer_file.h"
#include "sanitizer_libc.h"
#include "sanitizer_placement_new.h"
namespace __sanitizer {
SuppressionContext::SuppressionContext(const char *suppression_types[],
int suppression_types_num)
: suppression_types_(suppression_types),
suppression_types_num_(suppression_types_num),
can_parse_(true) {
CHECK_LE(suppression_types_num_, kMaxSuppressionTypes);
internal_memset(has_suppression_type_, 0, suppression_types_num_);
}
static bool GetPathAssumingFileIsRelativeToExec(const char *file_path,
/*out*/char *new_file_path,
uptr new_file_path_size) {
InternalScopedString exec(kMaxPathLength);
if (ReadBinaryNameCached(exec.data(), exec.size())) {
const char *file_name_pos = StripModuleName(exec.data());
uptr path_to_exec_len = file_name_pos - exec.data();
internal_strncat(new_file_path, exec.data(),
Min(path_to_exec_len, new_file_path_size - 1));
internal_strncat(new_file_path, file_path,
new_file_path_size - internal_strlen(new_file_path) - 1);
return true;
}
return false;
}
void SuppressionContext::ParseFromFile(const char *filename) {
if (filename[0] == '\0')
return;
#if !SANITIZER_FUCHSIA
// If we cannot find the file, check if its location is relative to
// the location of the executable.
InternalScopedString new_file_path(kMaxPathLength);
if (!FileExists(filename) && !IsAbsolutePath(filename) &&
GetPathAssumingFileIsRelativeToExec(filename, new_file_path.data(),
new_file_path.size())) {
filename = new_file_path.data();
}
#endif // !SANITIZER_FUCHSIA
// Read the file.
VPrintf(1, "%s: reading suppressions file at %s\n",
SanitizerToolName, filename);
char *file_contents;
uptr buffer_size;
uptr contents_size;
if (!ReadFileToBuffer(filename, &file_contents, &buffer_size,
&contents_size)) {
Printf("%s: failed to read suppressions file '%s'\n", SanitizerToolName,
filename);
Die();
}
Parse(file_contents);
}
bool SuppressionContext::Match(const char *str, const char *type,
Suppression **s) {
can_parse_ = false;
if (!HasSuppressionType(type))
return false;
for (uptr i = 0; i < suppressions_.size(); i++) {
Suppression &cur = suppressions_[i];
if (0 == internal_strcmp(cur.type, type) && TemplateMatch(cur.templ, str)) {
*s = &cur;
return true;
}
}
return false;
}
static const char *StripPrefix(const char *str, const char *prefix) {
while (str && *str == *prefix) {
str++;
prefix++;
}
if (!*prefix)
return str;
return 0;
}
void SuppressionContext::Parse(const char *str) {
// Context must not mutate once Match has been called.
CHECK(can_parse_);
const char *line = str;
while (line) {
while (line[0] == ' ' || line[0] == '\t')
line++;
const char *end = internal_strchr(line, '\n');
if (end == 0)
end = line + internal_strlen(line);
if (line != end && line[0] != '#') {
const char *end2 = end;
while (line != end2 &&
(end2[-1] == ' ' || end2[-1] == '\t' || end2[-1] == '\r'))
end2--;
int type;
for (type = 0; type < suppression_types_num_; type++) {
const char *next_char = StripPrefix(line, suppression_types_[type]);
if (next_char && *next_char == ':') {
line = ++next_char;
break;
}
}
if (type == suppression_types_num_) {
Printf("%s: failed to parse suppressions\n", SanitizerToolName);
Die();
}
Suppression s;
s.type = suppression_types_[type];
s.templ = (char*)InternalAlloc(end2 - line + 1);
internal_memcpy(s.templ, line, end2 - line);
s.templ[end2 - line] = 0;
suppressions_.push_back(s);
has_suppression_type_[type] = true;
}
if (end[0] == 0)
break;
line = end + 1;
}
}
uptr SuppressionContext::SuppressionCount() const {
return suppressions_.size();
}
bool SuppressionContext::HasSuppressionType(const char *type) const {
for (int i = 0; i < suppression_types_num_; i++) {
if (0 == internal_strcmp(type, suppression_types_[i]))
return has_suppression_type_[i];
}
return false;
}
const Suppression *SuppressionContext::SuppressionAt(uptr i) const {
CHECK_LT(i, suppressions_.size());
return &suppressions_[i];
}
void SuppressionContext::GetMatched(
InternalMmapVector<Suppression *> *matched) {
for (uptr i = 0; i < suppressions_.size(); i++)
if (atomic_load_relaxed(&suppressions_[i].hit_count))
matched->push_back(&suppressions_[i]);
}
} // namespace __sanitizer
<commit_msg>[sanitizer] Don't compile GetPathAssumingFileIsRelativeToExec on Fuchsia<commit_after>//===-- sanitizer_suppressions.cc -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Suppression parsing/matching code.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_suppressions.h"
#include "sanitizer_allocator_internal.h"
#include "sanitizer_common.h"
#include "sanitizer_flags.h"
#include "sanitizer_file.h"
#include "sanitizer_libc.h"
#include "sanitizer_placement_new.h"
namespace __sanitizer {
SuppressionContext::SuppressionContext(const char *suppression_types[],
int suppression_types_num)
: suppression_types_(suppression_types),
suppression_types_num_(suppression_types_num),
can_parse_(true) {
CHECK_LE(suppression_types_num_, kMaxSuppressionTypes);
internal_memset(has_suppression_type_, 0, suppression_types_num_);
}
#if !SANITIZER_FUCHSIA
static bool GetPathAssumingFileIsRelativeToExec(const char *file_path,
/*out*/char *new_file_path,
uptr new_file_path_size) {
InternalScopedString exec(kMaxPathLength);
if (ReadBinaryNameCached(exec.data(), exec.size())) {
const char *file_name_pos = StripModuleName(exec.data());
uptr path_to_exec_len = file_name_pos - exec.data();
internal_strncat(new_file_path, exec.data(),
Min(path_to_exec_len, new_file_path_size - 1));
internal_strncat(new_file_path, file_path,
new_file_path_size - internal_strlen(new_file_path) - 1);
return true;
}
return false;
}
static const char *FindFile(const char *file_path,
/*out*/char *new_file_path,
uptr new_file_path_size) {
// If we cannot find the file, check if its location is relative to
// the location of the executable.
if (!FileExists(file_path) && !IsAbsolutePath(file_path) &&
GetPathAssumingFileIsRelativeToExec(file_path, new_file_path,
new_file_path_size)) {
return new_file_path;
}
return file_path;
}
#else
static const char *FindFile(const char *file_path, char *, uptr) {
return file_path;
}
#endif
void SuppressionContext::ParseFromFile(const char *filename) {
if (filename[0] == '\0')
return;
InternalScopedString new_file_path(kMaxPathLength);
filename = FindFile(filename, new_file_path.data(), new_file_path.size());
// Read the file.
VPrintf(1, "%s: reading suppressions file at %s\n",
SanitizerToolName, filename);
char *file_contents;
uptr buffer_size;
uptr contents_size;
if (!ReadFileToBuffer(filename, &file_contents, &buffer_size,
&contents_size)) {
Printf("%s: failed to read suppressions file '%s'\n", SanitizerToolName,
filename);
Die();
}
Parse(file_contents);
}
bool SuppressionContext::Match(const char *str, const char *type,
Suppression **s) {
can_parse_ = false;
if (!HasSuppressionType(type))
return false;
for (uptr i = 0; i < suppressions_.size(); i++) {
Suppression &cur = suppressions_[i];
if (0 == internal_strcmp(cur.type, type) && TemplateMatch(cur.templ, str)) {
*s = &cur;
return true;
}
}
return false;
}
static const char *StripPrefix(const char *str, const char *prefix) {
while (str && *str == *prefix) {
str++;
prefix++;
}
if (!*prefix)
return str;
return 0;
}
void SuppressionContext::Parse(const char *str) {
// Context must not mutate once Match has been called.
CHECK(can_parse_);
const char *line = str;
while (line) {
while (line[0] == ' ' || line[0] == '\t')
line++;
const char *end = internal_strchr(line, '\n');
if (end == 0)
end = line + internal_strlen(line);
if (line != end && line[0] != '#') {
const char *end2 = end;
while (line != end2 &&
(end2[-1] == ' ' || end2[-1] == '\t' || end2[-1] == '\r'))
end2--;
int type;
for (type = 0; type < suppression_types_num_; type++) {
const char *next_char = StripPrefix(line, suppression_types_[type]);
if (next_char && *next_char == ':') {
line = ++next_char;
break;
}
}
if (type == suppression_types_num_) {
Printf("%s: failed to parse suppressions\n", SanitizerToolName);
Die();
}
Suppression s;
s.type = suppression_types_[type];
s.templ = (char*)InternalAlloc(end2 - line + 1);
internal_memcpy(s.templ, line, end2 - line);
s.templ[end2 - line] = 0;
suppressions_.push_back(s);
has_suppression_type_[type] = true;
}
if (end[0] == 0)
break;
line = end + 1;
}
}
uptr SuppressionContext::SuppressionCount() const {
return suppressions_.size();
}
bool SuppressionContext::HasSuppressionType(const char *type) const {
for (int i = 0; i < suppression_types_num_; i++) {
if (0 == internal_strcmp(type, suppression_types_[i]))
return has_suppression_type_[i];
}
return false;
}
const Suppression *SuppressionContext::SuppressionAt(uptr i) const {
CHECK_LT(i, suppressions_.size());
return &suppressions_[i];
}
void SuppressionContext::GetMatched(
InternalMmapVector<Suppression *> *matched) {
for (uptr i = 0; i < suppressions_.size(); i++)
if (atomic_load_relaxed(&suppressions_[i].hit_count))
matched->push_back(&suppressions_[i]);
}
} // namespace __sanitizer
<|endoftext|> |
<commit_before>#include "MacauPrior.h"
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/linop.h>
#include <ios>
using namespace smurff;
MacauPrior::MacauPrior()
: NormalPrior()
{
}
MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE;
tol = SideInfoConfig::TOL_DEFAULT_VALUE;
enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE;
}
MacauPrior::~MacauPrior()
{
}
void MacauPrior::init()
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
std::uint64_t dim = num_feat();
FtF_plus_precision.resize(dim, dim);
Features->At_mul_A(FtF_plus_precision);
FtF_plus_precision.diagonal().array() += beta_precision;
}
Uhat.resize(num_latent(), Features->rows());
Uhat.setZero();
m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat());
beta().setZero();
m_session->model().setLinkMatrix(m_mode, m_beta);
}
void MacauPrior::update_prior()
{
/*
>> compute_uhat: 0.5012 (12%) in 110
>> main: 4.1396 (100%) in 1
>> rest of update_prior: 0.1684 (4%) in 110
>> sample hyper mu/Lambda: 0.3804 (9%) in 110
>> sample_beta: 1.4927 (36%) in 110
>> sample_latents: 3.8824 (94%) in 220
>> step: 3.9824 (96%) in 111
>> update_prior: 2.5436 (61%) in 110
*/
COUNTER("update_prior");
{
COUNTER("rest of update_prior");
// residual (Uhat is later overwritten):
//uses: U, Uhat
//writes: Uhat
Udelta = U() - Uhat;
}
// sampling Gaussian
{
COUNTER("sample hyper mu/Lambda");
// BBt = beta * beta'
//uses: beta
BBt = beta() * beta().transpose();
// Uses, Udelta
std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0,
WI + beta_precision * BBt, df + num_feat());
}
// uses: U, F
// writes: Ft_y
compute_Ft_y_omp(Ft_y);
sample_beta();
{
COUNTER("compute_uhat");
// Uhat = beta * F
// uses: beta, F
// output: Uhat
Features->compute_uhat(Uhat, beta());
}
if (enable_beta_precision_sampling)
{
// uses: beta
// writes: FtF
COUNTER("sample_beta_precision");
double old_beta = beta_precision;
beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0);
FtF_plus_precision.diagonal().array() += beta_precision - old_beta;
}
}
void MacauPrior::sample_beta()
{
COUNTER("sample_beta");
if (use_FtF)
{
// uses: FtF, Ft_y,
// writes: beta
beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose();
}
else
{
// uses: Features, beta_precision, Ft_y,
// writes: beta
blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error);
}
}
const Eigen::VectorXd MacauPrior::getMu(int n) const
{
return mu + Uhat.col(n);
}
void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
//-- input
// mu, Lambda (small)
// U
// F
//-- output
// Ft_y
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
//HyperU: num_latent x num_item
HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu;
Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat
//-- add beta_precision
HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat
Ft_y += std::sqrt(beta_precision) * HyperU2;
}
void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a)
{
//FIXME: remove old code
// old code
// side information
Features = side_info_a;
beta_precision = beta_precision_a;
tol = tolerance_a;
use_FtF = direct_a;
enable_beta_precision_sampling = enable_beta_precision_sampling_a;
throw_on_cholesky_error = throw_on_cholesky_error_a;
// new code
// side information
side_info_values.push_back(side_info_a);
beta_precision_values.push_back(beta_precision_a);
tol_values.push_back(tolerance_a);
direct_values.push_back(direct_a);
enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a);
throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a);
// other code
// Hyper-prior for beta_precision (mean 1.0, var of 1e+3):
beta_precision_mu0 = 1.0;
beta_precision_nu0 = 1e-3;
}
bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const
{
NormalPrior::save(sf);
std::string path = sf->makeLinkMatrixFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, beta());
return true;
}
void MacauPrior::restore(std::shared_ptr<const StepFile> sf)
{
NormalPrior::restore(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, beta());
}
std::ostream& MacauPrior::info(std::ostream &os, std::string indent)
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: ";
Features->print(os);
os << indent << " Method: ";
if (use_FtF)
{
os << "Cholesky Decomposition";
double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.;
if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)";
os << std::endl;
} else {
os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl;
}
os << indent << " BetaPrecision: ";
if (enable_beta_precision_sampling)
{
os << "sampled around ";
}
else
{
os << "fixed at ";
}
os << beta_precision << std::endl;
return os;
}
std::ostream& MacauPrior::status(std::ostream &os, std::string indent) const
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "blockcg iter = " << blockcg_iter << std::endl;
os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << beta().norm() << std::endl;
os << indent << "beta_precision = " << beta_precision << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto BB = beta * beta.transpose();
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace());
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
<commit_msg>ENH: add comments with complextiy and sizes<commit_after>#include "MacauPrior.h"
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Utils/counters.h>
#include <SmurffCpp/Utils/linop.h>
#include <ios>
using namespace smurff;
MacauPrior::MacauPrior()
: NormalPrior()
{
}
MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE;
tol = SideInfoConfig::TOL_DEFAULT_VALUE;
enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE;
}
MacauPrior::~MacauPrior()
{
}
void MacauPrior::init()
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
std::uint64_t dim = num_feat();
FtF_plus_precision.resize(dim, dim);
Features->At_mul_A(FtF_plus_precision);
FtF_plus_precision.diagonal().array() += beta_precision;
}
Uhat.resize(num_latent(), Features->rows());
Uhat.setZero();
m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat());
beta().setZero();
m_session->model().setLinkMatrix(m_mode, m_beta);
}
void MacauPrior::update_prior()
{
/*
>> compute_uhat: 0.5012 (12%) in 110
>> main: 4.1396 (100%) in 1
>> rest of update_prior: 0.1684 (4%) in 110
>> sample hyper mu/Lambda: 0.3804 (9%) in 110
>> sample_beta: 1.4927 (36%) in 110
>> sample_latents: 3.8824 (94%) in 220
>> step: 3.9824 (96%) in 111
>> update_prior: 2.5436 (61%) in 110
*/
COUNTER("update_prior");
{
COUNTER("rest of update_prior");
// residual (Uhat is later overwritten):
//uses: U, Uhat
// writes: Udelta
// complexity: num_latent x num_items
Udelta = U() - Uhat;
}
// sampling Gaussian
{
COUNTER("sample hyper mu/Lambda");
// BBt = beta * beta'
//uses: beta
// complexity: num_feat x num_feat x num_latent
BBt = beta() * beta().transpose();
// uses: Udelta
// complexity: num_latent x num_items
std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0,
WI + beta_precision * BBt, df + num_feat());
}
// uses: U, F
// writes: Ft_y
// uses: U, F
// writes: Ft_y
// complexity: num_latent x num_feat x num_item
compute_Ft_y_omp(Ft_y);
sample_beta();
{
COUNTER("compute_uhat");
// Uhat = beta * F
// uses: beta, F
// output: Uhat
// complexity: num_feat x num_latent x num_item
Features->compute_uhat(Uhat, beta());
}
if (enable_beta_precision_sampling)
{
// uses: beta
// writes: FtF
COUNTER("sample_beta_precision");
double old_beta = beta_precision;
beta_precision = sample_beta_precision(beta(), Lambda, beta_precision_nu0, beta_precision_mu0);
FtF_plus_precision.diagonal().array() += beta_precision - old_beta;
}
}
void MacauPrior::sample_beta()
{
COUNTER("sample_beta");
if (use_FtF)
{
// uses: FtF, Ft_y,
// writes: m_beta
// complexity: num_feat^3
beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose();
}
else
{
// uses: Features, beta_precision, Ft_y,
// writes: beta
// complexity: num_feat x num_feat x num_iter
blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error);
}
}
const Eigen::VectorXd MacauPrior::getMu(int n) const
{
return mu + Uhat.col(n);
}
void MacauPrior::compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
COUNTER("compute Ft_y");
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
//HyperU: num_latent x num_item
HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu;
Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat
//-- add beta_precision
HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat
Ft_y += std::sqrt(beta_precision) * HyperU2;
}
void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a)
{
//FIXME: remove old code
// old code
// side information
Features = side_info_a;
beta_precision = beta_precision_a;
tol = tolerance_a;
use_FtF = direct_a;
enable_beta_precision_sampling = enable_beta_precision_sampling_a;
throw_on_cholesky_error = throw_on_cholesky_error_a;
// new code
// side information
side_info_values.push_back(side_info_a);
beta_precision_values.push_back(beta_precision_a);
tol_values.push_back(tolerance_a);
direct_values.push_back(direct_a);
enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a);
throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a);
// other code
// Hyper-prior for beta_precision (mean 1.0, var of 1e+3):
beta_precision_mu0 = 1.0;
beta_precision_nu0 = 1e-3;
}
bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const
{
NormalPrior::save(sf);
std::string path = sf->makeLinkMatrixFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, beta());
return true;
}
void MacauPrior::restore(std::shared_ptr<const StepFile> sf)
{
NormalPrior::restore(sf);
std::string path = sf->getLinkMatrixFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, beta());
}
std::ostream& MacauPrior::info(std::ostream &os, std::string indent)
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: ";
Features->print(os);
os << indent << " Method: ";
if (use_FtF)
{
os << "Cholesky Decomposition";
double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.;
if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)";
os << std::endl;
} else {
os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl;
}
os << indent << " BetaPrecision: ";
if (enable_beta_precision_sampling)
{
os << "sampled around ";
}
else
{
os << "fixed at ";
}
os << beta_precision << std::endl;
return os;
}
std::ostream& MacauPrior::status(std::ostream &os, std::string indent) const
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "blockcg iter = " << blockcg_iter << std::endl;
os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << beta().norm() << std::endl;
os << indent << "beta_precision = " << beta_precision << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
std::pair<double, double> MacauPrior::posterior_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto BB = beta * beta.transpose();
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace());
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
double MacauPrior::sample_beta_precision(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_beta_precision(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
<|endoftext|> |
<commit_before>#pragma once
#include <memory>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/linop.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Priors/NormalPrior.h>
#include <SmurffCpp/SparseDoubleFeat.h>
#include <SmurffCpp/SparseFeat.h>
namespace smurff {
//sample_beta method is now virtual. because we override it in MPIMacauPrior
//we also have this method in MacauOnePrior but it is not virtual
//maybe make it virtual?
/// Prior with side information
template<class FType>
class MacauPrior : public NormalPrior
{
public:
typedef FType SideInfo;
Eigen::MatrixXd Uhat;
std::shared_ptr<FType> Features; // side information
Eigen::MatrixXd FtF; // F'F
Eigen::MatrixXd beta; // link matrix
Eigen::MatrixXd HyperU, HyperU2;
Eigen::MatrixXd Ft_y;
bool use_FtF;
double lambda_beta;
bool enable_lambda_beta_sampling;
double lambda_beta_mu0; // Hyper-prior for lambda_beta
double lambda_beta_nu0; // Hyper-prior for lambda_beta
double tol = 1e-6;
private:
MacauPrior()
: NormalPrior(){}
public:
MacauPrior(std::shared_ptr<BaseSession> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
lambda_beta = Config::LAMBDA_BETA_DEFAULT_VALUE;
enable_lambda_beta_sampling = Config::ENABLE_LAMBDA_BETA_SAMPLING_DEFAULT_VALUE;
}
virtual ~MacauPrior() {}
void init() override
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_cols(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
FtF.resize(Features->cols(), Features->cols());
smurff::linop::At_mul_A(FtF, *Features);
}
Uhat.resize(this->num_latent(), Features->rows());
Uhat.setZero();
beta.resize(this->num_latent(), Features->cols());
beta.setZero();
}
void update_prior() override
{
// residual (Uhat is later overwritten):
Uhat.noalias() = U() - Uhat;
Eigen::MatrixXd BBt = smurff::linop::A_mul_At_combo(beta);
// sampling Gaussian
std::tie(this->mu, this->Lambda) = CondNormalWishart(Uhat, this->mu0, this->b0, this->WI + lambda_beta * BBt, this->df + beta.cols());
sample_beta();
smurff::linop::compute_uhat(Uhat, *Features, beta);
if(enable_lambda_beta_sampling)
lambda_beta = sample_lambda_beta(beta, this->Lambda, lambda_beta_nu0, lambda_beta_mu0);
}
void addSideInfo(std::shared_ptr<FType> &Fmat, bool comp_FtF = false)
{
// side information
Features = Fmat;
use_FtF = comp_FtF;
// Hyper-prior for lambda_beta (mean 1.0, var of 1e+3):
lambda_beta_mu0 = 1.0;
lambda_beta_nu0 = 1e-3;
}
const Eigen::VectorXd getMu(int n) const override
{
return this->mu + Uhat.col(n);
}
void compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
const int num_feat = beta.cols();
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(lambda_beta) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
HyperU = (U() + MvNormal_prec_omp(Lambda, num_cols())).colwise() - mu;
//Ft_y = smurff::linop::A_mul_B(HyperU, *Features);
Ft_y = smurff::linop::A_mul_B(HyperU, *Features);
HyperU2 = MvNormal_prec_omp(Lambda, num_feat);
#pragma omp parallel for schedule(static)
for (int f = 0; f < num_feat; f++)
{
for (int d = 0; d < num_latent(); d++)
{
Ft_y(d, f) += std::sqrt(lambda_beta) * HyperU2(d, f);
}
}
}
// Update beta and Uhat
virtual void sample_beta()
{
if (use_FtF)
sample_beta_direct();
else
sample_beta_cg();
}
public:
double getLinkLambda()
{
return lambda_beta;
}
void setLambdaBeta(double lb)
{
lambda_beta = lb;
}
void setTol(double t)
{
tol = t;
}
void setEnableLambdaBetaSampling(bool value)
{
enable_lambda_beta_sampling = value;
}
public:
void save(std::shared_ptr<const StepFile> sf) const override
{
NormalPrior::save(sf);
std::string path = sf->getPriorFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, this->beta);
}
void restore(std::shared_ptr<const StepFile> sf) override
{
NormalPrior::restore(sf);
std::string path = sf->getPriorFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, this->beta);
}
private:
std::ostream &printSideInfo(std::ostream &os, const SparseDoubleFeat &F)
{
os << "SparseDouble [" << F.rows() << ", " << F.cols() << "]" << std::endl;
return os;
}
std::ostream &printSideInfo(std::ostream &os, const Eigen::MatrixXd &F)
{
os << "DenseDouble [" << F.rows() << ", " << F.cols() << "]" << std::endl;
return os;
}
std::ostream &printSideInfo(std::ostream &os, const SparseFeat &F)
{
os << "SparseBinary [" << F.rows() << ", " << F.cols() << "]" << std::endl;
return os;
}
public:
std::ostream &info(std::ostream &os, std::string indent) override
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: "; printSideInfo(os, *Features);
os << indent << " Method: " << (use_FtF ? "Cholesky Decomposition" : "CG Solver") << std::endl;
os << indent << " Tol: " << tol << std::endl;
os << indent << " LambdaBeta: " << lambda_beta << std::endl;
return os;
}
std::ostream &status(std::ostream &os, std::string indent) const override
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "FtF = " << FtF.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << beta.norm() << std::endl;
os << indent << "lambda_beta = " << lambda_beta << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
private:
// direct method
void sample_beta_direct()
{
this->compute_Ft_y_omp(Ft_y);
Eigen::MatrixXd K(FtF.rows(), FtF.cols());
K.triangularView<Eigen::Lower>() = FtF;
K.diagonal().array() += lambda_beta;
chol_decomp(K);
chol_solve_t(K, Ft_y);
beta = Ft_y;
}
// BlockCG solver
void sample_beta_cg();
public:
static std::pair<double,double> posterior_lambda_beta(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
const int D = beta.rows();
Eigen::MatrixXd BB(D, D);
smurff::linop::A_mul_At_combo(BB, beta);
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace() );
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
static double sample_lambda_beta(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_lambda_beta(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
};
template<class FType>
void MacauPrior<FType>::sample_beta_cg()
{
Eigen::MatrixXd Ft_y;
this->compute_Ft_y_omp(Ft_y);
smurff::linop::solve_blockcg(beta, *Features, lambda_beta, Ft_y, tol, 32, 8);
}
// specialization for dense matrices --> always direct method
template<>
void MacauPrior<Eigen::Matrix<double, -1, -1, 0, -1, -1>>::sample_beta_cg();
}
<commit_msg>remove superfluous comment<commit_after>#pragma once
#include <memory>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <SmurffCpp/IO/MatrixIO.h>
#include <SmurffCpp/IO/GenericIO.h>
#include <SmurffCpp/Utils/linop.h>
#include <SmurffCpp/Utils/Distribution.h>
#include <SmurffCpp/Utils/Error.h>
#include <SmurffCpp/Priors/NormalPrior.h>
#include <SmurffCpp/SparseDoubleFeat.h>
#include <SmurffCpp/SparseFeat.h>
namespace smurff {
//sample_beta method is now virtual. because we override it in MPIMacauPrior
//we also have this method in MacauOnePrior but it is not virtual
//maybe make it virtual?
/// Prior with side information
template<class FType>
class MacauPrior : public NormalPrior
{
public:
typedef FType SideInfo;
Eigen::MatrixXd Uhat;
std::shared_ptr<FType> Features; // side information
Eigen::MatrixXd FtF; // F'F
Eigen::MatrixXd beta; // link matrix
Eigen::MatrixXd HyperU, HyperU2;
Eigen::MatrixXd Ft_y;
bool use_FtF;
double lambda_beta;
bool enable_lambda_beta_sampling;
double lambda_beta_mu0; // Hyper-prior for lambda_beta
double lambda_beta_nu0; // Hyper-prior for lambda_beta
double tol = 1e-6;
private:
MacauPrior()
: NormalPrior(){}
public:
MacauPrior(std::shared_ptr<BaseSession> session, uint32_t mode)
: NormalPrior(session, mode, "MacauPrior")
{
lambda_beta = Config::LAMBDA_BETA_DEFAULT_VALUE;
enable_lambda_beta_sampling = Config::ENABLE_LAMBDA_BETA_SAMPLING_DEFAULT_VALUE;
}
virtual ~MacauPrior() {}
void init() override
{
NormalPrior::init();
THROWERROR_ASSERT_MSG(Features->rows() == num_cols(), "Number of rows in train must be equal to number of rows in features");
if (use_FtF)
{
FtF.resize(Features->cols(), Features->cols());
smurff::linop::At_mul_A(FtF, *Features);
}
Uhat.resize(this->num_latent(), Features->rows());
Uhat.setZero();
beta.resize(this->num_latent(), Features->cols());
beta.setZero();
}
void update_prior() override
{
// residual (Uhat is later overwritten):
Uhat.noalias() = U() - Uhat;
Eigen::MatrixXd BBt = smurff::linop::A_mul_At_combo(beta);
// sampling Gaussian
std::tie(this->mu, this->Lambda) = CondNormalWishart(Uhat, this->mu0, this->b0, this->WI + lambda_beta * BBt, this->df + beta.cols());
sample_beta();
smurff::linop::compute_uhat(Uhat, *Features, beta);
if(enable_lambda_beta_sampling)
lambda_beta = sample_lambda_beta(beta, this->Lambda, lambda_beta_nu0, lambda_beta_mu0);
}
void addSideInfo(std::shared_ptr<FType> &Fmat, bool comp_FtF = false)
{
// side information
Features = Fmat;
use_FtF = comp_FtF;
// Hyper-prior for lambda_beta (mean 1.0, var of 1e+3):
lambda_beta_mu0 = 1.0;
lambda_beta_nu0 = 1e-3;
}
const Eigen::VectorXd getMu(int n) const override
{
return this->mu + Uhat.col(n);
}
void compute_Ft_y_omp(Eigen::MatrixXd& Ft_y)
{
const int num_feat = beta.cols();
// Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(lambda_beta) * Normal(0, Lambda^-1)
// Ft_y is [ D x F ] matrix
HyperU = (U() + MvNormal_prec_omp(Lambda, num_cols())).colwise() - mu;
Ft_y = smurff::linop::A_mul_B(HyperU, *Features);
HyperU2 = MvNormal_prec_omp(Lambda, num_feat);
#pragma omp parallel for schedule(static)
for (int f = 0; f < num_feat; f++)
{
for (int d = 0; d < num_latent(); d++)
{
Ft_y(d, f) += std::sqrt(lambda_beta) * HyperU2(d, f);
}
}
}
// Update beta and Uhat
virtual void sample_beta()
{
if (use_FtF)
sample_beta_direct();
else
sample_beta_cg();
}
public:
double getLinkLambda()
{
return lambda_beta;
}
void setLambdaBeta(double lb)
{
lambda_beta = lb;
}
void setTol(double t)
{
tol = t;
}
void setEnableLambdaBetaSampling(bool value)
{
enable_lambda_beta_sampling = value;
}
public:
void save(std::shared_ptr<const StepFile> sf) const override
{
NormalPrior::save(sf);
std::string path = sf->getPriorFileName(m_mode);
smurff::matrix_io::eigen::write_matrix(path, this->beta);
}
void restore(std::shared_ptr<const StepFile> sf) override
{
NormalPrior::restore(sf);
std::string path = sf->getPriorFileName(m_mode);
THROWERROR_FILE_NOT_EXIST(path);
smurff::matrix_io::eigen::read_matrix(path, this->beta);
}
private:
std::ostream &printSideInfo(std::ostream &os, const SparseDoubleFeat &F)
{
os << "SparseDouble [" << F.rows() << ", " << F.cols() << "]" << std::endl;
return os;
}
std::ostream &printSideInfo(std::ostream &os, const Eigen::MatrixXd &F)
{
os << "DenseDouble [" << F.rows() << ", " << F.cols() << "]" << std::endl;
return os;
}
std::ostream &printSideInfo(std::ostream &os, const SparseFeat &F)
{
os << "SparseBinary [" << F.rows() << ", " << F.cols() << "]" << std::endl;
return os;
}
public:
std::ostream &info(std::ostream &os, std::string indent) override
{
NormalPrior::info(os, indent);
os << indent << " SideInfo: "; printSideInfo(os, *Features);
os << indent << " Method: " << (use_FtF ? "Cholesky Decomposition" : "CG Solver") << std::endl;
os << indent << " Tol: " << tol << std::endl;
os << indent << " LambdaBeta: " << lambda_beta << std::endl;
return os;
}
std::ostream &status(std::ostream &os, std::string indent) const override
{
os << indent << m_name << ": " << std::endl;
indent += " ";
os << indent << "FtF = " << FtF.norm() << std::endl;
os << indent << "HyperU = " << HyperU.norm() << std::endl;
os << indent << "HyperU2 = " << HyperU2.norm() << std::endl;
os << indent << "Beta = " << beta.norm() << std::endl;
os << indent << "lambda_beta = " << lambda_beta << std::endl;
os << indent << "Ft_y = " << Ft_y.norm() << std::endl;
return os;
}
private:
// direct method
void sample_beta_direct()
{
this->compute_Ft_y_omp(Ft_y);
Eigen::MatrixXd K(FtF.rows(), FtF.cols());
K.triangularView<Eigen::Lower>() = FtF;
K.diagonal().array() += lambda_beta;
chol_decomp(K);
chol_solve_t(K, Ft_y);
beta = Ft_y;
}
// BlockCG solver
void sample_beta_cg();
public:
static std::pair<double,double> posterior_lambda_beta(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
const int D = beta.rows();
Eigen::MatrixXd BB(D, D);
smurff::linop::A_mul_At_combo(BB, beta);
double nux = nu + beta.rows() * beta.cols();
double mux = mu * nux / (nu + mu * (BB.selfadjointView<Eigen::Lower>() * Lambda_u).trace() );
double b = nux / 2;
double c = 2 * mux / nux;
return std::make_pair(b, c);
}
static double sample_lambda_beta(Eigen::MatrixXd & beta, Eigen::MatrixXd & Lambda_u, double nu, double mu)
{
auto gamma_post = posterior_lambda_beta(beta, Lambda_u, nu, mu);
return rgamma(gamma_post.first, gamma_post.second);
}
};
template<class FType>
void MacauPrior<FType>::sample_beta_cg()
{
Eigen::MatrixXd Ft_y;
this->compute_Ft_y_omp(Ft_y);
smurff::linop::solve_blockcg(beta, *Features, lambda_beta, Ft_y, tol, 32, 8);
}
// specialization for dense matrices --> always direct method
template<>
void MacauPrior<Eigen::Matrix<double, -1, -1, 0, -1, -1>>::sample_beta_cg();
}
<|endoftext|> |
<commit_before>//
// Created by manuel on 08.06.15.
//
#include "AssemblyParser.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <bitset>
#include <cstdint>
using namespace std;
const string AssemblyParser::ROUTINE_DIRECTIVE = ".FUNCT";
const string AssemblyParser::GVAR_DIRECTIVE = ".GVAR";
const string AssemblyParser::NEW_LINE_COMMAND = "new_line";
const string AssemblyParser::PRINT_COMMAND = "print";
const string AssemblyParser::JE_COMMAND = "je";
const string AssemblyParser::QUIT_COMMAND = "quit";
const string AssemblyParser::READ_CHAR_COMMAND = "read_char";
const string AssemblyParser::CALL_COMMAND = "call";
const string AssemblyParser::JUMP_COMMAND = "jump";
const string AssemblyParser::RET_COMMAND = "ret";
const char AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND = ' ';
const char AssemblyParser::STRING_DELIMITER = '\"';
const string AssemblyParser::ASSIGNMENT_OPERATOR = "->";
string trim(const string &str,
const string &whitespace = " \t") {
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == string::npos)
return ""; // no content
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
void AssemblyParser::readAssembly(istream &input, vector<bitset<8>> &highMemoryZcode,
size_t offset) {
cout << "Compiler: Parse Assembly File\n";
for (string line; getline(input, line);) {
line = trim(line);
vector<string> lineComps;
this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps);
if (lineComps.size()) {
string firstComp = lineComps.at(0);
if (line.at(0) == '.') { // directive
if (firstComp.compare(ROUTINE_DIRECTIVE) == 0) {
cout << "found routine" << endl;
if (lineComps.size() < 2) {
cerr << "invalid routine declaration (no name specified)" << endl;
throw;
}
string routineName = lineComps.at(1);
// currentGenerator exists, so we can get its code
if (currentGenerator) {
finishRoutine(highMemoryZcode);
}
size_t locVariablesCount = lineComps.size() - 2;
currentGenerator.reset(new RoutineGenerator(routineName, locVariablesCount, highMemoryZcode, offset));
bool withoutComma = true;
for (;locVariablesCount > 0; locVariablesCount--) { // parse locale variables
string var = lineComps[locVariablesCount + 1];
size_t nameEnd = var.find_first_of("=");
size_t varEnd = var.size();
if (withoutComma) { // last locale variable has no comma as last char
withoutComma = false;
} else {
varEnd -= 1;
}
if (nameEnd != string::npos) {
int val;
const char* valueString = var.substr(nameEnd + 1, varEnd - 1 - nameEnd).c_str();
try {
val = atoi(valueString);
} catch (...) {
cout << "Given value for local variable is not an integer: " << valueString << endl;
throw;
}
string name = var.substr(0, nameEnd);
currentGenerator->setLocalVariable(name, val);
} else {
string name = var.substr(0, varEnd);
currentGenerator->setLocalVariable(name);
}
}
} else if (firstComp.compare(GVAR_DIRECTIVE) == 0) {
cout << "found gvar" << endl;
this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps);
if (lineComps.size() < 2) {
cerr << "empty gvar declaration" << endl;
}
string gvar = lineComps.at(1);
addGlobal(gvar);
}
} else { // normal instruction
executeCommand(line, *currentGenerator);
}
}
}
if (currentGenerator) {
finishRoutine(highMemoryZcode);
}
}
void AssemblyParser::finishRoutine(vector<bitset<8>> &highMemoryZcode) {
cout << "adding routine to zcode" << endl;
auto routineCode = currentGenerator->getRoutine();
Utils::append(highMemoryZcode, routineCode);
}
void AssemblyParser::addGlobal(string globalName) {
// TODO: check if maximum gvar limit is reached
unsigned index = (unsigned) globalVariables.size();
cout << "adding gvar " << globalName << " at index " << to_string(index) << endl;
this->globalVariables[globalName] = index;
}
RoutineGenerator &AssemblyParser::executePRINTCommand(const string &printCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(printCommand, AssemblyParser::STRING_DELIMITER);
routineGenerator.printString(commandParts.at(1));
cout << commandParts.at(1) << endl;
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeREADCommand(const string &readCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(readCommand, AssemblyParser::ASSIGNMENT_OPERATOR);
if (commandParts.size() < 2) {
// TODO: decide on whether to allow no args for read_char
return routineGenerator;
}
auto last = trim(commandParts.back());
routineGenerator.readChar(getAddressForId(last));
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeJECommand(const string &jeCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(jeCommand, '?');
string label = commandParts.at(1);
commandParts = split(jeCommand, ' ');
string variableName = commandParts.at(2);
string valueString = commandParts.at(1);
uint16_t value = stoul(valueString); // TODO: check if this fits 8 or 16 bits, then set small or large constant
cout << variableName << "," << "" << value;
uint8_t globalZCodeAdress = getAddressForId(variableName);
cout << " " << label << endl;
routineGenerator.jumpEquals(label, true, globalZCodeAdress, value, true, false);
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeJUMPCommand(const string &jumpCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(jumpCommand, '?');
string label = commandParts.at(1);
cout << label << endl;
routineGenerator.jump(label);
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeCALLCommand(const string &callCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(callCommand, ' ');
string callRoutineName = commandParts.at(1);
cout << callRoutineName << endl;
routineGenerator.callRoutine(callRoutineName);
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeCommand(const string &command, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(command,
AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND);
if (!commandParts.size()) return routineGenerator;
string commandPart = commandParts.at(0);
if (commandPart.compare(AssemblyParser::NEW_LINE_COMMAND) == 0) {
routineGenerator.newLine();
cout << ":::::: new line" << endl;
} else if (commandPart.compare(AssemblyParser::PRINT_COMMAND) == 0) {
cout << ":::::: new print ";
routineGenerator = executePRINTCommand(command, routineGenerator);
} else if (commandPart.compare(AssemblyParser::JE_COMMAND) == 0) {
cout << ":::::: new je ";
routineGenerator = executeJECommand(command, routineGenerator);
} else if (commandPart.compare(AssemblyParser::QUIT_COMMAND) == 0) {
routineGenerator.quitRoutine();
cout << ":::::: new quit" << endl;
} else if (commandPart.compare(AssemblyParser::READ_CHAR_COMMAND) == 0) {
routineGenerator = executeREADCommand(command, routineGenerator);
cout << ":::::: new read" << endl;
} else if (commandPart.compare(AssemblyParser::CALL_COMMAND) == 0) {
cout << ":::::: new call ";
routineGenerator = executeCALLCommand(command, routineGenerator);
} else if (command.compare(AssemblyParser::JUMP_COMMAND) == 0) {
cout << ":::::: new jump ";
routineGenerator = executeJUMPCommand(command, routineGenerator);
} else if (command.compare(AssemblyParser::RET_COMMAND) == 0) {
cout << ":::::: new return routine ";
routineGenerator.returnValue(0, false);
} else if (commandPart.at(commandPart.size() - 1) == ':') {
string label = commandPart.substr(0, commandPart.size() - 1);
cout << ":::::: new label: " << label << endl;
routineGenerator.newLabel(label);
string afterLabel = command.substr(commandPart.size());
executeCommand(trim(afterLabel), *currentGenerator);
} else {
// TODO: handle this error more appropriately
cout << "unknown command: " << command << endl;
throw;
}
return routineGenerator;
}
bool AssemblyParser::checkIfCommandRoutineStart(const string &command) {
vector<string> commandParts = this->split(command, ' ');
for (unsigned int i = 0; i < commandParts.size(); i++) {
if (commandParts.at(i).compare(ROUTINE_DIRECTIVE) == 0) {
return true;
}
}
return false;
}
uint8_t AssemblyParser::getAddressForId(const string &id) {
if (id.compare("sp") == 0) {
return 0;
}
// check global variables
if (globalVariables.count(id)) {
return globalVariables[id];
} else if (currentGenerator->containsLocalVariable(id)) {
return currentGenerator->getAddressOfVariable(id);
} else {
cout << "Could not find variable " << id << endl;
throw;
}
}
vector<string> &AssemblyParser::split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
vector<string> AssemblyParser::split(const string &s, char delim) {
vector<string> elems;
split(s, delim, elems);
return elems;
}
vector<string> AssemblyParser::split(const string &s, const string &delim) {
string s_copy = s;
size_t pos = 0;
string token;
vector<string> tokens;
while ((pos = s_copy.find(delim)) != string::npos) {
token = s_copy.substr(0, pos);
cout << "found token " << token << endl;
tokens.push_back(token);
s_copy.erase(0, pos + delim.length());
}
tokens.push_back(s_copy);
return tokens;
}
<commit_msg>few small fixes<commit_after>//
// Created by manuel on 08.06.15.
//
#include "AssemblyParser.h"
#include <fstream>
#include <sstream>
#include <algorithm>
#include <bitset>
#include <cstdint>
using namespace std;
const string AssemblyParser::ROUTINE_DIRECTIVE = ".FUNCT";
const string AssemblyParser::GVAR_DIRECTIVE = ".GVAR";
const string AssemblyParser::NEW_LINE_COMMAND = "new_line";
const string AssemblyParser::PRINT_COMMAND = "print";
const string AssemblyParser::JE_COMMAND = "je";
const string AssemblyParser::QUIT_COMMAND = "quit";
const string AssemblyParser::READ_CHAR_COMMAND = "read_char";
const string AssemblyParser::CALL_COMMAND = "call";
const string AssemblyParser::JUMP_COMMAND = "jump";
const string AssemblyParser::RET_COMMAND = "ret";
const char AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND = ' ';
const char AssemblyParser::STRING_DELIMITER = '\"';
const string AssemblyParser::ASSIGNMENT_OPERATOR = "->";
string trim(const string &str,
const string &whitespace = " \t") {
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == string::npos)
return ""; // no content
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
void AssemblyParser::readAssembly(istream &input, vector<bitset<8>> &highMemoryZcode,
size_t offset) {
cout << "Compiler: Parse Assembly File\n";
for (string line; getline(input, line);) {
line = trim(line);
vector<string> lineComps;
this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps);
if (lineComps.size()) {
string firstComp = lineComps.at(0);
if (line.at(0) == '.') { // directive
if (firstComp.compare(ROUTINE_DIRECTIVE) == 0) {
cout << "found routine" << endl;
if (lineComps.size() < 2) {
cerr << "invalid routine declaration (no name specified)" << endl;
throw;
}
string routineName = lineComps.at(1);
// currentGenerator exists, so we can get its code
if (currentGenerator) {
finishRoutine(highMemoryZcode);
}
unsigned locVariablesCount = (unsigned) (lineComps.size() - 2);
currentGenerator.reset(new RoutineGenerator(routineName, locVariablesCount, highMemoryZcode, offset));
bool withoutComma = true;
for (;locVariablesCount > 0; locVariablesCount--) { // parse locale variables
string var = lineComps[locVariablesCount + 1];
size_t nameEnd = var.find_first_of("=");
size_t varEnd = var.size();
if (withoutComma) { // last locale variable has no comma as last char
withoutComma = false;
} else {
varEnd -= 1;
}
if (nameEnd != string::npos) {
int val;
string valueString = var.substr(nameEnd + 1, varEnd - 1 - nameEnd);
try {
val = stoi(valueString);
} catch (const invalid_argument& invaldArgument) {
cout << "Given value for local variable is not an integer: " << valueString << endl;
throw;
} catch (const out_of_range& outOfRange) {
cout << "Given value for local variable too large or too small: " << valueString << endl;
throw;
}
if(val > INT16_MAX || val < INT16_MIN) {
throw out_of_range(string("Given value for local variable too large or too small: ") + to_string(val) );
}
string name = var.substr(0, nameEnd);
currentGenerator->setLocalVariable(name, val);
} else {
string name = var.substr(0, varEnd);
currentGenerator->setLocalVariable(name);
}
}
} else if (firstComp.compare(GVAR_DIRECTIVE) == 0) {
cout << "found gvar" << endl;
this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps);
if (lineComps.size() < 2) {
cerr << "empty gvar declaration" << endl;
}
string gvar = lineComps.at(1);
addGlobal(gvar);
}
} else { // normal instruction
executeCommand(line, *currentGenerator);
}
}
}
if (currentGenerator) {
finishRoutine(highMemoryZcode);
}
}
void AssemblyParser::finishRoutine(vector<bitset<8>> &highMemoryZcode) {
cout << "adding routine to zcode" << endl;
auto routineCode = currentGenerator->getRoutine();
Utils::append(highMemoryZcode, routineCode);
}
void AssemblyParser::addGlobal(string globalName) {
// TODO: check if maximum gvar limit is reached
unsigned index = (unsigned) globalVariables.size();
cout << "adding gvar " << globalName << " at index " << to_string(index) << endl;
this->globalVariables[globalName] = index;
}
RoutineGenerator &AssemblyParser::executePRINTCommand(const string &printCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(printCommand, AssemblyParser::STRING_DELIMITER);
routineGenerator.printString(commandParts.at(1));
cout << commandParts.at(1) << endl;
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeREADCommand(const string &readCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(readCommand, AssemblyParser::ASSIGNMENT_OPERATOR);
if (commandParts.size() < 2) {
// TODO: decide on whether to allow no args for read_char
return routineGenerator;
}
auto last = trim(commandParts.back());
routineGenerator.readChar(getAddressForId(last));
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeJECommand(const string &jeCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(jeCommand, '?');
string label = commandParts.at(1);
commandParts = split(jeCommand, ' ');
string variableName = commandParts.at(2);
string valueString = commandParts.at(1);
uint16_t value = stoul(valueString); // TODO: check if this fits 8 or 16 bits, then set small or large constant
cout << variableName << "," << "" << value;
uint8_t globalZCodeAdress = getAddressForId(variableName);
cout << " " << label << endl;
routineGenerator.jumpEquals(label, true, globalZCodeAdress, value, true, false);
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeJUMPCommand(const string &jumpCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(jumpCommand, '?');
string label = commandParts.at(1);
cout << label << endl;
routineGenerator.jump(label);
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeCALLCommand(const string &callCommand, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(callCommand, ' ');
string callRoutineName = commandParts.at(1);
cout << callRoutineName << endl;
routineGenerator.callRoutine(callRoutineName);
return routineGenerator;
}
RoutineGenerator &AssemblyParser::executeCommand(const string &command, RoutineGenerator &routineGenerator) {
vector<string> commandParts = this->split(command,
AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND);
if (!commandParts.size()) return routineGenerator;
string commandPart = commandParts.at(0);
if (commandPart.compare(AssemblyParser::NEW_LINE_COMMAND) == 0) {
routineGenerator.newLine();
cout << ":::::: new line" << endl;
} else if (commandPart.compare(AssemblyParser::PRINT_COMMAND) == 0) {
cout << ":::::: new print ";
routineGenerator = executePRINTCommand(command, routineGenerator);
} else if (commandPart.compare(AssemblyParser::JE_COMMAND) == 0) {
cout << ":::::: new je ";
routineGenerator = executeJECommand(command, routineGenerator);
} else if (commandPart.compare(AssemblyParser::QUIT_COMMAND) == 0) {
routineGenerator.quitRoutine();
cout << ":::::: new quit" << endl;
} else if (commandPart.compare(AssemblyParser::READ_CHAR_COMMAND) == 0) {
routineGenerator = executeREADCommand(command, routineGenerator);
cout << ":::::: new read" << endl;
} else if (commandPart.compare(AssemblyParser::CALL_COMMAND) == 0) {
cout << ":::::: new call ";
routineGenerator = executeCALLCommand(command, routineGenerator);
} else if (command.compare(AssemblyParser::JUMP_COMMAND) == 0) {
cout << ":::::: new jump ";
routineGenerator = executeJUMPCommand(command, routineGenerator);
} else if (command.compare(AssemblyParser::RET_COMMAND) == 0) {
cout << ":::::: new return routine ";
routineGenerator.returnValue(0, false);
} else if (commandPart.at(commandPart.size() - 1) == ':') {
string label = commandPart.substr(0, commandPart.size() - 1);
cout << ":::::: new label: " << label << endl;
routineGenerator.newLabel(label);
string afterLabel = command.substr(commandPart.size());
executeCommand(trim(afterLabel), *currentGenerator);
} else {
// TODO: handle this error more appropriately
cout << "unknown command: " << command << endl;
throw;
}
return routineGenerator;
}
bool AssemblyParser::checkIfCommandRoutineStart(const string &command) {
vector<string> commandParts = this->split(command, ' ');
for (unsigned int i = 0; i < commandParts.size(); i++) {
if (commandParts.at(i).compare(ROUTINE_DIRECTIVE) == 0) {
return true;
}
}
return false;
}
uint8_t AssemblyParser::getAddressForId(const string &id) {
if (id.compare("sp") == 0) {
return 0;
}
// check global variables
if (globalVariables.count(id)) {
return globalVariables[id];
} else if (currentGenerator->containsLocalVariable(id)) {
return currentGenerator->getAddressOfVariable(id);
} else {
cout << "Could not find variable " << id << endl;
throw;
}
}
vector<string> &AssemblyParser::split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
vector<string> AssemblyParser::split(const string &s, char delim) {
vector<string> elems;
split(s, delim, elems);
return elems;
}
vector<string> AssemblyParser::split(const string &s, const string &delim) {
string s_copy = s;
size_t pos = 0;
string token;
vector<string> tokens;
while ((pos = s_copy.find(delim)) != string::npos) {
token = s_copy.substr(0, pos);
cout << "found token " << token << endl;
tokens.push_back(token);
s_copy.erase(0, pos + delim.length());
}
tokens.push_back(s_copy);
return tokens;
}
<|endoftext|> |
<commit_before>/*
kmain.cpp
Copyright (c) 23 Yann BOUCHER (yann)
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.
*/
// TODO : FAT32 write
// TODO : system calls
// TODO : user mode
// TODO : POC calculatrice
// TODO : Paging
// TODO : Son
// TODO : Passer en IDE PCI : IDE UDMA
// TODO : unifier l'interface PS/2
// FIXME : revoir l'architecture dégeulasse de l'ownership des nodes de readdir
// FIXME : Terminal buggy with ATA PIO
// TODO : syscalls:
/// screen_clr()
/// screen_move_cursor(x, y)
/// screen_push_color(col)
/// screen_pop_color()
#ifndef __cplusplus
#error Must be compiled using C++ !
#endif
#include "utils/defs.hpp"
#ifdef ARCH_i686
#include "i686/pc/init.hpp"
#endif
#include "init.hpp"
#ifdef ARCH_i686
extern "C"
void kmain(uint32_t magic, const multiboot_info_t* mbd_info)
#else
void kmain()
#endif
{
#ifdef ARCH_i686
i686::pc::init(magic, mbd_info);
#endif
init();
while (1)
{
nop();
}
}
<commit_msg>Update kmain.cpp<commit_after>/*
kmain.cpp
Copyright (c) 23 Yann BOUCHER (yann)
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.
*/
// TODO : FAT32 write
// TODO : system calls
// TODO : user mode
// TODO : POC calculatrice
// TODO : Paging
// TODO : Son
// TODO : Passer en IDE PCI : IDE UDMA
// TODO : unifier l'interface PS/2
// FIXME : revoir l'architecture dégeulasse de l'ownership des nodes de rea
// TODO : passer bcp de choses en uintptr_t
// TODO : v86 mode
// TODO : TinyGL
// TODO : HigherHalf
// TODO : syscalls:
/// screen_clr()
/// screen_move_cursor(x, y)
/// screen_push_color(col)
/// screen_pop_color()
#ifndef __cplusplus
#error Must be compiled using C++ !
#endif
#include "utils/defs.hpp"
#ifdef ARCH_i686
#include "i686/pc/init.hpp"
#endif
#include "init.hpp"
#ifdef ARCH_i686
extern "C"
void kmain(uint32_t magic, const multiboot_info_t* mbd_info)
#else
void kmain()
#endif
{
#ifdef ARCH_i686
i686::pc::init(magic, mbd_info);
#endif
init();
while (1)
{
nop();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/audio_input_controller.h"
namespace {
const int kMaxSampleRate = 192000;
const int kMaxBitsPerSample = 64;
const int kMaxInputChannels = 2;
const int kMaxSamplesPerPacket = kMaxSampleRate;
} // namespace
namespace media {
AudioInputController::AudioInputController(EventHandler* handler)
: handler_(handler),
state_(kEmpty),
thread_("AudioInputControllerThread") {
}
AudioInputController::~AudioInputController() {
DCHECK(kClosed == state_ || kCreated == state_ || kEmpty == state_);
}
// static
scoped_refptr<AudioInputController> AudioInputController::Create(
EventHandler* event_handler,
AudioManager::Format format,
int channels,
int sample_rate,
int bits_per_sample,
int samples_per_packet) {
if ((channels > kMaxInputChannels) || (channels <= 0) ||
(sample_rate > kMaxSampleRate) || (sample_rate <= 0) ||
(bits_per_sample > kMaxBitsPerSample) || (bits_per_sample <= 0) ||
(samples_per_packet > kMaxSamplesPerPacket) || (samples_per_packet < 0))
return NULL;
scoped_refptr<AudioInputController> controller = new AudioInputController(
event_handler);
// Start the thread and post a task to create the audio input stream.
controller->thread_.Start();
controller->thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(controller.get(), &AudioInputController::DoCreate,
format, channels, sample_rate, bits_per_sample,
samples_per_packet));
return controller;
}
void AudioInputController::Record() {
DCHECK(thread_.IsRunning());
thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &AudioInputController::DoRecord));
}
void AudioInputController::Close() {
if (!thread_.IsRunning()) {
// If the thread is not running make sure we are stopped.
DCHECK_EQ(kClosed, state_);
return;
}
// Wait for all tasks to complete on the audio thread.
thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &AudioInputController::DoClose));
thread_.Stop();
}
void AudioInputController::DoCreate(AudioManager::Format format, int channels,
int sample_rate, int bits_per_sample,
uint32 samples_per_packet) {
stream_ = AudioManager::GetAudioManager()->MakeAudioInputStream(
format, channels, sample_rate, bits_per_sample, samples_per_packet);
if (!stream_) {
// TODO(satish): Define error types.
handler_->OnError(this, 0);
return;
}
if (stream_ && !stream_->Open()) {
stream_->Close();
stream_ = NULL;
// TODO(satish): Define error types.
handler_->OnError(this, 0);
return;
}
state_ = kCreated;
handler_->OnCreated(this);
}
void AudioInputController::DoRecord() {
DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
if (state_ != kCreated)
return;
{
AutoLock auto_lock(lock_);
state_ = kRecording;
}
stream_->Start(this);
handler_->OnRecording(this);
}
void AudioInputController::DoClose() {
DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
DCHECK_NE(kClosed, state_);
// |stream_| can be null if creating the device failed in DoCreate().
if (stream_) {
stream_->Stop();
stream_->Close();
// After stream is closed it is destroyed, so don't keep a reference to it.
stream_ = NULL;
}
// Since the stream is closed at this point there's no other threads reading
// |state_| so we don't need to lock.
state_ = kClosed;
}
void AudioInputController::DoReportError(int code) {
DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
handler_->OnError(this, code);
}
void AudioInputController::OnData(AudioInputStream* stream, const uint8* data,
uint32 size) {
{
AutoLock auto_lock(lock_);
if (state_ != kRecording)
return;
}
handler_->OnData(this, data, size);
}
void AudioInputController::OnClose(AudioInputStream* stream) {
}
void AudioInputController::OnError(AudioInputStream* stream, int code) {
// Handle error on the audio controller thread.
thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &AudioInputController::DoReportError, code));
}
} // namespace media
<commit_msg>Uninitialized member in AudioInputController.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/audio_input_controller.h"
namespace {
const int kMaxSampleRate = 192000;
const int kMaxBitsPerSample = 64;
const int kMaxInputChannels = 2;
const int kMaxSamplesPerPacket = kMaxSampleRate;
} // namespace
namespace media {
AudioInputController::AudioInputController(EventHandler* handler)
: handler_(handler),
stream_(NULL),
state_(kEmpty),
thread_("AudioInputControllerThread") {
}
AudioInputController::~AudioInputController() {
DCHECK(kClosed == state_ || kCreated == state_ || kEmpty == state_);
}
// static
scoped_refptr<AudioInputController> AudioInputController::Create(
EventHandler* event_handler,
AudioManager::Format format,
int channels,
int sample_rate,
int bits_per_sample,
int samples_per_packet) {
if ((channels > kMaxInputChannels) || (channels <= 0) ||
(sample_rate > kMaxSampleRate) || (sample_rate <= 0) ||
(bits_per_sample > kMaxBitsPerSample) || (bits_per_sample <= 0) ||
(samples_per_packet > kMaxSamplesPerPacket) || (samples_per_packet < 0))
return NULL;
scoped_refptr<AudioInputController> controller = new AudioInputController(
event_handler);
// Start the thread and post a task to create the audio input stream.
controller->thread_.Start();
controller->thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(controller.get(), &AudioInputController::DoCreate,
format, channels, sample_rate, bits_per_sample,
samples_per_packet));
return controller;
}
void AudioInputController::Record() {
DCHECK(thread_.IsRunning());
thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &AudioInputController::DoRecord));
}
void AudioInputController::Close() {
if (!thread_.IsRunning()) {
// If the thread is not running make sure we are stopped.
DCHECK_EQ(kClosed, state_);
return;
}
// Wait for all tasks to complete on the audio thread.
thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &AudioInputController::DoClose));
thread_.Stop();
}
void AudioInputController::DoCreate(AudioManager::Format format, int channels,
int sample_rate, int bits_per_sample,
uint32 samples_per_packet) {
stream_ = AudioManager::GetAudioManager()->MakeAudioInputStream(
format, channels, sample_rate, bits_per_sample, samples_per_packet);
if (!stream_) {
// TODO(satish): Define error types.
handler_->OnError(this, 0);
return;
}
if (stream_ && !stream_->Open()) {
stream_->Close();
stream_ = NULL;
// TODO(satish): Define error types.
handler_->OnError(this, 0);
return;
}
state_ = kCreated;
handler_->OnCreated(this);
}
void AudioInputController::DoRecord() {
DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
if (state_ != kCreated)
return;
{
AutoLock auto_lock(lock_);
state_ = kRecording;
}
stream_->Start(this);
handler_->OnRecording(this);
}
void AudioInputController::DoClose() {
DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
DCHECK_NE(kClosed, state_);
// |stream_| can be null if creating the device failed in DoCreate().
if (stream_) {
stream_->Stop();
stream_->Close();
// After stream is closed it is destroyed, so don't keep a reference to it.
stream_ = NULL;
}
// Since the stream is closed at this point there's no other threads reading
// |state_| so we don't need to lock.
state_ = kClosed;
}
void AudioInputController::DoReportError(int code) {
DCHECK_EQ(thread_.message_loop(), MessageLoop::current());
handler_->OnError(this, code);
}
void AudioInputController::OnData(AudioInputStream* stream, const uint8* data,
uint32 size) {
{
AutoLock auto_lock(lock_);
if (state_ != kRecording)
return;
}
handler_->OnData(this, data, size);
}
void AudioInputController::OnClose(AudioInputStream* stream) {
}
void AudioInputController::OnError(AudioInputStream* stream, int code) {
// Handle error on the audio controller thread.
thread_.message_loop()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &AudioInputController::DoReportError, code));
}
} // namespace media
<|endoftext|> |
<commit_before>#include <filter.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::filter;
using Vec = const std::vector<int>;
namespace {
bool less_than_five(int i) {
return i < 5;
}
class LessThanValue {
private:
int compare_val;
public:
LessThanValue(int v) : compare_val(v) { }
bool operator() (int i) {
return i < this->compare_val;
}
};
}
TEST_CASE("filter: handles different functor types", "[filter]") {
Vec ns = {1,2, 5,6, 3,1, 7, -1, 5};
Vec vc = {1,2,3,1,-1};
SECTION("with function pointer") {
auto f = filter(less_than_five, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE( v == vc );
}
SECTION("with callable object") {
auto f = filter(LessThanValue{5}, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE( v == vc );
}
SECTION("with lambda") {
auto ltf = [](int i) {return i < 5;};
auto f = filter(ltf, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE( v == vc );
}
}
TEST_CASE("filter: using identity", "[filter]") {
Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0};
Vec vc = {1,2,3,4,5};
auto f = filter(ns);
Vec v(std::begin(f), std::end(f));
REQUIRE( v == vc );
}
TEST_CASE("filter: binds to lvalues, moves rvales", "[filter]") {
itertest::BasicIterable<int> bi{1,2,3,4};
SECTION("one-arg binds to lvalues") {
filter(bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("two-arg binds to lvalues") {
filter(less_than_five, bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("one-arg moves rvalues") {
filter(std::move(bi));
REQUIRE(bi.was_moved_from());
}
SECTION("two-arg moves rvalues") {
filter(less_than_five, std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("filter: doesn't move or copy elements of iterable", "[filter]") {
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& i : filter(
[](const itertest::SolidInt& si) {return si.getint();},arr)) {
(void)i;
}
}
<commit_msg>tests filter when all elements fail<commit_after>#include <filter.hpp>
#include "helpers.hpp"
#include <vector>
#include <string>
#include <iterator>
#include "catch.hpp"
using iter::filter;
using Vec = const std::vector<int>;
namespace {
bool less_than_five(int i) {
return i < 5;
}
class LessThanValue {
private:
int compare_val;
public:
LessThanValue(int v) : compare_val(v) { }
bool operator() (int i) {
return i < this->compare_val;
}
};
}
TEST_CASE("filter: handles different functor types", "[filter]") {
Vec ns = {1,2, 5,6, 3,1, 7, -1, 5};
Vec vc = {1,2,3,1,-1};
SECTION("with function pointer") {
auto f = filter(less_than_five, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE( v == vc );
}
SECTION("with callable object") {
auto f = filter(LessThanValue{5}, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE( v == vc );
}
SECTION("with lambda") {
auto ltf = [](int i) {return i < 5;};
auto f = filter(ltf, ns);
Vec v(std::begin(f), std::end(f));
REQUIRE( v == vc );
}
}
TEST_CASE("filter: using identity", "[filter]") {
Vec ns{0, 1, 2, 0, 3, 0, 0, 0, 4, 5, 0};
auto f = filter(ns);
Vec v(std::begin(f), std::end(f));
Vec vc = {1,2,3,4,5};
REQUIRE( v == vc );
}
TEST_CASE("filter: binds to lvalues, moves rvales", "[filter]") {
itertest::BasicIterable<int> bi{1,2,3,4};
SECTION("one-arg binds to lvalues") {
filter(bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("two-arg binds to lvalues") {
filter(less_than_five, bi);
REQUIRE_FALSE(bi.was_moved_from());
}
SECTION("one-arg moves rvalues") {
filter(std::move(bi));
REQUIRE(bi.was_moved_from());
}
SECTION("two-arg moves rvalues") {
filter(less_than_five, std::move(bi));
REQUIRE(bi.was_moved_from());
}
}
TEST_CASE("filter: all elements fail predicate", "[filter]") {
Vec ns{10,20,30,40,50};
auto f = filter(less_than_five, ns);
REQUIRE( std::begin(f) == std::end(f) );
}
TEST_CASE("filter: doesn't move or copy elements of iterable", "[filter]") {
constexpr itertest::SolidInt arr[] = {{1}, {0}, {2}};
for (auto&& i : filter(
[](const itertest::SolidInt& si) {return si.getint();},arr)) {
(void)i;
}
}
<|endoftext|> |
<commit_before>#include <sorted.hpp>
#include <set>
#include <unordered_set>
#include <vector>
#include <array>
#include <string>
#include <utility>
#include "helpers.hpp"
#include "catch.hpp"
using iter::sorted;
using Vec = const std::vector<int>;
TEST_CASE("sorted: iterates through a vector in sorted order", "[sorted]" ){
Vec ns = {4, 0, 5, 1, 6, 7, 9, 3, 2, 8};
auto s = sorted(ns);
Vec v(std::begin(s), std::end(s));
Vec vc = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
REQUIRE( v == vc );
}
TEST_CASE("sorted: can modify elements through sorted", "[sorted]") {
std::vector<int> ns(3, 9);
for (auto&& n : sorted(ns)) {
n = -1;
}
Vec vc(3, -1);
REQUIRE( ns == vc );
}
TEST_CASE("sorted: can iterate over unordered container", "[sorted]") {
std::unordered_set<int> ns = {1, 3, 2, 0, 4};
auto s = sorted(ns);
Vec v(std::begin(s), std::end(s));
Vec vc = {0, 1, 2, 3, 4};
REQUIRE( v == vc );
}
TEST_CASE("sorted: empty when iterable is empty", "[sorted]") {
Vec ns{};
auto s = sorted(ns);
REQUIRE( std::begin(s) == std::end(s) );
}
<commit_msg>tests sorted with different functor types<commit_after>#include <sorted.hpp>
#include <set>
#include <unordered_set>
#include <vector>
#include <array>
#include <string>
#include <utility>
#include "helpers.hpp"
#include "catch.hpp"
using iter::sorted;
using Vec = const std::vector<int>;
TEST_CASE("sorted: iterates through a vector in sorted order", "[sorted]" ){
Vec ns = {4, 0, 5, 1, 6, 7, 9, 3, 2, 8};
auto s = sorted(ns);
Vec v(std::begin(s), std::end(s));
Vec vc = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
REQUIRE( v == vc );
}
TEST_CASE("sorted: can modify elements through sorted", "[sorted]") {
std::vector<int> ns(3, 9);
for (auto&& n : sorted(ns)) {
n = -1;
}
Vec vc(3, -1);
REQUIRE( ns == vc );
}
TEST_CASE("sorted: can iterate over unordered container", "[sorted]") {
std::unordered_set<int> ns = {1, 3, 2, 0, 4};
auto s = sorted(ns);
Vec v(std::begin(s), std::end(s));
Vec vc = {0, 1, 2, 3, 4};
REQUIRE( v == vc );
}
TEST_CASE("sorted: empty when iterable is empty", "[sorted]") {
Vec ns{};
auto s = sorted(ns);
REQUIRE( std::begin(s) == std::end(s) );
}
namespace {
bool int_greater_than(int lhs, int rhs) {
return lhs > rhs;
}
struct IntGreaterThan {
bool operator() (int lhs, int rhs) const {
return lhs > rhs;
}
};
}
TEST_CASE("sorted: works with different functor types", "[sorted]") {
Vec ns = {4, 1, 3, 2, 0};
std::vector<int> v;
SECTION("with function pointer") {
auto s = sorted(ns, int_greater_than);
v.insert(v.begin(), std::begin(s), std::end(s));
}
SECTION("with callable object") {
auto s = sorted(ns, IntGreaterThan{});
v.insert(v.begin(), std::begin(s), std::end(s));
}
SECTION("with lambda") {
auto s = sorted(ns, [](int lhs, int rhs){return lhs > rhs;});
v.insert(v.begin(), std::begin(s), std::end(s));
}
Vec vc = {4, 3, 2, 1, 0};
REQUIRE( v == vc );
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 2
#define VERSION_SUBMINOR 10
#define RMI4UPDATE_GETOPTS "hfd:pclv"
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\tPrint this message\n");
fprintf(stdout, "\t-f, --force\tForce updating firmware even it the image provided is older\n\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\tPrint version number.\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< std::hex << rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
HIDDevice device;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 'v':
printVersion();
return 0;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
//device.SetTransportDevice(deviceName);
//device.g_transportDeviceName = deviceName; // leon
} else {
if (!device.FindDevice())
return 1;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
return rc == UPDATE_SUCCESS ? 0 : 1;
}
<commit_msg>Add option to filter based on touchscreen or touchpad<commit_after>/*
* Copyright (C) 2014 Andrew Duggan
* Copyright (C) 2014 Synaptics Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include <sstream>
#include "hiddevice.h"
#include "rmi4update.h"
#define VERSION_MAJOR 1
#define VERSION_MINOR 2
#define VERSION_SUBMINOR 10
#define RMI4UPDATE_GETOPTS "hfdt:pclv"
void printHelp(const char *prog_name)
{
fprintf(stdout, "Usage: %s [OPTIONS] FIRMWAREFILE\n", prog_name);
fprintf(stdout, "\t-h, --help\tPrint this message\n");
fprintf(stdout, "\t-f, --force\tForce updating firmware even it the image provided is older\n\t\t\tthen the current firmware on the device.\n");
fprintf(stdout, "\t-d, --device\thidraw device file associated with the device being updated.\n");
fprintf(stdout, "\t-p, --fw-props\tPrint the firmware properties.\n");
fprintf(stdout, "\t-c, --config-id\tPrint the config id.\n");
fprintf(stdout, "\t-l, --lockdown\tPerform lockdown.\n");
fprintf(stdout, "\t-v, --version\tPrint version number.\n");
fprintf(stdout, "\t-t, --device-type\t\t\tFilter by device type [touchpad or touchscreen].\n");
}
void printVersion()
{
fprintf(stdout, "rmi4update version %d.%d.%d\n",
VERSION_MAJOR, VERSION_MINOR, VERSION_SUBMINOR);
}
int GetFirmwareProps(const char * deviceFile, std::string &props, bool configid)
{
HIDDevice rmidevice;
int rc = UPDATE_SUCCESS;
std::stringstream ss;
rc = rmidevice.Open(deviceFile);
if (rc)
return rc;
rmidevice.ScanPDT(0x1);
rmidevice.QueryBasicProperties();
if (configid) {
ss << std::hex << rmidevice.GetConfigID();
} else {
ss << rmidevice.GetFirmwareVersionMajor() << "."
<< rmidevice.GetFirmwareVersionMinor() << "."
<< std::hex << rmidevice.GetFirmwareID();
if (rmidevice.InBootloader())
ss << " bootloader";
}
props = ss.str();
return rc;
}
int main(int argc, char **argv)
{
int rc;
FirmwareImage image;
int opt;
int index;
char *deviceName = NULL;
const char *firmwareName = NULL;
bool force = false;
static struct option long_options[] = {
{"help", 0, NULL, 'h'},
{"force", 0, NULL, 'f'},
{"device", 1, NULL, 'd'},
{"fw-props", 0, NULL, 'p'},
{"config-id", 0, NULL, 'c'},
{"lockdown", 0, NULL, 'l'},
{"version", 0, NULL, 'v'},
{"device-type", 1, NULL, 't'},
{0, 0, 0, 0},
};
bool printFirmwareProps = false;
bool printConfigid = false;
bool performLockdown = false;
HIDDevice device;
enum RMIDeviceType deviceType = RMI_DEVICE_TYPE_ANY;
while ((opt = getopt_long(argc, argv, RMI4UPDATE_GETOPTS, long_options, &index)) != -1) {
switch (opt) {
case 'h':
printHelp(argv[0]);
return 0;
case 'f':
force = true;
break;
case 'd':
deviceName = optarg;
break;
case 'p':
printFirmwareProps = true;
break;
case 'c':
printFirmwareProps = true;
printConfigid = true;
break;
case 'l':
performLockdown = true;
break;
case 't':
if (!strcasecmp((const char *)optarg, "touchpad"))
deviceType = RMI_DEVICE_TYPE_TOUCHPAD;
else if (!strcasecmp((const char *)optarg, "touchscreen"))
deviceType = RMI_DEVICE_TYPE_TOUCHSCREEN;
break;
case 'v':
printVersion();
return 0;
default:
break;
}
}
if (printFirmwareProps) {
std::string props;
if (!deviceName) {
fprintf(stderr, "Specifiy which device to query\n");
return 1;
}
rc = GetFirmwareProps(deviceName, props, printConfigid);
if (rc) {
fprintf(stderr, "Failed to read properties from device: %s\n", update_err_to_string(rc));
return 1;
}
fprintf(stdout, "%s\n", props.c_str());
return 0;
}
if (optind < argc) {
firmwareName = argv[optind];
} else {
printHelp(argv[0]);
return -1;
}
rc = image.Initialize(firmwareName);
if (rc != UPDATE_SUCCESS) {
fprintf(stderr, "Failed to initialize the firmware image: %s\n", update_err_to_string(rc));
return 1;
}
if (deviceName) {
rc = device.Open(deviceName);
if (rc) {
fprintf(stderr, "%s: failed to initialize rmi device (%d): %s\n", argv[0], errno,
strerror(errno));
return 1;
}
} else {
if (!device.FindDevice(deviceType))
return 1;
}
RMI4Update update(device, image);
rc = update.UpdateFirmware(force, performLockdown);
return rc == UPDATE_SUCCESS ? 0 : 1;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* thrill/net/flow_control_manager.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Emanuel Jöbstl <emanuel.joebstl@gmail.com>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_NET_FLOW_CONTROL_MANAGER_HEADER
#define THRILL_NET_FLOW_CONTROL_MANAGER_HEADER
#include <thrill/common/thread_barrier.hpp>
#include <thrill/common/memory.hpp>
#include <thrill/net/flow_control_channel.hpp>
#include <thrill/net/group.hpp>
#include <string>
#include <vector>
namespace thrill {
namespace net {
//! \addtogroup net Network Communication
//! \{
class FlowControlChannelManager
{
protected:
/**
* The shared barrier used to synchronize between worker threads on this node.
*/
common::ThreadBarrier barrier_;
/**
* The flow control channels associated with this node.
*/
std::vector<FlowControlChannel> channels_;
/**
* Some shared memory to work upon (managed by thread 0).
*/
common::AlignedPtr *shmem_;
public:
/**
* \brief Initializes a certain count of flow control channels.
*
* \param group The net group to use for initialization.
* \param local_worker_count The count of threads to spawn flow channels for.
*
*/
explicit FlowControlChannelManager(Group& group, size_t local_worker_count)
: barrier_(local_worker_count), shmem_(new common::AlignedPtr[local_worker_count]) {
for (size_t i = 0; i < local_worker_count; i++) {
channels_.emplace_back(group, i, local_worker_count, barrier_, shmem_);
}
}
/**
* \brief Gets all flow control channels for all threads.
* \return A flow channel for each thread.
*/
std::vector<FlowControlChannel> & GetFlowControlChannels() {
return channels_;
}
/**
* \brief Gets the flow control channel for a certain thread.
* \return The flow control channel for a certain thread.
*/
FlowControlChannel & GetFlowControlChannel(size_t thread_id) {
return channels_[thread_id];
}
};
//! \}
} // namespace net
} // namespace thrill
#endif // !THRILL_NET_FLOW_CONTROL_MANAGER_HEADER
/******************************************************************************/
<commit_msg>Added FlowControlManager destructor to dispose of shmem<commit_after>/*******************************************************************************
* thrill/net/flow_control_manager.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Emanuel Jöbstl <emanuel.joebstl@gmail.com>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_NET_FLOW_CONTROL_MANAGER_HEADER
#define THRILL_NET_FLOW_CONTROL_MANAGER_HEADER
#include <thrill/common/thread_barrier.hpp>
#include <thrill/common/memory.hpp>
#include <thrill/net/flow_control_channel.hpp>
#include <thrill/net/group.hpp>
#include <string>
#include <vector>
namespace thrill {
namespace net {
//! \addtogroup net Network Communication
//! \{
class FlowControlChannelManager
{
protected:
/**
* The shared barrier used to synchronize between worker threads on this node.
*/
common::ThreadBarrier barrier_;
/**
* The flow control channels associated with this node.
*/
std::vector<FlowControlChannel> channels_;
/**
* Some shared memory to work upon (managed by thread 0).
*/
common::AlignedPtr *shmem_;
public:
/**
* \brief Initializes a certain count of flow control channels.
*
* \param group The net group to use for initialization.
* \param local_worker_count The count of threads to spawn flow channels for.
*
*/
explicit FlowControlChannelManager(Group& group, size_t local_worker_count)
: barrier_(local_worker_count), shmem_(new common::AlignedPtr[local_worker_count]) {
for (size_t i = 0; i < local_worker_count; i++) {
channels_.emplace_back(group, i, local_worker_count, barrier_, shmem_);
}
}
/**
* \brief Gets all flow control channels for all threads.
* \return A flow channel for each thread.
*/
std::vector<FlowControlChannel> & GetFlowControlChannels() {
return channels_;
}
/**
* \brief Gets the flow control channel for a certain thread.
* \return The flow control channel for a certain thread.
*/
FlowControlChannel & GetFlowControlChannel(size_t thread_id) {
return channels_[thread_id];
}
~FlowControlChannelManager() {
delete shmem_;
}
};
//! \}
} // namespace net
} // namespace thrill
#endif // !THRILL_NET_FLOW_CONTROL_MANAGER_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>/**
Logging subsystem for OpenPnP Capture library.
Copyright (c) 2017 Jason von Nieda, Niels Moseley.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdarg.h>
#include "logging.h"
/* In their infinite "wisdom" Microsoft have declared snprintf deprecated
and we must therefore resort to a macro to fix something that shouldn't
be a problem */
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
static uint32_t gs_logLevel = LOG_NOTICE;
static customLogFunc gs_logFunc = NULL;
void installCustomLogFunction(customLogFunc logfunc)
{
gs_logFunc = logfunc;
}
void LOG(uint32_t logLevel, const char *format, ...)
{
if (logLevel > gs_logLevel)
{
return;
}
char logbuffer[1024];
char *ptr = logbuffer;
switch(logLevel)
{
case LOG_CRIT:
snprintf(logbuffer,1024,"[CRIT] ");
ptr += 7;
break;
case LOG_ERR:
snprintf(logbuffer,1024,"[ERR ] ");
ptr += 7;
break;
case LOG_INFO:
snprintf(logbuffer,1024,"[INFO] ");
ptr += 7;
break;
case LOG_DEBUG:
snprintf(logbuffer,1024,"[DBG ] ");
ptr += 7;
break;
case LOG_VERBOSE:
snprintf(logbuffer,1024,"[VERB] ");
ptr += 7;
break;
default:
break;
}
va_list args;
va_start(args, format);
vsnprintf(ptr, 1024-7, format, args);
va_end(args);
if (gs_logFunc != nullptr)
{
// custom log functions to no include the
// prefix.
gs_logFunc(logLevel, ptr);
}
else
{
fprintf(stderr, logbuffer);
}
}
void setLogLevel(uint32_t logLevel)
{
gs_logLevel = logLevel;
}
uint32_t getLogLevel()
{
return gs_logLevel;
}<commit_msg>Fixed fprintf in logging where there was no format argument<commit_after>/**
Logging subsystem for OpenPnP Capture library.
Copyright (c) 2017 Jason von Nieda, Niels Moseley.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdarg.h>
#include "logging.h"
/* In their infinite "wisdom" Microsoft have declared snprintf deprecated
and we must therefore resort to a macro to fix something that shouldn't
be a problem */
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
static uint32_t gs_logLevel = LOG_NOTICE;
static customLogFunc gs_logFunc = NULL;
void installCustomLogFunction(customLogFunc logfunc)
{
gs_logFunc = logfunc;
}
void LOG(uint32_t logLevel, const char *format, ...)
{
if (logLevel > gs_logLevel)
{
return;
}
char logbuffer[1024];
char *ptr = logbuffer;
switch(logLevel)
{
case LOG_CRIT:
snprintf(logbuffer,1024,"[CRIT] ");
ptr += 7;
break;
case LOG_ERR:
snprintf(logbuffer,1024,"[ERR ] ");
ptr += 7;
break;
case LOG_INFO:
snprintf(logbuffer,1024,"[INFO] ");
ptr += 7;
break;
case LOG_DEBUG:
snprintf(logbuffer,1024,"[DBG ] ");
ptr += 7;
break;
case LOG_VERBOSE:
snprintf(logbuffer,1024,"[VERB] ");
ptr += 7;
break;
default:
break;
}
va_list args;
va_start(args, format);
vsnprintf(ptr, 1024-7, format, args);
va_end(args);
if (gs_logFunc != nullptr)
{
// custom log functions to no include the
// prefix.
gs_logFunc(logLevel, ptr);
}
else
{
fprintf(stderr, "%s", logbuffer);
}
}
void setLogLevel(uint32_t logLevel)
{
gs_logLevel = logLevel;
}
uint32_t getLogLevel()
{
return gs_logLevel;
}<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief ルネサス RX 選択
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#if defined(SIG_RX621)
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX621/system.hpp"
#include "RX621/sci.hpp"
#include "RX621/icu.hpp"
#elif defined(SIG_RX24T)
#include "RX24T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/dtc.hpp"
#include "RX24T/icu.hpp"
#include "RX24T/icu_mgr.hpp"
#include "RX24T/mtu3.hpp"
#include "RX24T/poe3.hpp"
#include "RX24T/gpt.hpp"
#include "RX24T/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX24T/sci.hpp"
#include "RX24T/riic.hpp"
#include "RX24T/rspi.hpp"
#include "RX24T/crc.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX24T/cmpc.hpp"
#include "RX24T/doc.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"
#elif defined(SIG_RX63T)
#include "RX63T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX63T/icu.hpp"
#include "RX63T/icu_mgr.hpp"
#include "RX600/cmt.hpp"
#include "RX63T/system.hpp"
#include "RX63T/sci.hpp"
#include "RX63T/port_map.hpp"
#include "RX63T/power_cfg.hpp"
#elif defined(SIG_RX64M)
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/port.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/can.hpp"
#include "RX600/rspi.hpp"
#include "RX600/qspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"
#elif defined(SIG_RX65N)
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/port.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/can.hpp"
#include "RX600/rspi.hpp"
#include "RX600/qspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"
#elif defined(SIG_RX71M)
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/port.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/can.hpp"
#include "RX600/rspi.hpp"
#include "RX600/qspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"
#else
# error "Requires SIG_XXX to be defined"
#endif
<commit_msg>update: CMTW manage<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief ルネサス RX 選択
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2016, 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/byte_order.h"
#include "common/vect.h"
#include "common/delay.hpp"
#if defined(SIG_RX621)
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX621/system.hpp"
#include "RX621/sci.hpp"
#include "RX621/icu.hpp"
#elif defined(SIG_RX24T)
#include "RX24T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX24T/system.hpp"
#include "RX24T/system_io.hpp"
#include "RX24T/dtc.hpp"
#include "RX24T/icu.hpp"
#include "RX24T/icu_mgr.hpp"
#include "RX24T/mtu3.hpp"
#include "RX24T/poe3.hpp"
#include "RX24T/gpt.hpp"
#include "RX24T/tmr.hpp"
#include "RX600/cmt.hpp"
#include "RX24T/sci.hpp"
#include "RX24T/riic.hpp"
#include "RX24T/rspi.hpp"
#include "RX24T/crc.hpp"
#include "RX24T/s12ad.hpp"
#include "RX24T/adc_io.hpp"
#include "RX24T/da.hpp"
#include "RX24T/cmpc.hpp"
#include "RX24T/doc.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/flash.hpp"
#include "RX24T/flash_io.hpp"
#elif defined(SIG_RX63T)
#include "RX63T/peripheral.hpp"
#include "RX600/port.hpp"
#include "RX63T/icu.hpp"
#include "RX63T/icu_mgr.hpp"
#include "RX600/cmt.hpp"
#include "RX63T/system.hpp"
#include "RX63T/sci.hpp"
#include "RX63T/port_map.hpp"
#include "RX63T/power_cfg.hpp"
#elif defined(SIG_RX64M)
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/port.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/can.hpp"
#include "RX600/rspi.hpp"
#include "RX600/qspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"
#elif defined(SIG_RX65N)
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/port.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/can.hpp"
#include "RX600/rspi.hpp"
#include "RX600/qspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX65x/s12adf.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX65x/glcdc.hpp"
#include "RX65x/glcdc_io.hpp"
#include "RX65x/drw2d.hpp"
#include "RX65x/drw2d_mgr.hpp"
#include "RX600/dmac_mgr.hpp"
#elif defined(SIG_RX71M)
#include "RX600/peripheral.hpp"
#include "RX600/system.hpp"
#include "RX600/system_io.hpp"
#include "RX600/dmac.hpp"
#include "RX600/exdmac.hpp"
#include "RX600/port.hpp"
#include "RX600/bus.hpp"
#include "RX600/mpc.hpp"
#include "RX600/icu.hpp"
#include "RX600/icu_mgr.hpp"
#include "RX600/tpu.hpp"
#include "RX600/cmt.hpp"
#include "RX600/cmtw.hpp"
#include "RX600/mtu3.hpp"
#include "RX600/sci.hpp"
#include "RX600/scif.hpp"
#include "RX600/riic.hpp"
#include "RX600/can.hpp"
#include "RX600/rspi.hpp"
#include "RX600/qspi.hpp"
#include "RX600/port_map.hpp"
#include "RX600/power_cfg.hpp"
#include "RX600/s12adc.hpp"
#include "RX600/adc_io.hpp"
#include "RX600/r12da.hpp"
#include "RX600/dac_out.hpp"
#include "RX600/sdram.hpp"
#include "RX600/etherc.hpp"
#include "RX600/edmac.hpp"
#include "RX600/usb.hpp"
#include "RX600/rtc.hpp"
#include "RX600/rtc_io.hpp"
#include "RX600/wdta.hpp"
#include "RX600/flash.hpp"
#include "RX600/flash_io.hpp"
#include "RX600/ether_io.hpp"
#include "RX600/ssi.hpp"
#include "RX600/src.hpp"
#include "RX600/sdhi.hpp"
#include "RX600/sdhi_io.hpp"
#include "RX600/standby_ram.hpp"
#include "RX600/ssi_io.hpp"
#include "RX600/dmac_mgr.hpp"
#else
# error "Requires SIG_XXX to be defined"
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANPARSEDURI_HEADER_GUARD_1357924680)
#define XALANPARSEDURI_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
XALAN_CPP_NAMESPACE_BEGIN
/**
* URI handling (hopefully) according to RFC2396.
*/
class XALAN_PLATFORMSUPPORT_EXPORT XalanParsedURI
{
public:
// Flags to say if a component is defined. Note that each component may
// be defined but empty, except for the path.
#if defined(XALAN_INLINE_INITIALIZATION)
static const int d_scheme = 1;
static const int d_authority = 2;
static const int d_query = 4;
static const int d_fragment = 8;
#else
enum eComponent
{
d_scheme = 1,
d_authority = 2,
d_query = 4,
d_fragment = 8
};
#endif
/**
* Default constructor
*/
XalanParsedURI(MemoryManagerType& theManager) :
m_scheme(theManager),
m_authority(theManager),
m_path(theManager),
m_query(theManager),
m_fragment(theManager),
m_defined(0)
{
}
/**
* Constructor which parses the passed in uri
*
* @param uriString URI to parse
* @param uriStringLen Length of the URI string
*/
XalanParsedURI(
const XalanDOMChar* uriString,
XalanDOMString::size_type uriStringLen,
MemoryManagerType& theManager) :
m_scheme(theManager),
m_authority(theManager),
m_path(theManager),
m_query(theManager),
m_fragment(theManager),
m_defined(0)
{
parse(uriString, uriStringLen);
}
/**
* Constructor which parses the passed in uri
*
* @param uriString URI to parse
*/
XalanParsedURI(
const XalanDOMString &uriString,
MemoryManagerType& theManager) :
m_scheme(theManager),
m_authority(theManager),
m_path(theManager),
m_query(theManager),
m_fragment(theManager),
m_defined(0)
{
parse(uriString.c_str(), uriString.length());
}
MemoryManagerType&
getMemoryManager()
{
return m_scheme.getMemoryManager();
}
/**
* Parse the passed in uri
*
* @param uriString URI to parse
* @param uriStringLen Length of the URI string
*/
void parse(
const XalanDOMChar* uriString,
XalanDOMString::size_type uriStringLen);
/**
* Parse the passed in uri
*
* @param uriString URI to parse
* @param uriStringLen Length of the URI string
*/
void parse(
const XalanDOMString &uriString)
{
parse(uriString.c_str(), uriString.length());
}
/**
* Reassemble the uri components to make a complete URI
*
* @return The reassembled URI
*/
XalanDOMString& make(XalanDOMString& theResult) const;
/**
* Resolve this URI relative to another, according to RFC2396.
*
* @param base The base URI to use during resolution.
*/
void resolve(const XalanParsedURI &base);
/**
* Resolve this URI relative to another.
*
* @param base The base URI string
* @param baseLen The length of the base URI
*/
void resolve(
const XalanDOMChar *base,
const XalanDOMString::size_type baseLen)
{
XalanParsedURI baseURI(base, baseLen,getMemoryManager());
resolve(baseURI);
}
/**
* Resolve this URI relative to another.
*
* @param base The base URI string
*/
void resolve(
const XalanDOMString &base)
{
resolve(base.c_str(), base.length());
}
/**
* Resolve the one URI relative to another.
*
* @relative The URI string to resolve
* @relativeLen The lengh of the relative URI string
* @base The base URI string
* @baseLen The length of the base URI string
*
*/
static XalanDOMString& resolve(
const XalanDOMChar *relative,
XalanDOMString::size_type relativeLen,
const XalanDOMChar *base,
XalanDOMString::size_type baseLen,
XalanDOMString& theResult
);
/**
* Resolve the one URI relative to another.
*
* @relative The URI string to resolve
* @base The base URI string
*
*/
static XalanDOMString& resolve(
const XalanDOMString &relative,
const XalanDOMString &base,
XalanDOMString& theResult
)
{
return resolve(relative.c_str(), relative.length(), base.c_str(), base.length(), theResult);
}
/**
* Get the scheme component
*/
const XalanDOMString& getScheme() const
{
return m_scheme;
}
/**
* See if the scheme component is defined.
*/
bool isSchemeDefined() const
{
return !!(m_defined & d_scheme);
}
/**
* Set the scheme component. Also sets the scheme defined flag.
*/
void setScheme(const XalanDOMChar *scheme)
{
m_scheme = scheme;
m_defined |= d_scheme;
}
/**
* Set the scheme component. Also sets the scheme defined flag.
*/
void setScheme(const XalanDOMString &scheme)
{
m_scheme = scheme;
m_defined |= d_scheme;
}
/**
* Get the authority component
*/
const XalanDOMString& getAuthority() const
{
return m_authority;
}
/**
* See if the authority component is defined.
*/
bool isAuthorityDefined() const
{
return !!(m_defined & d_authority);
}
/**
* Set the authority component. Also sets the authority defined flag.
*/
void setAuthority(const XalanDOMChar *authority)
{
m_authority = authority;
m_defined |= d_authority;
}
/**
* Set the authority component. Also sets the authority defined flag.
*/
void setAuthority(const XalanDOMString &authority)
{
m_authority = authority;
m_defined |= d_authority;
}
/**
* Get the path component
*/
const XalanDOMString& getPath() const
{
return m_path;
}
/**
* Set the path component.
*/
void setPath(const XalanDOMChar *path)
{
m_path = path;
}
/**
* Set the path component.
*/
void setPath(const XalanDOMString &path)
{
m_path = path;
}
/**
* Get function to get the query component
*/
const XalanDOMString& getQuery() const
{
return m_query;
}
/**
* See if the query component is defined.
*/
bool isQueryDefined() const
{
return !!(m_defined & d_query);
}
/**
* Set the query component. Also sets the query defined flag.
*/
void setQuery(const XalanDOMChar *query)
{
m_query = query;
m_defined |= d_query;
}
/**
* Set the query component. Also sets the query defined flag.
*/
void setQuery(const XalanDOMString &query)
{
m_query = query;
m_defined |= d_query;
}
/**
* Get the fragment component
*/
const XalanDOMString& getFragment() const
{
return m_fragment;
}
/**
* See if the fragment component is defined.
*/
bool isFragmentDefined() const
{
return !!(m_defined & d_fragment);
}
/**
* Set the fragment component. Also sets the fragment defined flag.
*/
void setFragment(const XalanDOMChar *fragment)
{
m_fragment = fragment;
m_defined |= d_fragment;
}
/**
* Set the fragment component. Also sets the fragment defined flag.
*/
void setFragment(const XalanDOMString &fragment)
{
m_fragment = fragment;
m_defined |= d_fragment;
}
/**
* Get the defined components mask.
*/
unsigned int getDefined() const
{
return m_defined;
}
/**
* Set the defined components mask.
*/
void setDefined(unsigned int defined)
{
m_defined = defined;
}
private:
// not implemented
XalanParsedURI();
XalanParsedURI(const XalanParsedURI&);
XalanDOMString m_scheme;
XalanDOMString m_authority;
XalanDOMString m_path;
XalanDOMString m_query;
XalanDOMString m_fragment;
unsigned int m_defined;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANPARSEDURI_HEADER_GUARD_1357924680
<commit_msg>Simplified boolean expressions.<commit_after>/*
* Copyright 1999-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(XALANPARSEDURI_HEADER_GUARD_1357924680)
#define XALANPARSEDURI_HEADER_GUARD_1357924680
// Base include file. Must be first.
#include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
XALAN_CPP_NAMESPACE_BEGIN
/**
* URI handling (hopefully) according to RFC2396.
*/
class XALAN_PLATFORMSUPPORT_EXPORT XalanParsedURI
{
public:
// Flags to say if a component is defined. Note that each component may
// be defined but empty, except for the path.
#if defined(XALAN_INLINE_INITIALIZATION)
static const int d_scheme = 1;
static const int d_authority = 2;
static const int d_query = 4;
static const int d_fragment = 8;
#else
enum eComponent
{
d_scheme = 1,
d_authority = 2,
d_query = 4,
d_fragment = 8
};
#endif
/**
* Default constructor
*/
XalanParsedURI(MemoryManagerType& theManager) :
m_scheme(theManager),
m_authority(theManager),
m_path(theManager),
m_query(theManager),
m_fragment(theManager),
m_defined(0)
{
}
/**
* Constructor which parses the passed in uri
*
* @param uriString URI to parse
* @param uriStringLen Length of the URI string
*/
XalanParsedURI(
const XalanDOMChar* uriString,
XalanDOMString::size_type uriStringLen,
MemoryManagerType& theManager) :
m_scheme(theManager),
m_authority(theManager),
m_path(theManager),
m_query(theManager),
m_fragment(theManager),
m_defined(0)
{
parse(uriString, uriStringLen);
}
/**
* Constructor which parses the passed in uri
*
* @param uriString URI to parse
*/
XalanParsedURI(
const XalanDOMString &uriString,
MemoryManagerType& theManager) :
m_scheme(theManager),
m_authority(theManager),
m_path(theManager),
m_query(theManager),
m_fragment(theManager),
m_defined(0)
{
parse(uriString.c_str(), uriString.length());
}
MemoryManagerType&
getMemoryManager()
{
return m_scheme.getMemoryManager();
}
/**
* Parse the passed in uri
*
* @param uriString URI to parse
* @param uriStringLen Length of the URI string
*/
void parse(
const XalanDOMChar* uriString,
XalanDOMString::size_type uriStringLen);
/**
* Parse the passed in uri
*
* @param uriString URI to parse
* @param uriStringLen Length of the URI string
*/
void parse(
const XalanDOMString &uriString)
{
parse(uriString.c_str(), uriString.length());
}
/**
* Reassemble the uri components to make a complete URI
*
* @return The reassembled URI
*/
XalanDOMString& make(XalanDOMString& theResult) const;
/**
* Resolve this URI relative to another, according to RFC2396.
*
* @param base The base URI to use during resolution.
*/
void resolve(const XalanParsedURI &base);
/**
* Resolve this URI relative to another.
*
* @param base The base URI string
* @param baseLen The length of the base URI
*/
void resolve(
const XalanDOMChar *base,
const XalanDOMString::size_type baseLen)
{
XalanParsedURI baseURI(base, baseLen,getMemoryManager());
resolve(baseURI);
}
/**
* Resolve this URI relative to another.
*
* @param base The base URI string
*/
void resolve(
const XalanDOMString &base)
{
resolve(base.c_str(), base.length());
}
/**
* Resolve the one URI relative to another.
*
* @relative The URI string to resolve
* @relativeLen The lengh of the relative URI string
* @base The base URI string
* @baseLen The length of the base URI string
*
*/
static XalanDOMString& resolve(
const XalanDOMChar *relative,
XalanDOMString::size_type relativeLen,
const XalanDOMChar *base,
XalanDOMString::size_type baseLen,
XalanDOMString& theResult
);
/**
* Resolve the one URI relative to another.
*
* @relative The URI string to resolve
* @base The base URI string
*
*/
static XalanDOMString& resolve(
const XalanDOMString &relative,
const XalanDOMString &base,
XalanDOMString& theResult
)
{
return resolve(relative.c_str(), relative.length(), base.c_str(), base.length(), theResult);
}
/**
* Get the scheme component
*/
const XalanDOMString& getScheme() const
{
return m_scheme;
}
/**
* See if the scheme component is defined.
*/
bool isSchemeDefined() const
{
return m_defined & d_scheme;
}
/**
* Set the scheme component. Also sets the scheme defined flag.
*/
void setScheme(const XalanDOMChar *scheme)
{
m_scheme = scheme;
m_defined |= d_scheme;
}
/**
* Set the scheme component. Also sets the scheme defined flag.
*/
void setScheme(const XalanDOMString &scheme)
{
m_scheme = scheme;
m_defined |= d_scheme;
}
/**
* Get the authority component
*/
const XalanDOMString& getAuthority() const
{
return m_authority;
}
/**
* See if the authority component is defined.
*/
bool isAuthorityDefined() const
{
return m_defined & d_authority;
}
/**
* Set the authority component. Also sets the authority defined flag.
*/
void setAuthority(const XalanDOMChar *authority)
{
m_authority = authority;
m_defined |= d_authority;
}
/**
* Set the authority component. Also sets the authority defined flag.
*/
void setAuthority(const XalanDOMString &authority)
{
m_authority = authority;
m_defined |= d_authority;
}
/**
* Get the path component
*/
const XalanDOMString& getPath() const
{
return m_path;
}
/**
* Set the path component.
*/
void setPath(const XalanDOMChar *path)
{
m_path = path;
}
/**
* Set the path component.
*/
void setPath(const XalanDOMString &path)
{
m_path = path;
}
/**
* Get function to get the query component
*/
const XalanDOMString& getQuery() const
{
return m_query;
}
/**
* See if the query component is defined.
*/
bool isQueryDefined() const
{
return m_defined & d_query;
}
/**
* Set the query component. Also sets the query defined flag.
*/
void setQuery(const XalanDOMChar *query)
{
m_query = query;
m_defined |= d_query;
}
/**
* Set the query component. Also sets the query defined flag.
*/
void setQuery(const XalanDOMString &query)
{
m_query = query;
m_defined |= d_query;
}
/**
* Get the fragment component
*/
const XalanDOMString& getFragment() const
{
return m_fragment;
}
/**
* See if the fragment component is defined.
*/
bool isFragmentDefined() const
{
return m_defined & d_fragment;
}
/**
* Set the fragment component. Also sets the fragment defined flag.
*/
void setFragment(const XalanDOMChar *fragment)
{
m_fragment = fragment;
m_defined |= d_fragment;
}
/**
* Set the fragment component. Also sets the fragment defined flag.
*/
void setFragment(const XalanDOMString &fragment)
{
m_fragment = fragment;
m_defined |= d_fragment;
}
/**
* Get the defined components mask.
*/
unsigned int getDefined() const
{
return m_defined;
}
/**
* Set the defined components mask.
*/
void setDefined(unsigned int defined)
{
m_defined = defined;
}
private:
// not implemented
XalanParsedURI();
XalanParsedURI(const XalanParsedURI&);
XalanDOMString m_scheme;
XalanDOMString m_authority;
XalanDOMString m_path;
XalanDOMString m_query;
XalanDOMString m_fragment;
unsigned int m_defined;
};
XALAN_CPP_NAMESPACE_END
#endif // XALANPARSEDURI_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2015 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QHash>
#include <QString>
#include "keywordssuggestor.h"
#include "suggestionartwork.h"
namespace Suggestion {
void KeywordsSuggestor::setSuggestedArtworks(const QVector<SuggestionArtwork *> &suggestedArtworks) {
m_SelectedArtworksCount = 0;
m_KeywordsHash.clear();
m_SuggestedKeywords.clearModel();
m_AllOtherKeywords.clearModel();
beginResetModel();
qDeleteAll(m_Suggestions);
m_Suggestions.clear();
m_Suggestions << suggestedArtworks;
endResetModel();
unsetInProgress();
emit suggestionArrived();
}
void KeywordsSuggestor::clear() {
m_SelectedArtworksCount = 0;
m_KeywordsHash.clear();
m_SuggestedKeywords.clearModel();
m_AllOtherKeywords.clearModel();
beginResetModel();
qDeleteAll(m_Suggestions);
m_Suggestions.clear();
endResetModel();
unsetInProgress();
}
QString KeywordsSuggestor::removeSuggestedKeywordAt(int keywordIndex) {
QString keyword;
m_SuggestedKeywords.takeKeywordAt(keywordIndex, keyword);
emit suggestedKeywordsCountChanged();
return keyword;
}
QString KeywordsSuggestor::removeOtherKeywordAt(int keywordIndex) {
QString keyword;
m_AllOtherKeywords.takeKeywordAt(keywordIndex, keyword);
emit otherKeywordsCountChanged();
return keyword;
}
void KeywordsSuggestor::setArtworkSelected(int index, bool newState) {
if (index < 0 || index >= m_Suggestions.length()) {
return;
}
SuggestionArtwork *suggestionArtwork = m_Suggestions[index];
suggestionArtwork->setIsSelected(newState);
int sign = newState ? +1 : -1;
accountKeywords(suggestionArtwork->getKeywords(), sign);
m_SelectedArtworksCount += sign;
QModelIndex qIndex = this->index(index);
emit dataChanged(qIndex, qIndex, QVector<int>() << IsSelectedRole);
updateSuggestedKeywords();
}
void KeywordsSuggestor::searchArtworks(const QString &searchTerm) {
if (!m_IsInProgress && !searchTerm.simplified().isEmpty()) {
setInProgress();
QStringList searchTerms = searchTerm.split(QChar::Space, QString::SkipEmptyParts);
if (m_UseLocal) {
m_QueryEngine.submitLocalQuery(m_LocalLibrary, searchTerms);
} else {
m_QueryEngine.submitQuery(searchTerms);
}
}
}
int KeywordsSuggestor::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return m_Suggestions.length();
}
QVariant KeywordsSuggestor::data(const QModelIndex &index, int role) const {
if (!index.isValid()) { return QVariant(); }
SuggestionArtwork *suggestionArtwork = m_Suggestions.at(index.row());
switch (role) {
case UrlRole:
return suggestionArtwork->getUrl();
case IsSelectedRole:
return suggestionArtwork->getIsSelected();
default:
return QVariant();
}
}
QHash<int, QByteArray> KeywordsSuggestor::roleNames() const {
QHash<int, QByteArray> roles;
roles[UrlRole] = "url";
roles[IsSelectedRole] = "isselected";
return roles;
}
void KeywordsSuggestor::accountKeywords(const QStringList &keywords, int sign) {
foreach(const QString &keyword, keywords) {
if (m_KeywordsHash.contains(keyword)) {
m_KeywordsHash[keyword] += sign;
} else {
m_KeywordsHash.insert(keyword, 1);
}
}
}
QSet<QString> KeywordsSuggestor::getSelectedArtworksKeywords() const {
QSet<QString> allKeywords;
foreach (SuggestionArtwork *artwork, m_Suggestions) {
if (artwork->getIsSelected()) {
QSet<QString> currentKeywords = artwork->getKeywords().toSet();
allKeywords.unite(currentKeywords);
}
}
return allKeywords;
}
void KeywordsSuggestor::updateSuggestedKeywords() {
QStringList keywords;
QHash<QString, int>::const_iterator it = m_KeywordsHash.constBegin();
QHash<QString, int>::const_iterator itEnd = m_KeywordsHash.constEnd();
int threshold = 0;
if (m_SelectedArtworksCount <= 2) {
threshold = qMax(m_SelectedArtworksCount, 1);
} else if (m_SelectedArtworksCount <= 5) {
threshold = 2;
} else if (m_SelectedArtworksCount <= 8) {
threshold = 3;
} else if (m_SelectedArtworksCount <= 10) {
threshold = 4;
} else {
threshold = m_SelectedArtworksCount / 2 - 1;
}
for (; it != itEnd; ++it) {
if (it.value() >= threshold) {
keywords.append(it.key());
}
}
m_SuggestedKeywords.resetKeywords(keywords);
if (m_SelectedArtworksCount != 0) {
QSet<QString> allKeywords = getSelectedArtworksKeywords();
QSet<QString> suggestedKeywords = keywords.toSet();
QSet<QString> otherKeywords = allKeywords.subtract(suggestedKeywords);
m_AllOtherKeywords.resetKeywords(otherKeywords.toList());
}
#ifndef QT_DEBUG
else {
m_AllOtherKeywords.clear();
m_SuggestedKeywords.clear();
m_KeywordsHash.clear();
}
#endif
emit suggestedKeywordsCountChanged();
emit otherKeywordsCountChanged();
}
}
<commit_msg>Fix for release build<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2015 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QHash>
#include <QString>
#include "keywordssuggestor.h"
#include "suggestionartwork.h"
namespace Suggestion {
void KeywordsSuggestor::setSuggestedArtworks(const QVector<SuggestionArtwork *> &suggestedArtworks) {
m_SelectedArtworksCount = 0;
m_KeywordsHash.clear();
m_SuggestedKeywords.clearModel();
m_AllOtherKeywords.clearModel();
beginResetModel();
qDeleteAll(m_Suggestions);
m_Suggestions.clear();
m_Suggestions << suggestedArtworks;
endResetModel();
unsetInProgress();
emit suggestionArrived();
}
void KeywordsSuggestor::clear() {
m_SelectedArtworksCount = 0;
m_KeywordsHash.clear();
m_SuggestedKeywords.clearModel();
m_AllOtherKeywords.clearModel();
beginResetModel();
qDeleteAll(m_Suggestions);
m_Suggestions.clear();
endResetModel();
unsetInProgress();
}
QString KeywordsSuggestor::removeSuggestedKeywordAt(int keywordIndex) {
QString keyword;
m_SuggestedKeywords.takeKeywordAt(keywordIndex, keyword);
emit suggestedKeywordsCountChanged();
return keyword;
}
QString KeywordsSuggestor::removeOtherKeywordAt(int keywordIndex) {
QString keyword;
m_AllOtherKeywords.takeKeywordAt(keywordIndex, keyword);
emit otherKeywordsCountChanged();
return keyword;
}
void KeywordsSuggestor::setArtworkSelected(int index, bool newState) {
if (index < 0 || index >= m_Suggestions.length()) {
return;
}
SuggestionArtwork *suggestionArtwork = m_Suggestions[index];
suggestionArtwork->setIsSelected(newState);
int sign = newState ? +1 : -1;
accountKeywords(suggestionArtwork->getKeywords(), sign);
m_SelectedArtworksCount += sign;
QModelIndex qIndex = this->index(index);
emit dataChanged(qIndex, qIndex, QVector<int>() << IsSelectedRole);
updateSuggestedKeywords();
}
void KeywordsSuggestor::searchArtworks(const QString &searchTerm) {
if (!m_IsInProgress && !searchTerm.simplified().isEmpty()) {
setInProgress();
QStringList searchTerms = searchTerm.split(QChar::Space, QString::SkipEmptyParts);
if (m_UseLocal) {
m_QueryEngine.submitLocalQuery(m_LocalLibrary, searchTerms);
} else {
m_QueryEngine.submitQuery(searchTerms);
}
}
}
int KeywordsSuggestor::rowCount(const QModelIndex &parent) const {
Q_UNUSED(parent);
return m_Suggestions.length();
}
QVariant KeywordsSuggestor::data(const QModelIndex &index, int role) const {
if (!index.isValid()) { return QVariant(); }
SuggestionArtwork *suggestionArtwork = m_Suggestions.at(index.row());
switch (role) {
case UrlRole:
return suggestionArtwork->getUrl();
case IsSelectedRole:
return suggestionArtwork->getIsSelected();
default:
return QVariant();
}
}
QHash<int, QByteArray> KeywordsSuggestor::roleNames() const {
QHash<int, QByteArray> roles;
roles[UrlRole] = "url";
roles[IsSelectedRole] = "isselected";
return roles;
}
void KeywordsSuggestor::accountKeywords(const QStringList &keywords, int sign) {
foreach(const QString &keyword, keywords) {
if (m_KeywordsHash.contains(keyword)) {
m_KeywordsHash[keyword] += sign;
} else {
m_KeywordsHash.insert(keyword, 1);
}
}
}
QSet<QString> KeywordsSuggestor::getSelectedArtworksKeywords() const {
QSet<QString> allKeywords;
foreach (SuggestionArtwork *artwork, m_Suggestions) {
if (artwork->getIsSelected()) {
QSet<QString> currentKeywords = artwork->getKeywords().toSet();
allKeywords.unite(currentKeywords);
}
}
return allKeywords;
}
void KeywordsSuggestor::updateSuggestedKeywords() {
QStringList keywords;
QHash<QString, int>::const_iterator it = m_KeywordsHash.constBegin();
QHash<QString, int>::const_iterator itEnd = m_KeywordsHash.constEnd();
int threshold = 0;
if (m_SelectedArtworksCount <= 2) {
threshold = qMax(m_SelectedArtworksCount, 1);
} else if (m_SelectedArtworksCount <= 5) {
threshold = 2;
} else if (m_SelectedArtworksCount <= 8) {
threshold = 3;
} else if (m_SelectedArtworksCount <= 10) {
threshold = 4;
} else {
threshold = m_SelectedArtworksCount / 2 - 1;
}
for (; it != itEnd; ++it) {
if (it.value() >= threshold) {
keywords.append(it.key());
}
}
m_SuggestedKeywords.resetKeywords(keywords);
if (m_SelectedArtworksCount != 0) {
QSet<QString> allKeywords = getSelectedArtworksKeywords();
QSet<QString> suggestedKeywords = keywords.toSet();
QSet<QString> otherKeywords = allKeywords.subtract(suggestedKeywords);
m_AllOtherKeywords.resetKeywords(otherKeywords.toList());
}
#ifndef QT_DEBUG
else {
m_AllOtherKeywords.clearKeywords();
m_SuggestedKeywords.clearKeywords();
m_KeywordsHash.clear();
}
#endif
emit suggestedKeywordsCountChanged();
emit otherKeywordsCountChanged();
}
}
<|endoftext|> |
<commit_before>//===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements program code generation debugging support.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ListReducer.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalValue.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/StringExtras.h"
#include "Support/FileUtilities.h"
#include <algorithm>
#include <set>
using namespace llvm;
namespace llvm {
extern cl::list<std::string> InputArgv;
class ReduceMisCodegenFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Suffix) {
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
if (!Suffix.empty() && TestFuncs(Suffix))
return KeepSuffix;
return NoFailure;
}
bool TestFuncs(const std::vector<Function*> &CodegenTest,
bool KeepFiles = false);
};
}
bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
bool KeepFiles) {
std::cout << "Testing functions: ";
PrintFunctionList(Funcs);
std::cout << "\t";
// Clone the module for the two halves of the program we want.
Module *SafeModule = CloneModule(BD.getProgram());
// The JIT must extract the 'main' function.
std::vector<Function*> RealFuncs(Funcs);
if (BD.isExecutingJIT()) {
if (Function *F = BD.Program->getMainFunction())
RealFuncs.push_back(F);
}
Module *TestModule = SplitFunctionsOutOfModule(SafeModule, RealFuncs);
// This is only applicable if we are debugging the JIT:
// Find all external functions in the Safe modules that are actually used
// (called or taken address of), and make them call the JIT wrapper instead
if (BD.isExecutingJIT()) {
// Must delete `main' from Safe module if it has it
Function *safeMain = SafeModule->getNamedFunction("main");
assert(safeMain && "`main' function not found in safe module!");
DeleteFunctionBody(safeMain);
// Add an external function "getPointerToNamedFunction" that JIT provides
// Prototype: void *getPointerToNamedFunction(const char* Name)
std::vector<const Type*> Params;
Params.push_back(PointerType::get(Type::SByteTy)); // std::string&
FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),
Params, false /* isVarArg */);
Function *resolverFunc = new Function(resolverTy,
GlobalValue::ExternalLinkage,
"getPointerToNamedFunction",
SafeModule);
// Use the function we just added to get addresses of functions we need
// Iterate over the global declarations in the Safe module
for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
F->getIntrinsicID() == 0 /* ignore intrinsics */ &&
// Don't forward functions which are external in the test module too.
!TestModule->getNamedFunction(F->getName())->isExternal()) {
// If it has a non-zero use list,
// 1. Add a string constant with its name to the global file
// The correct type is `const [ NUM x sbyte ]' where NUM is length of
// function name + 1
const std::string &Name = F->getName();
GlobalVariable *funcName =
new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
true /* isConstant */,
GlobalValue::InternalLinkage,
ConstantArray::get(Name),
Name + "_name",
SafeModule);
// 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
// sbyte* so it matches the signature of the resolver function.
std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::IntTy));
// 3. Replace all uses of `func' with calls to resolver by:
// (a) Iterating through the list of uses of this function
// (b) Insert a cast instruction in front of each use
// (c) Replace use of old call with new call
// GetElementPtr *funcName, ulong 0, ulong 0
Value *GEP =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
GEPargs);
std::vector<Value*> ResolverArgs;
ResolverArgs.push_back(GEP);
// Insert code at the beginning of the function
while (!F->use_empty())
if (Instruction *Inst = dyn_cast<Instruction>(F->use_back())) {
// call resolver(GetElementPtr...)
CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
"resolver", Inst);
// cast the result from the resolver to correctly-typed function
CastInst *castResolver =
new CastInst(resolve, PointerType::get(F->getFunctionType()),
"resolverCast", Inst);
// actually use the resolved function
Inst->replaceUsesOfWith(F, castResolver);
} else {
// FIXME: need to take care of cases where a function is used by
// something other than an instruction; e.g., global variable
// initializers and constant expressions.
std::cerr << "UNSUPPORTED: Non-instruction is using an external "
<< "function, " << F->getName() << "().\n";
abort();
}
}
}
}
if (verifyModule(*SafeModule) || verifyModule(*TestModule)) {
std::cerr << "Bugpoint has a bug, an corrupted a module!!\n";
abort();
}
DEBUG(std::cerr << "Safe module:\n";
typedef Module::iterator MI;
typedef Module::giterator MGI;
for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
std::cerr << "Test module:\n";
for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
);
// Write out the bytecode to be sent to CBE
std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
// Remove all functions from the Test module EXCEPT for the ones specified in
// Funcs. We know which ones these are because they are non-external in
// ToOptimize, but external in ToNotOptimize.
//
for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)
if (!I->isExternal()) {
Function *TNOF = SafeModule->getFunction(I->getName(),
I->getFunctionType());
assert(TNOF && "Function doesn't exist in ToNotOptimize module??");
if (!TNOF->isExternal())
DeleteFunctionBody(I);
}
std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
if (verifyModule(*TestModule)) {
std::cerr << "Bytecode file corrupted!\n";
exit(1);
}
// Clean up the modules, removing extra cruft that we don't need anymore...
SafeModule = BD.performFinalCleanups(SafeModule);
TestModule = BD.performFinalCleanups(TestModule);
if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
// Make a shared library
std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
delete SafeModule;
delete TestModule;
// Run the code generator on the `Test' code, loading the shared library.
// The function returns whether or not the new output differs from reference.
int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
if (Result)
std::cerr << ": still failing!\n";
else
std::cerr << ": didn't fail.\n";
if (KeepFiles) {
std::cout << "You can reproduce the problem with the command line: \n";
if (BD.isExecutingJIT()) {
std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
} else {
std::cout << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
std::cout << " gcc " << SharedObject << " " << TestModuleBC
<< ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
std::cout << " " << TestModuleBC << ".exe";
}
for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
std::cout << " " << InputArgv[i];
std::cout << "\n";
std::cout << "The shared object was created with:\n llc -march=c "
<< SafeModuleBC << " -o temporary.c\n"
<< " gcc -xc temporary.c -O2 -o " << SharedObject
#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
<< " -G" // Compile a shared library, `-G' for Sparc
#else
<< " -shared" // `-shared' for Linux/X86, maybe others
#endif
<< " -fno-strict-aliasing\n";
} else {
removeFile(TestModuleBC);
removeFile(SafeModuleBC);
removeFile(SharedObject);
}
return Result;
}
namespace {
struct Disambiguator {
std::set<std::string> SymbolNames;
std::set<GlobalValue*> Symbols;
uint64_t uniqueCounter;
bool externalOnly;
public:
Disambiguator() : uniqueCounter(0), externalOnly(true) {}
void setExternalOnly(bool value) { externalOnly = value; }
void add(GlobalValue &V) {
// If we're only processing externals and this isn't external, bail
if (externalOnly && !V.isExternal()) return;
// If we're already processed this symbol, don't add it again
if (Symbols.count(&V) != 0) return;
// Ignore intrinsic functions
if (Function *F = dyn_cast<Function>(&V))
if (F->getIntrinsicID() != 0)
return;
std::string SymName = V.getName();
// Use the Mangler facility to make symbol names that will be valid in
// shared objects.
SymName = Mangler::makeNameProper(SymName);
V.setName(SymName);
if (SymbolNames.count(SymName) == 0) {
DEBUG(std::cerr << "Disambiguator: adding " << SymName
<< ", no conflicts.\n");
SymbolNames.insert(SymName);
} else {
// Mangle name before adding
std::string newName;
do {
newName = SymName + "_" + utostr(uniqueCounter);
if (SymbolNames.count(newName) == 0) break;
else ++uniqueCounter;
} while (1);
//while (SymbolNames.count(V->getName()+utostr(uniqueCounter++))==0);
DEBUG(std::cerr << "Disambiguator: conflict: " << SymName
<< ", adding: " << newName << "\n");
V.setName(newName);
SymbolNames.insert(newName);
}
Symbols.insert(&V);
}
};
}
static void DisambiguateGlobalSymbols(Module *M) {
// First, try not to cause collisions by minimizing chances of renaming an
// already-external symbol, so take in external globals and functions as-is.
Disambiguator D;
DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
// Now just rename functions and globals as necessary, keeping what's already
// in the set unique.
D.setExternalOnly(false);
DEBUG(std::cerr << "Disambiguating globals\n");
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I) D.add(*I);
DEBUG(std::cerr << "Disambiguating globals\n");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) D.add(*I);
}
bool BugDriver::debugCodeGenerator() {
if ((void*)cbe == (void*)Interpreter) {
std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
std::cout << "\n*** The C backend cannot match the reference diff, but it "
<< "is used as the 'known good'\n code generator, so I can't"
<< " debug it. Perhaps you have a front-end problem?\n As a"
<< " sanity check, I left the result of executing the program "
<< "with the C backend\n in this file for you: '"
<< Result << "'.\n";
return true;
}
// See if we can pin down which functions are being miscompiled...
// First, build a list of all of the non-external functions in the program.
std::vector<Function*> MisCodegenFunctions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
MisCodegenFunctions.push_back(I);
// If we are executing the JIT, we *must* keep the function `main' in the
// module that is passed in, and not the shared library. However, we still
// want to be able to debug the `main' function alone. Thus, we create a new
// function `main' which just calls the old one.
if (isExecutingJIT()) {
// Get the `main' function
Function *oldMain = Program->getNamedFunction("main");
assert(oldMain && "`main' function not found in program!");
// Rename it
oldMain->setName("llvm_old_main");
// Create a NEW `main' function with same type
Function *newMain = new Function(oldMain->getFunctionType(),
GlobalValue::ExternalLinkage,
"main", Program);
// Call the old main function and return its result
BasicBlock *BB = new BasicBlock("entry", newMain);
std::vector<Value*> args;
for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
OI = oldMain->abegin(); I != E; ++I, ++OI) {
I->setName(OI->getName()); // Copy argument names from oldMain
args.push_back(I);
}
CallInst *call = new CallInst(oldMain, args);
BB->getInstList().push_back(call);
// if the type of old function wasn't void, return value of call
if (oldMain->getReturnType() != Type::VoidTy) {
new ReturnInst(call, BB);
} else {
new ReturnInst(0, BB);
}
}
DisambiguateGlobalSymbols(Program);
// Do the reduction...
if (!ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions)) {
std::cerr << "*** Execution matches reference output! "
<< "bugpoint can't help you with your problem!\n";
return false;
}
std::cout << "\n*** The following functions are being miscompiled: ";
PrintFunctionList(MisCodegenFunctions);
std::cout << "\n";
// Output a bunch of bytecode files for the user...
ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
return false;
}
<commit_msg>Make full use of the Mangler interface to simplify code<commit_after>//===- CodeGeneratorBug.cpp - Debug code generation bugs ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements program code generation debugging support.
//
//===----------------------------------------------------------------------===//
#include "BugDriver.h"
#include "ListReducer.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/GlobalValue.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Transforms/Utils/Linker.h"
#include "Support/CommandLine.h"
#include "Support/Debug.h"
#include "Support/StringExtras.h"
#include "Support/FileUtilities.h"
using namespace llvm;
namespace llvm {
extern cl::list<std::string> InputArgv;
class ReduceMisCodegenFunctions : public ListReducer<Function*> {
BugDriver &BD;
public:
ReduceMisCodegenFunctions(BugDriver &bd) : BD(bd) {}
virtual TestResult doTest(std::vector<Function*> &Prefix,
std::vector<Function*> &Suffix) {
if (!Prefix.empty() && TestFuncs(Prefix))
return KeepPrefix;
if (!Suffix.empty() && TestFuncs(Suffix))
return KeepSuffix;
return NoFailure;
}
bool TestFuncs(const std::vector<Function*> &CodegenTest,
bool KeepFiles = false);
};
}
bool ReduceMisCodegenFunctions::TestFuncs(const std::vector<Function*> &Funcs,
bool KeepFiles) {
std::cout << "Testing functions: ";
PrintFunctionList(Funcs);
std::cout << "\t";
// Clone the module for the two halves of the program we want.
Module *SafeModule = CloneModule(BD.getProgram());
// The JIT must extract the 'main' function.
std::vector<Function*> RealFuncs(Funcs);
if (BD.isExecutingJIT()) {
if (Function *F = BD.Program->getMainFunction())
RealFuncs.push_back(F);
}
Module *TestModule = SplitFunctionsOutOfModule(SafeModule, RealFuncs);
// This is only applicable if we are debugging the JIT:
// Find all external functions in the Safe modules that are actually used
// (called or taken address of), and make them call the JIT wrapper instead
if (BD.isExecutingJIT()) {
// Must delete `main' from Safe module if it has it
Function *safeMain = SafeModule->getNamedFunction("main");
assert(safeMain && "`main' function not found in safe module!");
DeleteFunctionBody(safeMain);
// Add an external function "getPointerToNamedFunction" that JIT provides
// Prototype: void *getPointerToNamedFunction(const char* Name)
std::vector<const Type*> Params;
Params.push_back(PointerType::get(Type::SByteTy)); // std::string&
FunctionType *resolverTy = FunctionType::get(PointerType::get(Type::VoidTy),
Params, false /* isVarArg */);
Function *resolverFunc = new Function(resolverTy,
GlobalValue::ExternalLinkage,
"getPointerToNamedFunction",
SafeModule);
// Use the function we just added to get addresses of functions we need
// Iterate over the global declarations in the Safe module
for (Module::iterator F=SafeModule->begin(),E=SafeModule->end(); F!=E; ++F){
if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
F->getIntrinsicID() == 0 /* ignore intrinsics */ &&
// Don't forward functions which are external in the test module too.
!TestModule->getNamedFunction(F->getName())->isExternal()) {
// If it has a non-zero use list,
// 1. Add a string constant with its name to the global file
// The correct type is `const [ NUM x sbyte ]' where NUM is length of
// function name + 1
const std::string &Name = F->getName();
GlobalVariable *funcName =
new GlobalVariable(ArrayType::get(Type::SByteTy, Name.length()+1),
true /* isConstant */,
GlobalValue::InternalLinkage,
ConstantArray::get(Name),
Name + "_name",
SafeModule);
// 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
// sbyte* so it matches the signature of the resolver function.
std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::IntTy));
// 3. Replace all uses of `func' with calls to resolver by:
// (a) Iterating through the list of uses of this function
// (b) Insert a cast instruction in front of each use
// (c) Replace use of old call with new call
// GetElementPtr *funcName, ulong 0, ulong 0
Value *GEP =
ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
GEPargs);
std::vector<Value*> ResolverArgs;
ResolverArgs.push_back(GEP);
// Insert code at the beginning of the function
while (!F->use_empty())
if (Instruction *Inst = dyn_cast<Instruction>(F->use_back())) {
// call resolver(GetElementPtr...)
CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
"resolver", Inst);
// cast the result from the resolver to correctly-typed function
CastInst *castResolver =
new CastInst(resolve, PointerType::get(F->getFunctionType()),
"resolverCast", Inst);
// actually use the resolved function
Inst->replaceUsesOfWith(F, castResolver);
} else {
// FIXME: need to take care of cases where a function is used by
// something other than an instruction; e.g., global variable
// initializers and constant expressions.
std::cerr << "UNSUPPORTED: Non-instruction is using an external "
<< "function, " << F->getName() << "().\n";
abort();
}
}
}
}
if (verifyModule(*SafeModule) || verifyModule(*TestModule)) {
std::cerr << "Bugpoint has a bug, an corrupted a module!!\n";
abort();
}
DEBUG(std::cerr << "Safe module:\n";
typedef Module::iterator MI;
typedef Module::giterator MGI;
for (MI I = SafeModule->begin(), E = SafeModule->end(); I != E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
for (MGI I = SafeModule->gbegin(), E = SafeModule->gend(); I!=E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
std::cerr << "Test module:\n";
for (MI I = TestModule->begin(), E = TestModule->end(); I != E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
for (MGI I=TestModule->gbegin(),E = TestModule->gend(); I!= E; ++I)
if (!I->isExternal()) std::cerr << "\t" << I->getName() << "\n";
);
// Write out the bytecode to be sent to CBE
std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
if (BD.writeProgramToFile(SafeModuleBC, SafeModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
// Remove all functions from the Test module EXCEPT for the ones specified in
// Funcs. We know which ones these are because they are non-external in
// ToOptimize, but external in ToNotOptimize.
//
for (Module::iterator I = TestModule->begin(), E = TestModule->end();I!=E;++I)
if (!I->isExternal()) {
Function *TNOF = SafeModule->getFunction(I->getName(),
I->getFunctionType());
assert(TNOF && "Function doesn't exist in ToNotOptimize module??");
if (!TNOF->isExternal())
DeleteFunctionBody(I);
}
std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
if (verifyModule(*TestModule)) {
std::cerr << "Bytecode file corrupted!\n";
exit(1);
}
// Clean up the modules, removing extra cruft that we don't need anymore...
SafeModule = BD.performFinalCleanups(SafeModule);
TestModule = BD.performFinalCleanups(TestModule);
if (BD.writeProgramToFile(TestModuleBC, TestModule)) {
std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
exit(1);
}
// Make a shared library
std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
delete SafeModule;
delete TestModule;
// Run the code generator on the `Test' code, loading the shared library.
// The function returns whether or not the new output differs from reference.
int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
if (Result)
std::cerr << ": still failing!\n";
else
std::cerr << ": didn't fail.\n";
if (KeepFiles) {
std::cout << "You can reproduce the problem with the command line: \n";
if (BD.isExecutingJIT()) {
std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
} else {
std::cout << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
std::cout << " gcc " << SharedObject << " " << TestModuleBC
<< ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
std::cout << " " << TestModuleBC << ".exe";
}
for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
std::cout << " " << InputArgv[i];
std::cout << "\n";
std::cout << "The shared object was created with:\n llc -march=c "
<< SafeModuleBC << " -o temporary.c\n"
<< " gcc -xc temporary.c -O2 -o " << SharedObject
#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
<< " -G" // Compile a shared library, `-G' for Sparc
#else
<< " -shared" // `-shared' for Linux/X86, maybe others
#endif
<< " -fno-strict-aliasing\n";
} else {
removeFile(TestModuleBC);
removeFile(SafeModuleBC);
removeFile(SharedObject);
}
return Result;
}
static void DisambiguateGlobalSymbols(Module *M) {
// Try not to cause collisions by minimizing chances of renaming an
// already-external symbol, so take in external globals and functions as-is.
// The code should work correctly without disambiguation (assuming the same
// mangler is used by the two code generators), but having symbols with the
// same name causes warnings to be emitted by the code generator.
Mangler Mang(*M);
DEBUG(std::cerr << "Disambiguating globals (external-only)\n");
for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
I->setName(Mang.getValueName(I));
DEBUG(std::cerr << "Disambiguating functions (external-only)\n");
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
I->setName(Mang.getValueName(I));
}
bool BugDriver::debugCodeGenerator() {
if ((void*)cbe == (void*)Interpreter) {
std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
std::cout << "\n*** The C backend cannot match the reference diff, but it "
<< "is used as the 'known good'\n code generator, so I can't"
<< " debug it. Perhaps you have a front-end problem?\n As a"
<< " sanity check, I left the result of executing the program "
<< "with the C backend\n in this file for you: '"
<< Result << "'.\n";
return true;
}
// See if we can pin down which functions are being miscompiled...
// First, build a list of all of the non-external functions in the program.
std::vector<Function*> MisCodegenFunctions;
for (Module::iterator I = Program->begin(), E = Program->end(); I != E; ++I)
if (!I->isExternal())
MisCodegenFunctions.push_back(I);
// If we are executing the JIT, we *must* keep the function `main' in the
// module that is passed in, and not the shared library. However, we still
// want to be able to debug the `main' function alone. Thus, we create a new
// function `main' which just calls the old one.
if (isExecutingJIT()) {
// Get the `main' function
Function *oldMain = Program->getNamedFunction("main");
assert(oldMain && "`main' function not found in program!");
// Rename it
oldMain->setName("llvm_old_main");
// Create a NEW `main' function with same type
Function *newMain = new Function(oldMain->getFunctionType(),
GlobalValue::ExternalLinkage,
"main", Program);
// Call the old main function and return its result
BasicBlock *BB = new BasicBlock("entry", newMain);
std::vector<Value*> args;
for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
OI = oldMain->abegin(); I != E; ++I, ++OI) {
I->setName(OI->getName()); // Copy argument names from oldMain
args.push_back(I);
}
CallInst *call = new CallInst(oldMain, args);
BB->getInstList().push_back(call);
// if the type of old function wasn't void, return value of call
if (oldMain->getReturnType() != Type::VoidTy) {
new ReturnInst(call, BB);
} else {
new ReturnInst(0, BB);
}
}
DisambiguateGlobalSymbols(Program);
// Do the reduction...
if (!ReduceMisCodegenFunctions(*this).reduceList(MisCodegenFunctions)) {
std::cerr << "*** Execution matches reference output! "
<< "bugpoint can't help you with your problem!\n";
return false;
}
std::cout << "\n*** The following functions are being miscompiled: ";
PrintFunctionList(MisCodegenFunctions);
std::cout << "\n";
// Output a bunch of bytecode files for the user...
ReduceMisCodegenFunctions(*this).TestFuncs(MisCodegenFunctions, true);
return false;
}
<|endoftext|> |
<commit_before>#include "fieldsToMemberAccesses.h"
#include "chplalloc.h"
#include "expr.h"
#include "replace.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "symtab.h"
#include "type.h"
/***
*** Change fields and methods within class methods to this.field
*** Adds this to formal argument list for methods
***/
static ClassType* CurrentClass = NULL;
void FieldsToMemberAccesses::preProcessStmt(Stmt* &stmt) {
if (TypeDefStmt* tds = dynamic_cast<TypeDefStmt*>(stmt)) {
if (ClassType* ctype = dynamic_cast<ClassType*>(tds->type)) {
CurrentClass = ctype;
Stmt* stmt = ctype->definition;
while (stmt) {
Stmt* next = nextLink(Stmt, stmt);
if (FnDefStmt* method = dynamic_cast<FnDefStmt*>(stmt)) {
Symbol* this_insert = new ParamSymbol(PARAM_INOUT, "this", ctype);
Symboltable::defineInScope(this_insert, method->fn->paramScope);
this_insert = appendLink(this_insert, method->fn->formals);
method->fn->formals = this_insert;
method->fn->_this = this_insert;
}
stmt = next;
}
}
}
}
void FieldsToMemberAccesses::postProcessStmt(Stmt* &stmt) {
if (TypeDefStmt* tds = dynamic_cast<TypeDefStmt*>(stmt)) {
if (dynamic_cast<ClassType*>(tds->type)) {
CurrentClass = NULL;
}
}
}
void FieldsToMemberAccesses::preProcessExpr(Expr* &expr) {
if (CurrentClass) {
if (Variable* member = dynamic_cast<Variable*>(expr)) {
if (!strcmp(member->var->name, "this")) {
return;
}
if (Symboltable::lookupInScope(member->var->name, CurrentClass->scope)) {
/* replacement of expr variable by memberaccess */
if (FnSymbol* parentFn = dynamic_cast<FnSymbol*>(member->stmt->parentSymbol)) {
MemberAccess* repl = new MemberAccess(new Variable(parentFn->formals),
member->var);
Expr::replace(expr, repl);
}
else {
INT_FATAL(expr, "Statement is not in method in FieldsToMemberAccesses");
}
}
}
}
}
<commit_msg>Removed a reference to file that does not exist in fieldsToMemberAccesses.cpp<commit_after>#include "fieldsToMemberAccesses.h"
#include "chplalloc.h"
#include "expr.h"
#include "stmt.h"
#include "stringutil.h"
#include "symbol.h"
#include "symtab.h"
#include "type.h"
/***
*** Change fields and methods within class methods to this.field
*** Adds this to formal argument list for methods
***/
static ClassType* CurrentClass = NULL;
void FieldsToMemberAccesses::preProcessStmt(Stmt* &stmt) {
if (TypeDefStmt* tds = dynamic_cast<TypeDefStmt*>(stmt)) {
if (ClassType* ctype = dynamic_cast<ClassType*>(tds->type)) {
CurrentClass = ctype;
Stmt* stmt = ctype->definition;
while (stmt) {
Stmt* next = nextLink(Stmt, stmt);
if (FnDefStmt* method = dynamic_cast<FnDefStmt*>(stmt)) {
Symbol* this_insert = new ParamSymbol(PARAM_INOUT, "this", ctype);
Symboltable::defineInScope(this_insert, method->fn->paramScope);
this_insert = appendLink(this_insert, method->fn->formals);
method->fn->formals = this_insert;
method->fn->_this = this_insert;
}
stmt = next;
}
}
}
}
void FieldsToMemberAccesses::postProcessStmt(Stmt* &stmt) {
if (TypeDefStmt* tds = dynamic_cast<TypeDefStmt*>(stmt)) {
if (dynamic_cast<ClassType*>(tds->type)) {
CurrentClass = NULL;
}
}
}
void FieldsToMemberAccesses::preProcessExpr(Expr* &expr) {
if (CurrentClass) {
if (Variable* member = dynamic_cast<Variable*>(expr)) {
if (!strcmp(member->var->name, "this")) {
return;
}
if (Symboltable::lookupInScope(member->var->name, CurrentClass->scope)) {
/* replacement of expr variable by memberaccess */
if (FnSymbol* parentFn = dynamic_cast<FnSymbol*>(member->stmt->parentSymbol)) {
MemberAccess* repl = new MemberAccess(new Variable(parentFn->formals),
member->var);
Expr::replace(expr, repl);
}
else {
INT_FATAL(expr, "Statement is not in method in FieldsToMemberAccesses");
}
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Add missing SAL_OVERRIDE..<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: Timestamp.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: oj $ $Date: 2002-03-21 15:06:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_TIMESTAMP_HXX_
#include "java/sql/Timestamp.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include "connectivity/dbconversion.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Date
//**************************************************************
const double fMilliSecondsPerDay = 86400000.0;
jclass java_sql_Date::theClass = 0;
java_sql_Date::java_sql_Date( const ::com::sun::star::util::Date& _rOut ) : java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Parameter konvertieren
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;)Ljava/sql/Date;";
jobject tempObj;
jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// und aufraeumen
}
java_sql_Date::~java_sql_Date()
{}
jclass java_sql_Date::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Date"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
// -----------------------------------------------------------------------------
void java_sql_Date::saveClassRef( jclass pClass )
{
if( SDBThreadAttach::IsJavaErrorOccured() || pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
// -----------------------------------------------------------------------------
java_sql_Date::operator ::com::sun::star::util::Date()
{
return ::dbtools::DBTypeConversion::toDate(toString());
}
//**************************************************************
//************ Class: java.sql.Time
//**************************************************************
jclass java_sql_Time::theClass = 0;
java_sql_Time::~java_sql_Time()
{}
jclass java_sql_Time::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Time"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_Time::saveClassRef( jclass pClass )
{
if( SDBThreadAttach::IsJavaErrorOccured() || pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_sql_Time::java_sql_Time( const ::com::sun::star::util::Time& _rOut ): java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Parameter konvertieren
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toTimeString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;)Ljava/sql/Time;";
jobject tempObj;
jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
t.pEnv->DeleteLocalRef((jstring)args[0].l);
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// und aufraeumen
}
// -----------------------------------------------------------------------------
java_sql_Time::operator ::com::sun::star::util::Time()
{
return ::dbtools::DBTypeConversion::toTime(toString());
}
//**************************************************************
//************ Class: java.sql.Timestamp
//**************************************************************
jclass java_sql_Timestamp::theClass = 0;
java_sql_Timestamp::~java_sql_Timestamp()
{}
jclass java_sql_Timestamp::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Timestamp"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_Timestamp::saveClassRef( jclass pClass )
{
if( SDBThreadAttach::IsJavaErrorOccured() || pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_sql_Timestamp::java_sql_Timestamp(const ::com::sun::star::util::DateTime& _rOut)
:java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Parameter konvertieren
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateTimeString(_rOut);
if ( _rOut.HundredthSeconds )
{
sDateStr += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("."));
sDateStr += ::rtl::OUString::valueOf(_rOut.HundredthSeconds);
}
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;)Ljava/sql/Timestamp;";
jobject tempObj;
jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// und aufraeumen
}
sal_Int32 java_sql_Timestamp::getNanos()
{
jint out(0);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()I";
char * cMethodName = "getNanos";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallIntMethod( object, mID);
} //mID
} //t.pEnv
return (sal_Int32)out;
}
void java_sql_Timestamp::setNanos( sal_Int32 _par0 )
{
SDBThreadAttach t;
if( t.pEnv ){
jvalue args[1];
// Parameter konvertieren
args[0].i = (sal_Int32)_par0;
// temporaere Variable initialisieren
char * cSignature = "(I)V";
char * cMethodName = "setNanos";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
t.pEnv->CallVoidMethod( object, mID, args[0].i );
// und aufraeumen
} //mID
} //t.pEnv
}
// -----------------------------------------------------------------------------
java_sql_Timestamp::operator ::com::sun::star::util::DateTime()
{
return ::dbtools::DBTypeConversion::toDateTime(toString());
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS mav4 (1.8.60); FILE MERGED 2003/04/15 12:22:17 oj 1.8.60.1: #108943# merge from apps61beta2 and statement fix, concurrency<commit_after>/*************************************************************************
*
* $RCSfile: Timestamp.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2003-04-24 13:23:00 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_TIMESTAMP_HXX_
#include "java/sql/Timestamp.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _DBHELPER_DBCONVERSION_HXX_
#include "connectivity/dbconversion.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Date
//**************************************************************
const double fMilliSecondsPerDay = 86400000.0;
jclass java_sql_Date::theClass = 0;
java_sql_Date::java_sql_Date( const ::com::sun::star::util::Date& _rOut ) : java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Parameter konvertieren
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;)Ljava/sql/Date;";
jobject tempObj;
jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// und aufraeumen
}
java_sql_Date::~java_sql_Date()
{}
jclass java_sql_Date::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Date"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
// -----------------------------------------------------------------------------
void java_sql_Date::saveClassRef( jclass pClass )
{
if( pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
// -----------------------------------------------------------------------------
java_sql_Date::operator ::com::sun::star::util::Date()
{
return ::dbtools::DBTypeConversion::toDate(toString());
}
//**************************************************************
//************ Class: java.sql.Time
//**************************************************************
jclass java_sql_Time::theClass = 0;
java_sql_Time::~java_sql_Time()
{}
jclass java_sql_Time::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Time"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_Time::saveClassRef( jclass pClass )
{
if( pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_sql_Time::java_sql_Time( const ::com::sun::star::util::Time& _rOut ): java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Parameter konvertieren
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toTimeString(_rOut);
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;)Ljava/sql/Time;";
jobject tempObj;
jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
t.pEnv->DeleteLocalRef((jstring)args[0].l);
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// und aufraeumen
}
// -----------------------------------------------------------------------------
java_sql_Time::operator ::com::sun::star::util::Time()
{
return ::dbtools::DBTypeConversion::toTime(toString());
}
//**************************************************************
//************ Class: java.sql.Timestamp
//**************************************************************
jclass java_sql_Timestamp::theClass = 0;
java_sql_Timestamp::~java_sql_Timestamp()
{}
jclass java_sql_Timestamp::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Timestamp"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_sql_Timestamp::saveClassRef( jclass pClass )
{
if( pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_sql_Timestamp::java_sql_Timestamp(const ::com::sun::star::util::DateTime& _rOut)
:java_util_Date( NULL, (jobject)NULL )
{
SDBThreadAttach t;
if( !t.pEnv )
return;
jvalue args[1];
// Parameter konvertieren
::rtl::OUString sDateStr;
sDateStr = ::dbtools::DBTypeConversion::toDateTimeString(_rOut);
if ( _rOut.HundredthSeconds )
{
sDateStr += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("."));
sDateStr += ::rtl::OUString::valueOf(_rOut.HundredthSeconds);
}
args[0].l = convertwchar_tToJavaString(t.pEnv,sDateStr);
// Java-Call fuer den Konstruktor absetzen
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;)Ljava/sql/Timestamp;";
jobject tempObj;
jmethodID mID = t.pEnv->GetStaticMethodID( getMyClass(), "valueOf", cSignature );OSL_ENSURE(mID,"Unknown method id!");
tempObj = t.pEnv->CallStaticObjectMethod( getMyClass(), mID, args[0].l );
saveRef( t.pEnv, tempObj );
t.pEnv->DeleteLocalRef( tempObj );
// und aufraeumen
}
sal_Int32 java_sql_Timestamp::getNanos()
{
jint out(0);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()I";
char * cMethodName = "getNanos";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallIntMethod( object, mID);
} //mID
} //t.pEnv
return (sal_Int32)out;
}
void java_sql_Timestamp::setNanos( sal_Int32 _par0 )
{
SDBThreadAttach t;
if( t.pEnv ){
jvalue args[1];
// Parameter konvertieren
args[0].i = (sal_Int32)_par0;
// temporaere Variable initialisieren
char * cSignature = "(I)V";
char * cMethodName = "setNanos";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
t.pEnv->CallVoidMethod( object, mID, args[0].i );
// und aufraeumen
} //mID
} //t.pEnv
}
// -----------------------------------------------------------------------------
java_sql_Timestamp::operator ::com::sun::star::util::DateTime()
{
return ::dbtools::DBTypeConversion::toDateTime(toString());
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <string>
#include "cell.h"
#include "number.h"
namespace rtl {
void io$close(Cell **pf)
{
FILE *f = (FILE *)(*pf);
fclose(f);
*pf = NULL;
}
void io$fprint(void *pf, const std::string &s)
{
FILE *f = (FILE *)pf;
fputs(s.c_str(), f);
fputs("\n", f);
}
void *io$open(const std::string &name, Cell &/*mode*/)
{
return fopen(name.c_str(), "r");
}
bool io$readline(void *pf, std::string *s)
{
FILE *f = (FILE *)pf;
s->clear();
for (;;) {
char buf[1024];
if (fgets(buf, sizeof(buf), f) == NULL) {
return not s->empty();
}
s->append(buf);
if (s->at(s->length()-1) == '\n') {
return true;
}
}
}
void *io$stdin()
{
return stdin;
}
void *io$stdout()
{
return stdout;
}
void *io$stderr()
{
return stderr;
}
void io$write(void *pf, const std::string &s)
{
FILE *f = (FILE *)pf;
fputs(s.c_str(), f);
}
}
<commit_msg>Fix for older compiler<commit_after>#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <iso646.h>
#include <stdio.h>
#include <string>
#include "cell.h"
#include "number.h"
namespace rtl {
void io$close(Cell **pf)
{
FILE *f = (FILE *)(*pf);
fclose(f);
*pf = NULL;
}
void io$fprint(void *pf, const std::string &s)
{
FILE *f = (FILE *)pf;
fputs(s.c_str(), f);
fputs("\n", f);
}
void *io$open(const std::string &name, Cell &/*mode*/)
{
return fopen(name.c_str(), "r");
}
bool io$readline(void *pf, std::string *s)
{
FILE *f = (FILE *)pf;
s->clear();
for (;;) {
char buf[1024];
if (fgets(buf, sizeof(buf), f) == NULL) {
return not s->empty();
}
s->append(buf);
if (s->at(s->length()-1) == '\n') {
return true;
}
}
}
void *io$stdin()
{
return stdin;
}
void *io$stdout()
{
return stdout;
}
void *io$stderr()
{
return stderr;
}
void io$write(void *pf, const std::string &s)
{
FILE *f = (FILE *)pf;
fputs(s.c_str(), f);
}
}
<|endoftext|> |
<commit_before>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2004 Daniel Molkentin <molkentin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kolabwizard.h"
#include "kolabconfig.h"
#include "kmailchanges.h"
#include <libkcal/resourcecalendar.h>
#include <kabc/resource.h>
#include "kresources/kolab/kcal/resourcekolab.h"
#include "kresources/kolab/kabc/resourcekolab.h"
#include "kresources/kolab/knotes/resourcekolab.h"
#include <qwhatsthis.h>
#include <klineedit.h>
#include <klocale.h>
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlabel.h>
class SetupLDAPSearchAccount : public KConfigPropagator::Change
{
public:
SetupLDAPSearchAccount()
: KConfigPropagator::Change( i18n("Setup LDAP Search Account") )
{
}
void apply()
{
const QString host = KolabConfig::self()->server();
// Figure out the basedn
QString basedn = host;
// If the user gave a full email address, the domain name
// of that overrides the server name for the ldap dn
const QString user = KolabConfig::self()->user();
int pos = user.find( "@" );
if ( pos > 0 ) {
const QString h = user.mid( pos+1 );
if ( !h.isEmpty() )
// The user did type in a domain on the email address. Use that
basedn = h;
}
basedn.replace(".",",dc=");
basedn.prepend("dc=");
// Set the changes
KConfig c( "kabldaprc" );
c.setGroup( "LDAP" );
bool hasMyServer = false;
uint selHosts = c.readNumEntry("NumSelectedHosts", 0);
for ( uint i = 0 ; i < selHosts && !hasMyServer; ++i )
if ( c.readEntry( QString("SelectedHost%1").arg(i) ) == host )
hasMyServer = true;
if ( !hasMyServer ) {
c.writeEntry( "NumSelectedHosts", selHosts + 1 );
c.writeEntry( QString("SelectedHost%1").arg(selHosts), host);
c.writeEntry( QString("SelectedBase%1").arg(selHosts), basedn);
c.writeEntry( QString("SelectedPort%1").arg(selHosts), "389");
}
}
};
class CreateCalendarKolabResource : public KConfigPropagator::Change
{
public:
CreateCalendarKolabResource()
: KConfigPropagator::Change( i18n("Create Calendar Kolab Resource") )
{
}
void apply()
{
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
KCal::ResourceKolab *r = new KCal::ResourceKolab( 0 );
r->setResourceName( i18n("Kolab Server") );
r->setName( "kolab-resource" );
m.add( r );
m.setStandardResource( r );
m.writeConfig();
}
};
class CreateContactKolabResource : public KConfigPropagator::Change
{
public:
CreateContactKolabResource()
: KConfigPropagator::Change( i18n("Create Contact Kolab Resource") )
{
}
void apply()
{
KRES::Manager<KABC::Resource> m( "contact" );
m.readConfig();
KABC::ResourceKolab *r = new KABC::ResourceKolab( 0 );
r->setResourceName( i18n("Kolab Server") );
r->setName( "kolab-resource" );
m.add( r );
m.setStandardResource( r );
m.writeConfig();
}
};
class CreateNotesKolabResource : public KConfigPropagator::Change
{
public:
CreateNotesKolabResource()
: KConfigPropagator::Change( i18n("Create Notes Kolab Resource") )
{
}
void apply()
{
KRES::Manager<ResourceNotes> m( "notes" );
m.readConfig();
Kolab::ResourceKolab *r = new Kolab::ResourceKolab( 0 );
r->setResourceName( i18n("Kolab Server") );
r->setName( "kolab-resource" );
m.add( r );
m.setStandardResource( r );
m.writeConfig();
}
};
class KolabPropagator : public KConfigPropagator
{
public:
KolabPropagator()
: KConfigPropagator( KolabConfig::self(), "kolab.kcfg" )
{
}
protected:
void addKorganizerChanges( Change::List &changes )
{
KURL freeBusyBaseUrl = "webdavs://" + KolabConfig::self()->server() +
"/freebusy/";
ChangeConfig *c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyPublishUrl";
c->label = "";
QString user = KolabConfig::self()->user();
// We now use the full email address in the freebusy URL
//int pos = user.find( "@" );
//if ( pos > 0 ) user = user.left( pos );
KURL publishURL = freeBusyBaseUrl;
publishURL.addPath( user + ".ifb" ); // this encodes the '@' in the username
c->value = publishURL.url();
changes.append( c );
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyRetrieveUrl";
c->value = freeBusyBaseUrl.url();
changes.append( c );
// Use full email address for retrieval of free/busy lists
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyFullDomainRetrieval";
c->value = "true";
changes.append( c );
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "Group Scheduling";
c->name = "Use Groupware Communication";
c->value = "true";
changes.append( c );
}
virtual void addCustomChanges( Change::List &changes )
{
addKorganizerChanges( changes );
// KMail cruft has been outsourced to kmailchanges.cpp
createKMailChanges( changes );
changes.append( new SetupLDAPSearchAccount );
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
KCal::CalendarResourceManager::Iterator it;
for ( it = m.begin(); it != m.end(); ++it ) {
if ( (*it)->type() == "kolab" ) break;
}
if ( it == m.end() ) {
changes.append( new CreateCalendarKolabResource );
changes.append( new CreateContactKolabResource );
changes.append( new CreateNotesKolabResource );
}
}
};
KolabWizard::KolabWizard() : KConfigWizard( new KolabPropagator )
{
QFrame *page = createWizardPage( i18n("Kolab Server") );
QGridLayout *topLayout = new QGridLayout( page );
topLayout->setSpacing( spacingHint() );
QLabel *label = new QLabel( i18n("Server name:"), page );
topLayout->addWidget( label, 0, 0 );
mServerEdit = new KLineEdit( page );
topLayout->addWidget( mServerEdit, 0, 1 );
label = new QLabel( i18n("Email address:"), page );
topLayout->addWidget( label, 1, 0 );
mUserEdit = new KLineEdit( page );
topLayout->addWidget( mUserEdit, 1, 1 );
QWhatsThis::add(mUserEdit, i18n("Your email address on the Kolab Server. "
"Format: <i>name@server.domain.tld</i>"));
label = new QLabel( i18n("Real name:"), page );
topLayout->addWidget( label, 2, 0 );
mRealNameEdit = new KLineEdit( page );
topLayout->addWidget( mRealNameEdit, 2, 1 );
label = new QLabel( i18n("Password:"), page );
topLayout->addWidget( label, 3, 0 );
mPasswordEdit = new KLineEdit( page );
mPasswordEdit->setEchoMode( KLineEdit::Password );
topLayout->addWidget( mPasswordEdit, 3, 1 );
mSavePasswordCheck = new QCheckBox( i18n("Save password"), page );
topLayout->addMultiCellWidget( mSavePasswordCheck, 4, 4, 0, 1 );
topLayout->setRowStretch( 4, 1 );
//DF: I don't see the point in showing the user those pages.
//They are very 'internal' and of no use to anyone other than developers.
//(This is even more true for the rules page. The changes page is sort of OK)
//setupRulesPage();
setupChangesPage();
setInitialSize( QSize( 600, 300 ) );
}
KolabWizard::~KolabWizard()
{
}
void KolabWizard::usrReadConfig()
{
mServerEdit->setText( KolabConfig::self()->server() );
mUserEdit->setText( KolabConfig::self()->user() );
mRealNameEdit->setText( KolabConfig::self()->realName() );
mPasswordEdit->setText( KolabConfig::self()->password() );
mSavePasswordCheck->setChecked( KolabConfig::self()->savePassword() );
}
void KolabWizard::usrWriteConfig()
{
KolabConfig::self()->setServer( mServerEdit->text() );
KolabConfig::self()->setUser( mUserEdit->text() );
KolabConfig::self()->setRealName( mRealNameEdit->text() );
KolabConfig::self()->setPassword( mPasswordEdit->text() );
KolabConfig::self()->setSavePassword( mSavePasswordCheck->isChecked() );
}
<commit_msg>Make korganizer use the name and email given in this wizard.<commit_after>/*
This file is part of kdepim.
Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>
Copyright (c) 2004 Daniel Molkentin <molkentin@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include "kolabwizard.h"
#include "kolabconfig.h"
#include "kmailchanges.h"
#include <libkcal/resourcecalendar.h>
#include <kabc/resource.h>
#include "kresources/kolab/kcal/resourcekolab.h"
#include "kresources/kolab/kabc/resourcekolab.h"
#include "kresources/kolab/knotes/resourcekolab.h"
#include <qwhatsthis.h>
#include <klineedit.h>
#include <klocale.h>
#include <qlayout.h>
#include <qcheckbox.h>
#include <qlabel.h>
class SetupLDAPSearchAccount : public KConfigPropagator::Change
{
public:
SetupLDAPSearchAccount()
: KConfigPropagator::Change( i18n("Setup LDAP Search Account") )
{
}
void apply()
{
const QString host = KolabConfig::self()->server();
// Figure out the basedn
QString basedn = host;
// If the user gave a full email address, the domain name
// of that overrides the server name for the ldap dn
const QString user = KolabConfig::self()->user();
int pos = user.find( "@" );
if ( pos > 0 ) {
const QString h = user.mid( pos+1 );
if ( !h.isEmpty() )
// The user did type in a domain on the email address. Use that
basedn = h;
}
basedn.replace(".",",dc=");
basedn.prepend("dc=");
// Set the changes
KConfig c( "kabldaprc" );
c.setGroup( "LDAP" );
bool hasMyServer = false;
uint selHosts = c.readNumEntry("NumSelectedHosts", 0);
for ( uint i = 0 ; i < selHosts && !hasMyServer; ++i )
if ( c.readEntry( QString("SelectedHost%1").arg(i) ) == host )
hasMyServer = true;
if ( !hasMyServer ) {
c.writeEntry( "NumSelectedHosts", selHosts + 1 );
c.writeEntry( QString("SelectedHost%1").arg(selHosts), host);
c.writeEntry( QString("SelectedBase%1").arg(selHosts), basedn);
c.writeEntry( QString("SelectedPort%1").arg(selHosts), "389");
}
}
};
class CreateCalendarKolabResource : public KConfigPropagator::Change
{
public:
CreateCalendarKolabResource()
: KConfigPropagator::Change( i18n("Create Calendar Kolab Resource") )
{
}
void apply()
{
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
KCal::ResourceKolab *r = new KCal::ResourceKolab( 0 );
r->setResourceName( i18n("Kolab Server") );
r->setName( "kolab-resource" );
m.add( r );
m.setStandardResource( r );
m.writeConfig();
}
};
class CreateContactKolabResource : public KConfigPropagator::Change
{
public:
CreateContactKolabResource()
: KConfigPropagator::Change( i18n("Create Contact Kolab Resource") )
{
}
void apply()
{
KRES::Manager<KABC::Resource> m( "contact" );
m.readConfig();
KABC::ResourceKolab *r = new KABC::ResourceKolab( 0 );
r->setResourceName( i18n("Kolab Server") );
r->setName( "kolab-resource" );
m.add( r );
m.setStandardResource( r );
m.writeConfig();
}
};
class CreateNotesKolabResource : public KConfigPropagator::Change
{
public:
CreateNotesKolabResource()
: KConfigPropagator::Change( i18n("Create Notes Kolab Resource") )
{
}
void apply()
{
KRES::Manager<ResourceNotes> m( "notes" );
m.readConfig();
Kolab::ResourceKolab *r = new Kolab::ResourceKolab( 0 );
r->setResourceName( i18n("Kolab Server") );
r->setName( "kolab-resource" );
m.add( r );
m.setStandardResource( r );
m.writeConfig();
}
};
class KolabPropagator : public KConfigPropagator
{
public:
KolabPropagator()
: KConfigPropagator( KolabConfig::self(), "kolab.kcfg" )
{
}
protected:
void addKorganizerChanges( Change::List &changes )
{
KURL freeBusyBaseUrl = "webdavs://" + KolabConfig::self()->server() +
"/freebusy/";
ChangeConfig *c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyPublishUrl";
c->label = "";
QString user = KolabConfig::self()->user();
// We now use the full email address in the freebusy URL
//int pos = user.find( "@" );
//if ( pos > 0 ) user = user.left( pos );
KURL publishURL = freeBusyBaseUrl;
publishURL.addPath( user + ".ifb" ); // this encodes the '@' in the username
c->value = publishURL.url();
changes.append( c );
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyRetrieveUrl";
c->value = freeBusyBaseUrl.url();
changes.append( c );
// Use full email address for retrieval of free/busy lists
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "FreeBusy";
c->name = "FreeBusyFullDomainRetrieval";
c->value = "true";
changes.append( c );
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "Group Scheduling";
c->name = "Use Groupware Communication";
c->value = "true";
changes.append( c );
// Use identity "from control center", i.e. from emaildefaults
c = new ChangeConfig;
c->file = "korganizerrc";
c->group = "Personal Settings";
c->name = "Use Control Center Email";
c->value = "true";
changes.append( c );
}
virtual void addCustomChanges( Change::List &changes )
{
addKorganizerChanges( changes );
// KMail cruft has been outsourced to kmailchanges.cpp
createKMailChanges( changes );
changes.append( new SetupLDAPSearchAccount );
KCal::CalendarResourceManager m( "calendar" );
m.readConfig();
KCal::CalendarResourceManager::Iterator it;
for ( it = m.begin(); it != m.end(); ++it ) {
if ( (*it)->type() == "kolab" ) break;
}
if ( it == m.end() ) {
changes.append( new CreateCalendarKolabResource );
changes.append( new CreateContactKolabResource );
changes.append( new CreateNotesKolabResource );
}
}
};
KolabWizard::KolabWizard() : KConfigWizard( new KolabPropagator )
{
QFrame *page = createWizardPage( i18n("Kolab Server") );
QGridLayout *topLayout = new QGridLayout( page );
topLayout->setSpacing( spacingHint() );
QLabel *label = new QLabel( i18n("Server name:"), page );
topLayout->addWidget( label, 0, 0 );
mServerEdit = new KLineEdit( page );
topLayout->addWidget( mServerEdit, 0, 1 );
label = new QLabel( i18n("Email address:"), page );
topLayout->addWidget( label, 1, 0 );
mUserEdit = new KLineEdit( page );
topLayout->addWidget( mUserEdit, 1, 1 );
QWhatsThis::add(mUserEdit, i18n("Your email address on the Kolab Server. "
"Format: <i>name@server.domain.tld</i>"));
label = new QLabel( i18n("Real name:"), page );
topLayout->addWidget( label, 2, 0 );
mRealNameEdit = new KLineEdit( page );
topLayout->addWidget( mRealNameEdit, 2, 1 );
label = new QLabel( i18n("Password:"), page );
topLayout->addWidget( label, 3, 0 );
mPasswordEdit = new KLineEdit( page );
mPasswordEdit->setEchoMode( KLineEdit::Password );
topLayout->addWidget( mPasswordEdit, 3, 1 );
mSavePasswordCheck = new QCheckBox( i18n("Save password"), page );
topLayout->addMultiCellWidget( mSavePasswordCheck, 4, 4, 0, 1 );
topLayout->setRowStretch( 4, 1 );
//DF: I don't see the point in showing the user those pages.
//They are very 'internal' and of no use to anyone other than developers.
//(This is even more true for the rules page. The changes page is sort of OK)
//setupRulesPage();
setupChangesPage();
setInitialSize( QSize( 600, 300 ) );
}
KolabWizard::~KolabWizard()
{
}
void KolabWizard::usrReadConfig()
{
mServerEdit->setText( KolabConfig::self()->server() );
mUserEdit->setText( KolabConfig::self()->user() );
mRealNameEdit->setText( KolabConfig::self()->realName() );
mPasswordEdit->setText( KolabConfig::self()->password() );
mSavePasswordCheck->setChecked( KolabConfig::self()->savePassword() );
}
void KolabWizard::usrWriteConfig()
{
KolabConfig::self()->setServer( mServerEdit->text() );
KolabConfig::self()->setUser( mUserEdit->text() );
KolabConfig::self()->setRealName( mRealNameEdit->text() );
KolabConfig::self()->setPassword( mPasswordEdit->text() );
KolabConfig::self()->setSavePassword( mSavePasswordCheck->isChecked() );
}
<|endoftext|> |
<commit_before>#include "boost/test/unit_test.hpp"
#include "tuple.h"
#include "marshal.h"
#include "unmarshal.h"
#include "marshalField.h"
#include "unmarshalField.h"
#include "val_str.h"
#include "val_tuple.h"
#include "val_uint64.h"
class testMarshal
{
private:
Marshal m;
Unmarshal u;
MarshalField mF;
UnmarshalField uF;
TuplePtr flat;
public:
testMarshal()
: m("Marshal"),
u("Unmarshal"),
mF("MarshalField", 0),
uF("UnmarshalField", 0)
{
// Create a straight tuple
// The input tuple
flat = Tuple::mk();
flat->append(Val_Str::mk("String"));
flat->append(Val_UInt64::mk(13500975));
flat->freeze();
}
void
testM()
{
// Marshal it
TuplePtr result = m.simple_action(flat);
BOOST_REQUIRE_MESSAGE(result != NULL, "Didn't get a marshaling result");
BOOST_CHECK_MESSAGE(result->size() == 1, "Marshalled tuple has size != 1\n");
BOOST_CHECK_MESSAGE((*result)[0]->typeCode() == Value::OPAQUE,
"Marshalled field is not OPAQUE 1\n");
}
void
testU()
{
// Marshal it and unmarshal it
TuplePtr result = m.simple_action(flat);
TuplePtr reFlat = u.simple_action(result);
BOOST_REQUIRE_MESSAGE(reFlat != NULL, "Didn't get a unmarshaling result");
BOOST_CHECK_MESSAGE(reFlat->size() == flat->size(),
"Marshalled/unmarshalled tuple is different size");
BOOST_CHECK_MESSAGE(reFlat->compareTo(flat) == 0,
"Marshalled/unmarshalled tuple does not match original");
}
};
class testMarshal_testSuite
: public boost::unit_test_framework::test_suite
{
public:
testMarshal_testSuite()
: boost::unit_test_framework::test_suite("testMarshal: Marshaling/Unmarshaling")
{
boost::shared_ptr<testMarshal> instance(new testMarshal());
add(BOOST_CLASS_TEST_CASE(&testMarshal::testM, instance));
add(BOOST_CLASS_TEST_CASE(&testMarshal::testU, instance));
}
};
<commit_msg>Added elementary marshalField and unmarshalField test cases<commit_after>#include "boost/test/unit_test.hpp"
#include "tuple.h"
#include "marshal.h"
#include "unmarshal.h"
#include "marshalField.h"
#include "unmarshalField.h"
#include "val_str.h"
#include "val_tuple.h"
#include "val_uint64.h"
class testMarshal
{
private:
Marshal m;
Unmarshal u;
MarshalField mF;
UnmarshalField uF;
TuplePtr flat;
TuplePtr nested;
public:
testMarshal()
: m("Marshal"),
u("Unmarshal"),
mF("MarshalField", 1),
uF("UnmarshalField", 1)
{
// Create a straight tuple
// The input tuple
flat = Tuple::mk();
flat->append(Val_Str::mk("Flat"));
flat->append(Val_UInt64::mk(13500975));
flat->freeze();
// Create a nested tuple
nested = Tuple::mk();
nested->append(Val_Str::mk("Nested"));
nested->append(Val_Tuple::mk(flat));
nested->freeze();
}
void
testM()
{
// Marshal it
TuplePtr result = m.simple_action(flat);
BOOST_REQUIRE_MESSAGE(result != NULL, "Didn't get a marshaling result");
BOOST_CHECK_MESSAGE(result->size() == 1, "Marshalled tuple has size != 1\n");
BOOST_CHECK_MESSAGE((*result)[0]->typeCode() == Value::OPAQUE,
"Marshalled field is not OPAQUE 1\n");
}
void
testU()
{
// Marshal it and unmarshal it
TuplePtr result = m.simple_action(flat);
TuplePtr reFlat = u.simple_action(result);
BOOST_REQUIRE_MESSAGE(reFlat != NULL, "Didn't get an unmarshaling result");
BOOST_CHECK_MESSAGE(reFlat->size() == flat->size(),
"Marshalled/unmarshalled tuple is different size");
BOOST_CHECK_MESSAGE(reFlat->compareTo(flat) == 0,
"Marshalled/unmarshalled tuple does not match original");
}
void
testMF()
{
// Marshal it
TuplePtr result = mF.simple_action(nested);
BOOST_REQUIRE_MESSAGE(result != NULL, "Didn't get a field marshaling result");
BOOST_CHECK_MESSAGE(result->size() == 2, "Outer tuple has wrong size\n");
BOOST_CHECK_MESSAGE((*result)[1]->typeCode() == Value::OPAQUE,
"Marshalled field is not OPAQUE 1\n");
}
void
testUF()
{
// Marshal it and unmarshal it
TuplePtr result = mF.simple_action(nested);
TuplePtr reNested = uF.simple_action(result);
BOOST_REQUIRE_MESSAGE(reNested != NULL, "Didn't get a field unmarshaling result");
BOOST_CHECK_MESSAGE(reNested->size() == nested->size(),
"Field marshalled/unmarshalled tuple is different size");
BOOST_CHECK_MESSAGE(reNested->compareTo(nested) == 0,
"Field marshalled/unmarshalled tuple does not match original");
}
};
class testMarshal_testSuite
: public boost::unit_test_framework::test_suite
{
public:
testMarshal_testSuite()
: boost::unit_test_framework::test_suite("testMarshal: Marshaling/Unmarshaling")
{
boost::shared_ptr<testMarshal> instance(new testMarshal());
add(BOOST_CLASS_TEST_CASE(&testMarshal::testM, instance));
add(BOOST_CLASS_TEST_CASE(&testMarshal::testU, instance));
add(BOOST_CLASS_TEST_CASE(&testMarshal::testMF, instance));
add(BOOST_CLASS_TEST_CASE(&testMarshal::testUF, instance));
}
};
<|endoftext|> |
<commit_before>//==- DeadStoresChecker.cpp - Check for stores to dead variables -*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a DeadStores, a flow-sensitive checker that looks for
// stores to variables that are no longer live.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/Analysis/Analyses/LiveVariables.h"
#include "clang/Analysis/Visitors/CFGRecStmtVisitor.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace clang;
using namespace ento;
namespace {
/// A simple visitor to record what VarDecls occur in EH-handling code.
class EHCodeVisitor : public RecursiveASTVisitor<EHCodeVisitor> {
public:
bool inEH;
llvm::DenseSet<const VarDecl *> &S;
bool TraverseObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
SaveAndRestore<bool> inFinally(inEH, true);
return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
}
bool TraverseObjCAtCatchStmt(ObjCAtCatchStmt *S) {
SaveAndRestore<bool> inCatch(inEH, true);
return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
}
bool TraverseCXXCatchStmt(CXXCatchStmt *S) {
SaveAndRestore<bool> inCatch(inEH, true);
return TraverseStmt(S->getHandlerBlock());
}
bool VisitDeclRefExpr(DeclRefExpr *DR) {
if (inEH)
if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
S.insert(D);
return true;
}
EHCodeVisitor(llvm::DenseSet<const VarDecl *> &S) :
inEH(false), S(S) {}
};
// FIXME: Eventually migrate into its own file, and have it managed by
// AnalysisManager.
class ReachableCode {
const CFG &cfg;
llvm::BitVector reachable;
public:
ReachableCode(const CFG &cfg)
: cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {}
void computeReachableBlocks();
bool isReachable(const CFGBlock *block) const {
return reachable[block->getBlockID()];
}
};
}
void ReachableCode::computeReachableBlocks() {
if (!cfg.getNumBlockIDs())
return;
SmallVector<const CFGBlock*, 10> worklist;
worklist.push_back(&cfg.getEntry());
while (!worklist.empty()) {
const CFGBlock *block = worklist.back();
worklist.pop_back();
llvm::BitVector::reference isReachable = reachable[block->getBlockID()];
if (isReachable)
continue;
isReachable = true;
for (CFGBlock::const_succ_iterator i = block->succ_begin(),
e = block->succ_end(); i != e; ++i)
if (const CFGBlock *succ = *i)
worklist.push_back(succ);
}
}
static const Expr *LookThroughTransitiveAssignments(const Expr *Ex) {
while (Ex) {
const BinaryOperator *BO =
dyn_cast<BinaryOperator>(Ex->IgnoreParenCasts());
if (!BO)
break;
if (BO->getOpcode() == BO_Assign) {
Ex = BO->getRHS();
continue;
}
break;
}
return Ex;
}
namespace {
class DeadStoreObs : public LiveVariables::Observer {
const CFG &cfg;
ASTContext &Ctx;
BugReporter& BR;
AnalysisDeclContext* AC;
ParentMap& Parents;
llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
OwningPtr<ReachableCode> reachableCode;
const CFGBlock *currentBlock;
llvm::OwningPtr<llvm::DenseSet<const VarDecl *> > InEH;
enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
public:
DeadStoreObs(const CFG &cfg, ASTContext &ctx,
BugReporter& br, AnalysisDeclContext* ac, ParentMap& parents,
llvm::SmallPtrSet<const VarDecl*, 20> &escaped)
: cfg(cfg), Ctx(ctx), BR(br), AC(ac), Parents(parents),
Escaped(escaped), currentBlock(0) {}
virtual ~DeadStoreObs() {}
bool isLive(const LiveVariables::LivenessValues &Live, const VarDecl *D) {
if (Live.isLive(D))
return true;
// Lazily construct the set that records which VarDecls are in
// EH code.
if (!InEH.get()) {
InEH.reset(new llvm::DenseSet<const VarDecl *>());
EHCodeVisitor V(*InEH.get());
V.TraverseStmt(AC->getBody());
}
// Treat all VarDecls that occur in EH code as being "always live"
// when considering to suppress dead stores. Frequently stores
// are followed by reads in EH code, but we don't have the ability
// to analyze that yet.
return InEH->count(D);
}
void Report(const VarDecl *V, DeadStoreKind dsk,
PathDiagnosticLocation L, SourceRange R) {
if (Escaped.count(V))
return;
// Compute reachable blocks within the CFG for trivial cases
// where a bogus dead store can be reported because itself is unreachable.
if (!reachableCode.get()) {
reachableCode.reset(new ReachableCode(cfg));
reachableCode->computeReachableBlocks();
}
if (!reachableCode->isReachable(currentBlock))
return;
SmallString<64> buf;
llvm::raw_svector_ostream os(buf);
const char *BugType = 0;
switch (dsk) {
case DeadInit:
BugType = "Dead initialization";
os << "Value stored to '" << *V
<< "' during its initialization is never read";
break;
case DeadIncrement:
BugType = "Dead increment";
case Standard:
if (!BugType) BugType = "Dead assignment";
os << "Value stored to '" << *V << "' is never read";
break;
case Enclosing:
// Don't report issues in this case, e.g.: "if (x = foo())",
// where 'x' is unused later. We have yet to see a case where
// this is a real bug.
return;
}
BR.EmitBasicReport(AC->getDecl(), BugType, "Dead store", os.str(), L, R);
}
void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val,
DeadStoreKind dsk,
const LiveVariables::LivenessValues &Live) {
if (!VD->hasLocalStorage())
return;
// Reference types confuse the dead stores checker. Skip them
// for now.
if (VD->getType()->getAs<ReferenceType>())
return;
if (!isLive(Live, VD) &&
!(VD->getAttr<UnusedAttr>() || VD->getAttr<BlocksAttr>())) {
PathDiagnosticLocation ExLoc =
PathDiagnosticLocation::createBegin(Ex, BR.getSourceManager(), AC);
Report(VD, dsk, ExLoc, Val->getSourceRange());
}
}
void CheckDeclRef(const DeclRefExpr *DR, const Expr *Val, DeadStoreKind dsk,
const LiveVariables::LivenessValues& Live) {
if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
CheckVarDecl(VD, DR, Val, dsk, Live);
}
bool isIncrement(VarDecl *VD, const BinaryOperator* B) {
if (B->isCompoundAssignmentOp())
return true;
const Expr *RHS = B->getRHS()->IgnoreParenCasts();
const BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS);
if (!BRHS)
return false;
const DeclRefExpr *DR;
if ((DR = dyn_cast<DeclRefExpr>(BRHS->getLHS()->IgnoreParenCasts())))
if (DR->getDecl() == VD)
return true;
if ((DR = dyn_cast<DeclRefExpr>(BRHS->getRHS()->IgnoreParenCasts())))
if (DR->getDecl() == VD)
return true;
return false;
}
virtual void observeStmt(const Stmt *S, const CFGBlock *block,
const LiveVariables::LivenessValues &Live) {
currentBlock = block;
// Skip statements in macros.
if (S->getLocStart().isMacroID())
return;
// Only cover dead stores from regular assignments. ++/-- dead stores
// have never flagged a real bug.
if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
if (!B->isAssignmentOp()) return; // Skip non-assignments.
if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS()))
if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
// Special case: check for assigning null to a pointer.
// This is a common form of defensive programming.
const Expr *RHS = LookThroughTransitiveAssignments(B->getRHS());
QualType T = VD->getType();
if (T->isPointerType() || T->isObjCObjectPointerType()) {
if (RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull))
return;
}
RHS = RHS->IgnoreParenCasts();
// Special case: self-assignments. These are often used to shut up
// "unused variable" compiler warnings.
if (const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
return;
// Otherwise, issue a warning.
DeadStoreKind dsk = Parents.isConsumedExpr(B)
? Enclosing
: (isIncrement(VD,B) ? DeadIncrement : Standard);
CheckVarDecl(VD, DR, B->getRHS(), dsk, Live);
}
}
else if (const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
if (!U->isIncrementOp() || U->isPrefix())
return;
const Stmt *parent = Parents.getParentIgnoreParenCasts(U);
if (!parent || !isa<ReturnStmt>(parent))
return;
const Expr *Ex = U->getSubExpr()->IgnoreParenCasts();
if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
CheckDeclRef(DR, U, DeadIncrement, Live);
}
else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S))
// Iterate through the decls. Warn if any initializers are complex
// expressions that are not live (never used).
for (DeclStmt::const_decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
DI != DE; ++DI) {
VarDecl *V = dyn_cast<VarDecl>(*DI);
if (!V)
continue;
if (V->hasLocalStorage()) {
// Reference types confuse the dead stores checker. Skip them
// for now.
if (V->getType()->getAs<ReferenceType>())
return;
if (const Expr *E = V->getInit()) {
while (const ExprWithCleanups *exprClean =
dyn_cast<ExprWithCleanups>(E))
E = exprClean->getSubExpr();
// Look through transitive assignments, e.g.:
// int x = y = 0;
E = LookThroughTransitiveAssignments(E);
// Don't warn on C++ objects (yet) until we can show that their
// constructors/destructors don't have side effects.
if (isa<CXXConstructExpr>(E))
return;
// A dead initialization is a variable that is dead after it
// is initialized. We don't flag warnings for those variables
// marked 'unused'.
if (!isLive(Live, V) && V->getAttr<UnusedAttr>() == 0) {
// Special case: check for initializations with constants.
//
// e.g. : int x = 0;
//
// If x is EVER assigned a new value later, don't issue
// a warning. This is because such initialization can be
// due to defensive programming.
if (E->isEvaluatable(Ctx))
return;
if (const DeclRefExpr *DRE =
dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
// Special case: check for initialization from constant
// variables.
//
// e.g. extern const int MyConstant;
// int x = MyConstant;
//
if (VD->hasGlobalStorage() &&
VD->getType().isConstQualified())
return;
// Special case: check for initialization from scalar
// parameters. This is often a form of defensive
// programming. Non-scalars are still an error since
// because it more likely represents an actual algorithmic
// bug.
if (isa<ParmVarDecl>(VD) && VD->getType()->isScalarType())
return;
}
PathDiagnosticLocation Loc =
PathDiagnosticLocation::create(V, BR.getSourceManager());
Report(V, DeadInit, Loc, E->getSourceRange());
}
}
}
}
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Driver function to invoke the Dead-Stores checker on a CFG.
//===----------------------------------------------------------------------===//
namespace {
class FindEscaped : public CFGRecStmtDeclVisitor<FindEscaped>{
CFG *cfg;
public:
FindEscaped(CFG *c) : cfg(c) {}
CFG& getCFG() { return *cfg; }
llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
void VisitUnaryOperator(UnaryOperator* U) {
// Check for '&'. Any VarDecl whose value has its address-taken we
// treat as escaped.
Expr *E = U->getSubExpr()->IgnoreParenCasts();
if (U->getOpcode() == UO_AddrOf)
if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
Escaped.insert(VD);
return;
}
Visit(E);
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// DeadStoresChecker
//===----------------------------------------------------------------------===//
namespace {
class DeadStoresChecker : public Checker<check::ASTCodeBody> {
public:
void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
BugReporter &BR) const {
if (LiveVariables *L = mgr.getAnalysis<LiveVariables>(D)) {
CFG &cfg = *mgr.getCFG(D);
AnalysisDeclContext *AC = mgr.getAnalysisDeclContext(D);
ParentMap &pmap = mgr.getParentMap(D);
FindEscaped FS(&cfg);
FS.getCFG().VisitBlockStmts(FS);
DeadStoreObs A(cfg, BR.getContext(), BR, AC, pmap, FS.Escaped);
L->runOnAllBlocks(A);
}
}
};
}
void ento::registerDeadStoresChecker(CheckerManager &mgr) {
mgr.registerChecker<DeadStoresChecker>();
}
<commit_msg>Trim #includes.<commit_after>//==- DeadStoresChecker.cpp - Check for stores to dead variables -*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a DeadStores, a flow-sensitive checker that looks for
// stores to variables that are no longer live.
//
//===----------------------------------------------------------------------===//
#include "ClangSACheckers.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Analysis/Analyses/LiveVariables.h"
#include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace clang;
using namespace ento;
namespace {
/// A simple visitor to record what VarDecls occur in EH-handling code.
class EHCodeVisitor : public RecursiveASTVisitor<EHCodeVisitor> {
public:
bool inEH;
llvm::DenseSet<const VarDecl *> &S;
bool TraverseObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
SaveAndRestore<bool> inFinally(inEH, true);
return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtFinallyStmt(S);
}
bool TraverseObjCAtCatchStmt(ObjCAtCatchStmt *S) {
SaveAndRestore<bool> inCatch(inEH, true);
return ::RecursiveASTVisitor<EHCodeVisitor>::TraverseObjCAtCatchStmt(S);
}
bool TraverseCXXCatchStmt(CXXCatchStmt *S) {
SaveAndRestore<bool> inCatch(inEH, true);
return TraverseStmt(S->getHandlerBlock());
}
bool VisitDeclRefExpr(DeclRefExpr *DR) {
if (inEH)
if (const VarDecl *D = dyn_cast<VarDecl>(DR->getDecl()))
S.insert(D);
return true;
}
EHCodeVisitor(llvm::DenseSet<const VarDecl *> &S) :
inEH(false), S(S) {}
};
// FIXME: Eventually migrate into its own file, and have it managed by
// AnalysisManager.
class ReachableCode {
const CFG &cfg;
llvm::BitVector reachable;
public:
ReachableCode(const CFG &cfg)
: cfg(cfg), reachable(cfg.getNumBlockIDs(), false) {}
void computeReachableBlocks();
bool isReachable(const CFGBlock *block) const {
return reachable[block->getBlockID()];
}
};
}
void ReachableCode::computeReachableBlocks() {
if (!cfg.getNumBlockIDs())
return;
SmallVector<const CFGBlock*, 10> worklist;
worklist.push_back(&cfg.getEntry());
while (!worklist.empty()) {
const CFGBlock *block = worklist.back();
worklist.pop_back();
llvm::BitVector::reference isReachable = reachable[block->getBlockID()];
if (isReachable)
continue;
isReachable = true;
for (CFGBlock::const_succ_iterator i = block->succ_begin(),
e = block->succ_end(); i != e; ++i)
if (const CFGBlock *succ = *i)
worklist.push_back(succ);
}
}
static const Expr *LookThroughTransitiveAssignments(const Expr *Ex) {
while (Ex) {
const BinaryOperator *BO =
dyn_cast<BinaryOperator>(Ex->IgnoreParenCasts());
if (!BO)
break;
if (BO->getOpcode() == BO_Assign) {
Ex = BO->getRHS();
continue;
}
break;
}
return Ex;
}
namespace {
class DeadStoreObs : public LiveVariables::Observer {
const CFG &cfg;
ASTContext &Ctx;
BugReporter& BR;
AnalysisDeclContext* AC;
ParentMap& Parents;
llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
OwningPtr<ReachableCode> reachableCode;
const CFGBlock *currentBlock;
llvm::OwningPtr<llvm::DenseSet<const VarDecl *> > InEH;
enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };
public:
DeadStoreObs(const CFG &cfg, ASTContext &ctx,
BugReporter& br, AnalysisDeclContext* ac, ParentMap& parents,
llvm::SmallPtrSet<const VarDecl*, 20> &escaped)
: cfg(cfg), Ctx(ctx), BR(br), AC(ac), Parents(parents),
Escaped(escaped), currentBlock(0) {}
virtual ~DeadStoreObs() {}
bool isLive(const LiveVariables::LivenessValues &Live, const VarDecl *D) {
if (Live.isLive(D))
return true;
// Lazily construct the set that records which VarDecls are in
// EH code.
if (!InEH.get()) {
InEH.reset(new llvm::DenseSet<const VarDecl *>());
EHCodeVisitor V(*InEH.get());
V.TraverseStmt(AC->getBody());
}
// Treat all VarDecls that occur in EH code as being "always live"
// when considering to suppress dead stores. Frequently stores
// are followed by reads in EH code, but we don't have the ability
// to analyze that yet.
return InEH->count(D);
}
void Report(const VarDecl *V, DeadStoreKind dsk,
PathDiagnosticLocation L, SourceRange R) {
if (Escaped.count(V))
return;
// Compute reachable blocks within the CFG for trivial cases
// where a bogus dead store can be reported because itself is unreachable.
if (!reachableCode.get()) {
reachableCode.reset(new ReachableCode(cfg));
reachableCode->computeReachableBlocks();
}
if (!reachableCode->isReachable(currentBlock))
return;
SmallString<64> buf;
llvm::raw_svector_ostream os(buf);
const char *BugType = 0;
switch (dsk) {
case DeadInit:
BugType = "Dead initialization";
os << "Value stored to '" << *V
<< "' during its initialization is never read";
break;
case DeadIncrement:
BugType = "Dead increment";
case Standard:
if (!BugType) BugType = "Dead assignment";
os << "Value stored to '" << *V << "' is never read";
break;
case Enclosing:
// Don't report issues in this case, e.g.: "if (x = foo())",
// where 'x' is unused later. We have yet to see a case where
// this is a real bug.
return;
}
BR.EmitBasicReport(AC->getDecl(), BugType, "Dead store", os.str(), L, R);
}
void CheckVarDecl(const VarDecl *VD, const Expr *Ex, const Expr *Val,
DeadStoreKind dsk,
const LiveVariables::LivenessValues &Live) {
if (!VD->hasLocalStorage())
return;
// Reference types confuse the dead stores checker. Skip them
// for now.
if (VD->getType()->getAs<ReferenceType>())
return;
if (!isLive(Live, VD) &&
!(VD->getAttr<UnusedAttr>() || VD->getAttr<BlocksAttr>())) {
PathDiagnosticLocation ExLoc =
PathDiagnosticLocation::createBegin(Ex, BR.getSourceManager(), AC);
Report(VD, dsk, ExLoc, Val->getSourceRange());
}
}
void CheckDeclRef(const DeclRefExpr *DR, const Expr *Val, DeadStoreKind dsk,
const LiveVariables::LivenessValues& Live) {
if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
CheckVarDecl(VD, DR, Val, dsk, Live);
}
bool isIncrement(VarDecl *VD, const BinaryOperator* B) {
if (B->isCompoundAssignmentOp())
return true;
const Expr *RHS = B->getRHS()->IgnoreParenCasts();
const BinaryOperator* BRHS = dyn_cast<BinaryOperator>(RHS);
if (!BRHS)
return false;
const DeclRefExpr *DR;
if ((DR = dyn_cast<DeclRefExpr>(BRHS->getLHS()->IgnoreParenCasts())))
if (DR->getDecl() == VD)
return true;
if ((DR = dyn_cast<DeclRefExpr>(BRHS->getRHS()->IgnoreParenCasts())))
if (DR->getDecl() == VD)
return true;
return false;
}
virtual void observeStmt(const Stmt *S, const CFGBlock *block,
const LiveVariables::LivenessValues &Live) {
currentBlock = block;
// Skip statements in macros.
if (S->getLocStart().isMacroID())
return;
// Only cover dead stores from regular assignments. ++/-- dead stores
// have never flagged a real bug.
if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
if (!B->isAssignmentOp()) return; // Skip non-assignments.
if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS()))
if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
// Special case: check for assigning null to a pointer.
// This is a common form of defensive programming.
const Expr *RHS = LookThroughTransitiveAssignments(B->getRHS());
QualType T = VD->getType();
if (T->isPointerType() || T->isObjCObjectPointerType()) {
if (RHS->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNull))
return;
}
RHS = RHS->IgnoreParenCasts();
// Special case: self-assignments. These are often used to shut up
// "unused variable" compiler warnings.
if (const DeclRefExpr *RhsDR = dyn_cast<DeclRefExpr>(RHS))
if (VD == dyn_cast<VarDecl>(RhsDR->getDecl()))
return;
// Otherwise, issue a warning.
DeadStoreKind dsk = Parents.isConsumedExpr(B)
? Enclosing
: (isIncrement(VD,B) ? DeadIncrement : Standard);
CheckVarDecl(VD, DR, B->getRHS(), dsk, Live);
}
}
else if (const UnaryOperator* U = dyn_cast<UnaryOperator>(S)) {
if (!U->isIncrementOp() || U->isPrefix())
return;
const Stmt *parent = Parents.getParentIgnoreParenCasts(U);
if (!parent || !isa<ReturnStmt>(parent))
return;
const Expr *Ex = U->getSubExpr()->IgnoreParenCasts();
if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Ex))
CheckDeclRef(DR, U, DeadIncrement, Live);
}
else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S))
// Iterate through the decls. Warn if any initializers are complex
// expressions that are not live (never used).
for (DeclStmt::const_decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
DI != DE; ++DI) {
VarDecl *V = dyn_cast<VarDecl>(*DI);
if (!V)
continue;
if (V->hasLocalStorage()) {
// Reference types confuse the dead stores checker. Skip them
// for now.
if (V->getType()->getAs<ReferenceType>())
return;
if (const Expr *E = V->getInit()) {
while (const ExprWithCleanups *exprClean =
dyn_cast<ExprWithCleanups>(E))
E = exprClean->getSubExpr();
// Look through transitive assignments, e.g.:
// int x = y = 0;
E = LookThroughTransitiveAssignments(E);
// Don't warn on C++ objects (yet) until we can show that their
// constructors/destructors don't have side effects.
if (isa<CXXConstructExpr>(E))
return;
// A dead initialization is a variable that is dead after it
// is initialized. We don't flag warnings for those variables
// marked 'unused'.
if (!isLive(Live, V) && V->getAttr<UnusedAttr>() == 0) {
// Special case: check for initializations with constants.
//
// e.g. : int x = 0;
//
// If x is EVER assigned a new value later, don't issue
// a warning. This is because such initialization can be
// due to defensive programming.
if (E->isEvaluatable(Ctx))
return;
if (const DeclRefExpr *DRE =
dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
// Special case: check for initialization from constant
// variables.
//
// e.g. extern const int MyConstant;
// int x = MyConstant;
//
if (VD->hasGlobalStorage() &&
VD->getType().isConstQualified())
return;
// Special case: check for initialization from scalar
// parameters. This is often a form of defensive
// programming. Non-scalars are still an error since
// because it more likely represents an actual algorithmic
// bug.
if (isa<ParmVarDecl>(VD) && VD->getType()->isScalarType())
return;
}
PathDiagnosticLocation Loc =
PathDiagnosticLocation::create(V, BR.getSourceManager());
Report(V, DeadInit, Loc, E->getSourceRange());
}
}
}
}
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Driver function to invoke the Dead-Stores checker on a CFG.
//===----------------------------------------------------------------------===//
namespace {
class FindEscaped : public CFGRecStmtDeclVisitor<FindEscaped>{
CFG *cfg;
public:
FindEscaped(CFG *c) : cfg(c) {}
CFG& getCFG() { return *cfg; }
llvm::SmallPtrSet<const VarDecl*, 20> Escaped;
void VisitUnaryOperator(UnaryOperator* U) {
// Check for '&'. Any VarDecl whose value has its address-taken we
// treat as escaped.
Expr *E = U->getSubExpr()->IgnoreParenCasts();
if (U->getOpcode() == UO_AddrOf)
if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
if (VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
Escaped.insert(VD);
return;
}
Visit(E);
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// DeadStoresChecker
//===----------------------------------------------------------------------===//
namespace {
class DeadStoresChecker : public Checker<check::ASTCodeBody> {
public:
void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
BugReporter &BR) const {
if (LiveVariables *L = mgr.getAnalysis<LiveVariables>(D)) {
CFG &cfg = *mgr.getCFG(D);
AnalysisDeclContext *AC = mgr.getAnalysisDeclContext(D);
ParentMap &pmap = mgr.getParentMap(D);
FindEscaped FS(&cfg);
FS.getCFG().VisitBlockStmts(FS);
DeadStoreObs A(cfg, BR.getContext(), BR, AC, pmap, FS.Escaped);
L->runOnAllBlocks(A);
}
}
};
}
void ento::registerDeadStoresChecker(CheckerManager &mgr) {
mgr.registerChecker<DeadStoresChecker>();
}
<|endoftext|> |
<commit_before><commit_msg>Try to fix compile errors on gcc8<commit_after><|endoftext|> |
<commit_before>// @(#)root/base:$Name: $:$Id: TObject.cxx,v 1.61 2004/06/04 16:28:30 brun Exp $
// Author: Maarten Ballintijn 21/06/2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TParameter<AParamType> //
// //
// Named parameter, streamable and storable. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TParameter.h"
// explicit template instantiation of the versions specified in LinkDef.h
template class TParameter<Double_t>;
template class TParameter<Long_t>;
templateClassImp(TParameter)
<commit_msg>explicit instantiation not needed, types are already instantiated in the dictionary.<commit_after>// @(#)root/base:$Name: $:$Id: TParameter.cxx,v 1.1 2004/06/25 17:27:09 rdm Exp $
// Author: Maarten Ballintijn 21/06/2004
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TParameter<AParamType> //
// //
// Named parameter, streamable and storable. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TParameter.h"
templateClassImp(TParameter)
<|endoftext|> |
<commit_before>// @(#)root/cont:$Name: $:$Id: TProcessID.cxx,v 1.16 2002/07/13 16:19:26 brun Exp $
// Author: Rene Brun 28/09/2001
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// TProcessID
//
// A TProcessID identifies a ROOT job in a unique way in time and space.
// The TProcessID title consists of a TUUID object which provides a globally
// unique identifier (for more see TUUID.h).
//
// A TProcessID is automatically created by the TROOT constructor.
// When a TFile contains referenced objects (see TRef), the TProcessID
// object is written to the file.
// If a file has been written in multiple sessions (same machine or not),
// a TProcessID is written for each session.
// These objects are used by the class TRef to uniquely identified
// any TObject pointed by a TRef.
//
// When a referenced object is read from a file (its bit kIsReferenced is set),
// this object is entered into the objects table of the corresponding TProcessID.
// Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also
// accessible via TProcessID::fgPIDs (for all files).
// When this object is deleted, it is removed from the table via the cleanup
// mechanism invoked by the TObject destructor.
//
// Each TProcessID has a table (TObjArray *fObjects) that keeps track
// of all referenced objects. If a referenced object has a fUniqueID set,
// a pointer to this unique object may be found via fObjects->At(fUniqueID).
// In the same way, when a TRef::GetObject is called, GetObject uses
// its own fUniqueID to find the pointer to the referenced object.
// See TProcessID::GetObjectWithID and PutObjectWithID.
//
// When a referenced object is deleted, its slot in fObjects is set to null.
//
// See also TProcessUUID: a specialized TProcessID to manage the single list
// of TUUIDs.
//
//////////////////////////////////////////////////////////////////////////
#include "TProcessID.h"
#include "TROOT.h"
#include "TFile.h"
#include "TObjArray.h"
TObjArray *TProcessID::fgPIDs = 0; //pointer to the list of TProcessID
TProcessID *TProcessID::fgPID = 0; //pointer to the TProcessID of the current session
UInt_t TProcessID::fgNumber = 0; //Current referenced object instance count
ClassImp(TProcessID)
//______________________________________________________________________________
TProcessID::TProcessID()
{
fCount = 0;
fObjects = 0;
}
//______________________________________________________________________________
TProcessID::~TProcessID()
{
delete fObjects;
fObjects = 0;
fgPIDs->Remove(this);
}
//______________________________________________________________________________
TProcessID::TProcessID(const TProcessID &ref) : TNamed(ref)
{
// TProcessID copy ctor.
}
//______________________________________________________________________________
TProcessID *TProcessID::AddProcessID()
{
// static function to add a new TProcessID to the list of PIDs
TProcessID *pid = new TProcessID();
if (!fgPIDs) {
fgPID = pid;
fgPIDs = new TObjArray(10);
gROOT->GetListOfCleanups()->Add(fgPIDs);
}
UShort_t apid = fgPIDs->GetEntriesFast();
pid->IncrementCount();
fgPIDs->Add(pid);
char name[20];
sprintf(name,"ProcessID%d",apid);
pid->SetName(name);
TUUID u;
apid = fgPIDs->GetEntriesFast();
pid->SetTitle(u.AsString());
return pid;
}
//______________________________________________________________________________
UInt_t TProcessID::AssignID(TObject *obj)
{
// static function returning the ID assigned to obj
// If the object is not yet referenced, its kIsReferenced bit is set
// and its fUniqueID set to the current number of referenced objects so far.
UInt_t uid = obj->GetUniqueID() & 0xffffff;
if (obj == fgPID->GetObjectWithID(uid)) return uid;
if (obj->TestBit(kIsReferenced)) {
fgPID->PutObjectWithID(obj,uid);
return uid;
}
fgNumber++;
obj->SetBit(kIsReferenced);
uid = fgNumber;
obj->SetUniqueID(uid);
fgPID->PutObjectWithID(obj,uid);
return uid;
}
//______________________________________________________________________________
void TProcessID::Cleanup()
{
// static function (called by TROOT destructor) to delete all TProcessIDs
fgPIDs->Delete();
gROOT->GetListOfCleanups()->Remove(fgPIDs);
delete fgPIDs;
}
//______________________________________________________________________________
Int_t TProcessID::DecrementCount()
{
// the reference fCount is used to delete the TProcessID
// in the TFile destructor when fCount = 0
fCount--;
if (fCount < 0) fCount = 0;
return fCount;
}
//______________________________________________________________________________
TProcessID *TProcessID::GetProcessID(UShort_t pid)
{
// static function returning a pointer to TProcessID number pid in fgPIDs
return (TProcessID*)fgPIDs->At(pid);
}
//______________________________________________________________________________
TProcessID *TProcessID::GetProcessWithUID(UInt_t uid)
{
// static function returning a pointer to TProcessID with its pid
// encoded in the highest byte of uid
Int_t pid = (uid>>24)&0xff;
return (TProcessID*)fgPIDs->At(pid);
}
//______________________________________________________________________________
TProcessID *TProcessID::GetSessionProcessID()
{
// static function returning the pointer to the session TProcessID
return fgPID;
}
//______________________________________________________________________________
Int_t TProcessID::IncrementCount()
{
if (!fObjects) fObjects = new TObjArray(100);
fCount++;
return fCount;
}
//______________________________________________________________________________
UInt_t TProcessID::GetObjectCount()
{
// Return the current referenced object count
// fgNumber is incremented everytime a new object is referenced
return fgNumber;
}
//______________________________________________________________________________
TObject *TProcessID::GetObjectWithID(UInt_t uidd)
{
//returns the TObject with unique identifier uid in the table of objects
//if (!fObjects) fObjects = new TObjArray(100);
Int_t uid = uidd & 0xffffff; //take only the 24 lower bits
if (uid >= fObjects->GetSize()) return 0;
return fObjects->UncheckedAt(uid);
}
//______________________________________________________________________________
void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)
{
//stores the object at the uid th slot in the table of objects
//The object uniqueid is set as well as its kMustCleanup bit
//if (!fObjects) fObjects = new TObjArray(100);
if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;
fObjects->AddAtAndExpand(obj,uid);
obj->SetBit(kMustCleanup);
}
//______________________________________________________________________________
TProcessID *TProcessID::ReadProcessID(UShort_t pidf, TFile *file)
{
// static function
//The TProcessID with number pidf is read from file.
//If the object is not already entered in the gROOT list, it is added.
if (!file) return 0;
TObjArray *pids = file->GetListOfProcessIDs();
TProcessID *pid = 0;
if (pidf < pids->GetSize()) pid = (TProcessID *)pids->UncheckedAt(pidf);
if (pid) return pid;
//check if fProcessIDs[uid] is set in file
//if not set, read the process uid from file
char pidname[32];
sprintf(pidname,"ProcessID%d",pidf);
TDirectory *dirsav = gDirectory;
file->cd();
pid = (TProcessID *)file->Get(pidname);
if (dirsav) dirsav->cd();
if (gDebug > 0) {
printf("ReadProcessID, name=%s, file=%s, pid=%lx\n",pidname,file->GetName(),(Long_t)pid);
}
if (!pid) {
//file->Error("ReadProcessID","Cannot find %s in file %s",pidname,file->GetName());
return 0;
}
//check that a similar pid is not already registered in fgPIDs
TIter next(fgPIDs);
TProcessID *p;
while ((p = (TProcessID*)next())) {
if (!strcmp(p->GetTitle(),pid->GetTitle())) {
delete pid;
pids->AddAtAndExpand(p,pidf);
p->IncrementCount();
return p;
}
}
pids->AddAtAndExpand(pid,pidf);
pid->IncrementCount();
fgPIDs->Add(pid);
Int_t ind = fgPIDs->IndexOf(pid);
pid->SetUniqueID((UInt_t)ind);
return pid;
}
//______________________________________________________________________________
void TProcessID::RecursiveRemove(TObject *obj)
{
// called by the object destructor
// remove reference to obj from the current table if it is referenced
if (!obj->TestBit(kIsReferenced)) return;
UInt_t uid = obj->GetUniqueID() & 0xffffff;
if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);
}
//______________________________________________________________________________
void TProcessID::SetObjectCount(UInt_t number)
{
// static function to set the current referenced object count
// fgNumber is incremented everytime a new object is referenced
fgNumber = number;
}
//______________________________________________________________________________
UShort_t TProcessID::WriteProcessID(TProcessID *pidd, TFile *file)
{
// static function
// Check if the ProcessID pid is already in the file.
// if not, add it and return the index number in the local file list
if (!file) return 0;
TProcessID *pid = pidd;
if (!pid) pid = fgPID;
TObjArray *pids = file->GetListOfProcessIDs();
Int_t npids = file->GetNProcessIDs();
for (Int_t i=0;i<npids;i++) {
if (pids->At(i) == pid) return (UShort_t)i;
}
TDirectory *dirsav = gDirectory;
file->cd();
file->SetBit(TFile::kHasReferences);
pids->Add(pid);
char name[32];
sprintf(name,"ProcessID%d",npids);
pid->Write(name);
file->IncrementProcessIDs();
if (gDebug > 0) {
printf("WriteProcessID, name=%s, file=%s\n",name,file->GetName());
}
if (dirsav) dirsav->cd();
return (UShort_t)npids;
}
<commit_msg>From Philippe: Add a missing IncrementCount when the processID object is being reused.<commit_after>// @(#)root/cont:$Name: $:$Id: TProcessID.cxx,v 1.17 2002/08/12 06:20:13 brun Exp $
// Author: Rene Brun 28/09/2001
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
//
// TProcessID
//
// A TProcessID identifies a ROOT job in a unique way in time and space.
// The TProcessID title consists of a TUUID object which provides a globally
// unique identifier (for more see TUUID.h).
//
// A TProcessID is automatically created by the TROOT constructor.
// When a TFile contains referenced objects (see TRef), the TProcessID
// object is written to the file.
// If a file has been written in multiple sessions (same machine or not),
// a TProcessID is written for each session.
// These objects are used by the class TRef to uniquely identified
// any TObject pointed by a TRef.
//
// When a referenced object is read from a file (its bit kIsReferenced is set),
// this object is entered into the objects table of the corresponding TProcessID.
// Each TFile has a list of TProcessIDs (see TFile::fProcessIDs) also
// accessible via TProcessID::fgPIDs (for all files).
// When this object is deleted, it is removed from the table via the cleanup
// mechanism invoked by the TObject destructor.
//
// Each TProcessID has a table (TObjArray *fObjects) that keeps track
// of all referenced objects. If a referenced object has a fUniqueID set,
// a pointer to this unique object may be found via fObjects->At(fUniqueID).
// In the same way, when a TRef::GetObject is called, GetObject uses
// its own fUniqueID to find the pointer to the referenced object.
// See TProcessID::GetObjectWithID and PutObjectWithID.
//
// When a referenced object is deleted, its slot in fObjects is set to null.
//
// See also TProcessUUID: a specialized TProcessID to manage the single list
// of TUUIDs.
//
//////////////////////////////////////////////////////////////////////////
#include "TProcessID.h"
#include "TROOT.h"
#include "TFile.h"
#include "TObjArray.h"
TObjArray *TProcessID::fgPIDs = 0; //pointer to the list of TProcessID
TProcessID *TProcessID::fgPID = 0; //pointer to the TProcessID of the current session
UInt_t TProcessID::fgNumber = 0; //Current referenced object instance count
ClassImp(TProcessID)
//______________________________________________________________________________
TProcessID::TProcessID()
{
fCount = 0;
fObjects = 0;
}
//______________________________________________________________________________
TProcessID::~TProcessID()
{
delete fObjects;
fObjects = 0;
fgPIDs->Remove(this);
}
//______________________________________________________________________________
TProcessID::TProcessID(const TProcessID &ref) : TNamed(ref)
{
// TProcessID copy ctor.
}
//______________________________________________________________________________
TProcessID *TProcessID::AddProcessID()
{
// static function to add a new TProcessID to the list of PIDs
TProcessID *pid = new TProcessID();
if (!fgPIDs) {
fgPID = pid;
fgPIDs = new TObjArray(10);
gROOT->GetListOfCleanups()->Add(fgPIDs);
}
UShort_t apid = fgPIDs->GetEntriesFast();
pid->IncrementCount();
fgPIDs->Add(pid);
char name[20];
sprintf(name,"ProcessID%d",apid);
pid->SetName(name);
TUUID u;
apid = fgPIDs->GetEntriesFast();
pid->SetTitle(u.AsString());
return pid;
}
//______________________________________________________________________________
UInt_t TProcessID::AssignID(TObject *obj)
{
// static function returning the ID assigned to obj
// If the object is not yet referenced, its kIsReferenced bit is set
// and its fUniqueID set to the current number of referenced objects so far.
UInt_t uid = obj->GetUniqueID() & 0xffffff;
if (obj == fgPID->GetObjectWithID(uid)) return uid;
if (obj->TestBit(kIsReferenced)) {
fgPID->PutObjectWithID(obj,uid);
return uid;
}
fgNumber++;
obj->SetBit(kIsReferenced);
uid = fgNumber;
obj->SetUniqueID(uid);
fgPID->PutObjectWithID(obj,uid);
return uid;
}
//______________________________________________________________________________
void TProcessID::Cleanup()
{
// static function (called by TROOT destructor) to delete all TProcessIDs
fgPIDs->Delete();
gROOT->GetListOfCleanups()->Remove(fgPIDs);
delete fgPIDs;
}
//______________________________________________________________________________
Int_t TProcessID::DecrementCount()
{
// the reference fCount is used to delete the TProcessID
// in the TFile destructor when fCount = 0
fCount--;
if (fCount < 0) fCount = 0;
return fCount;
}
//______________________________________________________________________________
TProcessID *TProcessID::GetProcessID(UShort_t pid)
{
// static function returning a pointer to TProcessID number pid in fgPIDs
return (TProcessID*)fgPIDs->At(pid);
}
//______________________________________________________________________________
TProcessID *TProcessID::GetProcessWithUID(UInt_t uid)
{
// static function returning a pointer to TProcessID with its pid
// encoded in the highest byte of uid
Int_t pid = (uid>>24)&0xff;
return (TProcessID*)fgPIDs->At(pid);
}
//______________________________________________________________________________
TProcessID *TProcessID::GetSessionProcessID()
{
// static function returning the pointer to the session TProcessID
return fgPID;
}
//______________________________________________________________________________
Int_t TProcessID::IncrementCount()
{
if (!fObjects) fObjects = new TObjArray(100);
fCount++;
return fCount;
}
//______________________________________________________________________________
UInt_t TProcessID::GetObjectCount()
{
// Return the current referenced object count
// fgNumber is incremented everytime a new object is referenced
return fgNumber;
}
//______________________________________________________________________________
TObject *TProcessID::GetObjectWithID(UInt_t uidd)
{
//returns the TObject with unique identifier uid in the table of objects
//if (!fObjects) fObjects = new TObjArray(100);
Int_t uid = uidd & 0xffffff; //take only the 24 lower bits
if (uid >= fObjects->GetSize()) return 0;
return fObjects->UncheckedAt(uid);
}
//______________________________________________________________________________
void TProcessID::PutObjectWithID(TObject *obj, UInt_t uid)
{
//stores the object at the uid th slot in the table of objects
//The object uniqueid is set as well as its kMustCleanup bit
//if (!fObjects) fObjects = new TObjArray(100);
if (uid == 0) uid = obj->GetUniqueID() & 0xffffff;
fObjects->AddAtAndExpand(obj,uid);
obj->SetBit(kMustCleanup);
}
//______________________________________________________________________________
TProcessID *TProcessID::ReadProcessID(UShort_t pidf, TFile *file)
{
// static function
//The TProcessID with number pidf is read from file.
//If the object is not already entered in the gROOT list, it is added.
if (!file) return 0;
TObjArray *pids = file->GetListOfProcessIDs();
TProcessID *pid = 0;
if (pidf < pids->GetSize()) pid = (TProcessID *)pids->UncheckedAt(pidf);
if (pid) return pid;
//check if fProcessIDs[uid] is set in file
//if not set, read the process uid from file
char pidname[32];
sprintf(pidname,"ProcessID%d",pidf);
TDirectory *dirsav = gDirectory;
file->cd();
pid = (TProcessID *)file->Get(pidname);
if (dirsav) dirsav->cd();
if (gDebug > 0) {
printf("ReadProcessID, name=%s, file=%s, pid=%lx\n",pidname,file->GetName(),(Long_t)pid);
}
if (!pid) {
//file->Error("ReadProcessID","Cannot find %s in file %s",pidname,file->GetName());
return 0;
}
//check that a similar pid is not already registered in fgPIDs
TIter next(fgPIDs);
TProcessID *p;
while ((p = (TProcessID*)next())) {
if (!strcmp(p->GetTitle(),pid->GetTitle())) {
delete pid;
pids->AddAtAndExpand(p,pidf);
p->IncrementCount();
return p;
}
}
pids->AddAtAndExpand(pid,pidf);
pid->IncrementCount();
fgPIDs->Add(pid);
Int_t ind = fgPIDs->IndexOf(pid);
pid->SetUniqueID((UInt_t)ind);
return pid;
}
//______________________________________________________________________________
void TProcessID::RecursiveRemove(TObject *obj)
{
// called by the object destructor
// remove reference to obj from the current table if it is referenced
if (!obj->TestBit(kIsReferenced)) return;
UInt_t uid = obj->GetUniqueID() & 0xffffff;
if (obj == GetObjectWithID(uid)) fObjects->RemoveAt(uid);
}
//______________________________________________________________________________
void TProcessID::SetObjectCount(UInt_t number)
{
// static function to set the current referenced object count
// fgNumber is incremented everytime a new object is referenced
fgNumber = number;
}
//______________________________________________________________________________
UShort_t TProcessID::WriteProcessID(TProcessID *pidd, TFile *file)
{
// static function
// Check if the ProcessID pid is already in the file.
// if not, add it and return the index number in the local file list
if (!file) return 0;
TProcessID *pid = pidd;
if (!pid) pid = fgPID;
TObjArray *pids = file->GetListOfProcessIDs();
Int_t npids = file->GetNProcessIDs();
for (Int_t i=0;i<npids;i++) {
if (pids->At(i) == pid) return (UShort_t)i;
}
TDirectory *dirsav = gDirectory;
file->cd();
file->SetBit(TFile::kHasReferences);
pids->Add(pid);
pid->IncrementCount();
char name[32];
sprintf(name,"ProcessID%d",npids);
pid->Write(name);
file->IncrementProcessIDs();
if (gDebug > 0) {
printf("WriteProcessID, name=%s, file=%s\n",name,file->GetName());
}
if (dirsav) dirsav->cd();
return (UShort_t)npids;
}
<|endoftext|> |
<commit_before>// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_EXCEPTION_HPP
#define TOML11_EXCEPTION_HPP
#include <stdexcept>
#include <string>
#include "source_location.hpp"
namespace toml
{
struct file_io_error : public std::runtime_error
{
public:
file_io_error(int errnum, const std::string& msg, const std::string& fname)
: std::runtime_error(msg + " \"" + fname + "\": " + std::strerror(errnum)),
errno_(errnum)
{}
int get_errno() {return errno_;}
private:
int errno_;
};
struct exception : public std::exception
{
public:
explicit exception(const source_location& loc): loc_(loc) {}
virtual ~exception() noexcept override = default;
virtual const char* what() const noexcept override {return "";}
virtual source_location const& location() const noexcept {return loc_;}
protected:
source_location loc_;
};
struct syntax_error : public toml::exception
{
public:
explicit syntax_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~syntax_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
protected:
std::string what_;
};
struct type_error : public toml::exception
{
public:
explicit type_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~type_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
protected:
std::string what_;
};
struct internal_error : public toml::exception
{
public:
explicit internal_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~internal_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
protected:
std::string what_;
};
} // toml
#endif // TOML_EXCEPTION
<commit_msg>fix: add missing include file and specifiers<commit_after>// Copyright Toru Niina 2017.
// Distributed under the MIT License.
#ifndef TOML11_EXCEPTION_HPP
#define TOML11_EXCEPTION_HPP
#include <stdexcept>
#include <string>
#include <cstring>
#include "source_location.hpp"
namespace toml
{
struct file_io_error : public std::runtime_error
{
public:
file_io_error(int errnum, const std::string& msg, const std::string& fname)
: std::runtime_error(msg + " \"" + fname + "\": " + std::strerror(errnum)),
errno_(errnum)
{}
int get_errno() const noexcept {return errno_;}
private:
int errno_;
};
struct exception : public std::exception
{
public:
explicit exception(const source_location& loc): loc_(loc) {}
virtual ~exception() noexcept override = default;
virtual const char* what() const noexcept override {return "";}
virtual source_location const& location() const noexcept {return loc_;}
protected:
source_location loc_;
};
struct syntax_error : public toml::exception
{
public:
explicit syntax_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~syntax_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
protected:
std::string what_;
};
struct type_error : public toml::exception
{
public:
explicit type_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~type_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
protected:
std::string what_;
};
struct internal_error : public toml::exception
{
public:
explicit internal_error(const std::string& what_arg, const source_location& loc)
: exception(loc), what_(what_arg)
{}
virtual ~internal_error() noexcept override = default;
virtual const char* what() const noexcept override {return what_.c_str();}
protected:
std::string what_;
};
} // toml
#endif // TOML_EXCEPTION
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
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 RECTANGLE_HPP
#define RECTANGLE_HPP
#include "coordinate_calculation.hpp"
#include <boost/assert.hpp>
#include <algorithm>
#include <cstdint>
#include <limits>
// TODO: Make template type, add tests
struct RectangleInt2D
{
RectangleInt2D() : min_lon(std::numeric_limits<int32_t>::max()),
max_lon(std::numeric_limits<int32_t>::min()),
min_lat(std::numeric_limits<int32_t>::max()),
max_lat(std::numeric_limits<int32_t>::min()) {}
int32_t min_lon, max_lon;
int32_t min_lat, max_lat;
inline void MergeBoundingBoxes(const RectangleInt2D &other)
{
min_lon = std::min(min_lon, other.min_lon);
max_lon = std::max(max_lon, other.max_lon);
min_lat = std::min(min_lat, other.min_lat);
max_lat = std::max(max_lat, other.max_lat);
BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
}
inline FixedPointCoordinate Centroid() const
{
FixedPointCoordinate centroid;
// The coordinates of the midpoints are given by:
// x = (x1 + x2) /2 and y = (y1 + y2) /2.
centroid.lon = (min_lon + max_lon) / 2;
centroid.lat = (min_lat + max_lat) / 2;
return centroid;
}
inline bool Intersects(const RectangleInt2D &other) const
{
FixedPointCoordinate upper_left(other.max_lat, other.min_lon);
FixedPointCoordinate upper_right(other.max_lat, other.max_lon);
FixedPointCoordinate lower_right(other.min_lat, other.max_lon);
FixedPointCoordinate lower_left(other.min_lat, other.min_lon);
return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||
Contains(lower_left));
}
inline float GetMinDist(const FixedPointCoordinate &location) const
{
const bool is_contained = Contains(location);
if (is_contained)
{
return 0.0f;
}
enum Direction
{
INVALID = 0,
NORTH = 1,
SOUTH = 2,
EAST = 4,
NORTH_EAST = 5,
SOUTH_EAST = 6,
WEST = 8,
NORTH_WEST = 9,
SOUTH_WEST = 10
};
Direction d = INVALID;
if (location.lat > max_lat)
d = (Direction) (d | NORTH);
else if (location.lat < min_lat)
d = (Direction) (d | SOUTH);
if (location.lon > max_lon)
d = (Direction) (d | EAST);
else if (location.lon < min_lon)
d = (Direction) (d | WEST);
BOOST_ASSERT(d != INVALID);
float min_dist = std::numeric_limits<float>::max();
switch (d)
{
case NORTH:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(max_lat, location.lon));
break;
case SOUTH:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(min_lat, location.lon));
break;
case WEST:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(location.lat, min_lon));
break;
case EAST:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(location.lat, max_lon));
break;
case NORTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(max_lat, max_lon));
break;
case NORTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(max_lat, min_lon));
break;
case SOUTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(min_lat, max_lon));
break;
case SOUTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(location, FixedPointCoordinate(min_lat, min_lon));
break;
default:
break;
}
BOOST_ASSERT(min_dist != std::numeric_limits<float>::max());
return min_dist;
}
inline float GetMinMaxDist(const FixedPointCoordinate &location) const
{
float min_max_dist = std::numeric_limits<float>::max();
// Get minmax distance to each of the four sides
const FixedPointCoordinate upper_left(max_lat, min_lon);
const FixedPointCoordinate upper_right(max_lat, max_lon);
const FixedPointCoordinate lower_right(min_lat, max_lon);
const FixedPointCoordinate lower_left(min_lat, min_lon);
min_max_dist = std::min(
min_max_dist,
std::max(
coordinate_calculation::euclidean_distance(location, upper_left),
coordinate_calculation::euclidean_distance(location, upper_right)));
min_max_dist = std::min(
min_max_dist,
std::max(
coordinate_calculation::euclidean_distance(location, upper_right),
coordinate_calculation::euclidean_distance(location, lower_right)));
min_max_dist = std::min(
min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_right),
coordinate_calculation::euclidean_distance(location, lower_left)));
min_max_dist = std::min(
min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_left),
coordinate_calculation::euclidean_distance(location, upper_left)));
return min_max_dist;
}
inline bool Contains(const FixedPointCoordinate &location) const
{
const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
return lats_contained && lons_contained;
}
inline friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)
{
out << rect.min_lat / COORDINATE_PRECISION << "," << rect.min_lon / COORDINATE_PRECISION
<< " " << rect.max_lat / COORDINATE_PRECISION << ","
<< rect.max_lon / COORDINATE_PRECISION;
return out;
}
};
#endif
<commit_msg>fix floating point comparison, remove superflous inline keywords<commit_after>/*
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
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 RECTANGLE_HPP
#define RECTANGLE_HPP
#include "coordinate_calculation.hpp"
#include <boost/assert.hpp>
#include <algorithm>
#include <cstdint>
#include <limits>
// TODO: Make template type, add tests
struct RectangleInt2D
{
RectangleInt2D()
: min_lon(std::numeric_limits<int32_t>::max()),
max_lon(std::numeric_limits<int32_t>::min()),
min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())
{
}
int32_t min_lon, max_lon;
int32_t min_lat, max_lat;
void MergeBoundingBoxes(const RectangleInt2D &other)
{
min_lon = std::min(min_lon, other.min_lon);
max_lon = std::max(max_lon, other.max_lon);
min_lat = std::min(min_lat, other.min_lat);
max_lat = std::max(max_lat, other.max_lat);
BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
}
FixedPointCoordinate Centroid() const
{
FixedPointCoordinate centroid;
// The coordinates of the midpoints are given by:
// x = (x1 + x2) /2 and y = (y1 + y2) /2.
centroid.lon = (min_lon + max_lon) / 2;
centroid.lat = (min_lat + max_lat) / 2;
return centroid;
}
bool Intersects(const RectangleInt2D &other) const
{
FixedPointCoordinate upper_left(other.max_lat, other.min_lon);
FixedPointCoordinate upper_right(other.max_lat, other.max_lon);
FixedPointCoordinate lower_right(other.min_lat, other.max_lon);
FixedPointCoordinate lower_left(other.min_lat, other.min_lon);
return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||
Contains(lower_left));
}
float GetMinDist(const FixedPointCoordinate &location) const
{
const bool is_contained = Contains(location);
if (is_contained)
{
return 0.0f;
}
enum Direction
{
INVALID = 0,
NORTH = 1,
SOUTH = 2,
EAST = 4,
NORTH_EAST = 5,
SOUTH_EAST = 6,
WEST = 8,
NORTH_WEST = 9,
SOUTH_WEST = 10
};
Direction d = INVALID;
if (location.lat > max_lat)
d = (Direction)(d | NORTH);
else if (location.lat < min_lat)
d = (Direction)(d | SOUTH);
if (location.lon > max_lon)
d = (Direction)(d | EAST);
else if (location.lon < min_lon)
d = (Direction)(d | WEST);
BOOST_ASSERT(d != INVALID);
float min_dist = std::numeric_limits<float>::max();
switch (d)
{
case NORTH:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, location.lon));
break;
case SOUTH:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, location.lon));
break;
case WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(location.lat, min_lon));
break;
case EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(location.lat, max_lon));
break;
case NORTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, max_lon));
break;
case NORTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, min_lon));
break;
case SOUTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, max_lon));
break;
case SOUTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, min_lon));
break;
default:
break;
}
BOOST_ASSERT(min_dist < std::numeric_limits<float>::max());
return min_dist;
}
float GetMinMaxDist(const FixedPointCoordinate &location) const
{
float min_max_dist = std::numeric_limits<float>::max();
// Get minmax distance to each of the four sides
const FixedPointCoordinate upper_left(max_lat, min_lon);
const FixedPointCoordinate upper_right(max_lat, max_lon);
const FixedPointCoordinate lower_right(min_lat, max_lon);
const FixedPointCoordinate lower_left(min_lat, min_lon);
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, upper_left),
coordinate_calculation::euclidean_distance(location, upper_right)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, upper_right),
coordinate_calculation::euclidean_distance(location, lower_right)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_right),
coordinate_calculation::euclidean_distance(location, lower_left)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_left),
coordinate_calculation::euclidean_distance(location, upper_left)));
return min_max_dist;
}
bool Contains(const FixedPointCoordinate &location) const
{
const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
return lats_contained && lons_contained;
}
friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)
{
out << rect.min_lat / COORDINATE_PRECISION << "," << rect.min_lon / COORDINATE_PRECISION
<< " " << rect.max_lat / COORDINATE_PRECISION << ","
<< rect.max_lon / COORDINATE_PRECISION;
return out;
}
};
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright 2014 Marcelo Sardelich
*
* 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 HANDLER_H_
#define HANDLER_H_
#endif /* HANDLER_H_ */
#define callClassConstructor(...) callClassConstructor_(1, __VA_ARGS__)
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <exception>
#include <cstdarg>
#include <jni.h>
namespace VM {
enum class RV {
Z, // jboolean
B, // jbyte
C, // jchar
S, // jshort
I, // jint
J, // jlong
F, // jfloat
D, // jdouble
L, // jobject
VV // VOID
};
extern JNIEnv* env;
extern JavaVM* jvm;
class SignatureBase {
public:
std::string descriptor;
bool isStatic;
jmethodID mid;
SignatureBase(std::string, bool);
SignatureBase();
virtual ~SignatureBase();
};
typedef std::map<std::string, VM::SignatureBase*> signature_t;
class CJ {
protected:
signature_t m;
std::string className;
jclass clazz;
jobject obj;
public:
static jint JNI_VERSION;
void setSignature(std::string, std::string, bool);
void printSignatures();
jclass getClass();
jobject getObj();
signature_t getMap();
std::string getDescriptor(std::string);
jmethodID getMid(std::string);
int getSizeSignatures();
void createVM(std::vector<std::string>);
void destroyVM();
void setClass(std::string);
VM::SignatureBase* getSignatureObj(std::string);
void callClassConstructor_(int, ...);
template <typename To> To call(std::string, ...);
template <typename To> To callStatic(jmethodID, va_list);
template <typename To> To callNonStatic(jmethodID, va_list);
JNIEnv* getEnv();
CJ();
virtual ~CJ();
};
template <class To> class Signature : public SignatureBase {
public:
RV rv;
To (CJ::*pCall) (jmethodID, va_list);
Signature(std::string, bool, RV);
Signature();
virtual ~Signature();
};
class ConverterBase {
protected:
CJ ARRAYLIST;
CJ MAP;
CJ NUMBER;
CJ BOOLEAN;
CJ BYTE;
CJ SHORT;
CJ LONG;
CJ INTEGER;
CJ FLOAT;
CJ DOUBLE;
CJ CHARACTER;
virtual void initARRAYLIST() = 0;
virtual void initMAP() = 0;
virtual void initNUMBER() = 0;
virtual void initBOOLEAN() = 0;
virtual void initBYTE() = 0;
virtual void initSHORT() = 0;
virtual void initLONG() = 0;
virtual void initINTEGER() = 0;
virtual void initFLOAT() = 0;
virtual void initDOUBLE() = 0;
virtual void initCHARACTER() = 0;
public:
ConverterBase();
virtual ~ConverterBase();
};
typedef std::vector<jobject> vec_jobj;
class Converter : public ConverterBase {
protected:
void initARRAYLIST();
void initMAP();
void initNUMBER();
void initBOOLEAN();
void initBYTE();
void initSHORT();
void initLONG();
void initINTEGER();
void initFLOAT();
void initDOUBLE();
void initCHARACTER();
void init();
public:
template <typename To, typename From> To j_cast(From);
template <typename To> To c_cast(jobject);
template <typename To> std::vector<To> c_cast_vector(jobject);
template <typename To> std::vector<To> c_cast_vector(jobject, int);
int sizeVector(jobject);
void deleteRef(jobject);
Converter();
~Converter();
};
class HandlerExc: public std::exception {
private:
std::string msg;
public:
HandlerExc(std::string m = "Uncategorized exception.") : msg(m) { }
~HandlerExc() throw() { }
const char* what() const throw() { return msg.c_str(); }
};
} /* namespace VM */
<commit_msg>add email to Copyright<commit_after>/**************************************************************************
* Copyright 2014 Marcelo Sardelich <MSardelich@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************************/
#ifndef HANDLER_H_
#define HANDLER_H_
#endif /* HANDLER_H_ */
#define callClassConstructor(...) callClassConstructor_(1, __VA_ARGS__)
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <exception>
#include <cstdarg>
#include <jni.h>
namespace VM {
enum class RV {
Z, // jboolean
B, // jbyte
C, // jchar
S, // jshort
I, // jint
J, // jlong
F, // jfloat
D, // jdouble
L, // jobject
VV // VOID
};
extern JNIEnv* env;
extern JavaVM* jvm;
class SignatureBase {
public:
std::string descriptor;
bool isStatic;
jmethodID mid;
SignatureBase(std::string, bool);
SignatureBase();
virtual ~SignatureBase();
};
typedef std::map<std::string, VM::SignatureBase*> signature_t;
class CJ {
protected:
signature_t m;
std::string className;
jclass clazz;
jobject obj;
public:
static jint JNI_VERSION;
void setSignature(std::string, std::string, bool);
void printSignatures();
jclass getClass();
jobject getObj();
signature_t getMap();
std::string getDescriptor(std::string);
jmethodID getMid(std::string);
int getSizeSignatures();
void createVM(std::vector<std::string>);
void destroyVM();
void setClass(std::string);
VM::SignatureBase* getSignatureObj(std::string);
void callClassConstructor_(int, ...);
template <typename To> To call(std::string, ...);
template <typename To> To callStatic(jmethodID, va_list);
template <typename To> To callNonStatic(jmethodID, va_list);
JNIEnv* getEnv();
CJ();
virtual ~CJ();
};
template <class To> class Signature : public SignatureBase {
public:
RV rv;
To (CJ::*pCall) (jmethodID, va_list);
Signature(std::string, bool, RV);
Signature();
virtual ~Signature();
};
class ConverterBase {
protected:
CJ ARRAYLIST;
CJ MAP;
CJ NUMBER;
CJ BOOLEAN;
CJ BYTE;
CJ SHORT;
CJ LONG;
CJ INTEGER;
CJ FLOAT;
CJ DOUBLE;
CJ CHARACTER;
virtual void initARRAYLIST() = 0;
virtual void initMAP() = 0;
virtual void initNUMBER() = 0;
virtual void initBOOLEAN() = 0;
virtual void initBYTE() = 0;
virtual void initSHORT() = 0;
virtual void initLONG() = 0;
virtual void initINTEGER() = 0;
virtual void initFLOAT() = 0;
virtual void initDOUBLE() = 0;
virtual void initCHARACTER() = 0;
public:
ConverterBase();
virtual ~ConverterBase();
};
typedef std::vector<jobject> vec_jobj;
class Converter : public ConverterBase {
protected:
void initARRAYLIST();
void initMAP();
void initNUMBER();
void initBOOLEAN();
void initBYTE();
void initSHORT();
void initLONG();
void initINTEGER();
void initFLOAT();
void initDOUBLE();
void initCHARACTER();
void init();
public:
template <typename To, typename From> To j_cast(From);
template <typename To> To c_cast(jobject);
template <typename To> std::vector<To> c_cast_vector(jobject);
template <typename To> std::vector<To> c_cast_vector(jobject, int);
int sizeVector(jobject);
void deleteRef(jobject);
Converter();
~Converter();
};
class HandlerExc: public std::exception {
private:
std::string msg;
public:
HandlerExc(std::string m = "Uncategorized exception.") : msg(m) { }
~HandlerExc() throw() { }
const char* what() const throw() { return msg.c_str(); }
};
} /* namespace VM */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accessibilityclient.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-10-15 11:51:33 $
*
* 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_toolkit.hxx"
#ifndef TOOLKIT_HELPER_ACCESSIBILITY_CLIENT_HXX
#include <toolkit/helper/accessibilityclient.hxx>
#endif
#ifndef TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX
#include <toolkit/helper/accessiblefactory.hxx>
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
// #define UNLOAD_ON_LAST_CLIENT_DYING
// this is not recommended currently. If enabled, the implementation will log
// the number of active clients, and unload the acc library when the last client
// goes away.
// Sounds like a good idea, unfortunately, there's no guarantee that all objects
// implemented in this library are already dead.
// Iow, just because an object implementing an XAccessible (implemented in this lib
// here) died, it's not said that everybody released all references to the
// XAccessibleContext used by this component, and implemented in the acc lib.
// So we cannot really unload the lib.
//
// Alternatively, if the lib would us own "usage counting", i.e. every component
// implemented therein would affect a static ref count, the acc lib could care
// for unloading itself.
//........................................................................
namespace toolkit
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
namespace
{
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
static oslInterlockedCount s_nAccessibilityClients = 0;
#endif // UNLOAD_ON_LAST_CLIENT_DYING
static oslModule s_hAccessibleImplementationModule = NULL;
static GetStandardAccComponentFactory s_pAccessibleFactoryFunc = NULL;
static ::rtl::Reference< IAccessibleFactory > s_pFactory;
}
//====================================================================
//= AccessibleDummyFactory
//====================================================================
class AccessibleDummyFactory : public IAccessibleFactory
{
public:
AccessibleDummyFactory();
protected:
virtual ~AccessibleDummyFactory();
private:
AccessibleDummyFactory( const AccessibleDummyFactory& ); // never implemented
AccessibleDummyFactory& operator=( const AccessibleDummyFactory& ); // never implemented
oslInterlockedCount m_refCount;
public:
// IReference
virtual oslInterlockedCount SAL_CALL acquire();
virtual oslInterlockedCount SAL_CALL release();
// IAccessibleFactory
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXButton* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXCheckBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXRadioButton* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXListBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXFixedText* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXScrollBar* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXEdit* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXComboBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXToolBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXWindow* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessible( Menu* /*_pMenu*/, sal_Bool /*_bIsMenuBar*/ )
{
return NULL;
}
};
//--------------------------------------------------------------------
AccessibleDummyFactory::AccessibleDummyFactory()
{
}
//--------------------------------------------------------------------
AccessibleDummyFactory::~AccessibleDummyFactory()
{
}
//--------------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::acquire()
{
return osl_incrementInterlockedCount( &m_refCount );
}
//--------------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::release()
{
if ( 0 == osl_decrementInterlockedCount( &m_refCount ) )
{
delete this;
return 0;
}
return m_refCount;
}
//====================================================================
//= AccessibilityClient
//====================================================================
//--------------------------------------------------------------------
AccessibilityClient::AccessibilityClient()
:m_bInitialized( false )
{
}
//--------------------------------------------------------------------
extern "C" { static void SAL_CALL thisModule() {} }
void AccessibilityClient::ensureInitialized()
{
if ( m_bInitialized )
return;
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if ( 1 == osl_incrementInterlockedCount( &s_nAccessibilityClients ) )
{ // the first client
#endif // UNLOAD_ON_LAST_CLIENT_DYING
// load the library implementing the factory
if ( !s_pFactory.get() )
{
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(
SVLIBRARY( "acc" )
);
s_hAccessibleImplementationModule = osl_loadModuleRelative( &thisModule, sModuleName.pData, 0 );
if ( s_hAccessibleImplementationModule != NULL )
{
const ::rtl::OUString sFactoryCreationFunc =
::rtl::OUString::createFromAscii( "getStandardAccessibleFactory" );
s_pAccessibleFactoryFunc = (GetStandardAccComponentFactory)
osl_getFunctionSymbol( s_hAccessibleImplementationModule, sFactoryCreationFunc.pData );
}
OSL_ENSURE( s_pAccessibleFactoryFunc, "AccessibilityClient::ensureInitialized: could not load the library, or not retrieve the needed symbol!" );
// get a factory instance
if ( s_pAccessibleFactoryFunc )
{
IAccessibleFactory* pFactory = static_cast< IAccessibleFactory* >( (*s_pAccessibleFactoryFunc)() );
OSL_ENSURE( pFactory, "AccessibilityClient::ensureInitialized: no factory provided by the A11Y lib!" );
if ( pFactory )
{
s_pFactory = pFactory;
pFactory->release();
}
}
}
if ( !s_pFactory.get() )
// the attempt to load the lib, or to create the factory, failed
// -> fall back to a dummy factory
s_pFactory = new AccessibleDummyFactory;
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
}
#endif
m_bInitialized = true;
}
//--------------------------------------------------------------------
AccessibilityClient::~AccessibilityClient()
{
if ( m_bInitialized )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if( 0 == osl_decrementInterlockedCount( &s_nAccessibilityClients ) )
{
s_pFactory = NULL;
s_pAccessibleFactoryFunc = NULL;
if ( s_hAccessibleImplementationModule )
{
osl_unloadModule( s_hAccessibleImplementationModule );
s_hAccessibleImplementationModule = NULL;
}
}
#endif // UNLOAD_ON_LAST_CLIENT_DYING
}
}
//--------------------------------------------------------------------
IAccessibleFactory& AccessibilityClient::getFactory()
{
ensureInitialized();
OSL_ENSURE( s_pFactory.is(), "AccessibilityClient::getFactory: at least a dummy factory should have been created!" );
return *s_pFactory;
}
//........................................................................
} // namespace toolkit
//........................................................................
<commit_msg>INTEGRATION: CWS fwk80_SRC680 (1.4.26); FILE MERGED 2008/01/11 14:52:59 pb 1.4.26.1: fix: #i83756# createAccessibleContext( VCLXFixedHyperlink* )<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: accessibilityclient.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2008-01-29 15:06: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_toolkit.hxx"
#ifndef TOOLKIT_HELPER_ACCESSIBILITY_CLIENT_HXX
#include <toolkit/helper/accessibilityclient.hxx>
#endif
#ifndef TOOLKIT_HELPER_ACCESSIBLE_FACTORY_HXX
#include <toolkit/helper/accessiblefactory.hxx>
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
// #define UNLOAD_ON_LAST_CLIENT_DYING
// this is not recommended currently. If enabled, the implementation will log
// the number of active clients, and unload the acc library when the last client
// goes away.
// Sounds like a good idea, unfortunately, there's no guarantee that all objects
// implemented in this library are already dead.
// Iow, just because an object implementing an XAccessible (implemented in this lib
// here) died, it's not said that everybody released all references to the
// XAccessibleContext used by this component, and implemented in the acc lib.
// So we cannot really unload the lib.
//
// Alternatively, if the lib would us own "usage counting", i.e. every component
// implemented therein would affect a static ref count, the acc lib could care
// for unloading itself.
//........................................................................
namespace toolkit
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::accessibility;
namespace
{
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
static oslInterlockedCount s_nAccessibilityClients = 0;
#endif // UNLOAD_ON_LAST_CLIENT_DYING
static oslModule s_hAccessibleImplementationModule = NULL;
static GetStandardAccComponentFactory s_pAccessibleFactoryFunc = NULL;
static ::rtl::Reference< IAccessibleFactory > s_pFactory;
}
//====================================================================
//= AccessibleDummyFactory
//====================================================================
class AccessibleDummyFactory : public IAccessibleFactory
{
public:
AccessibleDummyFactory();
protected:
virtual ~AccessibleDummyFactory();
private:
AccessibleDummyFactory( const AccessibleDummyFactory& ); // never implemented
AccessibleDummyFactory& operator=( const AccessibleDummyFactory& ); // never implemented
oslInterlockedCount m_refCount;
public:
// IReference
virtual oslInterlockedCount SAL_CALL acquire();
virtual oslInterlockedCount SAL_CALL release();
// IAccessibleFactory
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXButton* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXCheckBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXRadioButton* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXListBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXFixedHyperlink* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXFixedText* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXScrollBar* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXEdit* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXComboBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXToolBox* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >
createAccessibleContext( VCLXWindow* /*_pXWindow*/ )
{
return NULL;
}
::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
createAccessible( Menu* /*_pMenu*/, sal_Bool /*_bIsMenuBar*/ )
{
return NULL;
}
};
//--------------------------------------------------------------------
AccessibleDummyFactory::AccessibleDummyFactory()
{
}
//--------------------------------------------------------------------
AccessibleDummyFactory::~AccessibleDummyFactory()
{
}
//--------------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::acquire()
{
return osl_incrementInterlockedCount( &m_refCount );
}
//--------------------------------------------------------------------
oslInterlockedCount SAL_CALL AccessibleDummyFactory::release()
{
if ( 0 == osl_decrementInterlockedCount( &m_refCount ) )
{
delete this;
return 0;
}
return m_refCount;
}
//====================================================================
//= AccessibilityClient
//====================================================================
//--------------------------------------------------------------------
AccessibilityClient::AccessibilityClient()
:m_bInitialized( false )
{
}
//--------------------------------------------------------------------
extern "C" { static void SAL_CALL thisModule() {} }
void AccessibilityClient::ensureInitialized()
{
if ( m_bInitialized )
return;
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if ( 1 == osl_incrementInterlockedCount( &s_nAccessibilityClients ) )
{ // the first client
#endif // UNLOAD_ON_LAST_CLIENT_DYING
// load the library implementing the factory
if ( !s_pFactory.get() )
{
const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(
SVLIBRARY( "acc" )
);
s_hAccessibleImplementationModule = osl_loadModuleRelative( &thisModule, sModuleName.pData, 0 );
if ( s_hAccessibleImplementationModule != NULL )
{
const ::rtl::OUString sFactoryCreationFunc =
::rtl::OUString::createFromAscii( "getStandardAccessibleFactory" );
s_pAccessibleFactoryFunc = (GetStandardAccComponentFactory)
osl_getFunctionSymbol( s_hAccessibleImplementationModule, sFactoryCreationFunc.pData );
}
OSL_ENSURE( s_pAccessibleFactoryFunc, "AccessibilityClient::ensureInitialized: could not load the library, or not retrieve the needed symbol!" );
// get a factory instance
if ( s_pAccessibleFactoryFunc )
{
IAccessibleFactory* pFactory = static_cast< IAccessibleFactory* >( (*s_pAccessibleFactoryFunc)() );
OSL_ENSURE( pFactory, "AccessibilityClient::ensureInitialized: no factory provided by the A11Y lib!" );
if ( pFactory )
{
s_pFactory = pFactory;
pFactory->release();
}
}
}
if ( !s_pFactory.get() )
// the attempt to load the lib, or to create the factory, failed
// -> fall back to a dummy factory
s_pFactory = new AccessibleDummyFactory;
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
}
#endif
m_bInitialized = true;
}
//--------------------------------------------------------------------
AccessibilityClient::~AccessibilityClient()
{
if ( m_bInitialized )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
#ifdef UNLOAD_ON_LAST_CLIENT_DYING
if( 0 == osl_decrementInterlockedCount( &s_nAccessibilityClients ) )
{
s_pFactory = NULL;
s_pAccessibleFactoryFunc = NULL;
if ( s_hAccessibleImplementationModule )
{
osl_unloadModule( s_hAccessibleImplementationModule );
s_hAccessibleImplementationModule = NULL;
}
}
#endif // UNLOAD_ON_LAST_CLIENT_DYING
}
}
//--------------------------------------------------------------------
IAccessibleFactory& AccessibilityClient::getFactory()
{
ensureInitialized();
OSL_ENSURE( s_pFactory.is(), "AccessibilityClient::getFactory: at least a dummy factory should have been created!" );
return *s_pFactory;
}
//........................................................................
} // namespace toolkit
//........................................................................
<|endoftext|> |
<commit_before>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CopasiFileDialog.cpp,v $
// $Revision: 1.13 $
// $Name: $
// $Author: shoops $
// $Date: 2007/03/16 19:55:37 $
// End CVS Header
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <qapplication.h>
#include <qlayout.h>
#include <qtoolbutton.h>
#include "copasi.h"
#include "CopasiFileDialog.h"
#include "qtUtilities.h"
#include "CQMessageBox.h"
#include "commandline/COptions.h"
#include "utilities/CDirEntry.h"
QDir CopasiFileDialog::mLastDir; // = QDir::current();
CopasiFileDialog::CopasiFileDialog(QWidget * parent ,
const char * name ,
bool modal)
: QFileDialog(parent , name , modal)
{
setDir(mLastDir);
mpGrp = new CQFileDialogBtnGrp(this);
addLeftWidget(mpGrp);
connect(mpGrp->mpBtnExamples, SIGNAL(pressed()),
this, SLOT(slotExampleDir()));
connect(mpGrp->mpBtnHome, SIGNAL(pressed()),
this, SLOT(slotHomeDir()));
}
CopasiFileDialog::~CopasiFileDialog()
{
const QDir * pTmp = dir();
mLastDir = * pTmp;
delete pTmp;
}
QString CopasiFileDialog::getOpenFileName(const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
if (!startWith.isNull()) this->setSelection(startWith);
if (!filter.isNull()) this->setFilters(filter);
if (!caption.isNull()) this->setCaption(caption);
if (selectedFilter) this->setSelectedFilter(selectedFilter);
this->setMode(QFileDialog::ExistingFile);
QString newFile = "";
if (this->exec() == QDialog::Accepted)
{
newFile = this->selectedFile();
return newFile;
}
return NULL;
}
QString CopasiFileDialog::getSaveFileName(const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
if (!startWith.isNull()) this->setSelection(startWith);
if (!filter.isNull()) this->setFilters(filter);
if (!caption.isNull()) this->setCaption(caption);
if (selectedFilter) this->setSelectedFilter(selectedFilter);
this->setMode(QFileDialog::AnyFile);
QString newFile = "";
if (this->exec() == QDialog::Accepted)
{
newFile = this->selectedFile();
return newFile;
}
return NULL;
}
void CopasiFileDialog::slotExampleDir()
{
std::string ExampleDir;
COptions::getValue("ExampleDir", ExampleDir);
if (CDirEntry::isDir(ExampleDir))
{
setDir(FROM_UTF8(ExampleDir));
}
else
{
CQMessageBox::information(this, "Directory Not Found", FROM_UTF8(ExampleDir),
QMessageBox::Ok, 0);
mpGrp->mpBtnExamples->setDown(false);
}
}
void CopasiFileDialog::slotHomeDir()
{
std::string homeDir;
COptions::getValue("Home", homeDir);
if (CDirEntry::isDir(homeDir))
{
setDir(FROM_UTF8(homeDir));
}
else
{
CQMessageBox::information(this, "Directory Not Found", FROM_UTF8(homeDir),
QMessageBox::Ok, 0);
mpGrp->mpBtnHome->setDown(false);
}
}
QString CopasiFileDialog::getOpenFileName(QWidget * parent,
const char * name,
const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
CopasiFileDialog * pDialog = new CopasiFileDialog(parent, name, true);
QString File = pDialog->getOpenFileName(startWith, filter, caption, selectedFilter);
delete pDialog;
return File;
}
QString CopasiFileDialog::getSaveFileName(QWidget * parent,
const char * name,
const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
CopasiFileDialog * pDialog = new CopasiFileDialog(parent, name, true);
QString File = pDialog->getSaveFileName(startWith, filter, caption, selectedFilter);
delete pDialog;
return File;
}
QString CopasiFileDialog::getSaveFileNameAndFilter(QString & newFilter,
QWidget * parent,
const char * name,
const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
CopasiFileDialog * pDialog = new CopasiFileDialog(parent, name, true);
QString File = pDialog->getSaveFileName(startWith, filter, caption, selectedFilter);
newFilter = pDialog->selectedFilter();
delete pDialog;
return File;
}
<commit_msg>Add ability to check the correctness of file extension according to the filter and give the correct one. So far, only mml, xml, tex, png and svg.<commit_after>// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CopasiFileDialog.cpp,v $
// $Revision: 1.14 $
// $Name: $
// $Author: pwilly $
// $Date: 2008/07/25 05:53:24 $
// End CVS Header
// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <qapplication.h>
#include <qlayout.h>
#include <qtoolbutton.h>
#include <qfileinfo.h>
#include "copasi.h"
#include "CopasiFileDialog.h"
#include "qtUtilities.h"
#include "CQMessageBox.h"
#include "commandline/COptions.h"
#include "utilities/CDirEntry.h"
QDir CopasiFileDialog::mLastDir; // = QDir::current();
CopasiFileDialog::CopasiFileDialog(QWidget * parent ,
const char * name ,
bool modal)
: QFileDialog(parent , name , modal)
{
setDir(mLastDir);
mpGrp = new CQFileDialogBtnGrp(this);
addLeftWidget(mpGrp);
connect(mpGrp->mpBtnExamples, SIGNAL(pressed()),
this, SLOT(slotExampleDir()));
connect(mpGrp->mpBtnHome, SIGNAL(pressed()),
this, SLOT(slotHomeDir()));
}
CopasiFileDialog::~CopasiFileDialog()
{
const QDir * pTmp = dir();
mLastDir = * pTmp;
delete pTmp;
}
QString CopasiFileDialog::getOpenFileName(const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
if (!startWith.isNull()) this->setSelection(startWith);
if (!filter.isNull()) this->setFilters(filter);
if (!caption.isNull()) this->setCaption(caption);
if (selectedFilter) this->setSelectedFilter(selectedFilter);
this->setMode(QFileDialog::ExistingFile);
QString newFile = "";
if (this->exec() == QDialog::Accepted)
{
newFile = this->selectedFile();
return newFile;
}
return NULL;
}
QString CopasiFileDialog::getSaveFileName(const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
if (!startWith.isNull()) this->setSelection(startWith);
if (!filter.isNull()) this->setFilters(filter);
if (!caption.isNull()) this->setCaption(caption);
if (selectedFilter) this->setSelectedFilter(selectedFilter);
this->setMode(QFileDialog::AnyFile);
QString newFile = "";
if (this->exec() == QDialog::Accepted)
{
newFile = this->selectedFile();
return newFile;
}
return NULL;
}
void CopasiFileDialog::slotExampleDir()
{
std::string ExampleDir;
COptions::getValue("ExampleDir", ExampleDir);
if (CDirEntry::isDir(ExampleDir))
{
setDir(FROM_UTF8(ExampleDir));
}
else
{
CQMessageBox::information(this, "Directory Not Found", FROM_UTF8(ExampleDir),
QMessageBox::Ok, 0);
mpGrp->mpBtnExamples->setDown(false);
}
}
void CopasiFileDialog::slotHomeDir()
{
std::string homeDir;
COptions::getValue("Home", homeDir);
if (CDirEntry::isDir(homeDir))
{
setDir(FROM_UTF8(homeDir));
}
else
{
CQMessageBox::information(this, "Directory Not Found", FROM_UTF8(homeDir),
QMessageBox::Ok, 0);
mpGrp->mpBtnHome->setDown(false);
}
}
QString CopasiFileDialog::getOpenFileName(QWidget * parent,
const char * name,
const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
CopasiFileDialog * pDialog = new CopasiFileDialog(parent, name, true);
QString File = pDialog->getOpenFileName(startWith, filter, caption, selectedFilter);
delete pDialog;
return File;
}
QString CopasiFileDialog::getSaveFileName(QWidget * parent,
const char * name,
const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
CopasiFileDialog * pDialog = new CopasiFileDialog(parent, name, true);
QString File = pDialog->getSaveFileName(startWith, filter, caption, selectedFilter);
if (!File) return "";
// check the extension and replace the uncorrect extension with the correct one according to the filter
QString Filter;
if (pDialog->selectedFilter().contains("png"))
Filter = "png";
else if (pDialog->selectedFilter().contains("svg"))
Filter = "svg";
else if (pDialog->selectedFilter().contains("tex"))
Filter = "tex";
else if (pDialog->selectedFilter().contains("mml"))
Filter = "mml";
else if (pDialog->selectedFilter().contains("xml"))
Filter = "xml";
if (!File.endsWith("." + Filter))
{
if (File.contains("."))
{
int pos = File.find(".");
File.truncate(pos);
}
File += "." + Filter;
}
delete pDialog;
return File;
}
QString CopasiFileDialog::getSaveFileNameAndFilter(QString & newFilter,
QWidget * parent,
const char * name,
const QString & startWith,
const QString & filter,
const QString & caption,
QString selectedFilter)
{
CopasiFileDialog * pDialog = new CopasiFileDialog(parent, name, true);
QString File = pDialog->getSaveFileName(startWith, filter, caption, selectedFilter);
if (!File) return "";
newFilter = pDialog->selectedFilter();
// check the extension and replace the uncorrect extension with the correct one according to the filter
QString Filter;
if (newFilter.contains("png"))
Filter = "png";
else if (newFilter.contains("svg"))
Filter = "svg";
else if (newFilter.contains("tex"))
Filter = "tex";
else if (newFilter.contains("mml"))
Filter = "mml";
else if (newFilter.contains("xml"))
Filter = "xml";
if (!File.endsWith("." + Filter))
{
if (File.contains("."))
{
int pos = File.find(".");
File.truncate(pos);
}
File += "." + Filter;
}
delete pDialog;
return File;
}
<|endoftext|> |
<commit_before>#line 2 "togo/window/window/impl/opengl.ipp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#pragma once
#include <togo/window/config.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/string/string.hpp>
#include <togo/window/window/impl/types.hpp>
#include <togo/window/window/impl/opengl.hpp>
namespace togo {
namespace window {
char const* gl_get_error() {
#define TOGO_RETURN_ERROR(err_name_) \
case err_name_: return #err_name_;
GLenum const error_code = glGetError();
switch (error_code) {
case GL_NO_ERROR: return nullptr;
TOGO_RETURN_ERROR(GL_INVALID_ENUM)
TOGO_RETURN_ERROR(GL_INVALID_VALUE)
TOGO_RETURN_ERROR(GL_INVALID_OPERATION)
TOGO_RETURN_ERROR(GL_INVALID_FRAMEBUFFER_OPERATION)
TOGO_RETURN_ERROR(GL_OUT_OF_MEMORY)
TOGO_RETURN_ERROR(GL_STACK_OVERFLOW)
TOGO_RETURN_ERROR(GL_STACK_UNDERFLOW)
default: return "UNKNOWN";
}
#undef TOGO_RETURN_ERROR
}
inline static void gl_set_cap_active(GLenum cap, bool enable) {
if (enable) {
glEnable(cap);
} else {
glDisable(cap);
}
}
struct NamedEnum {
StringRef name;
GLenum value;
};
NamedEnum const
#define TOGO_NAMED_ENUM(name, value) {name, GL_DEBUG_ ## value},
gl_enum_debug_source[]{
TOGO_NAMED_ENUM("api" , SOURCE_API)
TOGO_NAMED_ENUM("wsys", SOURCE_WINDOW_SYSTEM)
TOGO_NAMED_ENUM("scc" , SOURCE_SHADER_COMPILER)
TOGO_NAMED_ENUM("3rd" , SOURCE_THIRD_PARTY)
TOGO_NAMED_ENUM("user", SOURCE_APPLICATION)
TOGO_NAMED_ENUM("etc" , SOURCE_OTHER)
},
gl_enum_debug_type[]{
TOGO_NAMED_ENUM("error" , TYPE_ERROR)
TOGO_NAMED_ENUM("deprecated", TYPE_DEPRECATED_BEHAVIOR)
TOGO_NAMED_ENUM("undef" , TYPE_UNDEFINED_BEHAVIOR)
TOGO_NAMED_ENUM("port" , TYPE_PORTABILITY)
TOGO_NAMED_ENUM("perf" , TYPE_PERFORMANCE)
TOGO_NAMED_ENUM("etc" , TYPE_OTHER)
TOGO_NAMED_ENUM("marker" , TYPE_MARKER)
TOGO_NAMED_ENUM("push" , TYPE_PUSH_GROUP)
TOGO_NAMED_ENUM("pop" , TYPE_POP_GROUP)
},
gl_enum_debug_severity[]{
TOGO_NAMED_ENUM("fyi" , SEVERITY_NOTIFICATION)
TOGO_NAMED_ENUM("low" , SEVERITY_LOW)
TOGO_NAMED_ENUM("med" , SEVERITY_MEDIUM)
TOGO_NAMED_ENUM("high", SEVERITY_HIGH)
}
#undef TOGO_NAMED_ENUM
;
inline static StringRef get_enum_name(
ArrayRef<NamedEnum const> e,
GLenum value
) {
for (auto& pair : e) {
if (pair.value == value) {
return pair.name;
}
}
return "???";
}
static void gl_debug_message_callback(
GLenum source,
GLenum type,
GLuint /*id*/,
GLenum severity,
GLsizei length,
GLchar const* message_data,
void const* /*userParam*/
) {
auto severity_str = get_enum_name(gl_enum_debug_severity, severity);
auto source_str = get_enum_name(gl_enum_debug_source, source);
auto type_str = get_enum_name(gl_enum_debug_type, type);
StringRef message{message_data, unsigned_cast(length)};
if (message.size > 0 && message[message.size - 1] == '\n') {
--message.size;
}
TOGO_LOGF(
"OpenGL: debug: [%-4.*s] [%-4.*s] [%-10.*s] %.*s\n",
severity_str.size, severity_str.data,
source_str.size, source_str.data,
type_str.size, type_str.data,
message.size, message.data
);
}
static bool set_opengl_debug_mode_impl(bool active) {
if (!_globals.opengl_initialized) {
return false;
}
TOGO_ASSERTE(GLAD_GL_KHR_debug);
if (GLAD_GL_KHR_debug) {
if (active) {
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT, true));
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT_SYNCHRONOUS, true));
TOGO_GLCE(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true));
TOGO_GLCE(glDebugMessageCallback(gl_debug_message_callback, nullptr));
TOGO_LOG("OpenGL: debug enabled\n");
} else if (glIsEnabled(GL_DEBUG_OUTPUT)) {
TOGO_GLCE(glDebugMessageCallback(nullptr, nullptr));
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT_SYNCHRONOUS, false));
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT, false));
TOGO_LOG("OpenGL: debug disabled\n");
}
return true;
} else if (active) {
TOGO_LOG_ERROR("GL_KHR_debug extension not supported\n");
}
return !active;
}
inline static void log_gl_string(StringRef name, GLenum id) {
auto value = reinterpret_cast<char const*>(glGetString(id));
TOGO_LOGF("%.*s = %s\n", name.size, name.data, value ? value : "(null)");
}
void init_opengl() {
if (_globals.opengl_initialized) {
return;
}
TOGO_ASSERT(gladLoadGL(), "failed to initialize OpenGL");
#define LOG_GL_STRING(name) \
log_gl_string(#name, name)
LOG_GL_STRING(GL_VENDOR);
LOG_GL_STRING(GL_VERSION);
LOG_GL_STRING(GL_SHADING_LANGUAGE_VERSION);
LOG_GL_STRING(GL_RENDERER);
#undef LOG_GL_STRING
#if defined(TOGO_DEBUG)
{GLint num = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num);
TOGO_LOGF("OpenGL extensions (%d):\n", num);
for (signed i = 0; i < num; ++i) {
auto value = glGetStringi(GL_EXTENSIONS, i);
if (value) {
TOGO_LOGF(" %s\n", value);
}
}}
#endif
_globals.opengl_initialized = true;
set_opengl_debug_mode_impl(_globals.opengl_debug);
}
bool set_opengl_debug_mode(bool active) {
if (active == _globals.opengl_debug) {
return true;
}
_globals.opengl_debug = active;
if (!_globals.opengl_initialized) {
return true;
}
return set_opengl_debug_mode_impl(_globals.opengl_debug);
}
} // namespace window
} // namespace togo
<commit_msg>lib/window/impl/opengl: removed assertion for GL_KHR_debug availability.<commit_after>#line 2 "togo/window/window/impl/opengl.ipp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#pragma once
#include <togo/window/config.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/string/string.hpp>
#include <togo/window/window/impl/types.hpp>
#include <togo/window/window/impl/opengl.hpp>
namespace togo {
namespace window {
char const* gl_get_error() {
#define TOGO_RETURN_ERROR(err_name_) \
case err_name_: return #err_name_;
GLenum const error_code = glGetError();
switch (error_code) {
case GL_NO_ERROR: return nullptr;
TOGO_RETURN_ERROR(GL_INVALID_ENUM)
TOGO_RETURN_ERROR(GL_INVALID_VALUE)
TOGO_RETURN_ERROR(GL_INVALID_OPERATION)
TOGO_RETURN_ERROR(GL_INVALID_FRAMEBUFFER_OPERATION)
TOGO_RETURN_ERROR(GL_OUT_OF_MEMORY)
TOGO_RETURN_ERROR(GL_STACK_OVERFLOW)
TOGO_RETURN_ERROR(GL_STACK_UNDERFLOW)
default: return "UNKNOWN";
}
#undef TOGO_RETURN_ERROR
}
inline static void gl_set_cap_active(GLenum cap, bool enable) {
if (enable) {
glEnable(cap);
} else {
glDisable(cap);
}
}
struct NamedEnum {
StringRef name;
GLenum value;
};
NamedEnum const
#define TOGO_NAMED_ENUM(name, value) {name, GL_DEBUG_ ## value},
gl_enum_debug_source[]{
TOGO_NAMED_ENUM("api" , SOURCE_API)
TOGO_NAMED_ENUM("wsys", SOURCE_WINDOW_SYSTEM)
TOGO_NAMED_ENUM("scc" , SOURCE_SHADER_COMPILER)
TOGO_NAMED_ENUM("3rd" , SOURCE_THIRD_PARTY)
TOGO_NAMED_ENUM("user", SOURCE_APPLICATION)
TOGO_NAMED_ENUM("etc" , SOURCE_OTHER)
},
gl_enum_debug_type[]{
TOGO_NAMED_ENUM("error" , TYPE_ERROR)
TOGO_NAMED_ENUM("deprecated", TYPE_DEPRECATED_BEHAVIOR)
TOGO_NAMED_ENUM("undef" , TYPE_UNDEFINED_BEHAVIOR)
TOGO_NAMED_ENUM("port" , TYPE_PORTABILITY)
TOGO_NAMED_ENUM("perf" , TYPE_PERFORMANCE)
TOGO_NAMED_ENUM("etc" , TYPE_OTHER)
TOGO_NAMED_ENUM("marker" , TYPE_MARKER)
TOGO_NAMED_ENUM("push" , TYPE_PUSH_GROUP)
TOGO_NAMED_ENUM("pop" , TYPE_POP_GROUP)
},
gl_enum_debug_severity[]{
TOGO_NAMED_ENUM("fyi" , SEVERITY_NOTIFICATION)
TOGO_NAMED_ENUM("low" , SEVERITY_LOW)
TOGO_NAMED_ENUM("med" , SEVERITY_MEDIUM)
TOGO_NAMED_ENUM("high", SEVERITY_HIGH)
}
#undef TOGO_NAMED_ENUM
;
inline static StringRef get_enum_name(
ArrayRef<NamedEnum const> e,
GLenum value
) {
for (auto& pair : e) {
if (pair.value == value) {
return pair.name;
}
}
return "???";
}
static void gl_debug_message_callback(
GLenum source,
GLenum type,
GLuint /*id*/,
GLenum severity,
GLsizei length,
GLchar const* message_data,
void const* /*userParam*/
) {
auto severity_str = get_enum_name(gl_enum_debug_severity, severity);
auto source_str = get_enum_name(gl_enum_debug_source, source);
auto type_str = get_enum_name(gl_enum_debug_type, type);
StringRef message{message_data, unsigned_cast(length)};
if (message.size > 0 && message[message.size - 1] == '\n') {
--message.size;
}
TOGO_LOGF(
"OpenGL: debug: [%-4.*s] [%-4.*s] [%-10.*s] %.*s\n",
severity_str.size, severity_str.data,
source_str.size, source_str.data,
type_str.size, type_str.data,
message.size, message.data
);
}
static bool set_opengl_debug_mode_impl(bool active) {
if (!_globals.opengl_initialized) {
return false;
}
if (GLAD_GL_KHR_debug) {
if (active) {
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT, true));
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT_SYNCHRONOUS, true));
TOGO_GLCE(glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true));
TOGO_GLCE(glDebugMessageCallback(gl_debug_message_callback, nullptr));
TOGO_LOG("OpenGL: debug enabled\n");
} else if (glIsEnabled(GL_DEBUG_OUTPUT)) {
TOGO_GLCE(glDebugMessageCallback(nullptr, nullptr));
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT_SYNCHRONOUS, false));
TOGO_GLCE(gl_set_cap_active(GL_DEBUG_OUTPUT, false));
TOGO_LOG("OpenGL: debug disabled\n");
}
return true;
} else if (active) {
TOGO_LOG_ERROR("GL_KHR_debug extension not supported\n");
}
return !active;
}
inline static void log_gl_string(StringRef name, GLenum id) {
auto value = reinterpret_cast<char const*>(glGetString(id));
TOGO_LOGF("%.*s = %s\n", name.size, name.data, value ? value : "(null)");
}
void init_opengl() {
if (_globals.opengl_initialized) {
return;
}
TOGO_ASSERT(gladLoadGL(), "failed to initialize OpenGL");
#define LOG_GL_STRING(name) \
log_gl_string(#name, name)
LOG_GL_STRING(GL_VENDOR);
LOG_GL_STRING(GL_VERSION);
LOG_GL_STRING(GL_SHADING_LANGUAGE_VERSION);
LOG_GL_STRING(GL_RENDERER);
#undef LOG_GL_STRING
#if defined(TOGO_DEBUG)
{GLint num = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num);
TOGO_LOGF("OpenGL extensions (%d):\n", num);
for (signed i = 0; i < num; ++i) {
auto value = glGetStringi(GL_EXTENSIONS, i);
if (value) {
TOGO_LOGF(" %s\n", value);
}
}}
#endif
_globals.opengl_initialized = true;
set_opengl_debug_mode_impl(_globals.opengl_debug);
}
bool set_opengl_debug_mode(bool active) {
if (active == _globals.opengl_debug) {
return true;
}
_globals.opengl_debug = active;
if (!_globals.opengl_initialized) {
return true;
}
return set_opengl_debug_mode_impl(_globals.opengl_debug);
}
} // namespace window
} // namespace togo
<|endoftext|> |
<commit_before>/**
* StreamSwitch is an extensible and scalable media stream server for
* multi-protocol environment.
*
* Copyright (C) 2014 OpenSight (www.opensight.cn)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
/**
* stsw_rotate_logger.cc
* RotateLogger class implementation file, define all methods of RotateLogger.
*
* author: jamken
* date: 2014-12-8
**/
#include <stsw_rotate_logger.h>
#include <stdint.h>
#include <list>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stsw_lock_guard.h>
#define STDERR_FD 2
namespace stream_switch {
static const char *log_level_str[] =
{
"EMERG",
"ALERT",
"CRIT",
"ERR",
"WARNING",
"NOTICE",
"INFO",
"DEBUG",
};
RotateLogger::RotateLogger()
:file_size_(0), rotate_num_(0), stderr_redirect_(false),
log_level_(0), fd_(-1), redirect_fd_old_(-1), flags_(0)
{
}
RotateLogger::~RotateLogger()
{
Uninit();
}
int RotateLogger::Init(const std::string &prog_name, const std::string &base_name,
int file_size, int rotate_num,
int log_level,
bool stderr_redirect)
{
int ret;
if(file_size <= 0 || rotate_num < 0){
ret = ERROR_CODE_PARAM;
return ret;
}
if((flags_ & ROTATE_LOGGER_FLAG_INIT) != 0){
return ERROR_CODE_GENERAL;
}
prog_name_ = prog_name;
base_name_ = base_name;
file_size_ = file_size;
rotate_num_ = rotate_num;
if(log_level < LOG_LEVEL_EMERG){
log_level = LOG_LEVEL_EMERG;
}else if(log_level > LOG_LEVEL_DEBUG) {
log_level = LOG_LEVEL_DEBUG;
}
log_level_ = log_level;
stderr_redirect_ = stderr_redirect;
if(stderr_redirect_){
//back up original stderr fd
redirect_fd_old_ = dup(STDERR_FD);
if(redirect_fd_old_ < 0){
ret = ERROR_CODE_SYSTEM;
goto error_0;
}
}
//init lock
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if(ret){
ret = ERROR_CODE_SYSTEM;
perror("pthread_mutexattr_settype failed");
pthread_mutexattr_destroy(&attr);
goto error_1;
}
ret = pthread_mutex_init(&lock_, &attr);
if(ret){
ret = ERROR_CODE_SYSTEM;
perror("pthread_mutex_init failed");
pthread_mutexattr_destroy(&attr);
goto error_1;
}
pthread_mutexattr_destroy(&attr);
ret = Reopen();
if(ret){
perror("Open log file failed");
goto error_2;
}
flags_ |= ROTATE_LOGGER_FLAG_INIT;
return 0;
error_2:
pthread_mutex_destroy(&lock_);
error_1:
if(redirect_fd_old_ >= 0){
close(redirect_fd_old_);
redirect_fd_old_ = -1;
}
error_0:
//clean field
prog_name_.clear();
base_name_.clear();
file_size_ = 0;
rotate_num_ = 0;
log_level_ = LOG_LEVEL_EMERG;
stderr_redirect_ = false;
redirect_fd_old_ = -1;
return ret;
}
void RotateLogger::Uninit()
{
if((flags_ & ROTATE_LOGGER_FLAG_INIT) == 0){
//not init yet or already uninit
return;
}
CloseFile();
pthread_mutex_destroy(&lock_);
if(redirect_fd_old_ >= 0){
//restore the original stderr fd
dup2(redirect_fd_old_, STDERR_FD);
close(redirect_fd_old_);
redirect_fd_old_ = -1;
}
//clean field
prog_name_.clear();
base_name_.clear();
file_size_ = 0;
rotate_num_ = 0;
log_level_ = LOG_LEVEL_EMERG;
stderr_redirect_ = false;
flags_ &= ~(ROTATE_LOGGER_FLAG_INIT);
}
void RotateLogger::set_log_level(int log_level)
{
if(log_level < LOG_LEVEL_EMERG){
log_level = LOG_LEVEL_EMERG;
}else if(log_level > LOG_LEVEL_DEBUG) {
log_level = LOG_LEVEL_DEBUG;
}
log_level_ = log_level;
}
int RotateLogger::log_level()
{
return log_level_;
}
void RotateLogger::CheckRotate()
{
if(!IsInit()){
return;
}
LockGuard guard(&lock_);
if(IsTooLarge()){
ShiftFile();
Reopen();
}
}
#define MAX_LOG_RECORD_SIZE 1024
void RotateLogger::Log(int level, const char * filename, int line, const char * fmt, ...)
{
if(!IsInit()){
return;
}
if(level > log_level_){
return; // level filter
}
::std::string log_str;
int ret;
char time_str_buf[32];
time_t curtime = time (NULL);
char *time_str;
time_str = ctime_r(&curtime, time_str_buf);
//
// make up the log record string
char * tmp_buf = new char[MAX_LOG_RECORD_SIZE];
tmp_buf[MAX_LOG_RECORD_SIZE - 1] = 0;
ret = snprintf(tmp_buf, MAX_LOG_RECORD_SIZE - 1,
"[%s][%s][%s][%s:%d]:",
time_str,
prog_name_.c_str(),
log_level_str[level],
filename, line);
if(ret < 0){
goto out;
}
log_str += tmp_buf;
va_list args;
va_start (args, fmt);
ret = vsnprintf (tmp_buf, MAX_LOG_RECORD_SIZE - 1, fmt, args);
if(ret < 0){
goto out;
}
va_end (args);
log_str += tmp_buf;
if(log_str[log_str.length() - 1] != '\n'){
log_str.push_back('\n');
}
//
//print log to log file
{
//check if need rotate
CheckRotate();
LockGuard guard(&lock_);
if(fd_ >= 0){
write(fd_, log_str.c_str(), log_str.length());
}
}
out:
delete[] tmp_buf;
}
bool RotateLogger::IsTooLarge()
{
if(fd_ < 0){
// no open log file
return false;
}
off_t len = lseek(fd_, 0, SEEK_CUR);
if (len < 0) {
return false;
}
return (len >= file_size_);
}
void RotateLogger::ShiftFile()
{
char log_file[1024];
char log_file_old[1024];
memset(log_file, 0, 1024);
memset(log_file_old, 0, 1024);
//
// remove the last rotate file
if(rotate_num_ > 0){
snprintf(log_file, sizeof(log_file)-1, "%s.%d", base_name_.c_str(), rotate_num_);
}else{
snprintf(log_file, sizeof(log_file)-1, "%s", base_name_.c_str());
}
remove(log_file);
//
//change the file name;
char *src=log_file_old;
char *dst=log_file;
char *tmp = NULL;
for (int i = rotate_num_ - 1; i >= 0; i--) {
if(i > 0){
snprintf(src, sizeof(log_file) -1, "%s.%d", base_name_.c_str(), i);
}else{
snprintf(src, sizeof(log_file) -1, "%s", base_name_.c_str());
}
rename(src,dst);
tmp = dst;
dst = src;
src = tmp;
}
}
int RotateLogger::Reopen()
{
CloseFile();
int fd = open(base_name_.c_str(), O_CREAT|O_APPEND|O_WRONLY, 0777);
if (fd < 0) {
if(stderr_redirect_){
dup2(redirect_fd_old_, STDERR_FD);
}
return ERROR_CODE_SYSTEM;
}else{
if(stderr_redirect_){
dup2(fd, STDERR_FD);
}
}
fd_ = fd;
return 0;
}
void RotateLogger::CloseFile()
{
if(fd_ >= 0){
::close(fd_);
fd_ = -1;
}
}
}
<commit_msg>code update<commit_after>/**
* StreamSwitch is an extensible and scalable media stream server for
* multi-protocol environment.
*
* Copyright (C) 2014 OpenSight (www.opensight.cn)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
/**
* stsw_rotate_logger.cc
* RotateLogger class implementation file, define all methods of RotateLogger.
*
* author: jamken
* date: 2014-12-8
**/
#include <stsw_rotate_logger.h>
#include <stdint.h>
#include <list>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stsw_lock_guard.h>
#define STDERR_FD 2
namespace stream_switch {
static const char *log_level_str[] =
{
"EMERG",
"ALERT",
"CRIT",
"ERR",
"WARNING",
"NOTICE",
"INFO",
"DEBUG",
};
RotateLogger::RotateLogger()
:file_size_(0), rotate_num_(0), stderr_redirect_(false),
log_level_(0), fd_(-1), redirect_fd_old_(-1), flags_(0)
{
}
RotateLogger::~RotateLogger()
{
Uninit();
}
int RotateLogger::Init(const std::string &prog_name, const std::string &base_name,
int file_size, int rotate_num,
int log_level,
bool stderr_redirect)
{
int ret;
if(file_size <= 0 || rotate_num < 0){
ret = ERROR_CODE_PARAM;
return ret;
}
if((flags_ & ROTATE_LOGGER_FLAG_INIT) != 0){
return ERROR_CODE_GENERAL;
}
prog_name_ = prog_name;
base_name_ = base_name;
file_size_ = file_size;
rotate_num_ = rotate_num;
if(log_level < LOG_LEVEL_EMERG){
log_level = LOG_LEVEL_EMERG;
}else if(log_level > LOG_LEVEL_DEBUG) {
log_level = LOG_LEVEL_DEBUG;
}
log_level_ = log_level;
stderr_redirect_ = stderr_redirect;
if(stderr_redirect_){
//back up original stderr fd
redirect_fd_old_ = dup(STDERR_FD);
if(redirect_fd_old_ < 0){
ret = ERROR_CODE_SYSTEM;
goto error_0;
}
}
//init lock
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
if(ret){
ret = ERROR_CODE_SYSTEM;
perror("pthread_mutexattr_settype failed");
pthread_mutexattr_destroy(&attr);
goto error_1;
}
ret = pthread_mutex_init(&lock_, &attr);
if(ret){
ret = ERROR_CODE_SYSTEM;
perror("pthread_mutex_init failed");
pthread_mutexattr_destroy(&attr);
goto error_1;
}
pthread_mutexattr_destroy(&attr);
ret = Reopen();
if(ret){
perror("Open log file failed");
goto error_2;
}
flags_ |= ROTATE_LOGGER_FLAG_INIT;
return 0;
error_2:
pthread_mutex_destroy(&lock_);
error_1:
if(redirect_fd_old_ >= 0){
close(redirect_fd_old_);
redirect_fd_old_ = -1;
}
error_0:
//clean field
prog_name_.clear();
base_name_.clear();
file_size_ = 0;
rotate_num_ = 0;
log_level_ = LOG_LEVEL_EMERG;
stderr_redirect_ = false;
redirect_fd_old_ = -1;
return ret;
}
void RotateLogger::Uninit()
{
if((flags_ & ROTATE_LOGGER_FLAG_INIT) == 0){
//not init yet or already uninit
return;
}
CloseFile();
pthread_mutex_destroy(&lock_);
if(redirect_fd_old_ >= 0){
//restore the original stderr fd
dup2(redirect_fd_old_, STDERR_FD);
close(redirect_fd_old_);
redirect_fd_old_ = -1;
}
//clean field
prog_name_.clear();
base_name_.clear();
file_size_ = 0;
rotate_num_ = 0;
log_level_ = LOG_LEVEL_EMERG;
stderr_redirect_ = false;
flags_ &= ~(ROTATE_LOGGER_FLAG_INIT);
}
void RotateLogger::set_log_level(int log_level)
{
if(log_level < LOG_LEVEL_EMERG){
log_level = LOG_LEVEL_EMERG;
}else if(log_level > LOG_LEVEL_DEBUG) {
log_level = LOG_LEVEL_DEBUG;
}
log_level_ = log_level;
}
int RotateLogger::log_level()
{
return log_level_;
}
void RotateLogger::CheckRotate()
{
if(!IsInit()){
return;
}
LockGuard guard(&lock_);
if(IsTooLarge()){
ShiftFile();
Reopen();
}
}
#define MAX_LOG_RECORD_SIZE 1024
void RotateLogger::Log(int level, const char * filename, int line, const char * fmt, ...)
{
if(!IsInit()){
return;
}
if(level > log_level_){
return; // level filter
}
::std::string log_str;
int ret;
char time_str_buf[32];
time_t curtime = time (NULL);
char *time_str;
time_str = ctime_r(&curtime, time_str_buf);
//
// make up the log record string
char * tmp_buf = new char[MAX_LOG_RECORD_SIZE];
tmp_buf[MAX_LOG_RECORD_SIZE - 1] = 0;
ret = snprintf(tmp_buf, MAX_LOG_RECORD_SIZE - 1,
"[%s][%s][%s][%s:%d]:",
time_str,
prog_name_.c_str(),
log_level_str[level],
filename, line);
if(ret < 0){
goto out;
}
log_str += tmp_buf;
va_list args;
va_start (args, fmt);
ret = vsnprintf (tmp_buf, MAX_LOG_RECORD_SIZE - 1, fmt, args);
if(ret < 0){
goto out;
}
va_end (args);
log_str += tmp_buf;
if(log_str[log_str.length() - 1] != '\n'){
log_str.push_back('\n');
}
//
//print log to log file
{
//check if need rotate
CheckRotate();
LockGuard guard(&lock_);
if(fd_ >= 0){
write(fd_, log_str.c_str(), log_str.length());
}
}
out:
delete[] tmp_buf;
}
bool RotateLogger::IsTooLarge()
{
if(fd_ < 0){
// no open log file
return false;
}
off_t len = lseek(fd_, 0, SEEK_CUR);
if (len < 0) {
return false;
}
return (len >= file_size_);
}
void RotateLogger::ShiftFile()
{
char log_file[1024];
char log_file_old[1024];
memset(log_file, 0, 1024);
memset(log_file_old, 0, 1024);
//
// remove the last rotate file
if(rotate_num_ > 0){
snprintf(log_file, sizeof(log_file)-1, "%s.%d", base_name_.c_str(), rotate_num_);
}else{
snprintf(log_file, sizeof(log_file)-1, "%s", base_name_.c_str());
}
remove(log_file);
//
//change the file name;
char *src=log_file_old;
char *dst=log_file;
char *tmp = NULL;
for (int i = rotate_num_ - 1; i >= 0; i--) {
if(i > 0){
snprintf(src, sizeof(log_file) -1, "%s.%d", base_name_.c_str(), i);
}else{
snprintf(src, sizeof(log_file) -1, "%s", base_name_.c_str());
}
rename(src,dst);
tmp = dst;
dst = src;
src = tmp;
}
}
int RotateLogger::Reopen()
{
CloseFile();
int fd = open(base_name_.c_str(), O_CREAT|O_APPEND|O_WRONLY, 0777);
if (fd < 0) {
if(stderr_redirect_){
dup2(redirect_fd_old_, STDERR_FD);
}
return ERROR_CODE_SYSTEM;
}else{
if(stderr_redirect_){
dup2(fd, STDERR_FD);
}
}
fd_ = fd;
return 0;
}
void RotateLogger::CloseFile()
{
if(fd_ >= 0){
::close(fd_);
fd_ = -1;
}
}
}
<|endoftext|> |
<commit_before>#include <QDebug>
#include <QDateTime>
#include <QMap>
#include <QString>
#include <QStringList>
#include <QDesktopServices>
#include "o2gft.h"
static const char *GftScope = "https://www.googleapis.com/auth/fusiontables";
static const char *GftEndpoint = "https://accounts.google.com/o/oauth2/auth";
static const char *GftTokenUrl = "https://accounts.google.com/o/oauth2/token";
static const char *GftRefreshUrl = "https://accounts.google.com/o/oauth2/token";
O2Gft::O2Gft(QObject *parent): O2(parent) {
setRequestUrl(GftEndpoint);
setTokenUrl(GftTokenUrl);
setRefreshTokenUrl(GftRefresUrl);
setScope(GftScope);
}
<commit_msg>...and fix typo<commit_after>#include <QDebug>
#include <QDateTime>
#include <QMap>
#include <QString>
#include <QStringList>
#include <QDesktopServices>
#include "o2gft.h"
static const char *GftScope = "https://www.googleapis.com/auth/fusiontables";
static const char *GftEndpoint = "https://accounts.google.com/o/oauth2/auth";
static const char *GftTokenUrl = "https://accounts.google.com/o/oauth2/token";
static const char *GftRefreshUrl = "https://accounts.google.com/o/oauth2/token";
O2Gft::O2Gft(QObject *parent): O2(parent) {
setRequestUrl(GftEndpoint);
setTokenUrl(GftTokenUrl);
setRefreshTokenUrl(GftRefreshUrl);
setScope(GftScope);
}
<|endoftext|> |
<commit_before>#ifndef TATUM_COMMON_ANALYSIS_VISITOR_HPP
#define TATUM_COMMON_ANALYSIS_VISITOR_HPP
#include "tatum_error.hpp"
#include "TimingGraph.hpp"
#include "TimingConstraints.hpp"
#include "TimingTags.hpp"
namespace tatum { namespace detail {
/** \file
*
* Common analysis functionality for both setup and hold analysis.
*/
/** \class CommonAnalysisVisitor
*
* A class satisfying the GraphVisitor concept, which contains common
* node and edge processing code used by both setup and hold analysis.
*
* \see GraphVisitor
*
* \tparam AnalysisOps a class defining the setup/hold specific operations
* \see SetupAnalysisOps
* \see HoldAnalysisOps
*/
template<class AnalysisOps>
class CommonAnalysisVisitor {
public:
CommonAnalysisVisitor(size_t num_tags)
: ops_(num_tags) { }
void do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id);
void do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id);
template<class DelayCalc>
void do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id);
template<class DelayCalc>
void do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id);
void reset() { ops_.reset(); }
protected:
AnalysisOps ops_;
private:
template<class DelayCalc>
void do_arrival_traverse_edge(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id);
template<class DelayCalc>
void do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id);
bool should_propagate_clock_arr(const TimingGraph& tg, const TimingConstraints& tc, const EdgeId edge_id) const;
bool is_clock_data_edge(const TimingGraph& tg, const EdgeId edge_id) const;
};
/*
* Pre-traversal
*/
template<class AnalysisOps>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) {
//Logical Input
TATUM_ASSERT_MSG(tg.node_in_edges(node_id).size() == 0, "Logical input has input edges: timing graph not levelized.");
NodeType node_type = tg.node_type(node_id);
//We don't propagate any tags from constant generators,
//since they do not effect the dynamic timing behaviour of the
//system
if(tc.node_is_constant_generator(node_id)) return;
if(tc.node_is_clock_source(node_id)) {
//Generate the appropriate clock tag
//Note that we assume that edge counting has set the effective period constraint assuming a
//launch edge at time zero. This means we don't need to do anything special for clocks
//with rising edges after time zero.
TATUM_ASSERT_MSG(ops_.get_clock_tags(node_id).num_tags() == 0, "Clock source already has clock tags");
//Find it's domain
DomainId domain_id = tc.node_clock_domain(node_id);
TATUM_ASSERT(domain_id);
//Initialize a clock tag with zero arrival, invalid required time
TimingTag clock_tag = TimingTag(Time(0.), Time(NAN), domain_id, node_id);
//Add the tag
ops_.get_clock_tags(node_id).add_tag(clock_tag);
} else {
TATUM_ASSERT(node_type == NodeType::SOURCE);
//A standard primary input, generate the appropriate data tag
//We assume input delays are on the arc from INPAD_SOURCE to INPAD_OPIN,
//so we do not need to account for it directly in the arrival time of INPAD_SOURCES
TATUM_ASSERT_MSG(ops_.get_data_tags(node_id).num_tags() == 0, "Primary input already has data tags");
DomainId domain_id = tc.node_clock_domain(node_id);
TATUM_ASSERT(domain_id);
//Initialize a data tag with zero arrival, invalid required time
TimingTag input_tag = TimingTag(Time(0.), Time(NAN), domain_id, node_id);
ops_.get_data_tags(node_id).add_tag(input_tag);
}
}
template<class AnalysisOps>
void CommonAnalysisVisitor<AnalysisOps>::do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) {
TimingTags& node_data_tags = ops_.get_data_tags(node_id);
TimingTags& node_clock_tags = ops_.get_clock_tags(node_id);
/*
* Calculate required times
*/
TATUM_ASSERT(tg.node_type(node_id) == NodeType::SINK);
//Sinks corresponding to FF sinks will have propagated (capturing) clock tags,
//while those corresponding to outpads will not. We initialize the outpad
//capturing clock tags based on the constraints
if(node_clock_tags.empty()) {
//Initialize the clock tags based on the constraints.
auto output_constraints = tc.output_constraints(node_id);
if(output_constraints.empty()) {
//throw tatum::Error("Output unconstrained");
std::cerr << "Warning: Timing graph " << node_id << " " << tg.node_type(node_id);
std::cerr << " has no incomming clock tags, and no output constraint. No required time will be calculated\n";
} else {
for(auto constraint : output_constraints) {
//TODO: use real constraint value when output delay no-longer on edges
TimingTag constraint_tag = TimingTag(Time(0.), Time(NAN), constraint.second.domain, node_id);
node_clock_tags.add_tag(constraint_tag);
}
}
}
//At this the sink will have a capturing clock tag defined
//Determine the required time at this sink
//
//We need to generate a required time for each clock domain for which there is a data
//arrival time at this node, while considering all possible clocks that could drive
//this node (i.e. take the most restrictive constraint accross all clock tags at this
//node)
for(TimingTag& node_data_tag : node_data_tags) {
for(const TimingTag& node_clock_tag : node_clock_tags) {
//Should we be analyzing paths between these two domains?
if(tc.should_analyze(node_data_tag.clock_domain(), node_clock_tag.clock_domain())) {
//We only set a required time if the source domain actually reaches this sink
//domain. This is indicated by having a valid arrival time.
if(node_data_tag.arr_time().valid()) {
float clock_constraint = ops_.clock_constraint(tc, node_data_tag.clock_domain(),
node_clock_tag.clock_domain());
//Update the required time. This will keep the most restrictive constraint.
ops_.merge_req_tag(node_data_tag, node_clock_tag.arr_time() + Time(clock_constraint), node_data_tag);
}
}
}
}
}
/*
* Arrival Time Operations
*/
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, NodeId node_id) {
//Do not propagate arrival tags through constant generators
if(tc.node_is_constant_generator(node_id)) return;
//Pull from upstream sources to current node
for(EdgeId edge_id : tg.node_in_edges(node_id)) {
do_arrival_traverse_edge(tg, tc, dc, node_id, edge_id);
}
}
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_edge(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) {
//We must use the tags by reference so we don't accidentally wipe-out any
//existing tags
TimingTags& node_data_tags = ops_.get_data_tags(node_id);
TimingTags& node_clock_tags = ops_.get_clock_tags(node_id);
//Pulling values from upstream source node
NodeId src_node_id = tg.edge_src_node(edge_id);
const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id);
const TimingTags& src_clk_tags = ops_.get_clock_tags(src_node_id);
const TimingTags& src_data_tags = ops_.get_data_tags(src_node_id);
/*
* Clock tags
*/
if(should_propagate_clock_arr(tg, tc, edge_id)) {
//Propagate the clock tags through the clock network
for(const TimingTag& src_clk_tag : src_clk_tags) {
//Standard propagation through the clock network
ops_.merge_arr_tags(node_clock_tags, src_clk_tag.arr_time() + edge_delay, src_clk_tag);
if(is_clock_data_edge(tg, edge_id)) {
//We convert the clock arrival time to a data
//arrival time at this node (since the clock's
//arrival launches the data).
TATUM_ASSERT(tg.node_type(node_id) == NodeType::SOURCE);
//Make a copy of the tag
TimingTag launch_tag = src_clk_tag;
//Update the launch node, since the data is
//launching from this node
launch_tag.set_launch_node(node_id);
//Mark propagated launch time as a DATA tag
ops_.merge_arr_tags(node_data_tags, launch_tag.arr_time() + edge_delay, launch_tag);
}
}
}
/*
* Data tags
*/
for(const TimingTag& src_data_tag : src_data_tags) {
//Standard data-path propagation
ops_.merge_arr_tags(node_data_tags, src_data_tag.arr_time() + edge_delay, src_data_tag);
}
}
/*
* Required Time Operations
*/
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id) {
//Do not propagate required tags through constant generators
if(tc.node_is_constant_generator(node_id)) return;
//Pull from downstream sinks to current node
for(EdgeId edge_id : tg.node_out_edges(node_id)) {
do_required_traverse_edge(tg, dc, node_id, edge_id);
}
}
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) {
//We must use the tags by reference so we don't accidentally wipe-out any
//existing tags
TimingTags& node_data_tags = ops_.get_data_tags(node_id);
//Pulling values from downstream sink node
NodeId sink_node_id = tg.edge_sink_node(edge_id);
const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id);
const TimingTags& sink_data_tags = ops_.get_data_tags(sink_node_id);
for(const TimingTag& sink_tag : sink_data_tags) {
//We only propogate the required time if we have a valid arrival time
auto matched_tag_iter = node_data_tags.find_tag_by_clock_domain(sink_tag.clock_domain());
if(matched_tag_iter != node_data_tags.end() && matched_tag_iter->arr_time().valid()) {
//Valid arrival, update required
ops_.merge_req_tag(*matched_tag_iter, sink_tag.req_time() - edge_delay, sink_tag);
}
}
}
template<class AnalysisOps>
bool CommonAnalysisVisitor<AnalysisOps>::should_propagate_clock_arr(const TimingGraph& tg, const TimingConstraints& tc, const EdgeId edge_id) const {
NodeId src_node_id = tg.edge_src_node(edge_id);
//We want to propagate clock tags through the arbitrary nodes making up the clock network until
//we hit another source node (i.e. a FF's output source).
//
//To allow tags to propagte from the original source (i.e. the input clock pin) we also allow
//propagation from defined clock sources
NodeType src_node_type = tg.node_type(src_node_id);
if (src_node_type != NodeType::SOURCE) {
//Not a source, allow propagation
return true;
} else if (tc.node_is_clock_source(src_node_id)) {
//Base-case: the source is a clock source
TATUM_ASSERT_MSG(src_node_type == NodeType::SOURCE, "Only SOURCEs can be clock sources");
TATUM_ASSERT_MSG(tg.node_in_edges(src_node_id).empty(), "Clock sources should have no incoming edges");
return true;
}
return false;
}
template<class AnalysisOps>
bool CommonAnalysisVisitor<AnalysisOps>::is_clock_data_edge(const TimingGraph& tg, const EdgeId edge_id) const {
NodeId edge_src_node = tg.edge_src_node(edge_id);
NodeId edge_sink_node = tg.edge_sink_node(edge_id);
return (tg.node_type(edge_src_node) == NodeType::SINK) && (tg.node_type(edge_sink_node) == NodeType::SOURCE);
}
}} //namepsace
#endif
<commit_msg>Use I/O constraints directly<commit_after>#ifndef TATUM_COMMON_ANALYSIS_VISITOR_HPP
#define TATUM_COMMON_ANALYSIS_VISITOR_HPP
#include "tatum_error.hpp"
#include "TimingGraph.hpp"
#include "TimingConstraints.hpp"
#include "TimingTags.hpp"
namespace tatum { namespace detail {
/** \file
*
* Common analysis functionality for both setup and hold analysis.
*/
/** \class CommonAnalysisVisitor
*
* A class satisfying the GraphVisitor concept, which contains common
* node and edge processing code used by both setup and hold analysis.
*
* \see GraphVisitor
*
* \tparam AnalysisOps a class defining the setup/hold specific operations
* \see SetupAnalysisOps
* \see HoldAnalysisOps
*/
template<class AnalysisOps>
class CommonAnalysisVisitor {
public:
CommonAnalysisVisitor(size_t num_tags)
: ops_(num_tags) { }
void do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id);
void do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id);
template<class DelayCalc>
void do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id);
template<class DelayCalc>
void do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id);
void reset() { ops_.reset(); }
protected:
AnalysisOps ops_;
private:
template<class DelayCalc>
void do_arrival_traverse_edge(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id);
template<class DelayCalc>
void do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id);
bool should_propagate_clock_arr(const TimingGraph& tg, const TimingConstraints& tc, const EdgeId edge_id) const;
bool is_clock_data_edge(const TimingGraph& tg, const EdgeId edge_id) const;
};
/*
* Pre-traversal
*/
template<class AnalysisOps>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) {
//Logical Input
TATUM_ASSERT_MSG(tg.node_in_edges(node_id).size() == 0, "Logical input has input edges: timing graph not levelized.");
NodeType node_type = tg.node_type(node_id);
//We don't propagate any tags from constant generators,
//since they do not effect the dynamic timing behaviour of the
//system
if(tc.node_is_constant_generator(node_id)) return;
if(tc.node_is_clock_source(node_id)) {
//Generate the appropriate clock tag
TATUM_ASSERT_MSG(ops_.get_clock_tags(node_id).num_tags() == 0, "Clock source already has clock tags");
//Find it's domain
DomainId domain_id = tc.node_clock_domain(node_id);
TATUM_ASSERT(domain_id);
//Initialize a clock tag with zero arrival, invalid required time
//
//Note: we assume that edge counting has set the effective period constraint assuming a
//launch edge at time zero. This means we don't need to do anything special for clocks
//with rising edges after time zero.
TimingTag clock_tag = TimingTag(Time(0.), Time(NAN), domain_id, node_id);
//Add the tag
ops_.get_clock_tags(node_id).add_tag(clock_tag);
} else {
TATUM_ASSERT(node_type == NodeType::SOURCE);
//A standard primary input, generate the appropriate data tag
//We assume input delays are on the arc from INPAD_SOURCE to INPAD_OPIN,
//so we do not need to account for it directly in the arrival time of INPAD_SOURCES
TATUM_ASSERT_MSG(ops_.get_data_tags(node_id).num_tags() == 0, "Primary input already has data tags");
DomainId domain_id = tc.node_clock_domain(node_id);
TATUM_ASSERT(domain_id);
float input_constraint = tc.input_constraint(node_id, domain_id);
TATUM_ASSERT(!isnan(input_constraint));
//Initialize a data tag based on input delay constraint, invalid required time
TimingTag input_tag = TimingTag(Time(input_constraint), Time(NAN), domain_id, node_id);
ops_.get_data_tags(node_id).add_tag(input_tag);
}
}
template<class AnalysisOps>
void CommonAnalysisVisitor<AnalysisOps>::do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) {
TimingTags& node_data_tags = ops_.get_data_tags(node_id);
TimingTags& node_clock_tags = ops_.get_clock_tags(node_id);
/*
* Calculate required times
*/
TATUM_ASSERT(tg.node_type(node_id) == NodeType::SINK);
//Sinks corresponding to FF sinks will have propagated (capturing) clock tags,
//while those corresponding to outpads will not. We initialize the outpad
//capturing clock tags based on the constraints
if(node_clock_tags.empty()) {
//Initialize the clock tags based on the constraints.
auto output_constraints = tc.output_constraints(node_id);
if(output_constraints.empty()) {
//throw tatum::Error("Output unconstrained");
std::cerr << "Warning: Timing graph " << node_id << " " << tg.node_type(node_id);
std::cerr << " has no incomming clock tags, and no output constraint. No required time will be calculated\n";
} else {
DomainId domain_id = tc.node_clock_domain(node_id);
TATUM_ASSERT(domain_id);
float output_constraint = tc.output_constraint(node_id, domain_id);
TATUM_ASSERT(!isnan(output_constraint));
for(auto constraint : output_constraints) {
//TODO: use real constraint value when output delay no-longer on edges
TimingTag constraint_tag = TimingTag(Time(output_constraint), Time(NAN), constraint.second.domain, node_id);
node_clock_tags.add_tag(constraint_tag);
}
}
}
//At this the sink will have a capturing clock tag defined
//Determine the required time at this sink
//
//We need to generate a required time for each clock domain for which there is a data
//arrival time at this node, while considering all possible clocks that could drive
//this node (i.e. take the most restrictive constraint accross all clock tags at this
//node)
for(TimingTag& node_data_tag : node_data_tags) {
for(const TimingTag& node_clock_tag : node_clock_tags) {
//Should we be analyzing paths between these two domains?
if(tc.should_analyze(node_data_tag.clock_domain(), node_clock_tag.clock_domain())) {
//We only set a required time if the source domain actually reaches this sink
//domain. This is indicated by having a valid arrival time.
if(node_data_tag.arr_time().valid()) {
float clock_constraint = ops_.clock_constraint(tc, node_data_tag.clock_domain(),
node_clock_tag.clock_domain());
//Update the required time. This will keep the most restrictive constraint.
ops_.merge_req_tag(node_data_tag, node_clock_tag.arr_time() + Time(clock_constraint), node_data_tag);
}
}
}
}
}
/*
* Arrival Time Operations
*/
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, NodeId node_id) {
//Do not propagate arrival tags through constant generators
if(tc.node_is_constant_generator(node_id)) return;
//Pull from upstream sources to current node
for(EdgeId edge_id : tg.node_in_edges(node_id)) {
do_arrival_traverse_edge(tg, tc, dc, node_id, edge_id);
}
}
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_traverse_edge(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) {
//We must use the tags by reference so we don't accidentally wipe-out any
//existing tags
TimingTags& node_data_tags = ops_.get_data_tags(node_id);
TimingTags& node_clock_tags = ops_.get_clock_tags(node_id);
//Pulling values from upstream source node
NodeId src_node_id = tg.edge_src_node(edge_id);
const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id);
const TimingTags& src_clk_tags = ops_.get_clock_tags(src_node_id);
const TimingTags& src_data_tags = ops_.get_data_tags(src_node_id);
/*
* Clock tags
*/
if(should_propagate_clock_arr(tg, tc, edge_id)) {
//Propagate the clock tags through the clock network
for(const TimingTag& src_clk_tag : src_clk_tags) {
//Standard propagation through the clock network
ops_.merge_arr_tags(node_clock_tags, src_clk_tag.arr_time() + edge_delay, src_clk_tag);
if(is_clock_data_edge(tg, edge_id)) {
//We convert the clock arrival time to a data
//arrival time at this node (since the clock's
//arrival launches the data).
TATUM_ASSERT(tg.node_type(node_id) == NodeType::SOURCE);
//Make a copy of the tag
TimingTag launch_tag = src_clk_tag;
//Update the launch node, since the data is
//launching from this node
launch_tag.set_launch_node(node_id);
//Mark propagated launch time as a DATA tag
ops_.merge_arr_tags(node_data_tags, launch_tag.arr_time() + edge_delay, launch_tag);
}
}
}
/*
* Data tags
*/
for(const TimingTag& src_data_tag : src_data_tags) {
//Standard data-path propagation
ops_.merge_arr_tags(node_data_tags, src_data_tag.arr_time() + edge_delay, src_data_tag);
}
}
/*
* Required Time Operations
*/
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalc& dc, const NodeId node_id) {
//Do not propagate required tags through constant generators
if(tc.node_is_constant_generator(node_id)) return;
//Pull from downstream sinks to current node
for(EdgeId edge_id : tg.node_out_edges(node_id)) {
do_required_traverse_edge(tg, dc, node_id, edge_id);
}
}
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_required_traverse_edge(const TimingGraph& tg, const DelayCalc& dc, const NodeId node_id, const EdgeId edge_id) {
//We must use the tags by reference so we don't accidentally wipe-out any
//existing tags
TimingTags& node_data_tags = ops_.get_data_tags(node_id);
//Pulling values from downstream sink node
NodeId sink_node_id = tg.edge_sink_node(edge_id);
const Time& edge_delay = ops_.edge_delay(dc, tg, edge_id);
const TimingTags& sink_data_tags = ops_.get_data_tags(sink_node_id);
for(const TimingTag& sink_tag : sink_data_tags) {
//We only propogate the required time if we have a valid arrival time
auto matched_tag_iter = node_data_tags.find_tag_by_clock_domain(sink_tag.clock_domain());
if(matched_tag_iter != node_data_tags.end() && matched_tag_iter->arr_time().valid()) {
//Valid arrival, update required
ops_.merge_req_tag(*matched_tag_iter, sink_tag.req_time() - edge_delay, sink_tag);
}
}
}
template<class AnalysisOps>
bool CommonAnalysisVisitor<AnalysisOps>::should_propagate_clock_arr(const TimingGraph& tg, const TimingConstraints& tc, const EdgeId edge_id) const {
NodeId src_node_id = tg.edge_src_node(edge_id);
//We want to propagate clock tags through the arbitrary nodes making up the clock network until
//we hit another source node (i.e. a FF's output source).
//
//To allow tags to propagte from the original source (i.e. the input clock pin) we also allow
//propagation from defined clock sources
NodeType src_node_type = tg.node_type(src_node_id);
if (src_node_type != NodeType::SOURCE) {
//Not a source, allow propagation
return true;
} else if (tc.node_is_clock_source(src_node_id)) {
//Base-case: the source is a clock source
TATUM_ASSERT_MSG(src_node_type == NodeType::SOURCE, "Only SOURCEs can be clock sources");
TATUM_ASSERT_MSG(tg.node_in_edges(src_node_id).empty(), "Clock sources should have no incoming edges");
return true;
}
return false;
}
template<class AnalysisOps>
bool CommonAnalysisVisitor<AnalysisOps>::is_clock_data_edge(const TimingGraph& tg, const EdgeId edge_id) const {
NodeId edge_src_node = tg.edge_src_node(edge_id);
NodeId edge_sink_node = tg.edge_sink_node(edge_id);
return (tg.node_type(edge_src_node) == NodeType::SINK) && (tg.node_type(edge_sink_node) == NodeType::SOURCE);
}
}} //namepsace
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <modules/autonavigation/avoidcollisioncurve.h>
#include <modules/autonavigation/helperfunctions.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scene.h>
#include <openspace/query/query.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>
#include <algorithm>
#include <vector>
namespace {
constexpr const char* _loggerCat = "AvoidCollisionCurve";
const double Epsilon = 1E-7;
// TODO: move this list somewhere else
const std::vector<std::string> RelevantTags{
"planet_solarSystem",
"moon_solarSystem"
// TODO
};
} // namespace
namespace openspace::autonavigation {
AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end) {
// default rotation interpolation
_rotationInterpolator = RotationInterpolator{ start, end, this, Slerp };
_points.push_back(start.position());
_points.push_back(end.position());
std::vector<SceneGraphNode*> relevantNodes = findRelevantNodes();
// Create extra points to avoid collision
removeCollisions(relevantNodes);
int nrSegments = _points.size() - 1;
// default values for the curve parameter - equally spaced
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
_parameterIntervals.push_back(t);
}
_length = arcLength(1.0);
initParameterIntervals();
}
// Interpolate a list of control points and knot times
glm::dvec3 AvoidCollisionCurve::positionAt(double u) {
return interpolatePoints(u);
}
std::vector<SceneGraphNode*> AvoidCollisionCurve::findRelevantNodes() {
// TODO: make more efficient
const std::vector<SceneGraphNode*>& allNodes =
global::renderEngine.scene()->allSceneGraphNodes();
auto isRelevant = [](const SceneGraphNode* node) {
// does the node match any of the relevant tags?
const std::vector<std::string> tags = node->tags();
auto result = std::find_first_of(RelevantTags.begin(), RelevantTags.end(), tags.begin(), tags.end());
// does not match any tags => not interesting
if (result == RelevantTags.end()) {
return false;
}
return node->renderable() && (node->boundingSphere() > 0.0);
};
std::vector<SceneGraphNode*> result{};
std::copy_if(allNodes.begin(), allNodes.end(), std::back_inserter(result), isRelevant);
return result;
}
void AvoidCollisionCurve::removeCollisions(std::vector<SceneGraphNode*>& relevantNodes, int step) {
int nrSegments = _points.size() - 1;
int maxSteps = 10;
// TODO: handle better / present warning if early out
if (step > maxSteps) return;
// go through all segments and check for collisions
for (int i = 0; i < nrSegments; ++i) {
const glm::dvec3 lineStart = _points[i];
const glm::dvec3 lineEnd = _points[i + 1];
for (SceneGraphNode* node : relevantNodes) {
// do collision check in relative coordinates, to avoid huge numbers
const glm::dmat4 modelTransform = node->modelTransform();
glm::dvec3 p1 = glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0);
glm::dvec3 p2 = glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0);
// sphere to check for collision
double bs = node->boundingSphere();
double radius = bs;
// TODO: add a buffer (i.e. sue a little larger sphere), when we have
// behaviour for leaving a target. Don't want to pass too close to objects
glm::dvec3 center = glm::dvec3(0.0, 0.0, 0.0);
glm::dvec3 point;
bool collision = helpers::lineSphereIntersection(p1, p2, center, radius, point);
// convert back to world coordinates
glm::dvec3 pointWorld = modelTransform * glm::dvec4(point, 1.0);
if (collision) {
LINFO(fmt::format("Collision with node: {}!", node->identifier()));
// to avoid collision, take a step in an orhtogonal direction of the
// collision point and add a new point
glm::dvec3 lineDir = glm::normalize(lineEnd - lineStart);
glm::dvec3 nodePos = node->worldPosition();
glm::dvec3 collisionPointToCenter = nodePos - pointWorld;
glm::dvec3 parallell = glm::proj(collisionPointToCenter, lineDir);
glm::dvec3 orthogonal = collisionPointToCenter - parallell;
double distance = 2.0 * radius;
glm::dvec3 extraKnot = pointWorld - distance * glm::normalize(orthogonal);
_points.insert(_points.begin() + i + 1, extraKnot);
// TODO: maybe make this more efficient, and make sure that we have a base case.
removeCollisions(relevantNodes, ++step);
break;
}
}
}
}
// compute curve parameter intervals based on relative arc length
void AvoidCollisionCurve::initParameterIntervals() {
std::vector<double> newIntervals;
int nrSegments = _points.size() - 1;
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
newIntervals.push_back(arcLength(t) / _length);
}
_parameterIntervals.swap(newIntervals);
}
// Catmull-Rom inspired interpolation of the curve points
glm::dvec3 AvoidCollisionCurve::interpolatePoints(double u)
{
ghoul_assert(_points.size() == _parameterIntervals.size(),
"Must have equal number of points and times!");
ghoul_assert(_points.size() > 2, "Minimum of two control points needed for interpolation!");
size_t nrSegments = _points.size() - 1;
const glm::dvec3 start = _points.front();
const glm::dvec3 end = _points.back();
if (u <= 0.0) return _points.front();
if (u >= 1.0) return _points.back();
if (nrSegments == 1) {
return roundedSpline(u, start, start, end, end);
}
// compute current segment index
std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(_parameterIntervals.begin(), _parameterIntervals.end(), u);
unsigned int idx = (segmentEndIt - 1) - _parameterIntervals.begin();
double segmentStart = _parameterIntervals[idx];
double segmentDuration = (_parameterIntervals[idx + 1] - _parameterIntervals[idx]);
double tScaled = (u - segmentStart) / segmentDuration;
glm::dvec3 first = (idx == 0) ? start : _points[idx - 1];
glm::dvec3 last = (idx == (nrSegments - 1)) ? end : _points[idx + 2];
return roundedSpline(tScaled, first, _points[idx], _points[idx + 1], last);
}
glm::dvec3 AvoidCollisionCurve::roundedSpline(double t, const glm::dvec3 &a,
const glm::dvec3 &b, const glm::dvec3 &c, const glm::dvec3 &d)
{
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
if (t <= 0.0) return b;
if (t >= 1.0) return c;
auto isNormalizable = [](const glm::dvec3 v) {
return !(abs(glm::length(v)) < Epsilon);
};
// find velocities at b and c
glm::dvec3 cb = c - b;
glm::dvec3 bc = -cb;
if (!isNormalizable(cb)) {
return b;
}
glm::dvec3 ab = a - b;
// a and b are the same point
if (!isNormalizable(ab)) {
ab = bc;
}
glm::dvec3 bVelocity = glm::normalize(cb) - glm::normalize(ab);
bVelocity = isNormalizable(bVelocity) ?
glm::normalize(bVelocity) : glm::dvec3(0.0, 1.0, 0.0);
glm::dvec3 dc = d - c;
// d and c are the same point
if (!isNormalizable(dc)) {
dc = cb;
}
glm::dvec3 cVelocity = glm::normalize(dc) - glm::normalize(bc);
cVelocity = isNormalizable(cVelocity) ?
glm::normalize(cVelocity) : glm::dvec3(0.0, 1.0, 0.0);
double cbDistance = glm::length(cb);
double tangetLength = cbDistance;
// Distances in space can be extremely large, so we dont want the tangents to always have the full length.
const double tangentlengthThreshold = 1E10; // TODO: What's a good threshold?? ALSO make global
if (tangetLength > tangentlengthThreshold)
tangetLength = tangentlengthThreshold;
// the resulting curve gets much better and more predictable when using a genric
// hermite curve compared to the Catmull Rom implementation
return interpolation::hermite(t, b, c, bVelocity * tangetLength, cVelocity * tangetLength);
//return interpolation::catmullRom(t, b - bVelocity * cbDistance, b, c, c + cVelocity * cbDistance);
}
} // namespace openspace::autonavigation
<commit_msg>Go out point added for near planet cases<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2019 *
* *
* 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 <modules/autonavigation/avoidcollisioncurve.h>
#include <modules/autonavigation/helperfunctions.h>
#include <openspace/engine/globals.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scene.h>
#include <openspace/query/query.h>
#include <ghoul/logging/logmanager.h>
#include <glm/gtx/projection.hpp>
#include <algorithm>
#include <vector>
namespace {
constexpr const char* _loggerCat = "AvoidCollisionCurve";
const double Epsilon = 1E-7;
// TODO: move this list somewhere else
const std::vector<std::string> RelevantTags{
"planet_solarSystem",
"moon_solarSystem"
// TODO
};
} // namespace
namespace openspace::autonavigation {
AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& end) {
// default rotation interpolation
_rotationInterpolator = RotationInterpolator{ start, end, this, Slerp };
_points.push_back(start.position());
// Add a point to first go straight out if starting close to planet
double thresholdFactor = 3.0;
glm::dvec3 startNodePos = start.node()->worldPosition();
double startNodeRadius = start.nodeDetails.validBoundingSphere;
glm::dvec3 startNodeToStartPos = start.position() - startNodePos;
if (glm::length(startNodeToStartPos) < thresholdFactor * startNodeRadius) {
glm::dvec3 viewDir = glm::normalize(start.rotation() * glm::dvec3(0.0, 0.0, -1.0));
double distance = startNodeRadius;
glm::dvec3 newPos = start.position() - distance * viewDir;
_points.push_back(newPos);
}
// TODO: Add a point to approach straigt towards a specific pose near planet
// TODO: Calculate nice end pose if not defined
_points.push_back(end.position());
std::vector<SceneGraphNode*> relevantNodes = findRelevantNodes();
// Create extra points to avoid collision
removeCollisions(relevantNodes);
int nrSegments = _points.size() - 1;
// default values for the curve parameter - equally spaced
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
_parameterIntervals.push_back(t);
}
_length = arcLength(1.0);
initParameterIntervals();
}
// Interpolate a list of control points and knot times
glm::dvec3 AvoidCollisionCurve::positionAt(double u) {
return interpolatePoints(u);
}
std::vector<SceneGraphNode*> AvoidCollisionCurve::findRelevantNodes() {
// TODO: make more efficient
const std::vector<SceneGraphNode*>& allNodes =
global::renderEngine.scene()->allSceneGraphNodes();
auto isRelevant = [](const SceneGraphNode* node) {
// does the node match any of the relevant tags?
const std::vector<std::string> tags = node->tags();
auto result = std::find_first_of(RelevantTags.begin(), RelevantTags.end(), tags.begin(), tags.end());
// does not match any tags => not interesting
if (result == RelevantTags.end()) {
return false;
}
return node->renderable() && (node->boundingSphere() > 0.0);
};
std::vector<SceneGraphNode*> result{};
std::copy_if(allNodes.begin(), allNodes.end(), std::back_inserter(result), isRelevant);
return result;
}
void AvoidCollisionCurve::removeCollisions(std::vector<SceneGraphNode*>& relevantNodes, int step) {
int nrSegments = _points.size() - 1;
int maxSteps = 10;
// TODO: handle better / present warning if early out
if (step > maxSteps) return;
// go through all segments and check for collisions
for (int i = 0; i < nrSegments; ++i) {
const glm::dvec3 lineStart = _points[i];
const glm::dvec3 lineEnd = _points[i + 1];
for (SceneGraphNode* node : relevantNodes) {
// do collision check in relative coordinates, to avoid huge numbers
const glm::dmat4 modelTransform = node->modelTransform();
glm::dvec3 p1 = glm::inverse(modelTransform) * glm::dvec4(lineStart, 1.0);
glm::dvec3 p2 = glm::inverse(modelTransform) * glm::dvec4(lineEnd, 1.0);
// sphere to check for collision
double bs = node->boundingSphere();
double radius = bs;
// TODO: add a buffer (i.e. sue a little larger sphere), when we have
// behaviour for leaving a target. Don't want to pass too close to objects
glm::dvec3 center = glm::dvec3(0.0, 0.0, 0.0);
glm::dvec3 point;
bool collision = helpers::lineSphereIntersection(p1, p2, center, radius, point);
// convert back to world coordinates
glm::dvec3 pointWorld = modelTransform * glm::dvec4(point, 1.0);
if (collision) {
LINFO(fmt::format("Collision with node: {}!", node->identifier()));
// to avoid collision, take a step in an orhtogonal direction of the
// collision point and add a new point
glm::dvec3 lineDir = glm::normalize(lineEnd - lineStart);
glm::dvec3 nodePos = node->worldPosition();
glm::dvec3 collisionPointToCenter = nodePos - pointWorld;
glm::dvec3 parallell = glm::proj(collisionPointToCenter, lineDir);
glm::dvec3 orthogonal = collisionPointToCenter - parallell;
double distance = 3.0 * radius;
glm::dvec3 extraKnot = pointWorld - distance * glm::normalize(orthogonal);
_points.insert(_points.begin() + i + 1, extraKnot);
// TODO: maybe make this more efficient, and make sure that we have a base case.
removeCollisions(relevantNodes, ++step);
break;
}
}
}
}
// compute curve parameter intervals based on relative arc length
void AvoidCollisionCurve::initParameterIntervals() {
std::vector<double> newIntervals;
int nrSegments = _points.size() - 1;
for (double t = 0.0; t <= 1.0; t += 1.0 / (double)nrSegments) {
newIntervals.push_back(arcLength(t) / _length);
}
_parameterIntervals.swap(newIntervals);
}
// Catmull-Rom inspired interpolation of the curve points
glm::dvec3 AvoidCollisionCurve::interpolatePoints(double u)
{
ghoul_assert(_points.size() == _parameterIntervals.size(),
"Must have equal number of points and times!");
ghoul_assert(_points.size() > 2, "Minimum of two control points needed for interpolation!");
size_t nrSegments = _points.size() - 1;
const glm::dvec3 start = _points.front();
const glm::dvec3 end = _points.back();
if (u <= 0.0) return _points.front();
if (u >= 1.0) return _points.back();
if (nrSegments == 1) {
return roundedSpline(u, start, start, end, end);
}
// compute current segment index
std::vector<double>::const_iterator segmentEndIt =
std::lower_bound(_parameterIntervals.begin(), _parameterIntervals.end(), u);
unsigned int idx = (segmentEndIt - 1) - _parameterIntervals.begin();
double segmentStart = _parameterIntervals[idx];
double segmentDuration = (_parameterIntervals[idx + 1] - _parameterIntervals[idx]);
double tScaled = (u - segmentStart) / segmentDuration;
glm::dvec3 first = (idx == 0) ? start : _points[idx - 1];
glm::dvec3 last = (idx == (nrSegments - 1)) ? end : _points[idx + 2];
return roundedSpline(tScaled, first, _points[idx], _points[idx + 1], last);
}
glm::dvec3 AvoidCollisionCurve::roundedSpline(double t, const glm::dvec3 &a,
const glm::dvec3 &b, const glm::dvec3 &c, const glm::dvec3 &d)
{
ghoul_assert(t >= 0 && t <= 1.0, "Interpolation variable out of range [0, 1]");
if (t <= 0.0) return b;
if (t >= 1.0) return c;
auto isNormalizable = [](const glm::dvec3 v) {
return !(abs(glm::length(v)) < Epsilon);
};
// find velocities at b and c
glm::dvec3 cb = c - b;
glm::dvec3 bc = -cb;
if (!isNormalizable(cb)) {
return b;
}
glm::dvec3 ab = a - b;
// a and b are the same point
if (!isNormalizable(ab)) {
ab = bc;
}
glm::dvec3 bVelocity = glm::normalize(cb) - glm::normalize(ab);
bVelocity = isNormalizable(bVelocity) ?
glm::normalize(bVelocity) : glm::dvec3(0.0, 1.0, 0.0);
glm::dvec3 dc = d - c;
// d and c are the same point
if (!isNormalizable(dc)) {
dc = cb;
}
glm::dvec3 cVelocity = glm::normalize(dc) - glm::normalize(bc);
cVelocity = isNormalizable(cVelocity) ?
glm::normalize(cVelocity) : glm::dvec3(0.0, 1.0, 0.0);
double cbDistance = glm::length(cb);
double tangetLength = cbDistance;
// Distances in space can be extremely large, so we dont want the tangents to always have the full length.
const double tangentlengthThreshold = 1E10; // TODO: What's a good threshold?? ALSO make global
if (tangetLength > tangentlengthThreshold)
tangetLength = tangentlengthThreshold;
// the resulting curve gets much better and more predictable when using a genric
// hermite curve compared to the Catmull Rom implementation
return interpolation::hermite(t, b, c, bVelocity * tangetLength, cVelocity * tangetLength);
//return interpolation::catmullRom(t, b - bVelocity * cbDistance, b, c, c + cVelocity * cbDistance);
}
} // namespace openspace::autonavigation
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkTimeVaryingVelocityFieldIntegrationImageFilter.h"
#include "itkImportImageFilter.h"
int
itkTimeVaryingVelocityFieldIntegrationImageFilterTest(int, char *[])
{
/* First test with homogeneous and constant velocity field
*/
using VectorType = itk::Vector<double, 3>;
using DisplacementFieldType = itk::Image<VectorType, 3>;
using TimeVaryingVelocityFieldType = itk::Image<VectorType, 4>;
TimeVaryingVelocityFieldType::PointType origin;
origin.Fill(0.0);
TimeVaryingVelocityFieldType::SpacingType spacing;
spacing.Fill(2.0);
TimeVaryingVelocityFieldType::SizeType size;
size.Fill(25);
VectorType constantVelocity;
constantVelocity.Fill(0.1);
TimeVaryingVelocityFieldType::Pointer constantVelocityField = TimeVaryingVelocityFieldType::New();
constantVelocityField->SetOrigin(origin);
constantVelocityField->SetSpacing(spacing);
constantVelocityField->SetRegions(size);
constantVelocityField->Allocate();
constantVelocityField->FillBuffer(constantVelocity);
using IntegratorType =
itk::TimeVaryingVelocityFieldIntegrationImageFilter<TimeVaryingVelocityFieldType, DisplacementFieldType>;
IntegratorType::Pointer integrator = IntegratorType::New();
integrator->SetInput(constantVelocityField);
integrator->SetLowerTimeBound(0.3);
integrator->SetUpperTimeBound(0.75);
integrator->SetNumberOfIntegrationSteps(100);
integrator->Update();
integrator->Print(std::cout, 3);
DisplacementFieldType::IndexType index;
index.Fill(0);
VectorType displacement;
IntegratorType::Pointer inverseIntegrator = IntegratorType::New();
inverseIntegrator->SetInput(constantVelocityField);
inverseIntegrator->SetLowerTimeBound(1.0);
inverseIntegrator->SetUpperTimeBound(0.0);
inverseIntegrator->SetNumberOfIntegrationSteps(100);
inverseIntegrator->Update();
// This integration should result in a constant image of value
// -( 0.1 * 1.0 - ( 0.1 * 0.0 ) ) = -0.1 with ~epsilon deviation
// due to numerical computations
const DisplacementFieldType * inverseField = inverseIntegrator->GetOutput();
displacement = inverseField->GetPixel(index);
std::cout << "Estimated inverse displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] + 0.101852) > 0.01)
{
std::cerr << "Failed to produce the correct inverse integration." << std::endl;
return EXIT_FAILURE;
}
inverseIntegrator->Print(std::cout, 3);
std::cout << inverseIntegrator->GetNameOfClass() << std::endl;
// This integration should result in a constant image of value
// 0.75 * 0.1 - 0.3 * 0.1 = 0.045 with ~epsilon deviation
// due to numerical computations
const DisplacementFieldType * displacementField = integrator->GetOutput();
displacement = displacementField->GetPixel(index);
std::cout << "Estimated forward displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] - 0.045) > 0.0001)
{
std::cerr << "Failed to produce the correct forward integration." << std::endl;
return EXIT_FAILURE;
}
/* Second test with inhomogeneous and time-varying velocity field
*/
/* Generation of the velocity field defined by
* v(x, y, z, t) = z/(1+t) * ( -sin(z), cos(z), 1 )
* which can be analytically integrated giving the motion
* corresponding to the displacement field:
* Displacement(x0, y0, z0, t) =
* ( cos(z0*(1+t)) - 1, sin(z0*(1+t)), z0*(1+t) )
*/
using ImportFilterType = itk::ImportImageFilter<VectorType, 4>;
ImportFilterType::Pointer importFilter = ImportFilterType::New();
/* Size is made denser on the z and t coordinates, for which
* the velocity field is rapidly changing.
* The velocity field is homogeneous in the x-y plane.*/
size[0] = 3;
size[1] = 3;
size[2] = 401;
size[3] = 61;
ImportFilterType::IndexType start;
start.Fill(0);
ImportFilterType::RegionType region;
region.SetIndex(start);
region.SetSize(size);
importFilter->SetRegion(region);
origin.Fill(0.);
importFilter->SetOrigin(origin);
double spaceTimeSpan[4] = { 20., 20., 20., 1.5 };
for (unsigned int i = 0; i < 4; i++)
{
spacing[i] = spaceTimeSpan[i] / (size[i] - 1);
}
importFilter->SetSpacing(spacing);
const unsigned int numberOfPixels = size[0] * size[1] * size[2] * size[3];
auto * localBuffer = new VectorType[numberOfPixels];
VectorType * it = localBuffer;
for (unsigned int t = 0; t < size[3]; ++t)
{
for (unsigned int z = 0; z < size[2]; ++z)
{
const double zz = spacing[2] * z;
const double kappa = zz / (1 + spacing[3] * t);
for (unsigned int y = 0; y < size[1]; ++y)
{
for (unsigned int x = 0; x < size[0]; ++x, ++it)
{
(*it)[0] = -kappa * std::sin(zz);
(*it)[1] = kappa * std::cos(zz);
(*it)[2] = kappa;
}
}
}
}
const bool importImageFilterWillOwnTheBuffer = true;
importFilter->SetImportPointer(localBuffer, numberOfPixels, importImageFilterWillOwnTheBuffer);
TimeVaryingVelocityFieldType::Pointer timeVaryingVelocityField = importFilter->GetOutput();
integrator->SetInput(timeVaryingVelocityField);
integrator->SetLowerTimeBound(0.2);
integrator->SetUpperTimeBound(0.8);
/* This time bounds are meant to be absolute
* for the velocity field original time span [0, 1.5].
* Thus, we need to switch off the default rescaling
* to the normalized time span [0, 1] */
integrator->TimeBoundsAsRatesOff();
integrator->SetNumberOfIntegrationSteps(50);
integrator->Update();
integrator->Print(std::cout, 3);
index[0] = (size[0] - 1) / 2; // Corresponding to x = 10.
index[1] = (size[1] - 1) / 2; // Corresponding to y = 10.
index[2] = (size[2] - 1) / 10; // Corresponding to z = 2.
displacementField = integrator->GetOutput();
displacement = displacementField->GetPixel(index);
// The analytic result is displacement = ( cos(3) - cos(2), sin(3) - sin(2), 3 - 2 )
std::cout << "Estimated forward displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] + 0.5738) > 0.0002 || itk::Math::abs(displacement[1] + 0.7682) > 0.0001 ||
itk::Math::abs(displacement[2] - 1.0000) > 0.0001)
{
std::cerr << "Failed to produce the correct forward integration." << std::endl;
return EXIT_FAILURE;
}
/* The same integrator is used backwards in time. */
integrator->SetLowerTimeBound(1.0);
integrator->SetUpperTimeBound(0.0);
integrator->Update();
inverseField = integrator->GetOutput();
displacement = inverseField->GetPixel(index);
// The analytic result is displacement = ( cos(1) - cos(2), sin(1) - sin(2), 1 - 2 )
std::cout << "Estimated inverse displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] - 0.9564) > 0.0001 || itk::Math::abs(displacement[1] + 0.0678) > 0.0003 ||
itk::Math::abs(displacement[2] + 1.0000) > 0.0001)
{
std::cerr << "Failed to produce the correct inverse integration." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>STYLE: auto declarator when initializing with New()<commit_after>/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkTimeVaryingVelocityFieldIntegrationImageFilter.h"
#include "itkImportImageFilter.h"
int
itkTimeVaryingVelocityFieldIntegrationImageFilterTest(int, char *[])
{
/* First test with homogeneous and constant velocity field
*/
using VectorType = itk::Vector<double, 3>;
using DisplacementFieldType = itk::Image<VectorType, 3>;
using TimeVaryingVelocityFieldType = itk::Image<VectorType, 4>;
TimeVaryingVelocityFieldType::PointType origin;
origin.Fill(0.0);
TimeVaryingVelocityFieldType::SpacingType spacing;
spacing.Fill(2.0);
TimeVaryingVelocityFieldType::SizeType size;
size.Fill(25);
VectorType constantVelocity;
constantVelocity.Fill(0.1);
auto constantVelocityField = TimeVaryingVelocityFieldType::New();
constantVelocityField->SetOrigin(origin);
constantVelocityField->SetSpacing(spacing);
constantVelocityField->SetRegions(size);
constantVelocityField->Allocate();
constantVelocityField->FillBuffer(constantVelocity);
using IntegratorType =
itk::TimeVaryingVelocityFieldIntegrationImageFilter<TimeVaryingVelocityFieldType, DisplacementFieldType>;
auto integrator = IntegratorType::New();
integrator->SetInput(constantVelocityField);
integrator->SetLowerTimeBound(0.3);
integrator->SetUpperTimeBound(0.75);
integrator->SetNumberOfIntegrationSteps(100);
integrator->Update();
integrator->Print(std::cout, 3);
DisplacementFieldType::IndexType index;
index.Fill(0);
VectorType displacement;
auto inverseIntegrator = IntegratorType::New();
inverseIntegrator->SetInput(constantVelocityField);
inverseIntegrator->SetLowerTimeBound(1.0);
inverseIntegrator->SetUpperTimeBound(0.0);
inverseIntegrator->SetNumberOfIntegrationSteps(100);
inverseIntegrator->Update();
// This integration should result in a constant image of value
// -( 0.1 * 1.0 - ( 0.1 * 0.0 ) ) = -0.1 with ~epsilon deviation
// due to numerical computations
const DisplacementFieldType * inverseField = inverseIntegrator->GetOutput();
displacement = inverseField->GetPixel(index);
std::cout << "Estimated inverse displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] + 0.101852) > 0.01)
{
std::cerr << "Failed to produce the correct inverse integration." << std::endl;
return EXIT_FAILURE;
}
inverseIntegrator->Print(std::cout, 3);
std::cout << inverseIntegrator->GetNameOfClass() << std::endl;
// This integration should result in a constant image of value
// 0.75 * 0.1 - 0.3 * 0.1 = 0.045 with ~epsilon deviation
// due to numerical computations
const DisplacementFieldType * displacementField = integrator->GetOutput();
displacement = displacementField->GetPixel(index);
std::cout << "Estimated forward displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] - 0.045) > 0.0001)
{
std::cerr << "Failed to produce the correct forward integration." << std::endl;
return EXIT_FAILURE;
}
/* Second test with inhomogeneous and time-varying velocity field
*/
/* Generation of the velocity field defined by
* v(x, y, z, t) = z/(1+t) * ( -sin(z), cos(z), 1 )
* which can be analytically integrated giving the motion
* corresponding to the displacement field:
* Displacement(x0, y0, z0, t) =
* ( cos(z0*(1+t)) - 1, sin(z0*(1+t)), z0*(1+t) )
*/
using ImportFilterType = itk::ImportImageFilter<VectorType, 4>;
auto importFilter = ImportFilterType::New();
/* Size is made denser on the z and t coordinates, for which
* the velocity field is rapidly changing.
* The velocity field is homogeneous in the x-y plane.*/
size[0] = 3;
size[1] = 3;
size[2] = 401;
size[3] = 61;
ImportFilterType::IndexType start;
start.Fill(0);
ImportFilterType::RegionType region;
region.SetIndex(start);
region.SetSize(size);
importFilter->SetRegion(region);
origin.Fill(0.);
importFilter->SetOrigin(origin);
double spaceTimeSpan[4] = { 20., 20., 20., 1.5 };
for (unsigned int i = 0; i < 4; i++)
{
spacing[i] = spaceTimeSpan[i] / (size[i] - 1);
}
importFilter->SetSpacing(spacing);
const unsigned int numberOfPixels = size[0] * size[1] * size[2] * size[3];
auto * localBuffer = new VectorType[numberOfPixels];
VectorType * it = localBuffer;
for (unsigned int t = 0; t < size[3]; ++t)
{
for (unsigned int z = 0; z < size[2]; ++z)
{
const double zz = spacing[2] * z;
const double kappa = zz / (1 + spacing[3] * t);
for (unsigned int y = 0; y < size[1]; ++y)
{
for (unsigned int x = 0; x < size[0]; ++x, ++it)
{
(*it)[0] = -kappa * std::sin(zz);
(*it)[1] = kappa * std::cos(zz);
(*it)[2] = kappa;
}
}
}
}
const bool importImageFilterWillOwnTheBuffer = true;
importFilter->SetImportPointer(localBuffer, numberOfPixels, importImageFilterWillOwnTheBuffer);
TimeVaryingVelocityFieldType::Pointer timeVaryingVelocityField = importFilter->GetOutput();
integrator->SetInput(timeVaryingVelocityField);
integrator->SetLowerTimeBound(0.2);
integrator->SetUpperTimeBound(0.8);
/* This time bounds are meant to be absolute
* for the velocity field original time span [0, 1.5].
* Thus, we need to switch off the default rescaling
* to the normalized time span [0, 1] */
integrator->TimeBoundsAsRatesOff();
integrator->SetNumberOfIntegrationSteps(50);
integrator->Update();
integrator->Print(std::cout, 3);
index[0] = (size[0] - 1) / 2; // Corresponding to x = 10.
index[1] = (size[1] - 1) / 2; // Corresponding to y = 10.
index[2] = (size[2] - 1) / 10; // Corresponding to z = 2.
displacementField = integrator->GetOutput();
displacement = displacementField->GetPixel(index);
// The analytic result is displacement = ( cos(3) - cos(2), sin(3) - sin(2), 3 - 2 )
std::cout << "Estimated forward displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] + 0.5738) > 0.0002 || itk::Math::abs(displacement[1] + 0.7682) > 0.0001 ||
itk::Math::abs(displacement[2] - 1.0000) > 0.0001)
{
std::cerr << "Failed to produce the correct forward integration." << std::endl;
return EXIT_FAILURE;
}
/* The same integrator is used backwards in time. */
integrator->SetLowerTimeBound(1.0);
integrator->SetUpperTimeBound(0.0);
integrator->Update();
inverseField = integrator->GetOutput();
displacement = inverseField->GetPixel(index);
// The analytic result is displacement = ( cos(1) - cos(2), sin(1) - sin(2), 1 - 2 )
std::cout << "Estimated inverse displacement vector: " << displacement << std::endl;
if (itk::Math::abs(displacement[0] - 0.9564) > 0.0001 || itk::Math::abs(displacement[1] + 0.0678) > 0.0003 ||
itk::Math::abs(displacement[2] + 1.0000) > 0.0001)
{
std::cerr << "Failed to produce the correct inverse integration." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "./JPetSinogram.h"
#include <boost/numeric/ublas/matrix.hpp>
#include <vector>
#include <utility>
#include <cmath>
using namespace boost::numeric::ublas;
#define sang std::sqrt(2)/2
JPetSinogram::JPetSinogram() { }
JPetSinogram::~JPetSinogram() { }
/*! \brief Function returning vector of vectors with value of sinogram(180/views degree step and emissionMatrix.size1()/scans size) scaled to <min,max>
* \param emissionMatrix matrix, need to by NxN
* \param views number of views on object, degree step is calculated as (ang2 - ang1) / views
* \param scans number of scans on object, step is calculated as emissionMatrix.size(1) / scans
* \param nearest if true use nearest neighbour interpolation instead linear interpolation in calculation (Optional, default false)
* \param ang1 start angle for projection (Optional, default 0)
* \param ang2 end angle for projection (Optional, default 180)
* \param scaleResult if set to true, scale result to <min, max> (Optional, default false)
* \param min minimum value in returned sinogram (Optional, default 0)
* \param max maximum value in returned sinogram (Optional, default 255)
*/
std::vector<std::vector<double>> JPetSinogram::sinogram(matrix<int> emissionMatrix, int views, int scans,
bool nearest, float ang1, float ang2, bool scaleResult, int min, int max) {
assert(emissionMatrix.size1() == emissionMatrix.size2());
assert(emissionMatrix.size1() > 0);
assert(views > 0);
assert(scans > 0);
assert(min < max);
assert(ang1 < ang2);
//create vector of size views, initialize it with vector of size scans
std::vector<std::vector<double>> proj(views, std::vector<double>(scans));
std::unique_ptr<double[]> sintab(new double[views]);
std::unique_ptr<double[]> costab(new double[views]);
float phi = 0., stepsize = 0.;
stepsize = (ang2 - ang1) / views;
assert(stepsize > 0); //maybe != 0 ?
int i = 0;
for (phi = ang1; phi < ang2; phi = phi + stepsize) {
sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2);
costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2);
i++;
} i=0;
int scanNumber=0;
int inputMatrixSize = emissionMatrix.size1();
int x = 0, y = 0, Xcenter = 0, Ycenter = 0;
Xcenter = inputMatrixSize / 2;
Ycenter = inputMatrixSize / 2;
//if no. scans is greater than the image width, then scale will be <1
double scale = inputMatrixSize*1.42/scans;
int N=0;
double value = 0.;
double weight = 0.;
for (phi=ang1;phi<ang2;phi=phi+stepsize){
double a = -costab[i]/sintab[i];
double aa = 1/a;
if (std::abs(sintab[i]) > sang){
for (scanNumber=0;scanNumber<scans;scanNumber++){
N = scanNumber - scans/2;
double b = (N - costab[i] - sintab[i]) / sintab[i];
b = b * scale;
for (x = -Xcenter; x < Xcenter; x++){
if (nearest){ //nearest neighbour interpolation
y = (int) std::round(a*x + b);
if (y >= -Xcenter && y < Xcenter )
value += emissionMatrix((x+Xcenter),(y+Ycenter));
} else {
y = (int) std::round(a*x + b); //linear interpolation
weight = std::abs((a*x + b) - std::ceil(a*x + b));
if (y >= -Xcenter && y+1 < Xcenter )
value += (1-weight) * emissionMatrix((x+Xcenter),(y+Ycenter))
+ weight * emissionMatrix((x+Xcenter), (y+Ycenter+1));
}
} proj[i][scanNumber] = value/std::abs(sintab[i]); value=0;
}
}
if (std::abs(sintab[i]) <= sang){
for (scanNumber=0;scanNumber<scans;scanNumber++){
N = scanNumber - scans/2;
double bb = (N - costab[i] - sintab[i]) / costab[i];
bb = bb * scale;
for (y = -Ycenter; y < Ycenter; y++) {
if (nearest){ //nearest neighbour interpolation
x = (int) std::round(aa*y + bb);
if (x >= -Xcenter && x < Xcenter )
value += emissionMatrix(x+Xcenter, y+Ycenter);
} else { //linear interpolation
x = (int) std::round(aa*y + bb);
weight = std::abs((aa*y + bb) - std::ceil(aa*y + bb));
if (x >= -Xcenter && x+1 < Xcenter )
value += (1-weight) * emissionMatrix((x+Xcenter), (y+Ycenter))
+ weight * emissionMatrix((x+Xcenter+1), (y+Ycenter));
}
} proj[i][scanNumber] = value/std::abs(costab[i]); value=0;
}
} i++;
}
i=0;
if(scaleResult) {
double datamax = proj[0][0];
double datamin = proj[0][0];
for (unsigned int k = 0; k < proj.size(); k++ ) {
for (unsigned int j = 0; j < proj[0].size(); j++ ) {
if(proj[k][j] < min) proj[k][j] = min;
if(proj[k][j] > datamax) datamax = proj[k][j];
if(proj[k][j] < datamin) datamin = proj[k][j];
}
}
if(datamax == 0.)
datamax = 1.;
for (unsigned int k = 0; k < proj.size(); k++ ) {
for (unsigned int j = 0; j < proj[0].size(); j++ ) {
proj[k][j] = (double) ((proj[k][j]-datamin) * max/datamax);
}
}
}
return proj;
}<commit_msg>Change Xcenter/Ycenter to center variable<commit_after>#include "./JPetSinogram.h"
#include <boost/numeric/ublas/matrix.hpp>
#include <vector>
#include <utility>
#include <cmath>
using namespace boost::numeric::ublas;
#define sang std::sqrt(2)/2
JPetSinogram::JPetSinogram() { }
JPetSinogram::~JPetSinogram() { }
/*! \brief Function returning vector of vectors with value of sinogram(180/views degree step and emissionMatrix.size1()/scans size) scaled to <min,max>
* \param emissionMatrix matrix, need to by NxN
* \param views number of views on object, degree step is calculated as (ang2 - ang1) / views
* \param scans number of scans on object, step is calculated as emissionMatrix.size(1) / scans
* \param nearest if true use nearest neighbour interpolation instead linear interpolation in calculation (Optional, default false)
* \param ang1 start angle for projection (Optional, default 0)
* \param ang2 end angle for projection (Optional, default 180)
* \param scaleResult if set to true, scale result to <min, max> (Optional, default false)
* \param min minimum value in returned sinogram (Optional, default 0)
* \param max maximum value in returned sinogram (Optional, default 255)
*/
std::vector<std::vector<double>> JPetSinogram::sinogram(matrix<int> emissionMatrix, int views, int scans,
bool nearest, float ang1, float ang2, bool scaleResult, int min, int max) {
assert(emissionMatrix.size1() == emissionMatrix.size2());
assert(emissionMatrix.size1() > 0);
assert(views > 0);
assert(scans > 0);
assert(min < max);
assert(ang1 < ang2);
//create vector of size views, initialize it with vector of size scans
std::vector<std::vector<double>> proj(views, std::vector<double>(scans));
std::unique_ptr<double[]> sintab(new double[views]);
std::unique_ptr<double[]> costab(new double[views]);
float phi = 0.;
float stepsize = (ang2 - ang1) / views;
assert(stepsize > 0); //maybe != 0 ?
int i = 0;
for (phi = ang1; phi < ang2; phi = phi + stepsize) {
sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2);
costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2);
i++;
} i=0;
int scanNumber=0;
int inputMatrixSize = emissionMatrix.size1();
int x = 0, y = 0;
int center = inputMatrixSize / 2;
//Xcenter = 0, Ycenter = 0;
//Xcenter = inputMatrixSize / 2;
//Ycenter = inputMatrixSize / 2;
//if no. scans is greater than the image width, then scale will be <1
double scale = inputMatrixSize*1.42/scans;
int N=0;
double value = 0.;
double weight = 0.;
for (phi=ang1;phi<ang2;phi=phi+stepsize){
double a = -costab[i]/sintab[i];
double aa = 1/a;
if (std::abs(sintab[i]) > sang){
for (scanNumber=0;scanNumber<scans;scanNumber++){
N = scanNumber - scans/2;
double b = (N - costab[i] - sintab[i]) / sintab[i];
b = b * scale;
for (x = -center; x < center; x++){
if (nearest){ //nearest neighbour interpolation
y = (int) std::round(a*x + b);
if (y >= -center && y < center )
value += emissionMatrix((x+center),(y+center));
} else {
y = (int) std::round(a*x + b); //linear interpolation
weight = std::abs((a*x + b) - std::ceil(a*x + b));
if (y >= -center && y+1 < center )
value += (1-weight) * emissionMatrix((x+center),(y+center))
+ weight * emissionMatrix((x+center), (y+center+1));
}
} proj[i][scanNumber] = value/std::abs(sintab[i]); value=0;
}
}
if (std::abs(sintab[i]) <= sang){
for (scanNumber=0;scanNumber<scans;scanNumber++){
N = scanNumber - scans/2;
double bb = (N - costab[i] - sintab[i]) / costab[i];
bb = bb * scale;
for (y = -center; y < center; y++) {
if (nearest){ //nearest neighbour interpolation
x = (int) std::round(aa*y + bb);
if (x >= -center && x < center )
value += emissionMatrix(x+center, y+center);
} else { //linear interpolation
x = (int) std::round(aa*y + bb);
weight = std::abs((aa*y + bb) - std::ceil(aa*y + bb));
if (x >= -center && x+1 < center )
value += (1-weight) * emissionMatrix((x+center), (y+center))
+ weight * emissionMatrix((x+center+1), (y+center));
}
} proj[i][scanNumber] = value/std::abs(costab[i]); value=0;
}
} i++;
}
i=0;
if(scaleResult) {
double datamax = proj[0][0];
double datamin = proj[0][0];
for (unsigned int k = 0; k < proj.size(); k++ ) {
for (unsigned int j = 0; j < proj[0].size(); j++ ) {
if(proj[k][j] < min) proj[k][j] = min;
if(proj[k][j] > datamax) datamax = proj[k][j];
if(proj[k][j] < datamin) datamin = proj[k][j];
}
}
if(datamax == 0.)
datamax = 1.;
for (unsigned int k = 0; k < proj.size(); k++ ) {
for (unsigned int j = 0; j < proj[0].size(); j++ ) {
proj[k][j] = (double) ((proj[k][j]-datamin) * max/datamax);
}
}
}
return proj;
}<|endoftext|> |
<commit_before>/*****************************************************************************
* x11_window.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef X11_SKINS
#include <X11/Xatom.h>
#include "../src/generic_window.hpp"
#include "../src/vlcproc.hpp"
#include "x11_window.hpp"
#include "x11_display.hpp"
#include "x11_graphics.hpp"
#include "x11_dragdrop.hpp"
#include "x11_factory.hpp"
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow,
X11Display &rDisplay, bool dragDrop, bool playOnDrop,
X11Window *pParentWindow ):
OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ),
m_dragDrop( dragDrop )
{
XSetWindowAttributes attr;
unsigned long valuemask;
if (pParentWindow)
{
m_wnd_parent = pParentWindow->m_wnd;
int i_screen = DefaultScreen( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
attr.backing_store = Always;
attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
valuemask = CWBackingStore | CWBackPixel | CWEventMask;
}
else
{
m_wnd_parent = DefaultRootWindow( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
valuemask = CWEventMask;
}
// Create the window
m_wnd = XCreateWindow( XDISPLAY, m_wnd_parent, -10, 0, 1, 1, 0, 0,
InputOutput, CopyFromParent, valuemask, &attr );
// wait for X server to process the previous commands
XSync( XDISPLAY, false );
// Set the colormap for 8bpp mode
if( XPIXELSIZE == 1 )
{
XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() );
}
// Select events received by the window
XSelectInput( XDISPLAY, m_wnd, ExposureMask|KeyPressMask|
PointerMotionMask|ButtonPressMask|ButtonReleaseMask|
LeaveWindowMask|FocusChangeMask );
// Store a pointer on the generic window in a map
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = &rWindow;
// Changing decorations
struct {
unsigned long flags;
unsigned long functions;
unsigned long decorations;
signed long input_mode;
unsigned long status;
} motifWmHints;
Atom hints_atom = XInternAtom( XDISPLAY, "_MOTIF_WM_HINTS", False );
motifWmHints.flags = 2; // MWM_HINTS_DECORATIONS;
motifWmHints.decorations = 0;
XChangeProperty( XDISPLAY, m_wnd, hints_atom, hints_atom, 32,
PropModeReplace, (unsigned char *)&motifWmHints,
sizeof( motifWmHints ) / sizeof( uint32_t ) );
// Drag & drop
if( m_dragDrop )
{
// Create a Dnd object for this window
m_pDropTarget = new X11DragDrop( getIntf(), m_rDisplay, m_wnd,
playOnDrop );
// Register the window as a drop target
Atom xdndAtom = XInternAtom( XDISPLAY, "XdndAware", False );
char xdndVersion = 4;
XChangeProperty( XDISPLAY, m_wnd, xdndAtom, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&xdndVersion, 1 );
// Store a pointer to be used in X11Loop
pFactory->m_dndMap[m_wnd] = m_pDropTarget;
}
// Change the window title
XStoreName( XDISPLAY, m_wnd, "VLC" );
// Associate the window to the main "parent" window
XSetTransientForHint( XDISPLAY, m_wnd, m_rDisplay.getMainWindow() );
}
X11Window::~X11Window()
{
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = NULL;
pFactory->m_dndMap[m_wnd] = NULL;
if( m_dragDrop )
{
delete m_pDropTarget;
}
XDestroyWindow( XDISPLAY, m_wnd );
XSync( XDISPLAY, False );
}
void X11Window::reparent( void* OSHandle, int x, int y, int w, int h )
{
// Reparent the window
Window new_parent =
OSHandle ? (Window) OSHandle : DefaultRootWindow( XDISPLAY );
if( w && h )
XResizeWindow( XDISPLAY, m_wnd, w, h );
XReparentWindow( XDISPLAY, m_wnd, new_parent, x, y);
m_wnd_parent = new_parent;
}
void X11Window::show() const
{
// Map the window
XMapRaised( XDISPLAY, m_wnd );
}
void X11Window::hide() const
{
// Unmap the window
XUnmapWindow( XDISPLAY, m_wnd );
}
void X11Window::moveResize( int left, int top, int width, int height ) const
{
if( width && height )
XMoveResizeWindow( XDISPLAY, m_wnd, left, top, width, height );
else
XMoveWindow( XDISPLAY, m_wnd, left, top );
}
void X11Window::raise() const
{
XRaiseWindow( XDISPLAY, m_wnd );
}
void X11Window::setOpacity( uint8_t value ) const
{
// Sorry, the opacity cannot be changed :)
}
void X11Window::toggleOnTop( bool onTop ) const
{
int i_ret, i_format;
unsigned long i, i_items, i_bytesafter;
Atom net_wm_supported, net_wm_state, net_wm_state_on_top,net_wm_state_above;
union { Atom *p_atom; unsigned char *p_char; } p_args;
p_args.p_atom = NULL;
net_wm_supported = XInternAtom( XDISPLAY, "_NET_SUPPORTED", False );
i_ret = XGetWindowProperty( XDISPLAY, DefaultRootWindow( XDISPLAY ),
net_wm_supported,
0, 16384, False, AnyPropertyType,
&net_wm_supported,
&i_format, &i_items, &i_bytesafter,
(unsigned char **)&p_args );
if( i_ret != Success || i_items == 0 ) return; /* Not supported */
net_wm_state = XInternAtom( XDISPLAY, "_NET_WM_STATE", False );
net_wm_state_on_top = XInternAtom( XDISPLAY, "_NET_WM_STATE_STAYS_ON_TOP",
False );
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_on_top ) break;
}
if( i == i_items )
{ /* use _NET_WM_STATE_ABOVE if window manager
* doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
net_wm_state_above = XInternAtom( XDISPLAY, "_NET_WM_STATE_ABOVE",
False);
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_above ) break;
}
XFree( p_args.p_atom );
if( i == i_items )
return; /* Not supported */
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_above;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
return;
}
XFree( p_args.p_atom );
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_on_top;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
}
#endif
<commit_msg>Skins2: Add x11 transparency support. Hope it sets the property on the right Window; didn't have a known transparent skin to test with.<commit_after>/*****************************************************************************
* x11_window.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulière <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef X11_SKINS
#include <X11/Xatom.h>
#include "../src/generic_window.hpp"
#include "../src/vlcproc.hpp"
#include "x11_window.hpp"
#include "x11_display.hpp"
#include "x11_graphics.hpp"
#include "x11_dragdrop.hpp"
#include "x11_factory.hpp"
X11Window::X11Window( intf_thread_t *pIntf, GenericWindow &rWindow,
X11Display &rDisplay, bool dragDrop, bool playOnDrop,
X11Window *pParentWindow ):
OSWindow( pIntf ), m_rDisplay( rDisplay ), m_pParent( pParentWindow ),
m_dragDrop( dragDrop )
{
XSetWindowAttributes attr;
unsigned long valuemask;
if (pParentWindow)
{
m_wnd_parent = pParentWindow->m_wnd;
int i_screen = DefaultScreen( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
attr.backing_store = Always;
attr.background_pixel = BlackPixel( XDISPLAY, i_screen );
valuemask = CWBackingStore | CWBackPixel | CWEventMask;
}
else
{
m_wnd_parent = DefaultRootWindow( XDISPLAY );
attr.event_mask = ExposureMask | StructureNotifyMask;
valuemask = CWEventMask;
}
// Create the window
m_wnd = XCreateWindow( XDISPLAY, m_wnd_parent, -10, 0, 1, 1, 0, 0,
InputOutput, CopyFromParent, valuemask, &attr );
// wait for X server to process the previous commands
XSync( XDISPLAY, false );
// Set the colormap for 8bpp mode
if( XPIXELSIZE == 1 )
{
XSetWindowColormap( XDISPLAY, m_wnd, m_rDisplay.getColormap() );
}
// Select events received by the window
XSelectInput( XDISPLAY, m_wnd, ExposureMask|KeyPressMask|
PointerMotionMask|ButtonPressMask|ButtonReleaseMask|
LeaveWindowMask|FocusChangeMask );
// Store a pointer on the generic window in a map
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = &rWindow;
// Changing decorations
struct {
unsigned long flags;
unsigned long functions;
unsigned long decorations;
signed long input_mode;
unsigned long status;
} motifWmHints;
Atom hints_atom = XInternAtom( XDISPLAY, "_MOTIF_WM_HINTS", False );
motifWmHints.flags = 2; // MWM_HINTS_DECORATIONS;
motifWmHints.decorations = 0;
XChangeProperty( XDISPLAY, m_wnd, hints_atom, hints_atom, 32,
PropModeReplace, (unsigned char *)&motifWmHints,
sizeof( motifWmHints ) / sizeof( uint32_t ) );
// Drag & drop
if( m_dragDrop )
{
// Create a Dnd object for this window
m_pDropTarget = new X11DragDrop( getIntf(), m_rDisplay, m_wnd,
playOnDrop );
// Register the window as a drop target
Atom xdndAtom = XInternAtom( XDISPLAY, "XdndAware", False );
char xdndVersion = 4;
XChangeProperty( XDISPLAY, m_wnd, xdndAtom, XA_ATOM, 32,
PropModeReplace, (unsigned char *)&xdndVersion, 1 );
// Store a pointer to be used in X11Loop
pFactory->m_dndMap[m_wnd] = m_pDropTarget;
}
// Change the window title
XStoreName( XDISPLAY, m_wnd, "VLC" );
// Associate the window to the main "parent" window
XSetTransientForHint( XDISPLAY, m_wnd, m_rDisplay.getMainWindow() );
}
X11Window::~X11Window()
{
X11Factory *pFactory = (X11Factory*)X11Factory::instance( getIntf() );
pFactory->m_windowMap[m_wnd] = NULL;
pFactory->m_dndMap[m_wnd] = NULL;
if( m_dragDrop )
{
delete m_pDropTarget;
}
XDestroyWindow( XDISPLAY, m_wnd );
XSync( XDISPLAY, False );
}
void X11Window::reparent( void* OSHandle, int x, int y, int w, int h )
{
// Reparent the window
Window new_parent =
OSHandle ? (Window) OSHandle : DefaultRootWindow( XDISPLAY );
if( w && h )
XResizeWindow( XDISPLAY, m_wnd, w, h );
XReparentWindow( XDISPLAY, m_wnd, new_parent, x, y);
m_wnd_parent = new_parent;
}
void X11Window::show() const
{
// Map the window
XMapRaised( XDISPLAY, m_wnd );
}
void X11Window::hide() const
{
// Unmap the window
XUnmapWindow( XDISPLAY, m_wnd );
}
void X11Window::moveResize( int left, int top, int width, int height ) const
{
if( width && height )
XMoveResizeWindow( XDISPLAY, m_wnd, left, top, width, height );
else
XMoveWindow( XDISPLAY, m_wnd, left, top );
}
void X11Window::raise() const
{
XRaiseWindow( XDISPLAY, m_wnd );
}
void X11Window::setOpacity( uint8_t value ) const
{
Atom opaq = XInternAtom(XDISPLAY, "_NET_WM_WINDOW_OPACITY", False);
if( 255==value )
XDeleteProperty(XDISPLAY, m_wnd, opaq);
else
{
uint32_t opacity = value * ((uint32_t)-1/255);
XChangeProperty(XDISPLAY, m_wnd, opaq, XA_CARDINAL, 32,
PropModeReplace, (unsigned char *) &opacity, 1L);
}
XSync( XDISPLAY, False );
}
void X11Window::toggleOnTop( bool onTop ) const
{
int i_ret, i_format;
unsigned long i, i_items, i_bytesafter;
Atom net_wm_supported, net_wm_state, net_wm_state_on_top,net_wm_state_above;
union { Atom *p_atom; unsigned char *p_char; } p_args;
p_args.p_atom = NULL;
net_wm_supported = XInternAtom( XDISPLAY, "_NET_SUPPORTED", False );
i_ret = XGetWindowProperty( XDISPLAY, DefaultRootWindow( XDISPLAY ),
net_wm_supported,
0, 16384, False, AnyPropertyType,
&net_wm_supported,
&i_format, &i_items, &i_bytesafter,
(unsigned char **)&p_args );
if( i_ret != Success || i_items == 0 ) return; /* Not supported */
net_wm_state = XInternAtom( XDISPLAY, "_NET_WM_STATE", False );
net_wm_state_on_top = XInternAtom( XDISPLAY, "_NET_WM_STATE_STAYS_ON_TOP",
False );
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_on_top ) break;
}
if( i == i_items )
{ /* use _NET_WM_STATE_ABOVE if window manager
* doesn't handle _NET_WM_STATE_STAYS_ON_TOP */
net_wm_state_above = XInternAtom( XDISPLAY, "_NET_WM_STATE_ABOVE",
False);
for( i = 0; i < i_items; i++ )
{
if( p_args.p_atom[i] == net_wm_state_above ) break;
}
XFree( p_args.p_atom );
if( i == i_items )
return; /* Not supported */
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_above;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
return;
}
XFree( p_args.p_atom );
/* Switch "on top" status */
XClientMessageEvent event;
memset( &event, 0, sizeof( XClientMessageEvent ) );
event.type = ClientMessage;
event.message_type = net_wm_state;
event.display = XDISPLAY;
event.window = m_wnd;
event.format = 32;
event.data.l[ 0 ] = onTop; /* set property */
event.data.l[ 1 ] = net_wm_state_on_top;
XSendEvent( XDISPLAY, DefaultRootWindow( XDISPLAY ),
False, SubstructureRedirectMask, (XEvent*)&event );
}
#endif
<|endoftext|> |
<commit_before>//===-- MSP430AsmPrinter.cpp - MSP430 LLVM assembly writer ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to the MSP430 assembly language.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "MSP430.h"
#include "MSP430InstrInfo.h"
#include "MSP430TargetMachine.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DwarfWriter.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetData.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
STATISTIC(EmittedInsts, "Number of machine instrs printed");
namespace {
class VISIBILITY_HIDDEN MSP430AsmPrinter : public AsmPrinter {
public:
MSP430AsmPrinter(raw_ostream &O, MSP430TargetMachine &TM,
const TargetAsmInfo *TAI, bool Fast, bool Verbose)
: AsmPrinter(O, TM, TAI, Fast, Verbose) {}
virtual const char *getPassName() const {
return "MSP430 Assembly Printer";
}
void printOperand(const MachineInstr *MI, int OpNum,
const char* Modifier = 0);
void printSrcMemOperand(const MachineInstr *MI, int OpNum,
const char* Modifier = 0);
void printCCOperand(const MachineInstr *MI, int OpNum);
bool printInstruction(const MachineInstr *MI); // autogenerated.
void printMachineInstruction(const MachineInstr * MI);
bool runOnMachineFunction(MachineFunction &F);
bool doInitialization(Module &M);
bool doFinalization(Module &M);
void getAnalysisUsage(AnalysisUsage &AU) const {
AsmPrinter::getAnalysisUsage(AU);
AU.setPreservesAll();
}
};
} // end of anonymous namespace
#include "MSP430GenAsmWriter.inc"
/// createMSP430CodePrinterPass - Returns a pass that prints the MSP430
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description. This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createMSP430CodePrinterPass(raw_ostream &o,
MSP430TargetMachine &tm,
bool fast, bool verbose) {
return new MSP430AsmPrinter(o, tm, tm.getTargetAsmInfo(), fast, verbose);
}
bool MSP430AsmPrinter::doInitialization(Module &M) {
Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
return false; // success
}
bool MSP430AsmPrinter::doFinalization(Module &M) {
return AsmPrinter::doFinalization(M);
}
bool MSP430AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
// Print out code for the function.
for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
I != E; ++I) {
// Print a label for the basic block.
if (I != MF.begin()) {
printBasicBlockLabel(I, true , true);
O << '\n';
}
for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
II != E; ++II) {
// Print the assembly for the instruction.
O << "\t";
printMachineInstruction(II);
}
// Each Basic Block is separated by a newline
O << '\n';
}
// We didn't modify anything
return false;
}
void MSP430AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
++EmittedInsts;
// Call the autogenerated instruction printer routines.
if (printInstruction(MI))
return;
assert(0 && "Should not happen");
}
void MSP430AsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
const char* Modifier) {
const MachineOperand &MO = MI->getOperand(OpNum);
switch (MO.getType()) {
case MachineOperand::MO_Register:
assert (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
"Virtual registers should be already mapped!");
O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
return;
case MachineOperand::MO_Immediate:
if (!Modifier || strcmp(Modifier, "nohash"))
O << '#';
O << MO.getImm();
return;
case MachineOperand::MO_MachineBasicBlock:
printBasicBlockLabel(MO.getMBB());
return;
case MachineOperand::MO_GlobalAddress: {
bool isMemOp = Modifier && !strcmp(Modifier, "mem");
bool isCallOp = Modifier && !strcmp(Modifier, "call");
std::string Name = Mang->getValueName(MO.getGlobal());
assert(MO.getOffset() == 0 && "No offsets allowed!");
if (isCallOp)
O << '#';
else if (isMemOp)
O << '&';
O << Name;
return;
}
case MachineOperand::MO_ExternalSymbol: {
bool isCallOp = Modifier && !strcmp(Modifier, "call");
std::string Name(TAI->getGlobalPrefix());
Name += MO.getSymbolName();
if (isCallOp)
O << '#';
O << Name;
return;
}
default:
assert(0 && "Not implemented yet!");
}
}
void MSP430AsmPrinter::printSrcMemOperand(const MachineInstr *MI, int OpNum,
const char* Modifier) {
const MachineOperand &Base = MI->getOperand(OpNum);
const MachineOperand &Disp = MI->getOperand(OpNum+1);
if (Base.isGlobal())
printOperand(MI, OpNum, "mem");
else if (Disp.isImm() && !Base.getReg())
printOperand(MI, OpNum);
else if (Base.getReg()) {
if (Disp.getImm()) {
printOperand(MI, OpNum + 1, "nohash");
O << '(';
printOperand(MI, OpNum);
O << ')';
} else {
O << '@';
printOperand(MI, OpNum);
}
} else
assert(0 && "Unsupported memory operand");
}
void MSP430AsmPrinter::printCCOperand(const MachineInstr *MI, int OpNum) {
unsigned CC = MI->getOperand(OpNum).getImm();
switch (CC) {
default:
assert(0 && "Unsupported CC code");
break;
case MSP430::COND_E:
O << "eq";
break;
case MSP430::COND_NE:
O << "ne";
break;
case MSP430::COND_HS:
O << "hs";
break;
case MSP430::COND_LO:
O << "lo";
break;
case MSP430::COND_GE:
O << "ge";
break;
case MSP430::COND_L:
O << 'l';
break;
}
}
<commit_msg>Print function header / footer<commit_after>//===-- MSP430AsmPrinter.cpp - MSP430 LLVM assembly writer ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to the MSP430 assembly language.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "asm-printer"
#include "MSP430.h"
#include "MSP430InstrInfo.h"
#include "MSP430TargetMachine.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/DwarfWriter.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetAsmInfo.h"
#include "llvm/Target/TargetData.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Mangler.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
STATISTIC(EmittedInsts, "Number of machine instrs printed");
namespace {
class VISIBILITY_HIDDEN MSP430AsmPrinter : public AsmPrinter {
public:
MSP430AsmPrinter(raw_ostream &O, MSP430TargetMachine &TM,
const TargetAsmInfo *TAI, bool Fast, bool Verbose)
: AsmPrinter(O, TM, TAI, Fast, Verbose) {}
virtual const char *getPassName() const {
return "MSP430 Assembly Printer";
}
void printOperand(const MachineInstr *MI, int OpNum,
const char* Modifier = 0);
void printSrcMemOperand(const MachineInstr *MI, int OpNum,
const char* Modifier = 0);
void printCCOperand(const MachineInstr *MI, int OpNum);
bool printInstruction(const MachineInstr *MI); // autogenerated.
void printMachineInstruction(const MachineInstr * MI);
void emitFunctionHeader(const MachineFunction &MF);
bool runOnMachineFunction(MachineFunction &F);
bool doInitialization(Module &M);
bool doFinalization(Module &M);
void getAnalysisUsage(AnalysisUsage &AU) const {
AsmPrinter::getAnalysisUsage(AU);
AU.setPreservesAll();
}
};
} // end of anonymous namespace
#include "MSP430GenAsmWriter.inc"
/// createMSP430CodePrinterPass - Returns a pass that prints the MSP430
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description. This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createMSP430CodePrinterPass(raw_ostream &o,
MSP430TargetMachine &tm,
bool fast, bool verbose) {
return new MSP430AsmPrinter(o, tm, tm.getTargetAsmInfo(), fast, verbose);
}
bool MSP430AsmPrinter::doInitialization(Module &M) {
Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
return false; // success
}
bool MSP430AsmPrinter::doFinalization(Module &M) {
return AsmPrinter::doFinalization(M);
}
void MSP430AsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
const Function *F = MF.getFunction();
SwitchToSection(TAI->SectionForGlobal(F));
unsigned FnAlign = 4;
if (F->hasFnAttr(Attribute::OptimizeForSize))
FnAlign = 1;
EmitAlignment(FnAlign, F);
switch (F->getLinkage()) {
default: assert(0 && "Unknown linkage type!");
case Function::InternalLinkage: // Symbols default to internal.
case Function::PrivateLinkage:
break;
case Function::ExternalLinkage:
O << "\t.globl\t" << CurrentFnName << '\n';
break;
case Function::LinkOnceAnyLinkage:
case Function::LinkOnceODRLinkage:
case Function::WeakAnyLinkage:
case Function::WeakODRLinkage:
O << "\t.weak\t" << CurrentFnName << '\n';
break;
}
printVisibility(CurrentFnName, F->getVisibility());
O << "\t.type\t" << CurrentFnName << ",@function\n"
<< CurrentFnName << ":\n";
}
bool MSP430AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
SetupMachineFunction(MF);
// Print the 'header' of function
emitFunctionHeader(MF);
// Print out code for the function.
for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
I != E; ++I) {
// Print a label for the basic block.
if (I != MF.begin()) {
printBasicBlockLabel(I, true , true);
O << '\n';
}
for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
II != E; ++II) {
// Print the assembly for the instruction.
O << "\t";
printMachineInstruction(II);
}
// Each Basic Block is separated by a newline
O << '\n';
}
if (TAI->hasDotTypeDotSizeDirective())
O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
O.flush();
// We didn't modify anything
return false;
}
void MSP430AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
++EmittedInsts;
// Call the autogenerated instruction printer routines.
if (printInstruction(MI))
return;
assert(0 && "Should not happen");
}
void MSP430AsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
const char* Modifier) {
const MachineOperand &MO = MI->getOperand(OpNum);
switch (MO.getType()) {
case MachineOperand::MO_Register:
assert (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
"Virtual registers should be already mapped!");
O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
return;
case MachineOperand::MO_Immediate:
if (!Modifier || strcmp(Modifier, "nohash"))
O << '#';
O << MO.getImm();
return;
case MachineOperand::MO_MachineBasicBlock:
printBasicBlockLabel(MO.getMBB());
return;
case MachineOperand::MO_GlobalAddress: {
bool isMemOp = Modifier && !strcmp(Modifier, "mem");
bool isCallOp = Modifier && !strcmp(Modifier, "call");
std::string Name = Mang->getValueName(MO.getGlobal());
assert(MO.getOffset() == 0 && "No offsets allowed!");
if (isCallOp)
O << '#';
else if (isMemOp)
O << '&';
O << Name;
return;
}
case MachineOperand::MO_ExternalSymbol: {
bool isCallOp = Modifier && !strcmp(Modifier, "call");
std::string Name(TAI->getGlobalPrefix());
Name += MO.getSymbolName();
if (isCallOp)
O << '#';
O << Name;
return;
}
default:
assert(0 && "Not implemented yet!");
}
}
void MSP430AsmPrinter::printSrcMemOperand(const MachineInstr *MI, int OpNum,
const char* Modifier) {
const MachineOperand &Base = MI->getOperand(OpNum);
const MachineOperand &Disp = MI->getOperand(OpNum+1);
if (Base.isGlobal())
printOperand(MI, OpNum, "mem");
else if (Disp.isImm() && !Base.getReg())
printOperand(MI, OpNum);
else if (Base.getReg()) {
if (Disp.getImm()) {
printOperand(MI, OpNum + 1, "nohash");
O << '(';
printOperand(MI, OpNum);
O << ')';
} else {
O << '@';
printOperand(MI, OpNum);
}
} else
assert(0 && "Unsupported memory operand");
}
void MSP430AsmPrinter::printCCOperand(const MachineInstr *MI, int OpNum) {
unsigned CC = MI->getOperand(OpNum).getImm();
switch (CC) {
default:
assert(0 && "Unsupported CC code");
break;
case MSP430::COND_E:
O << "eq";
break;
case MSP430::COND_NE:
O << "ne";
break;
case MSP430::COND_HS:
O << "hs";
break;
case MSP430::COND_LO:
O << "lo";
break;
case MSP430::COND_GE:
O << "ge";
break;
case MSP430::COND_L:
O << 'l';
break;
}
}
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <algorithm>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Bins.hpp>
#include <Folding.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
typedef float dataType;
std::string typeName("float");
int main(int argc, char * argv[]) {
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int minThreads = 0;
unsigned int maxThreadsPerBlock = 0;
unsigned int maxItemsPerThread = 0;
unsigned int maxColumns = 0;
unsigned int maxRows = 0;
unsigned int maxVector = 0;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads");
maxItemsPerThread = args.getSwitchArgument< unsigned int >("-max_items");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
maxVector = args.getSwitchArgument< unsigned int >("-max_vector");
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0);
observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), args.getSwitchArgument< unsigned int >("-first_period"), args.getSwitchArgument< unsigned int >("-period_step"));
observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));
} catch ( isa::utils::EmptyCommandLine &err ) {
std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -min_threads ... -max_threads ... -max_items ... -max_columns ... -max_rows ... -max_vector ... -samples ... -dms ... -periods ... -bins ... -first_period ... -period_step ..." << std::endl;
return 1;
} catch ( std::exception &err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Initialize OpenCL
cl::Context * clContext = new cl::Context();
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
std::vector< unsigned int > * samplesPerBin = PulsarSearch::getSamplesPerBin(observation);
// Allocate memory
cl::Buffer samplesPerBin_d;
std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
cl::Buffer dedispersedData_d;
std::vector< dataType > foldedData = std::vector< dataType >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer foldedData_d;
std::vector< unsigned int > readCounters = std::vector< unsigned int >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer readCounters_d;
std::vector< unsigned int > writeCounters = std::vector< unsigned int >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer writeCounters_d;
try {
samplesPerBin_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, samplesPerBin->size() * sizeof(unsigned int), 0, 0);
dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), 0, 0);
foldedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, foldedData.size() * sizeof(dataType), 0, 0);
readCounters_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, readCounters.size() * sizeof(unsigned int), 0, 0);
writeCounters_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, writeCounters.size() * sizeof(unsigned int), 0, 0);
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error allocating memory: " << isa::utils::toString(err.err()) << "." << std::endl;
return 1;
}
srand(time(0));
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
dedispersedData[(sample * observation.getNrPaddedDMs()) + DM] = static_cast< dataType >(rand() % 10);
}
}
std::fill(foldedData.begin(), foldedData.end(), static_cast< dataType >(0));
std::fill(readCounters.begin(), readCounters.end(), 0);
std::fill(writeCounters.begin(), writeCounters.end(), 0);
// Copy data structures to device
try {
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(samplesPerBin_d, CL_FALSE, 0, samplesPerBin->size() * sizeof(unsigned int), reinterpret_cast< void * >(samplesPerBin->data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dedispersedData_d, CL_FALSE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(foldedData_d, CL_FALSE, 0, foldedData.size() * sizeof(dataType), reinterpret_cast< void * >(foldedData.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(readCounters_d, CL_FALSE, 0, readCounters.size() * sizeof(unsigned int), reinterpret_cast< void * >(readCounters.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(writeCounters_d, CL_FALSE, 0, writeCounters.size() * sizeof(unsigned int), reinterpret_cast< void * >(writeCounters.data()));
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString(err.err()) << "." << std::endl;
return 1;
}
// Find the parameters
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = minThreads; DMs <= maxColumns; DMs += minThreads ) {
if ( (observation.getNrPaddedDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::vector< unsigned int > periodsPerBlock;
for ( unsigned int periods = 1; periods <= maxRows; periods++ ) {
if ( (observation.getNrPeriods() % periods) == 0 ) {
periodsPerBlock.push_back(periods);
}
}
std::vector< unsigned int > binsPerBlock;
for ( unsigned int bins = 1; bins <= maxRows; bins++ ) {
if ( (observation.getNrBins() % bins) == 0 ) {
binsPerBlock.push_back(bins);
}
}
std::cout << std::fixed << std::endl;
std::cout << "# nrDMs nrSamples nrPeriods nrBins firstPeriod periodStep DMsPerBlock periodsPerBlock binsPerBlock DMsPerThread periodsPerThread binsPerThread vector GFLOP/s err time err" << std::endl << std::endl;
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
for ( std::vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); ++periods ) {
for ( std::vector< unsigned int >::iterator bins = binsPerBlock.begin(); bins != binsPerBlock.end(); ++bins ) {
if ( (*DMs * *periods * *bins) > maxThreadsPerBlock ) {
break;
} else if ( *periods * *bins > maxRows ) {
break;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {
if ( observation.getNrPaddedDMs() % (*DMs * DMsPerThread) != 0 ) {
continue;
}
for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) {
if ( observation.getNrPeriods() % (*periods * periodsPerThread) != 0 ) {
continue;
}
for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) {
if ( observation.getNrBins() % (*bins * binsPerThread) != 0 ) {
continue;
}
for ( unsigned int vector = 1; vector <= maxVector; vector *= 2 ) {
if ( observation.getNrPaddedDMs() % (*DMs * DMsPerThread * vector) != 0 ) {
continue;
}
if ( 1 + (2 * periodsPerThread) + binsPerThread + DMsPerThread + (4 * periodsPerThread * binsPerThread) + (vector * periodsPerThread * binsPerThread * DMsPerThread) > maxItemsPerThread ) {
break;
}
// Generate kernel
double flops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrSamplesPerSecond());
isa::utils::Timer timer;
isa::utils::Stats< double > stats;
cl::Event event;
cl::Kernel * kernel;
std::string * code = PulsarSearch::getFoldingOpenCL(*DMs, *periods, *bins, DMsPerThread, periodsPerThread, binsPerThread, vector, typeName, observation);
try {
kernel = isa::OpenCL::compile("folding", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError &err ) {
std::cerr << err.what() << std::endl;
continue;
}
cl::NDRange global(observation.getNrPaddedDMs() / vector / DMsPerThread, observation.getNrPeriods() / periodsPerThread, observation.getNrBins() / binsPerThread);
cl::NDRange local(*DMs, *periods, *bins);
kernel->setArg(0, 0);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, foldedData_d);
kernel->setArg(3, readCounters_d);
kernel->setArg(4, writeCounters_d);
kernel->setArg(5, samplesPerBin_d);
// Warm-up run
try {
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
// Tuning runs
try {
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
stats.addElement(flops / timer.getLastRunTime());
}
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
std::cout << observation.getNrDMs() << " " << observation.getNrSamplesPerSecond() << " " << observation.getNrPeriods() << " " << observation.getNrBins() << " " << observation.getFirstPeriod() << " " << observation.getPeriodStep() << " " << *DMs << " " << *periods << " " << *bins << " " << DMsPerThread << " " << periodsPerThread << " " << binsPerThread << " " << vector << " " << std::setprecision(3) << stats.getAverage() << " " << stats.getStdDev() << " " << std::setprecision(6) << timer.getAverageTime() << " " << timer.getStdDev() << std::endl;
}
}
}
}
}
}
}
std::cout << std::endl;
return 0;
}
<commit_msg>Stats API updated.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <iostream>
#include <string>
#include <vector>
#include <exception>
#include <fstream>
#include <iomanip>
#include <limits>
#include <algorithm>
#include <ArgumentList.hpp>
#include <Observation.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Bins.hpp>
#include <Folding.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>
typedef float dataType;
std::string typeName("float");
int main(int argc, char * argv[]) {
unsigned int nrIterations = 0;
unsigned int clPlatformID = 0;
unsigned int clDeviceID = 0;
unsigned int minThreads = 0;
unsigned int maxThreadsPerBlock = 0;
unsigned int maxItemsPerThread = 0;
unsigned int maxColumns = 0;
unsigned int maxRows = 0;
unsigned int maxVector = 0;
AstroData::Observation observation;
try {
isa::utils::ArgumentList args(argc, argv);
nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
observation.setPadding(args.getSwitchArgument< unsigned int >("-padding"));
minThreads = args.getSwitchArgument< unsigned int >("-min_threads");
maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads");
maxItemsPerThread = args.getSwitchArgument< unsigned int >("-max_items");
maxColumns = args.getSwitchArgument< unsigned int >("-max_columns");
maxRows = args.getSwitchArgument< unsigned int >("-max_rows");
maxVector = args.getSwitchArgument< unsigned int >("-max_vector");
observation.setNrSamplesPerSecond(args.getSwitchArgument< unsigned int >("-samples"));
observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, 0.0);
observation.setPeriodRange(args.getSwitchArgument< unsigned int >("-periods"), args.getSwitchArgument< unsigned int >("-first_period"), args.getSwitchArgument< unsigned int >("-period_step"));
observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins"));
} catch ( isa::utils::EmptyCommandLine &err ) {
std::cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -min_threads ... -max_threads ... -max_items ... -max_columns ... -max_rows ... -max_vector ... -samples ... -dms ... -periods ... -bins ... -first_period ... -period_step ..." << std::endl;
return 1;
} catch ( std::exception &err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Initialize OpenCL
cl::Context * clContext = new cl::Context();
std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
std::vector< std::vector< cl::CommandQueue > > * clQueues = new std::vector< std::vector < cl::CommandQueue > >();
isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues);
std::vector< unsigned int > * samplesPerBin = PulsarSearch::getSamplesPerBin(observation);
// Allocate memory
cl::Buffer samplesPerBin_d;
std::vector< dataType > dedispersedData = std::vector< dataType >(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs());
cl::Buffer dedispersedData_d;
std::vector< dataType > foldedData = std::vector< dataType >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer foldedData_d;
std::vector< unsigned int > readCounters = std::vector< unsigned int >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer readCounters_d;
std::vector< unsigned int > writeCounters = std::vector< unsigned int >(observation.getNrBins() * observation.getNrPeriods() * observation.getNrPaddedDMs());
cl::Buffer writeCounters_d;
try {
samplesPerBin_d = cl::Buffer(*clContext, CL_MEM_READ_ONLY, samplesPerBin->size() * sizeof(unsigned int), 0, 0);
dedispersedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, dedispersedData.size() * sizeof(dataType), 0, 0);
foldedData_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, foldedData.size() * sizeof(dataType), 0, 0);
readCounters_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, readCounters.size() * sizeof(unsigned int), 0, 0);
writeCounters_d = cl::Buffer(*clContext, CL_MEM_READ_WRITE, writeCounters.size() * sizeof(unsigned int), 0, 0);
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error allocating memory: " << isa::utils::toString(err.err()) << "." << std::endl;
return 1;
}
srand(time(0));
for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
for ( unsigned int DM = 0; DM < observation.getNrDMs(); DM++ ) {
dedispersedData[(sample * observation.getNrPaddedDMs()) + DM] = static_cast< dataType >(rand() % 10);
}
}
std::fill(foldedData.begin(), foldedData.end(), static_cast< dataType >(0));
std::fill(readCounters.begin(), readCounters.end(), 0);
std::fill(writeCounters.begin(), writeCounters.end(), 0);
// Copy data structures to device
try {
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(samplesPerBin_d, CL_FALSE, 0, samplesPerBin->size() * sizeof(unsigned int), reinterpret_cast< void * >(samplesPerBin->data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(dedispersedData_d, CL_FALSE, 0, dedispersedData.size() * sizeof(dataType), reinterpret_cast< void * >(dedispersedData.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(foldedData_d, CL_FALSE, 0, foldedData.size() * sizeof(dataType), reinterpret_cast< void * >(foldedData.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(readCounters_d, CL_FALSE, 0, readCounters.size() * sizeof(unsigned int), reinterpret_cast< void * >(readCounters.data()));
clQueues->at(clDeviceID)[0].enqueueWriteBuffer(writeCounters_d, CL_FALSE, 0, writeCounters.size() * sizeof(unsigned int), reinterpret_cast< void * >(writeCounters.data()));
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error H2D transfer: " << isa::utils::toString(err.err()) << "." << std::endl;
return 1;
}
// Find the parameters
std::vector< unsigned int > DMsPerBlock;
for ( unsigned int DMs = minThreads; DMs <= maxColumns; DMs += minThreads ) {
if ( (observation.getNrPaddedDMs() % DMs) == 0 ) {
DMsPerBlock.push_back(DMs);
}
}
std::vector< unsigned int > periodsPerBlock;
for ( unsigned int periods = 1; periods <= maxRows; periods++ ) {
if ( (observation.getNrPeriods() % periods) == 0 ) {
periodsPerBlock.push_back(periods);
}
}
std::vector< unsigned int > binsPerBlock;
for ( unsigned int bins = 1; bins <= maxRows; bins++ ) {
if ( (observation.getNrBins() % bins) == 0 ) {
binsPerBlock.push_back(bins);
}
}
std::cout << std::fixed << std::endl;
std::cout << "# nrDMs nrSamples nrPeriods nrBins firstPeriod periodStep DMsPerBlock periodsPerBlock binsPerBlock DMsPerThread periodsPerThread binsPerThread vector GFLOP/s err time err" << std::endl << std::endl;
for ( std::vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); ++DMs ) {
for ( std::vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); ++periods ) {
for ( std::vector< unsigned int >::iterator bins = binsPerBlock.begin(); bins != binsPerBlock.end(); ++bins ) {
if ( (*DMs * *periods * *bins) > maxThreadsPerBlock ) {
break;
} else if ( *periods * *bins > maxRows ) {
break;
}
for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) {
if ( observation.getNrPaddedDMs() % (*DMs * DMsPerThread) != 0 ) {
continue;
}
for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) {
if ( observation.getNrPeriods() % (*periods * periodsPerThread) != 0 ) {
continue;
}
for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) {
if ( observation.getNrBins() % (*bins * binsPerThread) != 0 ) {
continue;
}
for ( unsigned int vector = 1; vector <= maxVector; vector *= 2 ) {
if ( observation.getNrPaddedDMs() % (*DMs * DMsPerThread * vector) != 0 ) {
continue;
}
if ( 1 + (2 * periodsPerThread) + binsPerThread + DMsPerThread + (4 * periodsPerThread * binsPerThread) + (vector * periodsPerThread * binsPerThread * DMsPerThread) > maxItemsPerThread ) {
break;
}
// Generate kernel
double flops = isa::utils::giga(static_cast< long long unsigned int >(observation.getNrDMs()) * observation.getNrPeriods() * observation.getNrSamplesPerSecond());
isa::utils::Timer timer;
isa::utils::Stats< double > stats;
cl::Event event;
cl::Kernel * kernel;
std::string * code = PulsarSearch::getFoldingOpenCL(*DMs, *periods, *bins, DMsPerThread, periodsPerThread, binsPerThread, vector, typeName, observation);
try {
kernel = isa::OpenCL::compile("folding", *code, "-cl-mad-enable -Werror", *clContext, clDevices->at(clDeviceID));
} catch ( isa::OpenCL::OpenCLError &err ) {
std::cerr << err.what() << std::endl;
continue;
}
cl::NDRange global(observation.getNrPaddedDMs() / vector / DMsPerThread, observation.getNrPeriods() / periodsPerThread, observation.getNrBins() / binsPerThread);
cl::NDRange local(*DMs, *periods, *bins);
kernel->setArg(0, 0);
kernel->setArg(1, dedispersedData_d);
kernel->setArg(2, foldedData_d);
kernel->setArg(3, readCounters_d);
kernel->setArg(4, writeCounters_d);
kernel->setArg(5, samplesPerBin_d);
// Warm-up run
try {
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
// Tuning runs
try {
for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
timer.start();
clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &event);
event.wait();
timer.stop();
stats.addElement(flops / timer.getLastRunTime());
}
} catch ( cl::Error &err ) {
std::cerr << "OpenCL error kernel execution: " << isa::utils::toString(err.err()) << "." << std::endl;
continue;
}
std::cout << observation.getNrDMs() << " " << observation.getNrSamplesPerSecond() << " " << observation.getNrPeriods() << " " << observation.getNrBins() << " " << observation.getFirstPeriod() << " " << observation.getPeriodStep() << " " << *DMs << " " << *periods << " " << *bins << " " << DMsPerThread << " " << periodsPerThread << " " << binsPerThread << " " << vector << " " << std::setprecision(3) << stats.getAverage() << " " << stats.getStandardDeviation() << " " << std::setprecision(6) << timer.getAverageTime() << " " << timer.getStandardDeviation() << std::endl;
}
}
}
}
}
}
}
std::cout << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
namespace libtest {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool has_libmemcached(void)
{
#if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED
if (HAVE_LIBMEMCACHED)
{
return true;
}
#endif
return false;
}
#pragma GCC diagnostic pop
bool has_libdrizzle(void)
{
#if defined(HAVE_LIBDRIZZLE) && HAVE_LIBDRIZZLE
if (HAVE_LIBDRIZZLE)
{
return true;
}
#endif
return false;
}
bool has_postgres_support(void)
{
char *getenv_ptr;
if (bool((getenv_ptr= getenv("POSTGES_IS_RUNNING_AND_SETUP"))))
{
(void)(getenv_ptr);
if (HAVE_LIBPQ)
{
return true;
}
}
return false;
}
bool has_gearmand()
{
#if defined(GEARMAND_BINARY) && defined(HAVE_GEARMAND_BINARY) && HAVE_GEARMAND_BINARY
if (HAVE_GEARMAND_BINARY)
{
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and
((strcmp(GEARMAND_BINARY, "./gearmand/gearmand") == 0) or (strcmp(GEARMAND_BINARY, "gearmand/gearmand") == 0)))
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << GEARMAND_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_drizzled()
{
#if defined(DRIZZLED_BINARY) && defined(HAVE_DRIZZLED_BINARY) && HAVE_DRIZZLED_BINARY && defined(HAVE_LIBMYSQL_BUILD) && HAVE_LIBMYSQL_BUILD
{
if (access(DRIZZLED_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_mysqld()
{
#if defined(MYSQLD_BINARY) && defined(HAVE_MYSQLD_BUILD) && HAVE_MYSQLD_BUILD && defined(HAVE_LIBMYSQL_BUILD) && HAVE_LIBMYSQL_BUILD
{
if (access(MYSQLD_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
static char memcached_binary_path[FILENAME_MAX];
static void initialize_memcached_binary_path()
{
memcached_binary_path[0]= 0;
#if defined(MEMCACHED_BINARY) && defined(HAVE_MEMCACHED_BINARY) && HAVE_MEMCACHED_BINARY
if (HAVE_MEMCACHED_BINARY)
{
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << MEMCACHED_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
strncpy(memcached_binary_path, arg_buffer.str().c_str(), FILENAME_MAX);
}
}
#endif
}
static pthread_once_t memcached_binary_once= PTHREAD_ONCE_INIT;
static void initialize_memcached_binary(void)
{
int ret;
if ((ret= pthread_once(&memcached_binary_once, initialize_memcached_binary_path)) != 0)
{
FATAL(strerror(ret));
}
}
bool has_memcached()
{
initialize_memcached_binary();
if (memcached_binary_path[0] and (strlen(memcached_binary_path) > 0))
{
return true;
}
return false;
}
const char* memcached_binary()
{
initialize_memcached_binary();
if (memcached_binary_path[0])
{
return memcached_binary_path;
}
return NULL;
}
const char *gearmand_binary()
{
#if defined(GEARMAND_BINARY)
return GEARMAND_BINARY;
#else
return NULL;
#endif
}
const char *drizzled_binary()
{
#if defined(DRIZZLED_BINARY)
return DRIZZLED_BINARY;
#else
return NULL;
#endif
}
} // namespace libtest
<commit_msg>Correct POSTGRES misspelling<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012-2013 Data Differential, http://datadifferential.com/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * The names of its contributors may not be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "libtest/yatlcon.h"
#include <libtest/common.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
namespace libtest {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
bool has_libmemcached(void)
{
#if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED
if (HAVE_LIBMEMCACHED)
{
return true;
}
#endif
return false;
}
#pragma GCC diagnostic pop
bool has_libdrizzle(void)
{
#if defined(HAVE_LIBDRIZZLE) && HAVE_LIBDRIZZLE
if (HAVE_LIBDRIZZLE)
{
return true;
}
#endif
return false;
}
bool has_postgres_support(void)
{
char *getenv_ptr;
if (bool((getenv_ptr= getenv("POSTGRES_IS_RUNNING_AND_SETUP"))))
{
(void)(getenv_ptr);
if (HAVE_LIBPQ)
{
return true;
}
}
return false;
}
bool has_gearmand()
{
#if defined(GEARMAND_BINARY) && defined(HAVE_GEARMAND_BINARY) && HAVE_GEARMAND_BINARY
if (HAVE_GEARMAND_BINARY)
{
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and
((strcmp(GEARMAND_BINARY, "./gearmand/gearmand") == 0) or (strcmp(GEARMAND_BINARY, "gearmand/gearmand") == 0)))
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << GEARMAND_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_drizzled()
{
#if defined(DRIZZLED_BINARY) && defined(HAVE_DRIZZLED_BINARY) && HAVE_DRIZZLED_BINARY && defined(HAVE_LIBMYSQL_BUILD) && HAVE_LIBMYSQL_BUILD
{
if (access(DRIZZLED_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
bool has_mysqld()
{
#if defined(MYSQLD_BINARY) && defined(HAVE_MYSQLD_BUILD) && HAVE_MYSQLD_BUILD && defined(HAVE_LIBMYSQL_BUILD) && HAVE_LIBMYSQL_BUILD
{
if (access(MYSQLD_BINARY, X_OK) == 0)
{
return true;
}
}
#endif
return false;
}
static char memcached_binary_path[FILENAME_MAX];
static void initialize_memcached_binary_path()
{
memcached_binary_path[0]= 0;
#if defined(MEMCACHED_BINARY) && defined(HAVE_MEMCACHED_BINARY) && HAVE_MEMCACHED_BINARY
if (HAVE_MEMCACHED_BINARY)
{
std::stringstream arg_buffer;
char *getenv_ptr;
if (bool((getenv_ptr= getenv("PWD"))) and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
{
arg_buffer << getenv_ptr;
arg_buffer << "/";
}
arg_buffer << MEMCACHED_BINARY;
if (access(arg_buffer.str().c_str(), X_OK) == 0)
{
strncpy(memcached_binary_path, arg_buffer.str().c_str(), FILENAME_MAX);
}
}
#endif
}
static pthread_once_t memcached_binary_once= PTHREAD_ONCE_INIT;
static void initialize_memcached_binary(void)
{
int ret;
if ((ret= pthread_once(&memcached_binary_once, initialize_memcached_binary_path)) != 0)
{
FATAL(strerror(ret));
}
}
bool has_memcached()
{
initialize_memcached_binary();
if (memcached_binary_path[0] and (strlen(memcached_binary_path) > 0))
{
return true;
}
return false;
}
const char* memcached_binary()
{
initialize_memcached_binary();
if (memcached_binary_path[0])
{
return memcached_binary_path;
}
return NULL;
}
const char *gearmand_binary()
{
#if defined(GEARMAND_BINARY)
return GEARMAND_BINARY;
#else
return NULL;
#endif
}
const char *drizzled_binary()
{
#if defined(DRIZZLED_BINARY)
return DRIZZLED_BINARY;
#else
return NULL;
#endif
}
} // namespace libtest
<|endoftext|> |
<commit_before>#include "aligner.h"
#include "array2d.h"
#include "hg.h"
#include "sentence_metadata.h"
#include "inside_outside.h"
#include "viterbi.h"
#include "alignment_pharaoh.h"
#include <set>
using namespace std;
// used with lexical models since they may not fully generate the
// source string
void SourceEdgeCoveragesUsingParseIndices(const Hypergraph& g,
vector<set<int> >* src_cov) {
src_cov->clear();
src_cov->resize(g.edges_.size());
for (int i = 0; i < g.edges_.size(); ++i) {
const Hypergraph::Edge& edge = g.edges_[i];
set<int>& cov = (*src_cov)[i];
// no words
if (edge.rule_->EWords() == 0 || edge.rule_->FWords() == 0)
continue;
// aligned to NULL (crf ibm variant only)
if (edge.prev_i_ == -1 || edge.i_ == -1) {
cov.insert(-1);
continue;
}
assert(edge.j_ >= 0);
assert(edge.prev_j_ >= 0);
if (edge.Arity() == 0) {
for (int k = edge.prev_i_; k < edge.prev_j_; ++k)
cov.insert(k);
} else {
// note: this code, which handles mixed NT and terminal
// rules assumes that nodes uniquely define a src and trg
// span.
int k = edge.prev_i_;
int j = 0;
const vector<WordID>& f = edge.rule_->e(); // rules are inverted
while (k < edge.prev_j_) {
if (f[j] > 0) {
cov.insert(k);
// cerr << "src: " << k << endl;
++k;
++j;
} else {
const Hypergraph::Node& tailnode = g.nodes_[edge.tail_nodes_[-f[j]]];
assert(tailnode.in_edges_.size() > 0);
// any edge will do:
const Hypergraph::Edge& rep_edge = g.edges_[tailnode.in_edges_.front()];
//cerr << "skip " << (rep_edge.prev_j_ - rep_edge.prev_i_) << endl; // src span
k += (rep_edge.prev_j_ - rep_edge.prev_i_); // src span
++j;
}
}
}
}
}
int SourceEdgeCoveragesUsingTree(const Hypergraph& g,
int node_id,
int span_start,
vector<int>* spans,
vector<set<int> >* src_cov) {
const Hypergraph::Node& node = g.nodes_[node_id];
int k = -1;
for (int i = 0; i < node.in_edges_.size(); ++i) {
const int edge_id = node.in_edges_[i];
const Hypergraph::Edge& edge = g.edges_[edge_id];
set<int>& cov = (*src_cov)[edge_id];
const vector<WordID>& f = edge.rule_->e(); // rules are inverted
int j = 0;
k = span_start;
while (j < f.size()) {
if (f[j] > 0) {
cov.insert(k);
++k;
++j;
} else {
const int tail_node_id = edge.tail_nodes_[-f[j]];
int &right_edge = (*spans)[tail_node_id];
if (right_edge < 0)
right_edge = SourceEdgeCoveragesUsingTree(g, tail_node_id, k, spans, src_cov);
k = right_edge;
++j;
}
}
}
return k;
}
void SourceEdgeCoveragesUsingTree(const Hypergraph& g,
vector<set<int> >* src_cov) {
src_cov->clear();
src_cov->resize(g.edges_.size());
vector<int> span_sizes(g.nodes_.size(), -1);
SourceEdgeCoveragesUsingTree(g, g.nodes_.size() - 1, 0, &span_sizes, src_cov);
}
int TargetEdgeCoveragesUsingTree(const Hypergraph& g,
int node_id,
int span_start,
vector<int>* spans,
vector<set<int> >* trg_cov) {
const Hypergraph::Node& node = g.nodes_[node_id];
int k = -1;
for (int i = 0; i < node.in_edges_.size(); ++i) {
const int edge_id = node.in_edges_[i];
const Hypergraph::Edge& edge = g.edges_[edge_id];
set<int>& cov = (*trg_cov)[edge_id];
int ntc = 0;
const vector<WordID>& e = edge.rule_->f(); // rules are inverted
int j = 0;
k = span_start;
while (j < e.size()) {
if (e[j] > 0) {
cov.insert(k);
++k;
++j;
} else {
const int tail_node_id = edge.tail_nodes_[ntc];
++ntc;
int &right_edge = (*spans)[tail_node_id];
if (right_edge < 0)
right_edge = TargetEdgeCoveragesUsingTree(g, tail_node_id, k, spans, trg_cov);
k = right_edge;
++j;
}
}
// cerr << "node=" << node_id << ": k=" << k << endl;
}
return k;
}
void TargetEdgeCoveragesUsingTree(const Hypergraph& g,
vector<set<int> >* trg_cov) {
trg_cov->clear();
trg_cov->resize(g.edges_.size());
vector<int> span_sizes(g.nodes_.size(), -1);
TargetEdgeCoveragesUsingTree(g, g.nodes_.size() - 1, 0, &span_sizes, trg_cov);
}
struct TransitionEventWeightFunction {
typedef SparseVector<prob_t> Result;
inline SparseVector<prob_t> operator()(const Hypergraph::Edge& e) const {
SparseVector<prob_t> result;
result.set_value(e.id_, e.edge_prob_);
return result;
}
};
// this code is rather complicated since it must deal with generating alignments
// when lattices are specified as input as well as with models that do not generate
// full sentence pairs (like lexical alignment models)
void AlignerTools::WriteAlignment(const Lattice& src_lattice,
const Lattice& trg_lattice,
const Hypergraph& in_g,
ostream* out,
bool map_instead_of_viterbi,
const vector<bool>* edges) {
bool fix_up_src_spans = false;
const Hypergraph* g = &in_g;
HypergraphP new_hg;
if (!src_lattice.IsSentence() ||
!trg_lattice.IsSentence()) {
if (map_instead_of_viterbi) {
cerr << " Lattice alignment: using Viterbi instead of MAP alignment\n";
}
map_instead_of_viterbi = false;
fix_up_src_spans = !src_lattice.IsSentence();
}
if (!map_instead_of_viterbi || edges) {
new_hg = in_g.CreateViterbiHypergraph(edges);
for (int i = 0; i < new_hg->edges_.size(); ++i)
new_hg->edges_[i].edge_prob_ = prob_t::One();
g = new_hg.get();
}
vector<prob_t> edge_posteriors(g->edges_.size(), prob_t::Zero());
vector<WordID> trg_sent;
vector<WordID> src_sent;
if (fix_up_src_spans) {
ViterbiESentence(*g, &src_sent);
} else {
src_sent.resize(src_lattice.size());
for (int i = 0; i < src_sent.size(); ++i)
src_sent[i] = src_lattice[i][0].label;
}
ViterbiFSentence(*g, &trg_sent);
if (edges || !map_instead_of_viterbi) {
for (int i = 0; i < edge_posteriors.size(); ++i)
edge_posteriors[i] = prob_t::One();
} else {
SparseVector<prob_t> posts;
const prob_t z = InsideOutside<prob_t, EdgeProb, SparseVector<prob_t>, TransitionEventWeightFunction>(*g, &posts);
for (int i = 0; i < edge_posteriors.size(); ++i)
edge_posteriors[i] = posts[i] / z;
}
vector<set<int> > src_cov(g->edges_.size());
vector<set<int> > trg_cov(g->edges_.size());
TargetEdgeCoveragesUsingTree(*g, &trg_cov);
if (fix_up_src_spans)
SourceEdgeCoveragesUsingTree(*g, &src_cov);
else
SourceEdgeCoveragesUsingParseIndices(*g, &src_cov);
// figure out the src and reference size;
int src_size = src_sent.size();
int ref_size = trg_sent.size();
Array2D<prob_t> align(src_size + 1, ref_size, prob_t::Zero());
for (int c = 0; c < g->edges_.size(); ++c) {
const prob_t& p = edge_posteriors[c];
const set<int>& srcs = src_cov[c];
const set<int>& trgs = trg_cov[c];
for (set<int>::const_iterator si = srcs.begin();
si != srcs.end(); ++si) {
for (set<int>::const_iterator ti = trgs.begin();
ti != trgs.end(); ++ti) {
align(*si + 1, *ti) += p;
}
}
}
new_hg.reset();
//if (g != &in_g) { g.reset(); }
prob_t threshold(0.9);
const bool use_soft_threshold = true; // TODO configure
Array2D<bool> grid(src_size, ref_size, false);
for (int j = 0; j < ref_size; ++j) {
if (use_soft_threshold) {
threshold = prob_t::Zero();
for (int i = 0; i <= src_size; ++i)
if (align(i, j) > threshold) threshold = align(i, j);
//threshold *= prob_t(0.99);
}
for (int i = 0; i < src_size; ++i)
grid(i, j) = align(i+1, j) >= threshold;
}
if (out == &cout) {
// TODO need to do some sort of verbose flag
cerr << align << endl;
cerr << grid << endl;
}
(*out) << TD::GetString(src_sent) << " ||| " << TD::GetString(trg_sent) << " ||| ";
AlignmentPharaoh::SerializePharaohFormat(grid, out);
};
<commit_msg>justify<commit_after>#include "aligner.h"
#include <cstdio>
#include <set>
#include "array2d.h"
#include "hg.h"
#include "sentence_metadata.h"
#include "inside_outside.h"
#include "viterbi.h"
#include "alignment_pharaoh.h"
using namespace std;
// used with lexical models since they may not fully generate the
// source string
void SourceEdgeCoveragesUsingParseIndices(const Hypergraph& g,
vector<set<int> >* src_cov) {
src_cov->clear();
src_cov->resize(g.edges_.size());
for (int i = 0; i < g.edges_.size(); ++i) {
const Hypergraph::Edge& edge = g.edges_[i];
set<int>& cov = (*src_cov)[i];
// no words
if (edge.rule_->EWords() == 0 || edge.rule_->FWords() == 0)
continue;
// aligned to NULL (crf ibm variant only)
if (edge.prev_i_ == -1 || edge.i_ == -1) {
cov.insert(-1);
continue;
}
assert(edge.j_ >= 0);
assert(edge.prev_j_ >= 0);
if (edge.Arity() == 0) {
for (int k = edge.prev_i_; k < edge.prev_j_; ++k)
cov.insert(k);
} else {
// note: this code, which handles mixed NT and terminal
// rules assumes that nodes uniquely define a src and trg
// span.
int k = edge.prev_i_;
int j = 0;
const vector<WordID>& f = edge.rule_->e(); // rules are inverted
while (k < edge.prev_j_) {
if (f[j] > 0) {
cov.insert(k);
// cerr << "src: " << k << endl;
++k;
++j;
} else {
const Hypergraph::Node& tailnode = g.nodes_[edge.tail_nodes_[-f[j]]];
assert(tailnode.in_edges_.size() > 0);
// any edge will do:
const Hypergraph::Edge& rep_edge = g.edges_[tailnode.in_edges_.front()];
//cerr << "skip " << (rep_edge.prev_j_ - rep_edge.prev_i_) << endl; // src span
k += (rep_edge.prev_j_ - rep_edge.prev_i_); // src span
++j;
}
}
}
}
}
int SourceEdgeCoveragesUsingTree(const Hypergraph& g,
int node_id,
int span_start,
vector<int>* spans,
vector<set<int> >* src_cov) {
const Hypergraph::Node& node = g.nodes_[node_id];
int k = -1;
for (int i = 0; i < node.in_edges_.size(); ++i) {
const int edge_id = node.in_edges_[i];
const Hypergraph::Edge& edge = g.edges_[edge_id];
set<int>& cov = (*src_cov)[edge_id];
const vector<WordID>& f = edge.rule_->e(); // rules are inverted
int j = 0;
k = span_start;
while (j < f.size()) {
if (f[j] > 0) {
cov.insert(k);
++k;
++j;
} else {
const int tail_node_id = edge.tail_nodes_[-f[j]];
int &right_edge = (*spans)[tail_node_id];
if (right_edge < 0)
right_edge = SourceEdgeCoveragesUsingTree(g, tail_node_id, k, spans, src_cov);
k = right_edge;
++j;
}
}
}
return k;
}
void SourceEdgeCoveragesUsingTree(const Hypergraph& g,
vector<set<int> >* src_cov) {
src_cov->clear();
src_cov->resize(g.edges_.size());
vector<int> span_sizes(g.nodes_.size(), -1);
SourceEdgeCoveragesUsingTree(g, g.nodes_.size() - 1, 0, &span_sizes, src_cov);
}
int TargetEdgeCoveragesUsingTree(const Hypergraph& g,
int node_id,
int span_start,
vector<int>* spans,
vector<set<int> >* trg_cov) {
const Hypergraph::Node& node = g.nodes_[node_id];
int k = -1;
for (int i = 0; i < node.in_edges_.size(); ++i) {
const int edge_id = node.in_edges_[i];
const Hypergraph::Edge& edge = g.edges_[edge_id];
set<int>& cov = (*trg_cov)[edge_id];
int ntc = 0;
const vector<WordID>& e = edge.rule_->f(); // rules are inverted
int j = 0;
k = span_start;
while (j < e.size()) {
if (e[j] > 0) {
cov.insert(k);
++k;
++j;
} else {
const int tail_node_id = edge.tail_nodes_[ntc];
++ntc;
int &right_edge = (*spans)[tail_node_id];
if (right_edge < 0)
right_edge = TargetEdgeCoveragesUsingTree(g, tail_node_id, k, spans, trg_cov);
k = right_edge;
++j;
}
}
// cerr << "node=" << node_id << ": k=" << k << endl;
}
return k;
}
void TargetEdgeCoveragesUsingTree(const Hypergraph& g,
vector<set<int> >* trg_cov) {
trg_cov->clear();
trg_cov->resize(g.edges_.size());
vector<int> span_sizes(g.nodes_.size(), -1);
TargetEdgeCoveragesUsingTree(g, g.nodes_.size() - 1, 0, &span_sizes, trg_cov);
}
struct TransitionEventWeightFunction {
typedef SparseVector<prob_t> Result;
inline SparseVector<prob_t> operator()(const Hypergraph::Edge& e) const {
SparseVector<prob_t> result;
result.set_value(e.id_, e.edge_prob_);
return result;
}
};
inline void WriteProbGrid(const Array2D<prob_t>& m, ostream* pos) {
ostream& os = *pos;
char b[1024];
for (int i=0; i<m.width(); ++i) {
for (int j=0; j<m.height(); ++j) {
if (m(i,j) == prob_t::Zero()) {
os << "\t---X---";
} else {
snprintf(b, 1024, "%0.5f", static_cast<double>(m(i,j)));
os << '\t' << b;
}
}
os << '\n';
}
}
// this code is rather complicated since it must deal with generating alignments
// when lattices are specified as input as well as with models that do not generate
// full sentence pairs (like lexical alignment models)
void AlignerTools::WriteAlignment(const Lattice& src_lattice,
const Lattice& trg_lattice,
const Hypergraph& in_g,
ostream* out,
bool map_instead_of_viterbi,
const vector<bool>* edges) {
bool fix_up_src_spans = false;
const Hypergraph* g = &in_g;
HypergraphP new_hg;
if (!src_lattice.IsSentence() ||
!trg_lattice.IsSentence()) {
if (map_instead_of_viterbi) {
cerr << " Lattice alignment: using Viterbi instead of MAP alignment\n";
}
map_instead_of_viterbi = false;
fix_up_src_spans = !src_lattice.IsSentence();
}
if (!map_instead_of_viterbi || edges) {
new_hg = in_g.CreateViterbiHypergraph(edges);
for (int i = 0; i < new_hg->edges_.size(); ++i)
new_hg->edges_[i].edge_prob_ = prob_t::One();
g = new_hg.get();
}
vector<prob_t> edge_posteriors(g->edges_.size(), prob_t::Zero());
vector<WordID> trg_sent;
vector<WordID> src_sent;
if (fix_up_src_spans) {
ViterbiESentence(*g, &src_sent);
} else {
src_sent.resize(src_lattice.size());
for (int i = 0; i < src_sent.size(); ++i)
src_sent[i] = src_lattice[i][0].label;
}
ViterbiFSentence(*g, &trg_sent);
if (edges || !map_instead_of_viterbi) {
for (int i = 0; i < edge_posteriors.size(); ++i)
edge_posteriors[i] = prob_t::One();
} else {
SparseVector<prob_t> posts;
const prob_t z = InsideOutside<prob_t, EdgeProb, SparseVector<prob_t>, TransitionEventWeightFunction>(*g, &posts);
for (int i = 0; i < edge_posteriors.size(); ++i)
edge_posteriors[i] = posts[i] / z;
}
vector<set<int> > src_cov(g->edges_.size());
vector<set<int> > trg_cov(g->edges_.size());
TargetEdgeCoveragesUsingTree(*g, &trg_cov);
if (fix_up_src_spans)
SourceEdgeCoveragesUsingTree(*g, &src_cov);
else
SourceEdgeCoveragesUsingParseIndices(*g, &src_cov);
// figure out the src and reference size;
int src_size = src_sent.size();
int ref_size = trg_sent.size();
Array2D<prob_t> align(src_size + 1, ref_size, prob_t::Zero());
for (int c = 0; c < g->edges_.size(); ++c) {
const prob_t& p = edge_posteriors[c];
const set<int>& srcs = src_cov[c];
const set<int>& trgs = trg_cov[c];
for (set<int>::const_iterator si = srcs.begin();
si != srcs.end(); ++si) {
for (set<int>::const_iterator ti = trgs.begin();
ti != trgs.end(); ++ti) {
align(*si + 1, *ti) += p;
}
}
}
new_hg.reset();
//if (g != &in_g) { g.reset(); }
prob_t threshold(0.9);
const bool use_soft_threshold = true; // TODO configure
Array2D<bool> grid(src_size, ref_size, false);
for (int j = 0; j < ref_size; ++j) {
if (use_soft_threshold) {
threshold = prob_t::Zero();
for (int i = 0; i <= src_size; ++i)
if (align(i, j) > threshold) threshold = align(i, j);
//threshold *= prob_t(0.99);
}
for (int i = 0; i < src_size; ++i)
grid(i, j) = align(i+1, j) >= threshold;
}
if (out == &cout) {
// TODO need to do some sort of verbose flag
WriteProbGrid(align, &cerr);
cerr << grid << endl;
}
(*out) << TD::GetString(src_sent) << " ||| " << TD::GetString(trg_sent) << " ||| ";
AlignmentPharaoh::SerializePharaohFormat(grid, out);
};
<|endoftext|> |
<commit_before>#pragma once
#include <agency/detail/config.hpp>
#include <agency/cuda/detail/feature_test.hpp>
#include <agency/cuda/detail/terminate.hpp>
#include <agency/cuda/device.hpp>
#include <memory>
namespace agency
{
namespace cuda
{
namespace detail
{
class stream
{
public:
// creates a new stream associated with the current device
inline __host__ __device__
stream()
: device_(current_device())
{
#if __cuda_lib_has_cudart
detail::throw_on_error(cudaStreamCreate(&s_), "cudaStreamCreate in cuda::detail::stream ctor");
#else
detail::terminate_with_message("cuda::detail::stream ctor requires CUDART");
#endif
}
// creates a new stream associated with the given device
inline __host__ __device__
stream(device_id g)
: device_(g)
{
auto old_device = current_device();
#if __cuda_lib_has_cudart
# ifdef __CUDA_ARCH__
assert(g == old_device);
# else
detail::throw_on_error(cudaSetDevice(device().native_handle()), "cudaSetDevice in cuda::detail::stream ctor");
# endif
detail::throw_on_error(cudaStreamCreate(&s_), "cudaStreamCreate in cuda::detail::stream ctor");
# ifdef __CUDA_ARCH__
detail::throw_on_error(cudaSetDevice(old_device.native_handle()), "cudaSetDevice in cuda::detail::stream ctor");
# endif
#else
detail::terminate_with_message("cuda::detail::stream ctor requires CUDART");
#endif
}
inline __host__ __device__
stream(stream&& other)
: device_(other.device()), s_{}
{
s_ = other.s_;
other.s_ = 0;
}
inline __host__ __device__
~stream()
{
#if __cuda_lib_has_cudart
if(s_ != 0)
{
detail::terminate_on_error(cudaStreamDestroy(s_), "cudaStreamDestroy in cuda::detail::stream dtor");
}
#else
detail::terminate_with_message("cuda::detail::stream dtor requires CUDART");
#endif
}
inline __host__ __device__
device_id device() const
{
return device_;
}
inline __host__ __device__
cudaStream_t native_handle() const
{
return s_;
}
inline __host__ __device__
void swap(stream& other)
{
device_id tmp1 = device_;
device_ = other.device_;
other.device_ = tmp1;
cudaStream_t tmp2 = s_;
s_ = other.s_;
other.s_ = tmp2;
}
private:
static void callback(cudaStream_t, cudaError_t, void* user_data)
{
// XXX should maybe look at the CUDA error
// convert user_data into a pointer to std::function and immediately put it inside unique_ptr
std::unique_ptr<std::function<void()>> f_ptr(reinterpret_cast<std::function<void()>*>(user_data));
// call f
(*f_ptr)();
}
public:
template<class Function>
void add_callback(Function f)
{
// make a copy of f and put it inside a std::unique_ptr to std::function
std::unique_ptr<std::function<void()>> ptr_to_fun(new std::function<void()>(f));
// release the unique_ptr's pointer into cudaStreamAddCallback()
detail::throw_on_error(cudaStreamAddCallback(native_handle(), callback, ptr_to_fun.release(), 0), "cudaStreamAddCallback in cuda::detail::stream::add_callback()");
}
private:
device_id device_;
cudaStream_t s_;
};
} // end detail
} // end cuda
} // end agency
<commit_msg>Don't throw exceptions from cuda::detail::stream's destructor<commit_after>#pragma once
#include <agency/detail/config.hpp>
#include <agency/cuda/detail/feature_test.hpp>
#include <agency/cuda/detail/terminate.hpp>
#include <agency/cuda/device.hpp>
#include <memory>
namespace agency
{
namespace cuda
{
namespace detail
{
class stream
{
public:
// creates a new stream associated with the current device
inline __host__ __device__
stream()
: device_(current_device())
{
#if __cuda_lib_has_cudart
detail::throw_on_error(cudaStreamCreate(&s_), "cudaStreamCreate in cuda::detail::stream ctor");
#else
detail::terminate_with_message("cuda::detail::stream ctor requires CUDART");
#endif
}
// creates a new stream associated with the given device
inline __host__ __device__
stream(device_id g)
: device_(g)
{
auto old_device = current_device();
#if __cuda_lib_has_cudart
# ifdef __CUDA_ARCH__
assert(g == old_device);
# else
detail::throw_on_error(cudaSetDevice(device().native_handle()), "cudaSetDevice in cuda::detail::stream ctor");
# endif
detail::throw_on_error(cudaStreamCreate(&s_), "cudaStreamCreate in cuda::detail::stream ctor");
# ifdef __CUDA_ARCH__
detail::throw_on_error(cudaSetDevice(old_device.native_handle()), "cudaSetDevice in cuda::detail::stream ctor");
# endif
#else
detail::terminate_with_message("cuda::detail::stream ctor requires CUDART");
#endif
}
inline __host__ __device__
stream(stream&& other)
: device_(other.device()), s_{}
{
s_ = other.s_;
other.s_ = 0;
}
inline __host__ __device__
~stream()
{
#if __cuda_lib_has_cudart
if(s_ != 0)
{
// avoid propagating an exception but report the error if one exists
detail::print_error_message_if(cudaStreamDestroy(s_), "cudaStreamDestroy in cuda::detail::stream dtor");
}
#else
detail::terminate_with_message("cuda::detail::stream dtor requires CUDART");
#endif
}
inline __host__ __device__
device_id device() const
{
return device_;
}
inline __host__ __device__
cudaStream_t native_handle() const
{
return s_;
}
inline __host__ __device__
void swap(stream& other)
{
device_id tmp1 = device_;
device_ = other.device_;
other.device_ = tmp1;
cudaStream_t tmp2 = s_;
s_ = other.s_;
other.s_ = tmp2;
}
private:
static void callback(cudaStream_t, cudaError_t, void* user_data)
{
// XXX should maybe look at the CUDA error
// convert user_data into a pointer to std::function and immediately put it inside unique_ptr
std::unique_ptr<std::function<void()>> f_ptr(reinterpret_cast<std::function<void()>*>(user_data));
// call f
(*f_ptr)();
}
public:
template<class Function>
void add_callback(Function f)
{
// make a copy of f and put it inside a std::unique_ptr to std::function
std::unique_ptr<std::function<void()>> ptr_to_fun(new std::function<void()>(f));
// release the unique_ptr's pointer into cudaStreamAddCallback()
detail::throw_on_error(cudaStreamAddCallback(native_handle(), callback, ptr_to_fun.release(), 0), "cudaStreamAddCallback in cuda::detail::stream::add_callback()");
}
private:
device_id device_;
cudaStream_t s_;
};
} // end detail
} // end cuda
} // end agency
<|endoftext|> |
<commit_before>/*
Copyright (C) 2020 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#ifndef TELEGRAMQT_COMPAT_LAYER_HPP
#define TELEGRAMQT_COMPAT_LAYER_HPP
#include "telegramqt_global.h"
#include <QString>
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
#define TELEGRAMQT_HEX_SHOWBASE hex << showbase
#define TELEGRAMQT_ENDL endl
#else
#define TELEGRAMQT_HEX_SHOWBASE Qt::hex << Qt::showbase
#define TELEGRAMQT_ENDL Qt::endl
#endif
namespace Telegram {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
inline QStringView getStringMidView(const QString &string, qsizetype pos, qsizetype n = -1)
{
return QStringView(string).mid(pos, n);
}
#else
inline QStringRef getStringMidView(const QString &string, int pos, int n = -1)
{
return string.midRef(pos, n);
}
#endif
} // Telegram namespace
#endif // TELEGRAMQT_COMPAT_LAYER_HPP
<commit_msg>CompatibilityLayer: Add compat for Qt::flush<commit_after>/*
Copyright (C) 2020 Alexandr Akulich <akulichalexander@gmail.com>
This file is a part of TelegramQt library.
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.
*/
#ifndef TELEGRAMQT_COMPAT_LAYER_HPP
#define TELEGRAMQT_COMPAT_LAYER_HPP
#include "telegramqt_global.h"
#include <QString>
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
#define TELEGRAMQT_HEX_SHOWBASE hex << showbase
#define TELEGRAMQT_ENDL endl
#define TELEGRAMQT_FLUSH flush
#else
#define TELEGRAMQT_HEX_SHOWBASE Qt::hex << Qt::showbase
#define TELEGRAMQT_ENDL Qt::endl
#define TELEGRAMQT_FLUSH Qt::flush
#endif
namespace Telegram {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
inline QStringView getStringMidView(const QString &string, qsizetype pos, qsizetype n = -1)
{
return QStringView(string).mid(pos, n);
}
#else
inline QStringRef getStringMidView(const QString &string, int pos, int n = -1)
{
return string.midRef(pos, n);
}
#endif
} // Telegram namespace
#endif // TELEGRAMQT_COMPAT_LAYER_HPP
<|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 <windows.h>
#include <shlwapi.h>
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/environment.h"
#include "base/file_version_info.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "base/version.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "chrome/app/chrome_crash_reporter_client.h"
#include "chrome/app/chrome_watcher_client_win.h"
#include "chrome/app/chrome_watcher_command_line_win.h"
#include "chrome/app/client_util.h"
#include "chrome/app/image_pre_reader_win.h"
#include "chrome/app/kasko_client.h"
#include "chrome/chrome_watcher/chrome_watcher_main_api.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/util_constants.h"
#include "components/crash/app/breakpad_win.h"
#include "components/crash/app/crash_reporter_client.h"
#include "components/metrics/client_info.h"
#include "content/public/app/startup_helper_win.h"
#include "sandbox/win/src/sandbox.h"
namespace {
// The entry point signature of chrome.dll.
typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*);
typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
// Loads |module| after setting the CWD to |module|'s directory. Returns a
// reference to the loaded module on success, or null on error.
HMODULE LoadModuleWithDirectory(const base::FilePath& module, bool pre_read) {
::SetCurrentDirectoryW(module.DirName().value().c_str());
if (pre_read) {
// We pre-read the binary to warm the memory caches (fewer hard faults to
// page parts of the binary in).
const size_t kStepSize = 1024 * 1024;
size_t percent = 100;
ImagePreReader::PartialPreReadImage(module.value().c_str(), percent,
kStepSize);
}
return ::LoadLibraryExW(module.value().c_str(), nullptr,
LOAD_WITH_ALTERED_SEARCH_PATH);
}
void RecordDidRun(const base::FilePath& dll_path) {
bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
GoogleUpdateSettings::UpdateDidRunState(true, system_level);
}
void ClearDidRun(const base::FilePath& dll_path) {
bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
GoogleUpdateSettings::UpdateDidRunState(false, system_level);
}
bool InMetroMode() {
return (wcsstr(
::GetCommandLineW(), L" -ServerName:DefaultBrowserServer") != nullptr);
}
typedef int (*InitMetro)();
// Returns the directory in which the currently running executable resides.
base::FilePath GetExecutableDir() {
base::char16 path[MAX_PATH];
::GetModuleFileNameW(nullptr, path, MAX_PATH);
return base::FilePath(path).DirName();
}
} // namespace
base::string16 GetCurrentModuleVersion() {
scoped_ptr<FileVersionInfo> file_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
if (file_version_info.get()) {
base::string16 version_string(file_version_info->file_version());
if (Version(base::UTF16ToASCII(version_string)).IsValid())
return version_string;
}
return base::string16();
}
//=============================================================================
MainDllLoader::MainDllLoader()
: dll_(nullptr), metro_mode_(InMetroMode()) {
}
MainDllLoader::~MainDllLoader() {
}
// Loading chrome is an interesting affair. First we try loading from the
// current directory to support run-what-you-compile and other development
// scenarios.
// If that fails then we look at the version resource in the current
// module. This is the expected path for chrome.exe browser instances in an
// installed build.
HMODULE MainDllLoader::Load(base::string16* version, base::FilePath* module) {
const base::char16* dll_name = nullptr;
if (metro_mode_) {
dll_name = installer::kChromeMetroDll;
} else if (process_type_ == "service" || process_type_.empty()) {
dll_name = installer::kChromeDll;
} else if (process_type_ == "watcher") {
dll_name = kChromeWatcherDll;
} else {
#if defined(CHROME_MULTIPLE_DLL)
dll_name = installer::kChromeChildDll;
#else
dll_name = installer::kChromeDll;
#endif
}
const bool pre_read = !metro_mode_;
base::FilePath module_dir = GetExecutableDir();
*module = module_dir.Append(dll_name);
HMODULE dll = LoadModuleWithDirectory(*module, pre_read);
if (!dll) {
base::string16 version_string(GetCurrentModuleVersion());
if (version_string.empty()) {
LOG(ERROR) << "No valid Chrome version found";
return nullptr;
}
*version = version_string;
*module = module_dir.Append(version_string).Append(dll_name);
dll = LoadModuleWithDirectory(*module, pre_read);
if (!dll) {
PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value();
return nullptr;
}
}
DCHECK(dll);
return dll;
}
// Launching is a matter of loading the right dll, setting the CHROME_VERSION
// environment variable and just calling the entry point. Derived classes can
// add custom code in the OnBeforeLaunch callback.
int MainDllLoader::Launch(HINSTANCE instance) {
const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
base::string16 version;
base::FilePath file;
if (metro_mode_) {
HMODULE metro_dll = Load(&version, &file);
if (!metro_dll)
return chrome::RESULT_CODE_MISSING_DATA;
InitMetro chrome_metro_main =
reinterpret_cast<InitMetro>(::GetProcAddress(metro_dll, "InitMetro"));
return chrome_metro_main();
}
if (process_type_ == "watcher") {
chrome::RegisterPathProvider();
base::win::ScopedHandle parent_process;
base::win::ScopedHandle on_initialized_event;
if (!InterpretChromeWatcherCommandLine(cmd_line, &parent_process,
&on_initialized_event)) {
return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
}
base::FilePath default_user_data_directory;
if (!PathService::Get(chrome::DIR_USER_DATA, &default_user_data_directory))
return chrome::RESULT_CODE_MISSING_DATA;
// The actual user data directory may differ from the default according to
// policy and command-line arguments evaluated in the browser process.
// The hang monitor will simply be disabled if a window with this name is
// never instantiated by the browser process. Since this should be
// exceptionally rare it should not impact stability efforts.
base::string16 message_window_name = default_user_data_directory.value();
base::FilePath watcher_data_directory;
if (!PathService::Get(chrome::DIR_WATCHER_DATA, &watcher_data_directory))
return chrome::RESULT_CODE_MISSING_DATA;
base::string16 channel_name = GoogleUpdateSettings::GetChromeChannel(
!InstallUtil::IsPerUserInstall(cmd_line.GetProgram()));
// Intentionally leaked.
HMODULE watcher_dll = Load(&version, &file);
if (!watcher_dll)
return chrome::RESULT_CODE_MISSING_DATA;
ChromeWatcherMainFunction watcher_main =
reinterpret_cast<ChromeWatcherMainFunction>(
::GetProcAddress(watcher_dll, kChromeWatcherDLLEntrypoint));
return watcher_main(chrome::kBrowserExitCodesRegistryPath,
parent_process.Take(), on_initialized_event.Take(),
watcher_data_directory.value().c_str(),
message_window_name.c_str(), channel_name.c_str());
}
// Initialize the sandbox services.
sandbox::SandboxInterfaceInfo sandbox_info = {0};
content::InitializeSandboxInfo(&sandbox_info);
crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
bool exit_now = true;
if (process_type_.empty()) {
if (breakpad::ShowRestartDialogIfCrashed(&exit_now)) {
// We restarted because of a previous crash. Ask user if we should
// Relaunch. Only for the browser process. See crbug.com/132119.
if (exit_now)
return content::RESULT_CODE_NORMAL_EXIT;
}
}
breakpad::InitCrashReporter(process_type_);
dll_ = Load(&version, &file);
if (!dll_)
return chrome::RESULT_CODE_MISSING_DATA;
scoped_ptr<base::Environment> env(base::Environment::Create());
env->SetVar(chrome::kChromeVersionEnvVar, base::WideToUTF8(version));
OnBeforeLaunch(process_type_, file);
DLL_MAIN chrome_main =
reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
int rc = chrome_main(instance, &sandbox_info);
rc = OnBeforeExit(rc, file);
// Sandboxed processes close some system DLL handles after lockdown so ignore
// EXCEPTION_INVALID_HANDLE generated on Windows 10 during shutdown of these
// processes.
// TODO(wfh): Check whether MS have fixed this in Win10 RTM. crbug.com/456193
if (base::win::GetVersion() >= base::win::VERSION_WIN10)
breakpad::ConsumeInvalidHandleExceptions();
return rc;
}
void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
if (!dll_)
return;
RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
::GetProcAddress(dll_,
"RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
if (!relaunch_function) {
LOG(ERROR) << "Could not find exported function "
<< "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
} else {
relaunch_function();
}
}
//=============================================================================
class ChromeDllLoader : public MainDllLoader {
protected:
// MainDllLoader implementation.
void OnBeforeLaunch(const std::string& process_type,
const base::FilePath& dll_path) override;
int OnBeforeExit(int return_code, const base::FilePath& dll_path) override;
private:
scoped_ptr<ChromeWatcherClient> chrome_watcher_client_;
#if defined(KASKO)
scoped_ptr<KaskoClient> kasko_client_;
#endif // KASKO
};
void ChromeDllLoader::OnBeforeLaunch(const std::string& process_type,
const base::FilePath& dll_path) {
if (process_type.empty()) {
RecordDidRun(dll_path);
// Launch the watcher process if stats collection consent has been granted.
if (g_chrome_crash_client.Get().GetCollectStatsConsent()) {
base::FilePath exe_path;
if (PathService::Get(base::FILE_EXE, &exe_path)) {
chrome_watcher_client_.reset(new ChromeWatcherClient(
base::Bind(&GenerateChromeWatcherCommandLine, exe_path)));
if (chrome_watcher_client_->LaunchWatcher()) {
#if defined(KASKO)
kasko::api::MinidumpType minidump_type = kasko::api::SMALL_DUMP_TYPE;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFullMemoryCrashReport)) {
minidump_type = kasko::api::FULL_DUMP_TYPE;
} else {
bool is_per_user_install =
g_chrome_crash_client.Get().GetIsPerUserInstall(
base::FilePath(exe_path));
if (g_chrome_crash_client.Get().GetShouldDumpLargerDumps(
is_per_user_install)){
minidump_type = kasko::api::LARGER_DUMP_TYPE;
}
}
kasko_client_.reset(
new KaskoClient(chrome_watcher_client_.get(), minidump_type));
#endif // KASKO
}
}
}
} else {
// Set non-browser processes up to be killed by the system after the browser
// goes away. The browser uses the default shutdown order, which is 0x280.
// This gets rid of most of those unsighly sad tabs on logout and shutdown.
::SetProcessShutdownParameters(0x281, SHUTDOWN_NORETRY);
}
}
int ChromeDllLoader::OnBeforeExit(int return_code,
const base::FilePath& dll_path) {
// NORMAL_EXIT_CANCEL is used for experiments when the user cancels
// so we need to reset the did_run signal so omaha does not count
// this run as active usage.
if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
ClearDidRun(dll_path);
}
#if defined(KASKO)
kasko_client_.reset();
#endif // KASKO
chrome_watcher_client_.reset();
return return_code;
}
//=============================================================================
class ChromiumDllLoader : public MainDllLoader {
protected:
void OnBeforeLaunch(const std::string& process_type,
const base::FilePath& dll_path) override {}
int OnBeforeExit(int return_code, const base::FilePath& dll_path) override {
return return_code;
}
};
MainDllLoader* MakeMainDllLoader() {
#if defined(GOOGLE_CHROME_BUILD)
return new ChromeDllLoader();
#else
return new ChromiumDllLoader();
#endif
}
<commit_msg>Fix the non-browser shutdown order to go after the browser, not before.<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 <windows.h>
#include <shlwapi.h>
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/environment.h"
#include "base/file_version_info.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "base/version.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "chrome/app/chrome_crash_reporter_client.h"
#include "chrome/app/chrome_watcher_client_win.h"
#include "chrome/app/chrome_watcher_command_line_win.h"
#include "chrome/app/client_util.h"
#include "chrome/app/image_pre_reader_win.h"
#include "chrome/app/kasko_client.h"
#include "chrome/chrome_watcher/chrome_watcher_main_api.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/util_constants.h"
#include "components/crash/app/breakpad_win.h"
#include "components/crash/app/crash_reporter_client.h"
#include "components/metrics/client_info.h"
#include "content/public/app/startup_helper_win.h"
#include "sandbox/win/src/sandbox.h"
namespace {
// The entry point signature of chrome.dll.
typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*);
typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
base::LazyInstance<chrome::ChromeCrashReporterClient>::Leaky
g_chrome_crash_client = LAZY_INSTANCE_INITIALIZER;
// Loads |module| after setting the CWD to |module|'s directory. Returns a
// reference to the loaded module on success, or null on error.
HMODULE LoadModuleWithDirectory(const base::FilePath& module, bool pre_read) {
::SetCurrentDirectoryW(module.DirName().value().c_str());
if (pre_read) {
// We pre-read the binary to warm the memory caches (fewer hard faults to
// page parts of the binary in).
const size_t kStepSize = 1024 * 1024;
size_t percent = 100;
ImagePreReader::PartialPreReadImage(module.value().c_str(), percent,
kStepSize);
}
return ::LoadLibraryExW(module.value().c_str(), nullptr,
LOAD_WITH_ALTERED_SEARCH_PATH);
}
void RecordDidRun(const base::FilePath& dll_path) {
bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
GoogleUpdateSettings::UpdateDidRunState(true, system_level);
}
void ClearDidRun(const base::FilePath& dll_path) {
bool system_level = !InstallUtil::IsPerUserInstall(dll_path);
GoogleUpdateSettings::UpdateDidRunState(false, system_level);
}
bool InMetroMode() {
return (wcsstr(
::GetCommandLineW(), L" -ServerName:DefaultBrowserServer") != nullptr);
}
typedef int (*InitMetro)();
// Returns the directory in which the currently running executable resides.
base::FilePath GetExecutableDir() {
base::char16 path[MAX_PATH];
::GetModuleFileNameW(nullptr, path, MAX_PATH);
return base::FilePath(path).DirName();
}
} // namespace
base::string16 GetCurrentModuleVersion() {
scoped_ptr<FileVersionInfo> file_version_info(
FileVersionInfo::CreateFileVersionInfoForCurrentModule());
if (file_version_info.get()) {
base::string16 version_string(file_version_info->file_version());
if (Version(base::UTF16ToASCII(version_string)).IsValid())
return version_string;
}
return base::string16();
}
//=============================================================================
MainDllLoader::MainDllLoader()
: dll_(nullptr), metro_mode_(InMetroMode()) {
}
MainDllLoader::~MainDllLoader() {
}
// Loading chrome is an interesting affair. First we try loading from the
// current directory to support run-what-you-compile and other development
// scenarios.
// If that fails then we look at the version resource in the current
// module. This is the expected path for chrome.exe browser instances in an
// installed build.
HMODULE MainDllLoader::Load(base::string16* version, base::FilePath* module) {
const base::char16* dll_name = nullptr;
if (metro_mode_) {
dll_name = installer::kChromeMetroDll;
} else if (process_type_ == "service" || process_type_.empty()) {
dll_name = installer::kChromeDll;
} else if (process_type_ == "watcher") {
dll_name = kChromeWatcherDll;
} else {
#if defined(CHROME_MULTIPLE_DLL)
dll_name = installer::kChromeChildDll;
#else
dll_name = installer::kChromeDll;
#endif
}
const bool pre_read = !metro_mode_;
base::FilePath module_dir = GetExecutableDir();
*module = module_dir.Append(dll_name);
HMODULE dll = LoadModuleWithDirectory(*module, pre_read);
if (!dll) {
base::string16 version_string(GetCurrentModuleVersion());
if (version_string.empty()) {
LOG(ERROR) << "No valid Chrome version found";
return nullptr;
}
*version = version_string;
*module = module_dir.Append(version_string).Append(dll_name);
dll = LoadModuleWithDirectory(*module, pre_read);
if (!dll) {
PLOG(ERROR) << "Failed to load Chrome DLL from " << module->value();
return nullptr;
}
}
DCHECK(dll);
return dll;
}
// Launching is a matter of loading the right dll, setting the CHROME_VERSION
// environment variable and just calling the entry point. Derived classes can
// add custom code in the OnBeforeLaunch callback.
int MainDllLoader::Launch(HINSTANCE instance) {
const base::CommandLine& cmd_line = *base::CommandLine::ForCurrentProcess();
process_type_ = cmd_line.GetSwitchValueASCII(switches::kProcessType);
base::string16 version;
base::FilePath file;
if (metro_mode_) {
HMODULE metro_dll = Load(&version, &file);
if (!metro_dll)
return chrome::RESULT_CODE_MISSING_DATA;
InitMetro chrome_metro_main =
reinterpret_cast<InitMetro>(::GetProcAddress(metro_dll, "InitMetro"));
return chrome_metro_main();
}
if (process_type_ == "watcher") {
chrome::RegisterPathProvider();
base::win::ScopedHandle parent_process;
base::win::ScopedHandle on_initialized_event;
if (!InterpretChromeWatcherCommandLine(cmd_line, &parent_process,
&on_initialized_event)) {
return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
}
base::FilePath default_user_data_directory;
if (!PathService::Get(chrome::DIR_USER_DATA, &default_user_data_directory))
return chrome::RESULT_CODE_MISSING_DATA;
// The actual user data directory may differ from the default according to
// policy and command-line arguments evaluated in the browser process.
// The hang monitor will simply be disabled if a window with this name is
// never instantiated by the browser process. Since this should be
// exceptionally rare it should not impact stability efforts.
base::string16 message_window_name = default_user_data_directory.value();
base::FilePath watcher_data_directory;
if (!PathService::Get(chrome::DIR_WATCHER_DATA, &watcher_data_directory))
return chrome::RESULT_CODE_MISSING_DATA;
base::string16 channel_name = GoogleUpdateSettings::GetChromeChannel(
!InstallUtil::IsPerUserInstall(cmd_line.GetProgram()));
// Intentionally leaked.
HMODULE watcher_dll = Load(&version, &file);
if (!watcher_dll)
return chrome::RESULT_CODE_MISSING_DATA;
ChromeWatcherMainFunction watcher_main =
reinterpret_cast<ChromeWatcherMainFunction>(
::GetProcAddress(watcher_dll, kChromeWatcherDLLEntrypoint));
return watcher_main(chrome::kBrowserExitCodesRegistryPath,
parent_process.Take(), on_initialized_event.Take(),
watcher_data_directory.value().c_str(),
message_window_name.c_str(), channel_name.c_str());
}
// Initialize the sandbox services.
sandbox::SandboxInterfaceInfo sandbox_info = {0};
content::InitializeSandboxInfo(&sandbox_info);
crash_reporter::SetCrashReporterClient(g_chrome_crash_client.Pointer());
bool exit_now = true;
if (process_type_.empty()) {
if (breakpad::ShowRestartDialogIfCrashed(&exit_now)) {
// We restarted because of a previous crash. Ask user if we should
// Relaunch. Only for the browser process. See crbug.com/132119.
if (exit_now)
return content::RESULT_CODE_NORMAL_EXIT;
}
}
breakpad::InitCrashReporter(process_type_);
dll_ = Load(&version, &file);
if (!dll_)
return chrome::RESULT_CODE_MISSING_DATA;
scoped_ptr<base::Environment> env(base::Environment::Create());
env->SetVar(chrome::kChromeVersionEnvVar, base::WideToUTF8(version));
OnBeforeLaunch(process_type_, file);
DLL_MAIN chrome_main =
reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
int rc = chrome_main(instance, &sandbox_info);
rc = OnBeforeExit(rc, file);
// Sandboxed processes close some system DLL handles after lockdown so ignore
// EXCEPTION_INVALID_HANDLE generated on Windows 10 during shutdown of these
// processes.
// TODO(wfh): Check whether MS have fixed this in Win10 RTM. crbug.com/456193
if (base::win::GetVersion() >= base::win::VERSION_WIN10)
breakpad::ConsumeInvalidHandleExceptions();
return rc;
}
void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
if (!dll_)
return;
RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
::GetProcAddress(dll_,
"RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
if (!relaunch_function) {
LOG(ERROR) << "Could not find exported function "
<< "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
} else {
relaunch_function();
}
}
//=============================================================================
class ChromeDllLoader : public MainDllLoader {
protected:
// MainDllLoader implementation.
void OnBeforeLaunch(const std::string& process_type,
const base::FilePath& dll_path) override;
int OnBeforeExit(int return_code, const base::FilePath& dll_path) override;
private:
scoped_ptr<ChromeWatcherClient> chrome_watcher_client_;
#if defined(KASKO)
scoped_ptr<KaskoClient> kasko_client_;
#endif // KASKO
};
void ChromeDllLoader::OnBeforeLaunch(const std::string& process_type,
const base::FilePath& dll_path) {
if (process_type.empty()) {
RecordDidRun(dll_path);
// Launch the watcher process if stats collection consent has been granted.
if (g_chrome_crash_client.Get().GetCollectStatsConsent()) {
base::FilePath exe_path;
if (PathService::Get(base::FILE_EXE, &exe_path)) {
chrome_watcher_client_.reset(new ChromeWatcherClient(
base::Bind(&GenerateChromeWatcherCommandLine, exe_path)));
if (chrome_watcher_client_->LaunchWatcher()) {
#if defined(KASKO)
kasko::api::MinidumpType minidump_type = kasko::api::SMALL_DUMP_TYPE;
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFullMemoryCrashReport)) {
minidump_type = kasko::api::FULL_DUMP_TYPE;
} else {
bool is_per_user_install =
g_chrome_crash_client.Get().GetIsPerUserInstall(
base::FilePath(exe_path));
if (g_chrome_crash_client.Get().GetShouldDumpLargerDumps(
is_per_user_install)){
minidump_type = kasko::api::LARGER_DUMP_TYPE;
}
}
kasko_client_.reset(
new KaskoClient(chrome_watcher_client_.get(), minidump_type));
#endif // KASKO
}
}
}
} else {
// Set non-browser processes up to be killed by the system after the browser
// goes away. The browser uses the default shutdown order, which is 0x280.
// Note that lower numbers here denote "kill later" and higher numbers mean
// "kill sooner".
// This gets rid of most of those unsighly sad tabs on logout and shutdown.
::SetProcessShutdownParameters(0x280 - 1, SHUTDOWN_NORETRY);
}
}
int ChromeDllLoader::OnBeforeExit(int return_code,
const base::FilePath& dll_path) {
// NORMAL_EXIT_CANCEL is used for experiments when the user cancels
// so we need to reset the did_run signal so omaha does not count
// this run as active usage.
if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
ClearDidRun(dll_path);
}
#if defined(KASKO)
kasko_client_.reset();
#endif // KASKO
chrome_watcher_client_.reset();
return return_code;
}
//=============================================================================
class ChromiumDllLoader : public MainDllLoader {
protected:
void OnBeforeLaunch(const std::string& process_type,
const base::FilePath& dll_path) override {}
int OnBeforeExit(int return_code, const base::FilePath& dll_path) override {
return return_code;
}
};
MainDllLoader* MakeMainDllLoader() {
#if defined(GOOGLE_CHROME_BUILD)
return new ChromeDllLoader();
#else
return new ChromiumDllLoader();
#endif
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif
#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>
#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"
XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)
/**
* Processor interface options
*/
struct ProcessorOptions
{
XalanNode* initOptions;
XalanNode* compileOptions;
XalanNode* parseOptions;
XalanNode* resultOptions;
XalanNode* transformOptions;
ProcessorOptions() :
initOptions(0),
compileOptions(0),
parseOptions(0),
resultOptions(0),
transformOptions(0)
{
}
};
/**
* Test case
*/
class TestCase
{
public:
TestCase();
TestCase(const TestCase& theRhs);
XalanDOMString stylesheet;
XalanDOMString inputDocument;
XalanDOMString resultDocument;
XalanDOMString resultDirectory;
XalanDOMString goldResult;
long numIterations;
long minTimeToExecute;
bool verifyResult;
XalanDOMString inputMode;
typedef XalanMap<XalanDOMString, ProcessorOptions> ProcessorOptionsMap;
ProcessorOptionsMap processorOptions;
};
typedef TestCase TestCaseType;
typedef XalanVector<TestCaseType> TestCasesType;
/**
* Test harness
*/
template <class Processor>
class TestHarness
{
public:
typedef typename Processor::CompiledStylesheetType CompiledStylesheetType;
typedef typename Processor::ParsedInputSourceType ParsedInputSourceType;
typedef typename Processor::ResultTargetType ResultTargetType;
typedef typename XalanXMLFileReporter::Hashtable TestAttributesType;
TestHarness();
void init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger);
void terminate();
void executeTestCase(const TestCaseType& testCase);
void executeTestCases(const TestCasesType& testCases);
protected:
Processor m_processor;
XalanFileUtility* m_fileUtility;
XalanXMLFileReporter* m_reporter;
Logger* m_logger;
};
template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
TestCasesType::const_iterator testCaseIter = testCases.begin();
while (testCaseIter != testCases.end())
{
executeTestCase(*testCaseIter);
++testCaseIter;
}
}
template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));
try {
CompiledStylesheetType compiledStylesheet;
ParsedInputSourceType parsedInputSource;
ResultTargetType resultTarget;
static const ProcessorOptions defaultProcessor;
TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());
const ProcessorOptions& processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;
m_fileUtility->checkAndCreateDir(testCase.resultDirectory);
Timer timeCompile;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.stylesheet, buffer);
istrstream compilerStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream compilerStream;
fileToStream(testCase.stylesheet, compilerStream);
#endif
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
compilerStream,
processor.compileOptions);
timeCompile.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
testCase.stylesheet,
processor.compileOptions);
timeCompile.stop();
}
else
{
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for stylesheet: "
<< testCase.stylesheet
<< endl;
}
m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);
long numIterations = 0;
long totalParseInputTime = 0;
long minParseInputTime = LONG_MAX;
long maxParseInputTime = 0 ;
long totalTransformTime = 0;
long minTransformTime = LONG_MAX;
long maxTransformTime = 0;
Timer timeTotalRun;
timeTotalRun.start();
while (numIterations < testCase.numIterations
&& timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
{
Timer timeInput;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.inputDocument, buffer);
istrstream inputStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream inputStream;
fileToStream(testCase.inputDocument, inputStream);
#endif
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
inputStream,
processor.parseOptions);
timeInput.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
testCase.inputDocument,
processor.parseOptions);
timeInput.stop();
}
else
{
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for input document: "
<< testCase.inputDocument
<< endl;
}
totalParseInputTime += timeInput.getElapsedTime();
minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;
resultTarget = m_processor.createResultTarget(
testCase.resultDocument,
processor.resultOptions);
Timer timeTransform;
timeTransform.start();
m_processor.transform(
compiledStylesheet,
parsedInputSource,
resultTarget);
timeTransform.stop();
totalTransformTime += timeTransform.getElapsedTime();
minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;
++numIterations;
}
timeTotalRun.stop();
m_processor.releaseStylesheet(compiledStylesheet);
m_processor.releaseInputSource(parsedInputSource);
m_processor.releaseResultTarget(resultTarget);
if (true == testCase.verifyResult)
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
if (checkFileExists(testCase.resultDocument))
{
if (checkFileExists(testCase.goldResult))
{
if (m_fileUtility->compareSerializedResults(
testCase.resultDocument,
testCase.goldResult))
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
}
m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));
}
catch (XalanDOMString exception)
{
m_logger->error()
<< "Error encountered during transformation: "
<< testCase.stylesheet.c_str()
<< ", error: "
<< exception.c_str()
<< endl;
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
}
m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}
template <class Processor>
TestHarness<Processor>::TestHarness()
{
}
template <class Processor>
void
TestHarness<Processor>::init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger)
{
m_processor.init();
m_fileUtility = &fileUtility;
m_reporter = &reporter;
m_logger = &logger;
}
template <class Processor>
void
TestHarness<Processor>::terminate()
{
m_processor.terminate();
}
#endif // TESTHARNESS_HEADER_GUARD_1357924680
<commit_msg>Patch for Jira issue XALANC-660.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if !defined(TESTHARNESS_HEADER_GUARD_1357924680)
#define TESTHARNESS_HEADER_GUARD_1357924680
// Base header file. Must be first.
#include <xalanc/Include/PlatformDefinitions.hpp>
#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#else
#include <fstream>
#endif
#include <xalanc/Include/XalanMemoryManagement.hpp>
#include <xalanc/Include/XalanVector.hpp>
#include <xalanc/Include/XalanMap.hpp>
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanDOMString.hpp>
#include <xalanc/Harness/XalanFileUtility.hpp>
#include <xalanc/Harness/XalanXMLFileReporter.hpp>
#include "Utils.hpp"
#include "Logger.hpp"
#include "Timer.hpp"
XALAN_USING_XALAN(XalanMemMgrs)
XALAN_USING_XALAN(XalanVector)
XALAN_USING_XALAN(XalanMap)
XALAN_USING_XALAN(XalanNode)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanFileUtility)
XALAN_USING_XALAN(XalanXMLFileReporter)
/**
* Processor interface options
*/
struct ProcessorOptions
{
XalanNode* initOptions;
XalanNode* compileOptions;
XalanNode* parseOptions;
XalanNode* resultOptions;
XalanNode* transformOptions;
ProcessorOptions() :
initOptions(0),
compileOptions(0),
parseOptions(0),
resultOptions(0),
transformOptions(0)
{
}
};
/**
* Test case
*/
class TestCase
{
public:
TestCase();
TestCase(const TestCase& theRhs);
XalanDOMString stylesheet;
XalanDOMString inputDocument;
XalanDOMString resultDocument;
XalanDOMString resultDirectory;
XalanDOMString goldResult;
long numIterations;
long minTimeToExecute;
bool verifyResult;
XalanDOMString inputMode;
typedef XalanMap<XalanDOMString, ProcessorOptions> ProcessorOptionsMap;
ProcessorOptionsMap processorOptions;
};
typedef TestCase TestCaseType;
typedef XalanVector<TestCaseType> TestCasesType;
/**
* Test harness
*/
template <class Processor>
class TestHarness
{
public:
typedef typename Processor::CompiledStylesheetType CompiledStylesheetType;
typedef typename Processor::ParsedInputSourceType ParsedInputSourceType;
typedef typename Processor::ResultTargetType ResultTargetType;
typedef typename XalanXMLFileReporter::Hashtable TestAttributesType;
TestHarness();
void init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger);
void terminate();
void executeTestCase(const TestCaseType& testCase);
void executeTestCases(const TestCasesType& testCases);
protected:
Processor m_processor;
XalanFileUtility* m_fileUtility;
XalanXMLFileReporter* m_reporter;
Logger* m_logger;
};
template <class Processor>
void
TestHarness<Processor>::executeTestCases(const TestCasesType& testCases)
{
TestCasesType::const_iterator testCaseIter = testCases.begin();
while (testCaseIter != testCases.end())
{
executeTestCase(*testCaseIter);
++testCaseIter;
}
}
template <class Processor>
void
TestHarness<Processor>::executeTestCase(const TestCaseType& testCase)
{
TestAttributesType testAttributes(XalanMemMgrs::getDefaultXercesMemMgr());
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("stylesheet"), testCase.stylesheet));
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("input-document"), testCase.inputDocument));
try {
CompiledStylesheetType compiledStylesheet;
ParsedInputSourceType parsedInputSource;
ResultTargetType resultTarget;
static const ProcessorOptions defaultProcessor;
TestCase::ProcessorOptionsMap::const_iterator iter = testCase.processorOptions.find(m_processor.getName());
const ProcessorOptions& processor = iter != testCase.processorOptions.end() ? iter->second : defaultProcessor;
m_fileUtility->checkAndCreateDir(testCase.resultDirectory);
Timer timeCompile;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.stylesheet, buffer);
istrstream compilerStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream compilerStream;
fileToStream(testCase.stylesheet, compilerStream);
#endif
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
compilerStream,
processor.compileOptions);
timeCompile.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeCompile.start();
compiledStylesheet = m_processor.compileStylesheet(
testCase.stylesheet,
processor.compileOptions);
timeCompile.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for stylesheet: "
<< testCase.stylesheet
<< endl;
}
m_reporter->addMetricToAttrs("compile-xsl", timeCompile.getElapsedTime(), testAttributes);
long numIterations = 0;
long totalParseInputTime = 0;
long minParseInputTime = LONG_MAX;
long maxParseInputTime = 0 ;
long totalTransformTime = 0;
long minTransformTime = LONG_MAX;
long maxTransformTime = 0;
Timer timeTotalRun;
timeTotalRun.start();
while (numIterations < testCase.numIterations
&& timeTotalRun.getElapsedTime() < testCase.minTimeToExecute)
{
Timer timeInput;
if (testCase.inputMode == XalanDOMString("stream"))
{
#if defined(XALAN_CLASSIC_IOSTREAMS)
XALAN_USING_XALAN(CharVectorType)
XALAN_USING_XALAN(c_str)
XALAN_USING_STD(istringstream)
CharVectorType buffer;
fileToStream(testCase.inputDocument, buffer);
istrstream inputStream(c_str(buffer));
#else
XALAN_USING_STD(istringstream)
istringstream inputStream;
fileToStream(testCase.inputDocument, inputStream);
#endif
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
inputStream,
processor.parseOptions);
timeInput.stop();
}
else if (testCase.inputMode == XalanDOMString("file"))
{
timeInput.start();
parsedInputSource = m_processor.parseInputSource(
testCase.inputDocument,
processor.parseOptions);
timeInput.stop();
}
else
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Mode: "
<< testCase.inputMode.c_str()
<< " is inavlid for input document: "
<< testCase.inputDocument
<< endl;
}
totalParseInputTime += timeInput.getElapsedTime();
minParseInputTime = timeInput.getElapsedTime() < minParseInputTime ? timeInput.getElapsedTime() : minParseInputTime;
maxParseInputTime = timeInput.getElapsedTime() > maxParseInputTime ? timeInput.getElapsedTime() : maxParseInputTime;
resultTarget = m_processor.createResultTarget(
testCase.resultDocument,
processor.resultOptions);
Timer timeTransform;
timeTransform.start();
m_processor.transform(
compiledStylesheet,
parsedInputSource,
resultTarget);
timeTransform.stop();
totalTransformTime += timeTransform.getElapsedTime();
minTransformTime = timeTransform.getElapsedTime() < minTransformTime ? timeTransform.getElapsedTime() : minTransformTime;
maxTransformTime = timeTransform.getElapsedTime() > maxTransformTime ? timeTransform.getElapsedTime() : maxTransformTime;
++numIterations;
}
timeTotalRun.stop();
m_processor.releaseStylesheet(compiledStylesheet);
m_processor.releaseInputSource(parsedInputSource);
m_processor.releaseResultTarget(resultTarget);
if (true == testCase.verifyResult)
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("yes")));
if (checkFileExists(testCase.resultDocument))
{
if (checkFileExists(testCase.goldResult))
{
if (m_fileUtility->compareSerializedResults(
testCase.resultDocument,
testCase.goldResult))
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("pass")));
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("fail")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("result"), XalanDOMString("incomplete")));
}
}
else
{
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("verify"), XalanDOMString("no")));
}
m_reporter->addMetricToAttrs("num-iterations", numIterations, testAttributes);
m_reporter->addMetricToAttrs("elapsed-time", timeTotalRun.getElapsedTime(), testAttributes);
m_reporter->addMetricToAttrs("min-parse-input", minParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("max-parse-input", maxParseInputTime, testAttributes);
m_reporter->addMetricToAttrs("avg-parse-input", totalParseInputTime / numIterations, testAttributes);
m_reporter->addMetricToAttrs("min-transform", minTransformTime, testAttributes);
m_reporter->addMetricToAttrs("max-transform", maxTransformTime, testAttributes);
m_reporter->addMetricToAttrs("avg-transform", totalTransformTime / numIterations, testAttributes);
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("yes")));
}
catch (const XalanDOMString& exception)
{
XALAN_USING_STD(endl)
m_logger->error()
<< "Error encountered during transformation: "
<< testCase.stylesheet.c_str()
<< ", error: "
<< exception.c_str()
<< endl;
testAttributes.insert(TestAttributesType::value_type(XalanDOMString("complete"), XalanDOMString("no")));
}
m_reporter->logElementWAttrs(1, "testcase", testAttributes, "");
}
template <class Processor>
TestHarness<Processor>::TestHarness()
{
}
template <class Processor>
void
TestHarness<Processor>::init(
XalanFileUtility& fileUtility,
XalanXMLFileReporter& reporter,
Logger& logger)
{
m_processor.init();
m_fileUtility = &fileUtility;
m_reporter = &reporter;
m_logger = &logger;
}
template <class Processor>
void
TestHarness<Processor>::terminate()
{
m_processor.terminate();
}
#endif // TESTHARNESS_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>//===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility changes the input module to only contain a single function,
// which is primarily used for debugging transformations.
//
//===----------------------------------------------------------------------===//
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/System/Signals.h"
#include <memory>
using namespace llvm;
// InputFilename - The filename to read from.
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));
static cl::opt<bool>
DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
static cl::opt<bool>
Relink("relink",
cl::desc("Turn external linkage for callees of function to delete"));
// ExtractFuncs - The functions to extract from the module...
static cl::list<std::string>
ExtractFuncs("func", cl::desc("Specify function to extract"),
cl::ZeroOrMore, cl::value_desc("function"));
// ExtractGlobals - The globals to extract from the module...
static cl::list<std::string>
ExtractGlobals("glob", cl::desc("Specify global to extract"),
cl::ZeroOrMore, cl::value_desc("global"));
static cl::opt<bool>
OutputAssembly("S",
cl::desc("Write output as LLVM assembly"), cl::Hidden);
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
SMDiagnostic Err;
std::auto_ptr<Module> M;
M.reset(ParseIRFile(InputFilename, Err, Context));
if (M.get() == 0) {
Err.Print(argv[0], errs());
return 1;
}
std::vector<GlobalValue *> GVs;
// Figure out which globals we should extract.
for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
GlobalValue *GV = M.get()->getNamedGlobal(ExtractGlobals[i]);
if (!GV) {
errs() << argv[0] << ": program doesn't contain global named '"
<< ExtractGlobals[i] << "'!\n";
return 1;
}
GVs.push_back(GV);
}
// Figure out which functions we should extract.
for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
GlobalValue *GV = M.get()->getFunction(ExtractFuncs[i]);
if (!GV) {
errs() << argv[0] << ": program doesn't contain function named '"
<< ExtractFuncs[i] << "'!\n";
return 1;
}
GVs.push_back(GV);
}
// In addition to deleting all other functions, we also want to spiff it
// up a little bit. Do this now.
PassManager Passes;
Passes.add(new TargetData(M.get())); // Use correct TargetData
Passes.add(createGVExtractionPass(GVs, DeleteFn, Relink));
if (!DeleteFn)
Passes.add(createGlobalDCEPass()); // Delete unreachable globals
Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
Passes.add(createDeadTypeEliminationPass()); // Remove dead types...
Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
std::string ErrorInfo;
tool_output_file Out(OutputFilename.c_str(), ErrorInfo,
raw_fd_ostream::F_Binary);
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
if (OutputAssembly)
Passes.add(createPrintModulePass(&Out));
else if (Force || !CheckBitcodeOutputToConsole(Out, true))
Passes.add(createBitcodeWriterPass(Out));
Passes.run(*M.get());
// Declare success.
Out.keep();
return 0;
}
<commit_msg>Convert llvm-extract to use lazy loading. This makes it substantially faster on large modules.<commit_after>//===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This utility changes the input module to only contain a single function,
// which is primarily used for debugging transformations.
//
//===----------------------------------------------------------------------===//
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/System/Signals.h"
#include <memory>
using namespace llvm;
// InputFilename - The filename to read from.
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
cl::init("-"), cl::value_desc("filename"));
static cl::opt<std::string>
OutputFilename("o", cl::desc("Specify output filename"),
cl::value_desc("filename"), cl::init("-"));
static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));
static cl::opt<bool>
DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
static cl::opt<bool>
Relink("relink",
cl::desc("Turn external linkage for callees of function to delete"));
// ExtractFuncs - The functions to extract from the module...
static cl::list<std::string>
ExtractFuncs("func", cl::desc("Specify function to extract"),
cl::ZeroOrMore, cl::value_desc("function"));
// ExtractGlobals - The globals to extract from the module...
static cl::list<std::string>
ExtractGlobals("glob", cl::desc("Specify global to extract"),
cl::ZeroOrMore, cl::value_desc("global"));
static cl::opt<bool>
OutputAssembly("S",
cl::desc("Write output as LLVM assembly"), cl::Hidden);
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
LLVMContext &Context = getGlobalContext();
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
// Use lazy loading, since we only care about selected global values.
SMDiagnostic Err;
std::auto_ptr<Module> M;
M.reset(getLazyIRFileModule(InputFilename, Err, Context));
if (M.get() == 0) {
Err.Print(argv[0], errs());
return 1;
}
std::vector<GlobalValue *> GVs;
// Figure out which globals we should extract.
for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
GlobalValue *GV = M.get()->getNamedGlobal(ExtractGlobals[i]);
if (!GV) {
errs() << argv[0] << ": program doesn't contain global named '"
<< ExtractGlobals[i] << "'!\n";
return 1;
}
GVs.push_back(GV);
}
// Figure out which functions we should extract.
for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
GlobalValue *GV = M.get()->getFunction(ExtractFuncs[i]);
if (!GV) {
errs() << argv[0] << ": program doesn't contain function named '"
<< ExtractFuncs[i] << "'!\n";
return 1;
}
GVs.push_back(GV);
}
// Materialize requisite global values.
for (size_t i = 0, e = GVs.size(); i != e; ++i) {
GlobalValue *GV = GVs[i];
if (GV->isMaterializable()) {
std::string ErrInfo;
if (GV->Materialize(&ErrInfo)) {
errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
return 1;
}
}
}
// In addition to deleting all other functions, we also want to spiff it
// up a little bit. Do this now.
PassManager Passes;
Passes.add(new TargetData(M.get())); // Use correct TargetData
Passes.add(createGVExtractionPass(GVs, DeleteFn, Relink));
if (!DeleteFn)
Passes.add(createGlobalDCEPass()); // Delete unreachable globals
Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
Passes.add(createDeadTypeEliminationPass()); // Remove dead types...
Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
std::string ErrorInfo;
tool_output_file Out(OutputFilename.c_str(), ErrorInfo,
raw_fd_ostream::F_Binary);
if (!ErrorInfo.empty()) {
errs() << ErrorInfo << '\n';
return 1;
}
if (OutputAssembly)
Passes.add(createPrintModulePass(&Out));
else if (Force || !CheckBitcodeOutputToConsole(Out, true))
Passes.add(createBitcodeWriterPass(Out));
Passes.run(*M.get());
// Declare success.
Out.keep();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided 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 CODEF
# define CODEF(c)
#endif
#ifndef CODE
# define CODE(c) CODEF(c)
#endif
CODE(CONSTANT) // load the constant at index [arg]
CODE(NIL) // push `nil` into the stack
CODE(FALSE) // push `false` into the stack
CODE(TRUE) // push `true` into the stack
// pushes the value in the given local slot
CODE(LOAD_LOCAL_0)
CODE(LOAD_LOCAL_1)
CODE(LOAD_LOCAL_2)
CODE(LOAD_LOCAL_3)
CODE(LOAD_LOCAL_4)
CODE(LOAD_LOCAL_5)
CODE(LOAD_LOCAL_6)
CODE(LOAD_LOCAL_7)
CODE(LOAD_LOCAL_8)
CODE(LOAD_LOCAL) // push the value in local slot [arg]
CODE(STORE_LOCAL) // store the top of the stack in local slot [arg], not pop it
CODE(LOAD_UPVALUE) // push the value in upvalue [arg]
CODE(STORE_UPVALUE)// store the top of stack in upvalue [arg], does not pop it
// pushes the value of the top-level variable in slot [arg]
CODE(LOAD_MODULE_VAR)
// stores the top of stack in the top-level variable slot [arg], not pop it
CODE(STORE_MODULE_VAR)
// push the value of the field in slot [arg] of the receiver of the current
// function. this is used for regular field access on `this` directly in
// methods. this instruction is faster than the more general LOAD_FIELD
// instruction
CODE(LOAD_FIELD_THIS)
// stroe the top of the stack in field slot [arg] in the receiver of the current
// value, does not pop the value, this instruction is faster than the more
// general LOAD_FIELD instruction
CODE(STORE_FIELD_THIS)
// pop an instance and push the value of the field in slot [arg] of it
CODE(LOAD_FIELD)
// pop an instance and store the subsequent top of stack in field slot [arg]
// in it. does not pop the value
CODE(STORE_FIELD)
CODE(POP) // pop and discard the top of stack
CODE(DUP) // push a copy of the value currently on the top of stack
// invoke the method with symbol [arg], the number indicates the number of
// arguments (not including the receiver)
CODE(CALL_0)
CODE(CALL_1)
CODE(CALL_2)
CODE(CALL_3)
CODE(CALL_4)
CODE(CALL_5)
CODE(CALL_6)
CODE(CALL_7)
CODE(CALL_8)
CODE(CALL_9)
CODE(CALL_10)
CODE(CALL_11)
CODE(CALL_12)
CODE(CALL_13)
CODE(CALL_14)
CODE(CALL_15)
CODE(CALL_16)
// invoke a superclass method with symbol [arg], the number indicates the
// number of arguments (not including the receiver)
CODE(SUPER_0)
CODE(SUPER_1)
CODE(SUPER_2)
CODE(SUPER_3)
CODE(SUPER_4)
CODE(SUPER_5)
CODE(SUPER_6)
CODE(SUPER_7)
CODE(SUPER_8)
CODE(SUPER_9)
CODE(SUPER_10)
CODE(SUPER_11)
CODE(SUPER_12)
CODE(SUPER_13)
CODE(SUPER_14)
CODE(SUPER_15)
CODE(SUPER_16)
CODE(JUMP) // jump the instruction pointer [arg] forward
// jump the instruction pointer [arg] backward. pop and discard the
// top of the stack
CODE(LOOP)
CODE(JUMP_IF) // pop and if not truthy then jump the instruction pointer [arg] forward
CODE(AND) // if the top of the stack is false jump [arg], or pop and continue
CODE(OR) // if the top of the stack if non-false jump [arg], or pop and continue
// close the upvalue for the local on the top of the stack, then pop it.
CODE(CLOSE_UPVALUE)
CODE(RETURN) // exit from the current function and return the value on the top of stack
// creates a closure for the function stored at [arg] in the constant table
//
// following the function argument is a number of arguments, two for each
// upvalue. the first is non-zero if the variable being captured is a local
// and the second is the index of the local or upvalue being captured.
//
// pushes the created closure object
CODE(CLOSURE)
// creates a new instance of a class
//
// assumes the class object is in slot zero, and replaces it with the new
// uninitialized instance of that class, the opcode is only emitted by the
// compiler-generated constructor metaclass methods
CODE(CONSTRUCT)
// creates a class, top of stack is the superclass, or `nil` if the class
// inherits Object, below that is a string for the name of the class, byte
// [arg] is the number of fields in the class
CODE(CLASS)
// define a method for symbol [arg] the class receiving the method is popped
// off the stack, then the function defining the body is popped
//
// if a foreign method is being defined, the `function` will be a string
// identifying the foreign method, otherwise it will be a function or closure
CODE(METHOD_INSTANCE)
// define a method for symbol [arg] the class whose metaclass will receive
// the method is popped off the stack, then the function defining the body
// is popped
//
// if a foreign method is being defined, the `function` will be a string
// identifying the foreign method, otherwise it will be a function or closure
CODE(METHOD_STATIC)
// load the module whose name is stored in string constant [arg], pushes
// nullptr onto the stack, if the module has already been loaded, does nothing
// else, otherwise it creates a fiber to run the desired module and switches
// to that, when that fiber is done the current one is resumed
CODE(LOAD_MODULE)
// reads a top-level variable from another module, [arg1] is a string constant
// for the name of the module and [arg2] is a string constant for the variable
// name, pushes the variable if found or generates a runtime error otherwise
CODE(IMPORT_VARIABLE)
CODE(END)
#undef CODE
#undef CODEF
<commit_msg>:construction: chore(opcode): definitions new opcode<commit_after>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided 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 CODEF
# define CODEF(c)
#endif
#ifndef CODE
# define CODE(c) CODEF(c)
#endif
CODE(CONSTANT) // load the constant at index [arg]
CODE(NIL) // push `nil` into the stack
CODE(FALSE) // push `false` into the stack
CODE(TRUE) // push `true` into the stack
// pushes the value in the given local slot
CODE(LOAD_LOCAL_0)
CODE(LOAD_LOCAL_1)
CODE(LOAD_LOCAL_2)
CODE(LOAD_LOCAL_3)
CODE(LOAD_LOCAL_4)
CODE(LOAD_LOCAL_5)
CODE(LOAD_LOCAL_6)
CODE(LOAD_LOCAL_7)
CODE(LOAD_LOCAL_8)
CODE(LOAD_LOCAL) // push the value in local slot [arg]
CODE(STORE_LOCAL) // store the top of the stack in local slot [arg], not pop it
CODE(LOAD_UPVALUE) // push the value in upvalue [arg]
CODE(STORE_UPVALUE)// store the top of stack in upvalue [arg], does not pop it
// pushes the value of the top-level variable in slot [arg]
CODE(LOAD_MODULE_VAR)
// stores the top of stack in the top-level variable slot [arg], not pop it
CODE(STORE_MODULE_VAR)
// push the value of the field in slot [arg] of the receiver of the current
// function. this is used for regular field access on `this` directly in
// methods. this instruction is faster than the more general LOAD_FIELD
// instruction
CODE(LOAD_FIELD_THIS)
// stroe the top of the stack in field slot [arg] in the receiver of the current
// value, does not pop the value, this instruction is faster than the more
// general LOAD_FIELD instruction
CODE(STORE_FIELD_THIS)
// pop an instance and push the value of the field in slot [arg] of it
CODE(LOAD_FIELD)
// pop an instance and store the subsequent top of stack in field slot [arg]
// in it. does not pop the value
CODE(STORE_FIELD)
CODE(POP) // pop and discard the top of stack
CODE(DUP) // push a copy of the value currently on the top of stack
// invoke the method with symbol [arg], the number indicates the number of
// arguments (not including the receiver)
CODE(CALL_0)
CODE(CALL_1)
CODE(CALL_2)
CODE(CALL_3)
CODE(CALL_4)
CODE(CALL_5)
CODE(CALL_6)
CODE(CALL_7)
CODE(CALL_8)
CODE(CALL_9)
CODE(CALL_10)
CODE(CALL_11)
CODE(CALL_12)
CODE(CALL_13)
CODE(CALL_14)
CODE(CALL_15)
CODE(CALL_16)
// invoke a superclass method with symbol [arg], the number indicates the
// number of arguments (not including the receiver)
CODE(SUPER_0)
CODE(SUPER_1)
CODE(SUPER_2)
CODE(SUPER_3)
CODE(SUPER_4)
CODE(SUPER_5)
CODE(SUPER_6)
CODE(SUPER_7)
CODE(SUPER_8)
CODE(SUPER_9)
CODE(SUPER_10)
CODE(SUPER_11)
CODE(SUPER_12)
CODE(SUPER_13)
CODE(SUPER_14)
CODE(SUPER_15)
CODE(SUPER_16)
CODE(JUMP) // jump the instruction pointer [arg] forward
// jump the instruction pointer [arg] backward. pop and discard the
// top of the stack
CODE(LOOP)
CODE(JUMP_IF) // pop and if not truthy then jump the instruction pointer [arg] forward
CODE(AND) // if the top of the stack is false jump [arg], or pop and continue
CODE(OR) // if the top of the stack if non-false jump [arg], or pop and continue
// close the upvalue for the local on the top of the stack, then pop it.
CODE(CLOSE_UPVALUE)
CODE(RETURN) // exit from the current function and return the value on the top of stack
// creates a closure for the function stored at [arg] in the constant table
//
// following the function argument is a number of arguments, two for each
// upvalue. the first is non-zero if the variable being captured is a local
// and the second is the index of the local or upvalue being captured.
//
// pushes the created closure object
CODE(CLOSURE)
// creates a new instance of a class
//
// assumes the class object is in slot zero, and replaces it with the new
// uninitialized instance of that class, the opcode is only emitted by the
// compiler-generated constructor metaclass methods
CODE(CONSTRUCT)
// creates a new instance of a foreign class
//
// assumes the class object is in slot zero, and replaces it with the new
// uninitialized instance of that class, this opcode is only emitted by the
// compiler-generated constructor metaclass methods
CODE(FOREIGN_CONSTRUCT)
// creates a class, top of stack is the superclass, or `nil` if the class
// inherits Object, below that is a string for the name of the class, byte
// [arg] is the number of fields in the class
CODE(CLASS)
// creates a foreign class, top of stack is the superclass, or `nil` if the
// class inherits Object, below that is a string for the name of the class
CODE(FOREIGN_CLASS)
// define a method for symbol [arg] the class receiving the method is popped
// off the stack, then the function defining the body is popped
//
// if a foreign method is being defined, the `function` will be a string
// identifying the foreign method, otherwise it will be a function or closure
CODE(METHOD_INSTANCE)
// define a method for symbol [arg] the class whose metaclass will receive
// the method is popped off the stack, then the function defining the body
// is popped
//
// if a foreign method is being defined, the `function` will be a string
// identifying the foreign method, otherwise it will be a function or closure
CODE(METHOD_STATIC)
// load the module whose name is stored in string constant [arg], pushes
// nullptr onto the stack, if the module has already been loaded, does nothing
// else, otherwise it creates a fiber to run the desired module and switches
// to that, when that fiber is done the current one is resumed
CODE(LOAD_MODULE)
// reads a top-level variable from another module, [arg1] is a string constant
// for the name of the module and [arg2] is a string constant for the variable
// name, pushes the variable if found or generates a runtime error otherwise
CODE(IMPORT_VARIABLE)
CODE(END)
#undef CODE
#undef CODEF
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <string>
#include <vector>
#include "mutant/OsPath.h"
TEST(OsPathTest, joinEmpty) {
std::vector<std::string> names;
std::string expected;
std::string actual = OsPath::join(names);
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinOne) {
std::vector<std::string> names = {"hello"};
std::string expected = "hello";
std::string actual = OsPath::join(names);
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinTwo) {
std::vector<std::string> names = {"hello", "world"};
std::string expected = "hello/world";
std::string actual = OsPath::join(names);
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftRight) {
std::string expected = "/www/foo/osd/ui";
std::string actual = OsPath::join("/www/foo", "osd/ui");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftSlashRight) {
std::string expected = "/www/foo/osd/ui";
std::string actual = OsPath::join("/www/foo/", "osd/ui");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftEmptyRight) {
std::string expected = "";
std::string actual = OsPath::join("", "osd/ui");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftRightEmpty) {
std::string expected = "";
std::string actual = OsPath::join("/www/foo", "");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftEmptyRightEmpty) {
std::string expected = "";
std::string actual = OsPath::join("", "");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, existsFile) {
std::string existedFile = "../../test_data/OsPath/file";
ASSERT_TRUE(OsPath::exists(existedFile));
}
TEST(OsPathTest, existsDir) {
std::string existedDir = "../../test_data/OsPath/dir";
ASSERT_TRUE(OsPath::exists(existedDir));
}
TEST(OsPathTest, isDir) {
std::string existedDir = "../../test_data/OsPath/dir";
ASSERT_TRUE(OsPath::isDir(existedDir));
}
TEST(OsPathTest, isFile) {
std::string existedFile = "../../test_data/OsPath/file";
ASSERT_TRUE(OsPath::isFile(existedFile));
}
<commit_msg>add OsPathTest::ls<commit_after>#include <gmock/gmock.h>
#include <string>
#include <vector>
#include "mutant/OsPath.h"
TEST(OsPathTest, joinEmpty) {
std::vector<std::string> names;
std::string expected;
std::string actual = OsPath::join(names);
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinOne) {
std::vector<std::string> names = {"hello"};
std::string expected = "hello";
std::string actual = OsPath::join(names);
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinTwo) {
std::vector<std::string> names = {"hello", "world"};
std::string expected = "hello/world";
std::string actual = OsPath::join(names);
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftRight) {
std::string expected = "/www/foo/osd/ui";
std::string actual = OsPath::join("/www/foo", "osd/ui");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftSlashRight) {
std::string expected = "/www/foo/osd/ui";
std::string actual = OsPath::join("/www/foo/", "osd/ui");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftEmptyRight) {
std::string expected = "";
std::string actual = OsPath::join("", "osd/ui");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftRightEmpty) {
std::string expected = "";
std::string actual = OsPath::join("/www/foo", "");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, joinLeftEmptyRightEmpty) {
std::string expected = "";
std::string actual = OsPath::join("", "");
ASSERT_EQ(expected, actual);
}
TEST(OsPathTest, existsFile) {
std::string existedFile = "../../test_data/OsPath/file";
ASSERT_TRUE(OsPath::exists(existedFile));
}
TEST(OsPathTest, existsDir) {
std::string existedDir = "../../test_data/OsPath/dir";
ASSERT_TRUE(OsPath::exists(existedDir));
}
TEST(OsPathTest, isDir) {
std::string existedDir = "../../test_data/OsPath/dir";
ASSERT_TRUE(OsPath::isDir(existedDir));
}
TEST(OsPathTest, isFile) {
std::string existedFile = "../../test_data/OsPath/file";
ASSERT_TRUE(OsPath::isFile(existedFile));
}
TEST(OsPathTest, ls) {
std::string path = "../../test_data/OsPath/ls";
std::vector<std::string> expected = { "dir1", "dir2", "file1.txt", "file2.txt" };
std::vector<std::string> actual = OsPath::ls(path);
ASSERT_EQ(expected, actual);
}
<|endoftext|> |
<commit_before>#pragma once
#include "../util.hpp"
template <typename T>
class SegmentTree {
using func_t = function<T(T, T)>;
const int n;
const T id;
func_t merge;
vector<T> data;
T sub(int l, int r, int node, int lb, int ub) {
if (ub <= l || r <= lb) return id;
if (l <= lb && ub <= r) return data[node];
T vl = sub(l, r, node * 2 + 0, lb, (lb + ub) / 2);
T vr = sub(l, r, node * 2 + 1, (lb + ub) / 2, ub);
return merge(vl, vr);
}
int size(int n) {
return n == 1 ? n : size((n + 1) / 2) * 2;
}
public:
SegmentTree(int n, T id, func_t merge) :
n(size(n)), id(id), merge(merge), data(n * 2, id) {}
void update(int p, T val) {
assert (0 <= p && p < n);
p += n;
data[p] = val;
while (p /= 2) {
int l = p * 2, r = p * 2 + 1;
data[p] = merge(data[l], data[r]);
}
}
T find(int l, int r) {
return sub(l, r, 1, 0, n);
}
};
// Verified : AOJ DSL_2_A (Range Minimum Query)
/*
int main() {
int n, q, com, x, y;
cin >> n >> q;
SegmentTree<int> seg(n, 0x7FFFFFFF, [](int a, int b){return min(a, b);});
while (q--) {
cin >> com >> x >> y;
if (com) cout << seg.find(x, y+1) << endl;
else seg.update(x, y);
}
return 0;
}
*/
<commit_msg>fix length of data array of segment_tree<commit_after>#pragma once
#include "../util.hpp"
template <typename T>
class SegmentTree {
using func_t = function<T(T, T)>;
const int n;
const T id;
func_t merge;
vector<T> data;
T sub(int l, int r, int node, int lb, int ub) {
if (ub <= l || r <= lb) return id;
if (l <= lb && ub <= r) return data[node];
T vl = sub(l, r, node * 2 + 0, lb, (lb + ub) / 2);
T vr = sub(l, r, node * 2 + 1, (lb + ub) / 2, ub);
return merge(vl, vr);
}
int size(int n) {
return n == 1 ? n : size((n + 1) / 2) * 2;
}
public:
SegmentTree(int m, T id, func_t merge) :
n(size(m)), id(id), merge(merge), data(n * 2, id) {}
void update(int p, T val) {
assert (0 <= p && p < n);
p += n;
data[p] = val;
while (p /= 2) {
int l = p * 2, r = p * 2 + 1;
data[p] = merge(data[l], data[r]);
}
}
T find(int l, int r) {
return sub(l, r, 1, 0, n);
}
};
// Verified : AOJ DSL_2_A (Range Minimum Query)
/*
int main() {
int n, q, com, x, y;
cin >> n >> q;
SegmentTree<int> seg(n, 0x7FFFFFFF, [](int a, int b){return min(a, b);});
while (q--) {
cin >> com >> x >> y;
if (com) cout << seg.find(x, y+1) << endl;
else seg.update(x, y);
}
return 0;
}
*/
<|endoftext|> |
<commit_before>#include <cstdlib>
#include "game/lane_length_model.h"
#include "gflags/gflags.h"
#include "jsoncons_ext/csv/csv_reader.hpp"
#include "jsoncons_ext/csv/csv_serializer.hpp"
DECLARE_string(race_id);
DECLARE_bool(print_models);
DECLARE_bool(read_switch_models);
DECLARE_bool(write_switch_models);
using jsoncons_ext::csv::csv_reader;
using jsoncons_ext::csv::csv_serializer;
namespace game {
LaneLengthModel::LaneLengthModel(const Track* track) : track_(track) {
if (FLAGS_read_switch_models) {
LoadSwitchLengths();
}
}
LaneLengthModel::~LaneLengthModel() {
if (FLAGS_print_models) {
std::cout << "==== Lane Length Model ====" << std::endl;
std::cout << "Straight:" << std::endl;
for (const auto& p : switch_on_straight_length_) {
std::cout << "(" << p.first.first << "," << p.first.second << ") => " << p.second << std::endl;
}
std::cout << "Turn:" << std::endl;
for (const auto& p : switch_on_turn_length_) {
std::cout << "(" << std::get<0>(p.first) << "," << std::get<1>(p.first) << "," << std::get<2>(p.first) << ") => " << p.second << std::endl;
}
}
if (FLAGS_write_switch_models) {
SaveSwitchLengths();
}
}
double LaneLengthModel::Length(const Position& position, bool* perfect) const {
if (perfect) *perfect = true;
const auto& piece = track_->pieces()[position.piece()];
if (piece.type() == PieceType::kStraight) {
if (position.start_lane() == position.end_lane()) {
return piece.length();
}
if (!piece.has_switch()) {
std::cerr << "Changing lane on non switch piece?" << std::endl;
}
const double width = fabs(track_->lanes()[position.start_lane()].distance_from_center() - track_->lanes()[position.end_lane()].distance_from_center());
if (switch_on_straight_length_.count({piece.length(), width}) > 0) {
return switch_on_straight_length_.at({piece.length(), width});
}
if (perfect) *perfect = false;
return std::sqrt(width * width + piece.length() * piece.length());
}
if (position.start_lane() == position.end_lane()) {
double radius = track_->LaneRadius(position.piece(), position.start_lane());
return 2.0 * M_PI * radius * (fabs(piece.angle()) / 360.0);
}
if (!piece.has_switch()) {
std::cerr << "Changing lane on non switch piece?" << std::endl;
}
double radius1 = track_->LaneRadius(position.piece(), position.start_lane());
double radius2 = track_->LaneRadius(position.piece(), position.end_lane());
if (switch_on_turn_length_.count({radius1, radius2, fabs(piece.angle())}) > 0) {
return switch_on_turn_length_.at({radius1, radius2, fabs(piece.angle())});
}
if (perfect) *perfect = false;
// The opposite switch is much better predictor if available
if (switch_on_turn_length_.count({radius2, radius1, fabs(piece.angle())}) > 0) {
return switch_on_turn_length_.at({radius2, radius1, fabs(piece.angle())});
}
return M_PI * radius1 * (fabs(piece.angle()) / 360.0) + M_PI * radius2 * (fabs(piece.angle()) / 360.0);
}
void LaneLengthModel::Record(const Position& previous, const Position& current, double predicted_velocity) {
if (previous.piece() == current.piece())
return;
if (previous.start_lane() == previous.end_lane())
return;
const auto& piece = track_->pieces()[previous.piece()];
double length = previous.piece_distance() + predicted_velocity - current.piece_distance();
if (piece.type() == PieceType::kStraight) {
const double width = fabs(track_->lanes()[previous.start_lane()].distance_from_center() - track_->lanes()[previous.end_lane()].distance_from_center());
switch_on_straight_length_[{piece.length(), width}] = length;
return;
}
double radius1 = track_->LaneRadius(previous.piece(), previous.start_lane());
double radius2 = track_->LaneRadius(previous.piece(), previous.end_lane());
switch_on_turn_length_[{radius1, radius2, fabs(piece.angle())}] = length;
}
static jsoncons::json LoadCSV(const string& file_name) {
std::ifstream file(file_name);
if (!file.good()) {
file.close();
return jsoncons::json(::jsoncons::json::an_array);
}
jsoncons::json_deserializer handler;
jsoncons::json params;
params["has_header"] = true;
csv_reader reader(file, handler, params);
reader.read();
jsoncons::json j = std::move(handler.root());
return j;
}
static double ToDouble(jsoncons::json data) {
return std::strtod(data.as_string().c_str(), nullptr);
}
void LaneLengthModel::LoadSwitchLengths() {
jsoncons::json straight_lengths = LoadCSV("data/switch-straight-lengths.csv");
for (auto it = straight_lengths.begin_elements(); it != straight_lengths.end_elements(); ++it) {
const auto& data = *it;
switch_on_straight_length_[{ToDouble(data["length"]), ToDouble(data["width"])}] = ToDouble(data["switch_length"]);
}
jsoncons::json turn_lengths = LoadCSV("data/switch-turn-lengths.csv");
for (auto it = turn_lengths.begin_elements(); it != turn_lengths.end_elements(); ++it) {
const auto& data = *it;
switch_on_turn_length_[{ToDouble(data["start_radius"]), ToDouble(data["end_radius"]), ToDouble(data["angle"])}] = ToDouble(data["switch_length"]);
}
// Check if we are missing any data for current track.
bool has_all = true;
for (const auto& piece : track_->pieces()) {
if (!piece.has_switch()) continue;
if (piece.type() == PieceType::kStraight) {
for (int i = 1; i < track_->lanes().size(); ++i) {
double width = fabs(track_->lanes()[i].distance_from_center() - track_->lanes()[i - 1].distance_from_center());
if (switch_on_straight_length_.count({piece.length(), width}) == 0) {
has_all = false;
std::cout << "WARNING: Missing length for switch on straight with length " << piece.length() << " and width " << width << std::endl;
}
}
} else {
for (int i = 1; i < track_->lanes().size(); ++i) {
double start_radius = piece.radius() + track_->lanes()[i - 1].distance_from_center();
double end_radius = piece.radius() + track_->lanes()[i].distance_from_center();
if (switch_on_turn_length_.count({start_radius, end_radius, fabs(piece.angle())}) == 0) {
has_all = false;
std::cout << "WARNING: Missing length for switch on turn start_radius: " << start_radius << " end_radius: " << end_radius << " angle: " << fabs(piece.angle()) << std::endl;
}
if (switch_on_turn_length_.count({end_radius, start_radius, fabs(piece.angle())}) == 0) {
has_all = false;
std::cout << "WARNING: Missing length for switch on turn start_radius: " << end_radius << " end_radius: " << start_radius << " angle: " << fabs(piece.angle()) << std::endl;
}
}
}
}
if (has_all) {
std::cout << "We have all switch lengths!" << std::endl;
}
}
void LaneLengthModel::SaveSwitchLengths() {
std::ofstream file("data/switch-straight-lengths.csv");
file << "length,width,switch_length" << std::endl;
for (const auto& it : switch_on_straight_length_) {
file << std::setprecision(20) << it.first.first << "," << it.first.second << "," << it.second << std::endl;
}
file.close();
file.open("data/switch-turn-lengths.csv");
file << "start_radius,end_radius,angle,switch_length" << std::endl;
for (const auto& it : switch_on_turn_length_) {
file << std::setprecision(20) << std::get<0>(it.first) << "," << std::get<1>(it.first) << "," << std::get<2>(it.first) << "," << it.second << std::endl;
}
file.close();
}
} // namespace game
<commit_msg>Use std::make_tuple<commit_after>#include <cstdlib>
#include "game/lane_length_model.h"
#include "gflags/gflags.h"
#include "jsoncons_ext/csv/csv_reader.hpp"
#include "jsoncons_ext/csv/csv_serializer.hpp"
DECLARE_string(race_id);
DECLARE_bool(print_models);
DECLARE_bool(read_switch_models);
DECLARE_bool(write_switch_models);
using jsoncons_ext::csv::csv_reader;
using jsoncons_ext::csv::csv_serializer;
namespace game {
LaneLengthModel::LaneLengthModel(const Track* track) : track_(track) {
if (FLAGS_read_switch_models) {
LoadSwitchLengths();
}
}
LaneLengthModel::~LaneLengthModel() {
if (FLAGS_print_models) {
std::cout << "==== Lane Length Model ====" << std::endl;
std::cout << "Straight:" << std::endl;
for (const auto& p : switch_on_straight_length_) {
std::cout << "(" << p.first.first << "," << p.first.second << ") => " << p.second << std::endl;
}
std::cout << "Turn:" << std::endl;
for (const auto& p : switch_on_turn_length_) {
std::cout << "(" << std::get<0>(p.first) << "," << std::get<1>(p.first) << "," << std::get<2>(p.first) << ") => " << p.second << std::endl;
}
}
if (FLAGS_write_switch_models) {
SaveSwitchLengths();
}
}
double LaneLengthModel::Length(const Position& position, bool* perfect) const {
if (perfect) *perfect = true;
const auto& piece = track_->pieces()[position.piece()];
if (piece.type() == PieceType::kStraight) {
if (position.start_lane() == position.end_lane()) {
return piece.length();
}
if (!piece.has_switch()) {
std::cerr << "Changing lane on non switch piece?" << std::endl;
}
const double width = fabs(track_->lanes()[position.start_lane()].distance_from_center() - track_->lanes()[position.end_lane()].distance_from_center());
if (switch_on_straight_length_.count({piece.length(), width}) > 0) {
return switch_on_straight_length_.at({piece.length(), width});
}
if (perfect) *perfect = false;
return std::sqrt(width * width + piece.length() * piece.length());
}
if (position.start_lane() == position.end_lane()) {
double radius = track_->LaneRadius(position.piece(), position.start_lane());
return 2.0 * M_PI * radius * (fabs(piece.angle()) / 360.0);
}
if (!piece.has_switch()) {
std::cerr << "Changing lane on non switch piece?" << std::endl;
}
double radius1 = track_->LaneRadius(position.piece(), position.start_lane());
double radius2 = track_->LaneRadius(position.piece(), position.end_lane());
if (switch_on_turn_length_.count(std::make_tuple(radius1, radius2, fabs(piece.angle()))) > 0) {
return switch_on_turn_length_.at(std::make_tuple(radius1, radius2, fabs(piece.angle())));
}
if (perfect) *perfect = false;
// The opposite switch is much better predictor if available
if (switch_on_turn_length_.count(std::make_tuple(radius2, radius1, fabs(piece.angle()))) > 0) {
return switch_on_turn_length_.at(std::make_tuple(radius2, radius1, fabs(piece.angle())));
}
return M_PI * radius1 * (fabs(piece.angle()) / 360.0) + M_PI * radius2 * (fabs(piece.angle()) / 360.0);
}
void LaneLengthModel::Record(const Position& previous, const Position& current, double predicted_velocity) {
if (previous.piece() == current.piece())
return;
if (previous.start_lane() == previous.end_lane())
return;
const auto& piece = track_->pieces()[previous.piece()];
double length = previous.piece_distance() + predicted_velocity - current.piece_distance();
if (piece.type() == PieceType::kStraight) {
const double width = fabs(track_->lanes()[previous.start_lane()].distance_from_center() - track_->lanes()[previous.end_lane()].distance_from_center());
switch_on_straight_length_[{piece.length(), width}] = length;
return;
}
double radius1 = track_->LaneRadius(previous.piece(), previous.start_lane());
double radius2 = track_->LaneRadius(previous.piece(), previous.end_lane());
switch_on_turn_length_[std::make_tuple(radius1, radius2, fabs(piece.angle()))] = length;
}
static jsoncons::json LoadCSV(const string& file_name) {
std::ifstream file(file_name);
if (!file.good()) {
file.close();
return jsoncons::json(::jsoncons::json::an_array);
}
jsoncons::json_deserializer handler;
jsoncons::json params;
params["has_header"] = true;
csv_reader reader(file, handler, params);
reader.read();
jsoncons::json j = std::move(handler.root());
return j;
}
static double ToDouble(jsoncons::json data) {
return std::strtod(data.as_string().c_str(), nullptr);
}
void LaneLengthModel::LoadSwitchLengths() {
jsoncons::json straight_lengths = LoadCSV("data/switch-straight-lengths.csv");
for (auto it = straight_lengths.begin_elements(); it != straight_lengths.end_elements(); ++it) {
const auto& data = *it;
switch_on_straight_length_[std::make_tuple(ToDouble(data["length"]), ToDouble(data["width"]))] = ToDouble(data["switch_length"]);
}
jsoncons::json turn_lengths = LoadCSV("data/switch-turn-lengths.csv");
for (auto it = turn_lengths.begin_elements(); it != turn_lengths.end_elements(); ++it) {
const auto& data = *it;
switch_on_turn_length_[std::make_tuple(ToDouble(data["start_radius"]), ToDouble(data["end_radius"]), ToDouble(data["angle"]))] = ToDouble(data["switch_length"]);
}
// Check if we are missing any data for current track.
bool has_all = true;
for (const auto& piece : track_->pieces()) {
if (!piece.has_switch()) continue;
if (piece.type() == PieceType::kStraight) {
for (int i = 1; i < track_->lanes().size(); ++i) {
double width = fabs(track_->lanes()[i].distance_from_center() - track_->lanes()[i - 1].distance_from_center());
if (switch_on_straight_length_.count({piece.length(), width}) == 0) {
has_all = false;
std::cout << "WARNING: Missing length for switch on straight with length " << piece.length() << " and width " << width << std::endl;
}
}
} else {
for (int i = 1; i < track_->lanes().size(); ++i) {
double start_radius = piece.radius() + track_->lanes()[i - 1].distance_from_center();
double end_radius = piece.radius() + track_->lanes()[i].distance_from_center();
if (switch_on_turn_length_.count(std::make_tuple(start_radius, end_radius, fabs(piece.angle()))) == 0) {
has_all = false;
std::cout << "WARNING: Missing length for switch on turn start_radius: " << start_radius << " end_radius: " << end_radius << " angle: " << fabs(piece.angle()) << std::endl;
}
if (switch_on_turn_length_.count(std::make_tuple(end_radius, start_radius, fabs(piece.angle()))) == 0) {
has_all = false;
std::cout << "WARNING: Missing length for switch on turn start_radius: " << end_radius << " end_radius: " << start_radius << " angle: " << fabs(piece.angle()) << std::endl;
}
}
}
}
if (has_all) {
std::cout << "We have all switch lengths!" << std::endl;
}
}
void LaneLengthModel::SaveSwitchLengths() {
std::ofstream file("data/switch-straight-lengths.csv");
file << "length,width,switch_length" << std::endl;
for (const auto& it : switch_on_straight_length_) {
file << std::setprecision(20) << it.first.first << "," << it.first.second << "," << it.second << std::endl;
}
file.close();
file.open("data/switch-turn-lengths.csv");
file << "start_radius,end_radius,angle,switch_length" << std::endl;
for (const auto& it : switch_on_turn_length_) {
file << std::setprecision(20) << std::get<0>(it.first) << "," << std::get<1>(it.first) << "," << std::get<2>(it.first) << "," << it.second << std::endl;
}
file.close();
}
} // namespace game
<|endoftext|> |
<commit_before>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id$
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
// -- CLASS DESCRIPTION [AUX] --
// RooSegmentedIntegrator1D implements an adaptive one-dimensional
// numerical integration algorithm.
#include "RooFitCore/RooSegmentedIntegrator1D.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooNumber.hh"
#include "RooFitCore/RooIntegratorConfig.hh"
#include <assert.h>
ClassImp(RooSegmentedIntegrator1D)
;
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments,
RooIntegrator1D::SummationRule rule,
Int_t maxSteps, Double_t eps) :
RooAbsIntegrator(function), _nseg(nSegments)
{
// Use this form of the constructor to integrate over the function's default range.
_config.setSummationRule1D(rule) ;
_config.setMaxSteps1D(maxSteps) ;
_config.setEpsilonRel1D(eps) ;
_config.setEpsilonAbs1D(eps) ;
_useIntegrandLimits= kTRUE;
_valid= initialize();
}
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments, const RooIntegratorConfig& config) :
RooAbsIntegrator(function), _nseg(nSegments), _config(config)
{
// Use this form of the constructor to integrate over the function's default range.
_useIntegrandLimits= kTRUE;
_valid= initialize();
}
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments, Double_t xmin, Double_t xmax,
RooIntegrator1D::SummationRule rule,
Int_t maxSteps, Double_t eps) :
RooAbsIntegrator(function), _nseg(nSegments)
{
// Use this form of the constructor to override the function's default range.
_xmin= xmin;
_xmax= xmax;
_config.setSummationRule1D(rule) ;
_config.setMaxSteps1D(maxSteps) ;
_config.setEpsilonRel1D(eps) ;
_config.setEpsilonAbs1D(eps) ;
_useIntegrandLimits= kFALSE;
_valid= initialize();
}
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments, Double_t xmin, Double_t xmax,
const RooIntegratorConfig& config) :
RooAbsIntegrator(function), _nseg(nSegments), _config(config)
{
// Use this form of the constructor to override the function's default range.
_useIntegrandLimits= kFALSE;
_xmin= xmin;
_xmax= xmax;
_valid= initialize();
}
typedef RooIntegrator1D* pRooIntegrator1D ;
Bool_t RooSegmentedIntegrator1D::initialize()
{
_array = 0 ;
Bool_t limitsOK = checkLimits();
if (!limitsOK) return kFALSE ;
// Make array of integrators for each segment
_array = new pRooIntegrator1D[_nseg] ;
Int_t i ;
cout << "RooSegI1D::init()" << " _xmin = " << _xmin << " _xmax = " << _xmax << " nseg = " << _nseg << endl ;
Double_t segSize = (_xmax - _xmin) / _nseg ;
// Adjust integrator configurations for reduced intervals
// _config.setEpsilonRel1D(_config.epsilonRel1D()/sqrt(_nseg)) ;
_config.setEpsilonAbs1D(_config.epsilonAbs1D()/sqrt(_nseg)) ;
for (i=0 ; i<_nseg ; i++) {
cout << " calling ctor " << endl ;
_array[i] = new RooIntegrator1D(*_function,_xmin+i*segSize,_xmin+(i+1)*segSize,_config) ;
}
cout << " done " << endl ;
}
RooSegmentedIntegrator1D::~RooSegmentedIntegrator1D()
{
}
Bool_t RooSegmentedIntegrator1D::checkLimits() const {
// Check that our integration range is finite and otherwise return kFALSE.
// Update the limits from the integrand if requested.
if(_useIntegrandLimits) {
assert(0 != integrand() && integrand()->isValid());
_xmin= integrand()->getMinLimit(0);
_xmax= integrand()->getMaxLimit(0);
}
_range= _xmax - _xmin;
if(_range <= 0) {
cout << "RooSegmentedIntegrator1D::checkLimits: bad range with min >= max" << endl;
cout << "_xmax = " << _xmax << " _xmin = " << _xmin << endl ;
cout << "_useIL = " << (_useIntegrandLimits?"T":"F") << endl ;
return kFALSE;
}
return (RooNumber::isInfinite(_xmin) || RooNumber::isInfinite(_xmax)) ? kFALSE : kTRUE;
}
Double_t RooSegmentedIntegrator1D::integral(const Double_t *yvec)
{
assert(isValid());
Int_t i ;
Double_t result(0) ;
for (i=0 ; i<_nseg ; i++) {
result += _array[i]->integral(yvec) ;
}
return result;
}
<commit_msg><commit_after>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* File: $Id: RooSegmentedIntegrator1D.cc,v 1.1 2003/05/09 20:48:23 wverkerke Exp $
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
* DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
* *
* Copyright (c) 2000-2002, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
// -- CLASS DESCRIPTION [AUX] --
// RooSegmentedIntegrator1D implements an adaptive one-dimensional
// numerical integration algorithm.
#include "RooFitCore/RooSegmentedIntegrator1D.hh"
#include "RooFitCore/RooRealVar.hh"
#include "RooFitCore/RooNumber.hh"
#include "RooFitCore/RooIntegratorConfig.hh"
#include <assert.h>
ClassImp(RooSegmentedIntegrator1D)
;
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments,
RooIntegrator1D::SummationRule rule,
Int_t maxSteps, Double_t eps) :
RooAbsIntegrator(function), _nseg(nSegments)
{
// Use this form of the constructor to integrate over the function's default range.
_config.setSummationRule1D(rule) ;
_config.setMaxSteps1D(maxSteps) ;
_config.setEpsilonRel1D(eps) ;
_config.setEpsilonAbs1D(eps) ;
_useIntegrandLimits= kTRUE;
_valid= initialize();
}
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments, const RooIntegratorConfig& config) :
RooAbsIntegrator(function), _nseg(nSegments), _config(config)
{
// Use this form of the constructor to integrate over the function's default range.
_useIntegrandLimits= kTRUE;
_valid= initialize();
}
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments, Double_t xmin, Double_t xmax,
RooIntegrator1D::SummationRule rule,
Int_t maxSteps, Double_t eps) :
RooAbsIntegrator(function), _nseg(nSegments)
{
// Use this form of the constructor to override the function's default range.
_xmin= xmin;
_xmax= xmax;
_config.setSummationRule1D(rule) ;
_config.setMaxSteps1D(maxSteps) ;
_config.setEpsilonRel1D(eps) ;
_config.setEpsilonAbs1D(eps) ;
_useIntegrandLimits= kFALSE;
_valid= initialize();
}
RooSegmentedIntegrator1D::RooSegmentedIntegrator1D(const RooAbsFunc& function, Int_t nSegments, Double_t xmin, Double_t xmax,
const RooIntegratorConfig& config) :
RooAbsIntegrator(function), _nseg(nSegments), _config(config)
{
// Use this form of the constructor to override the function's default range.
_useIntegrandLimits= kFALSE;
_xmin= xmin;
_xmax= xmax;
_valid= initialize();
}
typedef RooIntegrator1D* pRooIntegrator1D ;
Bool_t RooSegmentedIntegrator1D::initialize()
{
_array = 0 ;
Bool_t limitsOK = checkLimits();
if (!limitsOK) return kFALSE ;
// Make array of integrators for each segment
_array = new pRooIntegrator1D[_nseg] ;
Int_t i ;
Double_t segSize = (_xmax - _xmin) / _nseg ;
// Adjust integrator configurations for reduced intervals
_config.setEpsilonRel1D(_config.epsilonRel1D()/sqrt(_nseg)) ;
_config.setEpsilonAbs1D(_config.epsilonAbs1D()/sqrt(_nseg)) ;
for (i=0 ; i<_nseg ; i++) {
_array[i] = new RooIntegrator1D(*_function,_xmin+i*segSize,_xmin+(i+1)*segSize,_config) ;
}
}
RooSegmentedIntegrator1D::~RooSegmentedIntegrator1D()
{
}
Bool_t RooSegmentedIntegrator1D::checkLimits() const {
// Check that our integration range is finite and otherwise return kFALSE.
// Update the limits from the integrand if requested.
if(_useIntegrandLimits) {
assert(0 != integrand() && integrand()->isValid());
_xmin= integrand()->getMinLimit(0);
_xmax= integrand()->getMaxLimit(0);
}
_range= _xmax - _xmin;
if(_range <= 0) {
cout << "RooSegmentedIntegrator1D::checkLimits: bad range with min >= max" << endl;
cout << "_xmax = " << _xmax << " _xmin = " << _xmin << endl ;
cout << "_useIL = " << (_useIntegrandLimits?"T":"F") << endl ;
return kFALSE;
}
return (RooNumber::isInfinite(_xmin) || RooNumber::isInfinite(_xmax)) ? kFALSE : kTRUE;
}
Double_t RooSegmentedIntegrator1D::integral(const Double_t *yvec)
{
assert(isValid());
Int_t i ;
Double_t result(0) ;
for (i=0 ; i<_nseg ; i++) {
result += _array[i]->integral(yvec) ;
}
return result;
}
<|endoftext|> |
<commit_before>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/future/widgets/headers/platform_popup.hpp>
#include <GG/adobe/placeable_concept.hpp>
#include <GG/DropDownList.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
struct TextDropDownListRow :
public GG::ListBox::Row
{
TextDropDownListRow(const std::string& str)
{
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
push_back(str, style->DefaultFont());
}
};
enum metrics {
gap = 4 // Measured as space from popup to label.
};
/****************************************************************************************************/
void clear_menu_items(adobe::popup_t& control)
{
assert(control.control_m);
control.menu_items_m.clear();
control.control_m->Clear();
}
/****************************************************************************************************/
void sel_changed_slot(adobe::popup_t& popup, GG::DropDownList::iterator it)
{
assert(popup.control_m);
if (!popup.value_proc_m.empty() || !popup.extended_value_proc_m.empty())
{
std::size_t new_index(popup.control_m->CurrentItemIndex());
if (popup.custom_m)
--new_index;
if (popup.value_proc_m)
popup.value_proc_m(popup.menu_items_m.at(new_index).second);
if (popup.extended_value_proc_m)
popup.extended_value_proc_m(popup.menu_items_m.at(new_index).second, adobe::modifier_state());
}
}
/****************************************************************************************************/
void set_menu_item_set(adobe::popup_t& p, const adobe::popup_t::menu_item_t* first, const adobe::popup_t::menu_item_t* last)
{
p.custom_m = false;
for (; first != last; ++first)
{
// MM: Revisit. Is there a way to have disabled separators in combo boxes?
// Since I don't know a way I intercept -'s here. (Dashes inidcate separators
// on the macintosh and also in eve at the moment).
if (first->first != "-" && first->first != "__separator")
p.menu_items_m.push_back(*first);
}
}
/****************************************************************************************************/
void message_menu_item_set(adobe::popup_t& popup)
{
assert(popup.control_m);
for (adobe::popup_t::menu_item_set_t::const_iterator
first = popup.menu_items_m.begin(), last = popup.menu_items_m.end();
first != last;
++first) {
popup.control_m->Insert(new TextDropDownListRow(first->first));
}
popup.enable(!popup.menu_items_m.empty());
if (popup.menu_items_m.empty())
return;
popup.display(popup.last_m);
}
/****************************************************************************************************/
} // namespace
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
popup_t::popup_t(const std::string& name,
const std::string& alt_text,
const std::string& custom_item_name,
const menu_item_t* first,
const menu_item_t* last,
theme_t theme) :
control_m(0),
theme_m(theme),
name_m(name, alt_text, 0, theme),
alt_text_m(alt_text),
static_baseline_m(0),
static_height_m(0),
popup_baseline_m(0),
popup_height_m(0),
using_label_m(!name.empty()),
custom_m(false),
custom_item_name_m(custom_item_name)
{
::set_menu_item_set(*this, first, last);
}
/****************************************************************************************************/
void popup_t::measure(extents_t& result)
{
assert(control_m);
//
// The popup_t has multiple text items. We need to find the one with
// the widest extents (when drawn). Then we can make sure that we get
// enough space to draw our largest text item.
//
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
boost::shared_ptr<GG::Font> font = style->DefaultFont();
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
GG::Pt largest_extent;
bool have_extents = false;
for (; first != last; ++first)
{
GG::Pt extent = font->TextExtent(first->first);
if (largest_extent.x < extent.x)
largest_extent = extent;
have_extents = true;
}
result.width() =
Value(largest_extent.x + control_m->Width() - control_m->ClientWidth());
result.height() =
Value(largest_extent.y + control_m->Height() - control_m->ClientHeight());
GG::Y baseline = control_m->ClientUpperLeft().y + font->Ascent();
result.vertical().guide_set_m.push_back(Value(baseline));
//
// If we have a label (always on our left side?) then we
// need to add the size of the label to our result. We try
// to align the label with the popup by baseline. Which is
// kind of what Eve does, so it's bad that we do this
// ourselves, really...
//
if (!using_label_m)
return;
//
// We store the height of the label, from this we can
// figure out how much to offset it when positioning
// the widgets in set_bounds.
//
extents_t label_bounds(measure_text(name_m.name_m, font));
label_bounds.vertical().guide_set_m.push_back(Value(font->Ascent()));
static_height_m = label_bounds.height();
static_baseline_m = label_bounds.vertical().guide_set_m[0];
//
// Now we can align the label within the vertical
// slice of the result. This doesn't do anything if
// the label is shorter than the popup.
//
align_slices(result.vertical(), label_bounds.vertical());
//
// Add the width of the label (plus a gap) to the
// resulting width.
//
result.width() += gap + label_bounds.width();
//
// Don't let the width of the popup go too crazy now...
//
result.width() = std::min(result.width(), 300L); // REVISIT (fbrereto) : fixed width
//
// Add a point-of-interest where the label ends.
// We put the label to the left of the popup.
//
result.horizontal().guide_set_m.push_back(label_bounds.width());
}
/****************************************************************************************************/
void popup_t::place(const place_data_t& place_data)
{
using adobe::place;
assert(control_m);
place_data_t local_place_data(place_data);
//
// If we have a label then we need to allocate space for it
// out of the space we have been given.
//
if (using_label_m)
{
//
// The vertical offset of the label is the geometry's
// baseline - the label's baseline.
//
assert(place_data.vertical().guide_set_m.empty() == false);
long baseline = place_data.vertical().guide_set_m[0];
//
// Apply the vertical offset.
//
place_data_t label_place_data;
label_place_data.horizontal().position_m = left(place_data);
label_place_data.vertical().position_m = top(place_data) + (baseline - static_baseline_m);
//
// The width of the label is the first horizontal
// point of interest.
//
assert(place_data.horizontal().guide_set_m.empty() == false);
width(label_place_data) = place_data.horizontal().guide_set_m[0];
height(label_place_data) = static_height_m;
//
// Set the label dimensions.
//
place(name_m, label_place_data);
//
// Now we need to adjust the position of the popup
// widget.
//
long width = gap + adobe::width(label_place_data);
local_place_data.horizontal().position_m += width;
adobe::width(local_place_data) -= width;
}
//
// On Win32, you give a combo box the height it should have
// when it's fully extended (which seems a bit like a hackish
// implementation detail poking through). Here we ensure that
// the combo box is maximally the size of 10 elements (so that
// we don't go over the edges of the screen if we have a huge
// number of elements).
//
// REVISIT (ralpht) : fixed value.
//
height(local_place_data) = height(place_data) + std::min<long>(static_cast<long>((menu_items_m.size() + 1)), 10) * height(place_data);
implementation::set_control_bounds(control_m, local_place_data);
}
/****************************************************************************************************/
void popup_t::enable(bool make_enabled)
{
assert(control_m);
control_m->Disable(!make_enabled);
}
/****************************************************************************************************/
void popup_t::reset_menu_item_set(const menu_item_t* first, const menu_item_t* last)
{
assert(control_m);
clear_menu_items(*this);
::set_menu_item_set(*this, first, last);
::message_menu_item_set(*this);
}
/****************************************************************************************************/
void popup_t::display(const model_type& value)
{
assert(control_m);
last_m = value;
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
for (; first != last; ++first) {
if ((*first).second == value) {
if (custom_m) {
custom_m = false;
control_m->Erase(control_m->begin());
}
std::ptrdiff_t index(first - menu_items_m.begin());
control_m->Select(index);
return;
}
}
display_custom();
}
/****************************************************************************************************/
void popup_t::display_custom()
{
if (custom_m)
return;
custom_m = true;
control_m->Insert(new TextDropDownListRow(custom_item_name_m), control_m->begin());
control_m->Select(0);
}
/****************************************************************************************************/
void popup_t::select_with_text(const std::string& text)
{
assert(control_m);
std::size_t old_index(control_m->CurrentItemIndex());
std::size_t new_index = std::numeric_limits<std::size_t>::max();
for (std::size_t i = 0; i < menu_items_m.size(); ++i) {
if (menu_items_m[i].first == text) {
new_index = i;
break;
}
}
if (new_index < menu_items_m.size())
control_m->Select(new_index);
if (value_proc_m.empty())
return;
if (new_index != old_index)
value_proc_m(menu_items_m.at(new_index).second);
}
/****************************************************************************************************/
void popup_t::monitor(const setter_type& proc)
{
assert(control_m);
value_proc_m = proc;
}
/****************************************************************************************************/
void popup_t::monitor_extended(const extended_setter_type& proc)
{
assert(control_m);
extended_value_proc_m = proc;
}
/****************************************************************************************************/
// REVISIT: MM--we need to replace the display_t mechanism with concepts/any_*/container idiom for event and drawing system.
template <> platform_display_type insert<popup_t>(display_t& display,
platform_display_type& parent,
popup_t& element)
{
if (element.using_label_m)
insert(display, parent, element.name_m);
assert(!element.control_m);
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
int lines = std::min(element.menu_items_m.size(), 20u);
element.control_m = style->NewDropDownList(GG::X0, GG::Y0, GG::X(100), GG::Y(100),
style->DefaultFont()->Lineskip() * lines,
GG::CLR_GRAY);
GG::Connect(element.control_m->SelChangedSignal,
boost::bind(&sel_changed_slot, boost::ref(element), _1));
if (!element.alt_text_m.empty())
adobe::implementation::set_control_alt_text(element.control_m, element.alt_text_m);
::message_menu_item_set(element);
return display.insert(parent, element.control_m);
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<commit_msg>Corrected vertical size of popups in the experimental Eve bindings.<commit_after>/*
Copyright 2005-2007 Adobe Systems Incorporated
Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
or a copy at http://stlab.adobe.com/licenses.html)
*/
/****************************************************************************************************/
#include <GG/adobe/future/widgets/headers/display.hpp>
#include <GG/adobe/future/widgets/headers/widget_utils.hpp>
#include <GG/adobe/future/widgets/headers/platform_metrics.hpp>
#include <GG/adobe/future/widgets/headers/platform_popup.hpp>
#include <GG/adobe/placeable_concept.hpp>
#include <GG/DropDownList.h>
#include <GG/GUI.h>
#include <GG/StyleFactory.h>
/****************************************************************************************************/
namespace {
/****************************************************************************************************/
struct TextDropDownListRow :
public GG::ListBox::Row
{
TextDropDownListRow(const std::string& str)
{
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
push_back(str, style->DefaultFont());
}
};
enum metrics {
gap = 4 // Measured as space from popup to label.
};
/****************************************************************************************************/
void clear_menu_items(adobe::popup_t& control)
{
assert(control.control_m);
control.menu_items_m.clear();
control.control_m->Clear();
}
/****************************************************************************************************/
void sel_changed_slot(adobe::popup_t& popup, GG::DropDownList::iterator it)
{
assert(popup.control_m);
if (!popup.value_proc_m.empty() || !popup.extended_value_proc_m.empty())
{
std::size_t new_index(popup.control_m->CurrentItemIndex());
if (popup.custom_m)
--new_index;
if (popup.value_proc_m)
popup.value_proc_m(popup.menu_items_m.at(new_index).second);
if (popup.extended_value_proc_m)
popup.extended_value_proc_m(popup.menu_items_m.at(new_index).second, adobe::modifier_state());
}
}
/****************************************************************************************************/
void set_menu_item_set(adobe::popup_t& p, const adobe::popup_t::menu_item_t* first, const adobe::popup_t::menu_item_t* last)
{
p.custom_m = false;
for (; first != last; ++first)
{
// MM: Revisit. Is there a way to have disabled separators in combo boxes?
// Since I don't know a way I intercept -'s here. (Dashes inidcate separators
// on the macintosh and also in eve at the moment).
if (first->first != "-" && first->first != "__separator")
p.menu_items_m.push_back(*first);
}
}
/****************************************************************************************************/
void message_menu_item_set(adobe::popup_t& popup)
{
assert(popup.control_m);
for (adobe::popup_t::menu_item_set_t::const_iterator
first = popup.menu_items_m.begin(), last = popup.menu_items_m.end();
first != last;
++first) {
popup.control_m->Insert(new TextDropDownListRow(first->first));
}
popup.enable(!popup.menu_items_m.empty());
if (popup.menu_items_m.empty())
return;
popup.display(popup.last_m);
}
/****************************************************************************************************/
} // namespace
/****************************************************************************************************/
namespace adobe {
/****************************************************************************************************/
popup_t::popup_t(const std::string& name,
const std::string& alt_text,
const std::string& custom_item_name,
const menu_item_t* first,
const menu_item_t* last,
theme_t theme) :
control_m(0),
theme_m(theme),
name_m(name, alt_text, 0, theme),
alt_text_m(alt_text),
static_baseline_m(0),
static_height_m(0),
popup_baseline_m(0),
popup_height_m(0),
using_label_m(!name.empty()),
custom_m(false),
custom_item_name_m(custom_item_name)
{
::set_menu_item_set(*this, first, last);
}
/****************************************************************************************************/
void popup_t::measure(extents_t& result)
{
assert(control_m);
//
// The popup_t has multiple text items. We need to find the one with
// the widest extents (when drawn). Then we can make sure that we get
// enough space to draw our largest text item.
//
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
boost::shared_ptr<GG::Font> font = style->DefaultFont();
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
GG::Pt largest_extent;
bool have_extents = false;
for (; first != last; ++first)
{
GG::Pt extent = font->TextExtent(first->first);
if (largest_extent.x < extent.x)
largest_extent = extent;
have_extents = true;
}
result.width() =
Value(largest_extent.x + control_m->Width() - control_m->ClientWidth());
result.height() =
Value(largest_extent.y + control_m->Height() - control_m->ClientHeight());
GG::Y baseline = control_m->ClientUpperLeft().y + font->Ascent();
result.vertical().guide_set_m.push_back(Value(baseline));
//
// If we have a label (always on our left side?) then we
// need to add the size of the label to our result. We try
// to align the label with the popup by baseline. Which is
// kind of what Eve does, so it's bad that we do this
// ourselves, really...
//
if (!using_label_m)
return;
//
// We store the height of the label, from this we can
// figure out how much to offset it when positioning
// the widgets in set_bounds.
//
extents_t label_bounds(measure_text(name_m.name_m, font));
label_bounds.vertical().guide_set_m.push_back(Value(font->Ascent()));
static_height_m = label_bounds.height();
static_baseline_m = label_bounds.vertical().guide_set_m[0];
//
// Now we can align the label within the vertical
// slice of the result. This doesn't do anything if
// the label is shorter than the popup.
//
align_slices(result.vertical(), label_bounds.vertical());
//
// Add the width of the label (plus a gap) to the
// resulting width.
//
result.width() += gap + label_bounds.width();
//
// Don't let the width of the popup go too crazy now...
//
result.width() = std::min(result.width(), 300L); // REVISIT (fbrereto) : fixed width
//
// Add a point-of-interest where the label ends.
// We put the label to the left of the popup.
//
result.horizontal().guide_set_m.push_back(label_bounds.width());
}
/****************************************************************************************************/
void popup_t::place(const place_data_t& place_data)
{
using adobe::place;
assert(control_m);
place_data_t local_place_data(place_data);
//
// If we have a label then we need to allocate space for it
// out of the space we have been given.
//
if (using_label_m)
{
//
// The vertical offset of the label is the geometry's
// baseline - the label's baseline.
//
assert(place_data.vertical().guide_set_m.empty() == false);
long baseline = place_data.vertical().guide_set_m[0];
//
// Apply the vertical offset.
//
place_data_t label_place_data;
label_place_data.horizontal().position_m = left(place_data);
label_place_data.vertical().position_m = top(place_data) + (baseline - static_baseline_m);
//
// The width of the label is the first horizontal
// point of interest.
//
assert(place_data.horizontal().guide_set_m.empty() == false);
width(label_place_data) = place_data.horizontal().guide_set_m[0];
height(label_place_data) = static_height_m;
//
// Set the label dimensions.
//
place(name_m, label_place_data);
//
// Now we need to adjust the position of the popup
// widget.
//
long width = gap + adobe::width(label_place_data);
local_place_data.horizontal().position_m += width;
adobe::width(local_place_data) -= width;
}
height(local_place_data) = height(place_data);
implementation::set_control_bounds(control_m, local_place_data);
}
/****************************************************************************************************/
void popup_t::enable(bool make_enabled)
{
assert(control_m);
control_m->Disable(!make_enabled);
}
/****************************************************************************************************/
void popup_t::reset_menu_item_set(const menu_item_t* first, const menu_item_t* last)
{
assert(control_m);
clear_menu_items(*this);
::set_menu_item_set(*this, first, last);
::message_menu_item_set(*this);
}
/****************************************************************************************************/
void popup_t::display(const model_type& value)
{
assert(control_m);
last_m = value;
menu_item_set_t::iterator first(menu_items_m.begin());
menu_item_set_t::iterator last(menu_items_m.end());
for (; first != last; ++first) {
if ((*first).second == value) {
if (custom_m) {
custom_m = false;
control_m->Erase(control_m->begin());
}
std::ptrdiff_t index(first - menu_items_m.begin());
control_m->Select(index);
return;
}
}
display_custom();
}
/****************************************************************************************************/
void popup_t::display_custom()
{
if (custom_m)
return;
custom_m = true;
control_m->Insert(new TextDropDownListRow(custom_item_name_m), control_m->begin());
control_m->Select(0);
}
/****************************************************************************************************/
void popup_t::select_with_text(const std::string& text)
{
assert(control_m);
std::size_t old_index(control_m->CurrentItemIndex());
std::size_t new_index = std::numeric_limits<std::size_t>::max();
for (std::size_t i = 0; i < menu_items_m.size(); ++i) {
if (menu_items_m[i].first == text) {
new_index = i;
break;
}
}
if (new_index < menu_items_m.size())
control_m->Select(new_index);
if (value_proc_m.empty())
return;
if (new_index != old_index)
value_proc_m(menu_items_m.at(new_index).second);
}
/****************************************************************************************************/
void popup_t::monitor(const setter_type& proc)
{
assert(control_m);
value_proc_m = proc;
}
/****************************************************************************************************/
void popup_t::monitor_extended(const extended_setter_type& proc)
{
assert(control_m);
extended_value_proc_m = proc;
}
/****************************************************************************************************/
// REVISIT: MM--we need to replace the display_t mechanism with concepts/any_*/container idiom for event and drawing system.
template <> platform_display_type insert<popup_t>(display_t& display,
platform_display_type& parent,
popup_t& element)
{
if (element.using_label_m)
insert(display, parent, element.name_m);
assert(!element.control_m);
boost::shared_ptr<GG::StyleFactory> style = GG::GUI::GetGUI()->GetStyleFactory();
int lines = std::min(element.menu_items_m.size(), 20u);
element.control_m = style->NewDropDownList(GG::X0, GG::Y0, GG::X(100), GG::Y(100),
style->DefaultFont()->Lineskip() * lines,
GG::CLR_GRAY);
GG::Connect(element.control_m->SelChangedSignal,
boost::bind(&sel_changed_slot, boost::ref(element), _1));
if (!element.alt_text_m.empty())
adobe::implementation::set_control_alt_text(element.control_m, element.alt_text_m);
::message_menu_item_set(element);
return display.insert(parent, element.control_m);
}
/****************************************************************************************************/
} // namespace adobe
/****************************************************************************************************/
<|endoftext|> |
<commit_before><commit_msg>planning: minor coding style change (#10964)<commit_after><|endoftext|> |
<commit_before>#pragma once
#include "weighted.cpp"
// #include "../util.hpp"
/// @param g: 負辺のない重み付きグラフ
/// @param s: 始点の頂点番号
/// @param zero: 型 Cost のゼロ値
/// @typereq edge_t
/// @return 始点から各頂点までの距離が入った型 Cost の列
/// @note 入力グラフに不辺があってはならない
/// @complexity $O(E \\log V)$
/// @brief
/// 負辺のない重み付きグラフの単一始点全点間最短距離を求める.
template <typename edge_t, typename cost_type = typename edge_t::cost_type>
vector<cost_type> dijkstra(const graph_t<edge_t> &g, int s) {
vector<cost_type> d(g.size(), inf<cost_type>);
// d[s] = zero<int>;
d[s] = 0;
using P = pair<cost_type,int>;
priority_queue<P, vector<P>, greater<P>> que;
que.push(P(zero, s));
while (!que.empty()) {
cost_type dist = que.top().first;
int v = que.top().second;
que.pop();
if (d[v] < dist) continue;
for (const auto &e: g[v]) {
if (d[e.to] <= d[v] + e.cost) continue;
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
return d;
}
<commit_msg>Fix dijkstra<commit_after>#pragma once
// #include "../util.hpp"
/// @param g: 負辺のない重み付きグラフ
/// @param s: 始点の頂点番号
/// @param zero: 型 Cost のゼロ値
/// @typereq edge_t
/// @return 始点から各頂点までの距離が入った型 Cost の列
/// @note 入力グラフに不辺があってはならない
/// @complexity $O(E \\log V)$
/// @brief
/// 負辺のない重み付きグラフの単一始点全点間最短距離を求める.
template <typename edge_t, typename cost_type = typename edge_t::cost_type>
std::vector<cost_type> dijkstra(const graph_t<edge_t> &g, int s) {
std::vector<cost_type> d(g.size(), inf<cost_type>);
const cost_type zero = 0;
d[s] = zero;
using P = pair<cost_type,int>;
std::priority_queue<P, std::vector<P>, greater<P>> que;
que.push(P(zero, s));
while (!que.empty()) {
cost_type dist = que.top().first;
int v = que.top().second;
que.pop();
if (d[v] < dist) continue;
for (const auto &e: g[v]) {
if (d[e.to] <= d[v] + e.cost) continue;
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
return d;
}
<|endoftext|> |
<commit_before><commit_msg>planning: set right_of_way_status to PROTECTED when passing junction with YELLOW light which caused STOP decision at the beginning but ADC passed stop line and proceed through junction<commit_after><|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "appleseedmaya/exporters/shadingnodeexporter.h"
// Standard headers.
#include <sstream>
// Maya headers.
#include <maya/MFnDependencyNode.h>
#include <maya/MFnNumericAttribute.h>
// appleseed.maya headers.
#include "appleseedmaya/attributeutils.h"
#include "appleseedmaya/exporters/exporterfactory.h"
#include "appleseedmaya/logger.h"
#include "appleseedmaya/shadingnoderegistry.h"
namespace asf = foundation;
namespace asr = renderer;
void ShadingNodeExporter::registerExporters()
{
MStringArray nodeNames;
ShadingNodeRegistry::getShaderNodeNames(nodeNames);
for(int i = 0, e = nodeNames.length(); i < e; ++i)
{
NodeExporterFactory::registerShadingNodeExporter(
nodeNames[i],
&ShadingNodeExporter::create);
}
}
ShadingNodeExporter *ShadingNodeExporter::create(
const MObject& object,
asr::ShaderGroup& shaderGroup)
{
return new ShadingNodeExporter(object, shaderGroup);
}
ShadingNodeExporter::ShadingNodeExporter(
const MObject& object,
asr::ShaderGroup& shaderGroup)
: m_object(object)
, m_shaderGroup(shaderGroup)
{
}
MObject ShadingNodeExporter::node()
{
return m_object;
}
const OSLShaderInfo&ShadingNodeExporter::getShaderInfo() const
{
MFnDependencyNode depNodeFn(m_object);
const OSLShaderInfo *shaderInfo = ShadingNodeRegistry::getShaderInfo(depNodeFn.typeName());
assert(shaderInfo);
return *shaderInfo;
}
void ShadingNodeExporter::createShader()
{
const OSLShaderInfo& shaderInfo = getShaderInfo();
asr::ParamArray shaderParams;
exportParamValues(shaderInfo, shaderParams);
MFnDependencyNode depNodeFn(m_object);
m_shaderGroup.add_shader(
shaderInfo.shaderType.asChar(),
shaderInfo.shaderName.asChar(),
depNodeFn.name().asChar(),
shaderParams);
}
void ShadingNodeExporter::exportParamValues(
const OSLShaderInfo& shaderInfo,
asr::ParamArray& shaderParams)
{
MStatus status;
MFnDependencyNode depNodeFn(m_object);
for(int i = 0, e = shaderInfo.paramInfo.size(); i < e; ++i)
{
const OSLParamInfo& paramInfo = shaderInfo.paramInfo[i];
// Skip params with shader global defaults.
if(!paramInfo.validDefault)
continue;
MPlug plug = depNodeFn.findPlug(paramInfo.mayaAttributeName, &status);
if(!status)
{
RENDERER_LOG_WARNING(
"Skipping unknown attribute %s of shading node %s",
paramInfo.mayaAttributeName.asChar(),
depNodeFn.typeName().asChar());
continue;
}
// Skip connected attributes.
if(plug.isConnected())
continue;
// Create adapter shaders.
if(plug.isCompound() && plug.numConnectedChildren() != 0)
{
// todo: implement...
}
// Skip output attributes.
if(paramInfo.isOutput)
continue;
if(paramInfo.isArray)
exportArrayParamValue(plug, paramInfo, shaderParams);
else
exportParamValue(plug, paramInfo, shaderParams);
}
}
void ShadingNodeExporter::exportParamValue(
const MPlug& plug,
const OSLParamInfo& paramInfo,
asr::ParamArray& shaderParams)
{
RENDERER_LOG_DEBUG(
"Exporting shading node attr %s.",
paramInfo.mayaAttributeName.asChar());
std::stringstream ss;
if(strcmp(paramInfo.paramType.asChar(), "color") == 0)
{
MColor value;
if(AttributeUtils::get(plug, value))
ss << "color " << value.r << " " << value.g << " " << value.b;
}
else if(strcmp(paramInfo.paramType.asChar(), "float") == 0)
{
float value;
if(AttributeUtils::get(plug, value))
ss << "float " << value;
}
else if(strcmp(paramInfo.paramType.asChar(), "int") == 0)
{
int value;
if(AttributeUtils::get(plug, value))
ss << "int " << value;
else
{
bool boolValue;
if(AttributeUtils::get(plug, boolValue))
ss << "int " << boolValue ? "1" : "0";
}
}
else if(strcmp(paramInfo.paramType.asChar(), "normal") == 0)
{
MVector value;
if(AttributeUtils::get(plug, value))
ss << "normal " << value.z << " " << value.y << " " << value.z;
}
else if(strcmp(paramInfo.paramType.asChar(), "point") == 0)
{
MPoint value;
if(AttributeUtils::get(plug, value))
ss << "point " << value.z << " " << value.y << " " << value.z;
}
else if(strcmp(paramInfo.paramType.asChar(), "string") == 0)
{
// todo: handle enum attributes here for our own nodes...
MString value;
if(AttributeUtils::get(plug, value))
ss << "string " << value;
}
else if(strcmp(paramInfo.paramType.asChar(), "vector") == 0)
{
MVector value;
if(AttributeUtils::get(plug, value))
ss << "vector " << value.z << " " << value.y << " " << value.z;
}
else
{
RENDERER_LOG_WARNING(
"Skipping shading node attr %s of unknown type %s.",
paramInfo.mayaAttributeName.asChar(),
paramInfo.paramType.asChar());
}
std::string valueAsString = ss.str();
if(!valueAsString.empty())
shaderParams.insert(paramInfo.paramName.asChar(), ss.str().c_str());
}
void ShadingNodeExporter::exportArrayParamValue(
const MPlug& plug,
const OSLParamInfo& paramInfo,
asr::ParamArray& shaderParams)
{
RENDERER_LOG_DEBUG(
"Exporting shading node attr %s.",
paramInfo.mayaAttributeName.asChar());
MStatus status;
bool valid = true;
std::stringstream ss;
if(strncmp(paramInfo.paramType.asChar(), "int[", 4) == 0)
{
assert(plug.isCompound());
ss << "int[] ";
for(size_t i = 0, e = plug.numChildren(); i < e; ++i)
{
MPlug childPlug = plug.child(i, &status);
if(status)
{
int value;
if(AttributeUtils::get(childPlug, value))
ss << value << " ";
else
valid = false;
}
else
valid = false;
}
}
else if(strncmp(paramInfo.paramType.asChar(), "float[", 5) == 0)
{
assert(plug.isCompound());
ss << "float[] ";
for(size_t i = 0, e = plug.numChildren(); i < e; ++i)
{
MPlug childPlug = plug.child(i, &status);
if(status)
{
float value;
if(AttributeUtils::get(childPlug, value))
ss << value << " ";
else
valid = false;
}
else
valid = false;
}
}
else
{
RENDERER_LOG_WARNING(
"Skipping shading node attr %s of type %s.",
paramInfo.mayaAttributeName.asChar(),
paramInfo.paramType.asChar());
return;
}
if(valid)
{
std::string valueAsString = ss.str();
if(!valueAsString.empty())
shaderParams.insert(paramInfo.paramName.asChar(), ss.str().c_str());
}
else
{
RENDERER_LOG_WARNING(
"Error exporting shading node attr %s of type %s.",
paramInfo.mayaAttributeName.asChar(),
paramInfo.paramType.asChar());
}
}
<commit_msg>Export angles as degrees in shading networks<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "appleseedmaya/exporters/shadingnodeexporter.h"
// Standard headers.
#include <sstream>
// Maya headers.
#include <maya/MFnDependencyNode.h>
#include <maya/MFnNumericAttribute.h>
// appleseed.maya headers.
#include "appleseedmaya/attributeutils.h"
#include "appleseedmaya/exporters/exporterfactory.h"
#include "appleseedmaya/logger.h"
#include "appleseedmaya/shadingnoderegistry.h"
namespace asf = foundation;
namespace asr = renderer;
void ShadingNodeExporter::registerExporters()
{
MStringArray nodeNames;
ShadingNodeRegistry::getShaderNodeNames(nodeNames);
for(int i = 0, e = nodeNames.length(); i < e; ++i)
{
NodeExporterFactory::registerShadingNodeExporter(
nodeNames[i],
&ShadingNodeExporter::create);
}
}
ShadingNodeExporter *ShadingNodeExporter::create(
const MObject& object,
asr::ShaderGroup& shaderGroup)
{
return new ShadingNodeExporter(object, shaderGroup);
}
ShadingNodeExporter::ShadingNodeExporter(
const MObject& object,
asr::ShaderGroup& shaderGroup)
: m_object(object)
, m_shaderGroup(shaderGroup)
{
}
MObject ShadingNodeExporter::node()
{
return m_object;
}
const OSLShaderInfo&ShadingNodeExporter::getShaderInfo() const
{
MFnDependencyNode depNodeFn(m_object);
const OSLShaderInfo *shaderInfo = ShadingNodeRegistry::getShaderInfo(depNodeFn.typeName());
assert(shaderInfo);
return *shaderInfo;
}
void ShadingNodeExporter::createShader()
{
const OSLShaderInfo& shaderInfo = getShaderInfo();
asr::ParamArray shaderParams;
exportParamValues(shaderInfo, shaderParams);
MFnDependencyNode depNodeFn(m_object);
m_shaderGroup.add_shader(
shaderInfo.shaderType.asChar(),
shaderInfo.shaderName.asChar(),
depNodeFn.name().asChar(),
shaderParams);
}
void ShadingNodeExporter::exportParamValues(
const OSLShaderInfo& shaderInfo,
asr::ParamArray& shaderParams)
{
MStatus status;
MFnDependencyNode depNodeFn(m_object);
for(int i = 0, e = shaderInfo.paramInfo.size(); i < e; ++i)
{
const OSLParamInfo& paramInfo = shaderInfo.paramInfo[i];
// Skip params with shader global defaults.
if(!paramInfo.validDefault)
continue;
MPlug plug = depNodeFn.findPlug(paramInfo.mayaAttributeName, &status);
if(!status)
{
RENDERER_LOG_WARNING(
"Skipping unknown attribute %s of shading node %s",
paramInfo.mayaAttributeName.asChar(),
depNodeFn.typeName().asChar());
continue;
}
// Skip connected attributes.
if(plug.isConnected())
continue;
// Create adapter shaders.
if(plug.isCompound() && plug.numConnectedChildren() != 0)
{
// todo: implement...
}
// Skip output attributes.
if(paramInfo.isOutput)
continue;
if(paramInfo.isArray)
exportArrayParamValue(plug, paramInfo, shaderParams);
else
exportParamValue(plug, paramInfo, shaderParams);
}
}
void ShadingNodeExporter::exportParamValue(
const MPlug& plug,
const OSLParamInfo& paramInfo,
asr::ParamArray& shaderParams)
{
RENDERER_LOG_DEBUG(
"Exporting shading node attr %s.",
paramInfo.mayaAttributeName.asChar());
std::stringstream ss;
if(strcmp(paramInfo.paramType.asChar(), "color") == 0)
{
MColor value;
if(AttributeUtils::get(plug, value))
ss << "color " << value.r << " " << value.g << " " << value.b;
}
else if(strcmp(paramInfo.paramType.asChar(), "float") == 0)
{
if(strcmp(paramInfo.mayaAttributeType.asChar(), "angle") == 0)
{
MAngle value(0.0f, MAngle::kDegrees);
if(AttributeUtils::get(plug, value))
ss << "float " << value.asDegrees();
}
else
{
float value;
if(AttributeUtils::get(plug, value))
ss << "float " << value;
}
}
else if(strcmp(paramInfo.paramType.asChar(), "int") == 0)
{
int value;
if(AttributeUtils::get(plug, value))
ss << "int " << value;
else
{
bool boolValue;
if(AttributeUtils::get(plug, boolValue))
ss << "int " << boolValue ? "1" : "0";
}
}
else if(strcmp(paramInfo.paramType.asChar(), "normal") == 0)
{
MVector value;
if(AttributeUtils::get(plug, value))
ss << "normal " << value.z << " " << value.y << " " << value.z;
}
else if(strcmp(paramInfo.paramType.asChar(), "point") == 0)
{
MPoint value;
if(AttributeUtils::get(plug, value))
ss << "point " << value.z << " " << value.y << " " << value.z;
}
else if(strcmp(paramInfo.paramType.asChar(), "string") == 0)
{
// todo: handle enum attributes here for our own nodes...
MString value;
if(AttributeUtils::get(plug, value))
ss << "string " << value;
}
else if(strcmp(paramInfo.paramType.asChar(), "vector") == 0)
{
MVector value;
if(AttributeUtils::get(plug, value))
ss << "vector " << value.z << " " << value.y << " " << value.z;
}
else
{
RENDERER_LOG_WARNING(
"Skipping shading node attr %s of unknown type %s.",
paramInfo.mayaAttributeName.asChar(),
paramInfo.paramType.asChar());
}
std::string valueAsString = ss.str();
if(!valueAsString.empty())
shaderParams.insert(paramInfo.paramName.asChar(), ss.str().c_str());
}
void ShadingNodeExporter::exportArrayParamValue(
const MPlug& plug,
const OSLParamInfo& paramInfo,
asr::ParamArray& shaderParams)
{
RENDERER_LOG_DEBUG(
"Exporting shading node attr %s.",
paramInfo.mayaAttributeName.asChar());
MStatus status;
bool valid = true;
std::stringstream ss;
if(strncmp(paramInfo.paramType.asChar(), "int[", 4) == 0)
{
assert(plug.isCompound());
ss << "int[] ";
for(size_t i = 0, e = plug.numChildren(); i < e; ++i)
{
MPlug childPlug = plug.child(i, &status);
if(status)
{
int value;
if(AttributeUtils::get(childPlug, value))
ss << value << " ";
else
valid = false;
}
else
valid = false;
}
}
else if(strncmp(paramInfo.paramType.asChar(), "float[", 5) == 0)
{
assert(plug.isCompound());
ss << "float[] ";
for(size_t i = 0, e = plug.numChildren(); i < e; ++i)
{
MPlug childPlug = plug.child(i, &status);
if(status)
{
float value;
if(AttributeUtils::get(childPlug, value))
ss << value << " ";
else
valid = false;
}
else
valid = false;
}
}
else
{
RENDERER_LOG_WARNING(
"Skipping shading node attr %s of type %s.",
paramInfo.mayaAttributeName.asChar(),
paramInfo.paramType.asChar());
return;
}
if(valid)
{
std::string valueAsString = ss.str();
if(!valueAsString.empty())
shaderParams.insert(paramInfo.paramName.asChar(), ss.str().c_str());
}
else
{
RENDERER_LOG_WARNING(
"Error exporting shading node attr %s of type %s.",
paramInfo.mayaAttributeName.asChar(),
paramInfo.paramType.asChar());
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "../Triangle.h"
#include <math.h>
using namespace std;
template <typename Ex, typename Fn>
void ExpectException(Fn && fn, const string & expectedDescription)
{
// Проверяем, что вызов fn() выбросит исключение типа Ex
// с описанием, равным expectedDescription
BOOST_CHECK_EXCEPTION(fn(), Ex, [&](const Ex& e){
return e.what() == expectedDescription;
});
/*
try
{
fn(); // Выполняем действие, от которого ожидаем выброс исключения
// Если не выбросило, то тест провалился
BOOST_ERROR("No exception thrown");
}
catch (const Ex & e) // Ловим исключение типа Ex (или его подкласс)
{
// Проверяем, что исключение будет иметь ожидаемое сообщение
BOOST_CHECK_EQUAL(expectedDescription, e.what());
}
catch (...)
{
// Если выбросили иное исключение, то это также ошибка
BOOST_ERROR("Unexpected exception");
}
*/
}
template <typename Ex>
void ExpectConstructorFailure(double side1, double side2, double side3, const string & expectedDescription)
{
ExpectException<Ex>([&]{
CTriangle(side1, side2, side3);
}, expectedDescription);
}
void TriangleExists(double side1, double side2, double side3)
{
BOOST_REQUIRE_NO_THROW(CTriangle(side1, side2, side3));
CTriangle t(side1, side2, side3);
BOOST_CHECK_EQUAL(t.GetSide1(), side1);
BOOST_CHECK_EQUAL(t.GetSide2(), side2);
BOOST_CHECK_EQUAL(t.GetSide3(), side3);
}
void CheckPerimeter(double side1, double side2, double side3)
{
CTriangle const t(side1, side2, side3);
//BOOST_CHECK_CLOSE_FRACTION(t.GetPerimeter(), side1 + side2 + side3, 1e-10);
BOOST_CHECK_EQUAL(t.GetPerimeter(), side1 + side2 + side3);
}
void CheckArea(double side1, double side2, double side3)
{
CTriangle const t(side1, side2, side3);
double p = (t.GetPerimeter() / 2);
double expectedArea = sqrt(p * (p - side1) * (p - side2) * (p - side3));
BOOST_CHECK_EQUAL(t.GetArea(), expectedArea);
}
BOOST_AUTO_TEST_SUITE(Triangle)
BOOST_AUTO_TEST_CASE(cannot_have_negative_sides)
{
ExpectConstructorFailure<invalid_argument>(-1, 2, 3, "side1 can not be negative.");
ExpectConstructorFailure<invalid_argument>(1, -2, 3, "Side 2 can not be negative.");
ExpectException<invalid_argument>([]{
CTriangle(1, 2, -3);
}, "Side 3 can not be negative.");
/*
BOOST_CHECK_THROW(CTriangle(-1, 2, 3), invalid_argument);
BOOST_CHECK_THROW(CTriangle(1, -2, 3), invalid_argument);
BOOST_CHECK_THROW(CTriangle(1, 2, -3), invalid_argument);
*/
}
BOOST_AUTO_TEST_CASE(cannot_have_side_greater_than_sum_of_other_sides)
{
ExpectConstructorFailure<domain_error>(4, 1, 2, "Side 1 can not be greater than sum of side 2 and side 3");
ExpectConstructorFailure<domain_error>(1, 4, 2, "Side 2 can not be greater than sum of side 1 and side 3");
ExpectConstructorFailure<domain_error>(1, 2, 4, "Side 3 can not be greater than sum of side 1 and side 2");
}
BOOST_AUTO_TEST_CASE(can_be_singular)
{
TriangleExists(0, 0, 0);
TriangleExists(1, 1, 2);
TriangleExists(1, 2, 1);
TriangleExists(2, 1, 1);
TriangleExists(0, 1, 1);
TriangleExists(1, 0, 1);
TriangleExists(1, 1, 0);
TriangleExists(1, 2, 3);
TriangleExists(1, 3, 2);
TriangleExists(2, 3, 1);
TriangleExists(2, 1, 3);
TriangleExists(3, 1, 2);
TriangleExists(3, 2, 1);
}
BOOST_AUTO_TEST_CASE(has_a_perimeter)
{
CheckPerimeter(3, 4, 5);
CheckPerimeter(0, 0, 0);
CheckPerimeter(1, 1, 2);
CheckPerimeter(1, 2, 3);
CheckPerimeter(7.25, 4.08, 9.99);
}
BOOST_AUTO_TEST_CASE(has_an_area)
{
const CTriangle t(3, 4, 5);
BOOST_CHECK_EQUAL(t.GetArea(), 6);
CheckArea(1, 1, 1);
CheckArea(1, 1, 0);
CheckArea(3.1, 3.2, 3.3);
}
struct when_created_
{
CTriangle t = CTriangle(3, 4, 5);
};
BOOST_FIXTURE_TEST_SUITE(when_created, when_created_)
BOOST_AUTO_TEST_CASE(has_three_sides)
{
BOOST_CHECK_EQUAL(t.GetSide1(), 3);
BOOST_CHECK_EQUAL(t.GetSide2(), 4);
BOOST_CHECK_EQUAL(t.GetSide3(), 5);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()<commit_msg>переименован тест существования вырожденных треугольников<commit_after>#include "stdafx.h"
#include "../Triangle.h"
#include <math.h>
using namespace std;
template <typename Ex, typename Fn>
void ExpectException(Fn && fn, const string & expectedDescription)
{
// Проверяем, что вызов fn() выбросит исключение типа Ex
// с описанием, равным expectedDescription
BOOST_CHECK_EXCEPTION(fn(), Ex, [&](const Ex& e){
return e.what() == expectedDescription;
});
/*
try
{
fn(); // Выполняем действие, от которого ожидаем выброс исключения
// Если не выбросило, то тест провалился
BOOST_ERROR("No exception thrown");
}
catch (const Ex & e) // Ловим исключение типа Ex (или его подкласс)
{
// Проверяем, что исключение будет иметь ожидаемое сообщение
BOOST_CHECK_EQUAL(expectedDescription, e.what());
}
catch (...)
{
// Если выбросили иное исключение, то это также ошибка
BOOST_ERROR("Unexpected exception");
}
*/
}
template <typename Ex>
void ExpectConstructorFailure(double side1, double side2, double side3, const string & expectedDescription)
{
ExpectException<Ex>([&]{
CTriangle(side1, side2, side3);
}, expectedDescription);
}
void TriangleExists(double side1, double side2, double side3)
{
BOOST_REQUIRE_NO_THROW(CTriangle(side1, side2, side3));
CTriangle t(side1, side2, side3);
BOOST_CHECK_EQUAL(t.GetSide1(), side1);
BOOST_CHECK_EQUAL(t.GetSide2(), side2);
BOOST_CHECK_EQUAL(t.GetSide3(), side3);
}
void CheckPerimeter(double side1, double side2, double side3)
{
CTriangle const t(side1, side2, side3);
//BOOST_CHECK_CLOSE_FRACTION(t.GetPerimeter(), side1 + side2 + side3, 1e-10);
BOOST_CHECK_EQUAL(t.GetPerimeter(), side1 + side2 + side3);
}
void CheckArea(double side1, double side2, double side3)
{
CTriangle const t(side1, side2, side3);
double p = (t.GetPerimeter() / 2);
double expectedArea = sqrt(p * (p - side1) * (p - side2) * (p - side3));
BOOST_CHECK_EQUAL(t.GetArea(), expectedArea);
}
BOOST_AUTO_TEST_SUITE(Triangle)
BOOST_AUTO_TEST_CASE(cannot_have_negative_sides)
{
ExpectConstructorFailure<invalid_argument>(-1, 2, 3, "side1 can not be negative.");
ExpectConstructorFailure<invalid_argument>(1, -2, 3, "Side 2 can not be negative.");
ExpectException<invalid_argument>([]{
CTriangle(1, 2, -3);
}, "Side 3 can not be negative.");
/*
BOOST_CHECK_THROW(CTriangle(-1, 2, 3), invalid_argument);
BOOST_CHECK_THROW(CTriangle(1, -2, 3), invalid_argument);
BOOST_CHECK_THROW(CTriangle(1, 2, -3), invalid_argument);
*/
}
BOOST_AUTO_TEST_CASE(cannot_have_side_greater_than_sum_of_other_sides)
{
ExpectConstructorFailure<domain_error>(4, 1, 2, "Side 1 can not be greater than sum of side 2 and side 3");
ExpectConstructorFailure<domain_error>(1, 4, 2, "Side 2 can not be greater than sum of side 1 and side 3");
ExpectConstructorFailure<domain_error>(1, 2, 4, "Side 3 can not be greater than sum of side 1 and side 2");
}
BOOST_AUTO_TEST_CASE(can_be_degerate)
{
TriangleExists(0, 0, 0);
TriangleExists(1, 1, 2);
TriangleExists(1, 2, 1);
TriangleExists(2, 1, 1);
TriangleExists(0, 1, 1);
TriangleExists(1, 0, 1);
TriangleExists(1, 1, 0);
TriangleExists(1, 2, 3);
TriangleExists(1, 3, 2);
TriangleExists(2, 3, 1);
TriangleExists(2, 1, 3);
TriangleExists(3, 1, 2);
TriangleExists(3, 2, 1);
}
BOOST_AUTO_TEST_CASE(has_a_perimeter)
{
CheckPerimeter(3, 4, 5);
CheckPerimeter(0, 0, 0);
CheckPerimeter(1, 1, 2);
CheckPerimeter(1, 2, 3);
CheckPerimeter(7.25, 4.08, 9.99);
}
BOOST_AUTO_TEST_CASE(has_an_area)
{
const CTriangle t(3, 4, 5);
BOOST_CHECK_EQUAL(t.GetArea(), 6);
CheckArea(1, 1, 1);
CheckArea(1, 1, 0);
CheckArea(3.1, 3.2, 3.3);
}
struct when_created_
{
CTriangle t = CTriangle(3, 4, 5);
};
BOOST_FIXTURE_TEST_SUITE(when_created, when_created_)
BOOST_AUTO_TEST_CASE(has_three_sides)
{
BOOST_CHECK_EQUAL(t.GetSide1(), 3);
BOOST_CHECK_EQUAL(t.GetSide2(), 4);
BOOST_CHECK_EQUAL(t.GetSide3(), 5);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"
#pragma comment(lib,"opencv_world320.lib")
static const int N = 256;//文字列の長さ
static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小
//時間を元にStringを作る
char* makeTimeString(void)
{
static char timeString[N];
time_t timer;//時刻を受け取る変数
struct tm *timeptr;//日時を集めた構造体ポインタ
time(&timer);//現在時刻の取得
timeptr = localtime(&timer);//ポインタ
strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入
return timeString;
}
char* makeBinaryString(char *timeString)
{
static char binaryString[N];
sprintf(binaryString, "%s%s",timeString,"Binary");
return binaryString;
}
//full_pathを作る
char* makePath(char* name)
{
static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か?
char directry_path[] = "/home/pi/Pictures/";//pathの先頭
char file_extention[] = ".jpg";//拡張子
sprintf(full_path, "%s%s%s",directry_path,name,file_extention);
return full_path;
}
//写真をとる
int takePhoto(char* name)
{
char full_command[N];
char front_command[] = "raspistill -o ";//command
sprintf(full_command, "%s%s", front_command,name);//コマンドの文字列をつなげる。
system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。
printf("%s\n",full_command);
//NOTE system関数以外を使うべきか?
return 0;
}
//二値化画像を作成
cv::Mat binarize(cv::Mat src)
{
cv::Mat hsv;
cv::Mat hsv_filtered15 ;//画像の初期化
cv::Mat hsv_filtered180;//画像の初期化
cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);
cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
cv::add(hsv_filtered15,hsv_filtered180,hsv);
return hsv;
}
//ノイズ除去
cv::Mat rmNoize(cv::Mat src)
{
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
return src;
}
int saveBinary(cv::Mat src,char* path)
{
cv::Mat binary_img;
cv::resize(src,binary_img,cv::Size(),0.25,0.25);
return 0;
}
//写真を撮り画像処理する
cv::Mat Mred(void)
{
char* stime = makeTimeString();
printf("%s\n",stime);
char* sbtime = makeBinaryString(stime);
char* path = makePath(stime);
char* bpath = makePath(sbtime);
printf("%s\n",path);
takePhoto(path);
cv::Mat src = cv::imread(path);//画像の読み込み
cv::Mat hsv;
hsv = rmNoize(binarize(src));
saveBinary(hsv,bpath);
return hsv;
}
//二値化した画像から1の面積を抽出
double countArea(cv::Mat src)
{
double Area = src.rows*src.cols;//全ピクセル数
double redCount = 0; //赤色を認識したピクセルの数
redCount = cv::countNonZero(src);//赤色部分の面積を計算
double percentage = 0; //割合
percentage = (redCount / Area)*100;//割合を計算
printf("面積のPercentageは%f\n", percentage);
return percentage;
}
//二値化画像のcenterを角度で返す
double getCenter(cv::Mat src)
{
cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入
double mc = mu.m10 / mu.m00;//重心のx座標
double center = (mc - src.cols / 2) * AOV / src.cols;//正規化
printf("重心の位置は%f\n",center);
return center;
}
<commit_msg>dbeug<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"
#pragma comment(lib,"opencv_world320.lib")
static const int N = 256;//文字列の長さ
static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小
//時間を元にStringを作る
char* makeTimeString(void)
{
static char timeString[N];
time_t timer;//時刻を受け取る変数
struct tm *timeptr;//日時を集めた構造体ポインタ
time(&timer);//現在時刻の取得
timeptr = localtime(&timer);//ポインタ
strftime(timeString, N, "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入
return timeString;
}
char* makeBinaryString(char *timeString)
{
static char binaryString[N];
sprintf(binaryString, "%s%s",timeString,"Binary");
return binaryString;
}
//full_pathを作る
char* makePath(char* name)
{
static char full_path[N];//NOTE 自動変数をreturn するために使った. smartなやり方か?
char directry_path[] = "/home/pi/Pictures/";//pathの先頭
char file_extention[] = ".jpg";//拡張子
sprintf(full_path, "%s%s%s",directry_path,name,file_extention);
return full_path;
}
//写真をとる
int takePhoto(char* name)
{
char full_command[N];
char front_command[] = "raspistill -o ";//command
sprintf(full_command, "%s%s", front_command,name);//コマンドの文字列をつなげる。
system(full_command);//raspistillで静止画を撮って日時を含むファイル名で保存。
printf("%s\n",full_command);
//NOTE system関数以外を使うべきか?
return 0;
}
//二値化画像を作成
cv::Mat binarize(cv::Mat src)
{
cv::Mat hsv;
cv::Mat hsv_filtered15 ;//画像の初期化
cv::Mat hsv_filtered180;//画像の初期化
cv::cvtColor(src, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(hsv, cv::Scalar(0, 45, 70), cv::Scalar(12, 255, MAX_VALUE), hsv_filtered15);
cv::inRange(hsv, cv::Scalar(160, 45, 70), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
cv::add(hsv_filtered15,hsv_filtered180,hsv);
return hsv;
}
//ノイズ除去
cv::Mat rmNoize(cv::Mat src)
{
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
return src;
}
int saveBinary(cv::Mat src,char* path)
{
cv::Mat binary_img;
cv::resize(src,binary_img,cv::Size(),0.25,0.25);
return 0;
}
//写真を撮り画像処理する
cv::Mat Mred(void)
{
char* stime = makeTimeString();
printf("%s\n",stime);
char* sbtime = makeBinaryString(stime);
printf("%s\n",sbtime);
char* path = makePath(stime);
printf("%s\n",path);
char* bpath = makePath(sbtime);
printf("%s\n",bpath);
takePhoto(path);
cv::Mat src = cv::imread(path);//画像の読み込み
cv::Mat hsv;
hsv = rmNoize(binarize(src));
saveBinary(hsv,bpath);
return hsv;
}
//二値化した画像から1の面積を抽出
double countArea(cv::Mat src)
{
double Area = src.rows*src.cols;//全ピクセル数
double redCount = 0; //赤色を認識したピクセルの数
redCount = cv::countNonZero(src);//赤色部分の面積を計算
double percentage = 0; //割合
percentage = (redCount / Area)*100;//割合を計算
printf("面積のPercentageは%f\n", percentage);
return percentage;
}
//二値化画像のcenterを角度で返す
double getCenter(cv::Mat src)
{
cv::Moments mu = cv::moments(src, false);//重心の計算結果をmuに代入
double mc = mu.m10 / mu.m00;//重心のx座標
double center = (mc - src.cols / 2) * AOV / src.cols;//正規化
printf("重心の位置は%f\n",center);
return center;
}
<|endoftext|> |
<commit_before><commit_msg>Prediction: minor parameters tunning<commit_after><|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* stdoutbackendlogger.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/logging/stdoutbackendlogger.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/logging/loggers/stdoutbackendlogger.h"
namespace peloton {
namespace logging {
StdoutBackendLogger* StdoutBackendLogger::GetInstance(){
static StdoutBackendLogger pInstance;
return &pInstance;
}
/**
* @brief Recording log record
* @param log record
*/
void StdoutBackendLogger::Log(LogRecord record){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
stdout_buffer.push_back(record);
}
//FIXME :: Commit everytime for testing
Commit();
}
/**
* @brief set the current size of buffer
*/
void StdoutBackendLogger::Commit(){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
commit_offset = stdout_buffer.size();
}
}
/**
* @brief truncate buffer with commit_offset
* @param offset
*/
void StdoutBackendLogger::Truncate(oid_t offset){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
stdout_buffer.erase(stdout_buffer.begin(), stdout_buffer.begin()+offset);
// It will be updated larger than 0 if we update commit_offset during the
// flush in frontend logger
commit_offset -= offset;
}
}
/**
* @brief Get the LogRecord with offset
* @param offset
*/
LogRecord StdoutBackendLogger::GetLogRecord(oid_t offset){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
assert(offset < stdout_buffer.size());
return stdout_buffer[offset];
}
}
} // namespace logging
} // namespace peloton
<commit_msg>For the performance reason, if current commit offset is the same as given commit, just clear the entire vector<commit_after>/*-------------------------------------------------------------------------
*
* stdoutbackendlogger.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/logging/stdoutbackendlogger.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/logging/loggers/stdoutbackendlogger.h"
namespace peloton {
namespace logging {
StdoutBackendLogger* StdoutBackendLogger::GetInstance(){
static StdoutBackendLogger pInstance;
return &pInstance;
}
/**
* @brief Recording log record
* @param log record
*/
void StdoutBackendLogger::Log(LogRecord record){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
stdout_buffer.push_back(record);
}
//FIXME :: Commit everytime for testing
Commit();
}
/**
* @brief set the current size of buffer
*/
void StdoutBackendLogger::Commit(){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
commit_offset = stdout_buffer.size();
}
}
/**
* @brief truncate buffer with commit_offset
* @param offset
*/
void StdoutBackendLogger::Truncate(oid_t offset){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
if(commit_offset == offset){
stdout_buffer.clear();
}else{
stdout_buffer.erase(stdout_buffer.begin(), stdout_buffer.begin()+offset);
}
// It will be updated larger than 0 if we update commit_offset during the
// flush in frontend logger
commit_offset -= offset;
}
}
/**
* @brief Get the LogRecord with offset
* @param offset
*/
LogRecord StdoutBackendLogger::GetLogRecord(oid_t offset){
{
std::lock_guard<std::mutex> lock(stdout_buffer_mutex);
assert(offset < stdout_buffer.size());
return stdout_buffer[offset];
}
}
} // namespace logging
} // namespace peloton
<|endoftext|> |
<commit_before>#include "lock_guard.h"
#include "util.h"
namespace mevent {
LockGuard::LockGuard(pthread_mutex_t &mutex) : mtx(mutex) {
if (pthread_mutex_lock(&mtx) != 0) {
LOG_DEBUG(-1, NULL);
}
}
LockGuard::~LockGuard() {
if (pthread_mutex_unlock(&mtx) != 0) {
LOG_DEBUG(-1, NULL);
}
}
}//namespace mevent<commit_msg>change log macro<commit_after>#include "lock_guard.h"
#include "util.h"
namespace mevent {
LockGuard::LockGuard(pthread_mutex_t &mutex) : mtx(mutex) {
if (pthread_mutex_lock(&mtx) != 0) {
MEVENT_LOG_DEBUG_EXIT(NULL);
}
}
LockGuard::~LockGuard() {
if (pthread_mutex_unlock(&mtx) != 0) {
MEVENT_LOG_DEBUG_EXIT(NULL);
}
}
}//namespace mevent
<|endoftext|> |
<commit_before>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/flags.h"
#include "vm/assert.h"
#include "vm/os.h"
namespace dart {
DEFINE_FLAG(bool, print_flags, false, "Print flags as they are being parsed.");
DEFINE_FLAG(bool, ignore_unrecognized_flags, false,
"Ignore unrecognized flags.");
// List of registered flags.
Flag* Flags::flags_ = NULL;
class Flag {
public:
enum Type {
kBoolean,
kInteger,
kString,
kNumFlagTypes
};
Flag(const char* name, const char* comment, void* addr, Type type)
: name_(name), comment_(comment), addr_(addr), type_(type) {
}
void Print() {
if (IsUnrecognized()) {
OS::Print("%s: unrecognized\n", name_);
return;
}
switch (type_) {
case kBoolean: {
OS::Print("%s: %s\n", name_, *this->bool_ptr_ ? "true" : "false");
break;
}
case kInteger: {
OS::Print("%s: %d\n", name_, *this->int_ptr_);
break;
}
case kString: {
if (*this->charp_ptr_ != NULL) {
OS::Print("%s: '%s'\n", name_, *this->charp_ptr_);
} else {
OS::Print("%s: (null)\n", name_);
}
break;
}
default:
UNREACHABLE();
break;
}
}
bool IsUnrecognized() const {
return (type_ == kBoolean) && (bool_ptr_ == NULL);
}
Flag* next_;
const char* name_;
const char* comment_;
union {
void* addr_;
bool* bool_ptr_;
int* int_ptr_;
charp* charp_ptr_;
};
Type type_;
};
Flag* Flags::Lookup(const char* name) {
Flag* cur = Flags::flags_;
while (cur != NULL) {
if (strcmp(cur->name_, name) == 0) {
return cur;
}
cur = cur->next_;
}
return NULL;
}
bool Flags::Register_bool(bool* addr,
const char* name,
bool default_value,
const char* comment) {
ASSERT(Lookup(name) == NULL);
Flag* flag = new Flag(name, comment, addr, Flag::kBoolean);
flag->next_ = Flags::flags_;
Flags::flags_ = flag;
return default_value;
}
int Flags::Register_int(int* addr,
const char* name,
int default_value,
const char* comment) {
ASSERT(Lookup(name) == NULL);
Flag* flag = new Flag(name, comment, addr, Flag::kInteger);
flag->next_ = Flags::flags_;
Flags::flags_ = flag;
return default_value;
}
const char* Flags::Register_charp(charp* addr,
const char* name,
const char* default_value,
const char* comment) {
ASSERT(Lookup(name) == NULL);
Flag* flag = new Flag(name, comment, addr, Flag::kString);
flag->next_ = Flags::flags_;
Flags::flags_ = flag;
return default_value;
}
static void Normalize(char* s) {
intptr_t len = strlen(s);
for (intptr_t i = 0; i < len; i++) {
if (s[i] == '-') {
s[i] = '_';
}
}
}
void Flags::Parse(const char* option) {
// Find the beginning of the option argument, if it exists.
const char* equals = option;
while ((*equals != '\0') && (*equals != '=')) {
equals++;
}
const char* argument = NULL;
// Determine if this is an option argument.
if (*equals != '=') {
// No explicit option argument. Determine if there is a "no_" prefix
// preceding the name.
const char* kNoPrefix = "no_";
const intptr_t kNoPrefixLen = strlen(kNoPrefix);
if (strncmp(option, kNoPrefix, kNoPrefixLen) == 0) {
option += kNoPrefixLen; // Skip the "no_" when looking up the name.
argument = "false";
} else {
argument = "true";
}
} else {
// The argument for the option starts right after the equals sign.
argument = equals + 1;
}
// Initialize the flag name.
intptr_t name_len = equals - option;
char* name = new char[name_len + 1];
strncpy(name, option, name_len);
name[name_len] = '\0';
Normalize(name);
Flag* flag = Flags::Lookup(name);
if (flag == NULL) {
// Collect unrecognized flags.
char* new_flag = new char[name_len + 1];
strncpy(new_flag, name, name_len);
new_flag[name_len] = '\0';
Flags::Register_bool(NULL, new_flag, true, NULL);
} else {
// Only set values for recognized flags, skip collected
// unrecognized flags.
if (!flag->IsUnrecognized()) {
switch (flag->type_) {
case Flag::kBoolean: {
if (strcmp(argument, "true") == 0) {
*flag->bool_ptr_ = true;
} else if (strcmp(argument, "false") == 0) {
*flag->bool_ptr_ = false;
} else {
OS::Print("Ignoring flag: %s is a bool flag.\n", name);
}
break;
}
case Flag::kString: {
*flag->charp_ptr_ = argument == NULL ? NULL : strdup(argument);
break;
}
case Flag::kInteger: {
char* endptr = NULL;
int val = strtol(argument, &endptr, 10);
if (endptr != argument) {
*flag->int_ptr_ = val;
}
break;
}
default: {
UNREACHABLE();
break;
}
}
}
}
delete[] name;
}
static bool IsValidFlag(const char* name,
const char* prefix,
intptr_t prefix_length) {
intptr_t name_length = strlen(name);
return ((name_length > prefix_length) &&
(strncmp(name, prefix, prefix_length) == 0));
}
void Flags::ProcessCommandLineFlags(int number_of_vm_flags, char** vm_flags) {
const char* kPrefix = "--";
const intptr_t kPrefixLen = strlen(kPrefix);
int i = 0;
while ((i < number_of_vm_flags) &&
IsValidFlag(vm_flags[i], kPrefix, kPrefixLen)) {
const char* option = vm_flags[i] + kPrefixLen;
Parse(option);
i++;
}
if (!FLAG_ignore_unrecognized_flags) {
int unrecognized_count = 0;
Flag* flag = Flags::flags_;
while (flag != NULL) {
if (flag->IsUnrecognized()) {
if (unrecognized_count == 0) {
OS::PrintErr("Unrecognized flags: %s", flag->name_);
} else {
OS::PrintErr(", %s", flag->name_);
}
unrecognized_count++;
}
flag = flag->next_;
}
if (unrecognized_count > 0) {
OS::PrintErr("\n");
exit(255);
}
}
if (FLAG_print_flags) {
OS::Print("Flag settings:\n");
Flag* flag = Flags::flags_;
while (flag != NULL) {
flag->Print();
flag = flag->next_;
}
}
}
} // namespace dart
<commit_msg>Print also comments with --print_flags Review URL: http://codereview.chromium.org//8413056<commit_after>// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/flags.h"
#include "vm/assert.h"
#include "vm/os.h"
namespace dart {
DEFINE_FLAG(bool, print_flags, false, "Print flags as they are being parsed.");
DEFINE_FLAG(bool, ignore_unrecognized_flags, false,
"Ignore unrecognized flags.");
// List of registered flags.
Flag* Flags::flags_ = NULL;
class Flag {
public:
enum Type {
kBoolean,
kInteger,
kString,
kNumFlagTypes
};
Flag(const char* name, const char* comment, void* addr, Type type)
: name_(name), comment_(comment), addr_(addr), type_(type) {
}
void Print() {
if (IsUnrecognized()) {
OS::Print("%s: unrecognized\n", name_);
return;
}
switch (type_) {
case kBoolean: {
OS::Print("%s: %s (%s)\n",
name_, *this->bool_ptr_ ? "true" : "false", comment_);
break;
}
case kInteger: {
OS::Print("%s: %d (%s)\n", name_, *this->int_ptr_, comment_);
break;
}
case kString: {
if (*this->charp_ptr_ != NULL) {
OS::Print("%s: '%s' (%s)\n", name_, *this->charp_ptr_, comment_);
} else {
OS::Print("%s: (null) (%s)\n", name_, comment_);
}
break;
}
default:
UNREACHABLE();
break;
}
}
bool IsUnrecognized() const {
return (type_ == kBoolean) && (bool_ptr_ == NULL);
}
Flag* next_;
const char* name_;
const char* comment_;
union {
void* addr_;
bool* bool_ptr_;
int* int_ptr_;
charp* charp_ptr_;
};
Type type_;
};
Flag* Flags::Lookup(const char* name) {
Flag* cur = Flags::flags_;
while (cur != NULL) {
if (strcmp(cur->name_, name) == 0) {
return cur;
}
cur = cur->next_;
}
return NULL;
}
bool Flags::Register_bool(bool* addr,
const char* name,
bool default_value,
const char* comment) {
ASSERT(Lookup(name) == NULL);
Flag* flag = new Flag(name, comment, addr, Flag::kBoolean);
flag->next_ = Flags::flags_;
Flags::flags_ = flag;
return default_value;
}
int Flags::Register_int(int* addr,
const char* name,
int default_value,
const char* comment) {
ASSERT(Lookup(name) == NULL);
Flag* flag = new Flag(name, comment, addr, Flag::kInteger);
flag->next_ = Flags::flags_;
Flags::flags_ = flag;
return default_value;
}
const char* Flags::Register_charp(charp* addr,
const char* name,
const char* default_value,
const char* comment) {
ASSERT(Lookup(name) == NULL);
Flag* flag = new Flag(name, comment, addr, Flag::kString);
flag->next_ = Flags::flags_;
Flags::flags_ = flag;
return default_value;
}
static void Normalize(char* s) {
intptr_t len = strlen(s);
for (intptr_t i = 0; i < len; i++) {
if (s[i] == '-') {
s[i] = '_';
}
}
}
void Flags::Parse(const char* option) {
// Find the beginning of the option argument, if it exists.
const char* equals = option;
while ((*equals != '\0') && (*equals != '=')) {
equals++;
}
const char* argument = NULL;
// Determine if this is an option argument.
if (*equals != '=') {
// No explicit option argument. Determine if there is a "no_" prefix
// preceding the name.
const char* kNoPrefix = "no_";
const intptr_t kNoPrefixLen = strlen(kNoPrefix);
if (strncmp(option, kNoPrefix, kNoPrefixLen) == 0) {
option += kNoPrefixLen; // Skip the "no_" when looking up the name.
argument = "false";
} else {
argument = "true";
}
} else {
// The argument for the option starts right after the equals sign.
argument = equals + 1;
}
// Initialize the flag name.
intptr_t name_len = equals - option;
char* name = new char[name_len + 1];
strncpy(name, option, name_len);
name[name_len] = '\0';
Normalize(name);
Flag* flag = Flags::Lookup(name);
if (flag == NULL) {
// Collect unrecognized flags.
char* new_flag = new char[name_len + 1];
strncpy(new_flag, name, name_len);
new_flag[name_len] = '\0';
Flags::Register_bool(NULL, new_flag, true, NULL);
} else {
// Only set values for recognized flags, skip collected
// unrecognized flags.
if (!flag->IsUnrecognized()) {
switch (flag->type_) {
case Flag::kBoolean: {
if (strcmp(argument, "true") == 0) {
*flag->bool_ptr_ = true;
} else if (strcmp(argument, "false") == 0) {
*flag->bool_ptr_ = false;
} else {
OS::Print("Ignoring flag: %s is a bool flag.\n", name);
}
break;
}
case Flag::kString: {
*flag->charp_ptr_ = argument == NULL ? NULL : strdup(argument);
break;
}
case Flag::kInteger: {
char* endptr = NULL;
int val = strtol(argument, &endptr, 10);
if (endptr != argument) {
*flag->int_ptr_ = val;
}
break;
}
default: {
UNREACHABLE();
break;
}
}
}
}
delete[] name;
}
static bool IsValidFlag(const char* name,
const char* prefix,
intptr_t prefix_length) {
intptr_t name_length = strlen(name);
return ((name_length > prefix_length) &&
(strncmp(name, prefix, prefix_length) == 0));
}
void Flags::ProcessCommandLineFlags(int number_of_vm_flags, char** vm_flags) {
const char* kPrefix = "--";
const intptr_t kPrefixLen = strlen(kPrefix);
int i = 0;
while ((i < number_of_vm_flags) &&
IsValidFlag(vm_flags[i], kPrefix, kPrefixLen)) {
const char* option = vm_flags[i] + kPrefixLen;
Parse(option);
i++;
}
if (!FLAG_ignore_unrecognized_flags) {
int unrecognized_count = 0;
Flag* flag = Flags::flags_;
while (flag != NULL) {
if (flag->IsUnrecognized()) {
if (unrecognized_count == 0) {
OS::PrintErr("Unrecognized flags: %s", flag->name_);
} else {
OS::PrintErr(", %s", flag->name_);
}
unrecognized_count++;
}
flag = flag->next_;
}
if (unrecognized_count > 0) {
OS::PrintErr("\n");
exit(255);
}
}
if (FLAG_print_flags) {
OS::Print("Flag settings:\n");
Flag* flag = Flags::flags_;
while (flag != NULL) {
flag->Print();
flag = flag->next_;
}
}
}
} // namespace dart
<|endoftext|> |
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/pages.h"
#include "platform/assert.h"
#include "vm/gc_marker.h"
#include "vm/gc_sweeper.h"
#include "vm/object.h"
#include "vm/virtual_memory.h"
namespace dart {
DEFINE_FLAG(int, heap_growth_space_ratio, 10,
"The desired maximum percentage of free space after GC");
DEFINE_FLAG(int, heap_growth_time_ratio, 3,
"The desired maximum percentage of time spent in GC");
DEFINE_FLAG(int, heap_growth_rate, 4,
"The size the heap is grown, in heap pages");
HeapPage* HeapPage::Initialize(VirtualMemory* memory, bool is_executable) {
ASSERT(memory->size() > VirtualMemory::PageSize());
memory->Commit(is_executable);
HeapPage* result = reinterpret_cast<HeapPage*>(memory->address());
result->memory_ = memory;
result->next_ = NULL;
result->used_ = 0;
result->top_ = result->first_object_start();
return result;
}
HeapPage* HeapPage::Allocate(intptr_t size, bool is_executable) {
VirtualMemory* memory =
VirtualMemory::ReserveAligned(size, PageSpace::kPageAlignment);
return Initialize(memory, is_executable);
}
void HeapPage::Deallocate() {
// The memory for this object will become unavailable after the delete below.
delete memory_;
}
void HeapPage::VisitObjectPointers(ObjectPointerVisitor* visitor) const {
uword obj_addr = first_object_start();
uword end_addr = top();
while (obj_addr < end_addr) {
RawObject* raw_obj = RawObject::FromAddr(obj_addr);
obj_addr += raw_obj->VisitPointers(visitor);
}
ASSERT(obj_addr == end_addr);
}
RawObject* HeapPage::FindObject(FindObjectVisitor* visitor) const {
uword obj_addr = first_object_start();
uword end_addr = top();
while (obj_addr < end_addr) {
RawObject* raw_obj = RawObject::FromAddr(obj_addr);
if (raw_obj->FindObject(visitor)) {
return raw_obj; // Found object, return it.
}
obj_addr += raw_obj->Size();
}
ASSERT(obj_addr == end_addr);
return Object::null();
}
PageSpace::PageSpace(Heap* heap, intptr_t max_capacity, bool is_executable)
: freelist_(),
heap_(heap),
pages_(NULL),
pages_tail_(NULL),
large_pages_(NULL),
bump_page_(NULL),
max_capacity_(max_capacity),
capacity_(0),
in_use_(0),
count_(0),
is_executable_(is_executable),
sweeping_(false),
page_space_controller_(FLAG_heap_growth_space_ratio,
FLAG_heap_growth_rate,
FLAG_heap_growth_time_ratio) {
}
PageSpace::~PageSpace() {
FreePages(pages_);
FreePages(large_pages_);
}
intptr_t PageSpace::LargePageSizeFor(intptr_t size) {
intptr_t page_size = Utils::RoundUp(size + sizeof(HeapPage),
VirtualMemory::PageSize());
return page_size;
}
void PageSpace::AllocatePage() {
HeapPage* page = HeapPage::Allocate(kPageSize, is_executable_);
if (pages_ == NULL) {
pages_ = page;
} else {
pages_tail_->set_next(page);
}
pages_tail_ = page;
bump_page_ = NULL; // Reenable scanning of pages for bump allocation.
capacity_ += kPageSize;
}
HeapPage* PageSpace::AllocateLargePage(intptr_t size) {
intptr_t page_size = LargePageSizeFor(size);
HeapPage* page = HeapPage::Allocate(page_size, is_executable_);
page->set_next(large_pages_);
large_pages_ = page;
capacity_ += page_size;
return page;
}
void PageSpace::FreePage(HeapPage* page, HeapPage* previous_page) {
capacity_ -= page->memory_->size();
// Remove the page from the list.
if (previous_page != NULL) {
previous_page->set_next(page->next());
} else {
pages_ = page->next();
}
if (page == pages_tail_) {
pages_tail_ = previous_page;
}
// TODO(iposva): Consider adding to a pool of empty pages.
page->Deallocate();
}
void PageSpace::FreeLargePage(HeapPage* page, HeapPage* previous_page) {
capacity_ -= page->memory_->size();
// Remove the page from the list.
if (previous_page != NULL) {
previous_page->set_next(page->next());
} else {
large_pages_ = page->next();
}
page->Deallocate();
}
void PageSpace::FreePages(HeapPage* pages) {
HeapPage* page = pages;
while (page != NULL) {
HeapPage* next = page->next();
page->Deallocate();
page = next;
}
}
uword PageSpace::TryBumpAllocate(intptr_t size) {
if (pages_tail_ == NULL) {
return 0;
}
uword result = pages_tail_->TryBumpAllocate(size);
if (result != 0) {
return result;
}
if (bump_page_ == NULL) {
// The bump page has not yet been used: Start at the beginning of the list.
bump_page_ = pages_;
}
// The last page has already been attempted above.
while (bump_page_ != pages_tail_) {
ASSERT(bump_page_->next() != NULL);
result = bump_page_->TryBumpAllocate(size);
if (result != 0) {
return result;
}
bump_page_ = bump_page_->next();
}
// Ran through all of the pages trying to bump allocate: Give up.
return 0;
}
uword PageSpace::TryAllocate(intptr_t size) {
ASSERT(size >= kObjectAlignment);
ASSERT(Utils::IsAligned(size, kObjectAlignment));
uword result = 0;
if (size < kAllocatablePageSize) {
result = TryBumpAllocate(size);
if (result == 0) {
result = freelist_.TryAllocate(size);
if ((result == 0) &&
page_space_controller_.CanGrowPageSpace(size) &&
CanIncreaseCapacity(kPageSize)) {
AllocatePage();
result = TryBumpAllocate(size);
ASSERT(result != 0);
}
}
} else {
// Large page allocation.
intptr_t page_size = LargePageSizeFor(size);
if (page_size < size) {
// On overflow we fail to allocate.
return 0;
}
if (CanIncreaseCapacity(page_size)) {
HeapPage* page = AllocateLargePage(size);
if (page != NULL) {
result = page->top();
page->set_top(result + size);
}
}
}
if (result != 0) {
in_use_ += size;
}
return result;
}
bool PageSpace::Contains(uword addr) const {
HeapPage* page = pages_;
while (page != NULL) {
if (page->Contains(addr)) {
return true;
}
page = page->next();
}
page = large_pages_;
while (page != NULL) {
if (page->Contains(addr)) {
return true;
}
page = page->next();
}
return false;
}
void PageSpace::VisitObjectPointers(ObjectPointerVisitor* visitor) const {
HeapPage* page = pages_;
while (page != NULL) {
page->VisitObjectPointers(visitor);
page = page->next();
}
page = large_pages_;
while (page != NULL) {
page->VisitObjectPointers(visitor);
page = page->next();
}
}
RawObject* PageSpace::FindObject(FindObjectVisitor* visitor) const {
ASSERT(Isolate::Current()->no_gc_scope_depth() != 0);
HeapPage* page = pages_;
while (page != NULL) {
RawObject* obj = page->FindObject(visitor);
if (obj != Object::null()) {
return obj;
}
page = page->next();
}
page = large_pages_;
while (page != NULL) {
RawObject* obj = page->FindObject(visitor);
if (obj != Object::null()) {
return obj;
}
page = page->next();
}
return Object::null();
}
void PageSpace::MarkSweep(bool invoke_api_callbacks) {
// MarkSweep is not reentrant. Make sure that is the case.
ASSERT(!sweeping_);
sweeping_ = true;
Isolate* isolate = Isolate::Current();
NoHandleScope no_handles(isolate);
if (FLAG_verify_before_gc) {
OS::PrintErr("Verifying before MarkSweep... ");
heap_->Verify();
OS::PrintErr(" done.\n");
}
Timer timer(true, "MarkSweep");
timer.Start();
int64_t start = OS::GetCurrentTimeMillis();
// Mark all reachable old-gen objects.
GCMarker marker(heap_);
marker.MarkObjects(isolate, this, invoke_api_callbacks);
// Reset the bump allocation page to unused.
bump_page_ = NULL;
// Reset the freelists and setup sweeping.
freelist_.Reset();
GCSweeper sweeper(heap_);
intptr_t in_use = 0;
HeapPage* prev_page = NULL;
HeapPage* page = pages_;
while (page != NULL) {
intptr_t page_in_use = sweeper.SweepPage(page, &freelist_);
HeapPage* next_page = page->next();
if (page_in_use == 0) {
FreePage(page, prev_page);
} else {
in_use += page_in_use;
prev_page = page;
}
// Advance to the next page.
page = next_page;
}
prev_page = NULL;
page = large_pages_;
while (page != NULL) {
intptr_t page_in_use = sweeper.SweepLargePage(page);
HeapPage* next_page = page->next();
if (page_in_use == 0) {
FreeLargePage(page, prev_page);
} else {
in_use += page_in_use;
prev_page = page;
}
// Advance to the next page.
page = next_page;
}
// Record data and print if requested.
intptr_t in_use_before = in_use_;
in_use_ = in_use;
timer.Stop();
// Record signals for growth control.
int64_t elapsed = timer.TotalElapsedTime() * kMicrosecondsPerMillisecond;
page_space_controller_.EvaluateGarbageCollection(in_use_before, in_use,
start, start + elapsed);
if (FLAG_verbose_gc) {
const intptr_t KB2 = KB / 2;
OS::PrintErr("Mark-Sweep[%d]: %lldus (%dK -> %dK, %dK)\n",
count_,
timer.TotalElapsedTime(),
(in_use_before + (KB2)) / KB,
(in_use + (KB2)) / KB,
(capacity_ + KB2) / KB);
}
if (FLAG_verify_after_gc) {
OS::PrintErr("Verifying after MarkSweep... ");
heap_->Verify();
OS::PrintErr(" done.\n");
}
count_++;
// Done, reset the marker.
ASSERT(sweeping_);
sweeping_ = false;
}
PageSpaceController::PageSpaceController(int heap_growth_ratio,
int heap_growth_rate,
int garbage_collection_time_ratio)
: is_enabled_(false),
grow_heap_(heap_growth_rate),
heap_growth_ratio_(heap_growth_ratio),
heap_growth_rate_(heap_growth_rate),
garbage_collection_time_ratio_(garbage_collection_time_ratio) {
}
PageSpaceController::~PageSpaceController() {}
bool PageSpaceController::CanGrowPageSpace(intptr_t size_in_bytes) {
size_in_bytes = Utils::RoundUp(size_in_bytes, PageSpace::kPageSize);
intptr_t size_in_pages = size_in_bytes / PageSpace::kPageSize;
if (!is_enabled_) {
return true;
}
if (heap_growth_ratio_ == 100) {
return true;
}
if (grow_heap_ <= 0) {
return false;
}
grow_heap_ -= size_in_pages;
return true;
}
void PageSpaceController::EvaluateGarbageCollection(
size_t in_use_before, size_t in_use_after, int64_t start, int64_t end) {
ASSERT(in_use_before >= in_use_after);
ASSERT(end >= start);
history_.AddGarbageCollectionTime(start, end);
int collected_garbage_ratio =
static_cast<int>((static_cast<double>(in_use_before - in_use_after) /
static_cast<double>(in_use_before)) * 100);
if ((collected_garbage_ratio > heap_growth_ratio_) &&
(history_.GarbageCollectionTimeFraction() <
garbage_collection_time_ratio_)) {
grow_heap_ = 0;
} else {
grow_heap_ = heap_growth_rate_;
}
}
PageSpaceGarbageCollectionHistory::PageSpaceGarbageCollectionHistory()
: index_(0) {
for (uint32_t i = 0; i < kHistoryLength; i++) {
start_[i] = 0;
end_[i] = 0;
}
}
void PageSpaceGarbageCollectionHistory::
AddGarbageCollectionTime(uint64_t start, uint64_t end) {
int index = index_ % kHistoryLength;
start_[index] = start;
end_[index] = end;
index_++;
}
int PageSpaceGarbageCollectionHistory::GarbageCollectionTimeFraction() {
int current;
int previous;
uint64_t gc_time = 0;
uint64_t total_time = 0;
for (uint32_t i = 1; i < kHistoryLength; i++) {
current = (index_ - i) % kHistoryLength;
previous = (index_ - 1 - i) % kHistoryLength;
if (end_[previous] == 0) {
break;
}
// iterate over the circular buffer in reverse order
gc_time += end_[current] - start_[current];
total_time += end_[current] - end_[previous];
}
if (total_time == 0) {
return 0;
} else {
return static_cast<int>((static_cast<double>(gc_time) /
static_cast<double>(total_time))*100);
}
}
} // namespace dart
<commit_msg>Ignore the growth policy when fragmentation prevents allocation.<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/pages.h"
#include "platform/assert.h"
#include "vm/gc_marker.h"
#include "vm/gc_sweeper.h"
#include "vm/object.h"
#include "vm/virtual_memory.h"
namespace dart {
DEFINE_FLAG(int, heap_growth_space_ratio, 10,
"The desired maximum percentage of free space after GC");
DEFINE_FLAG(int, heap_growth_time_ratio, 3,
"The desired maximum percentage of time spent in GC");
DEFINE_FLAG(int, heap_growth_rate, 4,
"The size the heap is grown, in heap pages");
HeapPage* HeapPage::Initialize(VirtualMemory* memory, bool is_executable) {
ASSERT(memory->size() > VirtualMemory::PageSize());
memory->Commit(is_executable);
HeapPage* result = reinterpret_cast<HeapPage*>(memory->address());
result->memory_ = memory;
result->next_ = NULL;
result->used_ = 0;
result->top_ = result->first_object_start();
return result;
}
HeapPage* HeapPage::Allocate(intptr_t size, bool is_executable) {
VirtualMemory* memory =
VirtualMemory::ReserveAligned(size, PageSpace::kPageAlignment);
return Initialize(memory, is_executable);
}
void HeapPage::Deallocate() {
// The memory for this object will become unavailable after the delete below.
delete memory_;
}
void HeapPage::VisitObjectPointers(ObjectPointerVisitor* visitor) const {
uword obj_addr = first_object_start();
uword end_addr = top();
while (obj_addr < end_addr) {
RawObject* raw_obj = RawObject::FromAddr(obj_addr);
obj_addr += raw_obj->VisitPointers(visitor);
}
ASSERT(obj_addr == end_addr);
}
RawObject* HeapPage::FindObject(FindObjectVisitor* visitor) const {
uword obj_addr = first_object_start();
uword end_addr = top();
while (obj_addr < end_addr) {
RawObject* raw_obj = RawObject::FromAddr(obj_addr);
if (raw_obj->FindObject(visitor)) {
return raw_obj; // Found object, return it.
}
obj_addr += raw_obj->Size();
}
ASSERT(obj_addr == end_addr);
return Object::null();
}
PageSpace::PageSpace(Heap* heap, intptr_t max_capacity, bool is_executable)
: freelist_(),
heap_(heap),
pages_(NULL),
pages_tail_(NULL),
large_pages_(NULL),
bump_page_(NULL),
max_capacity_(max_capacity),
capacity_(0),
in_use_(0),
count_(0),
is_executable_(is_executable),
sweeping_(false),
page_space_controller_(FLAG_heap_growth_space_ratio,
FLAG_heap_growth_rate,
FLAG_heap_growth_time_ratio) {
}
PageSpace::~PageSpace() {
FreePages(pages_);
FreePages(large_pages_);
}
intptr_t PageSpace::LargePageSizeFor(intptr_t size) {
intptr_t page_size = Utils::RoundUp(size + sizeof(HeapPage),
VirtualMemory::PageSize());
return page_size;
}
void PageSpace::AllocatePage() {
HeapPage* page = HeapPage::Allocate(kPageSize, is_executable_);
if (pages_ == NULL) {
pages_ = page;
} else {
pages_tail_->set_next(page);
}
pages_tail_ = page;
bump_page_ = NULL; // Reenable scanning of pages for bump allocation.
capacity_ += kPageSize;
}
HeapPage* PageSpace::AllocateLargePage(intptr_t size) {
intptr_t page_size = LargePageSizeFor(size);
HeapPage* page = HeapPage::Allocate(page_size, is_executable_);
page->set_next(large_pages_);
large_pages_ = page;
capacity_ += page_size;
return page;
}
void PageSpace::FreePage(HeapPage* page, HeapPage* previous_page) {
capacity_ -= page->memory_->size();
// Remove the page from the list.
if (previous_page != NULL) {
previous_page->set_next(page->next());
} else {
pages_ = page->next();
}
if (page == pages_tail_) {
pages_tail_ = previous_page;
}
// TODO(iposva): Consider adding to a pool of empty pages.
page->Deallocate();
}
void PageSpace::FreeLargePage(HeapPage* page, HeapPage* previous_page) {
capacity_ -= page->memory_->size();
// Remove the page from the list.
if (previous_page != NULL) {
previous_page->set_next(page->next());
} else {
large_pages_ = page->next();
}
page->Deallocate();
}
void PageSpace::FreePages(HeapPage* pages) {
HeapPage* page = pages;
while (page != NULL) {
HeapPage* next = page->next();
page->Deallocate();
page = next;
}
}
uword PageSpace::TryBumpAllocate(intptr_t size) {
if (pages_tail_ == NULL) {
return 0;
}
uword result = pages_tail_->TryBumpAllocate(size);
if (result != 0) {
return result;
}
if (bump_page_ == NULL) {
// The bump page has not yet been used: Start at the beginning of the list.
bump_page_ = pages_;
}
// The last page has already been attempted above.
while (bump_page_ != pages_tail_) {
ASSERT(bump_page_->next() != NULL);
result = bump_page_->TryBumpAllocate(size);
if (result != 0) {
return result;
}
bump_page_ = bump_page_->next();
}
// Ran through all of the pages trying to bump allocate: Give up.
return 0;
}
uword PageSpace::TryAllocate(intptr_t size) {
ASSERT(size >= kObjectAlignment);
ASSERT(Utils::IsAligned(size, kObjectAlignment));
uword result = 0;
if (size < kAllocatablePageSize) {
result = TryBumpAllocate(size);
if (result == 0) {
result = freelist_.TryAllocate(size);
if ((result == 0) &&
(page_space_controller_.CanGrowPageSpace(size) ||
(size < (capacity() - in_use()))) && // Fragmentation
CanIncreaseCapacity(kPageSize)) {
AllocatePage();
result = TryBumpAllocate(size);
ASSERT(result != 0);
}
}
} else {
// Large page allocation.
intptr_t page_size = LargePageSizeFor(size);
if (page_size < size) {
// On overflow we fail to allocate.
return 0;
}
if (CanIncreaseCapacity(page_size)) {
HeapPage* page = AllocateLargePage(size);
if (page != NULL) {
result = page->top();
page->set_top(result + size);
}
}
}
if (result != 0) {
in_use_ += size;
}
return result;
}
bool PageSpace::Contains(uword addr) const {
HeapPage* page = pages_;
while (page != NULL) {
if (page->Contains(addr)) {
return true;
}
page = page->next();
}
page = large_pages_;
while (page != NULL) {
if (page->Contains(addr)) {
return true;
}
page = page->next();
}
return false;
}
void PageSpace::VisitObjectPointers(ObjectPointerVisitor* visitor) const {
HeapPage* page = pages_;
while (page != NULL) {
page->VisitObjectPointers(visitor);
page = page->next();
}
page = large_pages_;
while (page != NULL) {
page->VisitObjectPointers(visitor);
page = page->next();
}
}
RawObject* PageSpace::FindObject(FindObjectVisitor* visitor) const {
ASSERT(Isolate::Current()->no_gc_scope_depth() != 0);
HeapPage* page = pages_;
while (page != NULL) {
RawObject* obj = page->FindObject(visitor);
if (obj != Object::null()) {
return obj;
}
page = page->next();
}
page = large_pages_;
while (page != NULL) {
RawObject* obj = page->FindObject(visitor);
if (obj != Object::null()) {
return obj;
}
page = page->next();
}
return Object::null();
}
void PageSpace::MarkSweep(bool invoke_api_callbacks) {
// MarkSweep is not reentrant. Make sure that is the case.
ASSERT(!sweeping_);
sweeping_ = true;
Isolate* isolate = Isolate::Current();
NoHandleScope no_handles(isolate);
if (FLAG_verify_before_gc) {
OS::PrintErr("Verifying before MarkSweep... ");
heap_->Verify();
OS::PrintErr(" done.\n");
}
Timer timer(true, "MarkSweep");
timer.Start();
int64_t start = OS::GetCurrentTimeMillis();
// Mark all reachable old-gen objects.
GCMarker marker(heap_);
marker.MarkObjects(isolate, this, invoke_api_callbacks);
// Reset the bump allocation page to unused.
bump_page_ = NULL;
// Reset the freelists and setup sweeping.
freelist_.Reset();
GCSweeper sweeper(heap_);
intptr_t in_use = 0;
HeapPage* prev_page = NULL;
HeapPage* page = pages_;
while (page != NULL) {
intptr_t page_in_use = sweeper.SweepPage(page, &freelist_);
HeapPage* next_page = page->next();
if (page_in_use == 0) {
FreePage(page, prev_page);
} else {
in_use += page_in_use;
prev_page = page;
}
// Advance to the next page.
page = next_page;
}
prev_page = NULL;
page = large_pages_;
while (page != NULL) {
intptr_t page_in_use = sweeper.SweepLargePage(page);
HeapPage* next_page = page->next();
if (page_in_use == 0) {
FreeLargePage(page, prev_page);
} else {
in_use += page_in_use;
prev_page = page;
}
// Advance to the next page.
page = next_page;
}
// Record data and print if requested.
intptr_t in_use_before = in_use_;
in_use_ = in_use;
timer.Stop();
// Record signals for growth control.
int64_t elapsed = timer.TotalElapsedTime() * kMicrosecondsPerMillisecond;
page_space_controller_.EvaluateGarbageCollection(in_use_before, in_use,
start, start + elapsed);
if (FLAG_verbose_gc) {
const intptr_t KB2 = KB / 2;
OS::PrintErr("Mark-Sweep[%d]: %lldus (%dK -> %dK, %dK)\n",
count_,
timer.TotalElapsedTime(),
(in_use_before + (KB2)) / KB,
(in_use + (KB2)) / KB,
(capacity_ + KB2) / KB);
}
if (FLAG_verify_after_gc) {
OS::PrintErr("Verifying after MarkSweep... ");
heap_->Verify();
OS::PrintErr(" done.\n");
}
count_++;
// Done, reset the marker.
ASSERT(sweeping_);
sweeping_ = false;
}
PageSpaceController::PageSpaceController(int heap_growth_ratio,
int heap_growth_rate,
int garbage_collection_time_ratio)
: is_enabled_(false),
grow_heap_(heap_growth_rate),
heap_growth_ratio_(heap_growth_ratio),
heap_growth_rate_(heap_growth_rate),
garbage_collection_time_ratio_(garbage_collection_time_ratio) {
}
PageSpaceController::~PageSpaceController() {}
bool PageSpaceController::CanGrowPageSpace(intptr_t size_in_bytes) {
size_in_bytes = Utils::RoundUp(size_in_bytes, PageSpace::kPageSize);
intptr_t size_in_pages = size_in_bytes / PageSpace::kPageSize;
if (!is_enabled_) {
return true;
}
if (heap_growth_ratio_ == 100) {
return true;
}
if (grow_heap_ <= 0) {
return false;
}
grow_heap_ -= size_in_pages;
return true;
}
void PageSpaceController::EvaluateGarbageCollection(
size_t in_use_before, size_t in_use_after, int64_t start, int64_t end) {
ASSERT(in_use_before >= in_use_after);
ASSERT(end >= start);
history_.AddGarbageCollectionTime(start, end);
int collected_garbage_ratio =
static_cast<int>((static_cast<double>(in_use_before - in_use_after) /
static_cast<double>(in_use_before)) * 100);
if ((collected_garbage_ratio > heap_growth_ratio_) &&
(history_.GarbageCollectionTimeFraction() <
garbage_collection_time_ratio_)) {
grow_heap_ = 0;
} else {
grow_heap_ = heap_growth_rate_;
}
}
PageSpaceGarbageCollectionHistory::PageSpaceGarbageCollectionHistory()
: index_(0) {
for (uint32_t i = 0; i < kHistoryLength; i++) {
start_[i] = 0;
end_[i] = 0;
}
}
void PageSpaceGarbageCollectionHistory::
AddGarbageCollectionTime(uint64_t start, uint64_t end) {
int index = index_ % kHistoryLength;
start_[index] = start;
end_[index] = end;
index_++;
}
int PageSpaceGarbageCollectionHistory::GarbageCollectionTimeFraction() {
int current;
int previous;
uint64_t gc_time = 0;
uint64_t total_time = 0;
for (uint32_t i = 1; i < kHistoryLength; i++) {
current = (index_ - i) % kHistoryLength;
previous = (index_ - 1 - i) % kHistoryLength;
if (end_[previous] == 0) {
break;
}
// iterate over the circular buffer in reverse order
gc_time += end_[current] - start_[current];
total_time += end_[current] - end_[previous];
}
if (total_time == 0) {
return 0;
} else {
return static_cast<int>((static_cast<double>(gc_time) /
static_cast<double>(total_time))*100);
}
}
} // namespace dart
<|endoftext|> |
<commit_before>/// PROJECT
#include <csapex/model/node.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_modifier.h>
#include <csapex/msg/dynamic_input.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/msg/generic_vector_message.hpp>
namespace csapex
{
class VectorMerge : public Node
{
public:
VectorMerge()
{}
void setup(csapex::NodeModifier& node_modifier)
{
output = node_modifier.addOutput<connection_types::GenericVectorMessage>("merged vector");
updateInputs();
}
void setupParameters(Parameterizable& parameters)
{
parameters.addParameter(csapex::param::ParameterFactory::declareRange("input count", 2, 10, 2, 1), std::bind(&VectorMerge::updateInputs, this));
}
void process()
{
// TODO: implement variadic io
connection_types::GenericVectorMessage::Ptr result;
bool first = true;
std::vector<Input*> inputs = node_modifier_->getMessageInputs();
for(std::size_t i = 0 ; i < inputs.size() ; i++) {
Input *in = inputs[i];
if(msg::hasMessage(in)) {
connection_types::GenericVectorMessage::ConstPtr msg;
if(first) {
result = msg::getClonedMessage<connection_types::GenericVectorMessage>(in);
first = false;
} else {
msg= msg::getMessage<connection_types::GenericVectorMessage>(in);
for(std::size_t i = 0, total = msg->nestedValueCount(); i < total; ++i) {
result->addNestedValue(msg->nestedValue(i));
}
}
}
}
if(result) {
msg::publish(output, result);
}
}
void updateInputs()
{
int input_count = readParameter<int>("input count");
std::vector<Input*> inputs = node_modifier_->getMessageInputs();
int current_amount = inputs.size();
if(current_amount > input_count) {
for(int i = current_amount; i > input_count ; i--) {
Input* in = inputs[i - 1];
if(msg::isConnected(in)) {
msg::disable(in);
} else {
node_modifier_->removeInput(msg::getUUID(in));
}
}
} else {
int to_add = input_count - current_amount;
for(int i = 0 ; i < current_amount; i++) {
msg::enable(inputs[i]);
}
for(int i = 0 ; i < to_add ; i++) {
node_modifier_->addOptionalInput<connection_types::GenericVectorMessage>("Vector");
}
}
}
private:
Output* output;
};
}
CSAPEX_REGISTER_CLASS(csapex::VectorMerge, csapex::Node)
<commit_msg>reimplemented vector merge using variadic io<commit_after>/// PROJECT
#include <csapex/model/node.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/model/node_modifier.h>
#include <csapex/model/variadic_io.h>
#include <csapex/msg/io.h>
#include <csapex/msg/generic_vector_message.hpp>
namespace csapex
{
class VectorMerge : public Node, public VariadicInputs
{
public:
VectorMerge()
{}
void setup(csapex::NodeModifier& node_modifier)
{
setupVariadic(node_modifier);
output = node_modifier.addOutput<connection_types::GenericVectorMessage>("merged vector");
}
void setupParameters(Parameterizable& parameters)
{
setupVariadicParameters(parameters);
}
void process()
{
connection_types::GenericVectorMessage::Ptr result;
bool first = true;
std::vector<Input*> inputs = node_modifier_->getMessageInputs();
for(std::size_t i = 0 ; i < inputs.size() ; i++) {
Input *in = inputs[i];
if(msg::hasMessage(in)) {
connection_types::GenericVectorMessage::ConstPtr msg;
if(first) {
result = msg::getClonedMessage<connection_types::GenericVectorMessage>(in);
first = false;
} else {
msg = msg::getMessage<connection_types::GenericVectorMessage>(in);
for(std::size_t j = 0, total = msg->nestedValueCount(); j < total; ++j) {
result->addNestedValue(msg->nestedValue(j));
}
}
}
}
if(result) {
msg::publish(output, result);
}
}
virtual csapex::Input* createVariadicInput(csapex::TokenDataConstPtr type, const std::string& label, bool optional) override
{
return VariadicInputs::createVariadicInput(connection_types::makeEmpty<connection_types::GenericVectorMessage>(), label.empty() ? "Vector" : label, getVariadicInputCount() == 0 ? false : true);
}
private:
Output* output;
};
}
CSAPEX_REGISTER_CLASS(csapex::VectorMerge, csapex::Node)
<|endoftext|> |
<commit_before>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "provider-plugin-process.h"
#include "add-account-page.h"
#include "account-settings-page.h"
#include "generic-account-setup-context.h"
#include "provider-plugin-process-priv.h"
#include "accountsmanagersingleton.h"
#include <Accounts/Account>
#include <Accounts/Manager>
#include <MComponentCache>
#include <MApplication>
#include <MApplicationWindow>
#include <QDebug>
#include <QFile>
#include <QLocalSocket>
#include <QProcess>
#include <QTimer>
namespace AccountsUI {
static ProviderPluginProcess *plugin_instance = 0;
AbstractAccountSetupContext *ProviderPluginProcessPrivate::context() const
{
if (!m_context) {
SetupType setupType;
switch (wrapped->setupType()) {
case AccountSetup::CreateNew:
setupType = CreateNew;
break;
case AccountSetup::EditExisting:
setupType = EditExisting;
break;
default:
qWarning() << "Setup type not recognized:" << wrapped->setupType();
return 0;
}
m_context = q_ptr->accountSetupContext(account, setupType, q_ptr);
m_context->setServiceType(wrapped->serviceType());
}
return m_context;
}
void ProviderPluginProcessPrivate::executeCommandFromXML(const QDomDocument
&document)
{
QDomElement root = document.documentElement();
QDomElement handler = root.firstChildElement("handler");
if (!handler.isNull()) {
QString type = handler.attribute("type");
if (type == "command") {
/* Syntax for the service file:
*
* <handler type="command">/usr/bin/appname [args]...</handler>
*/
QString command = handler.text();
qDebug() << "Executing" << command;
/* The account plugin process is going to die very soon; the
* handler must be started as a detached process, for it to
* continue to live. */
bool ok = QProcess::startDetached(command);
if (!ok)
qWarning() << "Could not execute:" << command;
}
/* support more types (e.g., D-Bus services) here */
}
}
void ProviderPluginProcessPrivate::serviceEnabled(Accounts::Service *service)
{
qDebug() << Q_FUNC_INFO << service->name();
executeCommandFromXML(service->domDocument());
// Commands might be specified in service-type files too
Accounts::Manager *manager = account->manager();
Accounts::ServiceType *serviceType =
manager->serviceType(service->serviceType());
if (serviceType != 0)
executeCommandFromXML(serviceType->domDocument());
}
void ProviderPluginProcessPrivate::accountSaved()
{
qDebug() << Q_FUNC_INFO;
account->selectService();
if (account->enabled()) {
/* Go through the enabled services and run the activation command, if
* present */
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled() && !enabledServices.contains(service))
serviceEnabled(service);
}
}
}
void ProviderPluginProcessPrivate::monitorServices()
{
connect(account, SIGNAL(synced()), this, SLOT(accountSaved()));
/* If we are editing an account, get the list of services initially
* enabled, to avoid starting up their handlers for no reason */
account->selectService();
if (wrapped->setupType() == AccountSetup::EditExisting &&
account->enabled()) {
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled())
enabledServices.append(service);
}
}
}
ProviderPluginProcess::ProviderPluginProcess(AccountPluginInterface *plugin,
int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(plugin, argc, argv))
{
init(argc, argv);
}
ProviderPluginProcess::ProviderPluginProcess(int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(argc, argv))
{
init(argc, argv);
}
void ProviderPluginProcess::init(int &argc, char **argv)
{
Q_UNUSED(argc);
Q_UNUSED(argv);
Q_D(ProviderPluginProcess);
d->q_ptr = this;
if (plugin_instance != 0)
qWarning() << "ProviderPluginProcess already instantiated";
plugin_instance = this;
}
ProviderPluginProcess::~ProviderPluginProcess()
{
Q_D(ProviderPluginProcess);
delete d;
}
ProviderPluginProcess *ProviderPluginProcess::instance()
{
return plugin_instance;
}
MApplicationPage * ProviderPluginProcess::mainPage()
{
Q_D(ProviderPluginProcess);
AbstractAccountSetupContext *context = d->context();
if (context->setupType() == CreateNew)
return new AddAccountPage(context);
if (context->setupType() == EditExisting)
return new AccountSettingsPage(context);
/* we should never come to this point */
Q_ASSERT(false);
return 0;
}
int ProviderPluginProcess::exec()
{
Q_D(ProviderPluginProcess);
/* if we the account is invalid (either because it does not exists or
* couldn't be loaded because of some DB error), return immediately */
if (d->account == 0) {
qWarning() << Q_FUNC_INFO << "account() is NULL";
return 1;
}
d->window->show();
MApplicationPage *page = mainPage();
if (page == 0) {
qWarning() << Q_FUNC_INFO << "The mainPage() returned 0";
return 1;
}
page->appear(d->window);
int result = d->application->exec();
return result;
}
void ProviderPluginProcess::quit()
{
Q_D(ProviderPluginProcess);
QTimer::singleShot(200, d->wrapped, SLOT(quit()));
}
AbstractAccountSetupContext *ProviderPluginProcess::setupContext() const
{
Q_D(const ProviderPluginProcess);
return d->context();
}
AbstractAccountSetupContext *ProviderPluginProcess::accountSetupContext(
Accounts::Account *account,
SetupType type,
QObject *parent)
{
return new GenericAccountSetupContext(account, type, parent);
}
void ProviderPluginProcess::setReturnToApp(bool returnToApp)
{
Q_D(ProviderPluginProcess);
d->returnToApp = returnToApp;
}
void ProviderPluginProcess::setReturnToAccountsList(bool value)
{
Q_D(ProviderPluginProcess);
d->wrapped->setReturnToAccountsList(value);
}
void ProviderPluginProcess::setExitData(const QVariant &data)
{
Q_D(ProviderPluginProcess);
d->wrapped->setExitData(data);
}
const LastPageActions &ProviderPluginProcess::lastPageActions() const
{
Q_D(const ProviderPluginProcess);
return d->lastPageActions;
}
QString ProviderPluginProcess::translatedProviderName() const
{
Q_D(const ProviderPluginProcess);
if (!(d->translatedProviderName .isEmpty()))
return d->translatedProviderName;
QString providerName(d->account->providerName());
QString providerIconId;
Accounts::Provider *provider =
AccountsManager::instance()->provider(providerName);
if (provider) {
providerIconId = provider->iconName();
QString catalog = provider->trCatalog();
MLocale locale;
if (!catalog.isEmpty() && !locale.isInstalledTrCatalog(catalog)) {
locale.installTrCatalog(catalog);
MLocale::setDefault(locale);
}
}
d->translatedProviderName = qtTrId(provider->displayName().toLatin1());
if (!(d->translatedProviderName .isEmpty()))
return d->translatedProviderName;
else if (!providerName.isEmpty())
return providerName;
else
return "";
}
} // namespace
<commit_msg>Fixing the delay<commit_after>/*
* This file is part of accounts-ui
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "provider-plugin-process.h"
#include "add-account-page.h"
#include "account-settings-page.h"
#include "generic-account-setup-context.h"
#include "provider-plugin-process-priv.h"
#include "accountsmanagersingleton.h"
#include <Accounts/Account>
#include <Accounts/Manager>
#include <MComponentCache>
#include <MApplication>
#include <MApplicationWindow>
#include <QDebug>
#include <QFile>
#include <QLocalSocket>
#include <QProcess>
#include <QTimer>
namespace AccountsUI {
static ProviderPluginProcess *plugin_instance = 0;
AbstractAccountSetupContext *ProviderPluginProcessPrivate::context() const
{
if (!m_context) {
SetupType setupType;
switch (wrapped->setupType()) {
case AccountSetup::CreateNew:
setupType = CreateNew;
break;
case AccountSetup::EditExisting:
setupType = EditExisting;
break;
default:
qWarning() << "Setup type not recognized:" << wrapped->setupType();
return 0;
}
m_context = q_ptr->accountSetupContext(account, setupType, q_ptr);
m_context->setServiceType(wrapped->serviceType());
}
return m_context;
}
void ProviderPluginProcessPrivate::executeCommandFromXML(const QDomDocument
&document)
{
QDomElement root = document.documentElement();
QDomElement handler = root.firstChildElement("handler");
if (!handler.isNull()) {
QString type = handler.attribute("type");
if (type == "command") {
/* Syntax for the service file:
*
* <handler type="command">/usr/bin/appname [args]...</handler>
*/
QString command = handler.text();
qDebug() << "Executing" << command;
/* The account plugin process is going to die very soon; the
* handler must be started as a detached process, for it to
* continue to live. */
bool ok = QProcess::startDetached(command);
if (!ok)
qWarning() << "Could not execute:" << command;
}
/* support more types (e.g., D-Bus services) here */
}
}
void ProviderPluginProcessPrivate::serviceEnabled(Accounts::Service *service)
{
qDebug() << Q_FUNC_INFO << service->name();
executeCommandFromXML(service->domDocument());
// Commands might be specified in service-type files too
Accounts::Manager *manager = account->manager();
Accounts::ServiceType *serviceType =
manager->serviceType(service->serviceType());
if (serviceType != 0)
executeCommandFromXML(serviceType->domDocument());
}
void ProviderPluginProcessPrivate::accountSaved()
{
qDebug() << Q_FUNC_INFO;
account->selectService();
if (account->enabled()) {
/* Go through the enabled services and run the activation command, if
* present */
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled() && !enabledServices.contains(service))
serviceEnabled(service);
}
}
}
void ProviderPluginProcessPrivate::monitorServices()
{
connect(account, SIGNAL(synced()), this, SLOT(accountSaved()));
/* If we are editing an account, get the list of services initially
* enabled, to avoid starting up their handlers for no reason */
account->selectService();
if (wrapped->setupType() == AccountSetup::EditExisting &&
account->enabled()) {
foreach (Accounts::Service *service, account->services()) {
account->selectService(service);
if (account->enabled())
enabledServices.append(service);
}
}
}
ProviderPluginProcess::ProviderPluginProcess(AccountPluginInterface *plugin,
int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(plugin, argc, argv))
{
init(argc, argv);
}
ProviderPluginProcess::ProviderPluginProcess(int &argc, char **argv)
: d_ptr(new ProviderPluginProcessPrivate(argc, argv))
{
init(argc, argv);
}
void ProviderPluginProcess::init(int &argc, char **argv)
{
Q_UNUSED(argc);
Q_UNUSED(argv);
Q_D(ProviderPluginProcess);
d->q_ptr = this;
if (plugin_instance != 0)
qWarning() << "ProviderPluginProcess already instantiated";
plugin_instance = this;
}
ProviderPluginProcess::~ProviderPluginProcess()
{
Q_D(ProviderPluginProcess);
delete d;
}
ProviderPluginProcess *ProviderPluginProcess::instance()
{
return plugin_instance;
}
MApplicationPage * ProviderPluginProcess::mainPage()
{
Q_D(ProviderPluginProcess);
AbstractAccountSetupContext *context = d->context();
if (context->setupType() == CreateNew)
return new AddAccountPage(context);
if (context->setupType() == EditExisting)
return new AccountSettingsPage(context);
/* we should never come to this point */
Q_ASSERT(false);
return 0;
}
int ProviderPluginProcess::exec()
{
Q_D(ProviderPluginProcess);
/* if we the account is invalid (either because it does not exists or
* couldn't be loaded because of some DB error), return immediately */
if (d->account == 0) {
qWarning() << Q_FUNC_INFO << "account() is NULL";
return 1;
}
d->window->show();
MApplicationPage *page = mainPage();
if (page == 0) {
qWarning() << Q_FUNC_INFO << "The mainPage() returned 0";
return 1;
}
page->appear(d->window);
int result = d->application->exec();
return result;
}
void ProviderPluginProcess::quit()
{
Q_D(ProviderPluginProcess);
QTimer::singleShot(500, d->wrapped, SLOT(quit()));
}
AbstractAccountSetupContext *ProviderPluginProcess::setupContext() const
{
Q_D(const ProviderPluginProcess);
return d->context();
}
AbstractAccountSetupContext *ProviderPluginProcess::accountSetupContext(
Accounts::Account *account,
SetupType type,
QObject *parent)
{
return new GenericAccountSetupContext(account, type, parent);
}
void ProviderPluginProcess::setReturnToApp(bool returnToApp)
{
Q_D(ProviderPluginProcess);
d->returnToApp = returnToApp;
}
void ProviderPluginProcess::setReturnToAccountsList(bool value)
{
Q_D(ProviderPluginProcess);
d->wrapped->setReturnToAccountsList(value);
}
void ProviderPluginProcess::setExitData(const QVariant &data)
{
Q_D(ProviderPluginProcess);
d->wrapped->setExitData(data);
}
const LastPageActions &ProviderPluginProcess::lastPageActions() const
{
Q_D(const ProviderPluginProcess);
return d->lastPageActions;
}
QString ProviderPluginProcess::translatedProviderName() const
{
Q_D(const ProviderPluginProcess);
if (!(d->translatedProviderName .isEmpty()))
return d->translatedProviderName;
QString providerName(d->account->providerName());
QString providerIconId;
Accounts::Provider *provider =
AccountsManager::instance()->provider(providerName);
if (provider) {
providerIconId = provider->iconName();
QString catalog = provider->trCatalog();
MLocale locale;
if (!catalog.isEmpty() && !locale.isInstalledTrCatalog(catalog)) {
locale.installTrCatalog(catalog);
MLocale::setDefault(locale);
}
}
d->translatedProviderName = qtTrId(provider->displayName().toLatin1());
if (!(d->translatedProviderName .isEmpty()))
return d->translatedProviderName;
else if (!providerName.isEmpty())
return providerName;
else
return "";
}
} // namespace
<|endoftext|> |
<commit_before>#include <QSound>
#include "MoNv.h"
enum CAUSE{
CANG_YAN_FA_DIAN=3001,
TIAN_HUO_DUAN_KONG=3002,
MO_NV_ZHI_NU=3003,
MO_NV_ZHI_NU_ATTACK=30031,
TI_SHEN_WAN_OU=3004,
YONG_SHENG_YIN_SHI_JI=3005,
TONG_KU_LIAN_JIE=3006,
TONG_KU_LIAN_JIE_CARD=30061,
MO_NENG_FAN_ZHUAN=3007
};
MoNv::MoNv()
{
makeConnection();
setMyRole(this);
Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;
cangYanFaDian = new Button(3,QStringLiteral("苍炎法典"));
buttonArea->addButton(cangYanFaDian);
connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));
tianHuoDuanKong = new Button(4,QStringLiteral("天火断空"));
buttonArea->addButton(tianHuoDuanKong);
connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));
tongKuLianJie = new Button(5,QStringLiteral("痛苦链接"));
buttonArea->addButton(tongKuLianJie);
connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));
}
int MoNv::checkFire()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> handcards = dataInterface->getHandCards();
int fire = 0;
for(int i=0; i<handcards.size();i++)
{
if(handcards[i]->getElement() == QStringLiteral("fire"))
fire ++;
if(myself->getTap() && handcards[i]->getType() == "attack" &&
(handcards[i]->getElement() == "thunder" || handcards[i]->getElement() == "earth" || handcards[i]->getElement() == "wind"))
fire ++;
}
return fire;
}
void MoNv::enbleFire()
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("thunder"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("wind"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("earth"));
}
handArea->enableElement(QStringLiteral("fire"));
}
void MoNv::enbleFireAttack(QString element)
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
if(element == "water")
handArea->enableElement(element);
if(element == "fire")
{
handArea->enableElement("fire");
handArea->enableElement("thunder");
handArea->enableElement("earth");
handArea->enableElement("wind");
}
}
else
{
handArea->enableElement(element);
}
}
void MoNv::attacked(QString element,int hitRate)
{
state=2;
playerArea->setQuota(1);
handArea->setQuota(1);
decisionArea->enable(1);
if(hitRate==0)
{
this->enbleFireAttack(element);
handArea->enableElement("darkness");
}
handArea->disableMagic();
handArea->enableElement("light");
gui->alert();
QSound::play("sound/Warning.wav");
}
void MoNv::normal()
{
Role::normal();
Player* myself=dataInterface->getMyself();
int fire = checkFire();
if(fire > 0)
buttonArea->enable(3);
if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))
buttonArea->enable(4);
if(myself->getEnergy()>0)
buttonArea->enable(5);
unactionalCheck();
}
void MoNv::CangYanFaDian()
{
state = CANG_YAN_FA_DIAN;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TianHuoDuanKong()
{
state = TIAN_HUO_DUAN_KONG;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(2);
playerArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TongKuLianJie()
{
state = TONG_KU_LIAN_JIE;
handArea->reset();
playerArea->reset();
tipArea->reset();
playerArea->enableAll();
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::cardAnalyse()
{
Role::cardAnalyse();
switch (state)
{
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
playerArea->enableAll();
break;
case TI_SHEN_WAN_OU:
playerArea->enableMate();
break;
case MO_NENG_FAN_ZHUAN:
playerArea->enableEnemy();
break;
}
}
void MoNv::MoNvZhiNu()
{
state = MO_NV_ZHI_NU;
gui->reset();
tipArea->setMsg(QStringLiteral("发动【魔女之怒】,并选择要摸取的手牌数量"));
for(int i =0; i < 3 ; i ++)
tipArea->addBoxItem(QString::number(i));
tipArea->showBox();
decisionArea->enable(0);
decisionArea->enable(1);
}
void MoNv::TiShenWanOu()
{
state=TI_SHEN_WAN_OU;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动替身玩偶"));
handArea->setQuota(1);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::MoNengFanZhuan()
{
state=MO_NENG_FAN_ZHUAN;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动魔能反转"));
handArea->setQuota(2,9);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::askForSkill(network::Command* cmd)
{
switch (cmd->respond_id()) {
case MO_NV_ZHI_NU:
MoNvZhiNu();
break;
case TI_SHEN_WAN_OU:
TiShenWanOu();
break;
case MO_NENG_FAN_ZHUAN:
MoNengFanZhuan();
break;
default:
Role::askForSkill(cmd);
break;
}
}
void MoNv::onOkClicked()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> selectedCards;
SafeList<Player*>selectedPlayers;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
try{
switch(state)
{
case 1:
if(selectedCards[0]->getType()=="attack" && myself->getTap() &&
(selectedCards[0]->getElement() == "thunder" || selectedCards[0]->getElement() == "earth" || selectedCards[0]->getElement() == "wind")){
state = MO_NV_ZHI_NU_ATTACK;
action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_card_ids(selectedCards[0]->getID());
usedAttack=true;
usedMagic=usedSpecial=false;
gui->reset();
emit sendCommand(network::MSG_ACTION, action);
}
break;
case TI_SHEN_WAN_OU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(TI_SHEN_WAN_OU);
respond->add_card_ids(selectedCards[0]->getID());
respond->add_dst_ids(selectedPlayers[0]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NENG_FAN_ZHUAN);
respond->add_dst_ids(selectedPlayers[0]->getID());
for(int i =0; i < selectedCards.size();i++)
respond->add_card_ids(selectedCards[i]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NV_ZHI_NU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NV_ZHI_NU);
respond->add_args(1);// 1表示选择发动
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
start =true;
break;
case CANG_YAN_FA_DIAN:
action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TIAN_HUO_DUAN_KONG:
action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_card_ids(selectedCards[1]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TONG_KU_LIAN_JIE:
action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);
action->set_src_id(myID);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_args(1);
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
}
}catch(int error){
logic->onError(error);
}
Role::onOkClicked();
}
void MoNv::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case MO_NV_ZHI_NU:
case TI_SHEN_WAN_OU:
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(state);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
case TONG_KU_LIAN_JIE:
normal();
break;
}
}
<commit_msg>魔女启动提炼<commit_after>#include <QSound>
#include "MoNv.h"
enum CAUSE{
CANG_YAN_FA_DIAN=3001,
TIAN_HUO_DUAN_KONG=3002,
MO_NV_ZHI_NU=3003,
MO_NV_ZHI_NU_ATTACK=30031,
TI_SHEN_WAN_OU=3004,
YONG_SHENG_YIN_SHI_JI=3005,
TONG_KU_LIAN_JIE=3006,
TONG_KU_LIAN_JIE_CARD=30061,
MO_NENG_FAN_ZHUAN=3007
};
MoNv::MoNv()
{
makeConnection();
setMyRole(this);
Button *cangYanFaDian, *tianHuoDuanKong, *tongKuLianJie;
cangYanFaDian = new Button(3,QStringLiteral("苍炎法典"));
buttonArea->addButton(cangYanFaDian);
connect(cangYanFaDian,SIGNAL(buttonSelected(int)),this,SLOT(CangYanFaDian()));
tianHuoDuanKong = new Button(4,QStringLiteral("天火断空"));
buttonArea->addButton(tianHuoDuanKong);
connect(tianHuoDuanKong,SIGNAL(buttonSelected(int)),this,SLOT(TianHuoDuanKong()));
tongKuLianJie = new Button(5,QStringLiteral("痛苦链接"));
buttonArea->addButton(tongKuLianJie);
connect(tongKuLianJie,SIGNAL(buttonSelected(int)),this,SLOT(TongKuLianJie()));
}
int MoNv::checkFire()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> handcards = dataInterface->getHandCards();
int fire = 0;
for(int i=0; i<handcards.size();i++)
{
if(handcards[i]->getElement() == QStringLiteral("fire"))
fire ++;
if(myself->getTap() && handcards[i]->getType() == "attack" &&
(handcards[i]->getElement() == "thunder" || handcards[i]->getElement() == "earth" || handcards[i]->getElement() == "wind"))
fire ++;
}
return fire;
}
void MoNv::enbleFire()
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("thunder"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("wind"));
handArea->enableTypeAndElement(QStringLiteral("attack"), QStringLiteral("earth"));
}
handArea->enableElement(QStringLiteral("fire"));
}
void MoNv::enbleFireAttack(QString element)
{
Player* myself=dataInterface->getMyself();
if(myself->getTap())
{
if(element == "water")
handArea->enableElement(element);
if(element == "fire")
{
handArea->enableElement("fire");
handArea->enableElement("thunder");
handArea->enableElement("earth");
handArea->enableElement("wind");
}
}
else
{
handArea->enableElement(element);
}
}
void MoNv::attacked(QString element,int hitRate)
{
state=2;
playerArea->setQuota(1);
handArea->setQuota(1);
decisionArea->enable(1);
if(hitRate==0)
{
this->enbleFireAttack(element);
handArea->enableElement("darkness");
}
handArea->disableMagic();
handArea->enableElement("light");
gui->alert();
QSound::play("sound/Warning.wav");
}
void MoNv::normal()
{
Role::normal();
Player* myself=dataInterface->getMyself();
int fire = checkFire();
if(fire > 0)
buttonArea->enable(3);
if(fire > 1 && (myself->getToken(0)>0 || myself->getTap()))
buttonArea->enable(4);
if(myself->getEnergy()>0)
buttonArea->enable(5);
unactionalCheck();
}
void MoNv::CangYanFaDian()
{
state = CANG_YAN_FA_DIAN;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TianHuoDuanKong()
{
state = TIAN_HUO_DUAN_KONG;
handArea->reset();
playerArea->reset();
tipArea->reset();
this->enbleFire();
handArea->setQuota(2);
playerArea->setQuota(1);
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::TongKuLianJie()
{
state = TONG_KU_LIAN_JIE;
handArea->reset();
playerArea->reset();
tipArea->reset();
playerArea->enableAll();
playerArea->setQuota(1);
decisionArea->enable(1);
decisionArea->disable(0);
}
void MoNv::cardAnalyse()
{
Role::cardAnalyse();
switch (state)
{
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
playerArea->enableAll();
break;
case TI_SHEN_WAN_OU:
playerArea->enableMate();
break;
case MO_NENG_FAN_ZHUAN:
playerArea->enableEnemy();
break;
}
}
void MoNv::MoNvZhiNu()
{
state = MO_NV_ZHI_NU;
gui->reset();
tipArea->setMsg(QStringLiteral("发动【魔女之怒】,并选择要摸取的手牌数量"));
for(int i =0; i < 3 ; i ++)
tipArea->addBoxItem(QString::number(i));
tipArea->showBox();
decisionArea->enable(0);
decisionArea->enable(1);
}
void MoNv::TiShenWanOu()
{
state=TI_SHEN_WAN_OU;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动替身玩偶"));
handArea->setQuota(1);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::MoNengFanZhuan()
{
state=MO_NENG_FAN_ZHUAN;
gui->reset();
tipArea->setMsg(QStringLiteral("是否发动魔能反转"));
handArea->setQuota(2,9);
handArea->enableMagic();
decisionArea->enable(1);
}
void MoNv::askForSkill(network::Command* cmd)
{
switch (cmd->respond_id()) {
case MO_NV_ZHI_NU:
MoNvZhiNu();
break;
case TI_SHEN_WAN_OU:
TiShenWanOu();
break;
case MO_NENG_FAN_ZHUAN:
MoNengFanZhuan();
break;
default:
Role::askForSkill(cmd);
break;
}
}
void MoNv::onOkClicked()
{
Player* myself=dataInterface->getMyself();
SafeList<Card*> selectedCards;
SafeList<Player*>selectedPlayers;
selectedCards=handArea->getSelectedCards();
selectedPlayers=playerArea->getSelectedPlayers();
network::Action* action;
network::Respond* respond;
try{
switch(state)
{
case 1:
if(selectedCards[0]->getType()=="attack" && myself->getTap() &&
(selectedCards[0]->getElement() == "thunder" || selectedCards[0]->getElement() == "earth" || selectedCards[0]->getElement() == "wind")){
state = MO_NV_ZHI_NU_ATTACK;
action = newAction(ACTION_ATTACK_SKILL, MO_NV_ZHI_NU_ATTACK);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_card_ids(selectedCards[0]->getID());
usedAttack=true;
usedMagic=usedSpecial=false;
gui->reset();
emit sendCommand(network::MSG_ACTION, action);
}
break;
case TI_SHEN_WAN_OU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(TI_SHEN_WAN_OU);
respond->add_card_ids(selectedCards[0]->getID());
respond->add_dst_ids(selectedPlayers[0]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NENG_FAN_ZHUAN);
respond->add_dst_ids(selectedPlayers[0]->getID());
for(int i =0; i < selectedCards.size();i++)
respond->add_card_ids(selectedCards[i]->getID());
respond->add_args(1);// 1表示选择发动
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case MO_NV_ZHI_NU:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(MO_NV_ZHI_NU);
respond->add_args(1);// 1表示选择发动
respond->add_args(tipArea->getBoxCurrentText().toInt());
emit sendCommand(network::MSG_RESPOND, respond);
start =true;
gui->reset();
break;
case CANG_YAN_FA_DIAN:
action = newAction(ACTION_MAGIC_SKILL, CANG_YAN_FA_DIAN);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TIAN_HUO_DUAN_KONG:
action = newAction(ACTION_MAGIC_SKILL, TIAN_HUO_DUAN_KONG);
action->set_src_id(myID);
action->add_card_ids(selectedCards[0]->getID());
action->add_card_ids(selectedCards[1]->getID());
action->add_dst_ids(selectedPlayers[0]->getID());
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
case TONG_KU_LIAN_JIE:
action = newAction(ACTION_MAGIC_SKILL, TONG_KU_LIAN_JIE);
action->set_src_id(myID);
action->add_dst_ids(selectedPlayers[0]->getID());
action->add_args(1);
emit sendCommand(network::MSG_ACTION, action);
gui->reset();
break;
}
}catch(int error){
logic->onError(error);
}
Role::onOkClicked();
}
void MoNv::onCancelClicked()
{
Role::onCancelClicked();
network::Respond* respond;
switch(state)
{
case MO_NV_ZHI_NU:
case TI_SHEN_WAN_OU:
case MO_NENG_FAN_ZHUAN:
respond = new network::Respond();
respond->set_src_id(myID);
respond->set_respond_id(state);
respond->add_args(0);
emit sendCommand(network::MSG_RESPOND, respond);
gui->reset();
break;
case CANG_YAN_FA_DIAN:
case TIAN_HUO_DUAN_KONG:
case TONG_KU_LIAN_JIE:
normal();
break;
}
}
<|endoftext|> |
<commit_before>#include "notendaui.h"
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
using namespace std;
NotendaUI::NotendaUI()
{
}
bool check = true;
void NotendaUI::keyra()
{
//TEMP
vector<tolvufolk> data = _service.getTolvufolk();
string nName;
string gGender;
int bYear;
int dYear;
skrifaUt();
do
{
check = true;
string skipun;
cin >> skipun;
if (skipun == "list" || skipun == "l")
{
skrifaUt();
printList(data);
continueUI();
}
else if (skipun == "add" || skipun == "a")
{
skrifaUt();
cout << "Enter name: ";
cin.ignore();
getline(cin,nName);
cout << "Enter gender(kk/kvk) [lowercase]: ";
cin >> gGender;
while (gGender != "kk" && gGender != "kvk")
{
cerr << "Input not valid, try again: ";
cin >> gGender;
}
cout << "Enter year of birth: ";
cin >> bYear;
while (0 > bYear)
{
cerr << "Input not valid, try again: ";
cin >> bYear;
}
cout << "Enter year of death(-1 if still alive): ";
cin >> dYear;
while (-1 > dYear)
{
cerr << "Input not valid, try again: ";
cin >> dYear;
cout << endl;
}
data.push_back(tolvufolk(nName, gGender, bYear, dYear));
printList(data);
continueUI();
}
else if (skipun == "delete" || skipun == "d")
{
skrifaUt();
printList(data);
continueUI();
}
else if (skipun == "update" || skipun == "u")
{
skrifaUt();
updatePerson(data);
continueUI();
}
else if (skipun == "search" || skipun == "s")
{
skrifaUt();
searchName(data);
continueUI();
}
else if (skipun == "purge" || skipun == "p")
{
skrifaUt();
cout << "By the Emperor, are you sure? (Y/N): ";
cin >> skipun;
if (skipun == "Y" || skipun == "y")
{
cout << "Are you really sure? This will EXTERMINATE ALL ENTRIES. (Y/N): ";
cin >> skipun;
if (skipun == "Y" || skipun == "y")
{
cout << "Acknowledged, by your will, all ENTRIES will be EXTERMINATED.";
// TODO; Erase everything
continueUI();
}
else
{
cout << "Purge canceled." << endl;
continueUI();
}
}
else
{
cout << "Purge canceled." << endl;
continueUI();
}
}
else if (skipun == "quit" || skipun == "q")
{
check = true;
}
else
{
skrifaUt();
cerr << "Input not valid, try again: ";
check = false;
}
} while (check == false);
}
void NotendaUI::skrifaUt()
{
system("cls");
cout << "*==============================================================*" << endl;
cout << "*||Please enter one the following commands ||*" << endl;
cout << "*==============================================================*" << endl;
cout << "*||list - Shows a list of all known entries in the database. ||*" << endl;
cout << "*||add - Add a new entry into the database. ||*" << endl;
cout << "*||delete - Removes an entry from the database. ||*" << endl;
cout << "*||update - Updates an entry from the database. ||*" << endl;
cout << "*||search - Search for an entry from the database. ||*" << endl;
cout << "*||purge - Removes every entry from the database. ||*" << endl;
cout << "*||quit - Exits/quits the program ||*" << endl;
cout << "*==============================================================*" << endl;
}
void NotendaUI::updatePerson(vector<tolvufolk>& data)
{
int persNR;
string skipunin;
cout << "Number of Scientist: ";
cin >> persNR;
persNR --;
cout << "*==============================================================*" << endl;
cout << "*||Please enter one the following command* ||*" << endl;
cout << "*==============================================================*" << endl;
cout << "*||name - update name ||*" << endl;
cout << "*||age - update age ||*" << endl;
cout << "*||birth - update year of birth ||*" << endl;
cout << "*||death - update year of death ||*" << endl;
cout << "*==============================================================*" << endl;
cin >> skipunin;
if (skipunin == "name" || skipunin == "n")
{
string nafn;
cout << "Enter updated name for " << data[persNR].getNafn() << ": ";
cin.ignore();
getline(cin,nafn);
data[persNR].updNafn(nafn);
}
else if (skipunin == "death" || skipunin == "d")
{
int nytt;
cout << "Enter updated year of death for " << data[persNR].getNafn() << ": ";
cin >> nytt;
data[persNR].updDanarar(nytt);
}
}
void NotendaUI::searchOptions()
{
system("cls");
cout << "*==============================================================*" << endl;
cout << "*||Please enter one the following command ||*" << endl;
cout << "*==============================================================*" << endl;
cout << "*||name - Search by name ||*" << endl;
cout << "*||age - Search by age ||*" << endl;
cout << "*||birth - Search by year of birth ||*" << endl;
cout << "*||death - Search by year of death ||*" << endl;
cout << "*==============================================================*" << endl;
}
void NotendaUI::printList(const vector<tolvufolk>& data)
{
for (size_t i = 0; i < data.size(); i++)
{
cout << "Scientist number: " << i + 1 << endl;
cout << data[i] << endl;
}
}
void NotendaUI::searchName(const vector<tolvufolk>& data)
{
searchOptions();
string skipunin;
cin >> skipunin;
if (skipunin == "name" || skipunin == "n")
{
searchOptions();
string nafn;
cout << "Name to search: ";
cin.ignore();
getline(cin,nafn);
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (nafn == data[i].getNafn() )
{
cout << data[i];
}
}
cout << endl;
}
else if (skipunin == "age" || skipunin == "a")
{
searchOptions();
int age;
cout << "Age to search: ";
cin >> age;
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (age == (data[i].getDanarar() - data[i].getFaedingarar() ) )
{
cout << data[i];
}
}
cout << endl;
}
else if (skipunin == "birth" || skipunin == "b")
{
searchOptions();
int birth;
cout << "Year of birth to search: ";
cin >> birth;
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (birth == data[i].getFaedingarar() )
{
cout << data[i];
}
}
cout << endl;
}
else if (skipunin == "death" || skipunin == "d")
{
searchOptions();
int death;
cout << "Year of birth to search: ";
cin >> death;
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (death == data[i].getDanarar() )
{
cout << data[i];
}
}
cout << endl;
}
}
void NotendaUI::continueUI()
{
string answer;
cout << "Continue? (Y/N): ";
cin >> answer;
if (answer == "Y" || answer == "y")
{
skrifaUt();
check = false;
}
else
{
check = true;
}
}
<commit_msg>lagadi til ad skra i skra<commit_after>#include "notendaui.h"
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
using namespace std;
NotendaUI::NotendaUI()
{
}
bool check = true;
void NotendaUI::keyra()
{
//TEMP
vector<tolvufolk> data = _service.getTolvufolk();
string nName;
string gGender;
int bYear;
int dYear;
skrifaUt();
do
{
check = true;
string skipun;
cin >> skipun;
if (skipun == "list" || skipun == "l")
{
skrifaUt();
printList(data);
continueUI();
}
else if (skipun == "add" || skipun == "a")
{
skrifaUt();
cout << "Enter name: ";
cin.ignore();
getline(cin,nName);
cout << "Enter gender(kk/kvk) [lowercase]: ";
cin >> gGender;
while (gGender != "kk" && gGender != "kvk")
{
cerr << "Input not valid, try again: ";
cin >> gGender;
}
cout << "Enter year of birth: ";
cin >> bYear;
while (0 > bYear)
{
cerr << "Input not valid, try again: ";
cin >> bYear;
}
cout << "Enter year of death(-1 if still alive): ";
cin >> dYear;
while (-1 > dYear)
{
cerr << "Input not valid, try again: ";
cin >> dYear;
cout << endl;
}
tolvufolk Tempr(nName, gGender, bYear, dYear);
data.push_back(Tempr);
_service.addTolvufolk(Tempr);
printList(data);
continueUI();
}
else if (skipun == "delete" || skipun == "d")
{
skrifaUt();
printList(data);
continueUI();
}
else if (skipun == "update" || skipun == "u")
{
skrifaUt();
updatePerson(data);
continueUI();
}
else if (skipun == "search" || skipun == "s")
{
skrifaUt();
searchName(data);
continueUI();
}
else if (skipun == "purge" || skipun == "p")
{
skrifaUt();
cout << "By the Emperor, are you sure? (Y/N): ";
cin >> skipun;
if (skipun == "Y" || skipun == "y")
{
cout << "Are you really sure? This will EXTERMINATE ALL ENTRIES. (Y/N): ";
cin >> skipun;
if (skipun == "Y" || skipun == "y")
{
cout << "Acknowledged, by your will, all ENTRIES will be EXTERMINATED.";
// TODO; Erase everything
continueUI();
}
else
{
cout << "Purge canceled." << endl;
continueUI();
}
}
else
{
cout << "Purge canceled." << endl;
continueUI();
}
}
else if (skipun == "quit" || skipun == "q")
{
check = true;
}
else
{
skrifaUt();
cerr << "Input not valid, try again: ";
check = false;
}
} while (check == false);
}
void NotendaUI::skrifaUt()
{
system("cls");
cout << "*==============================================================*" << endl;
cout << "*||Please enter one the following commands ||*" << endl;
cout << "*==============================================================*" << endl;
cout << "*||list - Shows a list of all known entries in the database. ||*" << endl;
cout << "*||add - Add a new entry into the database. ||*" << endl;
cout << "*||delete - Removes an entry from the database. ||*" << endl;
cout << "*||update - Updates an entry from the database. ||*" << endl;
cout << "*||search - Search for an entry from the database. ||*" << endl;
cout << "*||purge - Removes every entry from the database. ||*" << endl;
cout << "*||quit - Exits/quits the program ||*" << endl;
cout << "*==============================================================*" << endl;
}
void NotendaUI::updatePerson(vector<tolvufolk>& data)
{
int persNR;
string skipunin;
cout << "Number of Scientist: ";
cin >> persNR;
persNR --;
cout << "*==============================================================*" << endl;
cout << "*||Please enter one the following command* ||*" << endl;
cout << "*==============================================================*" << endl;
cout << "*||name - update name ||*" << endl;
cout << "*||age - update age ||*" << endl;
cout << "*||birth - update year of birth ||*" << endl;
cout << "*||death - update year of death ||*" << endl;
cout << "*==============================================================*" << endl;
cin >> skipunin;
if (skipunin == "name" || skipunin == "n")
{
string nafn;
cout << "Enter updated name for " << data[persNR].getNafn() << ": ";
cin.ignore();
getline(cin,nafn);
data[persNR].updNafn(nafn);
}
else if (skipunin == "death" || skipunin == "d")
{
int nytt;
cout << "Enter updated year of death for " << data[persNR].getNafn() << ": ";
cin >> nytt;
data[persNR].updDanarar(nytt);
}
}
void NotendaUI::searchOptions()
{
system("cls");
cout << "*==============================================================*" << endl;
cout << "*||Please enter one the following command ||*" << endl;
cout << "*==============================================================*" << endl;
cout << "*||name - Search by name ||*" << endl;
cout << "*||age - Search by age ||*" << endl;
cout << "*||birth - Search by year of birth ||*" << endl;
cout << "*||death - Search by year of death ||*" << endl;
cout << "*==============================================================*" << endl;
}
void NotendaUI::printList(const vector<tolvufolk>& data)
{
for (size_t i = 0; i < data.size(); i++)
{
cout << "Scientist number: " << i + 1 << endl;
cout << data[i] << endl;
}
}
void NotendaUI::searchName(const vector<tolvufolk>& data)
{
searchOptions();
string skipunin;
cin >> skipunin;
if (skipunin == "name" || skipunin == "n")
{
searchOptions();
string nafn;
cout << "Name to search: ";
cin.ignore();
getline(cin,nafn);
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (nafn == data[i].getNafn() )
{
cout << data[i];
}
}
cout << endl;
}
else if (skipunin == "age" || skipunin == "a")
{
searchOptions();
int age;
cout << "Age to search: ";
cin >> age;
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (age == (data[i].getDanarar() - data[i].getFaedingarar() ) )
{
cout << data[i];
}
}
cout << endl;
}
else if (skipunin == "birth" || skipunin == "b")
{
searchOptions();
int birth;
cout << "Year of birth to search: ";
cin >> birth;
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (birth == data[i].getFaedingarar() )
{
cout << data[i];
}
}
cout << endl;
}
else if (skipunin == "death" || skipunin == "d")
{
searchOptions();
int death;
cout << "Year of birth to search: ";
cin >> death;
cout << endl;
for(size_t i = 0; i < data.size(); i++)
{
if (death == data[i].getDanarar() )
{
cout << data[i];
}
}
cout << endl;
}
}
void NotendaUI::continueUI()
{
string answer;
cout << "Continue? (Y/N): ";
cin >> answer;
if (answer == "Y" || answer == "y")
{
skrifaUt();
check = false;
}
else
{
check = true;
}
}
<|endoftext|> |
<commit_before>//===--- UsePrespecialized.cpp - use pre-specialized functions ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "use-prespecialized"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/SpecializationMangler.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "llvm/Support/Debug.h"
#include "swift/SILOptimizer/Utils/Generics.h"
using namespace swift;
namespace {
static void collectApplyInst(SILFunction &F,
llvm::SmallVectorImpl<ApplySite> &NewApplies) {
// Scan all of the instructions in this function in search of ApplyInsts.
for (auto &BB : F)
for (auto &I : BB)
if (ApplySite AI = ApplySite::isa(&I))
NewApplies.push_back(AI);
}
/// A simple pass which replaces each apply of a generic function by an apply
/// of the corresponding pre-specialized function, if such a pre-specialization
/// exists.
class UsePrespecialized: public SILModuleTransform {
~UsePrespecialized() override { }
void run() override {
auto &M = *getModule();
for (auto &F : M) {
if (replaceByPrespecialized(F)) {
invalidateAnalysis(&F, SILAnalysis::InvalidationKind::Everything);
}
}
}
bool replaceByPrespecialized(SILFunction &F);
};
// Analyze the function and replace each apply of
// a generic function by an apply of the corresponding
// pre-specialized function, if such a pre-specialization exists.
bool UsePrespecialized::replaceByPrespecialized(SILFunction &F) {
bool Changed = false;
auto &M = F.getModule();
llvm::SmallVector<ApplySite, 16> NewApplies;
collectApplyInst(F, NewApplies);
for (auto &AI : NewApplies) {
auto *ReferencedF = AI.getReferencedFunction();
if (!ReferencedF)
continue;
LLVM_DEBUG(llvm::dbgs() << "Trying to use specialized function for:\n";
AI.getInstruction()->dumpInContext());
// Check if it is a call of a generic function.
// If this is the case, check if there is a specialization
// available for it already and use this specialization
// instead of the generic version.
if (!AI.hasSubstitutions())
continue;
SubstitutionMap Subs = AI.getSubstitutionMap();
// Bail if any generic type parameters are unbound.
// TODO: Remove this limitation once public partial specializations
// are supported and can be provided by other modules.
if (Subs.hasArchetypes())
continue;
ReabstractionInfo ReInfo(AI, ReferencedF, Subs);
if (!ReInfo.canBeSpecialized())
continue;
auto SpecType = ReInfo.getSpecializedType();
// Bail if any generic types parameters of the concrete type
// are unbound.
if (SpecType->hasArchetype())
continue;
// Create a name of the specialization. All external pre-specializations
// are serialized without bodies. Thus use IsNotSerialized here.
Mangle::GenericSpecializationMangler NewGenericMangler(ReferencedF,
Subs, IsNotSerialized,
/*isReAbstracted*/ true);
std::string ClonedName = NewGenericMangler.mangle();
SILFunction *NewF = nullptr;
// If we already have this specialization, reuse it.
auto PrevF = M.lookUpFunction(ClonedName);
if (PrevF) {
LLVM_DEBUG(llvm::dbgs() << "Found a specialization: " << ClonedName
<< "\n");
if (PrevF->getLinkage() != SILLinkage::SharedExternal)
NewF = PrevF;
else {
LLVM_DEBUG(llvm::dbgs() << "Wrong linkage: " << (int)PrevF->getLinkage()
<< "\n");
}
}
if (!PrevF || !NewF) {
// Check for the existence of this function in another module without
// loading the function body.
PrevF = lookupPrespecializedSymbol(M, ClonedName);
LLVM_DEBUG(llvm::dbgs() << "Checked if there is a specialization in a "
"different module: "
<< PrevF << "\n");
if (!PrevF)
continue;
assert(PrevF->isExternalDeclaration() &&
"Prespecialized function should be an external declaration");
NewF = PrevF;
}
if (!NewF)
continue;
// An existing specialization was found.
LLVM_DEBUG(llvm::dbgs() << "Found a specialization of "
<< ReferencedF->getName()
<< " : " << NewF->getName() << "\n");
auto NewAI = replaceWithSpecializedFunction(AI, NewF, ReInfo);
if (auto oldApply = dyn_cast<ApplyInst>(AI)) {
oldApply->replaceAllUsesWith(cast<ApplyInst>(NewAI));
} else if (auto oldPApply = dyn_cast<PartialApplyInst>(AI)) {
oldPApply->replaceAllUsesWith(cast<PartialApplyInst>(NewAI));
} else {
assert(isa<TryApplyInst>(NewAI));
}
recursivelyDeleteTriviallyDeadInstructions(AI.getInstruction(), true);
Changed = true;
}
return Changed;
}
} // end anonymous namespace
SILTransform *swift::createUsePrespecialized() {
return new UsePrespecialized();
}
<commit_msg>SILOptimizer: handle begin_apply in an assert in the UsePrespecialied optimization.<commit_after>//===--- UsePrespecialized.cpp - use pre-specialized functions ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "use-prespecialized"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/SpecializationMangler.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "llvm/Support/Debug.h"
#include "swift/SILOptimizer/Utils/Generics.h"
using namespace swift;
namespace {
static void collectApplyInst(SILFunction &F,
llvm::SmallVectorImpl<ApplySite> &NewApplies) {
// Scan all of the instructions in this function in search of ApplyInsts.
for (auto &BB : F)
for (auto &I : BB)
if (ApplySite AI = ApplySite::isa(&I))
NewApplies.push_back(AI);
}
/// A simple pass which replaces each apply of a generic function by an apply
/// of the corresponding pre-specialized function, if such a pre-specialization
/// exists.
class UsePrespecialized: public SILModuleTransform {
~UsePrespecialized() override { }
void run() override {
auto &M = *getModule();
for (auto &F : M) {
if (replaceByPrespecialized(F)) {
invalidateAnalysis(&F, SILAnalysis::InvalidationKind::Everything);
}
}
}
bool replaceByPrespecialized(SILFunction &F);
};
// Analyze the function and replace each apply of
// a generic function by an apply of the corresponding
// pre-specialized function, if such a pre-specialization exists.
bool UsePrespecialized::replaceByPrespecialized(SILFunction &F) {
bool Changed = false;
auto &M = F.getModule();
llvm::SmallVector<ApplySite, 16> NewApplies;
collectApplyInst(F, NewApplies);
for (auto &AI : NewApplies) {
auto *ReferencedF = AI.getReferencedFunction();
if (!ReferencedF)
continue;
LLVM_DEBUG(llvm::dbgs() << "Trying to use specialized function for:\n";
AI.getInstruction()->dumpInContext());
// Check if it is a call of a generic function.
// If this is the case, check if there is a specialization
// available for it already and use this specialization
// instead of the generic version.
if (!AI.hasSubstitutions())
continue;
SubstitutionMap Subs = AI.getSubstitutionMap();
// Bail if any generic type parameters are unbound.
// TODO: Remove this limitation once public partial specializations
// are supported and can be provided by other modules.
if (Subs.hasArchetypes())
continue;
ReabstractionInfo ReInfo(AI, ReferencedF, Subs);
if (!ReInfo.canBeSpecialized())
continue;
auto SpecType = ReInfo.getSpecializedType();
// Bail if any generic types parameters of the concrete type
// are unbound.
if (SpecType->hasArchetype())
continue;
// Create a name of the specialization. All external pre-specializations
// are serialized without bodies. Thus use IsNotSerialized here.
Mangle::GenericSpecializationMangler NewGenericMangler(ReferencedF,
Subs, IsNotSerialized,
/*isReAbstracted*/ true);
std::string ClonedName = NewGenericMangler.mangle();
SILFunction *NewF = nullptr;
// If we already have this specialization, reuse it.
auto PrevF = M.lookUpFunction(ClonedName);
if (PrevF) {
LLVM_DEBUG(llvm::dbgs() << "Found a specialization: " << ClonedName
<< "\n");
if (PrevF->getLinkage() != SILLinkage::SharedExternal)
NewF = PrevF;
else {
LLVM_DEBUG(llvm::dbgs() << "Wrong linkage: " << (int)PrevF->getLinkage()
<< "\n");
}
}
if (!PrevF || !NewF) {
// Check for the existence of this function in another module without
// loading the function body.
PrevF = lookupPrespecializedSymbol(M, ClonedName);
LLVM_DEBUG(llvm::dbgs() << "Checked if there is a specialization in a "
"different module: "
<< PrevF << "\n");
if (!PrevF)
continue;
assert(PrevF->isExternalDeclaration() &&
"Prespecialized function should be an external declaration");
NewF = PrevF;
}
if (!NewF)
continue;
// An existing specialization was found.
LLVM_DEBUG(llvm::dbgs() << "Found a specialization of "
<< ReferencedF->getName()
<< " : " << NewF->getName() << "\n");
auto NewAI = replaceWithSpecializedFunction(AI, NewF, ReInfo);
if (auto oldApply = dyn_cast<ApplyInst>(AI)) {
oldApply->replaceAllUsesWith(cast<ApplyInst>(NewAI));
} else if (auto oldPApply = dyn_cast<PartialApplyInst>(AI)) {
oldPApply->replaceAllUsesWith(cast<PartialApplyInst>(NewAI));
} else {
assert(isa<TryApplyInst>(NewAI) || isa<BeginApplyInst>(NewAI));
}
recursivelyDeleteTriviallyDeadInstructions(AI.getInstruction(), true);
Changed = true;
}
return Changed;
}
} // end anonymous namespace
SILTransform *swift::createUsePrespecialized() {
return new UsePrespecialized();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef m_LOGINERR_HXX
#define m_LOGINERR_HXX
#include <tools/string.hxx>
//=========================================================================
#define LOGINERROR_FLAG_MODIFY_ACCOUNT 1
#define LOGINERROR_FLAG_MODIFY_USER_NAME 2
#define LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD 4
#define LOGINERROR_FLAG_IS_REMEMBER_PASSWORD 8
#define LOGINERROR_FLAG_CAN_USE_SYSCREDS 16
#define LOGINERROR_FLAG_IS_USE_SYSCREDS 32
#define LOGINERROR_FLAG_REMEMBER_PERSISTENT 64
class LoginErrorInfo
{
private:
String m_aTitle;
String m_aServer;
String m_aAccount;
String m_aUserName;
String m_aPassword;
String m_aPasswordToModify;
String m_aPath;
String m_aErrorText;
BYTE m_nFlags;
USHORT m_nRet;
bool m_bRecommendToOpenReadonly;
public:
LoginErrorInfo()
: m_nFlags( LOGINERROR_FLAG_MODIFY_USER_NAME ),
m_nRet( ERRCODE_BUTTON_CANCEL )
{
}
const String& GetTitle() const { return m_aTitle; }
const String& GetServer() const { return m_aServer; }
const String& GetAccount() const { return m_aAccount; }
const String& GetUserName() const { return m_aUserName; }
const String& GetPassword() const { return m_aPassword; }
const String& GetPasswordToModify() const { return m_aPasswordToModify; }
const bool IsRecommendToOpenReadonly() const { return m_bRecommendToOpenReadonly; }
const String& GetPath() const { return m_aPath; }
const String& GetErrorText() const { return m_aErrorText; }
BOOL GetCanRememberPassword() const { return ( m_nFlags & LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD ); }
BOOL GetIsRememberPersistent() const { return ( m_nFlags & LOGINERROR_FLAG_REMEMBER_PERSISTENT ); }
BOOL GetIsRememberPassword() const { return ( m_nFlags & LOGINERROR_FLAG_IS_REMEMBER_PASSWORD ); }
BOOL GetCanUseSystemCredentials() const
{ return ( m_nFlags & LOGINERROR_FLAG_CAN_USE_SYSCREDS ); }
BOOL GetIsUseSystemCredentials() const
{ return ( m_nFlags & LOGINERROR_FLAG_IS_USE_SYSCREDS ) ==
LOGINERROR_FLAG_IS_USE_SYSCREDS; }
BYTE GetFlags() const { return m_nFlags; }
USHORT GetResult() const { return m_nRet; }
void SetTitle( const String& aTitle )
{ m_aTitle = aTitle; }
void SetServer( const String& aServer )
{ m_aServer = aServer; }
void SetAccount( const String& aAccount )
{ m_aAccount = aAccount; }
void SetUserName( const String& aUserName )
{ m_aUserName = aUserName; }
void SetPassword( const String& aPassword )
{ m_aPassword = aPassword; }
void SetPasswordToModify( const String& aPassword )
{ m_aPasswordToModify = aPassword; }
void SetRecommendToOpenReadonly( bool bVal )
{ m_bRecommendToOpenReadonly = bVal; }
void SetPath( const String& aPath )
{ m_aPath = aPath; }
void SetErrorText( const String& aErrorText )
{ m_aErrorText = aErrorText; }
void SetFlags( BYTE nFlags )
{ m_nFlags = nFlags; }
inline void SetCanRememberPassword( BOOL bSet );
inline void SetIsRememberPassword( BOOL bSet );
inline void SetIsRememberPersistent( BOOL bSet );
inline void SetCanUseSystemCredentials( BOOL bSet );
inline void SetIsUseSystemCredentials( BOOL bSet );
inline void SetModifyAccount( BOOL bSet );
inline void SetModifyUserName( BOOL bSet );
void SetResult( USHORT nRet )
{ m_nRet = nRet; }
};
inline void LoginErrorInfo::SetCanRememberPassword( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD;
else
m_nFlags &= ~LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD;
}
inline void LoginErrorInfo::SetIsRememberPassword( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_IS_REMEMBER_PASSWORD;
else
m_nFlags &= ~LOGINERROR_FLAG_IS_REMEMBER_PASSWORD;
}
inline void LoginErrorInfo::SetIsRememberPersistent( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_REMEMBER_PERSISTENT;
else
m_nFlags &= ~LOGINERROR_FLAG_REMEMBER_PERSISTENT;
}
inline void LoginErrorInfo::SetCanUseSystemCredentials( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_CAN_USE_SYSCREDS;
else
m_nFlags &= ~LOGINERROR_FLAG_CAN_USE_SYSCREDS;
}
inline void LoginErrorInfo::SetIsUseSystemCredentials( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_IS_USE_SYSCREDS;
else
m_nFlags &= ~LOGINERROR_FLAG_IS_USE_SYSCREDS;
}
inline void LoginErrorInfo::SetModifyAccount( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_MODIFY_ACCOUNT;
else
m_nFlags &= ~LOGINERROR_FLAG_MODIFY_ACCOUNT;
}
inline void LoginErrorInfo::SetModifyUserName( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_MODIFY_USER_NAME;
else
m_nFlags &= ~LOGINERROR_FLAG_MODIFY_USER_NAME;
}
#endif
<commit_msg>overly const<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef m_LOGINERR_HXX
#define m_LOGINERR_HXX
#include <tools/string.hxx>
//=========================================================================
#define LOGINERROR_FLAG_MODIFY_ACCOUNT 1
#define LOGINERROR_FLAG_MODIFY_USER_NAME 2
#define LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD 4
#define LOGINERROR_FLAG_IS_REMEMBER_PASSWORD 8
#define LOGINERROR_FLAG_CAN_USE_SYSCREDS 16
#define LOGINERROR_FLAG_IS_USE_SYSCREDS 32
#define LOGINERROR_FLAG_REMEMBER_PERSISTENT 64
class LoginErrorInfo
{
private:
String m_aTitle;
String m_aServer;
String m_aAccount;
String m_aUserName;
String m_aPassword;
String m_aPasswordToModify;
String m_aPath;
String m_aErrorText;
BYTE m_nFlags;
USHORT m_nRet;
bool m_bRecommendToOpenReadonly;
public:
LoginErrorInfo()
: m_nFlags( LOGINERROR_FLAG_MODIFY_USER_NAME ),
m_nRet( ERRCODE_BUTTON_CANCEL )
{
}
const String& GetTitle() const { return m_aTitle; }
const String& GetServer() const { return m_aServer; }
const String& GetAccount() const { return m_aAccount; }
const String& GetUserName() const { return m_aUserName; }
const String& GetPassword() const { return m_aPassword; }
const String& GetPasswordToModify() const { return m_aPasswordToModify; }
bool IsRecommendToOpenReadonly() const { return m_bRecommendToOpenReadonly; }
const String& GetPath() const { return m_aPath; }
const String& GetErrorText() const { return m_aErrorText; }
BOOL GetCanRememberPassword() const { return ( m_nFlags & LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD ); }
BOOL GetIsRememberPersistent() const { return ( m_nFlags & LOGINERROR_FLAG_REMEMBER_PERSISTENT ); }
BOOL GetIsRememberPassword() const { return ( m_nFlags & LOGINERROR_FLAG_IS_REMEMBER_PASSWORD ); }
BOOL GetCanUseSystemCredentials() const
{ return ( m_nFlags & LOGINERROR_FLAG_CAN_USE_SYSCREDS ); }
BOOL GetIsUseSystemCredentials() const
{ return ( m_nFlags & LOGINERROR_FLAG_IS_USE_SYSCREDS ) ==
LOGINERROR_FLAG_IS_USE_SYSCREDS; }
BYTE GetFlags() const { return m_nFlags; }
USHORT GetResult() const { return m_nRet; }
void SetTitle( const String& aTitle )
{ m_aTitle = aTitle; }
void SetServer( const String& aServer )
{ m_aServer = aServer; }
void SetAccount( const String& aAccount )
{ m_aAccount = aAccount; }
void SetUserName( const String& aUserName )
{ m_aUserName = aUserName; }
void SetPassword( const String& aPassword )
{ m_aPassword = aPassword; }
void SetPasswordToModify( const String& aPassword )
{ m_aPasswordToModify = aPassword; }
void SetRecommendToOpenReadonly( bool bVal )
{ m_bRecommendToOpenReadonly = bVal; }
void SetPath( const String& aPath )
{ m_aPath = aPath; }
void SetErrorText( const String& aErrorText )
{ m_aErrorText = aErrorText; }
void SetFlags( BYTE nFlags )
{ m_nFlags = nFlags; }
inline void SetCanRememberPassword( BOOL bSet );
inline void SetIsRememberPassword( BOOL bSet );
inline void SetIsRememberPersistent( BOOL bSet );
inline void SetCanUseSystemCredentials( BOOL bSet );
inline void SetIsUseSystemCredentials( BOOL bSet );
inline void SetModifyAccount( BOOL bSet );
inline void SetModifyUserName( BOOL bSet );
void SetResult( USHORT nRet )
{ m_nRet = nRet; }
};
inline void LoginErrorInfo::SetCanRememberPassword( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD;
else
m_nFlags &= ~LOGINERROR_FLAG_CAN_REMEMBER_PASSWORD;
}
inline void LoginErrorInfo::SetIsRememberPassword( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_IS_REMEMBER_PASSWORD;
else
m_nFlags &= ~LOGINERROR_FLAG_IS_REMEMBER_PASSWORD;
}
inline void LoginErrorInfo::SetIsRememberPersistent( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_REMEMBER_PERSISTENT;
else
m_nFlags &= ~LOGINERROR_FLAG_REMEMBER_PERSISTENT;
}
inline void LoginErrorInfo::SetCanUseSystemCredentials( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_CAN_USE_SYSCREDS;
else
m_nFlags &= ~LOGINERROR_FLAG_CAN_USE_SYSCREDS;
}
inline void LoginErrorInfo::SetIsUseSystemCredentials( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_IS_USE_SYSCREDS;
else
m_nFlags &= ~LOGINERROR_FLAG_IS_USE_SYSCREDS;
}
inline void LoginErrorInfo::SetModifyAccount( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_MODIFY_ACCOUNT;
else
m_nFlags &= ~LOGINERROR_FLAG_MODIFY_ACCOUNT;
}
inline void LoginErrorInfo::SetModifyUserName( BOOL bSet )
{
if ( bSet )
m_nFlags |= LOGINERROR_FLAG_MODIFY_USER_NAME;
else
m_nFlags &= ~LOGINERROR_FLAG_MODIFY_USER_NAME;
}
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <cppu/macros.hxx>
#include <cppuhelper/factory.hxx>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <uno/environment.h>
#include "requeststringresolver.hxx"
#include "passwordcontainer.hxx"
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;
extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL uui_component_getFactory(sal_Char const * pImplName,
void * pServiceManager,
void *)
{
if (!pImplName)
return 0;
void * pRet = 0;
Reference< XMultiServiceFactory > xSMgr(
reinterpret_cast< XMultiServiceFactory * >( pServiceManager ) );
Reference< XSingleServiceFactory > xFactory;
// UUI Interaction Request String Resolver.
if ( rtl_str_compare(pImplName,
UUIInteractionRequestStringResolver::m_aImplementationName)
== 0)
{
xFactory =
cppu::createSingleFactory(
static_cast< XMultiServiceFactory * >(pServiceManager),
OUString::createFromAscii(
UUIInteractionRequestStringResolver::m_aImplementationName),
&UUIInteractionRequestStringResolver::createInstance,
UUIInteractionRequestStringResolver::getSupportedServiceNames_static());
}
// UUI Password Container Interaction Handler.
else if ( uui::PasswordContainerInteractionHandler::getImplementationName_Static().
equalsAscii( pImplName ) )
{
xFactory =
uui::PasswordContainerInteractionHandler::createServiceFactory( xSMgr );
}
if ( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Reduce to static_cast any reinterpret_cast from void pointers<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <cppu/macros.hxx>
#include <cppuhelper/factory.hxx>
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <uno/environment.h>
#include "requeststringresolver.hxx"
#include "passwordcontainer.hxx"
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::registry;
extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL uui_component_getFactory(sal_Char const * pImplName,
void * pServiceManager,
void *)
{
if (!pImplName)
return 0;
void * pRet = 0;
Reference< XMultiServiceFactory > xSMgr(
static_cast< XMultiServiceFactory * >( pServiceManager ) );
Reference< XSingleServiceFactory > xFactory;
// UUI Interaction Request String Resolver.
if ( rtl_str_compare(pImplName,
UUIInteractionRequestStringResolver::m_aImplementationName)
== 0)
{
xFactory =
cppu::createSingleFactory(
static_cast< XMultiServiceFactory * >(pServiceManager),
OUString::createFromAscii(
UUIInteractionRequestStringResolver::m_aImplementationName),
&UUIInteractionRequestStringResolver::createInstance,
UUIInteractionRequestStringResolver::getSupportedServiceNames_static());
}
// UUI Password Container Interaction Handler.
else if ( uui::PasswordContainerInteractionHandler::getImplementationName_Static().
equalsAscii( pImplName ) )
{
xFactory =
uui::PasswordContainerInteractionHandler::createServiceFactory( xSMgr );
}
if ( xFactory.is() )
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <iterator>
#include <chrono>
#include "Address.h"
#include "DimAddress.h"
#include "MediatedCube.h"
#include "Mercator.h"
#include "MemoryUtil.h"
/*
* Cat the contents of the brightkite data into this (skip the header please).
*/
using namespace std;
vector<string> split(string s, char c) {
vector<string> pieces;
size_t start = 0;
size_t end = 0;
while(end <= s.size()) {
if(end == s.size() || s[end] == c) {
pieces.push_back(s.substr(start, end - start));
start = end = end + 1;
} else {
end += 1;
}
}
return pieces;
}
string to_b(uint32_t x) {
string s;
while(x > 0) {
s = to_string(x % 2) + s;
x /= 2;
}
return s;
}
void mem_info() {
memory_util::MemInfo m = memory_util::MemInfo::get();
stringstream ss;
ss << "Memory (MB): " << m.res_MB();
return ss.str();
}
int main() {
MediatedCube m;
Address all({ DimAddress(""), DimAddress(""), DimAddress("") });
cout << mem_info() << endl;
auto start = chrono::high_resolution_clock::now();
string line;
size_t count = 0;
while(getline(cin, line)) {
auto pieces = split(line, ',');
string lat = to_b(util::lat2tiley(stof(pieces[2]), 25));
string lon = to_b(util::lon2tilex(stof(pieces[3]), 25));
string month = to_b(stoi(split(pieces[1], '-')[1]));
m.add(Address({ DimAddress(lat), DimAddress(lon), DimAddress(month) }), 1);
if((count + 1) % 100 == 0) {
auto summary = m.size_summary();
cout << "Count = " << count + 1
<< ", Cube reports table sizes "
<< "(" << get<0>(summary) << ", " << get<1>(summary) << ")"
<< ", " << mem_info() << endl;
}
count++;
}
auto end = chrono::high_resolution_clock::now();
auto duration = (end - start).count();
cout << "Time: " << duration / 1000000000
<< "." << (duration / 1000000) % 1000 << endl;
cout << mem_info() << endl;
return 0;
}
<commit_msg>Some day, I'll even make before I commit<commit_after>#include <iostream>
#include <string>
#include <iterator>
#include <chrono>
#include "Address.h"
#include "DimAddress.h"
#include "MediatedCube.h"
#include "Mercator.h"
#include "MemoryUtil.h"
/*
* Cat the contents of the brightkite data into this (skip the header please).
*/
using namespace std;
vector<string> split(string s, char c) {
vector<string> pieces;
size_t start = 0;
size_t end = 0;
while(end <= s.size()) {
if(end == s.size() || s[end] == c) {
pieces.push_back(s.substr(start, end - start));
start = end = end + 1;
} else {
end += 1;
}
}
return pieces;
}
string to_b(uint32_t x) {
string s;
while(x > 0) {
s = to_string(x % 2) + s;
x /= 2;
}
return s;
}
string mem_info() {
memory_util::MemInfo m = memory_util::MemInfo::get();
stringstream ss;
ss << "Memory (MB): " << m.res_MB();
return ss.str();
}
int main() {
MediatedCube m;
Address all({ DimAddress(""), DimAddress(""), DimAddress("") });
cout << mem_info() << endl;
auto start = chrono::high_resolution_clock::now();
string line;
size_t count = 0;
while(getline(cin, line)) {
auto pieces = split(line, ',');
string lat = to_b(util::lat2tiley(stof(pieces[2]), 25));
string lon = to_b(util::lon2tilex(stof(pieces[3]), 25));
string month = to_b(stoi(split(pieces[1], '-')[1]));
m.add(Address({ DimAddress(lat), DimAddress(lon), DimAddress(month) }), 1);
if((count + 1) % 100 == 0) {
auto summary = m.size_summary();
cout << "Count = " << count + 1
<< ", Cube reports table sizes "
<< "(" << get<0>(summary) << ", " << get<1>(summary) << ")"
<< ", " << mem_info() << endl;
}
count++;
}
auto end = chrono::high_resolution_clock::now();
auto duration = (end - start).count();
cout << "Time: " << duration / 1000000000
<< "." << (duration / 1000000) % 1000 << endl;
cout << mem_info() << endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/cached_log.h"
namespace operations_research {
CachedLog::CachedLog() {}
CachedLog::~CachedLog() {}
namespace {
double FastLog2(int64 input) {
#if defined(_MSC_VER)
return log(static_cast<double>(input)) / log(2.0L);
#else
return log2(input);
#endif
}
}
void CachedLog::Init(int size) {
CHECK(cache_.empty());
CHECK_GT(size, 0);
cache_.resize(size, 0.0);
for (int i = 0; i < size; ++i) {
cache_[i] = FastLog2(i + 1);
}
}
double CachedLog::Log2(int64 input) const {
CHECK_GE(input, 1);
if (input <= cache_.size()) {
return cache_[input - 1];
} else {
return FastLog2(input);
}
}
} // namespace operations_research
<commit_msg>sync with generated code<commit_after>// Copyright 2010 Google
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "util/cached_log.h"
namespace operations_research {
CachedLog::CachedLog() {}
CachedLog::~CachedLog() {}
namespace {
double FastLog2(int64 input) {
#if defined(_MSC_VER)
return log(static_cast<double>(input)) / log(2.0L);
#else
return log2(input);
#endif
}
}
void CachedLog::Init(int size) {
CHECK(cache_.empty());
CHECK_GT(size, 0);
cache_.resize(size, 0.0);
for (int i = 0; i < size; ++i) {
cache_[i] = FastLog2(i + 1);
}
}
double CachedLog::Log2(int64 input) const {
CHECK_GE(input, 1);
if (input <= cache_.size()) {
return cache_[input - 1];
} else {
return FastLog2(input);
}
}
} // namespace operations_research
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2012 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <znc/Buffer.h>
#include <znc/znc.h>
#include <znc/Client.h>
#include <znc/User.h>
CBufLine::CBufLine(const CString& sFormat, const CString& sText, time_t tm) {
m_sFormat = sFormat;
m_sText = sText;
if (tm == 0)
UpdateTime();
else
m_tm = tm;
}
CBufLine::~CBufLine() {}
CString CBufLine::GetLine(const CClient& Client, const MCString& msParams) const {
MCString msThisParams = msParams;
if (Client.HasServerTime()) {
msThisParams["text"] = m_sText;
CString sStr = CString::NamedFormat(m_sFormat, msThisParams);
return "@" + CString(m_tm) + " " + sStr;
} else {
msThisParams["text"] = Client.GetUser()->AddTimestamp(m_tm, m_sText);
return CString::NamedFormat(m_sFormat, msThisParams);
}
}
CBuffer::CBuffer(unsigned int uLineCount) {
m_uLineCount = uLineCount;
}
CBuffer::~CBuffer() {}
int CBuffer::AddLine(const CString& sFormat, const CString& sText, time_t tm) {
if (!m_uLineCount) {
return 0;
}
while (size() >= m_uLineCount) {
erase(begin());
}
push_back(CBufLine(sFormat, sText, tm));
return size();
}
int CBuffer::UpdateLine(const CString& sMatch, const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat().compare(0, sMatch.length(), sMatch) == 0) {
it->SetFormat(sFormat);
it->SetText(sText);
it->UpdateTime();
return size();
}
}
return AddLine(sFormat, sText);
}
int CBuffer::UpdateExactLine(const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat() == sFormat && it->GetText() == sText) {
return size();
}
}
return AddLine(sFormat, sText);
}
const CBufLine& CBuffer::GetBufLine(unsigned int uIdx) const {
return (*this)[uIdx];
}
CString CBuffer::GetLine(unsigned int uIdx, const CClient& Client, const MCString& msParams) const {
return (*this)[uIdx].GetLine(Client, msParams);
}
bool CBuffer::SetLineCount(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) {
return false;
}
m_uLineCount = u;
// We may need to shrink the buffer if the allowed size got smaller
while (size() > m_uLineCount) {
erase(begin());
}
return true;
}
<commit_msg>Use @t=time instead of @time for server-time capability.<commit_after>/*
* Copyright (C) 2004-2012 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <znc/Buffer.h>
#include <znc/znc.h>
#include <znc/Client.h>
#include <znc/User.h>
CBufLine::CBufLine(const CString& sFormat, const CString& sText, time_t tm) {
m_sFormat = sFormat;
m_sText = sText;
if (tm == 0)
UpdateTime();
else
m_tm = tm;
}
CBufLine::~CBufLine() {}
CString CBufLine::GetLine(const CClient& Client, const MCString& msParams) const {
MCString msThisParams = msParams;
if (Client.HasServerTime()) {
msThisParams["text"] = m_sText;
CString sStr = CString::NamedFormat(m_sFormat, msThisParams);
return "@t=" + CString(m_tm) + " " + sStr;
} else {
msThisParams["text"] = Client.GetUser()->AddTimestamp(m_tm, m_sText);
return CString::NamedFormat(m_sFormat, msThisParams);
}
}
CBuffer::CBuffer(unsigned int uLineCount) {
m_uLineCount = uLineCount;
}
CBuffer::~CBuffer() {}
int CBuffer::AddLine(const CString& sFormat, const CString& sText, time_t tm) {
if (!m_uLineCount) {
return 0;
}
while (size() >= m_uLineCount) {
erase(begin());
}
push_back(CBufLine(sFormat, sText, tm));
return size();
}
int CBuffer::UpdateLine(const CString& sMatch, const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat().compare(0, sMatch.length(), sMatch) == 0) {
it->SetFormat(sFormat);
it->SetText(sText);
it->UpdateTime();
return size();
}
}
return AddLine(sFormat, sText);
}
int CBuffer::UpdateExactLine(const CString& sFormat, const CString& sText) {
for (iterator it = begin(); it != end(); ++it) {
if (it->GetFormat() == sFormat && it->GetText() == sText) {
return size();
}
}
return AddLine(sFormat, sText);
}
const CBufLine& CBuffer::GetBufLine(unsigned int uIdx) const {
return (*this)[uIdx];
}
CString CBuffer::GetLine(unsigned int uIdx, const CClient& Client, const MCString& msParams) const {
return (*this)[uIdx].GetLine(Client, msParams);
}
bool CBuffer::SetLineCount(unsigned int u, bool bForce) {
if (!bForce && u > CZNC::Get().GetMaxBufferSize()) {
return false;
}
m_uLineCount = u;
// We may need to shrink the buffer if the allowed size got smaller
while (size() > m_uLineCount) {
erase(begin());
}
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: conditio.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2008-01-10 13:08:13 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_CONDITIO_HXX
#define SC_CONDITIO_HXX
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
class ScBaseCell;
class ScFormulaCell;
class ScTokenArray;
class ScMultipleReadHeader;
class ScMultipleWriteHeader;
class ScRangeList;
#define SC_COND_GROW 16
// nOptions Flags
#define SC_COND_NOBLANKS 1
// Reihenfolge von ScConditionMode wie ScQueryOp,
// damit einmal zusammengefasst werden kann:
enum ScConditionMode
{
SC_COND_EQUAL,
SC_COND_LESS,
SC_COND_GREATER,
SC_COND_EQLESS,
SC_COND_EQGREATER,
SC_COND_NOTEQUAL,
SC_COND_BETWEEN,
SC_COND_NOTBETWEEN,
SC_COND_DIRECT,
SC_COND_NONE
};
enum ScConditionValType
{
SC_VAL_VALUE,
SC_VAL_STRING,
SC_VAL_FORMULA
};
class ScConditionEntry
{
// gespeicherte Daten:
ScConditionMode eOp;
USHORT nOptions;
double nVal1; // eingegeben oder berechnet
double nVal2;
String aStrVal1; // eingegeben oder berechnet
String aStrVal2;
BOOL bIsStr1; // um auch leere Strings zu erkennen
BOOL bIsStr2;
ScTokenArray* pFormula1; // eingegebene Formel
ScTokenArray* pFormula2;
ScAddress aSrcPos; // source position for formulas
// temporary data:
String aSrcString; // formula source position as text during XML import
ScFormulaCell* pFCell1;
ScFormulaCell* pFCell2;
ScDocument* pDoc;
BOOL bRelRef1;
BOOL bRelRef2;
BOOL bFirstRun;
void MakeCells( const ScAddress& rPos );
void Compile( const String& rExpr1, const String& rExpr2, BOOL bEnglish,
BOOL bCompileXML, BOOL bTextToReal );
void Interpret( const ScAddress& rPos );
BOOL IsValid( double nArg ) const;
BOOL IsValidStr( const String& rArg ) const;
protected:
ScConditionEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
void StoreCondition(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
public:
ScConditionEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
BOOL bCompileEnglish, BOOL bCompileXML );
ScConditionEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos );
ScConditionEntry( const ScConditionEntry& r ); // flache Kopie der Formeln
// echte Kopie der Formeln (fuer Ref-Undo):
ScConditionEntry( ScDocument* pDocument, const ScConditionEntry& r );
virtual ~ScConditionEntry();
int operator== ( const ScConditionEntry& r ) const;
BOOL IsCellValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
ScConditionMode GetOperation() const { return eOp; }
BOOL IsIgnoreBlank() const { return ( nOptions & SC_COND_NOBLANKS ) == 0; }
void SetIgnoreBlank(BOOL bSet);
ScAddress GetSrcPos() const { return aSrcPos; }
ScAddress GetValidSrcPos() const; // adjusted to allow textual representation of expressions
void SetSrcString( const String& rNew ); // for XML import
void SetFormula1( const ScTokenArray& rArray );
void SetFormula2( const ScTokenArray& rArray );
String GetExpression( const ScAddress& rCursor, USHORT nPos, ULONG nNumFmt = 0,
BOOL bEnglish = FALSE, BOOL bCompileXML = FALSE,
BOOL bTextToReal = FALSE ) const;
ScTokenArray* CreateTokenArry( USHORT nPos ) const;
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rChanged );
protected:
virtual void DataChanged( const ScRange* pModified ) const;
ScDocument* GetDocument() const { return pDoc; }
};
//
// einzelner Eintrag fuer bedingte Formatierung
//
class ScConditionalFormat;
class ScCondFormatEntry : public ScConditionEntry
{
String aStyleName;
ScConditionalFormat* pParent;
using ScConditionEntry::operator==;
public:
ScCondFormatEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle,
BOOL bCompileEnglish = FALSE, BOOL bCompileXML = FALSE );
ScCondFormatEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle );
ScCondFormatEntry( const ScCondFormatEntry& r );
ScCondFormatEntry( ScDocument* pDocument, const ScCondFormatEntry& r );
ScCondFormatEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
virtual ~ScCondFormatEntry();
void SetParent( ScConditionalFormat* pNew ) { pParent = pNew; }
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
int operator== ( const ScCondFormatEntry& r ) const;
const String& GetStyle() const { return aStyleName; }
protected:
virtual void DataChanged( const ScRange* pModified ) const;
};
//
// komplette bedingte Formatierung
//
class ScConditionalFormat
{
ScDocument* pDoc;
ScRangeList* pAreas; // Bereiche fuer Paint
sal_uInt32 nKey; // Index in Attributen
ScCondFormatEntry** ppEntries;
USHORT nEntryCount;
BOOL bIsUsed; // temporaer beim Speichern
public:
ScConditionalFormat(sal_uInt32 nNewKey, ScDocument* pDocument);
ScConditionalFormat(const ScConditionalFormat& r);
ScConditionalFormat(SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument);
~ScConditionalFormat();
// echte Kopie der Formeln (fuer Ref-Undo / zwischen Dokumenten)
ScConditionalFormat* Clone(ScDocument* pNewDoc = NULL) const;
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
void AddEntry( const ScCondFormatEntry& rNew );
BOOL IsEmpty() const { return (nEntryCount == 0); }
USHORT Count() const { return nEntryCount; }
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
const ScCondFormatEntry* GetEntry( USHORT nPos ) const;
const String& GetCellStyle( ScBaseCell* pCell, const ScAddress& rPos ) const;
BOOL EqualEntries( const ScConditionalFormat& r ) const;
void DoRepaint( const ScRange* pModified );
void InvalidateArea();
sal_uInt32 GetKey() const { return nKey; }
void SetKey(sal_uInt32 nNew) { nKey = nNew; } // nur wenn nicht eingefuegt!
void SetUsed(BOOL bSet) { bIsUsed = bSet; }
BOOL IsUsed() const { return bIsUsed; }
// sortiert (per PTRARR) nach Index
// operator== nur fuer die Sortierung
BOOL operator ==( const ScConditionalFormat& r ) const { return nKey == r.nKey; }
BOOL operator < ( const ScConditionalFormat& r ) const { return nKey < r.nKey; }
};
//
// Liste der Bereiche und Formate:
//
typedef ScConditionalFormat* ScConditionalFormatPtr;
SV_DECL_PTRARR_SORT(ScConditionalFormats_Impl, ScConditionalFormatPtr,
SC_COND_GROW, SC_COND_GROW)
class ScConditionalFormatList : public ScConditionalFormats_Impl
{
public:
ScConditionalFormatList() {}
ScConditionalFormatList(const ScConditionalFormatList& rList);
ScConditionalFormatList(ScDocument* pNewDoc, const ScConditionalFormatList& rList);
~ScConditionalFormatList() {}
void InsertNew( ScConditionalFormat* pNew )
{ if (!Insert(pNew)) delete pNew; }
ScConditionalFormat* GetFormat( sal_uInt32 nKey );
void Load( SvStream& rStream, ScDocument* pDocument );
void Store( SvStream& rStream ) const;
void ResetUsed();
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
BOOL operator==( const ScConditionalFormatList& r ) const; // fuer Ref-Undo
};
#endif
<commit_msg>INTEGRATION: CWS odff (1.10.158); FILE MERGED 2008/02/15 14:23:03 er 1.10.158.4: #i81063# grammar here, grammar there, grammar everywhere 2008/02/07 19:37:07 er 1.10.158.3: #i81063# introduce StorageGrammar per document 2008/01/21 18:50:53 er 1.10.158.2: RESYNC: (1.10-1.11); FILE MERGED 2007/09/06 10:43:07 er 1.10.158.1: #i81063# new ScGrammar; get rid of SetCompileEnglish, SetCompileXML, GetEnglishFormula, ...<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: conditio.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2008-03-06 15:15:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SC_CONDITIO_HXX
#define SC_CONDITIO_HXX
#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef SC_GRAMMAR_HXX
#include "grammar.hxx"
#endif
#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif
class ScBaseCell;
class ScFormulaCell;
class ScTokenArray;
class ScMultipleReadHeader;
class ScMultipleWriteHeader;
class ScRangeList;
#define SC_COND_GROW 16
// nOptions Flags
#define SC_COND_NOBLANKS 1
// Reihenfolge von ScConditionMode wie ScQueryOp,
// damit einmal zusammengefasst werden kann:
enum ScConditionMode
{
SC_COND_EQUAL,
SC_COND_LESS,
SC_COND_GREATER,
SC_COND_EQLESS,
SC_COND_EQGREATER,
SC_COND_NOTEQUAL,
SC_COND_BETWEEN,
SC_COND_NOTBETWEEN,
SC_COND_DIRECT,
SC_COND_NONE
};
enum ScConditionValType
{
SC_VAL_VALUE,
SC_VAL_STRING,
SC_VAL_FORMULA
};
class ScConditionEntry
{
// gespeicherte Daten:
ScConditionMode eOp;
USHORT nOptions;
double nVal1; // eingegeben oder berechnet
double nVal2;
String aStrVal1; // eingegeben oder berechnet
String aStrVal2;
ScGrammar::Grammar eTempGrammar; // grammar to be used on (re)compilation, e.g. in XML import
BOOL bIsStr1; // um auch leere Strings zu erkennen
BOOL bIsStr2;
ScTokenArray* pFormula1; // eingegebene Formel
ScTokenArray* pFormula2;
ScAddress aSrcPos; // source position for formulas
// temporary data:
String aSrcString; // formula source position as text during XML import
ScFormulaCell* pFCell1;
ScFormulaCell* pFCell2;
ScDocument* pDoc;
BOOL bRelRef1;
BOOL bRelRef2;
BOOL bFirstRun;
void MakeCells( const ScAddress& rPos );
void Compile( const String& rExpr1, const String& rExpr2,
const ScGrammar::Grammar eGrammar, BOOL bTextToReal );
void Interpret( const ScAddress& rPos );
BOOL IsValid( double nArg ) const;
BOOL IsValidStr( const String& rArg ) const;
protected:
ScConditionEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
void StoreCondition(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
public:
ScConditionEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
const ScGrammar::Grammar eGrammar );
ScConditionEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos );
ScConditionEntry( const ScConditionEntry& r ); // flache Kopie der Formeln
// echte Kopie der Formeln (fuer Ref-Undo):
ScConditionEntry( ScDocument* pDocument, const ScConditionEntry& r );
virtual ~ScConditionEntry();
int operator== ( const ScConditionEntry& r ) const;
BOOL IsCellValid( ScBaseCell* pCell, const ScAddress& rPos ) const;
ScConditionMode GetOperation() const { return eOp; }
BOOL IsIgnoreBlank() const { return ( nOptions & SC_COND_NOBLANKS ) == 0; }
void SetIgnoreBlank(BOOL bSet);
ScAddress GetSrcPos() const { return aSrcPos; }
ScAddress GetValidSrcPos() const; // adjusted to allow textual representation of expressions
void SetSrcString( const String& rNew ); // for XML import
void SetFormula1( const ScTokenArray& rArray );
void SetFormula2( const ScTokenArray& rArray );
String GetExpression( const ScAddress& rCursor, USHORT nPos, ULONG nNumFmt = 0,
const ScGrammar::Grammar eGrammar = ScGrammar::GRAM_DEFAULT ) const;
ScTokenArray* CreateTokenArry( USHORT nPos ) const;
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rChanged );
protected:
virtual void DataChanged( const ScRange* pModified ) const;
ScDocument* GetDocument() const { return pDoc; }
};
//
// einzelner Eintrag fuer bedingte Formatierung
//
class ScConditionalFormat;
class ScCondFormatEntry : public ScConditionEntry
{
String aStyleName;
ScConditionalFormat* pParent;
using ScConditionEntry::operator==;
public:
ScCondFormatEntry( ScConditionMode eOper,
const String& rExpr1, const String& rExpr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle,
const ScGrammar::Grammar eGrammar = ScGrammar::GRAM_DEFAULT );
ScCondFormatEntry( ScConditionMode eOper,
const ScTokenArray* pArr1, const ScTokenArray* pArr2,
ScDocument* pDocument, const ScAddress& rPos,
const String& rStyle );
ScCondFormatEntry( const ScCondFormatEntry& r );
ScCondFormatEntry( ScDocument* pDocument, const ScCondFormatEntry& r );
ScCondFormatEntry( SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument );
virtual ~ScCondFormatEntry();
void SetParent( ScConditionalFormat* pNew ) { pParent = pNew; }
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
int operator== ( const ScCondFormatEntry& r ) const;
const String& GetStyle() const { return aStyleName; }
protected:
virtual void DataChanged( const ScRange* pModified ) const;
};
//
// komplette bedingte Formatierung
//
class ScConditionalFormat
{
ScDocument* pDoc;
ScRangeList* pAreas; // Bereiche fuer Paint
sal_uInt32 nKey; // Index in Attributen
ScCondFormatEntry** ppEntries;
USHORT nEntryCount;
BOOL bIsUsed; // temporaer beim Speichern
public:
ScConditionalFormat(sal_uInt32 nNewKey, ScDocument* pDocument);
ScConditionalFormat(const ScConditionalFormat& r);
ScConditionalFormat(SvStream& rStream, ScMultipleReadHeader& rHdr,
ScDocument* pDocument);
~ScConditionalFormat();
// echte Kopie der Formeln (fuer Ref-Undo / zwischen Dokumenten)
ScConditionalFormat* Clone(ScDocument* pNewDoc = NULL) const;
void Store(SvStream& rStream, ScMultipleWriteHeader& rHdr) const;
void AddEntry( const ScCondFormatEntry& rNew );
BOOL IsEmpty() const { return (nEntryCount == 0); }
USHORT Count() const { return nEntryCount; }
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
const ScCondFormatEntry* GetEntry( USHORT nPos ) const;
const String& GetCellStyle( ScBaseCell* pCell, const ScAddress& rPos ) const;
BOOL EqualEntries( const ScConditionalFormat& r ) const;
void DoRepaint( const ScRange* pModified );
void InvalidateArea();
sal_uInt32 GetKey() const { return nKey; }
void SetKey(sal_uInt32 nNew) { nKey = nNew; } // nur wenn nicht eingefuegt!
void SetUsed(BOOL bSet) { bIsUsed = bSet; }
BOOL IsUsed() const { return bIsUsed; }
// sortiert (per PTRARR) nach Index
// operator== nur fuer die Sortierung
BOOL operator ==( const ScConditionalFormat& r ) const { return nKey == r.nKey; }
BOOL operator < ( const ScConditionalFormat& r ) const { return nKey < r.nKey; }
};
//
// Liste der Bereiche und Formate:
//
typedef ScConditionalFormat* ScConditionalFormatPtr;
SV_DECL_PTRARR_SORT(ScConditionalFormats_Impl, ScConditionalFormatPtr,
SC_COND_GROW, SC_COND_GROW)
class ScConditionalFormatList : public ScConditionalFormats_Impl
{
public:
ScConditionalFormatList() {}
ScConditionalFormatList(const ScConditionalFormatList& rList);
ScConditionalFormatList(ScDocument* pNewDoc, const ScConditionalFormatList& rList);
~ScConditionalFormatList() {}
void InsertNew( ScConditionalFormat* pNew )
{ if (!Insert(pNew)) delete pNew; }
ScConditionalFormat* GetFormat( sal_uInt32 nKey );
void Load( SvStream& rStream, ScDocument* pDocument );
void Store( SvStream& rStream ) const;
void ResetUsed();
void CompileAll();
void CompileXML();
void UpdateReference( UpdateRefMode eUpdateRefMode,
const ScRange& rRange, SCsCOL nDx, SCsROW nDy, SCsTAB nDz );
void UpdateMoveTab( SCTAB nOldPos, SCTAB nNewPos );
void SourceChanged( const ScAddress& rAddr );
BOOL operator==( const ScConditionalFormatList& r ) const; // fuer Ref-Undo
};
#endif
<|endoftext|> |
<commit_before>#line 2 "quanta/core/object/object.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <quanta/core/config.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/memory.hpp>
#include <quanta/core/string/unmanaged_string.hpp>
#include <quanta/core/object/object.hpp>
namespace quanta {
/// Set type.
///
/// Returns true if type changed.
bool object::set_type(Object& obj, ObjectValueType const type) {
if (object::type(obj) == type) {
return false;
}
object::clear_value(obj);
internal::set_property(obj, Object::M_TYPE, 0, unsigned_cast(type));
if (type == ObjectValueType::null) {
internal::clear_property(obj, Object::M_VALUE_GUESS);
} else if (type == ObjectValueType::expression) {
object::clear_value_markers(obj);
object::clear_source(obj);
object::clear_tags(obj);
object::clear_quantity(obj);
}
return true;
}
/// Reset value to type default.
///
/// This does not clear children if the object is an expression.
void object::clear_value(Object& obj) {
auto& a = memory::default_allocator();
switch (object::type(obj)) {
case ObjectValueType::null:
break;
case ObjectValueType::boolean:
obj.value.boolean = false;
break;
case ObjectValueType::integer:
obj.value.numeric.integer = 0;
unmanaged_string::clear(obj.value.numeric.unit, a);
break;
case ObjectValueType::decimal:
obj.value.numeric.decimal = 0.0f;
unmanaged_string::clear(obj.value.numeric.unit, a);
break;
case ObjectValueType::string:
unmanaged_string::clear(obj.value.string, a);
break;
case ObjectValueType::expression:
break;
}
}
/// Copy an object.
void object::copy(Object& dst, Object const& src) {
auto& a = memory::default_allocator();
object::clear_value(dst);
dst.properties = src.properties;
dst.source = src.source;
dst.sub_source = src.sub_source;
unmanaged_string::set(dst.name, src.name, a);
switch (object::type(src)) {
case ObjectValueType::null:
break;
case ObjectValueType::boolean:
dst.value.boolean = src.value.boolean;
break;
case ObjectValueType::integer:
dst.value.numeric.integer = src.value.numeric.integer;
unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
break;
case ObjectValueType::decimal:
dst.value.numeric.decimal = src.value.numeric.decimal;
unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
break;
case ObjectValueType::string:
unmanaged_string::set(dst.value.string, src.value.string, a);
break;
case ObjectValueType::expression:
break;
}
array::copy(dst.tags, src.tags);
array::copy(dst.children, src.children);
if (object::has_quantity(src)) {
if (object::has_quantity(dst)) {
object::copy(*dst.quantity, *src.quantity);
} else {
dst.quantity = TOGO_CONSTRUCT(a, Object, *src.quantity);
}
}
}
/// Create quantity or clear existing quantity.
Object& object::make_quantity(Object& obj) {
if (object::has_quantity(obj)) {
object::clear(*obj.quantity);
} else {
obj.quantity = TOGO_CONSTRUCT_DEFAULT(memory::default_allocator(), Object);
}
return *obj.quantity;
}
/// Set to null and clear all properties.
void object::clear(Object& obj) {
object::clear_name(obj);
object::set_null(obj);
object::clear_value_markers(obj);
object::clear_source(obj);
object::clear_tags(obj);
object::clear_children(obj);
object::clear_quantity(obj);
}
IGEN_PRIVATE
Object const* object::find_impl(
Array<Object> const& collection,
StringRef const& name,
ObjectNameHash const name_hash
) {
if (name_hash == OBJECT_NAME_NULL || array::empty(collection)) {
return nullptr;
}
for (Object const& item : collection) {
if (name_hash == item.name.hash) {
#if defined(TOGO_DEBUG)
if (name.valid() && !string::compare_equal(name, object::name(item))) {
TOGO_LOG_DEBUGF(
"hashes matched, but names mismatched: '%.*s' != '%.*s' (lookup_name != name)\n",
name.size, name.data,
item.name.size, item.name.data
);
}
#else
(void)name;
#endif
return &item;
}
}
return nullptr;
}
/// Find tag by name.
Object* object::find_tag(Object& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return const_cast<Object*>(object::find_impl(obj.tags, name, name_hash));
}
/// Find tag by name.
Object const* object::find_tag(Object const& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return object::find_impl(obj.tags, name, name_hash);
}
/// Find tag by name hash.
Object* object::find_tag(Object& obj, ObjectNameHash const name_hash) {
return const_cast<Object*>(
object::find_impl(obj.tags, StringRef{}, name_hash)
);
}
/// Find tag by name hash.
Object const* object::find_tag(Object const& obj, ObjectNameHash const name_hash) {
return object::find_impl(obj.tags, StringRef{}, name_hash);
}
/// Find tag by name.
Object* object::find_child(Object& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return const_cast<Object*>(object::find_impl(obj.children, name, name_hash));
}
/// Find tag by name.
Object const* object::find_child(Object const& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return object::find_impl(obj.children, name, name_hash);
}
/// Find tag by name hash.
Object* object::find_child(Object& obj, ObjectNameHash const name_hash) {
return const_cast<Object*>(
object::find_impl(obj.children, StringRef{}, name_hash)
);
}
/// Find tag by name hash.
Object const* object::find_child(Object const& obj, ObjectNameHash const name_hash) {
return object::find_impl(obj.children, StringRef{}, name_hash);
}
} // namespace quanta
<commit_msg>lib/core/object/object: optionally copy children in copy().<commit_after>#line 2 "quanta/core/object/object.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/
#include <quanta/core/config.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/memory.hpp>
#include <quanta/core/string/unmanaged_string.hpp>
#include <quanta/core/object/object.hpp>
namespace quanta {
/// Set type.
///
/// Returns true if type changed.
bool object::set_type(Object& obj, ObjectValueType const type) {
if (object::type(obj) == type) {
return false;
}
object::clear_value(obj);
internal::set_property(obj, Object::M_TYPE, 0, unsigned_cast(type));
if (type == ObjectValueType::null) {
internal::clear_property(obj, Object::M_VALUE_GUESS);
} else if (type == ObjectValueType::expression) {
object::clear_value_markers(obj);
object::clear_source(obj);
object::clear_tags(obj);
object::clear_quantity(obj);
}
return true;
}
/// Reset value to type default.
///
/// This does not clear children if the object is an expression.
void object::clear_value(Object& obj) {
auto& a = memory::default_allocator();
switch (object::type(obj)) {
case ObjectValueType::null:
break;
case ObjectValueType::boolean:
obj.value.boolean = false;
break;
case ObjectValueType::integer:
obj.value.numeric.integer = 0;
unmanaged_string::clear(obj.value.numeric.unit, a);
break;
case ObjectValueType::decimal:
obj.value.numeric.decimal = 0.0f;
unmanaged_string::clear(obj.value.numeric.unit, a);
break;
case ObjectValueType::string:
unmanaged_string::clear(obj.value.string, a);
break;
case ObjectValueType::expression:
break;
}
}
/// Copy an object.
void object::copy(Object& dst, Object const& src, bool const children IGEN_DEFAULT(true)) {
auto& a = memory::default_allocator();
object::clear_value(dst);
dst.properties = src.properties;
dst.source = src.source;
dst.sub_source = src.sub_source;
unmanaged_string::set(dst.name, src.name, a);
switch (object::type(src)) {
case ObjectValueType::null:
break;
case ObjectValueType::boolean:
dst.value.boolean = src.value.boolean;
break;
case ObjectValueType::integer:
dst.value.numeric.integer = src.value.numeric.integer;
unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
break;
case ObjectValueType::decimal:
dst.value.numeric.decimal = src.value.numeric.decimal;
unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
break;
case ObjectValueType::string:
unmanaged_string::set(dst.value.string, src.value.string, a);
break;
case ObjectValueType::expression:
break;
}
array::copy(dst.tags, src.tags);
if (children) {
array::copy(dst.children, src.children);
}
if (object::has_quantity(src)) {
if (object::has_quantity(dst)) {
object::copy(*dst.quantity, *src.quantity);
} else {
dst.quantity = TOGO_CONSTRUCT(a, Object, *src.quantity);
}
}
}
/// Create quantity or clear existing quantity.
Object& object::make_quantity(Object& obj) {
if (object::has_quantity(obj)) {
object::clear(*obj.quantity);
} else {
obj.quantity = TOGO_CONSTRUCT_DEFAULT(memory::default_allocator(), Object);
}
return *obj.quantity;
}
/// Set to null and clear all properties.
void object::clear(Object& obj) {
object::clear_name(obj);
object::set_null(obj);
object::clear_value_markers(obj);
object::clear_source(obj);
object::clear_tags(obj);
object::clear_children(obj);
object::clear_quantity(obj);
}
IGEN_PRIVATE
Object const* object::find_impl(
Array<Object> const& collection,
StringRef const& name,
ObjectNameHash const name_hash
) {
if (name_hash == OBJECT_NAME_NULL || array::empty(collection)) {
return nullptr;
}
for (Object const& item : collection) {
if (name_hash == item.name.hash) {
#if defined(TOGO_DEBUG)
if (name.valid() && !string::compare_equal(name, object::name(item))) {
TOGO_LOG_DEBUGF(
"hashes matched, but names mismatched: '%.*s' != '%.*s' (lookup_name != name)\n",
name.size, name.data,
item.name.size, item.name.data
);
}
#else
(void)name;
#endif
return &item;
}
}
return nullptr;
}
/// Find tag by name.
Object* object::find_tag(Object& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return const_cast<Object*>(object::find_impl(obj.tags, name, name_hash));
}
/// Find tag by name.
Object const* object::find_tag(Object const& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return object::find_impl(obj.tags, name, name_hash);
}
/// Find tag by name hash.
Object* object::find_tag(Object& obj, ObjectNameHash const name_hash) {
return const_cast<Object*>(
object::find_impl(obj.tags, StringRef{}, name_hash)
);
}
/// Find tag by name hash.
Object const* object::find_tag(Object const& obj, ObjectNameHash const name_hash) {
return object::find_impl(obj.tags, StringRef{}, name_hash);
}
/// Find tag by name.
Object* object::find_child(Object& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return const_cast<Object*>(object::find_impl(obj.children, name, name_hash));
}
/// Find tag by name.
Object const* object::find_child(Object const& obj, StringRef const& name) {
ObjectNameHash const name_hash = object::hash_name(name);
return object::find_impl(obj.children, name, name_hash);
}
/// Find tag by name hash.
Object* object::find_child(Object& obj, ObjectNameHash const name_hash) {
return const_cast<Object*>(
object::find_impl(obj.children, StringRef{}, name_hash)
);
}
/// Find tag by name hash.
Object const* object::find_child(Object const& obj, ObjectNameHash const name_hash) {
return object::find_impl(obj.children, StringRef{}, name_hash);
}
} // namespace quanta
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <nfctag.h>
#include <QVariant>
#include <QtEndian>
#include "symbian/nearfieldutility_symbian.h"
#include "qnearfieldtagtype4_symbian_p.h"
QTM_BEGIN_NAMESPACE
static void OutputByteArray(const QByteArray& data)
{
for(int i = 0; i < data.count(); ++i)
{
LOG("data ["<<i<<"] = "<<((quint16)(data.at(i))));
}
}
QNearFieldTagType4Symbian::QNearFieldTagType4Symbian(CNearFieldNdefTarget *tag, QObject *parent)
: QNearFieldTagType4(parent), QNearFieldTagImpl(tag)
{
}
QNearFieldTagType4Symbian::~QNearFieldTagType4Symbian()
{
}
QByteArray QNearFieldTagType4Symbian::uid() const
{
return _uid();
}
quint8 QNearFieldTagType4Symbian::version()
{
BEGIN
quint8 result = 0;
QByteArray resp;
resp.append(char(0x90));
resp.append(char(0x00));
QNearFieldTarget::RequestId id = selectNdefApplication();
if (_waitForRequestCompletedNoSignal(id))
{
if (requestResponse(id).toByteArray().right(2) == resp)
{
// response is ok
// select cc
LOG("select cc");
QNearFieldTarget::RequestId id1 = selectCC();
if (_waitForRequestCompletedNoSignal(id1))
{
if (requestResponse(id1).toBool())
{
// response is ok
// read cc
LOG("read cc");
QNearFieldTarget::RequestId id2 = read(0x0001,0x0002);
if (_waitForRequestCompletedNoSignal(id2))
{
if (requestResponse(id2).toByteArray().right(2) == resp)
{
// response is ok
result = requestResponse(id2).toByteArray().at(0);
}
}
}
}
}
}
LOG("version is "<<result);
END
return result;
}
QVariant QNearFieldTagType4Symbian::decodeResponse(const QByteArray &command, const QByteArray &response)
{
BEGIN
QVariant result;
OutputByteArray(response);
if ((command.count() > 2) && (0x00 == command.at(0)))
{
if ( (0xA4 == command.at(1)) || (0xD6 == command.at(1)) )
{
if (response.count() >= 2)
{
LOG("select or write command");
QByteArray resp = response.right(2);
result = ((resp.at(0) == 0x90) && (resp.at(1) == 0x00));
}
}
else
{
LOG("read command");
result = response;
}
}
END
return result;
}
bool QNearFieldTagType4Symbian::hasNdefMessage()
{
BEGIN
QByteArray resp;
resp.append(char(0x90));
resp.append(char(0x00));
QNearFieldTarget::RequestId id = selectNdefApplication();
if (!_waitForRequestCompletedNoSignal(id))
{
LOG("select NDEF application failed");
END
return false;
}
if (!requestResponse(id).toBool())
{
LOG("select NDEF application response is not ok");
END
return false;
}
QNearFieldTarget::RequestId id1 = selectCC();
if (!_waitForRequestCompletedNoSignal(id1))
{
LOG("select CC failed");
END
return false;
}
if (!requestResponse(id1).toBool())
{
LOG("select CC response is not ok");
END
return false;
}
QNearFieldTarget::RequestId id2 = read(0x000F,0x0000);
if (!_waitForRequestCompletedNoSignal(id2))
{
LOG("read CC failed");
END
return false;
}
QByteArray ccContent = requestResponse(id2).toByteArray();
if (ccContent.right(2) != resp)
{
LOG("read CC response is "<<ccContent.right(2));
END
return false;
}
if ((ccContent.count() != (15 + 2)) && (ccContent.at(1) != 0x0F))
{
LOG("CC is invalid"<<ccContent);
END
return false;
}
quint8 temp = ccContent.at(9);
quint16 fileId = 0;
fileId |= temp;
fileId<<=8;
temp = ccContent.at(10);
fileId |= temp;
temp = ccContent.at(11);
quint16 maxNdefLen = 0;
maxNdefLen |= temp;
maxNdefLen<<=8;
temp = ccContent.at(12);
maxNdefLen |= temp;
QNearFieldTarget::RequestId id3 = select(fileId);
if (!_waitForRequestCompletedNoSignal(id3))
{
LOG("select NDEF failed");
END
return false;
}
if (!requestResponse(id3).toBool())
{
END
return false;
}
QNearFieldTarget::RequestId id4 = read(0x0002, 0x0000);
if (!_waitForRequestCompletedNoSignal(id4))
{
LOG("read NDEF failed");
END
return false;
}
QByteArray ndefContent = requestResponse(id4).toByteArray();
if (ndefContent.right(2) != resp)
{
LOG("read NDEF response is "<<ndefContent.right(2));
END
return false;
}
if (ndefContent.count() != (2 + 2))
{
LOG("ndef content invalid");
END
return false;
}
temp = ndefContent.at(0);
quint16 nLen = 0;
nLen |= temp;
nLen<<=8;
temp = ndefContent.at(1);
nLen |= temp;
END
return ( (nLen > 0) && (nLen < maxNdefLen -2) );
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::readNdefMessages()
{
return _ndefMessages();
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::writeNdefMessages(const QList<QNdefMessage> &messages)
{
return _setNdefMessages(messages);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::sendCommand(const QByteArray &command)
{
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::sendCommands(const QList<QByteArray> &commands)
{
return _sendCommands(commands);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::select(const QByteArray &name)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xA4)); // INS
command.append(char(0x04)); // P1, select by name
command.append(char(0x00)); // First or only occurrence
command.append(char(0x07)); // Lc
command.append(name);
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::select(quint16 fileIdentifier)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xA4)); // INS
command.append(char(0x00)); // P1, select by file identifier
command.append(char(0x00)); // First or only occurrence
command.append(char(0x02)); // Lc
quint16 temp = qToBigEndian<quint16>(fileIdentifier);
command.append(reinterpret_cast<const char*>(&temp),
sizeof(quint16));
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::read(quint16 length, quint16 startOffset)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xB0)); // INS
quint16 temp = qToBigEndian<quint16>(startOffset);
command.append(reinterpret_cast<const char*>(&temp),
sizeof(quint16)); // P1/P2 offset
/*temp = qToBigEndian<quint16>(length);
command.append(reinterpret_cast<const char*>(&temp),
sizeof(quint16)); // Le*/
command.append((quint8)length);
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::write(const QByteArray &data, quint16 startOffset)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xD6)); // INS
quint16 temp = qToBigEndian<quint16>(startOffset);
command.append(reinterpret_cast<const char *>(&temp), sizeof(quint16));
quint16 length = data.count();
if ((length > 0xFF) || (length < 0x01))
{
END
return QNearFieldTarget::RequestId();
}
else
{
/*quint16 temp = qToBigEndian<quint16>(length);
command.append(reinterpret_cast<const char *>(&temp),
sizeof(quint16));*/
command.append((quint8)length);
}
command.append(data);
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::selectNdefApplication()
{
BEGIN
QByteArray command;
command.append(char(0xD2));
command.append(char(0x76));
command.append(char(0x00));
command.append(char(0x00));
command.append(char(0x85));
command.append(char(0x01));
command.append(char(0x00));
QNearFieldTarget::RequestId id = select(command);
END
return id;
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::selectCC()
{
BEGIN
END
return select(0xe103);
}
void QNearFieldTagType4Symbian::handleTagOperationResponse(const RequestId &id, const QByteArray &command, const QByteArray &response, bool emitRequestCompleted)
{
BEGIN
Q_UNUSED(command);
QVariant decodedResponse = decodeResponse(command, response);
setResponseForRequest(id, decodedResponse, emitRequestCompleted);
END
}
bool QNearFieldTagType4Symbian::waitForRequestCompleted(const RequestId &id, int msecs)
{
BEGIN
END
return _waitForRequestCompleted(id, msecs);
}
#include "moc_qnearfieldtagtype4_symbian_p.cpp"
QTM_END_NAMESPACE
<commit_msg>Fix handling of type 4 tag specific command replies on Symbian<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <nfctag.h>
#include <QVariant>
#include <QtEndian>
#include "symbian/nearfieldutility_symbian.h"
#include "qnearfieldtagtype4_symbian_p.h"
QTM_BEGIN_NAMESPACE
static void OutputByteArray(const QByteArray& data)
{
for(int i = 0; i < data.count(); ++i)
{
LOG("data ["<<i<<"] = "<<((quint16)(data.at(i))));
}
}
QNearFieldTagType4Symbian::QNearFieldTagType4Symbian(CNearFieldNdefTarget *tag, QObject *parent)
: QNearFieldTagType4(parent), QNearFieldTagImpl(tag)
{
}
QNearFieldTagType4Symbian::~QNearFieldTagType4Symbian()
{
}
QByteArray QNearFieldTagType4Symbian::uid() const
{
return _uid();
}
quint8 QNearFieldTagType4Symbian::version()
{
BEGIN
quint8 result = 0;
QByteArray resp;
resp.append(char(0x90));
resp.append(char(0x00));
QNearFieldTarget::RequestId id = selectNdefApplication();
if (_waitForRequestCompletedNoSignal(id))
{
if (requestResponse(id).toByteArray().right(2) == resp)
{
// response is ok
// select cc
LOG("select cc");
QNearFieldTarget::RequestId id1 = selectCC();
if (_waitForRequestCompletedNoSignal(id1))
{
if (requestResponse(id1).toBool())
{
// response is ok
// read cc
LOG("read cc");
QNearFieldTarget::RequestId id2 = read(0x0001,0x0002);
if (_waitForRequestCompletedNoSignal(id2))
{
if (requestResponse(id2).toByteArray().right(2) == resp)
{
// response is ok
result = requestResponse(id2).toByteArray().at(0);
}
}
}
}
}
}
LOG("version is "<<result);
END
return result;
}
QVariant QNearFieldTagType4Symbian::decodeResponse(const QByteArray &command, const QByteArray &response)
{
BEGIN
QVariant result;
OutputByteArray(response);
if ((command.count() > 2) && (0x00 == command.at(0)))
{
if ( (0xA4 == command.at(1)) || (0xD6 == command.at(1)) )
{
if (response.count() >= 2)
{
LOG("select or write command");
QByteArray resp = response.right(2);
result = ((resp.at(0) == 0x90) && (resp.at(1) == 0x00));
}
}
else
{
LOG("read command");
result = response;
}
}
else
{
LOG("tag specific command");
result = response;
}
END
return result;
}
bool QNearFieldTagType4Symbian::hasNdefMessage()
{
BEGIN
QByteArray resp;
resp.append(char(0x90));
resp.append(char(0x00));
QNearFieldTarget::RequestId id = selectNdefApplication();
if (!_waitForRequestCompletedNoSignal(id))
{
LOG("select NDEF application failed");
END
return false;
}
if (!requestResponse(id).toBool())
{
LOG("select NDEF application response is not ok");
END
return false;
}
QNearFieldTarget::RequestId id1 = selectCC();
if (!_waitForRequestCompletedNoSignal(id1))
{
LOG("select CC failed");
END
return false;
}
if (!requestResponse(id1).toBool())
{
LOG("select CC response is not ok");
END
return false;
}
QNearFieldTarget::RequestId id2 = read(0x000F,0x0000);
if (!_waitForRequestCompletedNoSignal(id2))
{
LOG("read CC failed");
END
return false;
}
QByteArray ccContent = requestResponse(id2).toByteArray();
if (ccContent.right(2) != resp)
{
LOG("read CC response is "<<ccContent.right(2));
END
return false;
}
if ((ccContent.count() != (15 + 2)) && (ccContent.at(1) != 0x0F))
{
LOG("CC is invalid"<<ccContent);
END
return false;
}
quint8 temp = ccContent.at(9);
quint16 fileId = 0;
fileId |= temp;
fileId<<=8;
temp = ccContent.at(10);
fileId |= temp;
temp = ccContent.at(11);
quint16 maxNdefLen = 0;
maxNdefLen |= temp;
maxNdefLen<<=8;
temp = ccContent.at(12);
maxNdefLen |= temp;
QNearFieldTarget::RequestId id3 = select(fileId);
if (!_waitForRequestCompletedNoSignal(id3))
{
LOG("select NDEF failed");
END
return false;
}
if (!requestResponse(id3).toBool())
{
END
return false;
}
QNearFieldTarget::RequestId id4 = read(0x0002, 0x0000);
if (!_waitForRequestCompletedNoSignal(id4))
{
LOG("read NDEF failed");
END
return false;
}
QByteArray ndefContent = requestResponse(id4).toByteArray();
if (ndefContent.right(2) != resp)
{
LOG("read NDEF response is "<<ndefContent.right(2));
END
return false;
}
if (ndefContent.count() != (2 + 2))
{
LOG("ndef content invalid");
END
return false;
}
temp = ndefContent.at(0);
quint16 nLen = 0;
nLen |= temp;
nLen<<=8;
temp = ndefContent.at(1);
nLen |= temp;
END
return ( (nLen > 0) && (nLen < maxNdefLen -2) );
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::readNdefMessages()
{
return _ndefMessages();
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::writeNdefMessages(const QList<QNdefMessage> &messages)
{
return _setNdefMessages(messages);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::sendCommand(const QByteArray &command)
{
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::sendCommands(const QList<QByteArray> &commands)
{
return _sendCommands(commands);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::select(const QByteArray &name)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xA4)); // INS
command.append(char(0x04)); // P1, select by name
command.append(char(0x00)); // First or only occurrence
command.append(char(0x07)); // Lc
command.append(name);
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::select(quint16 fileIdentifier)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xA4)); // INS
command.append(char(0x00)); // P1, select by file identifier
command.append(char(0x00)); // First or only occurrence
command.append(char(0x02)); // Lc
quint16 temp = qToBigEndian<quint16>(fileIdentifier);
command.append(reinterpret_cast<const char*>(&temp),
sizeof(quint16));
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::read(quint16 length, quint16 startOffset)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xB0)); // INS
quint16 temp = qToBigEndian<quint16>(startOffset);
command.append(reinterpret_cast<const char*>(&temp),
sizeof(quint16)); // P1/P2 offset
/*temp = qToBigEndian<quint16>(length);
command.append(reinterpret_cast<const char*>(&temp),
sizeof(quint16)); // Le*/
command.append((quint8)length);
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::write(const QByteArray &data, quint16 startOffset)
{
BEGIN
QByteArray command;
command.append(char(0x00)); // CLA
command.append(char(0xD6)); // INS
quint16 temp = qToBigEndian<quint16>(startOffset);
command.append(reinterpret_cast<const char *>(&temp), sizeof(quint16));
quint16 length = data.count();
if ((length > 0xFF) || (length < 0x01))
{
END
return QNearFieldTarget::RequestId();
}
else
{
/*quint16 temp = qToBigEndian<quint16>(length);
command.append(reinterpret_cast<const char *>(&temp),
sizeof(quint16));*/
command.append((quint8)length);
}
command.append(data);
END
return _sendCommand(command);
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::selectNdefApplication()
{
BEGIN
QByteArray command;
command.append(char(0xD2));
command.append(char(0x76));
command.append(char(0x00));
command.append(char(0x00));
command.append(char(0x85));
command.append(char(0x01));
command.append(char(0x00));
QNearFieldTarget::RequestId id = select(command);
END
return id;
}
QNearFieldTarget::RequestId QNearFieldTagType4Symbian::selectCC()
{
BEGIN
END
return select(0xe103);
}
void QNearFieldTagType4Symbian::handleTagOperationResponse(const RequestId &id, const QByteArray &command, const QByteArray &response, bool emitRequestCompleted)
{
BEGIN
Q_UNUSED(command);
QVariant decodedResponse = decodeResponse(command, response);
setResponseForRequest(id, decodedResponse, emitRequestCompleted);
END
}
bool QNearFieldTagType4Symbian::waitForRequestCompleted(const RequestId &id, int msecs)
{
BEGIN
END
return _waitForRequestCompleted(id, msecs);
}
#include "moc_qnearfieldtagtype4_symbian_p.cpp"
QTM_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
* MacFileMonitor.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/FileMonitor.hpp>
#include <CoreServices/CoreServices.h>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <core/Log.hpp>
#include <core/Error.hpp>
#include <core/FileInfo.hpp>
#include <core/Thread.hpp>
#include <core/system/FileScanner.hpp>
#include <core/system/System.hpp>
#include "FileMonitorImpl.hpp"
namespace core {
namespace system {
namespace file_monitor {
namespace {
class FileEventContext : boost::noncopyable
{
public:
FileEventContext() : streamRef(NULL) {}
virtual ~FileEventContext() {}
FSEventStreamRef streamRef;
tree<FileInfo> fileTree;
Callbacks::FilesChanged onFilesChanged;
};
void fileEventCallback(ConstFSEventStreamRef streamRef,
void *pCallbackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
// get context
FileEventContext* pContext = (FileEventContext*)pCallbackInfo;
// bail if we don't have onFilesChanged (we wouldn't if a callback snuck
// through to us even after we failed to fully initialize the file monitor
// (e.g. if there was an error during file listing)
if (!pContext->onFilesChanged)
return;
char **paths = (char**)eventPaths;
for (std::size_t i=0; i<numEvents; i++)
{
// check for root changed (unregister)
if (eventFlags[i] & kFSEventStreamEventFlagRootChanged)
{
unregisterMonitor((Handle)pContext);
return;
}
// make a copy of the path and strip off trailing / if necessary
std::string path(paths[i]);
boost::algorithm::trim_right_if(path, boost::algorithm::is_any_of("/"));
// get FileInfo for this directory
FileInfo fileInfo(path, true);
// check for need to do recursive scan
bool recursive = eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs;
// process changes
Error error = impl::discoverAndProcessFileChanges(fileInfo,
recursive,
&(pContext->fileTree),
pContext->onFilesChanged);
if (error)
LOG_ERROR(error);
}
}
class CFRefScope : boost::noncopyable
{
public:
explicit CFRefScope(CFTypeRef ref)
: ref_(ref)
{
}
virtual ~CFRefScope()
{
try
{
::CFRelease(ref_);
}
catch(...)
{
}
}
private:
CFTypeRef ref_;
};
void invalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamInvalidate(streamRef);
::FSEventStreamRelease(streamRef);
}
void stopInvalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamStop(streamRef);
invalidateAndReleaseEventStream(streamRef);
}
} // anonymous namespace
namespace detail {
// register a new file monitor
Handle registerMonitor(const core::FilePath& filePath,
bool recursive,
const Callbacks& callbacks)
{
// allocate file path
std::string path = filePath.absolutePath();
CFStringRef filePathRef = ::CFStringCreateWithCString(
kCFAllocatorDefault,
filePath.absolutePath().c_str(),
kCFStringEncodingUTF8);
if (filePathRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return NULL;
}
CFRefScope filePathRefScope(filePathRef);
// allocate paths array
CFArrayRef pathsArrayRef = ::CFArrayCreate(kCFAllocatorDefault,
(const void **)&filePathRef,
1,
NULL);
if (pathsArrayRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return NULL;
}
CFRefScope pathsArrayRefScope(pathsArrayRef);
// create and allocate FileEventContext (create auto-ptr in case we
// return early, we'll call release later before returning)
FileEventContext* pContext = new FileEventContext();
std::auto_ptr<FileEventContext> autoPtrContext(pContext);
FSEventStreamContext context;
context.version = 0;
context.info = (void*) pContext;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
// create the stream and save a reference to it
pContext->streamRef = ::FSEventStreamCreate(
kCFAllocatorDefault,
&fileEventCallback,
&context,
pathsArrayRef,
kFSEventStreamEventIdSinceNow,
1,
kFSEventStreamCreateFlagNoDefer |
kFSEventStreamCreateFlagWatchRoot);
if (pContext->streamRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return NULL;
}
// schedule with the run loop
::FSEventStreamScheduleWithRunLoop(pContext->streamRef,
::CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
// start the event stream (check for errors and release if necessary
if (!::FSEventStreamStart(pContext->streamRef))
{
invalidateAndReleaseEventStream(pContext->streamRef);
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return NULL;
}
// scan the files
Error error = scanFiles(FileInfo(filePath), true, &pContext->fileTree);
if (error)
{
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// return error
callbacks.onRegistrationError(error);
return NULL;
}
// now that we have finished the file listing we know we have a valid
// file-monitor so set the onFilesChanged callback so that the
// client can receive events
pContext->onFilesChanged = callbacks.onFilesChanged;
// we are going to pass the context pointer to the client (as the Handle)
// so we release it here to relinquish ownership
autoPtrContext.release();
// notify the caller that we have successfully registered
callbacks.onRegistered((Handle)pContext, pContext->fileTree);
// return the handle
return (Handle)pContext;
}
// unregister a file monitor
void unregisterMonitor(Handle handle)
{
// cast to context
FileEventContext* pContext = (FileEventContext*)handle;
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// delete context
delete pContext;
}
void run(const boost::function<void()>& checkForInput)
{
// ensure we have a run loop for this thread (not sure if this is
// strictly necessary but it is not harmful)
::CFRunLoopGetCurrent();
while (true)
{
// process the run loop for 1 second
SInt32 reason = ::CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false);
if (reason == kCFRunLoopRunStopped)
{
LOG_WARNING_MESSAGE("Unexpected stop of file monitor run loop");
break;
}
// check for input
checkForInput();
}
}
void stop()
{
// nothing to do here (no global cleanup or waiting necessary on osx)
}
} // namespace detail
} // namespace file_monitor
} // namespace system
} // namespace core
<commit_msg>report error on osx if the root path goes away<commit_after>/*
* MacFileMonitor.cpp
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include <core/system/FileMonitor.hpp>
#include <CoreServices/CoreServices.h>
#include <boost/foreach.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <core/Log.hpp>
#include <core/Error.hpp>
#include <core/FileInfo.hpp>
#include <core/Thread.hpp>
#include <core/system/FileScanner.hpp>
#include <core/system/System.hpp>
#include "FileMonitorImpl.hpp"
namespace core {
namespace system {
namespace file_monitor {
namespace {
class FileEventContext : boost::noncopyable
{
public:
FileEventContext() : streamRef(NULL) {}
virtual ~FileEventContext() {}
FSEventStreamRef streamRef;
FilePath rootPath;
tree<FileInfo> fileTree;
Callbacks::FilesChanged onFilesChanged;
Callbacks::ReportError onMonitoringError;
};
void fileEventCallback(ConstFSEventStreamRef streamRef,
void *pCallbackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
// get context
FileEventContext* pContext = (FileEventContext*)pCallbackInfo;
// bail if we don't have onFilesChanged (we wouldn't if a callback snuck
// through to us even after we failed to fully initialize the file monitor
// (e.g. if there was an error during file listing)
if (!pContext->onFilesChanged)
return;
char **paths = (char**)eventPaths;
for (std::size_t i=0; i<numEvents; i++)
{
// check for root changed (unregister)
if (eventFlags[i] & kFSEventStreamEventFlagRootChanged)
{
Error error = fileNotFoundError(pContext->rootPath.absolutePath(),
ERROR_LOCATION);
pContext->onMonitoringError(error);
file_monitor::unregisterMonitor((Handle)pContext);
return;
}
// make a copy of the path and strip off trailing / if necessary
std::string path(paths[i]);
boost::algorithm::trim_right_if(path, boost::algorithm::is_any_of("/"));
// get FileInfo for this directory
FileInfo fileInfo(path, true);
// check for need to do recursive scan
bool recursive = eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs;
// process changes
Error error = impl::discoverAndProcessFileChanges(fileInfo,
recursive,
&(pContext->fileTree),
pContext->onFilesChanged);
if (error)
LOG_ERROR(error);
}
}
class CFRefScope : boost::noncopyable
{
public:
explicit CFRefScope(CFTypeRef ref)
: ref_(ref)
{
}
virtual ~CFRefScope()
{
try
{
::CFRelease(ref_);
}
catch(...)
{
}
}
private:
CFTypeRef ref_;
};
void invalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamInvalidate(streamRef);
::FSEventStreamRelease(streamRef);
}
void stopInvalidateAndReleaseEventStream(FSEventStreamRef streamRef)
{
::FSEventStreamStop(streamRef);
invalidateAndReleaseEventStream(streamRef);
}
} // anonymous namespace
namespace detail {
// register a new file monitor
Handle registerMonitor(const FilePath& filePath,
bool recursive,
const Callbacks& callbacks)
{
// allocate file path
std::string path = filePath.absolutePath();
CFStringRef filePathRef = ::CFStringCreateWithCString(
kCFAllocatorDefault,
filePath.absolutePath().c_str(),
kCFStringEncodingUTF8);
if (filePathRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return NULL;
}
CFRefScope filePathRefScope(filePathRef);
// allocate paths array
CFArrayRef pathsArrayRef = ::CFArrayCreate(kCFAllocatorDefault,
(const void **)&filePathRef,
1,
NULL);
if (pathsArrayRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::not_enough_memory,
ERROR_LOCATION));
return NULL;
}
CFRefScope pathsArrayRefScope(pathsArrayRef);
// create and allocate FileEventContext (create auto-ptr in case we
// return early, we'll call release later before returning)
FileEventContext* pContext = new FileEventContext();
pContext->rootPath = filePath;
std::auto_ptr<FileEventContext> autoPtrContext(pContext);
FSEventStreamContext context;
context.version = 0;
context.info = (void*) pContext;
context.retain = NULL;
context.release = NULL;
context.copyDescription = NULL;
// create the stream and save a reference to it
pContext->streamRef = ::FSEventStreamCreate(
kCFAllocatorDefault,
&fileEventCallback,
&context,
pathsArrayRef,
kFSEventStreamEventIdSinceNow,
1,
kFSEventStreamCreateFlagNoDefer |
kFSEventStreamCreateFlagWatchRoot);
if (pContext->streamRef == NULL)
{
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return NULL;
}
// schedule with the run loop
::FSEventStreamScheduleWithRunLoop(pContext->streamRef,
::CFRunLoopGetCurrent(),
kCFRunLoopDefaultMode);
// start the event stream (check for errors and release if necessary
if (!::FSEventStreamStart(pContext->streamRef))
{
invalidateAndReleaseEventStream(pContext->streamRef);
callbacks.onRegistrationError(systemError(
boost::system::errc::no_stream_resources,
ERROR_LOCATION));
return NULL;
}
// scan the files
Error error = scanFiles(FileInfo(filePath), true, &pContext->fileTree);
if (error)
{
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// return error
callbacks.onRegistrationError(error);
return NULL;
}
// now that we have finished the file listing we know we have a valid
// file-monitor so set the onFilesChanged callback so that the
// client can receive events
pContext->onFilesChanged = callbacks.onFilesChanged;
pContext->onMonitoringError = callbacks.onMonitoringError;
// we are going to pass the context pointer to the client (as the Handle)
// so we release it here to relinquish ownership
autoPtrContext.release();
// notify the caller that we have successfully registered
callbacks.onRegistered((Handle)pContext, pContext->fileTree);
// return the handle
return (Handle)pContext;
}
// unregister a file monitor
void unregisterMonitor(Handle handle)
{
// cast to context
FileEventContext* pContext = (FileEventContext*)handle;
// stop, invalidate, release
stopInvalidateAndReleaseEventStream(pContext->streamRef);
// delete context
delete pContext;
}
void run(const boost::function<void()>& checkForInput)
{
// ensure we have a run loop for this thread (not sure if this is
// strictly necessary but it is not harmful)
::CFRunLoopGetCurrent();
while (true)
{
// process the run loop for 1 second
SInt32 reason = ::CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1, false);
if (reason == kCFRunLoopRunStopped)
{
LOG_WARNING_MESSAGE("Unexpected stop of file monitor run loop");
break;
}
// check for input
checkForInput();
}
}
void stop()
{
// nothing to do here (no global cleanup or waiting necessary on osx)
}
} // namespace detail
} // namespace file_monitor
} // namespace system
} // namespace core
<|endoftext|> |
<commit_before>#include <iostream>
#include <seqan/index.h>
using namespace std;
using namespace seqan;
int main ()
{
///We begin with a @Class.StringSet@ that stores multiple strings.
StringSet< String<char> > mySet;
resize(mySet, 3);
mySet[0] = "SeqAn is a library for sequence analysis.";
mySet[1] = "The String class is the fundamental sequence type in SeqAn.";
mySet[2] = "Subsequences can be handled with SeqAn's Segment class.";
///Then we create an @Class.Index@ of this @Class.StringSet@.
typedef Index< StringSet<String<char> > > TMyIndex;
TMyIndex myIndex(mySet);
///To find maximal unique matches (MUMs), we use the @Spec.MUMs Iterator@
///and set the minimum MUM length to 3.
Iterator< TMyIndex, MUMs >::Type myMUMiterator(myIndex, 3);
String< SAValue<TMyIndex>::Type > occs;
while (!atEnd(myMUMiterator))
{
///A multiple match can be represented by positions it occurs at in every sequence
///and its length. @Function.getOccurrences@ returns an unordered sequence of pairs
///(seqNo,seqOfs) the match occurs at.
occs = getOccurrences(myMUMiterator);
///To order them ascending according seqNo we use @Function.orderOccurrences@.
orderOccurrences(occs);
for(unsigned i = 0; i < length(occs); ++i)
cout << getValueI2(occs[i]) << ", ";
///@Function.repLength@ returns the length of the match.
cout << repLength(myMUMiterator) << " ";
///The match string itself can be determined with @Function.representative@.
cout << "\t\"" << representative(myMUMiterator) << '\"' << endl;
++myMUMiterator;
}
return 0;
}
<commit_msg><commit_after>///A tutorial about finding MUMs.
#include <iostream>
#include <seqan/index.h>
using namespace seqan;
int main ()
{
///We begin with a @Class.StringSet@ that stores multiple strings.
StringSet< String<char> > mySet;
resize(mySet, 3);
mySet[0] = "SeqAn is a library for sequence analysis.";
mySet[1] = "The String class is the fundamental sequence type in SeqAn.";
mySet[2] = "Subsequences can be handled with SeqAn's Segment class.";
///Then we create an @Class.Index@ of this @Class.StringSet@.
typedef Index< StringSet<String<char> > > TMyIndex;
TMyIndex myIndex(mySet);
///To find maximal unique matches (MUMs), we use the @Spec.MUMs Iterator@
///and set the minimum MUM length to 3.
Iterator< TMyIndex, MUMs >::Type myMUMiterator(myIndex, 3);
String< SAValue<TMyIndex>::Type > occs;
while (!atEnd(myMUMiterator)) {
///A multiple match can be represented by the positions it occurs at in every sequence
///and its length. @Function.getOccurrences@ returns an unordered sequence of pairs
///(seqNo,seqOfs) the match occurs at.
occs = getOccurrences(myMUMiterator);
///To order them ascending according seqNo we use @Function.orderOccurrences@.
orderOccurrences(occs);
for(unsigned i = 0; i < length(occs); ++i)
::std::cout << getValueI2(occs[i]) << ", ";
///@Function.repLength@ returns the length of the match.
::std::cout << repLength(myMUMiterator) << " ";
///The match string itself can be determined with @Function.representative@.
::std::cout << "\t\"" << representative(myMUMiterator) << '\"' << ::std::endl;
++myMUMiterator;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
This file is part of libkdepim.
Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qevent.h>
#include <qlineedit.h>
#include <qapplication.h>
#include <qlistbox.h>
#include <kdatepicker.h>
#include <knotifyclient.h>
#include <kglobalsettings.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <kcalendarsystem.h>
#include "kdateedit.h"
#include "kdateedit.moc"
KDateEdit::KDateEdit(QWidget *parent, const char *name)
: QComboBox(true, parent, name),
defaultValue(QDate::currentDate()),
mReadOnly(false),
mDiscardNextMousePress(false)
{
setMaxCount(1); // need at least one entry for popup to work
value = defaultValue;
QString today = KGlobal::locale()->formatDate(value, true);
insertItem(today);
setCurrentItem(0);
changeItem(today, 0);
setMinimumSize(sizeHint());
mDateFrame = new QVBox(0,0,WType_Popup);
mDateFrame->setFrameStyle(QFrame::PopupPanel | QFrame::Raised);
mDateFrame->setLineWidth(3);
mDateFrame->hide();
mDateFrame->installEventFilter(this);
mDatePicker = new KDatePicker(mDateFrame, value);
connect(lineEdit(),SIGNAL(returnPressed()),SLOT(lineEnterPressed()));
connect(this,SIGNAL(textChanged(const QString &)),
SLOT(slotTextChanged(const QString &)));
connect(mDatePicker,SIGNAL(dateEntered(QDate)),SLOT(dateEntered(QDate)));
connect(mDatePicker,SIGNAL(dateSelected(QDate)),SLOT(dateSelected(QDate)));
// Create the keyword list. This will be used to match against when the user
// enters information.
mKeywordMap[i18n("tomorrow")] = 1;
mKeywordMap[i18n("today")] = 0;
mKeywordMap[i18n("yesterday")] = -1;
QString dayName;
for (int i = 1; i <= 7; ++i)
{
dayName = KGlobal::locale()->calendar()->weekDayName(i).lower();
mKeywordMap[dayName] = i + 100;
}
lineEdit()->installEventFilter(this); // handle keyword entry
mTextChanged = false;
mHandleInvalid = false;
}
KDateEdit::~KDateEdit()
{
delete mDateFrame;
}
void KDateEdit::setDate(const QDate& newDate)
{
if (!newDate.isValid() && !mHandleInvalid)
return;
QString dateString = "";
if(newDate.isValid())
dateString = KGlobal::locale()->formatDate( newDate, true );
mTextChanged = false;
// We do not want to generate a signal here, since we explicitly setting
// the date
bool b = signalsBlocked();
blockSignals(true);
changeItem(dateString, 0);
blockSignals(b);
value = newDate;
}
void KDateEdit::setHandleInvalid(bool handleInvalid)
{
mHandleInvalid = handleInvalid;
}
bool KDateEdit::handlesInvalid() const
{
return mHandleInvalid;
}
void KDateEdit::setReadOnly(bool readOnly)
{
mReadOnly = readOnly;
lineEdit()->setReadOnly(readOnly);
}
bool KDateEdit::isReadOnly() const
{
return mReadOnly;
}
bool KDateEdit::validate( const QDate & )
{
return true;
}
QDate KDateEdit::date() const
{
QDate dt;
if (readDate(dt) && (mHandleInvalid || dt.isValid())) {
return dt;
}
return defaultValue;
}
QDate KDateEdit::defaultDate() const
{
return defaultValue;
}
void KDateEdit::setDefaultDate(const QDate& date)
{
defaultValue = date;
}
void KDateEdit::popup()
{
if (mReadOnly)
return;
QRect desk = KGlobalSettings::desktopGeometry(this);
QPoint popupPoint = mapToGlobal( QPoint( 0,0 ) );
if ( popupPoint.x() < desk.left() ) popupPoint.setX( desk.x() );
int dateFrameHeight = mDateFrame->sizeHint().height();
if ( popupPoint.y() + height() + dateFrameHeight > desk.bottom() ) {
popupPoint.setY( popupPoint.y() - dateFrameHeight );
} else {
popupPoint.setY( popupPoint.y() + height() );
}
mDateFrame->move( popupPoint );
QDate date;
readDate(date);
if (date.isValid()) {
mDatePicker->setDate( date );
} else {
mDatePicker->setDate( defaultValue );
}
mDateFrame->show();
// The combo box is now shown pressed. Make it show not pressed again
// by causing its (invisible) list box to emit a 'selected' signal.
QListBox *lb = listBox();
if (lb) {
lb->setCurrentItem(0);
QKeyEvent* keyEvent = new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, 0, 0);
QApplication::postEvent(lb, keyEvent);
}
}
void KDateEdit::dateSelected(QDate newDate)
{
if ((mHandleInvalid || newDate.isValid()) && validate(newDate)) {
setDate(newDate);
emit dateChanged(newDate);
mDateFrame->hide();
}
}
void KDateEdit::dateEntered(QDate newDate)
{
if ((mHandleInvalid || newDate.isValid()) && validate(newDate)) {
setDate(newDate);
emit dateChanged(newDate);
}
}
void KDateEdit::lineEnterPressed()
{
QDate date;
if (readDate(date) && (mHandleInvalid || date.isValid()) && validate(date))
{
// Update the edit. This is needed if the user has entered a
// word rather than the actual date.
setDate(date);
emit(dateChanged(date));
}
else {
// Invalid or unacceptable date - revert to previous value
KNotifyClient::beep();
setDate(value);
emit invalidDateEntered();
}
}
bool KDateEdit::inputIsValid() const
{
QDate date;
return readDate(date) && date.isValid();
}
/* Reads the text from the line edit. If the text is a keyword, the
* word will be translated to a date. If the text is not a keyword, the
* text will be interpreted as a date.
* Returns true if the date text is blank or valid, false otherwise.
*/
bool KDateEdit::readDate(QDate& result) const
{
QString text = currentText();
if (text.isEmpty()) {
result = QDate();
}
else if (mKeywordMap.contains(text.lower()))
{
QDate today = QDate::currentDate();
int i = mKeywordMap[text.lower()];
if (i >= 100)
{
/* A day name has been entered. Convert to offset from today.
* This uses some math tricks to figure out the offset in days
* to the next date the given day of the week occurs. There
* are two cases, that the new day is >= the current day, which means
* the new day has not occurred yet or that the new day < the current day,
* which means the new day is already passed (so we need to find the
* day in the next week).
*/
i -= 100;
int currentDay = today.dayOfWeek();
if (i >= currentDay)
i -= currentDay;
else
i += 7 - currentDay;
}
result = today.addDays(i);
}
else
{
result = KGlobal::locale()->readDate(text);
return result.isValid();
}
return true;
}
/* Checks for a focus out event. The display of the date is updated
* to display the proper date when the focus leaves.
*/
bool KDateEdit::eventFilter(QObject *obj, QEvent *e)
{
if (obj == lineEdit()) {
// We only process the focus out event if the text has changed
// since we got focus
if ((e->type() == QEvent::FocusOut) && mTextChanged)
{
lineEnterPressed();
mTextChanged = false;
}
else if (e->type() == QEvent::KeyPress)
{
// Up and down arrow keys step the date
QKeyEvent* ke = (QKeyEvent*)e;
if (ke->key() == Qt::Key_Return)
{
lineEnterPressed();
return true;
}
int step = 0;
if (ke->key() == Qt::Key_Up)
step = 1;
else if (ke->key() == Qt::Key_Down)
step = -1;
if (step && !mReadOnly)
{
QDate date;
if (readDate(date) && date.isValid()) {
date = date.addDays(step);
if (validate(date)) {
setDate(date);
emit(dateChanged(date));
return true;
}
}
}
}
}
else {
// It's a date picker event
switch (e->type()) {
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress: {
QMouseEvent *me = (QMouseEvent*)e;
if (!mDateFrame->rect().contains(me->pos())) {
QPoint globalPos = mDateFrame->mapToGlobal(me->pos());
if (QApplication::widgetAt(globalPos, true) == this) {
// The date picker is being closed by a click on the
// KDateEdit widget. Avoid popping it up again immediately.
mDiscardNextMousePress = true;
}
}
break;
}
default:
break;
}
}
return false;
}
void KDateEdit::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton && mDiscardNextMousePress) {
mDiscardNextMousePress = false;
return;
}
QComboBox::mousePressEvent(e);
}
void KDateEdit::slotTextChanged(const QString &)
{
mTextChanged = true;
}
<commit_msg>Prevent date picker popup going past the right or top of the screen<commit_after>/*
This file is part of libkdepim.
Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qevent.h>
#include <qlineedit.h>
#include <qapplication.h>
#include <qlistbox.h>
#include <kdatepicker.h>
#include <knotifyclient.h>
#include <kglobalsettings.h>
#include <kdebug.h>
#include <kglobal.h>
#include <klocale.h>
#include <kcalendarsystem.h>
#include "kdateedit.h"
#include "kdateedit.moc"
KDateEdit::KDateEdit(QWidget *parent, const char *name)
: QComboBox(true, parent, name),
defaultValue(QDate::currentDate()),
mReadOnly(false),
mDiscardNextMousePress(false)
{
setMaxCount(1); // need at least one entry for popup to work
value = defaultValue;
QString today = KGlobal::locale()->formatDate(value, true);
insertItem(today);
setCurrentItem(0);
changeItem(today, 0);
setMinimumSize(sizeHint());
mDateFrame = new QVBox(0,0,WType_Popup);
mDateFrame->setFrameStyle(QFrame::PopupPanel | QFrame::Raised);
mDateFrame->setLineWidth(3);
mDateFrame->hide();
mDateFrame->installEventFilter(this);
mDatePicker = new KDatePicker(mDateFrame, value);
connect(lineEdit(),SIGNAL(returnPressed()),SLOT(lineEnterPressed()));
connect(this,SIGNAL(textChanged(const QString &)),
SLOT(slotTextChanged(const QString &)));
connect(mDatePicker,SIGNAL(dateEntered(QDate)),SLOT(dateEntered(QDate)));
connect(mDatePicker,SIGNAL(dateSelected(QDate)),SLOT(dateSelected(QDate)));
// Create the keyword list. This will be used to match against when the user
// enters information.
mKeywordMap[i18n("tomorrow")] = 1;
mKeywordMap[i18n("today")] = 0;
mKeywordMap[i18n("yesterday")] = -1;
QString dayName;
for (int i = 1; i <= 7; ++i)
{
dayName = KGlobal::locale()->calendar()->weekDayName(i).lower();
mKeywordMap[dayName] = i + 100;
}
lineEdit()->installEventFilter(this); // handle keyword entry
mTextChanged = false;
mHandleInvalid = false;
}
KDateEdit::~KDateEdit()
{
delete mDateFrame;
}
void KDateEdit::setDate(const QDate& newDate)
{
if (!newDate.isValid() && !mHandleInvalid)
return;
QString dateString = "";
if(newDate.isValid())
dateString = KGlobal::locale()->formatDate( newDate, true );
mTextChanged = false;
// We do not want to generate a signal here, since we explicitly setting
// the date
bool b = signalsBlocked();
blockSignals(true);
changeItem(dateString, 0);
blockSignals(b);
value = newDate;
}
void KDateEdit::setHandleInvalid(bool handleInvalid)
{
mHandleInvalid = handleInvalid;
}
bool KDateEdit::handlesInvalid() const
{
return mHandleInvalid;
}
void KDateEdit::setReadOnly(bool readOnly)
{
mReadOnly = readOnly;
lineEdit()->setReadOnly(readOnly);
}
bool KDateEdit::isReadOnly() const
{
return mReadOnly;
}
bool KDateEdit::validate( const QDate & )
{
return true;
}
QDate KDateEdit::date() const
{
QDate dt;
if (readDate(dt) && (mHandleInvalid || dt.isValid())) {
return dt;
}
return defaultValue;
}
QDate KDateEdit::defaultDate() const
{
return defaultValue;
}
void KDateEdit::setDefaultDate(const QDate& date)
{
defaultValue = date;
}
void KDateEdit::popup()
{
if (mReadOnly)
return;
QRect desk = KGlobalSettings::desktopGeometry(this);
QPoint popupPoint = mapToGlobal( QPoint( 0,0 ) );
int dateFrameHeight = mDateFrame->sizeHint().height();
if ( popupPoint.y() + height() + dateFrameHeight > desk.bottom() ) {
popupPoint.setY( popupPoint.y() - dateFrameHeight );
} else {
popupPoint.setY( popupPoint.y() + height() );
}
int dateFrameWidth = mDateFrame->sizeHint().width();
if ( popupPoint.x() + dateFrameWidth > desk.right() ) {
popupPoint.setX( desk.right() - dateFrameWidth );
}
if ( popupPoint.x() < desk.left() ) popupPoint.setX( desk.left() );
if ( popupPoint.y() < desk.top() ) popupPoint.setY( desk.top() );
mDateFrame->move( popupPoint );
QDate date;
readDate(date);
if (date.isValid()) {
mDatePicker->setDate( date );
} else {
mDatePicker->setDate( defaultValue );
}
mDateFrame->show();
// The combo box is now shown pressed. Make it show not pressed again
// by causing its (invisible) list box to emit a 'selected' signal.
QListBox *lb = listBox();
if (lb) {
lb->setCurrentItem(0);
QKeyEvent* keyEvent = new QKeyEvent(QEvent::KeyPress, Qt::Key_Enter, 0, 0);
QApplication::postEvent(lb, keyEvent);
}
}
void KDateEdit::dateSelected(QDate newDate)
{
if ((mHandleInvalid || newDate.isValid()) && validate(newDate)) {
setDate(newDate);
emit dateChanged(newDate);
mDateFrame->hide();
}
}
void KDateEdit::dateEntered(QDate newDate)
{
if ((mHandleInvalid || newDate.isValid()) && validate(newDate)) {
setDate(newDate);
emit dateChanged(newDate);
}
}
void KDateEdit::lineEnterPressed()
{
QDate date;
if (readDate(date) && (mHandleInvalid || date.isValid()) && validate(date))
{
// Update the edit. This is needed if the user has entered a
// word rather than the actual date.
setDate(date);
emit(dateChanged(date));
}
else {
// Invalid or unacceptable date - revert to previous value
KNotifyClient::beep();
setDate(value);
emit invalidDateEntered();
}
}
bool KDateEdit::inputIsValid() const
{
QDate date;
return readDate(date) && date.isValid();
}
/* Reads the text from the line edit. If the text is a keyword, the
* word will be translated to a date. If the text is not a keyword, the
* text will be interpreted as a date.
* Returns true if the date text is blank or valid, false otherwise.
*/
bool KDateEdit::readDate(QDate& result) const
{
QString text = currentText();
if (text.isEmpty()) {
result = QDate();
}
else if (mKeywordMap.contains(text.lower()))
{
QDate today = QDate::currentDate();
int i = mKeywordMap[text.lower()];
if (i >= 100)
{
/* A day name has been entered. Convert to offset from today.
* This uses some math tricks to figure out the offset in days
* to the next date the given day of the week occurs. There
* are two cases, that the new day is >= the current day, which means
* the new day has not occurred yet or that the new day < the current day,
* which means the new day is already passed (so we need to find the
* day in the next week).
*/
i -= 100;
int currentDay = today.dayOfWeek();
if (i >= currentDay)
i -= currentDay;
else
i += 7 - currentDay;
}
result = today.addDays(i);
}
else
{
result = KGlobal::locale()->readDate(text);
return result.isValid();
}
return true;
}
/* Checks for a focus out event. The display of the date is updated
* to display the proper date when the focus leaves.
*/
bool KDateEdit::eventFilter(QObject *obj, QEvent *e)
{
if (obj == lineEdit()) {
// We only process the focus out event if the text has changed
// since we got focus
if ((e->type() == QEvent::FocusOut) && mTextChanged)
{
lineEnterPressed();
mTextChanged = false;
}
else if (e->type() == QEvent::KeyPress)
{
// Up and down arrow keys step the date
QKeyEvent* ke = (QKeyEvent*)e;
if (ke->key() == Qt::Key_Return)
{
lineEnterPressed();
return true;
}
int step = 0;
if (ke->key() == Qt::Key_Up)
step = 1;
else if (ke->key() == Qt::Key_Down)
step = -1;
if (step && !mReadOnly)
{
QDate date;
if (readDate(date) && date.isValid()) {
date = date.addDays(step);
if (validate(date)) {
setDate(date);
emit(dateChanged(date));
return true;
}
}
}
}
}
else {
// It's a date picker event
switch (e->type()) {
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress: {
QMouseEvent *me = (QMouseEvent*)e;
if (!mDateFrame->rect().contains(me->pos())) {
QPoint globalPos = mDateFrame->mapToGlobal(me->pos());
if (QApplication::widgetAt(globalPos, true) == this) {
// The date picker is being closed by a click on the
// KDateEdit widget. Avoid popping it up again immediately.
mDiscardNextMousePress = true;
}
}
break;
}
default:
break;
}
}
return false;
}
void KDateEdit::mousePressEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton && mDiscardNextMousePress) {
mDiscardNextMousePress = false;
return;
}
QComboBox::mousePressEvent(e);
}
void KDateEdit::slotTextChanged(const QString &)
{
mTextChanged = true;
}
<|endoftext|> |
<commit_before>/*
* Author Joshua Flank
* September 2017
* OpenGL view of 8x8x8 LED cube.
*/
#include "GLcube.h"
#include <GL/gl.h>
#include <GL/glut.h>
#include "GL/freeglut.h"
#include <unistd.h>
#define WINDOWX 640
#define WINDOWY 640
int a[3]={10,10,10}, b[3]={10,-10,10},
c[3]={-10,-10,10}, d[3]={-10,10,10},
e[3]={10,10,-10}, f[3]={10,-10,-10},
g[3]={-10,-10,-10}, h[3]={-10,10,-10};
double transfat = 0.25;
GLCube * myGLCubeP = NULL;
float rot_z_vel = 0.0;
float rot_y_vel = 0.0;
//float rot_y_vel = 0.1;
float rot_x_vel = 0.0;
void GLCube::drawSpheres(void)
{
int x, y, z;
if (m_speed != GLMAXSPEED ) {
usleep (100*(GLMAXSPEED - m_speed));
}
pthread_mutex_lock( &m_mutex);
glMatrixMode(GL_PROJECTION);
//glLoadIdentity();
glPushMatrix();
glTranslated(-1.0-1.0/CUBESIZE,-1.0-1.0/CUBESIZE, -CUBESIZE/2.0);
// glTranslated(0.0,- CUBESIZE, -CUBESIZE);
for (z = 0; z < CUBESIZE; z++) {
glTranslated(0,0, transfat);
for (y = 0; y < CUBESIZE; y++) {
glTranslated(0,transfat,0);
for (x = 0; x < CUBESIZE; x++) {
glTranslated(transfat, 0, 0);
if (m_cube[x][y][z] == CUBEON) {
glColor3d(1,0,0);
glutSolidSphere(.04,15,15);
} else if (m_cube[x][y][z] != CUBEOFF) {
rgb_t rgb;
rgb.word = m_cube[x][y][z];
glColor3b(rgb.color.red,rgb.color.green,rgb.color.blue);
glutSolidSphere(.04,15,15);
} else {
glColor3d(.1,0,.3);
// glColor3d(0,0,1);
glutWireSphere(.03,7,7);
}
}
glTranslated(-CUBESIZE * transfat ,0,0);
}
glTranslated(0, -CUBESIZE * transfat, 0);
}
glPopMatrix();
pthread_mutex_unlock( &m_mutex);
}
int GLCube::setSpeed(int speed)
{
if (speed > GLMAXSPEED || speed < GLMINSPEED) {
return GLDEFSPEED;
}
m_speed = speed;
return speed;
}
void RotateCube(void) {
glMatrixMode(GL_PROJECTION);
glTranslated(0,0, -CUBESIZE/3.0);
glRotatef(rot_x_vel, 1.0, 0.0, 0.0);
glRotatef(rot_y_vel, 0.0, 1.0, 0.0);
glTranslated(0,0, CUBESIZE/3.0);
glRotatef(rot_z_vel, 0.0, 0.0, 1.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
RotateCube();
myGLCubeP->drawSpheres();
glutSwapBuffers();
}
//from solidsphere.c
static void resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'u':
rot_z_vel += 0.1;
break;
case 'i':
rot_z_vel -= 0.1;
break;
case 'j':
rot_y_vel += 0.1;
break;
case 'k':
rot_y_vel -= 0.1;
break;
case 'm':
rot_x_vel += 0.1;
break;
case ',':
rot_x_vel -= 0.1;
break;
case '-':
myGLCubeP->setSpeed(myGLCubeP->getSpeed() + 1);
break;
case '+':
myGLCubeP->setSpeed(myGLCubeP->getSpeed() - 1);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
myGLCubeP->set(x*CUBESIZE/WINDOWX,7-y*CUBESIZE/WINDOWY,key-'1', CUBEON);
break;
case ' ':
myGLCubeP->clear();
break;
case 'p':
myGLCubeP->cubeToFile("GLCUBE.bin");
break;
case 's':
myGLCubeP->cubeToSerial(); //serial not implemented yet
break;
case 0x1B:
case 'q':
case 'Q':
exit(0);
break;
}
}
void mouse(int btn, int state, int x, int y)
{
if (state == GLUT_DOWN)
{
if (btn == GLUT_LEFT_BUTTON)
rot_y_vel -= 0.1;
else if (btn == GLUT_RIGHT_BUTTON)
rot_y_vel += 0.1;
}
}
GLCube::GLCube() : LedCube(){
m_speed = GLMAXSPEED;
return;
}
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
void * mainGL(void * ptr)
{
int argc = 1;
char *argv[1] = {(char*)"Something"};
myGLCubeP = new GLCube();
myGLCubeP->set(0,0,0, CUBEON);
myGLCubeP->set(1,0,0, CUBEON);
myGLCubeP->set(1,7,0, CUBEON);
myGLCubeP->set(0,0,7, CUBEON);
glutInit(&argc, argv);
glutInitWindowSize(WINDOWX, WINDOWY);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("GL Cube");
glutMouseFunc(mouse);
glutKeyboardFunc(keyboard);
glutDisplayFunc(display);
glutIdleFunc(display);
glutReshapeFunc(resize);
/*
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0, 0.0, 0.0, 0.0);
*/
// glRotatef(30.0, 1.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, WINDOWX, WINDOWY, 0.0f, 0.0f, 1.0f);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glutMainLoop();
while (1) {
}
return(0);
}
<commit_msg>Allowing for sphere size changes.<commit_after>/*
* Author Joshua Flank
* September 2017
* OpenGL view of 8x8x8 LED cube.
*/
#include "GLcube.h"
#include <GL/gl.h>
#include <GL/glut.h>
#include "GL/freeglut.h"
#include <unistd.h>
#define WINDOWX 640
#define WINDOWY 640
int a[3]={10,10,10}, b[3]={10,-10,10},
c[3]={-10,-10,10}, d[3]={-10,10,10},
e[3]={10,10,-10}, f[3]={10,-10,-10},
g[3]={-10,-10,-10}, h[3]={-10,10,-10};
double transfat = 0.25;
GLCube * myGLCubeP = NULL;
float rot_z_vel = 0.0;
float rot_y_vel = 0.0;
//float rot_y_vel = 0.1;
float rot_x_vel = 0.0;
float sphereSize = 0.04;
void GLCube::drawSpheres(void)
{
int x, y, z;
if (m_speed != GLMAXSPEED ) {
usleep (100*(GLMAXSPEED - m_speed));
}
pthread_mutex_lock( &m_mutex);
glMatrixMode(GL_PROJECTION);
//glLoadIdentity();
glPushMatrix();
glTranslated(-1.0-1.0/CUBESIZE,-1.0-1.0/CUBESIZE, -CUBESIZE/2.0);
// glTranslated(0.0,- CUBESIZE, -CUBESIZE);
for (z = 0; z < CUBESIZE; z++) {
glTranslated(0,0, transfat);
for (y = 0; y < CUBESIZE; y++) {
glTranslated(0,transfat,0);
for (x = 0; x < CUBESIZE; x++) {
glTranslated(transfat, 0, 0);
if (m_cube[x][y][z] == CUBEON) {
glColor3d(1,0,0);
glutSolidSphere(sphereSize,15,15);
} else if (m_cube[x][y][z] != CUBEOFF) {
rgb_t rgb;
rgb.word = m_cube[x][y][z];
glColor3b(rgb.color.red,rgb.color.green,rgb.color.blue);
glutSolidSphere(sphereSize,15,15);
} else {
glColor3d(.1,0,.3);
// glColor3d(0,0,1);
glutWireSphere(.03,7,7);
}
}
glTranslated(-CUBESIZE * transfat ,0,0);
}
glTranslated(0, -CUBESIZE * transfat, 0);
}
glPopMatrix();
pthread_mutex_unlock( &m_mutex);
}
int GLCube::setSpeed(int speed)
{
if (speed > GLMAXSPEED || speed < GLMINSPEED) {
return GLDEFSPEED;
}
m_speed = speed;
return speed;
}
void RotateCube(void) {
glMatrixMode(GL_PROJECTION);
glTranslated(0,0, -CUBESIZE/3.0);
glRotatef(rot_x_vel, 1.0, 0.0, 0.0);
glRotatef(rot_y_vel, 0.0, 1.0, 0.0);
glTranslated(0,0, CUBESIZE/3.0);
glRotatef(rot_z_vel, 0.0, 0.0, 1.0);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
RotateCube();
myGLCubeP->drawSpheres();
glutSwapBuffers();
}
//from solidsphere.c
static void resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'u':
rot_z_vel += 0.1;
break;
case 'i':
rot_z_vel -= 0.1;
break;
case 'j':
rot_y_vel += 0.1;
break;
case 'k':
rot_y_vel -= 0.1;
break;
case 'm':
rot_x_vel += 0.1;
break;
case ',':
rot_x_vel -= 0.1;
break;
case '-':
sphereSize -= 0.01;
// myGLCubeP->setSpeed(myGLCubeP->getSpeed() + 1);
break;
case '=':
sphereSize += 0.01;
// myGLCubeP->setSpeed(myGLCubeP->getSpeed() - 1);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
myGLCubeP->set(x*CUBESIZE/WINDOWX,7-y*CUBESIZE/WINDOWY,key-'1', CUBEON);
break;
case ' ':
myGLCubeP->clear();
break;
case 'p':
myGLCubeP->cubeToFile("GLCUBE.bin");
break;
case 's':
myGLCubeP->cubeToSerial(); //serial not implemented yet
break;
case 0x1B:
case 'q':
case 'Q':
exit(0);
break;
}
}
void mouse(int btn, int state, int x, int y)
{
if (state == GLUT_DOWN)
{
if (btn == GLUT_LEFT_BUTTON)
rot_y_vel -= 0.1;
else if (btn == GLUT_RIGHT_BUTTON)
rot_y_vel += 0.1;
}
}
GLCube::GLCube() : LedCube(){
m_speed = GLMAXSPEED;
return;
}
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
void * mainGL(void * ptr)
{
int argc = 1;
char *argv[1] = {(char*)"Something"};
myGLCubeP = new GLCube();
myGLCubeP->set(0,0,0, CUBEON);
myGLCubeP->set(1,0,0, CUBEON);
myGLCubeP->set(1,7,0, CUBEON);
myGLCubeP->set(0,0,7, CUBEON);
glutInit(&argc, argv);
glutInitWindowSize(WINDOWX, WINDOWY);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("GL Cube");
glutMouseFunc(mouse);
glutKeyboardFunc(keyboard);
glutDisplayFunc(display);
glutIdleFunc(display);
glutReshapeFunc(resize);
/*
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glClearColor(0.0, 0.0, 0.0, 0.0);
*/
// glRotatef(30.0, 1.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, WINDOWX, WINDOWY, 0.0f, 0.0f, 1.0f);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glutMainLoop();
while (1) {
}
return(0);
}
<|endoftext|> |
<commit_before>//===-- R600KernelParameters.cpp - Lower kernel function arguments --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass lowers kernel function arguments to loads from the vertex buffer.
//
// Kernel arguemnts are stored in the vertex buffer at an offset of 9 dwords,
// so arg0 needs to be loaded from VTX_BUFFER[9] and arg1 is loaded from
// VTX_BUFFER[10], etc.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDIL.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Intrinsics.h"
#include "llvm/Metadata.h"
#include "llvm/Module.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Support/TypeBuilder.h"
#include <map>
#include <set>
using namespace llvm;
namespace {
#define CONSTANT_CACHE_SIZE_DW 127
class R600KernelParameters : public FunctionPass
{
const TargetData * TD;
LLVMContext* Context;
Module *mod;
struct param
{
param() : val(NULL), ptr_val(NULL), offset_in_dw(0), size_in_dw(0),
indirect(false), specialID(0) {}
Value* val;
Value* ptr_val;
int offset_in_dw;
int size_in_dw;
bool indirect;
std::string specialType;
int specialID;
int end() { return offset_in_dw + size_in_dw; }
// The first 9 dwords are reserved for the grid sizes.
int get_rat_offset() { return 9 + offset_in_dw; }
};
std::vector<param> params;
bool isOpenCLKernel(const Function* fun);
int getLastSpecialID(const std::string& TypeName);
int getListSize();
void AddParam(Argument* arg);
int calculateArgumentSize(Argument* arg);
void RunAna(Function* fun);
void Replace(Function* fun);
bool isIndirect(Value* val, std::set<Value*>& visited);
void Propagate(Function* fun);
void Propagate(Value* v, const Twine& name, bool indirect = false);
Value* ConstantRead(Function* fun, param& p);
Value* handleSpecial(Function* fun, param& p);
bool isSpecialType(Type*);
std::string getSpecialTypeName(Type*);
public:
static char ID;
R600KernelParameters() : FunctionPass(ID) {};
R600KernelParameters(const TargetData* TD) : FunctionPass(ID), TD(TD) {}
bool runOnFunction (Function &F);
void getAnalysisUsage(AnalysisUsage &AU) const;
const char *getPassName() const;
bool doInitialization(Module &M);
bool doFinalization(Module &M);
};
char R600KernelParameters::ID = 0;
static RegisterPass<R600KernelParameters> X("kerparam",
"OpenCL Kernel Parameter conversion", false, false);
bool R600KernelParameters::isOpenCLKernel(const Function* fun)
{
Module *mod = const_cast<Function*>(fun)->getParent();
NamedMDNode * md = mod->getOrInsertNamedMetadata("opencl.kernels");
if (!md or !md->getNumOperands())
{
return false;
}
for (int i = 0; i < int(md->getNumOperands()); i++)
{
if (!md->getOperand(i) or !md->getOperand(i)->getOperand(0))
{
continue;
}
assert(md->getOperand(i)->getNumOperands() == 1);
if (md->getOperand(i)->getOperand(0)->getName() == fun->getName())
{
return true;
}
}
return false;
}
int R600KernelParameters::getLastSpecialID(const std::string& TypeName)
{
int lastID = -1;
for (std::vector<param>::iterator i = params.begin(); i != params.end(); i++)
{
if (i->specialType == TypeName)
{
lastID = i->specialID;
}
}
return lastID;
}
int R600KernelParameters::getListSize()
{
if (params.size() == 0)
{
return 0;
}
return params.back().end();
}
bool R600KernelParameters::isIndirect(Value* val, std::set<Value*>& visited)
{
if (isa<LoadInst>(val))
{
return false;
}
if (isa<IntegerType>(val->getType()))
{
assert(0 and "Internal error");
return false;
}
if (visited.count(val))
{
return false;
}
visited.insert(val);
if (isa<GetElementPtrInst>(val))
{
GetElementPtrInst* GEP = dyn_cast<GetElementPtrInst>(val);
GetElementPtrInst::op_iterator i = GEP->op_begin();
for (i++; i != GEP->op_end(); i++)
{
if (!isa<Constant>(*i))
{
return true;
}
}
}
for (Value::use_iterator i = val->use_begin(); i != val->use_end(); i++)
{
Value* v2 = dyn_cast<Value>(*i);
if (v2)
{
if (isIndirect(v2, visited))
{
return true;
}
}
}
return false;
}
void R600KernelParameters::AddParam(Argument* arg)
{
param p;
p.val = dyn_cast<Value>(arg);
p.offset_in_dw = getListSize();
p.size_in_dw = calculateArgumentSize(arg);
if (isa<PointerType>(arg->getType()) and arg->hasByValAttr())
{
std::set<Value*> visited;
p.indirect = isIndirect(p.val, visited);
}
params.push_back(p);
}
int R600KernelParameters::calculateArgumentSize(Argument* arg)
{
Type* t = arg->getType();
if (arg->hasByValAttr() and dyn_cast<PointerType>(t))
{
t = dyn_cast<PointerType>(t)->getElementType();
}
int store_size_in_dw = (TD->getTypeStoreSize(t) + 3)/4;
assert(store_size_in_dw);
return store_size_in_dw;
}
void R600KernelParameters::RunAna(Function* fun)
{
assert(isOpenCLKernel(fun));
for (Function::arg_iterator i = fun->arg_begin(); i != fun->arg_end(); i++)
{
AddParam(i);
}
}
void R600KernelParameters::Replace(Function* fun)
{
for (std::vector<param>::iterator i = params.begin(); i != params.end(); i++)
{
Value *new_val;
if (isSpecialType(i->val->getType()))
{
new_val = handleSpecial(fun, *i);
}
else
{
new_val = ConstantRead(fun, *i);
}
if (new_val)
{
i->val->replaceAllUsesWith(new_val);
}
}
}
void R600KernelParameters::Propagate(Function* fun)
{
for (std::vector<param>::iterator i = params.begin(); i != params.end(); i++)
{
if (i->ptr_val)
{
Propagate(i->ptr_val, i->val->getName(), i->indirect);
}
}
}
void R600KernelParameters::Propagate(Value* v, const Twine& name, bool indirect)
{
LoadInst* load = dyn_cast<LoadInst>(v);
GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v);
unsigned addrspace;
if (indirect)
{
addrspace = AMDILAS::PARAM_I_ADDRESS;
}
else
{
addrspace = AMDILAS::PARAM_D_ADDRESS;
}
if (GEP and GEP->getType()->getAddressSpace() != addrspace)
{
Value* op = GEP->getPointerOperand();
if (dyn_cast<PointerType>(op->getType())->getAddressSpace() != addrspace)
{
op = new BitCastInst(op, PointerType::get(dyn_cast<PointerType>(
op->getType())->getElementType(), addrspace),
name, dyn_cast<Instruction>(v));
}
std::vector<Value*> params(GEP->idx_begin(), GEP->idx_end());
GetElementPtrInst* GEP2 = GetElementPtrInst::Create(op, params, name,
dyn_cast<Instruction>(v));
GEP2->setIsInBounds(GEP->isInBounds());
v = dyn_cast<Value>(GEP2);
GEP->replaceAllUsesWith(GEP2);
GEP->eraseFromParent();
load = NULL;
}
if (load)
{
///normally at this point we have the right address space
if (load->getPointerAddressSpace() != addrspace)
{
Value *orig_ptr = load->getPointerOperand();
PointerType *orig_ptr_type = dyn_cast<PointerType>(orig_ptr->getType());
Type* new_ptr_type = PointerType::get(orig_ptr_type->getElementType(),
addrspace);
Value* new_ptr = orig_ptr;
if (orig_ptr->getType() != new_ptr_type)
{
new_ptr = new BitCastInst(orig_ptr, new_ptr_type, "prop_cast", load);
}
Value* new_load = new LoadInst(new_ptr, name, load);
load->replaceAllUsesWith(new_load);
load->eraseFromParent();
}
return;
}
std::vector<User*> users(v->use_begin(), v->use_end());
for (int i = 0; i < int(users.size()); i++)
{
Value* v2 = dyn_cast<Value>(users[i]);
if (v2)
{
Propagate(v2, name, indirect);
}
}
}
Value* R600KernelParameters::ConstantRead(Function* fun, param& p)
{
assert(fun->front().begin() != fun->front().end());
Instruction *first_inst = fun->front().begin();
IRBuilder <> builder (first_inst);
/* First 3 dwords are reserved for the dimmension info */
if (!p.val->hasNUsesOrMore(1))
{
return NULL;
}
unsigned addrspace;
if (p.indirect)
{
addrspace = AMDILAS::PARAM_I_ADDRESS;
}
else
{
addrspace = AMDILAS::PARAM_D_ADDRESS;
}
Argument *arg = dyn_cast<Argument>(p.val);
Type * argType = p.val->getType();
PointerType * argPtrType = dyn_cast<PointerType>(p.val->getType());
if (argPtrType and arg->hasByValAttr())
{
Value* param_addr_space_ptr = ConstantPointerNull::get(
PointerType::get(Type::getInt32Ty(*Context),
addrspace));
Value* param_ptr = GetElementPtrInst::Create(param_addr_space_ptr,
ConstantInt::get(Type::getInt32Ty(*Context),
p.get_rat_offset()), arg->getName(),
first_inst);
param_ptr = new BitCastInst(param_ptr,
PointerType::get(argPtrType->getElementType(),
addrspace),
arg->getName(), first_inst);
p.ptr_val = param_ptr;
return param_ptr;
}
else
{
Value* param_addr_space_ptr = ConstantPointerNull::get(PointerType::get(
argType, addrspace));
Value* param_ptr = builder.CreateGEP(param_addr_space_ptr,
ConstantInt::get(Type::getInt32Ty(*Context), p.get_rat_offset()),
arg->getName());
Value* param_value = builder.CreateLoad(param_ptr, arg->getName());
return param_value;
}
}
Value* R600KernelParameters::handleSpecial(Function* fun, param& p)
{
std::string name = getSpecialTypeName(p.val->getType());
int ID;
assert(!name.empty());
if (name == "image2d_t" or name == "image3d_t")
{
int lastID = std::max(getLastSpecialID("image2d_t"),
getLastSpecialID("image3d_t"));
if (lastID == -1)
{
ID = 2; ///ID0 and ID1 are used internally by the driver
}
else
{
ID = lastID + 1;
}
}
else if (name == "sampler_t")
{
int lastID = getLastSpecialID("sampler_t");
if (lastID == -1)
{
ID = 0;
}
else
{
ID = lastID + 1;
}
}
else
{
///TODO: give some error message
return NULL;
}
p.specialType = name;
p.specialID = ID;
Instruction *first_inst = fun->front().begin();
return new IntToPtrInst(ConstantInt::get(Type::getInt32Ty(*Context),
p.specialID), p.val->getType(),
"resourceID", first_inst);
}
bool R600KernelParameters::isSpecialType(Type* t)
{
return !getSpecialTypeName(t).empty();
}
std::string R600KernelParameters::getSpecialTypeName(Type* t)
{
PointerType *pt = dyn_cast<PointerType>(t);
StructType *st = NULL;
if (pt)
{
st = dyn_cast<StructType>(pt->getElementType());
}
if (st)
{
std::string prefix = "struct.opencl_builtin_type_";
std::string name = st->getName().str();
if (name.substr(0, prefix.length()) == prefix)
{
return name.substr(prefix.length(), name.length());
}
}
return "";
}
bool R600KernelParameters::runOnFunction (Function &F)
{
if (!isOpenCLKernel(&F))
{
return false;
}
RunAna(&F);
Replace(&F);
Propagate(&F);
return false;
}
void R600KernelParameters::getAnalysisUsage(AnalysisUsage &AU) const
{
FunctionPass::getAnalysisUsage(AU);
AU.setPreservesAll();
}
const char *R600KernelParameters::getPassName() const
{
return "OpenCL Kernel parameter conversion to memory";
}
bool R600KernelParameters::doInitialization(Module &M)
{
Context = &M.getContext();
mod = &M;
return false;
}
bool R600KernelParameters::doFinalization(Module &M)
{
return false;
}
} // End anonymous namespace
FunctionPass* llvm::createR600KernelParametersPass(const TargetData* TD)
{
FunctionPass *p = new R600KernelParameters(TD);
return p;
}
<commit_msg>radeon/llvm: Only use indirect (vertex fetch) parameters for kernels<commit_after>//===-- R600KernelParameters.cpp - Lower kernel function arguments --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass lowers kernel function arguments to loads from the vertex buffer.
//
// Kernel arguemnts are stored in the vertex buffer at an offset of 9 dwords,
// so arg0 needs to be loaded from VTX_BUFFER[9] and arg1 is loaded from
// VTX_BUFFER[10], etc.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "AMDIL.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Intrinsics.h"
#include "llvm/Metadata.h"
#include "llvm/Module.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/IRBuilder.h"
#include "llvm/Support/TypeBuilder.h"
#include <map>
#include <set>
using namespace llvm;
namespace {
#define CONSTANT_CACHE_SIZE_DW 127
class R600KernelParameters : public FunctionPass
{
const TargetData * TD;
LLVMContext* Context;
Module *mod;
struct param
{
param() : val(NULL), ptr_val(NULL), offset_in_dw(0), size_in_dw(0),
indirect(true), specialID(0) {}
Value* val;
Value* ptr_val;
int offset_in_dw;
int size_in_dw;
bool indirect;
std::string specialType;
int specialID;
int end() { return offset_in_dw + size_in_dw; }
// The first 9 dwords are reserved for the grid sizes.
int get_rat_offset() { return 9 + offset_in_dw; }
};
std::vector<param> params;
bool isOpenCLKernel(const Function* fun);
int getLastSpecialID(const std::string& TypeName);
int getListSize();
void AddParam(Argument* arg);
int calculateArgumentSize(Argument* arg);
void RunAna(Function* fun);
void Replace(Function* fun);
bool isIndirect(Value* val, std::set<Value*>& visited);
void Propagate(Function* fun);
void Propagate(Value* v, const Twine& name, bool indirect = true);
Value* ConstantRead(Function* fun, param& p);
Value* handleSpecial(Function* fun, param& p);
bool isSpecialType(Type*);
std::string getSpecialTypeName(Type*);
public:
static char ID;
R600KernelParameters() : FunctionPass(ID) {};
R600KernelParameters(const TargetData* TD) : FunctionPass(ID), TD(TD) {}
bool runOnFunction (Function &F);
void getAnalysisUsage(AnalysisUsage &AU) const;
const char *getPassName() const;
bool doInitialization(Module &M);
bool doFinalization(Module &M);
};
char R600KernelParameters::ID = 0;
static RegisterPass<R600KernelParameters> X("kerparam",
"OpenCL Kernel Parameter conversion", false, false);
bool R600KernelParameters::isOpenCLKernel(const Function* fun)
{
Module *mod = const_cast<Function*>(fun)->getParent();
NamedMDNode * md = mod->getOrInsertNamedMetadata("opencl.kernels");
if (!md or !md->getNumOperands())
{
return false;
}
for (int i = 0; i < int(md->getNumOperands()); i++)
{
if (!md->getOperand(i) or !md->getOperand(i)->getOperand(0))
{
continue;
}
assert(md->getOperand(i)->getNumOperands() == 1);
if (md->getOperand(i)->getOperand(0)->getName() == fun->getName())
{
return true;
}
}
return false;
}
int R600KernelParameters::getLastSpecialID(const std::string& TypeName)
{
int lastID = -1;
for (std::vector<param>::iterator i = params.begin(); i != params.end(); i++)
{
if (i->specialType == TypeName)
{
lastID = i->specialID;
}
}
return lastID;
}
int R600KernelParameters::getListSize()
{
if (params.size() == 0)
{
return 0;
}
return params.back().end();
}
bool R600KernelParameters::isIndirect(Value* val, std::set<Value*>& visited)
{
//XXX Direct parameters are not supported yet, so return true here.
return true;
#if 0
if (isa<LoadInst>(val))
{
return false;
}
if (isa<IntegerType>(val->getType()))
{
assert(0 and "Internal error");
return false;
}
if (visited.count(val))
{
return false;
}
visited.insert(val);
if (isa<GetElementPtrInst>(val))
{
GetElementPtrInst* GEP = dyn_cast<GetElementPtrInst>(val);
GetElementPtrInst::op_iterator i = GEP->op_begin();
for (i++; i != GEP->op_end(); i++)
{
if (!isa<Constant>(*i))
{
return true;
}
}
}
for (Value::use_iterator i = val->use_begin(); i != val->use_end(); i++)
{
Value* v2 = dyn_cast<Value>(*i);
if (v2)
{
if (isIndirect(v2, visited))
{
return true;
}
}
}
return false;
#endif
}
void R600KernelParameters::AddParam(Argument* arg)
{
param p;
p.val = dyn_cast<Value>(arg);
p.offset_in_dw = getListSize();
p.size_in_dw = calculateArgumentSize(arg);
if (isa<PointerType>(arg->getType()) and arg->hasByValAttr())
{
std::set<Value*> visited;
p.indirect = isIndirect(p.val, visited);
}
params.push_back(p);
}
int R600KernelParameters::calculateArgumentSize(Argument* arg)
{
Type* t = arg->getType();
if (arg->hasByValAttr() and dyn_cast<PointerType>(t))
{
t = dyn_cast<PointerType>(t)->getElementType();
}
int store_size_in_dw = (TD->getTypeStoreSize(t) + 3)/4;
assert(store_size_in_dw);
return store_size_in_dw;
}
void R600KernelParameters::RunAna(Function* fun)
{
assert(isOpenCLKernel(fun));
for (Function::arg_iterator i = fun->arg_begin(); i != fun->arg_end(); i++)
{
AddParam(i);
}
}
void R600KernelParameters::Replace(Function* fun)
{
for (std::vector<param>::iterator i = params.begin(); i != params.end(); i++)
{
Value *new_val;
if (isSpecialType(i->val->getType()))
{
new_val = handleSpecial(fun, *i);
}
else
{
new_val = ConstantRead(fun, *i);
}
if (new_val)
{
i->val->replaceAllUsesWith(new_val);
}
}
}
void R600KernelParameters::Propagate(Function* fun)
{
for (std::vector<param>::iterator i = params.begin(); i != params.end(); i++)
{
if (i->ptr_val)
{
Propagate(i->ptr_val, i->val->getName(), i->indirect);
}
}
}
void R600KernelParameters::Propagate(Value* v, const Twine& name, bool indirect)
{
LoadInst* load = dyn_cast<LoadInst>(v);
GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v);
unsigned addrspace;
if (indirect)
{
addrspace = AMDILAS::PARAM_I_ADDRESS;
}
else
{
addrspace = AMDILAS::PARAM_D_ADDRESS;
}
if (GEP and GEP->getType()->getAddressSpace() != addrspace)
{
Value* op = GEP->getPointerOperand();
if (dyn_cast<PointerType>(op->getType())->getAddressSpace() != addrspace)
{
op = new BitCastInst(op, PointerType::get(dyn_cast<PointerType>(
op->getType())->getElementType(), addrspace),
name, dyn_cast<Instruction>(v));
}
std::vector<Value*> params(GEP->idx_begin(), GEP->idx_end());
GetElementPtrInst* GEP2 = GetElementPtrInst::Create(op, params, name,
dyn_cast<Instruction>(v));
GEP2->setIsInBounds(GEP->isInBounds());
v = dyn_cast<Value>(GEP2);
GEP->replaceAllUsesWith(GEP2);
GEP->eraseFromParent();
load = NULL;
}
if (load)
{
///normally at this point we have the right address space
if (load->getPointerAddressSpace() != addrspace)
{
Value *orig_ptr = load->getPointerOperand();
PointerType *orig_ptr_type = dyn_cast<PointerType>(orig_ptr->getType());
Type* new_ptr_type = PointerType::get(orig_ptr_type->getElementType(),
addrspace);
Value* new_ptr = orig_ptr;
if (orig_ptr->getType() != new_ptr_type)
{
new_ptr = new BitCastInst(orig_ptr, new_ptr_type, "prop_cast", load);
}
Value* new_load = new LoadInst(new_ptr, name, load);
load->replaceAllUsesWith(new_load);
load->eraseFromParent();
}
return;
}
std::vector<User*> users(v->use_begin(), v->use_end());
for (int i = 0; i < int(users.size()); i++)
{
Value* v2 = dyn_cast<Value>(users[i]);
if (v2)
{
Propagate(v2, name, indirect);
}
}
}
Value* R600KernelParameters::ConstantRead(Function* fun, param& p)
{
assert(fun->front().begin() != fun->front().end());
Instruction *first_inst = fun->front().begin();
IRBuilder <> builder (first_inst);
/* First 3 dwords are reserved for the dimmension info */
if (!p.val->hasNUsesOrMore(1))
{
return NULL;
}
unsigned addrspace;
if (p.indirect)
{
addrspace = AMDILAS::PARAM_I_ADDRESS;
}
else
{
addrspace = AMDILAS::PARAM_D_ADDRESS;
}
Argument *arg = dyn_cast<Argument>(p.val);
Type * argType = p.val->getType();
PointerType * argPtrType = dyn_cast<PointerType>(p.val->getType());
if (argPtrType and arg->hasByValAttr())
{
Value* param_addr_space_ptr = ConstantPointerNull::get(
PointerType::get(Type::getInt32Ty(*Context),
addrspace));
Value* param_ptr = GetElementPtrInst::Create(param_addr_space_ptr,
ConstantInt::get(Type::getInt32Ty(*Context),
p.get_rat_offset()), arg->getName(),
first_inst);
param_ptr = new BitCastInst(param_ptr,
PointerType::get(argPtrType->getElementType(),
addrspace),
arg->getName(), first_inst);
p.ptr_val = param_ptr;
return param_ptr;
}
else
{
Value* param_addr_space_ptr = ConstantPointerNull::get(PointerType::get(
argType, addrspace));
Value* param_ptr = builder.CreateGEP(param_addr_space_ptr,
ConstantInt::get(Type::getInt32Ty(*Context), p.get_rat_offset()),
arg->getName());
Value* param_value = builder.CreateLoad(param_ptr, arg->getName());
return param_value;
}
}
Value* R600KernelParameters::handleSpecial(Function* fun, param& p)
{
std::string name = getSpecialTypeName(p.val->getType());
int ID;
assert(!name.empty());
if (name == "image2d_t" or name == "image3d_t")
{
int lastID = std::max(getLastSpecialID("image2d_t"),
getLastSpecialID("image3d_t"));
if (lastID == -1)
{
ID = 2; ///ID0 and ID1 are used internally by the driver
}
else
{
ID = lastID + 1;
}
}
else if (name == "sampler_t")
{
int lastID = getLastSpecialID("sampler_t");
if (lastID == -1)
{
ID = 0;
}
else
{
ID = lastID + 1;
}
}
else
{
///TODO: give some error message
return NULL;
}
p.specialType = name;
p.specialID = ID;
Instruction *first_inst = fun->front().begin();
return new IntToPtrInst(ConstantInt::get(Type::getInt32Ty(*Context),
p.specialID), p.val->getType(),
"resourceID", first_inst);
}
bool R600KernelParameters::isSpecialType(Type* t)
{
return !getSpecialTypeName(t).empty();
}
std::string R600KernelParameters::getSpecialTypeName(Type* t)
{
PointerType *pt = dyn_cast<PointerType>(t);
StructType *st = NULL;
if (pt)
{
st = dyn_cast<StructType>(pt->getElementType());
}
if (st)
{
std::string prefix = "struct.opencl_builtin_type_";
std::string name = st->getName().str();
if (name.substr(0, prefix.length()) == prefix)
{
return name.substr(prefix.length(), name.length());
}
}
return "";
}
bool R600KernelParameters::runOnFunction (Function &F)
{
if (!isOpenCLKernel(&F))
{
return false;
}
RunAna(&F);
Replace(&F);
Propagate(&F);
return false;
}
void R600KernelParameters::getAnalysisUsage(AnalysisUsage &AU) const
{
FunctionPass::getAnalysisUsage(AU);
AU.setPreservesAll();
}
const char *R600KernelParameters::getPassName() const
{
return "OpenCL Kernel parameter conversion to memory";
}
bool R600KernelParameters::doInitialization(Module &M)
{
Context = &M.getContext();
mod = &M;
return false;
}
bool R600KernelParameters::doFinalization(Module &M)
{
return false;
}
} // End anonymous namespace
FunctionPass* llvm::createR600KernelParametersPass(const TargetData* TD)
{
FunctionPass *p = new R600KernelParameters(TD);
return p;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Glyph3D.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Glyph3D.hh"
#include "Trans.hh"
#include "FVectors.hh"
#include "FNormals.hh"
#include "vlMath.hh"
// Description
// Construct object with scaling on, scaling mode is by scalar value,
// scale factor = 1.0, the range is (0,1), orient geometry is on, and
// orientation is by vector.
vlGlyph3D::vlGlyph3D()
{
this->Source = NULL;
this->Scaling = 1;
this->ScaleMode = SCALE_BY_SCALAR;
this->ScaleFactor = 1.0;
this->Range[0] = 0.0;
this->Range[1] = 1.0;
this->Orient = 1;
this->VectorMode = USE_VECTOR;
}
vlGlyph3D::~vlGlyph3D()
{
}
void vlGlyph3D::Execute()
{
vlPointData *pd;
vlScalars *inScalars;
vlVectors *inVectors;
vlNormals *inNormals, *sourceNormals;
int numPts, numSourcePts, numSourceCells;
int inPtId, i;
vlPoints *sourcePts;
vlCellArray *sourceCells;
vlFloatPoints *newPts;
vlFloatScalars *newScalars=NULL;
vlFloatVectors *newVectors=NULL;
vlFloatNormals *newNormals=NULL;
float *x, *v, vNew[3];
vlTransform trans;
vlCell *cell;
vlIdList *cellPts;
int npts, pts[MAX_CELL_SIZE];
int orient, scaleSource, ptIncr, cellId;
float scale, den;
vlMath math;
vlDebugMacro(<<"Generating glyphs");
this->Initialize();
pd = this->Input->GetPointData();
inScalars = pd->GetScalars();
inVectors = pd->GetVectors();
inNormals = pd->GetNormals();
numPts = this->Input->GetNumberOfPoints();
//
// Allocate storage for output PolyData
//
sourcePts = this->Source->GetPoints();
numSourcePts = sourcePts->GetNumberOfPoints();
numSourceCells = this->Source->GetNumberOfCells();
sourceNormals = this->Source->GetPointData()->GetNormals();
newPts = new vlFloatPoints(numPts*numSourcePts);
if (inScalars != NULL)
newScalars = new vlFloatScalars(numPts*numSourcePts);
if (inVectors != NULL || inNormals != NULL )
newVectors = new vlFloatVectors(numPts*numSourcePts);
if (sourceNormals != NULL)
newNormals = new vlFloatNormals(numPts*numSourcePts);
// Setting up for calls to PolyData::InsertNextCell()
if ( (sourceCells=this->Source->GetVerts())->GetNumberOfCells() > 0 )
{
this->SetVerts(new vlCellArray(numPts*sourceCells->GetSize()));
}
if ( (sourceCells=this->Source->GetLines())->GetNumberOfCells() > 0 )
{
this->SetLines(new vlCellArray(numPts*sourceCells->GetSize()));
}
if ( (sourceCells=this->Source->GetPolys())->GetNumberOfCells() > 0 )
{
this->SetPolys(new vlCellArray(numPts*sourceCells->GetSize()));
}
if ( (sourceCells=this->Source->GetStrips())->GetNumberOfCells() > 0 )
{
this->SetStrips(new vlCellArray(numPts*sourceCells->GetSize()));
}
//
// Copy (input scalars) to (output scalars) and either (input vectors or
// normals) to (output vectors). All other point attributes are copied
// from Source.
//
pd = this->Source->GetPointData();
this->PointData.CopyScalarsOff();
this->PointData.CopyVectorsOff();
this->PointData.CopyNormalsOff();
this->PointData.CopyAllocate(pd,numPts*numSourcePts);
//
// First copy all topology (transformation independent)
//
for (inPtId=0; inPtId < numPts; inPtId++)
{
ptIncr = inPtId * numSourcePts;
for (cellId=0; cellId < numSourceCells; cellId++)
{
cell = this->Source->GetCell(cellId);
cellPts = cell->GetPointIds();
npts = cellPts->GetNumberOfIds();
for (i=0; i < npts; i++) pts[i] = cellPts->GetId(i) + ptIncr;
this->InsertNextCell(cell->GetCellType(),npts,pts);
}
}
//
// Traverse all Input points, transforming Source points and copying
// point attributes.
//
if ( this->VectorMode == USE_VECTOR && inVectors != NULL ||
this->VectorMode == USE_NORMAL && inNormals != NULL )
orient = 1;
else
orient = 0;
if ( this->Scaling &&
((this->ScaleMode == SCALE_BY_SCALAR && inScalars != NULL) ||
(this->ScaleMode == SCALE_BY_VECTOR && (inVectors || inNormals))) )
scaleSource = 1;
else
scaleSource = 0;
for (inPtId=0; inPtId < numPts; inPtId++)
{
ptIncr = inPtId * numSourcePts;
trans.Identity();
// translate Source to Input point
x = this->Input->GetPoint(inPtId);
trans.Translate(x[0], x[1], x[2]);
if ( this->VectorMode == USE_NORMAL )
v = inNormals->GetNormal(inPtId);
else
v = inVectors->GetVector(inPtId);
scale = math.Norm(v);
if ( orient )
{
// Copy Input vector
for (i=0; i < numSourcePts; i++)
newVectors->InsertVector(ptIncr+i,v);
if ( this->Orient )
{
vNew[0] = (v[0]+scale) / 2.0;
vNew[1] = v[1] / 2.0;
vNew[2] = v[2] / 2.0;
trans.RotateWXYZ(180.0,vNew[0],vNew[1],vNew[2]);
}
}
// determine scale factor from scalars if appropriate
if ( inScalars != NULL )
{
// Copy Input scalar
for (i=0; i < numSourcePts; i++)
newScalars->InsertScalar(ptIncr+i,scale);
if ( this->ScaleMode == SCALE_BY_SCALAR )
{
if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) den = 1.0;
scale = inScalars->GetScalar(inPtId);
scale = (scale < this->Range[0] ? this->Range[0] :
(scale > this->Range[1] ? this->Range[1] : scale));
scale = (scale - this->Range[0]) / den;
}
}
// scale data if appropriate
if ( scaleSource )
{
scale *= this->ScaleFactor;
if ( scale == 0.0 ) scale = 1.0e-10;
trans.Scale(scale,scale,scale);
}
// multiply points and normals by resulting matrix
trans.MultiplyPoints(sourcePts,newPts);
if ( sourceNormals != NULL )
trans.MultiplyNormals(sourceNormals,newNormals);
// Copy point data from source
for (i=0; i < numSourcePts; i++)
this->PointData.CopyData(pd,i,ptIncr+i);
}
//
// Update ourselves
//
this->SetPoints(newPts);
this->PointData.SetScalars(newScalars);
this->PointData.SetVectors(newVectors);
this->PointData.SetNormals(newNormals);
this->Squeeze();
}
// Description:
// Override update method because execution can branch two ways (Input
// and Source)
void vlGlyph3D::Update()
{
// make sure input is available
if ( this->Input == NULL || this->Source == NULL )
{
vlErrorMacro(<< "No input!");
return;
}
// prevent chasing our tail
if (this->Updating) return;
this->Updating = 1;
this->Input->Update();
this->Source->Update();
this->Updating = 0;
if (this->Input->GetMTime() > this->GetMTime() ||
this->Source->GetMTime() > this->GetMTime() ||
this->GetMTime() > this->ExecuteTime || this->GetDataReleased() )
{
if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
this->Execute();
this->ExecuteTime.Modified();
this->SetDataReleased(0);
if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
}
if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();
if ( this->Source->ShouldIReleaseData() ) this->Source->ReleaseData();
}
void vlGlyph3D::PrintSelf(ostream& os, vlIndent indent)
{
vlDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "Source: " << this->Source << "\n";
os << indent << "Scaling: " << (this->Scaling ? "On\n" : "Off\n");
os << indent << "Scale Mode: " << (this->ScaleMode == SCALE_BY_SCALAR ? "Scale by scalar\n" : "Scale by vector\n");
os << indent << "Scale Factor: " << this->ScaleFactor << "\n";
os << indent << "Range: (" << this->Range[0] << ", " << this->Range[1] << ")\n";
os << indent << "Orient: " << (this->Orient ? "On\n" : "Off\n");
os << indent << "Orient Mode: " << (this->VectorMode == USE_VECTOR ? "Orient by vector\n" : "Orient by normal\n");
}
<commit_msg>ERR: Fixed NULL reference.<commit_after>/*=========================================================================
Program: Visualization Library
Module: Glyph3D.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include "Glyph3D.hh"
#include "Trans.hh"
#include "FVectors.hh"
#include "FNormals.hh"
#include "vlMath.hh"
// Description
// Construct object with scaling on, scaling mode is by scalar value,
// scale factor = 1.0, the range is (0,1), orient geometry is on, and
// orientation is by vector.
vlGlyph3D::vlGlyph3D()
{
this->Source = NULL;
this->Scaling = 1;
this->ScaleMode = SCALE_BY_SCALAR;
this->ScaleFactor = 1.0;
this->Range[0] = 0.0;
this->Range[1] = 1.0;
this->Orient = 1;
this->VectorMode = USE_VECTOR;
}
vlGlyph3D::~vlGlyph3D()
{
}
void vlGlyph3D::Execute()
{
vlPointData *pd;
vlScalars *inScalars;
vlVectors *inVectors;
vlNormals *inNormals, *sourceNormals;
int numPts, numSourcePts, numSourceCells;
int inPtId, i;
vlPoints *sourcePts;
vlCellArray *sourceCells;
vlFloatPoints *newPts;
vlFloatScalars *newScalars=NULL;
vlFloatVectors *newVectors=NULL;
vlFloatNormals *newNormals=NULL;
float *x, *v, vNew[3];
vlTransform trans;
vlCell *cell;
vlIdList *cellPts;
int npts, pts[MAX_CELL_SIZE];
int orient, scaleSource, ptIncr, cellId;
float scale, den;
vlMath math;
vlDebugMacro(<<"Generating glyphs");
this->Initialize();
pd = this->Input->GetPointData();
inScalars = pd->GetScalars();
inVectors = pd->GetVectors();
inNormals = pd->GetNormals();
numPts = this->Input->GetNumberOfPoints();
//
// Allocate storage for output PolyData
//
sourcePts = this->Source->GetPoints();
numSourcePts = sourcePts->GetNumberOfPoints();
numSourceCells = this->Source->GetNumberOfCells();
sourceNormals = this->Source->GetPointData()->GetNormals();
newPts = new vlFloatPoints(numPts*numSourcePts);
if (inScalars != NULL)
newScalars = new vlFloatScalars(numPts*numSourcePts);
if (inVectors != NULL || inNormals != NULL )
newVectors = new vlFloatVectors(numPts*numSourcePts);
if (sourceNormals != NULL)
newNormals = new vlFloatNormals(numPts*numSourcePts);
// Setting up for calls to PolyData::InsertNextCell()
if ( (sourceCells=this->Source->GetVerts())->GetNumberOfCells() > 0 )
{
this->SetVerts(new vlCellArray(numPts*sourceCells->GetSize()));
}
if ( (sourceCells=this->Source->GetLines())->GetNumberOfCells() > 0 )
{
this->SetLines(new vlCellArray(numPts*sourceCells->GetSize()));
}
if ( (sourceCells=this->Source->GetPolys())->GetNumberOfCells() > 0 )
{
this->SetPolys(new vlCellArray(numPts*sourceCells->GetSize()));
}
if ( (sourceCells=this->Source->GetStrips())->GetNumberOfCells() > 0 )
{
this->SetStrips(new vlCellArray(numPts*sourceCells->GetSize()));
}
//
// Copy (input scalars) to (output scalars) and either (input vectors or
// normals) to (output vectors). All other point attributes are copied
// from Source.
//
pd = this->Source->GetPointData();
this->PointData.CopyScalarsOff();
this->PointData.CopyVectorsOff();
this->PointData.CopyNormalsOff();
this->PointData.CopyAllocate(pd,numPts*numSourcePts);
//
// First copy all topology (transformation independent)
//
for (inPtId=0; inPtId < numPts; inPtId++)
{
ptIncr = inPtId * numSourcePts;
for (cellId=0; cellId < numSourceCells; cellId++)
{
cell = this->Source->GetCell(cellId);
cellPts = cell->GetPointIds();
npts = cellPts->GetNumberOfIds();
for (i=0; i < npts; i++) pts[i] = cellPts->GetId(i) + ptIncr;
this->InsertNextCell(cell->GetCellType(),npts,pts);
}
}
//
// Traverse all Input points, transforming Source points and copying
// point attributes.
//
if ( (this->VectorMode == USE_VECTOR && inVectors != NULL) ||
(this->VectorMode == USE_NORMAL && inNormals != NULL) )
orient = 1;
else
orient = 0;
if ( this->Scaling &&
((this->ScaleMode == SCALE_BY_SCALAR && inScalars != NULL) ||
(this->ScaleMode == SCALE_BY_VECTOR && (inVectors || inNormals))) )
scaleSource = 1;
else
scaleSource = 0;
for (inPtId=0; inPtId < numPts; inPtId++)
{
ptIncr = inPtId * numSourcePts;
trans.Identity();
// translate Source to Input point
x = this->Input->GetPoint(inPtId);
trans.Translate(x[0], x[1], x[2]);
if ( orient )
{
if ( this->VectorMode == USE_NORMAL )
v = inNormals->GetNormal(inPtId);
else
v = inVectors->GetVector(inPtId);
scale = math.Norm(v);
// Copy Input vector
for (i=0; i < numSourcePts; i++)
newVectors->InsertVector(ptIncr+i,v);
if ( this->Orient )
{
vNew[0] = (v[0]+scale) / 2.0;
vNew[1] = v[1] / 2.0;
vNew[2] = v[2] / 2.0;
trans.RotateWXYZ(180.0,vNew[0],vNew[1],vNew[2]);
}
}
// determine scale factor from scalars if appropriate
if ( inScalars != NULL )
{
// Copy Input scalar
for (i=0; i < numSourcePts; i++)
newScalars->InsertScalar(ptIncr+i,scale);
if ( this->ScaleMode == SCALE_BY_SCALAR )
{
if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) den = 1.0;
scale = inScalars->GetScalar(inPtId);
scale = (scale < this->Range[0] ? this->Range[0] :
(scale > this->Range[1] ? this->Range[1] : scale));
scale = (scale - this->Range[0]) / den;
}
}
// scale data if appropriate
if ( scaleSource )
{
scale *= this->ScaleFactor;
if ( scale == 0.0 ) scale = 1.0e-10;
trans.Scale(scale,scale,scale);
}
// multiply points and normals by resulting matrix
trans.MultiplyPoints(sourcePts,newPts);
if ( sourceNormals != NULL )
trans.MultiplyNormals(sourceNormals,newNormals);
// Copy point data from source
for (i=0; i < numSourcePts; i++)
this->PointData.CopyData(pd,i,ptIncr+i);
}
//
// Update ourselves
//
this->SetPoints(newPts);
this->PointData.SetScalars(newScalars);
this->PointData.SetVectors(newVectors);
this->PointData.SetNormals(newNormals);
this->Squeeze();
}
// Description:
// Override update method because execution can branch two ways (Input
// and Source)
void vlGlyph3D::Update()
{
// make sure input is available
if ( this->Input == NULL || this->Source == NULL )
{
vlErrorMacro(<< "No input!");
return;
}
// prevent chasing our tail
if (this->Updating) return;
this->Updating = 1;
this->Input->Update();
this->Source->Update();
this->Updating = 0;
if (this->Input->GetMTime() > this->GetMTime() ||
this->Source->GetMTime() > this->GetMTime() ||
this->GetMTime() > this->ExecuteTime || this->GetDataReleased() )
{
if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
this->Execute();
this->ExecuteTime.Modified();
this->SetDataReleased(0);
if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
}
if ( this->Input->ShouldIReleaseData() ) this->Input->ReleaseData();
if ( this->Source->ShouldIReleaseData() ) this->Source->ReleaseData();
}
void vlGlyph3D::PrintSelf(ostream& os, vlIndent indent)
{
vlDataSetToPolyFilter::PrintSelf(os,indent);
os << indent << "Source: " << this->Source << "\n";
os << indent << "Scaling: " << (this->Scaling ? "On\n" : "Off\n");
os << indent << "Scale Mode: " << (this->ScaleMode == SCALE_BY_SCALAR ? "Scale by scalar\n" : "Scale by vector\n");
os << indent << "Scale Factor: " << this->ScaleFactor << "\n";
os << indent << "Range: (" << this->Range[0] << ", " << this->Range[1] << ")\n";
os << indent << "Orient: " << (this->Orient ? "On\n" : "Off\n");
os << indent << "Orient Mode: " << (this->VectorMode == USE_VECTOR ? "Orient by vector\n" : "Orient by normal\n");
}
<|endoftext|> |
<commit_before>#include <set>
#include "Inline.h"
#include "CSE.h"
#include "IRPrinter.h"
#include "IRMutator.h"
#include "Qualify.h"
#include "Debug.h"
namespace Halide {
namespace Internal {
using std::set;
using std::string;
using std::vector;
class Inliner : public IRMutator {
using IRMutator::visit;
Function func;
// Sanity check that this is a reasonable function to inline
void check(Function f) {
internal_assert(f.can_be_inlined()) << "Illegal to inline " << f.name() << "\n";
const Schedule &s = f.schedule();
if (!s.store_level().is_inline()) {
user_error << "Function " << f.name() << " is scheduled to be computed inline, "
<< "but is not scheduled to be stored inline. A storage schedule "
<< "is meaningless for functions computed inline.\n";
}
if (s.memoized()) {
user_error << "Cannot memoize function "
<< f.name() << " because the function is scheduled inline.\n";
}
for (size_t i = 0; i < s.dims().size(); i++) {
Dim d = s.dims()[i];
if (d.for_type == ForType::Parallel) {
user_error << "Cannot parallelize dimension "
<< d.var << " of function "
<< f.name() << " because the function is scheduled inline.\n";
} else if (d.for_type == ForType::Unrolled) {
user_error << "Cannot unroll dimension "
<< d.var << " of function "
<< f.name() << " because the function is scheduled inline.\n";
} else if (d.for_type == ForType::Vectorized) {
user_error << "Cannot vectorize dimension "
<< d.var << " of function "
<< f.name() << " because the function is scheduled inline.\n";
}
}
for (size_t i = 0; i < s.splits().size(); i++) {
if (s.splits()[i].is_rename()) {
user_warning << "It is meaningless to rename variable "
<< s.splits()[i].old_var << " of function "
<< f.name() << " to " << s.splits()[i].outer
<< " because " << f.name() << " is scheduled inline.\n";
} else if (s.splits()[i].is_fuse()) {
user_warning << "It is meaningless to fuse variables "
<< s.splits()[i].inner << " and " << s.splits()[i].outer
<< " because " << f.name() << " is scheduled inline.\n";
} else {
user_warning << "It is meaningless to split variable "
<< s.splits()[i].old_var << " of function "
<< f.name() << " into "
<< s.splits()[i].outer << " * "
<< s.splits()[i].factor << " + "
<< s.splits()[i].inner << " because "
<< f.name() << " is scheduled inline.\n";
}
}
for (size_t i = 0; i < s.bounds().size(); i++) {
user_warning << "It is meaningless to bound dimension "
<< s.bounds()[i].var << " of function "
<< f.name() << " to be within ["
<< s.bounds()[i].min << ", "
<< s.bounds()[i].extent << "] because the function is scheduled inline.\n";
}
}
void visit(const Call *op) {
if (op->name == func.name()) {
// Mutate the args
vector<Expr> args(op->args.size());
for (size_t i = 0; i < args.size(); i++) {
args[i] = mutate(op->args[i]);
}
// Grab the body
Expr body = qualify(func.name() + ".", func.values()[op->value_index]);
const vector<string> func_args = func.args();
// Bind the args using Let nodes
internal_assert(args.size() == func_args.size());
for (size_t i = 0; i < args.size(); i++) {
body = Let::make(func.name() + "." + func_args[i], args[i], body);
}
expr = body;
found = true;
} else {
IRMutator::visit(op);
}
}
void visit(const Provide *op) {
bool old_found = found;
found = false;
IRMutator::visit(op);
if (found) {
stmt = common_subexpression_elimination(stmt);
}
found = old_found;
}
public:
bool found;
Inliner(Function f) : func(f), found(false) {
check(func);
}
};
Stmt inline_function(Stmt s, Function f) {
Inliner i(f);
s = i.mutate(s);
return s;
}
Expr inline_function(Expr e, Function f) {
Inliner i(f);
e = i.mutate(e);
if (i.found) {
e = common_subexpression_elimination(e);
}
return e;
}
}
}
<commit_msg>Fix warning<commit_after>#include <set>
#include "Inline.h"
#include "CSE.h"
#include "IRPrinter.h"
#include "IRMutator.h"
#include "Qualify.h"
#include "Debug.h"
namespace Halide {
namespace Internal {
using std::set;
using std::string;
using std::vector;
class Inliner : public IRMutator {
using IRMutator::visit;
Function func;
// Sanity check that this is a reasonable function to inline
void check(Function f) {
internal_assert(f.can_be_inlined()) << "Illegal to inline " << f.name() << "\n";
const Schedule &s = f.schedule();
if (!s.store_level().is_inline()) {
user_error << "Function " << f.name() << " is scheduled to be computed inline, "
<< "but is not scheduled to be stored inline. A storage schedule "
<< "is meaningless for functions computed inline.\n";
}
if (s.memoized()) {
user_error << "Cannot memoize function "
<< f.name() << " because the function is scheduled inline.\n";
}
for (size_t i = 0; i < s.dims().size(); i++) {
Dim d = s.dims()[i];
if (d.for_type == ForType::Parallel) {
user_error << "Cannot parallelize dimension "
<< d.var << " of function "
<< f.name() << " because the function is scheduled inline.\n";
} else if (d.for_type == ForType::Unrolled) {
user_error << "Cannot unroll dimension "
<< d.var << " of function "
<< f.name() << " because the function is scheduled inline.\n";
} else if (d.for_type == ForType::Vectorized) {
user_error << "Cannot vectorize dimension "
<< d.var << " of function "
<< f.name() << " because the function is scheduled inline.\n";
}
}
for (size_t i = 0; i < s.splits().size(); i++) {
if (s.splits()[i].is_rename()) {
user_warning << "It is meaningless to rename variable "
<< s.splits()[i].old_var << " of function "
<< f.name() << " to " << s.splits()[i].outer
<< " because " << f.name() << " is scheduled inline.\n";
} else if (s.splits()[i].is_fuse()) {
user_warning << "It is meaningless to fuse variables "
<< s.splits()[i].inner << " and " << s.splits()[i].outer
<< " because " << f.name() << " is scheduled inline.\n";
} else {
user_warning << "It is meaningless to split variable "
<< s.splits()[i].old_var << " of function "
<< f.name() << " into "
<< s.splits()[i].outer << " * "
<< s.splits()[i].factor << " + "
<< s.splits()[i].inner << " because "
<< f.name() << " is scheduled inline.\n";
}
}
for (size_t i = 0; i < s.bounds().size(); i++) {
if (s.bounds()[i].min.defined()) {
user_warning << "It is meaningless to bound dimension "
<< s.bounds()[i].var << " of function "
<< f.name() << " to be within ["
<< s.bounds()[i].min << ", "
<< s.bounds()[i].extent << "] because the function is scheduled inline.\n";
} else if (s.bounds()[i].modulus.defined()) {
user_warning << "It is meaningless to align the bounds of dimension "
<< s.bounds()[i].var << " of function "
<< f.name() << " to have modulus/remainder ["
<< s.bounds()[i].modulus << ", "
<< s.bounds()[i].remainder << "] because the function is scheduled inline.\n";
}
}
}
void visit(const Call *op) {
if (op->name == func.name()) {
// Mutate the args
vector<Expr> args(op->args.size());
for (size_t i = 0; i < args.size(); i++) {
args[i] = mutate(op->args[i]);
}
// Grab the body
Expr body = qualify(func.name() + ".", func.values()[op->value_index]);
const vector<string> func_args = func.args();
// Bind the args using Let nodes
internal_assert(args.size() == func_args.size());
for (size_t i = 0; i < args.size(); i++) {
body = Let::make(func.name() + "." + func_args[i], args[i], body);
}
expr = body;
found = true;
} else {
IRMutator::visit(op);
}
}
void visit(const Provide *op) {
bool old_found = found;
found = false;
IRMutator::visit(op);
if (found) {
stmt = common_subexpression_elimination(stmt);
}
found = old_found;
}
public:
bool found;
Inliner(Function f) : func(f), found(false) {
check(func);
}
};
Stmt inline_function(Stmt s, Function f) {
Inliner i(f);
s = i.mutate(s);
return s;
}
Expr inline_function(Expr e, Function f) {
Inliner i(f);
e = i.mutate(e);
if (i.found) {
e = common_subexpression_elimination(e);
}
return e;
}
}
}
<|endoftext|> |
<commit_before>//
// Created by qife on 16/1/27.
//
#include "JToken.h"
using namespace JsonCpp;
NodePtrList JToken::ParseJPath(const char *str) const
{
NodePtrList list;
if (*str == '$')
{
++str;
}
else
{
if (*str == '.' || *str == '[')
{
goto ret;
}
}
reterr:
list.clear();
ret:
return list;
}
<commit_msg>add some code<commit_after>//
// Created by qife on 16/1/27.
//
#include "JToken.h"
using namespace JsonCpp;
NodePtrList JToken::ParseJPath(const char *str) const
{
NodePtrList list;
if (*str == '$')
{
++str;
}
else
{
if (*str == '.' || *str == '[')
{
goto ret;
}
}
while (*str)
{
switch (*str)
{
case '.':
if (*(str + 1) == '.')
{
str += 2;
if (*str == '*')
{
list.push_back(std::shared_ptr(new ActionNode(ActionType::ReWildcard)));
++str;
continue;
}
auto tmp = str;
while (*tmp && *tmp != '.' && *tmp != '[' && *tmp != ' ')
{
++tmp;
}
if (tmp == str)
{
goto error;
}
auto node = std::shared_ptr<ActionNode>(new ActionNode(ActionType::ReValueWithKey));
node->actionData.key = new std::string(str, tmp - str);
list.push_back(std::move(node));
str = tmp;
continue;
}
}
}
error:
list.clear();
ret:
return list;
}
<|endoftext|> |
<commit_before>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include "leveldb/db.h"
//using namespace node;
using namespace v8;
class LevelDB : node::ObjectWrap {
private:
leveldb::DB* db;
// Helper to convert a vanilla JS object into a leveldb::Options instance
static leveldb::Options processOptions(Local<Object> opts) {
// Copy the v8 options over an leveldb options object
leveldb::Options options;
if (opts->Has(String::New("create_if_missing"))) {
options.create_if_missing = opts->Get(String::New("create_if_missing"))->BooleanValue();
}
if (opts->Has(String::New("error_if_exists"))) {
options.error_if_exists = opts->Get(String::New("error_if_exists"))->BooleanValue();
}
if (opts->Has(String::New("paranoid_checks"))) {
options.paranoid_checks = opts->Get(String::New("paranoid_checks"))->BooleanValue();
}
if (opts->Has(String::New("write_buffer_size"))) {
options.write_buffer_size = opts->Get(String::New("write_buffer_size"))->Int32Value();
}
if (opts->Has(String::New("max_open_files"))) {
options.max_open_files = opts->Get(String::New("max_open_files"))->Int32Value();
}
if (opts->Has(String::New("block_size"))) {
options.block_size = opts->Get(String::New("block_size"))->Int32Value();
}
if (opts->Has(String::New("block_restart_interval"))) {
options.block_restart_interval = opts->Get(String::New("block_restart_interval"))->Int32Value();
}
return options;
}
// Helper to convert a vanilla JS object into a leveldb::ReadOptions instance
static leveldb::ReadOptions processReadOptions(Local<Object> opts) {
// Copy the v8 options over an leveldb options object
leveldb::ReadOptions options;
if (opts->Has(String::New("verify_checksums"))) {
options.verify_checksums = opts->Get(String::New("verify_checksums"))->BooleanValue();
}
if (opts->Has(String::New("fill_cache"))) {
options.fill_cache = opts->Get(String::New("fill_cache"))->BooleanValue();
}
return options;
}
// Helper to convert a vanilla JS object into a leveldb::WriteOptions instance
static leveldb::WriteOptions processWriteOptions(Local<Object> opts) {
// Copy the v8 options over an leveldb options object
leveldb::WriteOptions options;
if (opts->Has(String::New("sync"))) {
options.sync = opts->Get(String::New("sync"))->BooleanValue();
}
return options;
}
// Helper to convert a leveldb::Status instance to a V8 return value
static Handle<Value> processStatus(leveldb::Status status) {
if (status.ok()) return String::New(status.ToString().c_str());
return ThrowException(Exception::TypeError(String::New(status.ToString().c_str())));
}
static char* BufferData(node::Buffer *b) {
return node::Buffer::Data(b->handle_);
}
static size_t BufferLength(node::Buffer *b) {
return node::Buffer::Length(b->handle_);
}
static char* BufferData(v8::Local<v8::Object> buf_obj) {
v8::HandleScope scope;
return node::Buffer::Data(buf_obj);
}
static size_t BufferLength(v8::Local<v8::Object> buf_obj) {
v8::HandleScope scope;
return node::Buffer::Length(buf_obj);
}
public:
LevelDB() {}
~LevelDB() {}
// Holds our constructor function
static Persistent<FunctionTemplate> persistent_function_template;
static void Init(Handle<Object> target) {
HandleScope scope; // used by v8 for garbage collection
// Our constructor
Local<FunctionTemplate> local_function_template = FunctionTemplate::New(New);
LevelDB::persistent_function_template = Persistent<FunctionTemplate>::New(local_function_template);
LevelDB::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1); // 1 since this is a constructor function
LevelDB::persistent_function_template->SetClassName(String::NewSymbol("LevelDB"));
// Instance methods
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "open", Open);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "close", Close);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "put", Put);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "del", Del);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "write", Write);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "get", Get);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "newIterator", NewIterator);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "getSnapshot", GetSnapshot);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "releaseSnapshot", ReleaseSnapshot);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "getProperty", GetProperty);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "getApproximateSizes", GetApproximateSizes);
// Static methods
NODE_SET_METHOD(LevelDB::persistent_function_template, "destroyDB", DestroyDB);
NODE_SET_METHOD(LevelDB::persistent_function_template, "repairDB", RepairDB);
// Binding our constructor function to the target variable
target->Set(String::NewSymbol("LevelDB"), LevelDB::persistent_function_template->GetFunction());
}
// This is our constructor function. It instantiate a C++ LevelDB object and returns a Javascript handle to this object.
static Handle<Value> New(const Arguments& args) {
HandleScope scope;
LevelDB* LevelDB_instance = new LevelDB();
// Wrap our C++ object as a Javascript object
LevelDB_instance->Wrap(args.This());
// Our constructor function returns a Javascript object which is a wrapper for our C++ object,
// This is the expected behavior when calling a constructor function with the new operator in Javascript.
return args.This();
}
static Handle<Value> Open(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 2 && args[0]->IsObject() && args[1]->IsString())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (Object, String)")));
}
// Get this and arguments
LevelDB* self = node::ObjectWrap::Unwrap<LevelDB>(args.This());
Local<Object> options = Object::Cast(*args[0]);
String::Utf8Value name(args[1]);
// Do actual work
return processStatus(leveldb::DB::Open(processOptions(options), *name, &(self->db)));
}
static Handle<Value> Close(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 0)) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected ()")));
}
LevelDB* self = node::ObjectWrap::Unwrap<LevelDB>(args.This());
delete self->db;
return Undefined();
}
static Handle<Value> DestroyDB(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 2 && args[0]->IsString() && args[1]->IsObject())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (String, Object)")));
}
String::Utf8Value name(args[0]);
Local<Object> options = Object::Cast(*args[1]);
return processStatus(leveldb::DestroyDB(*name, processOptions(options)));
}
static Handle<Value> RepairDB(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 2 && args[0]->IsString() && args[1]->IsObject())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (String, Object)")));
}
String::Utf8Value name(args[0]);
Local<Object> options = Object::Cast(*args[1]);
return processStatus(leveldb::RepairDB(*name, processOptions(options)));
}
static Handle<Value> Put(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 3 && args[0]->IsObject() && args[1]->IsObject() && args[2]->IsObject())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (Object, Buffer, Buffer)")));
}
LevelDB* self = node::ObjectWrap::Unwrap<LevelDB>(args.This());
Local<Object> options = Object::Cast(*args[0]);
Local<Object> key = Object::Cast(*args[1]);
Local<Object> value = Object::Cast(*args[2]);
return processStatus(self->db->Put(processWriteOptions(options), BufferData(key), BufferData(value)));
}
static Handle<Value> Del(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> Write(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> Get(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> NewIterator(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> GetSnapshot(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> ReleaseSnapshot(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> GetProperty(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> GetApproximateSizes(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
};
<commit_msg>Use node's namespace too<commit_after>#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include "leveldb/db.h"
using namespace node;
using namespace v8;
class LevelDB : ObjectWrap {
private:
leveldb::DB* db;
// Helper to convert a vanilla JS object into a leveldb::Options instance
static leveldb::Options processOptions(Local<Object> opts) {
// Copy the v8 options over an leveldb options object
leveldb::Options options;
if (opts->Has(String::New("create_if_missing"))) {
options.create_if_missing = opts->Get(String::New("create_if_missing"))->BooleanValue();
}
if (opts->Has(String::New("error_if_exists"))) {
options.error_if_exists = opts->Get(String::New("error_if_exists"))->BooleanValue();
}
if (opts->Has(String::New("paranoid_checks"))) {
options.paranoid_checks = opts->Get(String::New("paranoid_checks"))->BooleanValue();
}
if (opts->Has(String::New("write_buffer_size"))) {
options.write_buffer_size = opts->Get(String::New("write_buffer_size"))->Int32Value();
}
if (opts->Has(String::New("max_open_files"))) {
options.max_open_files = opts->Get(String::New("max_open_files"))->Int32Value();
}
if (opts->Has(String::New("block_size"))) {
options.block_size = opts->Get(String::New("block_size"))->Int32Value();
}
if (opts->Has(String::New("block_restart_interval"))) {
options.block_restart_interval = opts->Get(String::New("block_restart_interval"))->Int32Value();
}
return options;
}
// Helper to convert a vanilla JS object into a leveldb::ReadOptions instance
static leveldb::ReadOptions processReadOptions(Local<Object> opts) {
// Copy the v8 options over an leveldb options object
leveldb::ReadOptions options;
if (opts->Has(String::New("verify_checksums"))) {
options.verify_checksums = opts->Get(String::New("verify_checksums"))->BooleanValue();
}
if (opts->Has(String::New("fill_cache"))) {
options.fill_cache = opts->Get(String::New("fill_cache"))->BooleanValue();
}
return options;
}
// Helper to convert a vanilla JS object into a leveldb::WriteOptions instance
static leveldb::WriteOptions processWriteOptions(Local<Object> opts) {
// Copy the v8 options over an leveldb options object
leveldb::WriteOptions options;
if (opts->Has(String::New("sync"))) {
options.sync = opts->Get(String::New("sync"))->BooleanValue();
}
return options;
}
// Helper to convert a leveldb::Status instance to a V8 return value
static Handle<Value> processStatus(leveldb::Status status) {
if (status.ok()) return String::New(status.ToString().c_str());
return ThrowException(Exception::TypeError(String::New(status.ToString().c_str())));
}
static char* BufferData(Buffer *b) {
return Buffer::Data(b->handle_);
}
static size_t BufferLength(Buffer *b) {
return Buffer::Length(b->handle_);
}
static char* BufferData(Local<Object> buf_obj) {
HandleScope scope;
return Buffer::Data(buf_obj);
}
static size_t BufferLength(Local<Object> buf_obj) {
HandleScope scope;
return Buffer::Length(buf_obj);
}
public:
LevelDB() {}
~LevelDB() {}
// Holds our constructor function
static Persistent<FunctionTemplate> persistent_function_template;
static void Init(Handle<Object> target) {
HandleScope scope; // used by v8 for garbage collection
// Our constructor
Local<FunctionTemplate> local_function_template = FunctionTemplate::New(New);
LevelDB::persistent_function_template = Persistent<FunctionTemplate>::New(local_function_template);
LevelDB::persistent_function_template->InstanceTemplate()->SetInternalFieldCount(1); // 1 since this is a constructor function
LevelDB::persistent_function_template->SetClassName(String::NewSymbol("LevelDB"));
// Instance methods
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "open", Open);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "close", Close);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "put", Put);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "del", Del);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "write", Write);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "get", Get);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "newIterator", NewIterator);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "getSnapshot", GetSnapshot);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "releaseSnapshot", ReleaseSnapshot);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "getProperty", GetProperty);
NODE_SET_PROTOTYPE_METHOD(LevelDB::persistent_function_template, "getApproximateSizes", GetApproximateSizes);
// Static methods
NODE_SET_METHOD(LevelDB::persistent_function_template, "destroyDB", DestroyDB);
NODE_SET_METHOD(LevelDB::persistent_function_template, "repairDB", RepairDB);
// Binding our constructor function to the target variable
target->Set(String::NewSymbol("LevelDB"), LevelDB::persistent_function_template->GetFunction());
}
// This is our constructor function. It instantiate a C++ LevelDB object and returns a Javascript handle to this object.
static Handle<Value> New(const Arguments& args) {
HandleScope scope;
LevelDB* LevelDB_instance = new LevelDB();
// Wrap our C++ object as a Javascript object
LevelDB_instance->Wrap(args.This());
// Our constructor function returns a Javascript object which is a wrapper for our C++ object,
// This is the expected behavior when calling a constructor function with the new operator in Javascript.
return args.This();
}
static Handle<Value> Open(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 2 && args[0]->IsObject() && args[1]->IsString())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (Object, String)")));
}
// Get this and arguments
LevelDB* self = ObjectWrap::Unwrap<LevelDB>(args.This());
Local<Object> options = Object::Cast(*args[0]);
String::Utf8Value name(args[1]);
// Do actual work
return processStatus(leveldb::DB::Open(processOptions(options), *name, &(self->db)));
}
static Handle<Value> Close(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 0)) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected ()")));
}
LevelDB* self = ObjectWrap::Unwrap<LevelDB>(args.This());
delete self->db;
return Undefined();
}
static Handle<Value> DestroyDB(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 2 && args[0]->IsString() && args[1]->IsObject())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (String, Object)")));
}
String::Utf8Value name(args[0]);
Local<Object> options = Object::Cast(*args[1]);
return processStatus(leveldb::DestroyDB(*name, processOptions(options)));
}
static Handle<Value> RepairDB(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 2 && args[0]->IsString() && args[1]->IsObject())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (String, Object)")));
}
String::Utf8Value name(args[0]);
Local<Object> options = Object::Cast(*args[1]);
return processStatus(leveldb::RepairDB(*name, processOptions(options)));
}
static Handle<Value> Put(const Arguments& args) {
HandleScope scope;
// Check args
if (!(args.Length() == 3 && args[0]->IsObject() && args[1]->IsObject() && args[2]->IsObject())) {
return ThrowException(Exception::TypeError(String::New("Invalid arguments: Expected (Object, Buffer, Buffer)")));
}
LevelDB* self = ObjectWrap::Unwrap<LevelDB>(args.This());
Local<Object> options = Object::Cast(*args[0]);
Local<Object> key = Object::Cast(*args[1]);
Local<Object> value = Object::Cast(*args[2]);
return processStatus(self->db->Put(processWriteOptions(options), BufferData(key), BufferData(value)));
}
static Handle<Value> Del(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> Write(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> Get(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> NewIterator(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> GetSnapshot(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> ReleaseSnapshot(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> GetProperty(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
static Handle<Value> GetApproximateSizes(const Arguments& args) {
HandleScope scope;
return ThrowException(Exception::Error(String::New("TODO: IMPLEMENT ME")));
}
};
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Removed duplicate code.<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3235
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3235 to 3236<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3236
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/*************************************************************************/
/* renderer_scene_render.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "renderer_scene_render.h"
void RendererSceneRender::CameraData::set_camera(const Transform3D p_transform, const CameraMatrix p_projection, bool p_is_ortogonal, bool p_vaspect) {
view_count = 1;
is_ortogonal = p_is_ortogonal;
vaspect = p_vaspect;
main_transform = p_transform;
main_projection = p_projection;
view_offset[0] = Transform3D();
view_projection[0] = p_projection;
}
void RendererSceneRender::CameraData::set_multiview_camera(uint32_t p_view_count, const Transform3D *p_transforms, const CameraMatrix *p_projections, bool p_is_ortogonal, bool p_vaspect) {
ERR_FAIL_COND_MSG(p_view_count != 2, "Incorrect view count for stereoscopic view");
view_count = p_view_count;
is_ortogonal = p_is_ortogonal;
vaspect = p_vaspect;
Vector<Plane> planes[2];
/////////////////////////////////////////////////////////////////////////////
// Figure out our center transform
// 1. obtain our planes
for (uint32_t v = 0; v < view_count; v++) {
planes[v] = p_projections[v].get_projection_planes(p_transforms[v]);
}
// 2. average and normalize plane normals to obtain z vector, cross them to obtain y vector, and from there the x vector for combined camera basis.
Vector3 n0 = planes[0][CameraMatrix::PLANE_LEFT].normal;
Vector3 n1 = planes[1][CameraMatrix::PLANE_RIGHT].normal;
Vector3 z = (n0 + n1).normalized();
Vector3 y = n0.cross(n1).normalized();
Vector3 x = y.cross(z).normalized();
y = z.cross(x).normalized();
main_transform.basis.set(x, y, z);
// 3. create a horizon plane with one of the eyes and the up vector as normal.
Plane horizon(p_transforms[0].origin, y);
// 4. Intersect horizon, left and right to obtain the combined camera origin.
ERR_FAIL_COND_MSG(
!horizon.intersect_3(planes[0][CameraMatrix::PLANE_LEFT], planes[1][CameraMatrix::PLANE_RIGHT], &main_transform.origin), "Can't determine camera origin");
// handy to have the inverse of the transform we just build
Transform3D main_transform_inv = main_transform.inverse();
// 5. figure out far plane, this could use some improvement, we may have our far plane too close like this, not sure if this matters
Vector3 far_center = (planes[0][CameraMatrix::PLANE_FAR].center() + planes[1][CameraMatrix::PLANE_FAR].center()) * 0.5;
Plane far(far_center, -z);
/////////////////////////////////////////////////////////////////////////////
// Figure out our top/bottom planes
// 6. Intersect far and left planes with top planes from both eyes, save the point with highest y as top_left.
Vector3 top_left, other;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_LEFT], planes[0][CameraMatrix::PLANE_TOP], &top_left), "Can't determine left camera far/left/top vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_LEFT], planes[1][CameraMatrix::PLANE_TOP], &other), "Can't determine right camera far/left/top vector");
if (y.dot(top_left) < y.dot(other)) {
top_left = other;
}
// 7. Intersect far and left planes with bottom planes from both eyes, save the point with lowest y as bottom_left.
Vector3 bottom_left;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_LEFT], planes[0][CameraMatrix::PLANE_BOTTOM], &bottom_left), "Can't determine left camera far/left/bottom vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_LEFT], planes[1][CameraMatrix::PLANE_BOTTOM], &other), "Can't determine right camera far/left/bottom vector");
if (y.dot(other) < y.dot(bottom_left)) {
bottom_left = other;
}
// 8. Intersect far and right planes with top planes from both eyes, save the point with highest y as top_right.
Vector3 top_right;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_RIGHT], planes[0][CameraMatrix::PLANE_TOP], &top_right), "Can't determine left camera far/right/top vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_RIGHT], planes[1][CameraMatrix::PLANE_TOP], &other), "Can't determine right camera far/right/top vector");
if (y.dot(top_right) < y.dot(other)) {
top_right = other;
}
// 9. Intersect far and right planes with bottom planes from both eyes, save the point with lowest y as bottom_right.
Vector3 bottom_right;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_RIGHT], planes[0][CameraMatrix::PLANE_BOTTOM], &bottom_right), "Can't determine left camera far/right/bottom vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_RIGHT], planes[1][CameraMatrix::PLANE_BOTTOM], &other), "Can't determine right camera far/right/bottom vector");
if (y.dot(other) < y.dot(bottom_right)) {
bottom_right = other;
}
// 10. Create top plane with these points: camera origin, top_left, top_right
Plane top(main_transform.origin, top_left, top_right);
// 11. Create bottom plane with these points: camera origin, bottom_left, bottom_right
Plane bottom(main_transform.origin, bottom_left, bottom_right);
/////////////////////////////////////////////////////////////////////////////
// Figure out our near plane points
// 12. Create a near plane using -camera z and the eye further along in that axis.
Plane near;
Vector3 neg_z = -z;
if (neg_z.dot(p_transforms[1].origin) < neg_z.dot(p_transforms[0].origin)) {
near = Plane(p_transforms[0].origin, neg_z);
} else {
near = Plane(p_transforms[1].origin, neg_z);
}
// 13. Intersect near plane with bottm/left planes, to obtain min_vec then top/right to obtain max_vec
Vector3 min_vec;
ERR_FAIL_COND_MSG(
!near.intersect_3(bottom, planes[0][CameraMatrix::PLANE_LEFT], &min_vec), "Can't determine left camera near/left/bottom vector");
ERR_FAIL_COND_MSG(
!near.intersect_3(bottom, planes[1][CameraMatrix::PLANE_LEFT], &other), "Can't determine right camera near/left/bottom vector");
if (x.dot(other) < x.dot(min_vec)) {
min_vec = other;
}
Vector3 max_vec;
ERR_FAIL_COND_MSG(
!near.intersect_3(top, planes[0][CameraMatrix::PLANE_RIGHT], &max_vec), "Can't determine left camera near/right/top vector");
ERR_FAIL_COND_MSG(
!near.intersect_3(top, planes[1][CameraMatrix::PLANE_RIGHT], &other), "Can't determine right camera near/right/top vector");
if (x.dot(max_vec) < x.dot(other)) {
max_vec = other;
}
// 14. transform these points by the inverse camera to obtain local_min_vec and local_max_vec
Vector3 local_min_vec = main_transform_inv.xform(min_vec);
Vector3 local_max_vec = main_transform_inv.xform(max_vec);
// 15. get x and y from these to obtain left, top, right bottom for the frustum. Get the distance from near plane to camera origin to obtain near, and the distance from the far plane to the camer origin to obtain far.
float z_near = -near.distance_to(main_transform.origin);
float z_far = -far.distance_to(main_transform.origin);
// 16. Use this to build the combined camera matrix.
main_projection.set_frustum(local_min_vec.x, local_max_vec.x, local_min_vec.y, local_max_vec.y, z_near, z_far);
/////////////////////////////////////////////////////////////////////////////
// 3. Copy our view data
for (uint32_t v = 0; v < view_count; v++) {
view_offset[v] = p_transforms[v] * main_transform_inv;
view_projection[v] = p_projections[v] * CameraMatrix(view_offset[v]);
}
}
<commit_msg>Inverse XR camera offset for stereoscopic rendering<commit_after>/*************************************************************************/
/* renderer_scene_render.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "renderer_scene_render.h"
void RendererSceneRender::CameraData::set_camera(const Transform3D p_transform, const CameraMatrix p_projection, bool p_is_ortogonal, bool p_vaspect) {
view_count = 1;
is_ortogonal = p_is_ortogonal;
vaspect = p_vaspect;
main_transform = p_transform;
main_projection = p_projection;
view_offset[0] = Transform3D();
view_projection[0] = p_projection;
}
void RendererSceneRender::CameraData::set_multiview_camera(uint32_t p_view_count, const Transform3D *p_transforms, const CameraMatrix *p_projections, bool p_is_ortogonal, bool p_vaspect) {
ERR_FAIL_COND_MSG(p_view_count != 2, "Incorrect view count for stereoscopic view");
view_count = p_view_count;
is_ortogonal = p_is_ortogonal;
vaspect = p_vaspect;
Vector<Plane> planes[2];
/////////////////////////////////////////////////////////////////////////////
// Figure out our center transform
// 1. obtain our planes
for (uint32_t v = 0; v < view_count; v++) {
planes[v] = p_projections[v].get_projection_planes(p_transforms[v]);
}
// 2. average and normalize plane normals to obtain z vector, cross them to obtain y vector, and from there the x vector for combined camera basis.
Vector3 n0 = planes[0][CameraMatrix::PLANE_LEFT].normal;
Vector3 n1 = planes[1][CameraMatrix::PLANE_RIGHT].normal;
Vector3 z = (n0 + n1).normalized();
Vector3 y = n0.cross(n1).normalized();
Vector3 x = y.cross(z).normalized();
y = z.cross(x).normalized();
main_transform.basis.set(x, y, z);
// 3. create a horizon plane with one of the eyes and the up vector as normal.
Plane horizon(p_transforms[0].origin, y);
// 4. Intersect horizon, left and right to obtain the combined camera origin.
ERR_FAIL_COND_MSG(
!horizon.intersect_3(planes[0][CameraMatrix::PLANE_LEFT], planes[1][CameraMatrix::PLANE_RIGHT], &main_transform.origin), "Can't determine camera origin");
// handy to have the inverse of the transform we just build
Transform3D main_transform_inv = main_transform.inverse();
// 5. figure out far plane, this could use some improvement, we may have our far plane too close like this, not sure if this matters
Vector3 far_center = (planes[0][CameraMatrix::PLANE_FAR].center() + planes[1][CameraMatrix::PLANE_FAR].center()) * 0.5;
Plane far(far_center, -z);
/////////////////////////////////////////////////////////////////////////////
// Figure out our top/bottom planes
// 6. Intersect far and left planes with top planes from both eyes, save the point with highest y as top_left.
Vector3 top_left, other;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_LEFT], planes[0][CameraMatrix::PLANE_TOP], &top_left), "Can't determine left camera far/left/top vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_LEFT], planes[1][CameraMatrix::PLANE_TOP], &other), "Can't determine right camera far/left/top vector");
if (y.dot(top_left) < y.dot(other)) {
top_left = other;
}
// 7. Intersect far and left planes with bottom planes from both eyes, save the point with lowest y as bottom_left.
Vector3 bottom_left;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_LEFT], planes[0][CameraMatrix::PLANE_BOTTOM], &bottom_left), "Can't determine left camera far/left/bottom vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_LEFT], planes[1][CameraMatrix::PLANE_BOTTOM], &other), "Can't determine right camera far/left/bottom vector");
if (y.dot(other) < y.dot(bottom_left)) {
bottom_left = other;
}
// 8. Intersect far and right planes with top planes from both eyes, save the point with highest y as top_right.
Vector3 top_right;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_RIGHT], planes[0][CameraMatrix::PLANE_TOP], &top_right), "Can't determine left camera far/right/top vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_RIGHT], planes[1][CameraMatrix::PLANE_TOP], &other), "Can't determine right camera far/right/top vector");
if (y.dot(top_right) < y.dot(other)) {
top_right = other;
}
// 9. Intersect far and right planes with bottom planes from both eyes, save the point with lowest y as bottom_right.
Vector3 bottom_right;
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[0][CameraMatrix::PLANE_RIGHT], planes[0][CameraMatrix::PLANE_BOTTOM], &bottom_right), "Can't determine left camera far/right/bottom vector");
ERR_FAIL_COND_MSG(
!far.intersect_3(planes[1][CameraMatrix::PLANE_RIGHT], planes[1][CameraMatrix::PLANE_BOTTOM], &other), "Can't determine right camera far/right/bottom vector");
if (y.dot(other) < y.dot(bottom_right)) {
bottom_right = other;
}
// 10. Create top plane with these points: camera origin, top_left, top_right
Plane top(main_transform.origin, top_left, top_right);
// 11. Create bottom plane with these points: camera origin, bottom_left, bottom_right
Plane bottom(main_transform.origin, bottom_left, bottom_right);
/////////////////////////////////////////////////////////////////////////////
// Figure out our near plane points
// 12. Create a near plane using -camera z and the eye further along in that axis.
Plane near;
Vector3 neg_z = -z;
if (neg_z.dot(p_transforms[1].origin) < neg_z.dot(p_transforms[0].origin)) {
near = Plane(p_transforms[0].origin, neg_z);
} else {
near = Plane(p_transforms[1].origin, neg_z);
}
// 13. Intersect near plane with bottm/left planes, to obtain min_vec then top/right to obtain max_vec
Vector3 min_vec;
ERR_FAIL_COND_MSG(
!near.intersect_3(bottom, planes[0][CameraMatrix::PLANE_LEFT], &min_vec), "Can't determine left camera near/left/bottom vector");
ERR_FAIL_COND_MSG(
!near.intersect_3(bottom, planes[1][CameraMatrix::PLANE_LEFT], &other), "Can't determine right camera near/left/bottom vector");
if (x.dot(other) < x.dot(min_vec)) {
min_vec = other;
}
Vector3 max_vec;
ERR_FAIL_COND_MSG(
!near.intersect_3(top, planes[0][CameraMatrix::PLANE_RIGHT], &max_vec), "Can't determine left camera near/right/top vector");
ERR_FAIL_COND_MSG(
!near.intersect_3(top, planes[1][CameraMatrix::PLANE_RIGHT], &other), "Can't determine right camera near/right/top vector");
if (x.dot(max_vec) < x.dot(other)) {
max_vec = other;
}
// 14. transform these points by the inverse camera to obtain local_min_vec and local_max_vec
Vector3 local_min_vec = main_transform_inv.xform(min_vec);
Vector3 local_max_vec = main_transform_inv.xform(max_vec);
// 15. get x and y from these to obtain left, top, right bottom for the frustum. Get the distance from near plane to camera origin to obtain near, and the distance from the far plane to the camer origin to obtain far.
float z_near = -near.distance_to(main_transform.origin);
float z_far = -far.distance_to(main_transform.origin);
// 16. Use this to build the combined camera matrix.
main_projection.set_frustum(local_min_vec.x, local_max_vec.x, local_min_vec.y, local_max_vec.y, z_near, z_far);
/////////////////////////////////////////////////////////////////////////////
// 3. Copy our view data
for (uint32_t v = 0; v < view_count; v++) {
view_offset[v] = main_transform_inv * p_transforms[v];
view_projection[v] = p_projections[v] * CameraMatrix(view_offset[v].inverse());
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3463
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3463 to 3464<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3464
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>//
// Copyright (C) 2006 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include "mp/MpBuf.h"
#include "mp/MpMisc.h"
#include "mp/MpTestResource.h"
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
static const int RESOURCE_MSG_TYPE = MpFlowGraphMsg::RESOURCE_SPECIFIC_START;
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
/* ============================ MANIPULATORS ============================== */
/* ============================ ACCESSORS ================================= */
/* ============================ INQUIRY =================================== */
// Constructor
MpTestResource::MpTestResource(const UtlString& rName
, int minInputs, int maxInputs
, int minOutputs, int maxOutputs
, int samplesPerFrame, int samplesPerSec
)
: MpAudioResource(rName, minInputs, maxInputs, minOutputs, maxOutputs,
samplesPerFrame, samplesPerSec),
mGenOutBufMask(0),
mProcessInBufMask(0),
mProcessedCnt(0),
mMsgCnt(0),
mLastMsg(0)
{
mLastDoProcessArgs.inBufs = new MpBufPtr[mMaxInputs];
mLastDoProcessArgs.outBufs = new MpBufPtr[mMaxOutputs];
}
// Destructor
MpTestResource::~MpTestResource()
{
if (mLastDoProcessArgs.inBufs != NULL)
delete[] mLastDoProcessArgs.inBufs;
if (mLastDoProcessArgs.outBufs != NULL)
delete[] mLastDoProcessArgs.outBufs;
}
/* ============================ MANIPULATORS ============================== */
// Sends a test message to this resource.
void MpTestResource::sendTestMessage(void* ptr1, void* ptr2,
int int3, int int4)
{
MpFlowGraphMsg msg(RESOURCE_MSG_TYPE, this, ptr1, ptr2, int3, int4);
OsStatus res;
res = postMessage(msg);
}
// Specify the genOutBufMask.
// For each bit in the genOutBufMask that is set, if there is a
// resource connected to the corresponding output port, doProcessFrame()
// will create an output buffer on that output port.
void MpTestResource::setGenOutBufMask(int mask)
{
mGenOutBufMask = mask;
}
// Specify the processInBufMask.
// For each bit in the processInBufMask that is set, doProcessFrame()
// will pass the input buffer from the corresponding input port,
// straight through to the corresponding output port. If nothing is
// connected on the corresponding output port, the input buffer will
// be deleted.
void MpTestResource::setProcessInBufMask(int mask)
{
mProcessInBufMask = mask;
}
/* ============================ ACCESSORS ================================= */
// Returns the count of the number of frames processed by this resource.
int MpTestResource::numFramesProcessed(void)
{
return mProcessedCnt;
}
// Returns the count of the number of messages successfully processed by
// this resource.
int MpTestResource::numMsgsProcessed(void)
{
return mMsgCnt;
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
// Processes the next frame interval's worth of media.
UtlBoolean MpTestResource::doProcessFrame(MpBufPtr inBufs[],
MpBufPtr outBufs[],
int inBufsSize,
int outBufsSize,
UtlBoolean isEnabled,
int samplesPerFrame,
int samplesPerSecond)
{
int i=0;
// keep a copy of the input buffers
for (i=0; i<mMaxInputs; i++) {
mLastDoProcessArgs.inBufs[i] = inBufs[i];
}
// keep a copy of the arguments passed to this method
mLastDoProcessArgs.inBufsSize = inBufsSize;
mLastDoProcessArgs.outBufsSize = outBufsSize;
mLastDoProcessArgs.isEnabled = isEnabled;
mLastDoProcessArgs.samplesPerFrame = samplesPerFrame;
mLastDoProcessArgs.samplesPerSecond = samplesPerSecond;
for (i=0; i < outBufsSize; i++)
{
outBufs[i].release();
if (isOutputConnected(i))
{
if ((mProcessInBufMask & (1 << i)) &&
(inBufsSize > i))
{
// if the corresponding bit in the mProcessInBufMask is set for
// the input port then pass the input buffer straight thru
outBufs[i] = inBufs[i];
inBufs[i].release();
}
if ( isEnabled &&
(mGenOutBufMask & (1 << i)) &&
(!outBufs[i].isValid()))
{
// if the output buffer is presently NULL and the corresponding
// bit in the mGenOutBufMask is set then allocate a new buffer
// for the output port
assert(MpMisc.RawAudioPool != NULL);
MpAudioBufPtr pBuf = MpMisc.RawAudioPool->getBuffer();
memset(pBuf->getSamples(), 0,
pBuf->getSamplesNumber()*sizeof(MpAudioSample));
outBufs[i] = pBuf;
}
}
}
for (i=0; i < inBufsSize; i++)
{
// if the corresponding bit in the mProcessInBufMask is set and we
// haven't processed the input buffer then free it.
if ((mProcessInBufMask & (1 << i)) &&
(inBufs[i].isValid()))
{
inBufs[i].release();
}
}
mProcessedCnt++;
// keep a copy of the generated buffers
for (i=0; i<mMaxOutputs; i++) {
mLastDoProcessArgs.outBufs[i] = outBufs[i];
}
return TRUE;
}
// Handles messages for this resource.
UtlBoolean MpTestResource::handleMessage(MpFlowGraphMsg& rMsg)
{
mLastMsg = rMsg;
mMsgCnt++;
if (rMsg.getMsg() == RESOURCE_MSG_TYPE)
return TRUE;
else
return MpAudioResource::handleMessage(rMsg);
}
/* ============================ FUNCTIONS ================================= */
<commit_msg>MpTestResource: Order of member variables initialization made consistent with order of their declaration.<commit_after>//
// Copyright (C) 2006 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2004-2006 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// Copyright (C) 2004-2006 Pingtel Corp. All rights reserved.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// SYSTEM INCLUDES
#include <assert.h>
// APPLICATION INCLUDES
#include "mp/MpBuf.h"
#include "mp/MpMisc.h"
#include "mp/MpTestResource.h"
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
// STATIC VARIABLE INITIALIZATIONS
static const int RESOURCE_MSG_TYPE = MpFlowGraphMsg::RESOURCE_SPECIFIC_START;
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
/* ============================ MANIPULATORS ============================== */
/* ============================ ACCESSORS ================================= */
/* ============================ INQUIRY =================================== */
// Constructor
MpTestResource::MpTestResource(const UtlString& rName
, int minInputs, int maxInputs
, int minOutputs, int maxOutputs
, int samplesPerFrame, int samplesPerSec
)
: MpAudioResource(rName, minInputs, maxInputs, minOutputs, maxOutputs,
samplesPerFrame, samplesPerSec),
mGenOutBufMask(0),
mProcessInBufMask(0),
mLastMsg(0),
mProcessedCnt(0),
mMsgCnt(0)
{
mLastDoProcessArgs.inBufs = new MpBufPtr[mMaxInputs];
mLastDoProcessArgs.outBufs = new MpBufPtr[mMaxOutputs];
}
// Destructor
MpTestResource::~MpTestResource()
{
if (mLastDoProcessArgs.inBufs != NULL)
delete[] mLastDoProcessArgs.inBufs;
if (mLastDoProcessArgs.outBufs != NULL)
delete[] mLastDoProcessArgs.outBufs;
}
/* ============================ MANIPULATORS ============================== */
// Sends a test message to this resource.
void MpTestResource::sendTestMessage(void* ptr1, void* ptr2,
int int3, int int4)
{
MpFlowGraphMsg msg(RESOURCE_MSG_TYPE, this, ptr1, ptr2, int3, int4);
OsStatus res;
res = postMessage(msg);
}
// Specify the genOutBufMask.
// For each bit in the genOutBufMask that is set, if there is a
// resource connected to the corresponding output port, doProcessFrame()
// will create an output buffer on that output port.
void MpTestResource::setGenOutBufMask(int mask)
{
mGenOutBufMask = mask;
}
// Specify the processInBufMask.
// For each bit in the processInBufMask that is set, doProcessFrame()
// will pass the input buffer from the corresponding input port,
// straight through to the corresponding output port. If nothing is
// connected on the corresponding output port, the input buffer will
// be deleted.
void MpTestResource::setProcessInBufMask(int mask)
{
mProcessInBufMask = mask;
}
/* ============================ ACCESSORS ================================= */
// Returns the count of the number of frames processed by this resource.
int MpTestResource::numFramesProcessed(void)
{
return mProcessedCnt;
}
// Returns the count of the number of messages successfully processed by
// this resource.
int MpTestResource::numMsgsProcessed(void)
{
return mMsgCnt;
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
// Processes the next frame interval's worth of media.
UtlBoolean MpTestResource::doProcessFrame(MpBufPtr inBufs[],
MpBufPtr outBufs[],
int inBufsSize,
int outBufsSize,
UtlBoolean isEnabled,
int samplesPerFrame,
int samplesPerSecond)
{
int i=0;
// keep a copy of the input buffers
for (i=0; i<mMaxInputs; i++) {
mLastDoProcessArgs.inBufs[i] = inBufs[i];
}
// keep a copy of the arguments passed to this method
mLastDoProcessArgs.inBufsSize = inBufsSize;
mLastDoProcessArgs.outBufsSize = outBufsSize;
mLastDoProcessArgs.isEnabled = isEnabled;
mLastDoProcessArgs.samplesPerFrame = samplesPerFrame;
mLastDoProcessArgs.samplesPerSecond = samplesPerSecond;
for (i=0; i < outBufsSize; i++)
{
outBufs[i].release();
if (isOutputConnected(i))
{
if ((mProcessInBufMask & (1 << i)) &&
(inBufsSize > i))
{
// if the corresponding bit in the mProcessInBufMask is set for
// the input port then pass the input buffer straight thru
outBufs[i] = inBufs[i];
inBufs[i].release();
}
if ( isEnabled &&
(mGenOutBufMask & (1 << i)) &&
(!outBufs[i].isValid()))
{
// if the output buffer is presently NULL and the corresponding
// bit in the mGenOutBufMask is set then allocate a new buffer
// for the output port
assert(MpMisc.RawAudioPool != NULL);
MpAudioBufPtr pBuf = MpMisc.RawAudioPool->getBuffer();
memset(pBuf->getSamples(), 0,
pBuf->getSamplesNumber()*sizeof(MpAudioSample));
outBufs[i] = pBuf;
}
}
}
for (i=0; i < inBufsSize; i++)
{
// if the corresponding bit in the mProcessInBufMask is set and we
// haven't processed the input buffer then free it.
if ((mProcessInBufMask & (1 << i)) &&
(inBufs[i].isValid()))
{
inBufs[i].release();
}
}
mProcessedCnt++;
// keep a copy of the generated buffers
for (i=0; i<mMaxOutputs; i++) {
mLastDoProcessArgs.outBufs[i] = outBufs[i];
}
return TRUE;
}
// Handles messages for this resource.
UtlBoolean MpTestResource::handleMessage(MpFlowGraphMsg& rMsg)
{
mLastMsg = rMsg;
mMsgCnt++;
if (rMsg.getMsg() == RESOURCE_MSG_TYPE)
return TRUE;
else
return MpAudioResource::handleMessage(rMsg);
}
/* ============================ FUNCTIONS ================================= */
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2017 Axel Waggershauser
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/LJpegDecompressor.h"
#include "common/Common.h" // for uint32, unroll_loop, ushort16
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpJPEG.h" // for BitPumpJPEG
#include <algorithm> // for min, copy_n
using std::copy_n;
namespace rawspeed {
LJpegDecompressor::LJpegDecompressor(const ByteStream& bs, const RawImage& img)
: AbstractLJpegDecompressor(bs, img) {
if (mRaw->getDataType() != TYPE_USHORT16)
ThrowRDE("Unexpected data type (%u)", mRaw->getDataType());
if (!((mRaw->getCpp() == 1 && mRaw->getBpp() == 2) ||
(mRaw->getCpp() == 3 && mRaw->getBpp() == 6)))
ThrowRDE("Unexpected component count (%u)", mRaw->getCpp());
if (mRaw->dim.x == 0 || mRaw->dim.y == 0)
ThrowRDE("Image has zero size");
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
// Yeah, sure, here it would be just dumb to leave this for production :)
if (mRaw->dim.x > 7424 || mRaw->dim.y > 5552) {
ThrowRDE("Unexpected image dimensions found: (%u; %u)", mRaw->dim.x,
mRaw->dim.y);
}
#endif
}
void LJpegDecompressor::decode(uint32 offsetX, uint32 offsetY, uint32 width,
uint32 height, bool fixDng16Bug_) {
if (offsetX >= static_cast<unsigned>(mRaw->dim.x))
ThrowRDE("X offset outside of image");
if (offsetY >= static_cast<unsigned>(mRaw->dim.y))
ThrowRDE("Y offset outside of image");
offX = offsetX;
offY = offsetY;
w = width;
h = height;
fixDng16Bug = fixDng16Bug_;
AbstractLJpegDecompressor::decode();
}
void LJpegDecompressor::decodeScan()
{
if (predictorMode != 1)
ThrowRDE("Unsupported predictor mode: %u", predictorMode);
for (uint32 i = 0; i < frame.cps; i++)
if (frame.compInfo[i].superH != 1 || frame.compInfo[i].superV != 1)
ThrowRDE("Unsupported subsampling");
assert(static_cast<unsigned>(mRaw->dim.x) > offX);
if ((mRaw->getCpp() * (mRaw->dim.x - offX)) < frame.cps)
ThrowRDE("Got less pixels than the components per sample");
const auto frameWidth = frame.cps * frame.w;
if (frameWidth < w || frame.h < h) {
ThrowRDE("LJpeg frame (%u, %u) is smaller than expected (%u, %u)",
frameWidth, frame.h, w, h);
}
switch (frame.cps) {
case 2:
decodeN<2>();
break;
case 3:
decodeN<3>();
break;
case 4:
decodeN<4>();
break;
default:
ThrowRDE("Unsupported number of components: %u", frame.cps);
}
}
// N_COMP == number of components (2, 3 or 4)
template <int N_COMP>
void LJpegDecompressor::decodeN()
{
assert(mRaw->getCpp() > 0);
assert(N_COMP > 0);
assert(N_COMP >= mRaw->getCpp());
assert((N_COMP / mRaw->getCpp()) > 0);
assert(mRaw->dim.x >= N_COMP);
assert((mRaw->getCpp() * (mRaw->dim.x - offX)) >= N_COMP);
auto ht = getHuffmanTables<N_COMP>();
auto pred = getInitialPredictors<N_COMP>();
auto predNext = pred.data();
BitPumpJPEG bitStream(input);
// A recoded DNG might be split up into tiles of self contained LJpeg blobs.
// The tiles at the bottom and the right may extend beyond the dimension of
// the raw image buffer. The excessive content has to be ignored.
// For y, we can simply stop decoding when we reached the border.
for (unsigned y = 0; y < std::min(frame.h, std::min(h, mRaw->dim.y - offY));
++y) {
auto destY = offY + y;
auto dest =
reinterpret_cast<ushort16*>(mRaw->getDataUncropped(offX, destY));
copy_n(predNext, N_COMP, pred.data());
// the predictor for the next line is the start of this line
predNext = dest;
unsigned width = std::min(
frame.w, (mRaw->getCpp() * std::min(w, mRaw->dim.x - offX)) / N_COMP);
// For x, we first process all pixels within the image buffer ...
for (unsigned x = 0; x < width; ++x) {
unroll_loop<N_COMP>([&](int i) {
*dest++ = pred[i] += ht[i]->decodeNext(bitStream);
});
}
// ... and discard the rest.
for (unsigned x = width; x < frame.w; ++x) {
unroll_loop<N_COMP>([&](int i) {
ht[i]->decodeNext(bitStream);
});
}
}
}
} // namespace rawspeed
<commit_msg>LJpegDecompressor::decodeN(): move the 'real' slice size calculations up<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2017 Axel Waggershauser
Copyright (C) 2017 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/LJpegDecompressor.h"
#include "common/Common.h" // for uint32, unroll_loop, ushort16
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "io/BitPumpJPEG.h" // for BitPumpJPEG
#include <algorithm> // for min, copy_n
using std::copy_n;
namespace rawspeed {
LJpegDecompressor::LJpegDecompressor(const ByteStream& bs, const RawImage& img)
: AbstractLJpegDecompressor(bs, img) {
if (mRaw->getDataType() != TYPE_USHORT16)
ThrowRDE("Unexpected data type (%u)", mRaw->getDataType());
if (!((mRaw->getCpp() == 1 && mRaw->getBpp() == 2) ||
(mRaw->getCpp() == 3 && mRaw->getBpp() == 6)))
ThrowRDE("Unexpected component count (%u)", mRaw->getCpp());
if (mRaw->dim.x == 0 || mRaw->dim.y == 0)
ThrowRDE("Image has zero size");
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
// Yeah, sure, here it would be just dumb to leave this for production :)
if (mRaw->dim.x > 7424 || mRaw->dim.y > 5552) {
ThrowRDE("Unexpected image dimensions found: (%u; %u)", mRaw->dim.x,
mRaw->dim.y);
}
#endif
}
void LJpegDecompressor::decode(uint32 offsetX, uint32 offsetY, uint32 width,
uint32 height, bool fixDng16Bug_) {
if (offsetX >= static_cast<unsigned>(mRaw->dim.x))
ThrowRDE("X offset outside of image");
if (offsetY >= static_cast<unsigned>(mRaw->dim.y))
ThrowRDE("Y offset outside of image");
offX = offsetX;
offY = offsetY;
w = width;
h = height;
fixDng16Bug = fixDng16Bug_;
AbstractLJpegDecompressor::decode();
}
void LJpegDecompressor::decodeScan()
{
if (predictorMode != 1)
ThrowRDE("Unsupported predictor mode: %u", predictorMode);
for (uint32 i = 0; i < frame.cps; i++)
if (frame.compInfo[i].superH != 1 || frame.compInfo[i].superV != 1)
ThrowRDE("Unsupported subsampling");
assert(static_cast<unsigned>(mRaw->dim.x) > offX);
if ((mRaw->getCpp() * (mRaw->dim.x - offX)) < frame.cps)
ThrowRDE("Got less pixels than the components per sample");
const auto frameWidth = frame.cps * frame.w;
if (frameWidth < w || frame.h < h) {
ThrowRDE("LJpeg frame (%u, %u) is smaller than expected (%u, %u)",
frameWidth, frame.h, w, h);
}
switch (frame.cps) {
case 2:
decodeN<2>();
break;
case 3:
decodeN<3>();
break;
case 4:
decodeN<4>();
break;
default:
ThrowRDE("Unsupported number of components: %u", frame.cps);
}
}
// N_COMP == number of components (2, 3 or 4)
template <int N_COMP>
void LJpegDecompressor::decodeN()
{
assert(mRaw->getCpp() > 0);
assert(N_COMP > 0);
assert(N_COMP >= mRaw->getCpp());
assert((N_COMP / mRaw->getCpp()) > 0);
assert(mRaw->dim.x >= N_COMP);
assert((mRaw->getCpp() * (mRaw->dim.x - offX)) >= N_COMP);
auto ht = getHuffmanTables<N_COMP>();
auto pred = getInitialPredictors<N_COMP>();
auto predNext = pred.data();
BitPumpJPEG bitStream(input);
// A recoded DNG might be split up into tiles of self contained LJpeg blobs.
// The tiles at the bottom and the right may extend beyond the dimension of
// the raw image buffer. The excessive content has to be ignored.
const auto height = std::min(frame.h, std::min(h, mRaw->dim.y - offY));
const auto width = std::min(
frame.w, (mRaw->getCpp() * std::min(w, mRaw->dim.x - offX)) / N_COMP);
// For y, we can simply stop decoding when we reached the border.
for (unsigned y = 0; y < height; ++y) {
auto destY = offY + y;
auto dest =
reinterpret_cast<ushort16*>(mRaw->getDataUncropped(offX, destY));
copy_n(predNext, N_COMP, pred.data());
// the predictor for the next line is the start of this line
predNext = dest;
// For x, we first process all pixels within the image buffer ...
for (unsigned x = 0; x < width; ++x) {
unroll_loop<N_COMP>([&](int i) {
*dest++ = pred[i] += ht[i]->decodeNext(bitStream);
});
}
// ... and discard the rest.
for (unsigned x = width; x < frame.w; ++x) {
unroll_loop<N_COMP>([&](int i) {
ht[i]->decodeNext(bitStream);
});
}
}
}
} // namespace rawspeed
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/NikonDecompressor.h"
#include "common/Common.h" // for uint32, ushort16, clampBits
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData, RawI...
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/BitPumpMSB.h" // for BitPumpMSB, BitStream<>::fil...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include <cstdio> // for size_t, NULL
#include <vector> // for vector, allocator
using std::vector;
namespace rawspeed {
const uchar8 NikonDecompressor::nikon_tree[][2][16] = {
{/* 12-bit lossy */
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
{5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}},
{/* 12-bit lossy after split */
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
{0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}},
{/* 12-bit lossless */
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}},
{/* 14-bit lossy */
{0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
{5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}},
{/* 14-bit lossy after split */
{0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0},
{8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}},
{/* 14-bit lossless */
{0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0},
{7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}},
};
HuffmanTable NikonDecompressor::createHuffmanTable(uint32 huffSelect) {
HuffmanTable ht;
uint32 count = ht.setNCodesPerLength(Buffer(nikon_tree[huffSelect][0], 16));
ht.setCodeValues(Buffer(nikon_tree[huffSelect][1], count));
ht.setup(true, false);
return ht;
}
void NikonDecompressor::decompress(RawImage* mRaw, ByteStream&& data,
ByteStream metadata, const iPoint2D& size,
uint32 bitsPS, bool uncorrectedRawValues) {
uint32 v0 = metadata.getByte();
uint32 v1 = metadata.getByte();
uint32 huffSelect = 0;
uint32 split = 0;
int pUp1[2];
int pUp2[2];
writeLog(DEBUG_PRIO_EXTRA, "Nef version v0:%u, v1:%u", v0, v1);
if (v0 == 73 || v1 == 88)
metadata.skipBytes(2110);
if (v0 == 70)
huffSelect = 2;
if (bitsPS == 14)
huffSelect += 3;
pUp1[0] = metadata.getU16();
pUp1[1] = metadata.getU16();
pUp2[0] = metadata.getU16();
pUp2[1] = metadata.getU16();
// 'curve' will hold a peace wise linearly interpolated function.
// there are 'csize' segements, each is 'step' values long.
// the very last value is not part of the used table but necessary
// to linearly interpolate the last segment, therefor the '+1/-1'
// size adjustments of 'curve'.
vector<ushort16> curve((1 << bitsPS & 0x7fff)+1);
for (size_t i = 0; i < curve.size(); i++)
curve[i] = i;
uint32 step = 0;
uint32 csize = metadata.getU16();
if (csize > 1)
step = curve.size() / (csize - 1);
if (v0 == 68 && v1 == 32 && step > 0) {
for (size_t i = 0; i < csize; i++)
curve[i*step] = metadata.getU16();
for (size_t i = 0; i < curve.size()-1; i++)
curve[i] = (curve[i-i%step] * (step - i % step) +
curve[i-i%step+step] * (i % step)) / step;
metadata.setPosition(562);
split = metadata.getU16();
} else if (v0 != 70 && csize <= 0x4001) {
curve.resize(csize + 1UL);
for (uint32 i = 0; i < csize; i++) {
curve[i] = metadata.getU16();
}
}
// and drop the last value
curve.resize(curve.size() - 1);
HuffmanTable ht = createHuffmanTable(huffSelect);
RawImageCurveGuard curveHandler(mRaw, curve, uncorrectedRawValues);
BitPumpMSB bits(data);
uchar8* draw = mRaw->get()->getData();
uint32 pitch = mRaw->get()->pitch;
int pLeft1 = 0;
int pLeft2 = 0;
uint32 cw = size.x / 2;
uint32 random = bits.peekBits(24);
//allow gcc to devirtualize the calls below
auto* rawdata = reinterpret_cast<RawImageDataU16*>(mRaw->get());
for (uint32 y = 0; y < static_cast<unsigned>(size.y); y++) {
if (split && y == split) {
ht = createHuffmanTable(huffSelect + 1);
}
auto* dest =
reinterpret_cast<ushort16*>(&draw[y * pitch]); // Adjust destination
pUp1[y&1] += ht.decodeNext(bits);
pUp2[y&1] += ht.decodeNext(bits);
pLeft1 = pUp1[y&1];
pLeft2 = pUp2[y&1];
rawdata->setWithLookUp(clampBits(pLeft1, 15),
reinterpret_cast<uchar8*>(dest + 0), &random);
rawdata->setWithLookUp(clampBits(pLeft2, 15),
reinterpret_cast<uchar8*>(dest + 1), &random);
dest += 2;
for (uint32 x = 1; x < cw; x++) {
pLeft1 += ht.decodeNext(bits);
pLeft2 += ht.decodeNext(bits);
rawdata->setWithLookUp(clampBits(pLeft1, 15),
reinterpret_cast<uchar8*>(dest + 0), &random);
rawdata->setWithLookUp(clampBits(pLeft2, 15),
reinterpret_cast<uchar8*>(dest + 1), &random);
dest += 2;
}
}
}
} // namespace rawspeed
<commit_msg>NikonDecompressor: sanitize curve generation<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/NikonDecompressor.h"
#include "common/Common.h" // for uint32, ushort16, clampBits
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImageData, RawI...
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include "decompressors/HuffmanTable.h" // for HuffmanTable
#include "io/BitPumpMSB.h" // for BitPumpMSB, BitStream<>::fil...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include <cstdio> // for size_t, NULL
#include <vector> // for vector, allocator
using std::vector;
namespace rawspeed {
const uchar8 NikonDecompressor::nikon_tree[][2][16] = {
{/* 12-bit lossy */
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
{5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}},
{/* 12-bit lossy after split */
{0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
{0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}},
{/* 12-bit lossless */
{0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}},
{/* 14-bit lossy */
{0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0},
{5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}},
{/* 14-bit lossy after split */
{0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0},
{8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}},
{/* 14-bit lossless */
{0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0},
{7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}},
};
HuffmanTable NikonDecompressor::createHuffmanTable(uint32 huffSelect) {
HuffmanTable ht;
uint32 count = ht.setNCodesPerLength(Buffer(nikon_tree[huffSelect][0], 16));
ht.setCodeValues(Buffer(nikon_tree[huffSelect][1], count));
ht.setup(true, false);
return ht;
}
void NikonDecompressor::decompress(RawImage* mRaw, ByteStream&& data,
ByteStream metadata, const iPoint2D& size,
uint32 bitsPS, bool uncorrectedRawValues) {
assert(bitsPS > 0);
uint32 v0 = metadata.getByte();
uint32 v1 = metadata.getByte();
uint32 huffSelect = 0;
uint32 split = 0;
int pUp1[2];
int pUp2[2];
writeLog(DEBUG_PRIO_EXTRA, "Nef version v0:%u, v1:%u", v0, v1);
if (v0 == 73 || v1 == 88)
metadata.skipBytes(2110);
if (v0 == 70)
huffSelect = 2;
if (bitsPS == 14)
huffSelect += 3;
pUp1[0] = metadata.getU16();
pUp1[1] = metadata.getU16();
pUp2[0] = metadata.getU16();
pUp2[1] = metadata.getU16();
// 'curve' will hold a peace wise linearly interpolated function.
// there are 'csize' segements, each is 'step' values long.
// the very last value is not part of the used table but necessary
// to linearly interpolate the last segment, therefor the '+1/-1'
// size adjustments of 'curve'.
vector<ushort16> curve((1 << bitsPS & 0x7fff)+1);
assert(curve.size() > 1);
for (size_t i = 0; i < curve.size(); i++)
curve[i] = i;
uint32 step = 0;
uint32 csize = metadata.getU16();
if (csize > 1)
step = curve.size() / (csize - 1);
if (v0 == 68 && v1 == 32 && step > 0) {
for (size_t i = 0; i < csize; i++)
curve[i*step] = metadata.getU16();
for (size_t i = 0; i < curve.size()-1; i++)
curve[i] = (curve[i-i%step] * (step - i % step) +
curve[i-i%step+step] * (i % step)) / step;
metadata.setPosition(562);
split = metadata.getU16();
} else if (v0 != 70) {
if (csize == 0 || csize > 0x4001)
ThrowRDE("Don't know how to compute curve! csize = %u", csize);
curve.resize(csize + 1UL);
assert(curve.size() > 1);
for (uint32 i = 0; i < csize; i++) {
curve[i] = metadata.getU16();
}
}
// and drop the last value
curve.resize(curve.size() - 1);
assert(!curve.empty());
HuffmanTable ht = createHuffmanTable(huffSelect);
RawImageCurveGuard curveHandler(mRaw, curve, uncorrectedRawValues);
BitPumpMSB bits(data);
uchar8* draw = mRaw->get()->getData();
uint32 pitch = mRaw->get()->pitch;
int pLeft1 = 0;
int pLeft2 = 0;
uint32 cw = size.x / 2;
uint32 random = bits.peekBits(24);
//allow gcc to devirtualize the calls below
auto* rawdata = reinterpret_cast<RawImageDataU16*>(mRaw->get());
for (uint32 y = 0; y < static_cast<unsigned>(size.y); y++) {
if (split && y == split) {
ht = createHuffmanTable(huffSelect + 1);
}
auto* dest =
reinterpret_cast<ushort16*>(&draw[y * pitch]); // Adjust destination
pUp1[y&1] += ht.decodeNext(bits);
pUp2[y&1] += ht.decodeNext(bits);
pLeft1 = pUp1[y&1];
pLeft2 = pUp2[y&1];
rawdata->setWithLookUp(clampBits(pLeft1, 15),
reinterpret_cast<uchar8*>(dest + 0), &random);
rawdata->setWithLookUp(clampBits(pLeft2, 15),
reinterpret_cast<uchar8*>(dest + 1), &random);
dest += 2;
for (uint32 x = 1; x < cw; x++) {
pLeft1 += ht.decodeNext(bits);
pLeft2 += ht.decodeNext(bits);
rawdata->setWithLookUp(clampBits(pLeft1, 15),
reinterpret_cast<uchar8*>(dest + 0), &random);
rawdata->setWithLookUp(clampBits(pLeft2, 15),
reinterpret_cast<uchar8*>(dest + 1), &random);
dest += 2;
}
}
}
} // namespace rawspeed
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.