text
stringlengths 54
60.6k
|
---|
<commit_before>#include "stdafx.h"
#include "Misc.h"
#include "Common.h"
#include "Core/FileManager.h"
#include <iostream>
#ifdef _MSC_VER
#include <Windows.h>
#endif
std::vector<Logger::QueueEntry> Logger::queue;
std::vector<std::wstring> Logger::errors;
bool Logger::error = false;
bool Logger::fatalError = false;
bool Logger::errorOnWarning = false;
bool Logger::silent = false;
std::wstring Logger::formatError(ErrorType type, const std::wstring& text)
{
std::wstring& fileName = Global.FileInfo.FileList[Global.FileInfo.FileNum];
switch (type)
{
case Warning:
return formatString(L"%s(%d) warning: %s",fileName,Global.FileInfo.LineNumber,text);
case Error:
return formatString(L"%s(%d) error: %s",fileName,Global.FileInfo.LineNumber,text);
case FatalError:
return formatString(L"%s(%d) fatal error: %s",fileName,Global.FileInfo.LineNumber,text);
case Notice:
return formatString(L"%s(%d) notice: %s",fileName,Global.FileInfo.LineNumber,text);
}
return L"";
}
void Logger::setFlags(ErrorType type)
{
switch (type)
{
case Warning:
if (errorOnWarning)
error = true;
break;
case Error:
error = true;
break;
case FatalError:
error = true;
fatalError = true;
break;
}
}
void Logger::clear()
{
queue.clear();
errors.clear();
error = false;
fatalError = false;
errorOnWarning = false;
silent = false;
}
void Logger::printLine(const std::wstring& text)
{
std::wcout << text << std::endl;
#if defined(_MSC_VER) && defined(_DEBUG)
OutputDebugStringW(text.c_str());
OutputDebugStringW(L"\n");
#endif
}
void Logger::printLine(const std::string& text)
{
std::cout << text << std::endl;
#if defined(_MSC_VER) && defined(_DEBUG)
OutputDebugStringA(text.c_str());
OutputDebugStringA("\n");
#endif
}
void Logger::print(const std::wstring& text)
{
std::wcout << text;
#if defined(_MSC_VER) && defined(_DEBUG)
OutputDebugStringW(text.c_str());
#endif
}
void Logger::printError(ErrorType type, const std::wstring& text)
{
std::wstring errorText = formatError(type,text);
errors.push_back(errorText);
if (!silent)
printLine(errorText);
setFlags(type);
}
void Logger::queueError(ErrorType type, const std::wstring& text)
{
QueueEntry entry;
entry.type = type;
entry.text = formatError(type,text);
queue.push_back(entry);
}
void Logger::printQueue()
{
for (size_t i = 0; i < queue.size(); i++)
{
errors.push_back(queue[i].text);
if (!silent)
printLine(queue[i].text);
setFlags(queue[i].type);
}
}
void TempData::start()
{
if (file.getFileName().empty() == false)
{
if (file.open(TextFile::Write) == false)
{
Logger::printError(Logger::Error,L"Could not open temp file %s.",file.getFileName());
return;
}
size_t fileCount = Global.FileInfo.FileList.size();
size_t lineCount = Global.FileInfo.TotalLineCount;
size_t labelCount = Global.symbolTable.getLabelCount();
size_t equCount = Global.symbolTable.getEquationCount();
file.writeFormat(L"; %d %S included\n",fileCount,fileCount == 1 ? "file" : "files");
file.writeFormat(L"; %d %S\n",lineCount,lineCount == 1 ? "line" : "lines");
file.writeFormat(L"; %d %S\n",labelCount,labelCount == 1 ? "label" : "labels");
file.writeFormat(L"; %d %S\n\n",equCount,equCount == 1 ? "equation" : "equations");
for (size_t i = 0; i < fileCount; i++)
{
file.writeFormat(L"; %S\n",Global.FileInfo.FileList[i]);
}
file.writeLine("");
}
}
void TempData::end()
{
if (file.isOpen())
file.close();
}
void TempData::writeLine(u64 memoryAddress, const std::wstring& text)
{
if (file.isOpen())
{
std::wstring str = formatString(L"%08X %s",memoryAddress,text);
while (str.size() < 70)
str += ' ';
str += formatString(L"; %S line %d",
Global.FileInfo.FileList[Global.FileInfo.FileNum],Global.FileInfo.LineNumber);
file.writeLine(str);
}
}
<commit_msg>Optimize temp hex pos formatting.<commit_after>#include "stdafx.h"
#include "Misc.h"
#include "Common.h"
#include "Core/FileManager.h"
#include <iostream>
#ifdef _MSC_VER
#include <Windows.h>
#endif
std::vector<Logger::QueueEntry> Logger::queue;
std::vector<std::wstring> Logger::errors;
bool Logger::error = false;
bool Logger::fatalError = false;
bool Logger::errorOnWarning = false;
bool Logger::silent = false;
std::wstring Logger::formatError(ErrorType type, const std::wstring& text)
{
std::wstring& fileName = Global.FileInfo.FileList[Global.FileInfo.FileNum];
switch (type)
{
case Warning:
return formatString(L"%s(%d) warning: %s",fileName,Global.FileInfo.LineNumber,text);
case Error:
return formatString(L"%s(%d) error: %s",fileName,Global.FileInfo.LineNumber,text);
case FatalError:
return formatString(L"%s(%d) fatal error: %s",fileName,Global.FileInfo.LineNumber,text);
case Notice:
return formatString(L"%s(%d) notice: %s",fileName,Global.FileInfo.LineNumber,text);
}
return L"";
}
void Logger::setFlags(ErrorType type)
{
switch (type)
{
case Warning:
if (errorOnWarning)
error = true;
break;
case Error:
error = true;
break;
case FatalError:
error = true;
fatalError = true;
break;
}
}
void Logger::clear()
{
queue.clear();
errors.clear();
error = false;
fatalError = false;
errorOnWarning = false;
silent = false;
}
void Logger::printLine(const std::wstring& text)
{
std::wcout << text << std::endl;
#if defined(_MSC_VER) && defined(_DEBUG)
OutputDebugStringW(text.c_str());
OutputDebugStringW(L"\n");
#endif
}
void Logger::printLine(const std::string& text)
{
std::cout << text << std::endl;
#if defined(_MSC_VER) && defined(_DEBUG)
OutputDebugStringA(text.c_str());
OutputDebugStringA("\n");
#endif
}
void Logger::print(const std::wstring& text)
{
std::wcout << text;
#if defined(_MSC_VER) && defined(_DEBUG)
OutputDebugStringW(text.c_str());
#endif
}
void Logger::printError(ErrorType type, const std::wstring& text)
{
std::wstring errorText = formatError(type,text);
errors.push_back(errorText);
if (!silent)
printLine(errorText);
setFlags(type);
}
void Logger::queueError(ErrorType type, const std::wstring& text)
{
QueueEntry entry;
entry.type = type;
entry.text = formatError(type,text);
queue.push_back(entry);
}
void Logger::printQueue()
{
for (size_t i = 0; i < queue.size(); i++)
{
errors.push_back(queue[i].text);
if (!silent)
printLine(queue[i].text);
setFlags(queue[i].type);
}
}
void TempData::start()
{
if (file.getFileName().empty() == false)
{
if (file.open(TextFile::Write) == false)
{
Logger::printError(Logger::Error,L"Could not open temp file %s.",file.getFileName());
return;
}
size_t fileCount = Global.FileInfo.FileList.size();
size_t lineCount = Global.FileInfo.TotalLineCount;
size_t labelCount = Global.symbolTable.getLabelCount();
size_t equCount = Global.symbolTable.getEquationCount();
file.writeFormat(L"; %d %S included\n",fileCount,fileCount == 1 ? "file" : "files");
file.writeFormat(L"; %d %S\n",lineCount,lineCount == 1 ? "line" : "lines");
file.writeFormat(L"; %d %S\n",labelCount,labelCount == 1 ? "label" : "labels");
file.writeFormat(L"; %d %S\n\n",equCount,equCount == 1 ? "equation" : "equations");
for (size_t i = 0; i < fileCount; i++)
{
file.writeFormat(L"; %S\n",Global.FileInfo.FileList[i]);
}
file.writeLine("");
}
}
void TempData::end()
{
if (file.isOpen())
file.close();
}
void TempData::writeLine(u64 memoryAddress, const std::wstring& text)
{
if (file.isOpen())
{
wchar_t hexbuf[10] = {0};
swprintf(hexbuf, 10, L"%08X ", memoryAddress);
std::wstring str = hexbuf + text;
while (str.size() < 70)
str += ' ';
str += formatString(L"; %S line %d",
Global.FileInfo.FileList[Global.FileInfo.FileNum],Global.FileInfo.LineNumber);
file.writeLine(str);
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>
using namespace std;
#define HASHSIZE 32
string getCutHex(unsigned char hash[HASHSIZE]) {
string base64Index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#";
string output = "";
for (int i = 0; i < 12; i+=3) {
output += base64Index[hash[i+0]>>2];
output += base64Index[((hash[i+0]&0x03)<<4) + (hash[i+1]>>4)];
output += base64Index[((hash[i+1]&0x0F)<<2) + (hash[i+2]>>6)];
output += base64Index[hash[i+2] & 0x3F];
}
return output;
}
string getPassword(string masterpass, string domain) {
string prehash = masterpass+domain;
unsigned char hash[HASHSIZE];
SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);
getCutHex(hash);
//unsigned char hash[20];
return prehash;
}
void help() {
cout << "THIS IS THE HELP PAGE" << endl;
}
int main(int argc, char* argv[]) {
// check to make sure there are enough arguments
// if (argc < 3) {
// cout << "you must specify a username with -u" << endl;
// help();
// return 0;
// }
bool silent = false;
bool passwordFlag = false;
string domain = "";
string password = "";
string *pointer = NULL;
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "-p") { // password flag
pointer = &password;
}
else if (string(argv[i]) == "-d") { // domain flag
pointer = &domain;
}
else if (string(argv[i]) == "-s") { // silent flag
silent = true;
}
else if (string(argv[i]) == "-h") { // help flag
cout << "triggered on the help flag" << endl;
help();
return 0;
}
else {
if (pointer == NULL) {
cout << "triggered on bad argument " << argv[i] << endl;
help();
return 0;
}
else {
*pointer += argv[i];
}
}
}
if (passwordFlag && !silent) {
cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
}
cout << "domain is: " << domain << endl;
cout << "password is: " << password << endl;
getPassword ("harvy","dent");
cout << "DONE!" << endl;
}<commit_msg>command line entering of username and password works<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <openssl/sha.h>
using namespace std;
#define HASHSIZE 32
string getCutHex(unsigned char hash[HASHSIZE]) {
string base64Index = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#";
string output = "";
for (int i = 0; i < 12; i+=3) {
output += base64Index[hash[i+0]>>2];
output += base64Index[((hash[i+0]&0x03)<<4) + (hash[i+1]>>4)];
output += base64Index[((hash[i+1]&0x0F)<<2) + (hash[i+2]>>6)];
output += base64Index[hash[i+2] & 0x3F];
}
return output;
}
string getPassword(string masterpass, string domain) {
string prehash = masterpass+domain;
unsigned char hash[HASHSIZE];
SHA256((unsigned char*)prehash.c_str(), prehash.size(), hash);
getCutHex(hash);
//unsigned char hash[20];
return prehash;
}
void help() {
cout << "THIS IS THE HELP PAGE" << endl;
}
int main(int argc, char* argv[]) {
// check to make sure there are enough arguments
// if (argc < 3) {
// cout << "you must specify a username with -u" << endl;
// help();
// return 0;
// }
bool silent = false;
string domain = "";
string password = "";
string *pointer = NULL;
for (int i = 1; i < argc; i++) {
if (string(argv[i]) == "-p") { // password flag
pointer = &password;
}
else if (string(argv[i]) == "-d") { // domain flag
pointer = &domain;
}
else if (string(argv[i]) == "-s") { // silent flag
silent = true;
}
else if (string(argv[i]) == "-h") { // help flag
cout << "triggered on the help flag" << endl;
help();
return 0;
}
else {
if (pointer == NULL) {
cout << "triggered on bad argument " << argv[i] << endl;
help();
return 0;
}
else {
*pointer += argv[i];
}
}
}
if (password != "" && !silent) {
cout <<"WARNING: you should not use the -p flag as it may be insecure" << endl;
}
cout << "domain is: " << domain << endl;
cout << "password is: " << password << endl;
getPassword (domain,password);
cout << "DONE!" << endl;
}<|endoftext|>
|
<commit_before>#include "Include.h"
#include "Node.h"
using namespace std;
Node::Node(int init){
//Creation
value = init;
visited = false;
x_pos = 0;
y_pos = 0;
}
Node::~Node(){
//Destruction
}
// 0 clean, 1 dirty, 2 blocked, 3 unknown/yet to visit, 4 node for Ai2
int Node::getValue(){
return value;
}
int Node::setValue(int _new){
value = _new;
return value;
}
void Node::visit(bool set){
if(set){
visited = true;
} else {
visited = false;
}
}
bool Node::getVisit() {
return visited;
}
void Node::readFile(std::ifstream &in){
int ant;
in >> ant;
for( int x = 0; x < ant; x++){
std::vector<int> link;
for (int y = 0; y < 3; y++){
int temp;
in >> temp;
link.push_back( temp );
}
links.push_back( link );
}
}
float Node::GetF() {
return G + H;
}
float Node::ManhattanDistance(Node* nodeEnd) {
float x = (float)(abs(x_pos - nodeEnd->x_pos));
float y = (float)(abs(y_pos - nodeEnd->y_pos));
return x + y;
}
int Node::x() { return x_pos; }
int Node::y() { return y_pos; }
int Node::x(int _x) {
x_pos = _x;
return x_pos;
}
int Node::y(int _y) {
y_pos = _y;
return y_pos;
}
int Node::id(){
return ID;
}
int Node::id(int _ID){
ID = _ID;
return ID;
}<commit_msg>Node edits...?<commit_after>#include "Include.h"
#include "Node.h"
using namespace std;
Node::Node(int init){
//Creation
value = init;
visited = false;
x_pos = 0;
y_pos = 0;
}
Node::~Node(){
//Destruction
}
// 0 clean, 1 dirty, 2 blocked, 3 unknown/yet to visit, 4 node for Ai2
int Node::getValue(){
return value;
}
int Node::setValue(int _new){
value = _new;
return value;
}
void Node::visit(bool set){
if(set){
visited = true;
} else {
visited = false;
}
}
bool Node::getVisit() {
return visited;
}
void Node::readFile(std::ifstream &in){
int ant;
in >> ant;
for( int x = 0; x < ant; x++){
std::vector<int> link;
for (int y = 0; y < 3; y++){
int temp;
in >> temp;
link.push_back( temp );
}
links.push_back( link );
}
}
float Node::GetF() {
return G + H;
}
float Node::ManhattanDistance(Node* nodeEnd) {
float x = (float)(abs(x_pos - nodeEnd->x_pos));
float y = (float)(abs(y_pos - nodeEnd->y_pos));
return x + y;
}
int Node::x() { return x_pos; }
int Node::y() { return y_pos; }
int Node::id(){ return ID; }
int Node::x(int _x) {
x_pos = _x;
return x_pos;
}
int Node::y(int _y) {
y_pos = _y;
return y_pos;
}
int Node::id(int _ID){
ID = _ID;
return ID;
}<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "../common/tutorial/tutorial.h"
#include "../common/tutorial/statistics.h"
#include <set>
#include "../../common/sys/mutex.h"
#include "../common/core/ray.h"
#include "../../kernels/geometry/triangle_triangle_intersector.h"
namespace embree
{
RTCDevice g_device = nullptr;
RTCScene g_scene = nullptr;
std::shared_ptr<TutorialScene> g_tutorial_scene = nullptr;
size_t cur_time = 0;
std::vector<std::shared_ptr<TutorialScene>> g_animation;
std::set<std::pair<unsigned,unsigned>> collision_candidates;
//RTCScene g_scene0 = nullptr;
//RTCScene g_scene1 = nullptr;
//TutorialScene g_tutorial_scene0;
//TutorialScene g_tutorial_scene1;
//std::set<std::pair<unsigned,unsigned>> set0;
//std::set<std::pair<unsigned,unsigned>> set1;
bool use_user_geometry = false;
size_t skipBenchmarkRounds = 0;
size_t numBenchmarkRounds = 0;
std::atomic<size_t> numTotalCollisions(0);
SpinLock mutex;
bool intersect_triangle_triangle (TutorialScene* scene0, unsigned geomID0, unsigned primID0, TutorialScene* scene1, unsigned geomID1, unsigned primID1)
{
//CSTAT(bvh_collide_prim_intersections1++);
const SceneGraph::TriangleMeshNode* mesh0 = (SceneGraph::TriangleMeshNode*) scene0->geometries[geomID0].ptr;
const SceneGraph::TriangleMeshNode* mesh1 = (SceneGraph::TriangleMeshNode*) scene1->geometries[geomID1].ptr;
const SceneGraph::TriangleMeshNode::Triangle& tri0 = mesh0->triangles[primID0];
const SceneGraph::TriangleMeshNode::Triangle& tri1 = mesh1->triangles[primID1];
/* special culling for scene intersection with itself */
if (scene0 == scene1 && geomID0 == geomID1)
{
/* ignore self intersections */
if (primID0 == primID1)
return false;
}
//CSTAT(bvh_collide_prim_intersections2++);
if (scene0 == scene1 && geomID0 == geomID1)
{
/* ignore intersection with topological neighbors */
const vint4 t0(tri0.v0,tri0.v1,tri0.v2,tri0.v2);
if (any(vint4(tri1.v0) == t0)) return false;
if (any(vint4(tri1.v1) == t0)) return false;
if (any(vint4(tri1.v2) == t0)) return false;
}
//CSTAT(bvh_collide_prim_intersections3++);
const Vec3fa a0 = mesh0->positions[0][tri0.v0];
const Vec3fa a1 = mesh0->positions[0][tri0.v1];
const Vec3fa a2 = mesh0->positions[0][tri0.v2];
const Vec3fa b0 = mesh1->positions[0][tri1.v0];
const Vec3fa b1 = mesh1->positions[0][tri1.v1];
const Vec3fa b2 = mesh1->positions[0][tri1.v2];
return isa::TriangleTriangleIntersector::intersect_triangle_triangle(a0,a1,a2,b0,b1,b2);
}
void CollideFunc (void* userPtr, RTCCollision* collisions, size_t num_collisions)
{
if (use_user_geometry)
{
for (size_t i=0; i<num_collisions;)
{
bool intersect = intersect_triangle_triangle(g_tutorial_scene.get(),collisions[i].geomID0,collisions[i].primID0,
g_tutorial_scene.get(),collisions[i].geomID1,collisions[i].primID1);
if (intersect) i++;
else collisions[i] = collisions[--num_collisions];
}
}
if (num_collisions == 0)
return;
if (numBenchmarkRounds)
return;
//numTotalCollisions+=num_collisions;
Lock<SpinLock> lock(mutex);
for (size_t i=0; i<num_collisions; i++)
{
const unsigned geomID0 = collisions[i].geomID0;
const unsigned primID0 = collisions[i].primID0;
const unsigned geomID1 = collisions[i].geomID1;
const unsigned primID1 = collisions[i].primID1;
//PRINT4(geomID0,primID0,geomID1,primID1);
collision_candidates.insert(std::make_pair(geomID0,primID0));
collision_candidates.insert(std::make_pair(geomID1,primID1));
//set0.insert(std::make_pair(geomID0,primID0));
//set1.insert(std::make_pair(geomID1,primID1));
#if 0
/* verify result */
Ref<TutorialScene::TriangleMesh> mesh0 = g_tutorial_scene->geometries[geomID0].dynamicCast<TutorialScene::TriangleMesh>();
TutorialScene::Triangle tri0 = mesh0->triangles[primID0];
BBox3fa bounds0 = empty;
bounds0.extend(mesh0->positions[0][tri0.v0]);
bounds0.extend(mesh0->positions[0][tri0.v1]);
bounds0.extend(mesh0->positions[0][tri0.v2]);
Ref<TutorialScene::TriangleMesh> mesh1 = g_tutorial_scene->geometries[geomID1].dynamicCast<TutorialScene::TriangleMesh>();
TutorialScene::Triangle tri1 = mesh1->triangles[primID1];
BBox3fa bounds1 = empty;
bounds1.extend(mesh1->positions[0][tri1.v0]);
bounds1.extend(mesh1->positions[0][tri1.v1]);
bounds1.extend(mesh1->positions[0][tri1.v2]);
if (disjoint(bounds0,bounds1))
std::cout << "WARNING: bounds do not overlap!" << std::endl;
#endif
}
}
void triangle_bounds_func(const struct RTCBoundsFunctionArguments* args)
{
const unsigned geomID = (unsigned) (size_t) args->geometryUserPtr;
const SceneGraph::TriangleMeshNode* mesh = (SceneGraph::TriangleMeshNode*) g_tutorial_scene->geometries[geomID].ptr;
const SceneGraph::TriangleMeshNode::Triangle& tri = mesh->triangles[args->primID];
BBox3fa bounds = empty;
bounds.extend(mesh->positions[0][tri.v0]);
bounds.extend(mesh->positions[0][tri.v1]);
bounds.extend(mesh->positions[0][tri.v2]);
*(BBox3fa*) args->bounds_o = bounds;
}
void triangle_intersect_func(const RTCIntersectFunctionNArguments* args)
{
void* ptr = args->geometryUserPtr;
::Ray* ray = (::Ray*)args->rayhit;
unsigned int primID = args->primID;
const unsigned geomID = (unsigned) (size_t) ptr;
const SceneGraph::TriangleMeshNode* mesh = (SceneGraph::TriangleMeshNode*) g_tutorial_scene->geometries[geomID].ptr;
const SceneGraph::TriangleMeshNode::Triangle& tri = mesh->triangles[primID];
const Vec3fa v0 = mesh->positions[0][tri.v0];
const Vec3fa v1 = mesh->positions[0][tri.v1];
const Vec3fa v2 = mesh->positions[0][tri.v2];
const Vec3fa e1 = v0-v1;
const Vec3fa e2 = v2-v0;
const Vec3fa Ng = cross(e1,e2);
/* calculate denominator */
const Vec3fa O = Vec3fa(ray->org);
const Vec3fa D = Vec3fa(ray->dir);
const Vec3fa C = v0 - O;
const Vec3fa R = cross(D,C);
const float den = dot(Ng,D);
const float rcpDen = rcp(den);
/* perform edge tests */
const float u = dot(R,e2)*rcpDen;
const float v = dot(R,e1)*rcpDen;
/* perform backface culling */
bool valid = (den != 0.0f) & (u >= 0.0f) & (v >= 0.0f) & (u+v<=1.0f);
if (likely(!valid)) return;
/* perform depth test */
const float t = dot(Vec3fa(Ng),C)*rcpDen;
valid &= (t > ray->tnear()) & (t < ray->tfar);
if (likely(!valid)) return;
/* update hit */
ray->tfar = t;
ray->u = u;
ray->v = v;
ray->geomID = geomID;
ray->primID = primID;
ray->Ng = Ng;
}
struct Tutorial : public TutorialApplication
{
bool pause;
Tutorial()
: TutorialApplication("collide",FEATURE_RTCORE), pause(false)//, use_user_geometry(false)
{
}
};
}
int main(int argc, char** argv) {
return embree::Tutorial().main(argc,argv);
}
<commit_msg>better default camera for possible bug inspect<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "../common/tutorial/tutorial.h"
#include "../common/tutorial/statistics.h"
#include <set>
#include "../../common/sys/mutex.h"
#include "../common/core/ray.h"
#include "../../kernels/geometry/triangle_triangle_intersector.h"
namespace embree
{
RTCDevice g_device = nullptr;
RTCScene g_scene = nullptr;
std::shared_ptr<TutorialScene> g_tutorial_scene = nullptr;
size_t cur_time = 0;
std::vector<std::shared_ptr<TutorialScene>> g_animation;
std::set<std::pair<unsigned,unsigned>> collision_candidates;
//RTCScene g_scene0 = nullptr;
//RTCScene g_scene1 = nullptr;
//TutorialScene g_tutorial_scene0;
//TutorialScene g_tutorial_scene1;
//std::set<std::pair<unsigned,unsigned>> set0;
//std::set<std::pair<unsigned,unsigned>> set1;
bool use_user_geometry = false;
size_t skipBenchmarkRounds = 0;
size_t numBenchmarkRounds = 0;
std::atomic<size_t> numTotalCollisions(0);
SpinLock mutex;
bool intersect_triangle_triangle (TutorialScene* scene0, unsigned geomID0, unsigned primID0, TutorialScene* scene1, unsigned geomID1, unsigned primID1)
{
//CSTAT(bvh_collide_prim_intersections1++);
const SceneGraph::TriangleMeshNode* mesh0 = (SceneGraph::TriangleMeshNode*) scene0->geometries[geomID0].ptr;
const SceneGraph::TriangleMeshNode* mesh1 = (SceneGraph::TriangleMeshNode*) scene1->geometries[geomID1].ptr;
const SceneGraph::TriangleMeshNode::Triangle& tri0 = mesh0->triangles[primID0];
const SceneGraph::TriangleMeshNode::Triangle& tri1 = mesh1->triangles[primID1];
/* special culling for scene intersection with itself */
if (scene0 == scene1 && geomID0 == geomID1)
{
/* ignore self intersections */
if (primID0 == primID1)
return false;
}
//CSTAT(bvh_collide_prim_intersections2++);
if (scene0 == scene1 && geomID0 == geomID1)
{
/* ignore intersection with topological neighbors */
const vint4 t0(tri0.v0,tri0.v1,tri0.v2,tri0.v2);
if (any(vint4(tri1.v0) == t0)) return false;
if (any(vint4(tri1.v1) == t0)) return false;
if (any(vint4(tri1.v2) == t0)) return false;
}
//CSTAT(bvh_collide_prim_intersections3++);
const Vec3fa a0 = mesh0->positions[0][tri0.v0];
const Vec3fa a1 = mesh0->positions[0][tri0.v1];
const Vec3fa a2 = mesh0->positions[0][tri0.v2];
const Vec3fa b0 = mesh1->positions[0][tri1.v0];
const Vec3fa b1 = mesh1->positions[0][tri1.v1];
const Vec3fa b2 = mesh1->positions[0][tri1.v2];
return isa::TriangleTriangleIntersector::intersect_triangle_triangle(a0,a1,a2,b0,b1,b2);
}
void CollideFunc (void* userPtr, RTCCollision* collisions, size_t num_collisions)
{
if (use_user_geometry)
{
for (size_t i=0; i<num_collisions;)
{
bool intersect = intersect_triangle_triangle(g_tutorial_scene.get(),collisions[i].geomID0,collisions[i].primID0,
g_tutorial_scene.get(),collisions[i].geomID1,collisions[i].primID1);
if (intersect) i++;
else collisions[i] = collisions[--num_collisions];
}
}
if (num_collisions == 0)
return;
if (numBenchmarkRounds)
return;
//numTotalCollisions+=num_collisions;
Lock<SpinLock> lock(mutex);
for (size_t i=0; i<num_collisions; i++)
{
const unsigned geomID0 = collisions[i].geomID0;
const unsigned primID0 = collisions[i].primID0;
const unsigned geomID1 = collisions[i].geomID1;
const unsigned primID1 = collisions[i].primID1;
//PRINT4(geomID0,primID0,geomID1,primID1);
collision_candidates.insert(std::make_pair(geomID0,primID0));
collision_candidates.insert(std::make_pair(geomID1,primID1));
//set0.insert(std::make_pair(geomID0,primID0));
//set1.insert(std::make_pair(geomID1,primID1));
#if 0
/* verify result */
Ref<TutorialScene::TriangleMesh> mesh0 = g_tutorial_scene->geometries[geomID0].dynamicCast<TutorialScene::TriangleMesh>();
TutorialScene::Triangle tri0 = mesh0->triangles[primID0];
BBox3fa bounds0 = empty;
bounds0.extend(mesh0->positions[0][tri0.v0]);
bounds0.extend(mesh0->positions[0][tri0.v1]);
bounds0.extend(mesh0->positions[0][tri0.v2]);
Ref<TutorialScene::TriangleMesh> mesh1 = g_tutorial_scene->geometries[geomID1].dynamicCast<TutorialScene::TriangleMesh>();
TutorialScene::Triangle tri1 = mesh1->triangles[primID1];
BBox3fa bounds1 = empty;
bounds1.extend(mesh1->positions[0][tri1.v0]);
bounds1.extend(mesh1->positions[0][tri1.v1]);
bounds1.extend(mesh1->positions[0][tri1.v2]);
if (disjoint(bounds0,bounds1))
std::cout << "WARNING: bounds do not overlap!" << std::endl;
#endif
}
}
void triangle_bounds_func(const struct RTCBoundsFunctionArguments* args)
{
const unsigned geomID = (unsigned) (size_t) args->geometryUserPtr;
const SceneGraph::TriangleMeshNode* mesh = (SceneGraph::TriangleMeshNode*) g_tutorial_scene->geometries[geomID].ptr;
const SceneGraph::TriangleMeshNode::Triangle& tri = mesh->triangles[args->primID];
BBox3fa bounds = empty;
bounds.extend(mesh->positions[0][tri.v0]);
bounds.extend(mesh->positions[0][tri.v1]);
bounds.extend(mesh->positions[0][tri.v2]);
*(BBox3fa*) args->bounds_o = bounds;
}
void triangle_intersect_func(const RTCIntersectFunctionNArguments* args)
{
void* ptr = args->geometryUserPtr;
::Ray* ray = (::Ray*)args->rayhit;
unsigned int primID = args->primID;
const unsigned geomID = (unsigned) (size_t) ptr;
const SceneGraph::TriangleMeshNode* mesh = (SceneGraph::TriangleMeshNode*) g_tutorial_scene->geometries[geomID].ptr;
const SceneGraph::TriangleMeshNode::Triangle& tri = mesh->triangles[primID];
const Vec3fa v0 = mesh->positions[0][tri.v0];
const Vec3fa v1 = mesh->positions[0][tri.v1];
const Vec3fa v2 = mesh->positions[0][tri.v2];
const Vec3fa e1 = v0-v1;
const Vec3fa e2 = v2-v0;
const Vec3fa Ng = cross(e1,e2);
/* calculate denominator */
const Vec3fa O = Vec3fa(ray->org);
const Vec3fa D = Vec3fa(ray->dir);
const Vec3fa C = v0 - O;
const Vec3fa R = cross(D,C);
const float den = dot(Ng,D);
const float rcpDen = rcp(den);
/* perform edge tests */
const float u = dot(R,e2)*rcpDen;
const float v = dot(R,e1)*rcpDen;
/* perform backface culling */
bool valid = (den != 0.0f) & (u >= 0.0f) & (v >= 0.0f) & (u+v<=1.0f);
if (likely(!valid)) return;
/* perform depth test */
const float t = dot(Vec3fa(Ng),C)*rcpDen;
valid &= (t > ray->tnear()) & (t < ray->tfar);
if (likely(!valid)) return;
/* update hit */
ray->tfar = t;
ray->u = u;
ray->v = v;
ray->geomID = geomID;
ray->primID = primID;
ray->Ng = Ng;
}
struct Tutorial : public TutorialApplication
{
bool pause;
Tutorial()
: TutorialApplication("collide",FEATURE_RTCORE), pause(false)//, use_user_geometry(false)
{
camera.from = Vec3fa(-2.5f,2.5f,-2.5f);
camera.to = Vec3fa(0.0f,0.0f,0.0f);
}
};
}
int main(int argc, char** argv) {
return embree::Tutorial().main(argc,argv);
}
<|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 <cstring>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include "vcl/helper.hxx"
#include "vcl/ppdparser.hxx"
#include "tools/string.hxx"
#include "tools/urlobj.hxx"
#include "osl/file.hxx"
#include "osl/process.h"
#include "rtl/bootstrap.hxx"
using ::rtl::Bootstrap;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::rtl::OString;
using ::rtl::OStringToOUString;
using ::rtl::OUStringToOString;
namespace psp {
OUString getOfficePath( enum whichOfficePath ePath )
{
static OUString aInstallationRootPath;
static OUString aUserPath;
static OUString aConfigPath;
static OUString aEmpty;
static bool bOnce = false;
if( ! bOnce )
{
bOnce = true;
OUString aIni;
Bootstrap::get( "BRAND_BASE_DIR", aInstallationRootPath );
aIni = aInstallationRootPath + "/program/" + SAL_CONFIGFILE( "bootstrap" );
Bootstrap aBootstrap( aIni );
aBootstrap.getFrom( "CustomDataUrl", aConfigPath );
aBootstrap.getFrom( "UserInstallation", aUserPath );
OUString aUPath = aUserPath;
if( ! aConfigPath.compareToAscii( "file://", 7 ) )
{
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aConfigPath.pData, &aSysPath.pData ) == osl_File_E_None )
aConfigPath = aSysPath;
}
if( ! aInstallationRootPath.compareToAscii( "file://", 7 ) )
{
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aInstallationRootPath.pData, &aSysPath.pData ) == osl_File_E_None )
aInstallationRootPath = aSysPath;
}
if( ! aUserPath.compareToAscii( "file://", 7 ) )
{
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aUserPath.pData, &aSysPath.pData ) == osl_File_E_None )
aUserPath = aSysPath;
}
// ensure user path exists
aUPath += "/user/psprint";
#if OSL_DEBUG_LEVEL > 1
oslFileError eErr =
#endif
osl_createDirectoryPath( aUPath.pData, NULL, NULL );
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "try to create \"%s\" = %d\n", OUStringToOString( aUPath, RTL_TEXTENCODING_UTF8 ).getStr(), eErr );
#endif
}
switch( ePath )
{
case ConfigPath: return aConfigPath;
case InstallationRootPath: return aInstallationRootPath;
case UserPath: return aUserPath;
}
return aEmpty;
}
static OString getEnvironmentPath( const char* pKey )
{
OString aPath;
const char* pValue = getenv( pKey );
if( pValue && *pValue )
{
aPath = OString( pValue );
}
return aPath;
}
} // namespace psp
void psp::getPrinterPathList( std::list< OUString >& rPathList, const char* pSubDir )
{
rPathList.clear();
rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
OUStringBuffer aPathBuffer( 256 );
// append net path
aPathBuffer.append( getOfficePath( psp::InstallationRootPath ) );
if( aPathBuffer.getLength() )
{
aPathBuffer.appendAscii( "/share/psprint" );
if( pSubDir )
{
aPathBuffer.append( sal_Unicode('/') );
aPathBuffer.appendAscii( pSubDir );
}
rPathList.push_back( aPathBuffer.makeStringAndClear() );
}
// append user path
aPathBuffer.append( getOfficePath( psp::UserPath ) );
if( aPathBuffer.getLength() )
{
aPathBuffer.appendAscii( "/user/psprint" );
if( pSubDir )
{
aPathBuffer.append( sal_Unicode('/') );
aPathBuffer.appendAscii( pSubDir );
}
rPathList.push_back( aPathBuffer.makeStringAndClear() );
}
OString aPath( getEnvironmentPath("SAL_PSPRINT") );
sal_Int32 nIndex = 0;
do
{
OString aDir( aPath.getToken( 0, ':', nIndex ) );
if( aDir.isEmpty() )
continue;
if( pSubDir )
{
aDir += "/";
aDir += pSubDir;
}
struct stat aStat;
if( stat( aDir.getStr(), &aStat ) || ! S_ISDIR( aStat.st_mode ) )
continue;
rPathList.push_back( OStringToOUString( aDir, aEncoding ) );
} while( nIndex != -1 );
#ifdef SYSTEM_PPD_DIR
if( pSubDir && rtl_str_compare( pSubDir, PRINTER_PPDDIR ) == 0 )
{
rPathList.push_back( rtl::OStringToOUString( rtl::OString( SYSTEM_PPD_DIR ), RTL_TEXTENCODING_UTF8 ) );
}
#endif
if( rPathList.empty() )
{
// last resort: next to program file (mainly for setup)
OUString aExe;
if( osl_getExecutableFile( &aExe.pData ) == osl_Process_E_None )
{
INetURLObject aDir( aExe );
aDir.removeSegment();
aExe = aDir.GetMainURL( INetURLObject::NO_DECODE );
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aExe.pData, &aSysPath.pData ) == osl_File_E_None )
{
rPathList.push_back( aSysPath );
}
}
}
}
OUString psp::getFontPath()
{
static OUString aPath;
if (aPath.isEmpty())
{
OUStringBuffer aPathBuffer( 512 );
OUString aConfigPath( getOfficePath( psp::ConfigPath ) );
OUString aInstallationRootPath( getOfficePath( psp::InstallationRootPath ) );
OUString aUserPath( getOfficePath( psp::UserPath ) );
if( !aConfigPath.isEmpty() )
{
// #i53530# Path from CustomDataUrl will completely
// replace net and user paths if the path exists
aPathBuffer.append(aConfigPath);
aPathBuffer.appendAscii("/share/fonts");
// check existance of config path
struct stat aStat;
if( 0 != stat( OUStringToOString( aPathBuffer.makeStringAndClear(), osl_getThreadTextEncoding() ).getStr(), &aStat )
|| ! S_ISDIR( aStat.st_mode ) )
aConfigPath = OUString();
else
{
aPathBuffer.append(aConfigPath);
aPathBuffer.appendAscii("/share/fonts");
}
}
if( aConfigPath.isEmpty() )
{
if( !aInstallationRootPath.isEmpty() )
{
aPathBuffer.append( aInstallationRootPath );
aPathBuffer.appendAscii( "/share/fonts/truetype;");
aPathBuffer.append( aInstallationRootPath );
aPathBuffer.appendAscii( "/share/fonts/type1;" );
}
if( !aUserPath.isEmpty() )
{
aPathBuffer.append( aUserPath );
aPathBuffer.appendAscii( "/user/fonts" );
}
}
aPath = aPathBuffer.makeStringAndClear();
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "initializing font path to \"%s\"\n", OUStringToOString( aPath, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
}
return aPath;
}
bool psp::convertPfbToPfa( ::osl::File& rInFile, ::osl::File& rOutFile )
{
static unsigned char hexDigits[] =
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
bool bSuccess = true;
bool bEof = false;
unsigned char buffer[256];
sal_uInt64 nRead;
sal_uInt64 nOrgPos = 0;
rInFile.getPos( nOrgPos );
while( bSuccess && ! bEof )
{
// read leading bytes
bEof = ! rInFile.read( buffer, 6, nRead ) && nRead == 6 ? false : true;
unsigned int nType = buffer[ 1 ];
unsigned int nBytesToRead = buffer[2] | buffer[3] << 8 | buffer[4] << 16 | buffer[5] << 24;
if( buffer[0] != 0x80 ) // test for pfb m_agic number
{
// this migt be a pfa font already
if( ! rInFile.read( buffer+6, 9, nRead ) && nRead == 9 &&
( ! std::strncmp( (char*)buffer, "%!FontType1-", 12 ) ||
! std::strncmp( (char*)buffer, "%!PS-AdobeFont-", 15 ) ) )
{
sal_uInt64 nWrite = 0;
if( rOutFile.write( buffer, 15, nWrite ) || nWrite != 15 )
bSuccess = false;
while( bSuccess &&
! rInFile.read( buffer, sizeof( buffer ), nRead ) &&
nRead != 0 )
{
if( rOutFile.write( buffer, nRead, nWrite ) ||
nWrite != nRead )
bSuccess = false;
}
bEof = true;
}
else
bSuccess = false;
}
else if( nType == 1 || nType == 2 )
{
unsigned char* pBuffer = new unsigned char[ nBytesToRead+1 ];
if( ! rInFile.read( pBuffer, nBytesToRead, nRead ) && nRead == nBytesToRead )
{
if( nType == 1 )
{
// ascii data, convert dos lineends( \r\n ) and
// m_ac lineends( \r ) to \n
unsigned char * pWriteBuffer = new unsigned char[ nBytesToRead ];
unsigned int nBytesToWrite = 0;
for( unsigned int i = 0; i < nBytesToRead; i++ )
{
if( pBuffer[i] != '\r' )
pWriteBuffer[ nBytesToWrite++ ] = pBuffer[i];
else if( pBuffer[ i+1 ] == '\n' )
{
i++;
pWriteBuffer[ nBytesToWrite++ ] = '\n';
}
else
pWriteBuffer[ nBytesToWrite++ ] = '\n';
}
if( rOutFile.write( pWriteBuffer, nBytesToWrite, nRead ) || nRead != nBytesToWrite )
bSuccess = false;
delete [] pWriteBuffer;
}
else
{
// binary data
unsigned int nBuffer = 0;
for( unsigned int i = 0; i < nBytesToRead && bSuccess; i++ )
{
buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] >> 4 ];
buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] & 15 ];
if( nBuffer >= 80 )
{
buffer[ nBuffer++ ] = '\n';
if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
bSuccess = false;
nBuffer = 0;
}
}
if( nBuffer > 0 && bSuccess )
{
buffer[ nBuffer++ ] = '\n';
if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
bSuccess = false;
}
}
}
else
bSuccess = false;
delete [] pBuffer;
}
else if( nType == 3 )
bEof = true;
else
bSuccess = false;
}
return bSuccess;
}
void psp::normPath( OString& rPath )
{
char buf[PATH_MAX];
// double slashes and slash at end are probably
// removed by realpath anyway, but since this runs
// on many different platforms let's play it safe
rtl::OString aPath = rPath.replaceAll("//", "/");
if( !aPath.isEmpty() && aPath[aPath.getLength()-1] == '/' )
aPath = aPath.copy(0, aPath.getLength()-1);
if( ( aPath.indexOf("./") != -1 ||
aPath.indexOf( '~' ) != -1 )
&& realpath( aPath.getStr(), buf ) )
{
rPath = buf;
}
else
{
rPath = aPath;
}
}
void psp::splitPath( OString& rPath, OString& rDir, OString& rBase )
{
normPath( rPath );
sal_Int32 nIndex = rPath.lastIndexOf( '/' );
if( nIndex > 0 )
rDir = rPath.copy( 0, nIndex );
else if( nIndex == 0 ) // root dir
rDir = rPath.copy( 0, 1 );
if( rPath.getLength() > nIndex+1 )
rBase = rPath.copy( nIndex+1 );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>c#706171# handle invalid PFB chunk header<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 <cstring>
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include "vcl/helper.hxx"
#include "vcl/ppdparser.hxx"
#include "tools/string.hxx"
#include "tools/urlobj.hxx"
#include "osl/file.hxx"
#include "osl/process.h"
#include "rtl/bootstrap.hxx"
using ::rtl::Bootstrap;
using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::rtl::OString;
using ::rtl::OStringToOUString;
using ::rtl::OUStringToOString;
namespace psp {
OUString getOfficePath( enum whichOfficePath ePath )
{
static OUString aInstallationRootPath;
static OUString aUserPath;
static OUString aConfigPath;
static OUString aEmpty;
static bool bOnce = false;
if( ! bOnce )
{
bOnce = true;
OUString aIni;
Bootstrap::get( "BRAND_BASE_DIR", aInstallationRootPath );
aIni = aInstallationRootPath + "/program/" + SAL_CONFIGFILE( "bootstrap" );
Bootstrap aBootstrap( aIni );
aBootstrap.getFrom( "CustomDataUrl", aConfigPath );
aBootstrap.getFrom( "UserInstallation", aUserPath );
OUString aUPath = aUserPath;
if( ! aConfigPath.compareToAscii( "file://", 7 ) )
{
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aConfigPath.pData, &aSysPath.pData ) == osl_File_E_None )
aConfigPath = aSysPath;
}
if( ! aInstallationRootPath.compareToAscii( "file://", 7 ) )
{
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aInstallationRootPath.pData, &aSysPath.pData ) == osl_File_E_None )
aInstallationRootPath = aSysPath;
}
if( ! aUserPath.compareToAscii( "file://", 7 ) )
{
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aUserPath.pData, &aSysPath.pData ) == osl_File_E_None )
aUserPath = aSysPath;
}
// ensure user path exists
aUPath += "/user/psprint";
#if OSL_DEBUG_LEVEL > 1
oslFileError eErr =
#endif
osl_createDirectoryPath( aUPath.pData, NULL, NULL );
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "try to create \"%s\" = %d\n", OUStringToOString( aUPath, RTL_TEXTENCODING_UTF8 ).getStr(), eErr );
#endif
}
switch( ePath )
{
case ConfigPath: return aConfigPath;
case InstallationRootPath: return aInstallationRootPath;
case UserPath: return aUserPath;
}
return aEmpty;
}
static OString getEnvironmentPath( const char* pKey )
{
OString aPath;
const char* pValue = getenv( pKey );
if( pValue && *pValue )
{
aPath = OString( pValue );
}
return aPath;
}
} // namespace psp
void psp::getPrinterPathList( std::list< OUString >& rPathList, const char* pSubDir )
{
rPathList.clear();
rtl_TextEncoding aEncoding = osl_getThreadTextEncoding();
OUStringBuffer aPathBuffer( 256 );
// append net path
aPathBuffer.append( getOfficePath( psp::InstallationRootPath ) );
if( aPathBuffer.getLength() )
{
aPathBuffer.appendAscii( "/share/psprint" );
if( pSubDir )
{
aPathBuffer.append( sal_Unicode('/') );
aPathBuffer.appendAscii( pSubDir );
}
rPathList.push_back( aPathBuffer.makeStringAndClear() );
}
// append user path
aPathBuffer.append( getOfficePath( psp::UserPath ) );
if( aPathBuffer.getLength() )
{
aPathBuffer.appendAscii( "/user/psprint" );
if( pSubDir )
{
aPathBuffer.append( sal_Unicode('/') );
aPathBuffer.appendAscii( pSubDir );
}
rPathList.push_back( aPathBuffer.makeStringAndClear() );
}
OString aPath( getEnvironmentPath("SAL_PSPRINT") );
sal_Int32 nIndex = 0;
do
{
OString aDir( aPath.getToken( 0, ':', nIndex ) );
if( aDir.isEmpty() )
continue;
if( pSubDir )
{
aDir += "/";
aDir += pSubDir;
}
struct stat aStat;
if( stat( aDir.getStr(), &aStat ) || ! S_ISDIR( aStat.st_mode ) )
continue;
rPathList.push_back( OStringToOUString( aDir, aEncoding ) );
} while( nIndex != -1 );
#ifdef SYSTEM_PPD_DIR
if( pSubDir && rtl_str_compare( pSubDir, PRINTER_PPDDIR ) == 0 )
{
rPathList.push_back( rtl::OStringToOUString( rtl::OString( SYSTEM_PPD_DIR ), RTL_TEXTENCODING_UTF8 ) );
}
#endif
if( rPathList.empty() )
{
// last resort: next to program file (mainly for setup)
OUString aExe;
if( osl_getExecutableFile( &aExe.pData ) == osl_Process_E_None )
{
INetURLObject aDir( aExe );
aDir.removeSegment();
aExe = aDir.GetMainURL( INetURLObject::NO_DECODE );
OUString aSysPath;
if( osl_getSystemPathFromFileURL( aExe.pData, &aSysPath.pData ) == osl_File_E_None )
{
rPathList.push_back( aSysPath );
}
}
}
}
OUString psp::getFontPath()
{
static OUString aPath;
if (aPath.isEmpty())
{
OUStringBuffer aPathBuffer( 512 );
OUString aConfigPath( getOfficePath( psp::ConfigPath ) );
OUString aInstallationRootPath( getOfficePath( psp::InstallationRootPath ) );
OUString aUserPath( getOfficePath( psp::UserPath ) );
if( !aConfigPath.isEmpty() )
{
// #i53530# Path from CustomDataUrl will completely
// replace net and user paths if the path exists
aPathBuffer.append(aConfigPath);
aPathBuffer.appendAscii("/share/fonts");
// check existance of config path
struct stat aStat;
if( 0 != stat( OUStringToOString( aPathBuffer.makeStringAndClear(), osl_getThreadTextEncoding() ).getStr(), &aStat )
|| ! S_ISDIR( aStat.st_mode ) )
aConfigPath = OUString();
else
{
aPathBuffer.append(aConfigPath);
aPathBuffer.appendAscii("/share/fonts");
}
}
if( aConfigPath.isEmpty() )
{
if( !aInstallationRootPath.isEmpty() )
{
aPathBuffer.append( aInstallationRootPath );
aPathBuffer.appendAscii( "/share/fonts/truetype;");
aPathBuffer.append( aInstallationRootPath );
aPathBuffer.appendAscii( "/share/fonts/type1;" );
}
if( !aUserPath.isEmpty() )
{
aPathBuffer.append( aUserPath );
aPathBuffer.appendAscii( "/user/fonts" );
}
}
aPath = aPathBuffer.makeStringAndClear();
#if OSL_DEBUG_LEVEL > 1
fprintf( stderr, "initializing font path to \"%s\"\n", OUStringToOString( aPath, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
}
return aPath;
}
bool psp::convertPfbToPfa( ::osl::File& rInFile, ::osl::File& rOutFile )
{
static const unsigned char hexDigits[] =
{
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
bool bSuccess = true;
bool bEof = false;
unsigned char buffer[256];
sal_uInt64 nRead;
sal_uInt64 nOrgPos = 0;
rInFile.getPos( nOrgPos );
while( bSuccess && ! bEof )
{
// read leading bytes
bEof = ((0 != rInFile.read( buffer, 6, nRead)) || (nRead != 6));
if( bEof )
break;
unsigned int nType = buffer[ 1 ];
unsigned int nBytesToRead = buffer[2] | buffer[3] << 8 | buffer[4] << 16 | buffer[5] << 24;
if( buffer[0] != 0x80 ) // test for pfb magic number
{
// this migt be a pfa font already
if( ! rInFile.read( buffer+6, 9, nRead ) && nRead == 9 &&
( ! std::strncmp( (char*)buffer, "%!FontType1-", 12 ) ||
! std::strncmp( (char*)buffer, "%!PS-AdobeFont-", 15 ) ) )
{
sal_uInt64 nWrite = 0;
if( rOutFile.write( buffer, 15, nWrite ) || nWrite != 15 )
bSuccess = false;
while( bSuccess &&
! rInFile.read( buffer, sizeof( buffer ), nRead ) &&
nRead != 0 )
{
if( rOutFile.write( buffer, nRead, nWrite ) ||
nWrite != nRead )
bSuccess = false;
}
bEof = true;
}
else
bSuccess = false;
}
else if( nType == 1 || nType == 2 )
{
unsigned char* pBuffer = new unsigned char[ nBytesToRead+1 ];
if( ! rInFile.read( pBuffer, nBytesToRead, nRead ) && nRead == nBytesToRead )
{
if( nType == 1 )
{
// ascii data, convert dos lineends( \r\n ) and
// m_ac lineends( \r ) to \n
unsigned char * pWriteBuffer = new unsigned char[ nBytesToRead ];
unsigned int nBytesToWrite = 0;
for( unsigned int i = 0; i < nBytesToRead; i++ )
{
if( pBuffer[i] != '\r' )
pWriteBuffer[ nBytesToWrite++ ] = pBuffer[i];
else if( pBuffer[ i+1 ] == '\n' )
{
i++;
pWriteBuffer[ nBytesToWrite++ ] = '\n';
}
else
pWriteBuffer[ nBytesToWrite++ ] = '\n';
}
if( rOutFile.write( pWriteBuffer, nBytesToWrite, nRead ) || nRead != nBytesToWrite )
bSuccess = false;
delete [] pWriteBuffer;
}
else
{
// binary data
unsigned int nBuffer = 0;
for( unsigned int i = 0; i < nBytesToRead && bSuccess; i++ )
{
buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] >> 4 ];
buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] & 15 ];
if( nBuffer >= 80 )
{
buffer[ nBuffer++ ] = '\n';
if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
bSuccess = false;
nBuffer = 0;
}
}
if( nBuffer > 0 && bSuccess )
{
buffer[ nBuffer++ ] = '\n';
if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
bSuccess = false;
}
}
}
else
bSuccess = false;
delete [] pBuffer;
}
else if( nType == 3 )
bEof = true;
else
bSuccess = false;
}
return bSuccess;
}
void psp::normPath( OString& rPath )
{
char buf[PATH_MAX];
// double slashes and slash at end are probably
// removed by realpath anyway, but since this runs
// on many different platforms let's play it safe
rtl::OString aPath = rPath.replaceAll("//", "/");
if( !aPath.isEmpty() && aPath[aPath.getLength()-1] == '/' )
aPath = aPath.copy(0, aPath.getLength()-1);
if( ( aPath.indexOf("./") != -1 ||
aPath.indexOf( '~' ) != -1 )
&& realpath( aPath.getStr(), buf ) )
{
rPath = buf;
}
else
{
rPath = aPath;
}
}
void psp::splitPath( OString& rPath, OString& rDir, OString& rBase )
{
normPath( rPath );
sal_Int32 nIndex = rPath.lastIndexOf( '/' );
if( nIndex > 0 )
rDir = rPath.copy( 0, nIndex );
else if( nIndex == 0 ) // root dir
rDir = rPath.copy( 0, 1 );
if( rPath.getLength() > nIndex+1 )
rBase = rPath.copy( nIndex+1 );
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include <vector>
#include <unordered_set>
#include <sys/mman.h>
#include "it.x64.asm.h"
static const struct rejit_threadset_t *NFA = NULL; // used for offset calculation
static const struct rejit_thread_t *THREAD = NULL;
struct re2jit::native
{
void init() {}
void * entry;
void * state;
size_t _size;
native(re2::Prog *prog) : entry(NULL), state(NULL), _size(0)
{
size_t i;
size_t n = prog->size();
as::code code;
std::vector<as::label> labels(n);
// How many transitions have the i-th opcode as a target.
// Opcodes with indegree 1 don't need to be tracked in the bit vector
// (as there is only one way to reach them and we've already checked that).
// Opcodes with indegree 0 are completely unreachable, no need to compile those.
std::vector< unsigned > indegree(n);
std::vector< unsigned > emitted(n);
// If the regexp contains backreferences, we have to fall back to sort-of
// backtracking. Well, *technically*, we can simply replace our bit vector
// of `m` visited states with a bit vector of `m * n ** (2 * k)` states
// where `k` is the number of (referenced) groups and `n` is the length of input.
// You thought the `m * n` bits required to make backtrackers run in linear time
// was a lot? Think again.
std::unordered_set< unsigned > backreferences;
ssize_t *stack = new ssize_t[prog->size()];
ssize_t *stptr = stack;
indegree[*stptr++ = prog->start()]++;
while (stptr != stack) {
auto op = prog->inst(*--stptr);
auto vec = re2jit::is_extcode(prog, op);
for (auto& op : vec) {
if (op.opcode() == re2jit::inst::kBackReference)
// Note that the fact that a regex with backreferences requires
// at most O(m * n ** (2 * k + 1)) time to match does not prove
// P = NP in any way. Reducing 3-SAT to PCRE matching is done
// by constructing a regex in which m = k = O(n). O(n * n ** n)?
// That's worse than brute-force.
backreferences.insert(op.arg());
if (!indegree[op.out()]++)
*stptr++ = op.out();
}
if (!vec.size())
switch (op->opcode()) {
case re2::kInstAlt:
case re2::kInstAltMatch:
if (!indegree[op->out1()]++)
*stptr++ = op->out1();
default:
if (!indegree[op->out()]++)
*stptr++ = op->out();
case re2::kInstFail:
case re2::kInstMatch:
break;
case re2::kInstByteRange:
if (!indegree[op->out()])
*stptr++ = op->out();
// subsequent byte ranges are concatenated into one block of code
auto next = prog->inst(op->out());
if (next->opcode() != re2::kInstByteRange && !re2jit::maybe_extcode(next))
indegree[op->out()]++;
}
}
// NFA will call this code with itself (%rdi) and a state (%rsi).
// In our case, the state is a pointer to actual code to execute.
// Each thread has its own array of group indices...
if (backreferences.size())
// ...so it must have its own zero-filled bit vector of visited states.
code.push(as::rdi)
.push(as::rsi)
.call(&rejit_thread_bitmap_clear)
.pop (as::rsi)
.pop (as::rdi)
.jmp (as::rsi);
else
// ...but we don't care, so we can simply jump to actual code.
code.jmp(as::rsi);
as::label fail; // jump here to return 0
as::label succeed; // jump here to return 1 (if a matching state is reachable)
code.mark(fail).xor_(as::eax, as::eax).mark(succeed).ret();
emitted[*stptr++ = prog->start()]++;
while (stptr != stack) {
#define EMIT_NEXT(i) if (!emitted[i]++) *stptr++ = i
#define EMIT_JUMP(i) EMIT_NEXT(i); else code.jmp(labels[i])
code.mark(labels[i = *--stptr]);
// Each opcode should conform to the System V ABI calling convention.
// argument 1: %rdi = struct rejit_threadset_t *nfa
// return reg: %rax = 1 iff found a match somewhere
auto op = prog->inst(i);
auto vec = re2jit::is_extcode(prog, op);
// kInstFail will do `ret` anyway.
if (op->opcode() != re2::kInstFail && indegree[i] > 1)
// if (bit(nfa->visited, i) == 1) return; bit(nfa->visited, i) = 1;
code.mov (as::mem(as::rdi + &NFA->visited), as::rsi)
.test (as::i8(1 << (i % 8)), as::mem(as::rsi + i / 8)).jmp(fail, as::not_zero)
.or_ (as::i8(1 << (i % 8)), as::mem(as::rsi + i / 8));
if (vec.size()) {
for (auto &op : vec) {
// Instead of returning, a failed pseudo-inst should jump
// to the next inst in the alternation.
as::label fail;
switch (op.opcode()) {
case re2jit::inst::kUnicodeType:
// utf8_chr = rejit_read_utf8(nfa->input, nfa->length);
code.push (as::rdi)
.mov (as::mem(as::rdi + &NFA->length), as::rsi)
.mov (as::mem(as::rdi + &NFA->input), as::rdi)
.call (&rejit_read_utf8)
.pop (as::rdi)
// if ((utf8_length = utf8_chr >> 32) == 0) return;
.mov (as::rax, as::rdx)
.shr (32, as::rdx).jmp(fail, as::zero)
// if ((rejit_unicode_category(utf8_chr) & UNICODE_CATEGORY_GENERAL) != arg) return;
.push (as::rdi)
.push (as::rdx)
.mov (as::eax, as::edi)
.call (&rejit_unicode_category) // inlining is hard.
.pop (as::rdx)
.pop (as::rdi)
.and_ (UNICODE_CATEGORY_GENERAL, as::al)
.cmp (op.arg(), as::al).jmp(fail, as::not_equal)
// rejit_thread_wait(nfa, &out, utf8_length);
.mov (labels[op.out()], as::rsi)
.push (as::rdi)
.call (&rejit_thread_wait)
.pop (as::rdi);
EMIT_NEXT(op.out());
break;
case re2jit::inst::kBackReference: {
as::label empty;
// if (nfa->groups <= arg * 2) return;
code.cmp(as::i32(op.arg() * 2), as::mem(as::rdi + &NFA->groups))
.jmp(fail, as::less_equal_u) // wasn't enough space to record that group
// if (start == -1 || end < start) return;
.mov(as::mem(as::rdi + &NFA->running), as::rsi)
.mov(as::mem(as::rsi + &THREAD->groups[op.arg() * 2 + 1]), as::ecx)
.mov(as::mem(as::rsi + &THREAD->groups[op.arg() * 2]), as::esi)
.cmp(as::i8(-1), as::esi).jmp(fail, as::equal)
.sub(as::esi, as::ecx).jmp(fail, as::less)
// if (start == end) goto empty;
.jmp(empty, as::equal)
// if (nfa->length < end - start) return;
.cmp(as::rcx, as::mem(as::rdi + &NFA->length)).jmp(fail, as::less_u)
// if (memcmp(nfa->input, nfa->input + start - nfa->offset, end - start)) return;
.push(as::rdi)
.sub (as::mem(as::rdi + &NFA->offset), as::rsi)
.mov (as::mem(as::rdi + &NFA->input), as::rdi)
.mov (as::ecx, as::edx)
.add (as::rdi, as::rsi)
.repz().cmpsb().pop(as::rdi).jmp(fail, as::not_equal)
// return rejit_thread_wait(nfa, &out, end - start);
.mov (labels[op.out()], as::rsi)
.push(as::rdi)
.call(&rejit_thread_wait)
.pop (as::rdi)
.jmp (fail)
// empty: eax = out(nfa);
.mark(empty)
.push(as::rdi)
.call(labels[op.out()])
.pop (as::rdi);
EMIT_NEXT(op.out());
break;
}
}
code.test(as::eax, as::eax).jmp(succeed, as::not_zero).mark(fail);
}
code.jmp(fail);
} else switch (op->opcode()) {
case re2::kInstAltMatch:
case re2::kInstAlt:
// if (out(nfa)) return 1;
code.push (as::rdi)
.call (labels[op->out()])
.pop (as::rdi)
.test (as::eax, as::eax).jmp(succeed, as::not_zero);
EMIT_NEXT(op->out());
EMIT_JUMP(op->out1());
break;
case re2::kInstByteRange: {
std::vector<re2::Prog::Inst *> seq{ op };
while ((op = prog->inst(op->out()))->opcode() == re2::kInstByteRange && !re2jit::maybe_extcode(op))
seq.push_back(op);
// if (nfa->length < len) return; else rsi = nfa->input;
code.cmp(as::i32(seq.size()), as::mem(as::rdi + &NFA->length)).jmp(fail, as::less_u)
.mov(as::mem(as::rdi + &NFA->input), as::rsi);
for (auto op : seq) {
code.mov(as::mem(as::rsi), as::al)
.add(as::i8(1), as::rsi);
if (op->foldcase())
// if ('A' <= al && al <= 'Z') al = al - 'A' + 'a';
code.mov(as::rax - 'A', as::ecx)
.mov(as::rcx + 'a', as::edx)
.cmp('Z' - 'A', as::cl)
.mov(as::edx, as::eax, as::less_equal_u);
if (op->hi() == op->lo())
// if (al != lo) return;
code.cmp(op->lo(), as::al).jmp(fail, as::not_equal);
else
// if (al < lo || hi < al) return;
code.sub(op->lo(), as::al)
.cmp(op->hi() - op->lo(), as::al).jmp(fail, as::more_u);
}
// return rejit_thread_wait(nfa, &out, len);
code.mov(labels[seq.back()->out()], as::rsi)
.mov(seq.size(), as::edx)
.jmp(&rejit_thread_wait);
EMIT_NEXT(seq.back()->out());
break;
}
case re2::kInstCapture:
// if (nfa->groups <= cap) goto out;
code.cmp (as::i32(op->cap()), as::mem(as::rdi + &NFA->groups))
.jmp (labels[op->out()], as::less_equal_u)
// esi = nfa->running->groups[cap]; nfa->running->groups[cap] = nfa->offset;
.mov (as::mem(as::rdi + &NFA->running), as::rcx)
.mov (as::mem(as::rdi + &NFA->offset), as::eax)
.mov (as::mem(as::rcx + &THREAD->groups[op->cap()]), as::esi)
.mov (as::eax, as::mem(as::rcx + &THREAD->groups[op->cap()]))
.push (as::rsi)
.push (as::rcx);
if (backreferences.find(op->cap() / 2) != backreferences.end())
// rejit_thread_bitmap_save(nfa); eax = out(nfa);
// rejit_thread_bitmap_restore(nfa);
code.push (as::rdi).call(&rejit_thread_bitmap_save) .pop(as::rdi)
.push (as::rdi).call(labels[op->out()]) .pop(as::rdi)
.push (as::rax).call(&rejit_thread_bitmap_restore) .pop(as::rax);
else
// eax = out(nfa);
code.call(labels[op->out()]);
code.pop(as::rcx)
.pop(as::rsi)
// nfa->running->groups[cap] = esi; return eax;
.mov(as::esi, as::mem(as::rcx + &THREAD->groups[op->cap()]))
.ret();
EMIT_NEXT(op->out());
break;
case re2::kInstEmptyWidth:
// if (~nfa->empty & empty) return;
code.mov (as::mem(as::rdi + &NFA->empty), as::eax)
.not_ (as::eax)
.test (op->empty(), as::eax).jmp(fail, as::not_zero);
EMIT_JUMP(op->out());
break;
case re2::kInstNop:
EMIT_JUMP(op->out());
break;
case re2::kInstMatch:
// return rejit_thread_match(nfa);
code.jmp(&rejit_thread_match);
break;
case re2::kInstFail:
code.ret();
break;
}
}
delete[] stack;
void *target = mmap(NULL, code.size(), PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (target == (void *) -1)
return;
if (!code.write(target) || mprotect(target, code.size(), PROT_READ | PROT_EXEC) == -1) {
munmap(target, code.size());
return;
}
entry = target;
state = labels[prog->start()]->deref(target);
_size = code.size();
}
~native()
{
munmap(entry, _size);
}
};
<commit_msg>x64: emit slightly less opcodes for kInstCapture<commit_after>#include <vector>
#include <unordered_set>
#include <sys/mman.h>
#include "it.x64.asm.h"
static const struct rejit_threadset_t *NFA = NULL; // used for offset calculation
static const struct rejit_thread_t *THREAD = NULL;
struct re2jit::native
{
void init() {}
void * entry;
void * state;
size_t _size;
native(re2::Prog *prog) : entry(NULL), state(NULL), _size(0)
{
size_t i;
size_t n = prog->size();
as::code code;
std::vector<as::label> labels(n);
// How many transitions have the i-th opcode as a target.
// Opcodes with indegree 1 don't need to be tracked in the bit vector
// (as there is only one way to reach them and we've already checked that).
// Opcodes with indegree 0 are completely unreachable, no need to compile those.
std::vector< unsigned > indegree(n);
std::vector< unsigned > emitted(n);
// If the regexp contains backreferences, we have to fall back to sort-of
// backtracking. Well, *technically*, we can simply replace our bit vector
// of `m` visited states with a bit vector of `m * n ** (2 * k)` states
// where `k` is the number of (referenced) groups and `n` is the length of input.
// You thought the `m * n` bits required to make backtrackers run in linear time
// was a lot? Think again.
std::unordered_set< unsigned > backreferences;
ssize_t *stack = new ssize_t[prog->size()];
ssize_t *stptr = stack;
indegree[*stptr++ = prog->start()]++;
while (stptr != stack) {
auto op = prog->inst(*--stptr);
auto vec = re2jit::is_extcode(prog, op);
for (auto& op : vec) {
if (op.opcode() == re2jit::inst::kBackReference)
// Note that the fact that a regex with backreferences requires
// at most O(m * n ** (2 * k + 1)) time to match does not prove
// P = NP in any way. Reducing 3-SAT to PCRE matching is done
// by constructing a regex in which m = k = O(n). O(n * n ** n)?
// That's worse than brute-force.
backreferences.insert(op.arg());
if (!indegree[op.out()]++)
*stptr++ = op.out();
}
if (!vec.size())
switch (op->opcode()) {
case re2::kInstAlt:
case re2::kInstAltMatch:
if (!indegree[op->out1()]++)
*stptr++ = op->out1();
default:
if (!indegree[op->out()]++)
*stptr++ = op->out();
case re2::kInstFail:
case re2::kInstMatch:
break;
case re2::kInstByteRange:
if (!indegree[op->out()])
*stptr++ = op->out();
// subsequent byte ranges are concatenated into one block of code
auto next = prog->inst(op->out());
if (next->opcode() != re2::kInstByteRange && !re2jit::maybe_extcode(next))
indegree[op->out()]++;
}
}
// NFA will call this code with itself (%rdi) and a state (%rsi).
// In our case, the state is a pointer to actual code to execute.
// Each thread has its own array of group indices...
if (backreferences.size())
// ...so it must have its own zero-filled bit vector of visited states.
code.push(as::rdi)
.push(as::rsi)
.call(&rejit_thread_bitmap_clear)
.pop (as::rsi)
.pop (as::rdi)
.jmp (as::rsi);
else
// ...but we don't care, so we can simply jump to actual code.
code.jmp(as::rsi);
as::label fail; // jump here to return 0
as::label succeed; // jump here to return 1 (if a matching state is reachable)
code.mark(fail).xor_(as::eax, as::eax).mark(succeed).ret();
emitted[*stptr++ = prog->start()]++;
while (stptr != stack) {
#define EMIT_NEXT(i) if (!emitted[i]++) *stptr++ = i
#define EMIT_JUMP(i) EMIT_NEXT(i); else code.jmp(labels[i])
code.mark(labels[i = *--stptr]);
// Each opcode should conform to the System V ABI calling convention.
// argument 1: %rdi = struct rejit_threadset_t *nfa
// return reg: %rax = 1 iff found a match somewhere
auto op = prog->inst(i);
auto vec = re2jit::is_extcode(prog, op);
// kInstFail will do `ret` anyway.
if (op->opcode() != re2::kInstFail && indegree[i] > 1)
// if (bit(nfa->visited, i) == 1) return; bit(nfa->visited, i) = 1;
code.mov (as::mem(as::rdi + &NFA->visited), as::rsi)
.test (as::i8(1 << (i % 8)), as::mem(as::rsi + i / 8)).jmp(fail, as::not_zero)
.or_ (as::i8(1 << (i % 8)), as::mem(as::rsi + i / 8));
if (vec.size()) {
for (auto &op : vec) {
// Instead of returning, a failed pseudo-inst should jump
// to the next inst in the alternation.
as::label fail;
switch (op.opcode()) {
case re2jit::inst::kUnicodeType:
// utf8_chr = rejit_read_utf8(nfa->input, nfa->length);
code.push (as::rdi)
.mov (as::mem(as::rdi + &NFA->length), as::rsi)
.mov (as::mem(as::rdi + &NFA->input), as::rdi)
.call (&rejit_read_utf8)
.pop (as::rdi)
// if ((utf8_length = utf8_chr >> 32) == 0) return;
.mov (as::rax, as::rdx)
.shr (32, as::rdx).jmp(fail, as::zero)
// if ((rejit_unicode_category(utf8_chr) & UNICODE_CATEGORY_GENERAL) != arg) return;
.push (as::rdi)
.push (as::rdx)
.mov (as::eax, as::edi)
.call (&rejit_unicode_category) // inlining is hard.
.pop (as::rdx)
.pop (as::rdi)
.and_ (UNICODE_CATEGORY_GENERAL, as::al)
.cmp (op.arg(), as::al).jmp(fail, as::not_equal)
// rejit_thread_wait(nfa, &out, utf8_length);
.mov (labels[op.out()], as::rsi)
.push (as::rdi)
.call (&rejit_thread_wait)
.pop (as::rdi);
EMIT_NEXT(op.out());
break;
case re2jit::inst::kBackReference: {
as::label empty;
// if (nfa->groups <= arg * 2) return;
code.cmp(as::i32(op.arg() * 2), as::mem(as::rdi + &NFA->groups))
.jmp(fail, as::less_equal_u) // wasn't enough space to record that group
// if (start == -1 || end < start) return;
.mov(as::mem(as::rdi + &NFA->running), as::rsi)
.mov(as::mem(as::rsi + &THREAD->groups[op.arg() * 2 + 1]), as::ecx)
.mov(as::mem(as::rsi + &THREAD->groups[op.arg() * 2]), as::esi)
.cmp(as::i8(-1), as::esi).jmp(fail, as::equal)
.sub(as::esi, as::ecx).jmp(fail, as::less)
// if (start == end) goto empty;
.jmp(empty, as::equal)
// if (nfa->length < end - start) return;
.cmp(as::rcx, as::mem(as::rdi + &NFA->length)).jmp(fail, as::less_u)
// if (memcmp(nfa->input, nfa->input + start - nfa->offset, end - start)) return;
.push(as::rdi)
.sub (as::mem(as::rdi + &NFA->offset), as::rsi)
.mov (as::mem(as::rdi + &NFA->input), as::rdi)
.mov (as::ecx, as::edx)
.add (as::rdi, as::rsi)
.repz().cmpsb().pop(as::rdi).jmp(fail, as::not_equal)
// return rejit_thread_wait(nfa, &out, end - start);
.mov (labels[op.out()], as::rsi)
.push(as::rdi)
.call(&rejit_thread_wait)
.pop (as::rdi)
.jmp (fail)
// empty: eax = out(nfa);
.mark(empty)
.push(as::rdi)
.call(labels[op.out()])
.pop (as::rdi);
EMIT_NEXT(op.out());
break;
}
}
code.test(as::eax, as::eax).jmp(succeed, as::not_zero).mark(fail);
}
code.jmp(fail);
} else switch (op->opcode()) {
case re2::kInstAltMatch:
case re2::kInstAlt:
// if (out(nfa)) return 1;
code.push (as::rdi)
.call (labels[op->out()])
.pop (as::rdi)
.test (as::eax, as::eax).jmp(succeed, as::not_zero);
EMIT_NEXT(op->out());
EMIT_JUMP(op->out1());
break;
case re2::kInstByteRange: {
std::vector<re2::Prog::Inst *> seq{ op };
while ((op = prog->inst(op->out()))->opcode() == re2::kInstByteRange && !re2jit::maybe_extcode(op))
seq.push_back(op);
// if (nfa->length < len) return; else rsi = nfa->input;
code.cmp(as::i32(seq.size()), as::mem(as::rdi + &NFA->length)).jmp(fail, as::less_u)
.mov(as::mem(as::rdi + &NFA->input), as::rsi);
for (auto op : seq) {
code.mov(as::mem(as::rsi), as::al)
.add(as::i8(1), as::rsi);
if (op->foldcase())
// if ('A' <= al && al <= 'Z') al = al - 'A' + 'a';
code.mov(as::rax - 'A', as::ecx)
.mov(as::rcx + 'a', as::edx)
.cmp('Z' - 'A', as::cl)
.mov(as::edx, as::eax, as::less_equal_u);
if (op->hi() == op->lo())
// if (al != lo) return;
code.cmp(op->lo(), as::al).jmp(fail, as::not_equal);
else
// if (al < lo || hi < al) return;
code.sub(op->lo(), as::al)
.cmp(op->hi() - op->lo(), as::al).jmp(fail, as::more_u);
}
// return rejit_thread_wait(nfa, &out, len);
code.mov(labels[seq.back()->out()], as::rsi)
.mov(seq.size(), as::edx)
.jmp(&rejit_thread_wait);
EMIT_NEXT(seq.back()->out());
break;
}
case re2::kInstCapture:
// if (nfa->groups <= cap) goto out;
code.cmp (as::i32(op->cap()), as::mem(as::rdi + &NFA->groups))
.jmp (labels[op->out()], as::less_equal_u)
// push(nfa->running->groups[cap]); nfa->running->groups[cap] = nfa->offset;
.mov (as::mem(as::rdi + &NFA->running), as::rcx)
.mov (as::mem(as::rdi + &NFA->offset), as::eax)
.push (as::mem(as::rcx + &THREAD->groups[op->cap()]))
.push (as::rcx)
.mov (as::eax, as::mem(as::rcx + &THREAD->groups[op->cap()]));
if (backreferences.find(op->cap() / 2) != backreferences.end())
// rejit_thread_bitmap_save(nfa); eax = out(nfa);
// rejit_thread_bitmap_restore(nfa);
code.push (as::rdi).call(&rejit_thread_bitmap_save) .pop(as::rdi)
.push (as::rdi).call(labels[op->out()]) .pop(as::rdi)
.push (as::rax).call(&rejit_thread_bitmap_restore) .pop(as::rax);
else
// eax = out(nfa);
code.call(labels[op->out()]);
// pop(nfa->running->groups[cap]); return eax;
code.pop(as::rcx)
.pop(as::mem(as::rcx + &THREAD->groups[op->cap()]))
.ret();
EMIT_NEXT(op->out());
break;
case re2::kInstEmptyWidth:
// if (~nfa->empty & empty) return;
code.mov (as::mem(as::rdi + &NFA->empty), as::eax)
.not_ (as::eax)
.test (op->empty(), as::eax).jmp(fail, as::not_zero);
EMIT_JUMP(op->out());
break;
case re2::kInstNop:
EMIT_JUMP(op->out());
break;
case re2::kInstMatch:
// return rejit_thread_match(nfa);
code.jmp(&rejit_thread_match);
break;
case re2::kInstFail:
code.ret();
break;
}
}
delete[] stack;
void *target = mmap(NULL, code.size(), PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (target == (void *) -1)
return;
if (!code.write(target) || mprotect(target, code.size(), PROT_READ | PROT_EXEC) == -1) {
munmap(target, code.size());
return;
}
entry = target;
state = labels[prog->start()]->deref(target);
_size = code.size();
}
~native()
{
munmap(entry, _size);
}
};
<|endoftext|>
|
<commit_before>// Main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "arduino.h"
#include "OneNoteHelper.h"
#include "MinSerLib.h"
#include <time.h>
int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}
const int buttonPin = 2;
int buttonState = 0;
OneNoteHelper *One;
std::list<std::wstring> skipIDs;
MinSerClass * msc = nullptr;
int idlecount = 0;
void PostToDo(void)
{
// get current time
char buf[80];
time_t now = time(0);
struct tm tstruct;
localtime_s(&tstruct, &now);
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
// Write a page
std::string message = "";
message += "<!DOCTYPE html><html><head><title>TODO</title><meta name = \"created\" content = \"2014-10-13T07:00:00.000-7:00\" /></head>";
message += "<body>";
message += "<p>";
message += buf;
message += "</p>";
message += "<p>Buy: milk, bread<br/>Pick up: laundry, dog<br/>Clean: floors, car<br>Fix: sink, door<br/>Appt: 6pm football</p>";
message += "</body>";
message += "</html>";
One->PageWrite(message.c_str());
}
bool PrintToDo(bool force)
{
// Read a page
char * p = One->PageRead(NULL, 0, skipIDs);
if (force || (p != NULL && *p != 0))
{
// Print it
One->StripMarkup(One->_buf, _countof(One->_buf));
if (msc->Open(L"\\\\.\\COM2") == S_OK) {
const char trailer[] = "\r\n\r\n\r\n----------\r\n\r\n\r\n";
strcat_s(One->_buf, _countof(One->_buf), trailer);
msc->SchedWrite((BYTE*)One->_buf, strlen(One->_buf));
int ok = msc->WaitToComplete(10000);
}
}
return (p != NULL && *p != 0);
}
void setup()
{
pinMode(buttonPin, INPUT);
One = new OneNoteHelper();
One->_showLog = true;
One->OpenNotebook(NULL, NULL, L"TODO", NULL);
One->GetPageIDs(NULL, 0, skipIDs);
msc = new MinSerClass();
}
// the loop routine runs over and over again forever:
void loop()
{
delay(100);
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == LOW) {
Log(L"Pushbutton pressed .. \n");
std::string msg;
PostToDo();
PrintToDo(true);
}
}
<commit_msg>Removing unused msg<commit_after>// Main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "arduino.h"
#include "OneNoteHelper.h"
#include "MinSerLib.h"
#include <time.h>
int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}
const int buttonPin = 2;
int buttonState = 0;
OneNoteHelper *One;
std::list<std::wstring> skipIDs;
MinSerClass * msc = nullptr;
int idlecount = 0;
void PostToDo(void)
{
// get current time
char buf[80];
time_t now = time(0);
struct tm tstruct;
localtime_s(&tstruct, &now);
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
// Write a page
std::string message = "";
message += "<!DOCTYPE html><html><head><title>TODO</title><meta name = \"created\" content = \"2014-10-13T07:00:00.000-7:00\" /></head>";
message += "<body>";
message += "<p>";
message += buf;
message += "</p>";
message += "<p>Buy: milk, bread<br/>Pick up: laundry, dog<br/>Clean: floors, car<br>Fix: sink, door<br/>Appt: 6pm football</p>";
message += "</body>";
message += "</html>";
One->PageWrite(message.c_str());
}
bool PrintToDo(bool force)
{
// Read a page
char * p = One->PageRead(NULL, 0, skipIDs);
if (force || (p != NULL && *p != 0))
{
// Print it
One->StripMarkup(One->_buf, _countof(One->_buf));
if (msc->Open(L"\\\\.\\COM2") == S_OK) {
const char trailer[] = "\r\n\r\n\r\n----------\r\n\r\n\r\n";
strcat_s(One->_buf, _countof(One->_buf), trailer);
msc->SchedWrite((BYTE*)One->_buf, strlen(One->_buf));
int ok = msc->WaitToComplete(10000);
}
}
return (p != NULL && *p != 0);
}
void setup()
{
pinMode(buttonPin, INPUT);
One = new OneNoteHelper();
One->_showLog = true;
One->OpenNotebook(NULL, NULL, L"TODO", NULL);
One->GetPageIDs(NULL, 0, skipIDs);
msc = new MinSerClass();
}
// the loop routine runs over and over again forever:
void loop()
{
delay(100);
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
if (buttonState == LOW) {
Log(L"Pushbutton pressed .. \n");
PostToDo();
PrintToDo(true);
}
}
<|endoftext|>
|
<commit_before><commit_msg>TriggerPaintEvent too then<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: accessiblecontexthelper.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: fs $ $Date: 2002-04-26 14:24:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX
#include <comphelper/accessiblecontexthelper.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::drafts::com::sun::star::accessibility;
//=====================================================================
//= OContextHelper_Impl
//=====================================================================
/** implementation class for OAccessibleContextHelper. No own thread safety!
*/
class OContextHelper_Impl
{
private:
OAccessibleContextHelper* m_pAntiImpl; // the owning instance
::cppu::OInterfaceContainerHelper* m_pEventListeners;
WeakReference< XAccessible > m_aCreator; // the XAccessible which created our XAccessibleContext
public:
::cppu::OInterfaceContainerHelper* getListenerContainer( sal_Bool _bCreate = sal_True );
// not const - will create if necessary
inline Reference< XAccessible > getCreator( ) const { return m_aCreator; }
inline void setCreator( const Reference< XAccessible >& _rAcc );
public:
OContextHelper_Impl( OAccessibleContextHelper* _pAntiImpl )
:m_pAntiImpl( _pAntiImpl )
,m_pEventListeners( NULL )
{
}
};
//---------------------------------------------------------------------
inline void OContextHelper_Impl::setCreator( const Reference< XAccessible >& _rAcc )
{
m_aCreator = _rAcc;
}
//---------------------------------------------------------------------
::cppu::OInterfaceContainerHelper* OContextHelper_Impl::getListenerContainer( sal_Bool _bCreate )
{
if ( !m_pEventListeners && _bCreate )
m_pEventListeners = new ::cppu::OInterfaceContainerHelper( m_pAntiImpl->GetMutex( OAccessibleContextHelper::OAccessControl() ) );
return m_pEventListeners;
}
//=====================================================================
//= OAccessibleContextHelper
//=====================================================================
//---------------------------------------------------------------------
OAccessibleContextHelper::OAccessibleContextHelper( )
:OAccessibleContextHelper_Base( GetMutex() )
,m_pImpl( NULL )
{
m_pImpl = new OContextHelper_Impl( this );
}
//---------------------------------------------------------------------
OAccessibleContextHelper::~OAccessibleContextHelper( )
{
ensureDisposed();
delete m_pImpl;
m_pImpl = NULL;
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::disposing()
{
// notify our listeners that we're going to be defunc
NotifyAccessibleEvent(
AccessibleEventId::ACCESSIBLE_STATE_EVENT,
Any(),
makeAny( AccessibleStateType::DEFUNC )
);
::osl::ClearableMutexGuard aGuard( GetMutex() );
::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False );
if ( pListeners )
{
EventObject aDisposee( *this );
aGuard.clear();
pListeners->disposeAndClear( aDisposee );
}
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::addEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException)
{
OContextEntryGuard( this );
if ( _rxListener.is() )
m_pImpl->getListenerContainer()->addInterface( _rxListener );
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::removeEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException)
{
OContextEntryGuard( this );
if ( _rxListener.is() )
m_pImpl->getListenerContainer()->removeInterface( _rxListener );
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::NotifyAccessibleEvent( const sal_Int16 _nEventId,
const Any& _rOldValue, const Any& _rNewValue )
{
// copy our current listeners
::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False );
Sequence< Reference< XInterface > > aListeners;
if ( pListeners )
aListeners = pListeners->getElements();
if ( aListeners.getLength() )
{
AccessibleEventObject aEvent;
aEvent.Source = m_pImpl->getCreator();
OSL_ENSURE( aEvent.Source.is(), "OAccessibleContextHelper::NotifyAccessibleEvent: invalid creator!" );
aEvent.EventId = _nEventId;
aEvent.OldValue = _rOldValue;
aEvent.NewValue = _rNewValue;
const Reference< XInterface >* pLoop = aListeners.getConstArray();
const Reference< XInterface >* pLoopEnd = pLoop + aListeners.getLength();
while ( pLoop != pLoopEnd )
{
try
{
while ( pLoop != pLoopEnd )
{
XAccessibleEventListener* pListener = static_cast< XAccessibleEventListener* > (
pLoop->get() );
// note that this cast is valid:
// We added the interface to our listener container, and at this time it was an
// XAccessibleEventListener. As we did not query for XInterface, but instead used
// the XInterface which is the base of XAccessibleEventListener, we can now safely
// cast.
if ( pListener )
pListener->notifyEvent( aEvent );
++pLoop;
}
}
catch( const Exception& e )
{
e; // make compiler happy
// skip this listener and continue with the next one
++pLoop;
}
}
}
}
//---------------------------------------------------------------------
sal_Bool OAccessibleContextHelper::isAlive() const
{
return !GetBroadcastHelper().bDisposed && !GetBroadcastHelper().bInDispose;
}
//---------------------------------------------------------------------
void OAccessibleContextHelper::ensureAlive() const SAL_THROW( ( DisposedException ) )
{
if( !isAlive() )
throw DisposedException();
}
//---------------------------------------------------------------------
void OAccessibleContextHelper::ensureDisposed( )
{
if ( !GetBroadcastHelper().bDisposed )
{
OSL_ENSURE( 0 == m_refCount, "OAccessibleContextHelper::ensureDisposed: this method _has_ to be called from without your dtor only!" );
acquire();
dispose();
}
}
//---------------------------------------------------------------------
void OAccessibleContextHelper::lateInit( const Reference< XAccessible >& _rxAccessible )
{
m_pImpl->setCreator( _rxAccessible );
}
//---------------------------------------------------------------------
Reference< XAccessible > OAccessibleContextHelper::getAccessibleCreator( ) const
{
return m_pImpl->getCreator();
}
//---------------------------------------------------------------------
sal_Int32 SAL_CALL OAccessibleContextHelper::getAccessibleIndexInParent( ) throw (RuntimeException)
{
OContextEntryGuard aGuard( this );
// -1 for child not found/no parent (according to specification)
sal_Int32 nRet = -1;
try
{
Reference< XAccessibleContext > xParentContext( implGetParentContext() );
// iterate over parent's children and search for this object
if ( xParentContext.is() )
{
// our own XAccessible for comparing with the children of our parent
Reference< XAccessible > xCreator( m_pImpl->getCreator() );
OSL_ENSURE( xCreator.is(), "OAccessibleContextHelper::getAccessibleIndexInParent: invalid creator!" );
// two ideas why this could be NULL:
// * nobody called our late ctor (init), so we never had a creator at all -> bad
// * the creator is already dead. In this case, we should have been disposed, and
// never survived the above OContextEntryGuard.
// in all other situations the creator should be non-NULL
if ( xCreator.is() )
{
sal_Int32 nChildCount = xParentContext->getAccessibleChildCount();
for ( sal_Int32 nChild = 0; ( nChild < nChildCount ) && ( -1 == nRet ); ++nChild )
{
Reference< XAccessible > xChild( xParentContext->getAccessibleChild( nChild ) );
if ( xChild.get() == xCreator.get() )
nRet = nChild;
}
}
}
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "OAccessibleContextHelper::getAccessibleIndexInParent: caught an exception!" );
}
return nRet;
}
//---------------------------------------------------------------------
Locale SAL_CALL OAccessibleContextHelper::getLocale( ) throw (IllegalAccessibleComponentStateException, RuntimeException)
{
// simply ask the parent
Reference< XAccessible > xParent = getAccessibleParent();
Reference< XAccessibleContext > xParentContext;
if ( xParent.is() )
xParentContext = xParent->getAccessibleContext();
if ( !xParentContext.is() )
throw IllegalAccessibleComponentStateException( ::rtl::OUString(), *this );
return xParentContext->getLocale();
}
//---------------------------------------------------------------------
Reference< XAccessibleContext > OAccessibleContextHelper::implGetParentContext() SAL_THROW( ( RuntimeException ) )
{
Reference< XAccessible > xParent = getAccessibleParent();
Reference< XAccessibleContext > xParentContext;
if ( xParent.is() )
xParentContext = xParent->getAccessibleContext();
return xParentContext;
}
//.........................................................................
} // namespace comphelper
//.........................................................................
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
* Revision 1.3 2002/04/26 07:25:50 fs
* #98750# corrected NotifyAccessibleEvent
*
* Revision 1.2 2002/04/26 05:52:18 fs
* #98750# use correct broadcasthelper (in the WeagAggComponentImpl* base)
*
* Revision 1.1 2002/04/23 11:10:30 fs
* initial checkin - helper for implementing an XAccessibleContext
*
*
* Revision 1.0 17.04.2002 16:06:46 fs
************************************************************************/
<commit_msg>#65293#: removed not needed vcl/svapp.hxx includes to reduce dependencies<commit_after>/*************************************************************************
*
* $RCSfile: accessiblecontexthelper.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2002-04-30 07:42:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef COMPHELPER_ACCESSIBLE_CONTEXT_HELPER_HXX
#include <comphelper/accessiblecontexthelper.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
//.........................................................................
namespace comphelper
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::drafts::com::sun::star::accessibility;
//=====================================================================
//= OContextHelper_Impl
//=====================================================================
/** implementation class for OAccessibleContextHelper. No own thread safety!
*/
class OContextHelper_Impl
{
private:
OAccessibleContextHelper* m_pAntiImpl; // the owning instance
::cppu::OInterfaceContainerHelper* m_pEventListeners;
WeakReference< XAccessible > m_aCreator; // the XAccessible which created our XAccessibleContext
public:
::cppu::OInterfaceContainerHelper* getListenerContainer( sal_Bool _bCreate = sal_True );
// not const - will create if necessary
inline Reference< XAccessible > getCreator( ) const { return m_aCreator; }
inline void setCreator( const Reference< XAccessible >& _rAcc );
public:
OContextHelper_Impl( OAccessibleContextHelper* _pAntiImpl )
:m_pAntiImpl( _pAntiImpl )
,m_pEventListeners( NULL )
{
}
};
//---------------------------------------------------------------------
inline void OContextHelper_Impl::setCreator( const Reference< XAccessible >& _rAcc )
{
m_aCreator = _rAcc;
}
//---------------------------------------------------------------------
::cppu::OInterfaceContainerHelper* OContextHelper_Impl::getListenerContainer( sal_Bool _bCreate )
{
if ( !m_pEventListeners && _bCreate )
m_pEventListeners = new ::cppu::OInterfaceContainerHelper( m_pAntiImpl->GetMutex( OAccessibleContextHelper::OAccessControl() ) );
return m_pEventListeners;
}
//=====================================================================
//= OAccessibleContextHelper
//=====================================================================
//---------------------------------------------------------------------
OAccessibleContextHelper::OAccessibleContextHelper( )
:OAccessibleContextHelper_Base( GetMutex() )
,m_pImpl( NULL )
{
m_pImpl = new OContextHelper_Impl( this );
}
//---------------------------------------------------------------------
OAccessibleContextHelper::~OAccessibleContextHelper( )
{
ensureDisposed();
delete m_pImpl;
m_pImpl = NULL;
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::disposing()
{
// notify our listeners that we're going to be defunc
NotifyAccessibleEvent(
AccessibleEventId::ACCESSIBLE_STATE_EVENT,
Any(),
makeAny( AccessibleStateType::DEFUNC )
);
::osl::ClearableMutexGuard aGuard( GetMutex() );
::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False );
if ( pListeners )
{
EventObject aDisposee( *this );
aGuard.clear();
pListeners->disposeAndClear( aDisposee );
}
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::addEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException)
{
OContextEntryGuard( this );
if ( _rxListener.is() )
m_pImpl->getListenerContainer()->addInterface( _rxListener );
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::removeEventListener( const Reference< XAccessibleEventListener >& _rxListener ) throw (RuntimeException)
{
OContextEntryGuard( this );
if ( _rxListener.is() )
m_pImpl->getListenerContainer()->removeInterface( _rxListener );
}
//---------------------------------------------------------------------
void SAL_CALL OAccessibleContextHelper::NotifyAccessibleEvent( const sal_Int16 _nEventId,
const Any& _rOldValue, const Any& _rNewValue )
{
// copy our current listeners
::cppu::OInterfaceContainerHelper* pListeners = m_pImpl->getListenerContainer( sal_False );
Sequence< Reference< XInterface > > aListeners;
if ( pListeners )
aListeners = pListeners->getElements();
if ( aListeners.getLength() )
{
AccessibleEventObject aEvent;
aEvent.Source = m_pImpl->getCreator();
OSL_ENSURE( aEvent.Source.is(), "OAccessibleContextHelper::NotifyAccessibleEvent: invalid creator!" );
aEvent.EventId = _nEventId;
aEvent.OldValue = _rOldValue;
aEvent.NewValue = _rNewValue;
const Reference< XInterface >* pLoop = aListeners.getConstArray();
const Reference< XInterface >* pLoopEnd = pLoop + aListeners.getLength();
while ( pLoop != pLoopEnd )
{
try
{
while ( pLoop != pLoopEnd )
{
XAccessibleEventListener* pListener = static_cast< XAccessibleEventListener* > (
pLoop->get() );
// note that this cast is valid:
// We added the interface to our listener container, and at this time it was an
// XAccessibleEventListener. As we did not query for XInterface, but instead used
// the XInterface which is the base of XAccessibleEventListener, we can now safely
// cast.
if ( pListener )
pListener->notifyEvent( aEvent );
++pLoop;
}
}
catch( const Exception& e )
{
e; // make compiler happy
// skip this listener and continue with the next one
++pLoop;
}
}
}
}
//---------------------------------------------------------------------
sal_Bool OAccessibleContextHelper::isAlive() const
{
return !GetBroadcastHelper().bDisposed && !GetBroadcastHelper().bInDispose;
}
//---------------------------------------------------------------------
void OAccessibleContextHelper::ensureAlive() const SAL_THROW( ( DisposedException ) )
{
if( !isAlive() )
throw DisposedException();
}
//---------------------------------------------------------------------
void OAccessibleContextHelper::ensureDisposed( )
{
if ( !GetBroadcastHelper().bDisposed )
{
OSL_ENSURE( 0 == m_refCount, "OAccessibleContextHelper::ensureDisposed: this method _has_ to be called from without your dtor only!" );
acquire();
dispose();
}
}
//---------------------------------------------------------------------
void OAccessibleContextHelper::lateInit( const Reference< XAccessible >& _rxAccessible )
{
m_pImpl->setCreator( _rxAccessible );
}
//---------------------------------------------------------------------
Reference< XAccessible > OAccessibleContextHelper::getAccessibleCreator( ) const
{
return m_pImpl->getCreator();
}
//---------------------------------------------------------------------
sal_Int32 SAL_CALL OAccessibleContextHelper::getAccessibleIndexInParent( ) throw (RuntimeException)
{
OContextEntryGuard aGuard( this );
// -1 for child not found/no parent (according to specification)
sal_Int32 nRet = -1;
try
{
Reference< XAccessibleContext > xParentContext( implGetParentContext() );
// iterate over parent's children and search for this object
if ( xParentContext.is() )
{
// our own XAccessible for comparing with the children of our parent
Reference< XAccessible > xCreator( m_pImpl->getCreator() );
OSL_ENSURE( xCreator.is(), "OAccessibleContextHelper::getAccessibleIndexInParent: invalid creator!" );
// two ideas why this could be NULL:
// * nobody called our late ctor (init), so we never had a creator at all -> bad
// * the creator is already dead. In this case, we should have been disposed, and
// never survived the above OContextEntryGuard.
// in all other situations the creator should be non-NULL
if ( xCreator.is() )
{
sal_Int32 nChildCount = xParentContext->getAccessibleChildCount();
for ( sal_Int32 nChild = 0; ( nChild < nChildCount ) && ( -1 == nRet ); ++nChild )
{
Reference< XAccessible > xChild( xParentContext->getAccessibleChild( nChild ) );
if ( xChild.get() == xCreator.get() )
nRet = nChild;
}
}
}
}
catch( const Exception& )
{
OSL_ENSURE( sal_False, "OAccessibleContextHelper::getAccessibleIndexInParent: caught an exception!" );
}
return nRet;
}
//---------------------------------------------------------------------
Locale SAL_CALL OAccessibleContextHelper::getLocale( ) throw (IllegalAccessibleComponentStateException, RuntimeException)
{
// simply ask the parent
Reference< XAccessible > xParent = getAccessibleParent();
Reference< XAccessibleContext > xParentContext;
if ( xParent.is() )
xParentContext = xParent->getAccessibleContext();
if ( !xParentContext.is() )
throw IllegalAccessibleComponentStateException( ::rtl::OUString(), *this );
return xParentContext->getLocale();
}
//---------------------------------------------------------------------
Reference< XAccessibleContext > OAccessibleContextHelper::implGetParentContext() SAL_THROW( ( RuntimeException ) )
{
Reference< XAccessible > xParent = getAccessibleParent();
Reference< XAccessibleContext > xParentContext;
if ( xParent.is() )
xParentContext = xParent->getAccessibleContext();
return xParentContext;
}
//.........................................................................
} // namespace comphelper
//.........................................................................
/*************************************************************************
* history:
* $Log: not supported by cvs2svn $
* Revision 1.4 2002/04/26 14:24:28 fs
* #98750# +getAccessibleCreator / use the creator (XAccessible) as event source
*
* Revision 1.3 2002/04/26 07:25:50 fs
* #98750# corrected NotifyAccessibleEvent
*
* Revision 1.2 2002/04/26 05:52:18 fs
* #98750# use correct broadcasthelper (in the WeagAggComponentImpl* base)
*
* Revision 1.1 2002/04/23 11:10:30 fs
* initial checkin - helper for implementing an XAccessibleContext
*
*
* Revision 1.0 17.04.2002 16:06:46 fs
************************************************************************/
<|endoftext|>
|
<commit_before>///
/// @file PhiTiny.hpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PHITINY_HPP
#define PHITINY_HPP
#include <int128.hpp>
#include <stdint.h>
#include <cassert>
#include <vector>
namespace primecount {
class PhiTiny {
public:
PhiTiny();
static int64_t max_a() { return 6; }
static bool is_tiny(int64_t a) { return a <= max_a(); }
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
/// @pre is_tiny(a).
///
template <typename X, typename A>
X phi(X x, A a) const
{
assert(is_tiny(a));
// phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
// with pp = 2 * 3 * ... * prime[a]
X pp = prime_products[a];
X x_div_pp = x / pp;
X x_mod_pp = x - pp * x_div_pp;
return x_div_pp * totients[a] + phi_cache_[a][x_mod_pp];
}
private:
std::vector<int16_t> phi_cache_[7];
static const int primes[7];
static const int prime_products[7];
static const int totients[7];
};
inline bool is_phi_tiny(int64_t a)
{
return PhiTiny::is_tiny(a);
}
#if __cplusplus >= 201103L
#include <type_traits>
template <typename X, typename A>
typename std::make_signed<X>::type phi_tiny(X x, A a)
{
extern const PhiTiny phiTiny;
return phiTiny.phi(x, a);
}
#else /* C++98 */
template <typename X, typename A>
X phi_tiny(X x, A a)
{
extern const PhiTiny phiTiny;
return phiTiny.phi(x, a);
}
#endif
} // namespace primecount
#endif
<commit_msg>Disable C++11 traits code<commit_after>///
/// @file PhiTiny.hpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PHITINY_HPP
#define PHITINY_HPP
#include <int128.hpp>
#include <stdint.h>
#include <cassert>
#include <vector>
namespace primecount {
class PhiTiny {
public:
PhiTiny();
static int64_t max_a() { return 6; }
static bool is_tiny(int64_t a) { return a <= max_a(); }
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
/// @pre is_tiny(a).
///
template <typename X, typename A>
X phi(X x, A a) const
{
assert(is_tiny(a));
// phi(x, a) = (x / pp) * φ(pp) + phi(x % pp, a)
// with pp = 2 * 3 * ... * prime[a]
X pp = prime_products[a];
X x_div_pp = x / pp;
X x_mod_pp = x - pp * x_div_pp;
return x_div_pp * totients[a] + phi_cache_[a][x_mod_pp];
}
private:
std::vector<int16_t> phi_cache_[7];
static const int primes[7];
static const int prime_products[7];
static const int totients[7];
};
inline bool is_phi_tiny(int64_t a)
{
return PhiTiny::is_tiny(a);
}
/* C++ compilers (2014) have trouble compiling:
* std::make_signed<__uint128_t>::type
#if __cplusplus >= 201103L
#include <type_traits>
template <typename X, typename A>
typename std::make_signed<X>::type phi_tiny(X x, A a)
{
extern const PhiTiny phiTiny;
return phiTiny.phi(x, a);
}
#else */
template <typename X, typename A>
X phi_tiny(X x, A a)
{
extern const PhiTiny phiTiny;
return phiTiny.phi(x, a);
}
} // namespace primecount
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: Renderer.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Toolkit. 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
=========================================================================*/
// .NAME vtkRenderer - abstract specification for renderers
// .SECTION Description
// vtkRenderer provides an abstract specification for renderers. A renderer
// is an object that controls the rendering process for objects. Rendering
// is the process of converting geometry, a specification for lights, and
// a camera view into an image. vtkRenderer also performs coordinate
// transformation between world coordinates, view coordinates (the computer
// graphics rendering coordinate system), and display coordinates (the
// actual screen coordinates on the display device).
#ifndef __vtkRenderer_hh
#define __vtkRenderer_hh
#include "Object.hh"
#include "Mat4x4.hh"
#include "LightC.hh"
#include "Camera.hh"
#include "ActorC.hh"
#include "GeomPrim.hh"
class vtkRenderWindow;
class vtkVolumeRenderer;
class vtkRenderer : public vtkObject
{
public:
vtkRenderer();
char *GetClassName() {return "vtkRenderer";};
void PrintSelf(ostream& os, vtkIndent indent);
void AddLights(vtkLight *);
void AddActors(vtkActor *);
void RemoveLights(vtkLight *);
void RemoveActors(vtkActor *);
vtkLightCollection *GetLights();
vtkActorCollection *GetActors();
void SetActiveCamera(vtkCamera *);
vtkCamera *GetActiveCamera();
void SetVolumeRenderer(vtkVolumeRenderer *);
vtkVolumeRenderer *GetVolumeRenderer();
// Description:
// Set the background color of the rendering screen using an rgb color
// specification.
vtkSetVector3Macro(Background,float);
vtkGetVectorMacro(Background,float,3);
// Description:
// Set the aspect ratio of the rendered image.
vtkSetVector2Macro(Aspect,float);
vtkGetVectorMacro(Aspect,float,2);
// Description:
// Set the level of ambient lighting.
vtkSetVector3Macro(Ambient,float);
vtkGetVectorMacro(Ambient,float,3);
// Description:
// Turn on/off whether objects are lit from behind with another light.
// If backlighting is on, for every light that is created, a second
// opposing light is created to backlight the object.
vtkSetMacro(BackLight,int);
vtkGetMacro(BackLight,int);
vtkBooleanMacro(BackLight,int);
// Description:
// Turn on/off erasing the screen between images. Allows multiple exposure
// sequences if turned on.
vtkSetMacro(Erase,int);
vtkGetMacro(Erase,int);
vtkBooleanMacro(Erase,int);
// Description:
// Create an image.
virtual void Render() = 0;
// Description:
// Get a device specific geometry representation.
virtual vtkGeometryPrimitive *GetPrimitive(char *) = 0;
// Description:
// Ask all actors to build and draw themselves.
virtual int UpdateActors(void) = 0;
// Description:
// Ask the camera to load its view matrix.
virtual int UpdateCameras(void) = 0;
// Description:
// Ask all lights to load themselves into rendering pipeline.
virtual int UpdateLights(void) = 0;
void DoCameras();
void DoLights();
void DoActors();
void ResetCamera();
void ResetCamera(float bounds[6]);
void SetRenderWindow(vtkRenderWindow *);
vtkRenderWindow *GetRenderWindow() {return RenderWindow;};
// Description:
// Specify a point location in display (or screen) coordinates.
vtkSetVector3Macro(DisplayPoint,float);
vtkGetVectorMacro(DisplayPoint,float,3);
// Description:
// Specify a point location in view coordinates.
vtkSetVector3Macro(ViewPoint,float);
vtkGetVectorMacro(ViewPoint,float,3);
// Description:
// Specify a point location in world coordinates.
vtkSetVector4Macro(WorldPoint,float);
vtkGetVectorMacro(WorldPoint,float,4);
// Description:
// Specify the area for the renderer to draw in the rendering window.
// Coordinates are expressed as (xmin,ymin,xmax,ymax) where each
// coordinate is 0 <= coordinate <= 1.0.
vtkSetVector4Macro(Viewport,float);
vtkGetVectorMacro(Viewport,float,4);
virtual float *GetCenter();
virtual void DisplayToView(); // these get modified in subclasses
virtual void ViewToDisplay(); // to handle stereo rendering
virtual int IsInViewport(int x,int y);
void WorldToView();
void ViewToWorld();
void DisplayToWorld();
void WorldToDisplay();
void SetStartRenderMethod(void (*f)(void *), void *arg);
void SetEndRenderMethod(void (*f)(void *), void *arg);
void SetStartRenderMethodArgDelete(void (*f)(void *));
void SetEndRenderMethodArgDelete(void (*f)(void *));
protected:
vtkVolumeRenderer *VolumeRenderer;
vtkCamera *ActiveCamera;
vtkLightCollection Lights;
vtkActorCollection Actors;
float Ambient[3];
float Background[3];
int BackLight;
vtkRenderWindow *RenderWindow;
float DisplayPoint[3];
float ViewPoint[3];
float WorldPoint[4];
float Viewport[4];
int Erase;
float Aspect[2];
float Center[2];
void (*StartRenderMethod)(void *);
void (*StartRenderMethodArgDelete)(void *);
void *StartRenderMethodArg;
void (*EndRenderMethod)(void *);
void (*EndRenderMethodArgDelete)(void *);
void *EndRenderMethodArg;
};
// Description:
// Get the list of lights for this renderer.
inline vtkLightCollection *vtkRenderer::GetLights() {return &(this->Lights);};
// Description:
// Get the list of actors for this renderer.
inline vtkActorCollection *vtkRenderer::GetActors() {return &(this->Actors);};
// Description:
// Convert display (or screen) coordinates to world coordinates.
inline void vtkRenderer::DisplayToWorld() {DisplayToView(); ViewToWorld();};
// Description:
// Convert world point coordinates to display (or screen) coordinates.
inline void vtkRenderer::WorldToDisplay() {WorldToView(); ViewToDisplay();};
#endif
<commit_msg>added better memory freeing<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: Renderer.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Toolkit. 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
=========================================================================*/
// .NAME vtkRenderer - abstract specification for renderers
// .SECTION Description
// vtkRenderer provides an abstract specification for renderers. A renderer
// is an object that controls the rendering process for objects. Rendering
// is the process of converting geometry, a specification for lights, and
// a camera view into an image. vtkRenderer also performs coordinate
// transformation between world coordinates, view coordinates (the computer
// graphics rendering coordinate system), and display coordinates (the
// actual screen coordinates on the display device).
#ifndef __vtkRenderer_hh
#define __vtkRenderer_hh
#include "Object.hh"
#include "Mat4x4.hh"
#include "LightC.hh"
#include "Camera.hh"
#include "ActorC.hh"
#include "GeomPrim.hh"
class vtkRenderWindow;
class vtkVolumeRenderer;
class vtkRenderer : public vtkObject
{
public:
vtkRenderer();
~vtkRenderer();
char *GetClassName() {return "vtkRenderer";};
void PrintSelf(ostream& os, vtkIndent indent);
void AddLights(vtkLight *);
void AddActors(vtkActor *);
void RemoveLights(vtkLight *);
void RemoveActors(vtkActor *);
vtkLightCollection *GetLights();
vtkActorCollection *GetActors();
void SetActiveCamera(vtkCamera *);
vtkCamera *GetActiveCamera();
void SetVolumeRenderer(vtkVolumeRenderer *);
vtkVolumeRenderer *GetVolumeRenderer();
// Description:
// Set the background color of the rendering screen using an rgb color
// specification.
vtkSetVector3Macro(Background,float);
vtkGetVectorMacro(Background,float,3);
// Description:
// Set the aspect ratio of the rendered image.
vtkSetVector2Macro(Aspect,float);
vtkGetVectorMacro(Aspect,float,2);
// Description:
// Set the level of ambient lighting.
vtkSetVector3Macro(Ambient,float);
vtkGetVectorMacro(Ambient,float,3);
// Description:
// Turn on/off whether objects are lit from behind with another light.
// If backlighting is on, for every light that is created, a second
// opposing light is created to backlight the object.
vtkSetMacro(BackLight,int);
vtkGetMacro(BackLight,int);
vtkBooleanMacro(BackLight,int);
// Description:
// Turn on/off erasing the screen between images. Allows multiple exposure
// sequences if turned on.
vtkSetMacro(Erase,int);
vtkGetMacro(Erase,int);
vtkBooleanMacro(Erase,int);
// Description:
// Create an image.
virtual void Render() = 0;
// Description:
// Get a device specific geometry representation.
virtual vtkGeometryPrimitive *GetPrimitive(char *) = 0;
// Description:
// Ask all actors to build and draw themselves.
virtual int UpdateActors(void) = 0;
// Description:
// Ask the camera to load its view matrix.
virtual int UpdateCameras(void) = 0;
// Description:
// Ask all lights to load themselves into rendering pipeline.
virtual int UpdateLights(void) = 0;
void DoCameras();
void DoLights();
void DoActors();
void ResetCamera();
void ResetCamera(float bounds[6]);
void SetRenderWindow(vtkRenderWindow *);
vtkRenderWindow *GetRenderWindow() {return RenderWindow;};
// Description:
// Specify a point location in display (or screen) coordinates.
vtkSetVector3Macro(DisplayPoint,float);
vtkGetVectorMacro(DisplayPoint,float,3);
// Description:
// Specify a point location in view coordinates.
vtkSetVector3Macro(ViewPoint,float);
vtkGetVectorMacro(ViewPoint,float,3);
// Description:
// Specify a point location in world coordinates.
vtkSetVector4Macro(WorldPoint,float);
vtkGetVectorMacro(WorldPoint,float,4);
// Description:
// Specify the area for the renderer to draw in the rendering window.
// Coordinates are expressed as (xmin,ymin,xmax,ymax) where each
// coordinate is 0 <= coordinate <= 1.0.
vtkSetVector4Macro(Viewport,float);
vtkGetVectorMacro(Viewport,float,4);
virtual float *GetCenter();
virtual void DisplayToView(); // these get modified in subclasses
virtual void ViewToDisplay(); // to handle stereo rendering
virtual int IsInViewport(int x,int y);
void WorldToView();
void ViewToWorld();
void DisplayToWorld();
void WorldToDisplay();
void SetStartRenderMethod(void (*f)(void *), void *arg);
void SetEndRenderMethod(void (*f)(void *), void *arg);
void SetStartRenderMethodArgDelete(void (*f)(void *));
void SetEndRenderMethodArgDelete(void (*f)(void *));
protected:
vtkVolumeRenderer *VolumeRenderer;
vtkCamera *ActiveCamera;
vtkLight *CreatedLight;
vtkLightCollection Lights;
vtkActorCollection Actors;
float Ambient[3];
float Background[3];
int BackLight;
vtkRenderWindow *RenderWindow;
float DisplayPoint[3];
float ViewPoint[3];
float WorldPoint[4];
float Viewport[4];
int Erase;
float Aspect[2];
float Center[2];
int SelfCreatedCamera;
int SelfCreatedLight;
void (*StartRenderMethod)(void *);
void (*StartRenderMethodArgDelete)(void *);
void *StartRenderMethodArg;
void (*EndRenderMethod)(void *);
void (*EndRenderMethodArgDelete)(void *);
void *EndRenderMethodArg;
};
// Description:
// Get the list of lights for this renderer.
inline vtkLightCollection *vtkRenderer::GetLights() {return &(this->Lights);};
// Description:
// Get the list of actors for this renderer.
inline vtkActorCollection *vtkRenderer::GetActors() {return &(this->Actors);};
// Description:
// Convert display (or screen) coordinates to world coordinates.
inline void vtkRenderer::DisplayToWorld() {DisplayToView(); ViewToWorld();};
// Description:
// Convert world point coordinates to display (or screen) coordinates.
inline void vtkRenderer::WorldToDisplay() {WorldToView(); ViewToDisplay();};
#endif
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CONSOLE_H
#define CONSOLE_H
#include <vector>
#include <string>
#include <iostream>
#include "money.hpp"
#include "date.hpp"
#include "accounts.hpp"
#include "assets.hpp"
namespace budget {
inline std::string red(const std::string& str){
return "\033[0;31m" + str + "\033[0;3047m";
}
inline std::string green(const std::string& str){
return "\033[0;32m" + str + "\033[0;3047m";
}
inline std::string cyan(const std::string& str){
return "\033[0;33m" + str + "\033[0;3047m";
}
std::string format_money(const budget::money& m);
std::string format_money_no_color(const budget::money& m);
std::string format_money_reverse(const budget::money& m);
/**
* Returns the real size of a string. By default, accented characteres are
* represented by several chars and make the length of the string being bigger
* than its displayable length. This functionr returns only a size of 1 for an
* accented chars.
* \param value The string we want the real length for.
* \return The real length of the string.
*/
size_t rsize(const std::string& value);
size_t rsize_after(const std::string& value);
template<typename T>
void print_minimum(std::ostream& os, const T& value, size_t min_width){
auto str = to_string(value);
auto old_width = os.width();
os.width(min_width + (str.size() - rsize(str)));
os << str;
os.width(old_width);
}
template<typename T>
void print_minimum(const T& value, size_t min_width){
print_minimum(std::cout, value, min_width);
}
/**
* Indicate if the given option was present in the list. If present, the option
* is removed from the list.
* \param option The full option name with any - included
* \param args The command line arguments
* \return true if the option was present, false otherwise.
*/
bool option(const std::string& option, std::vector<std::string>& args);
/**
* Return the value of the given option if present or the default value
* otherwise
* \param option The full option name with any - included
* \param args The command line arguments
* \return The string value of the option or the default value is not present.
*/
std::string option_value(const std::string& option, std::vector<std::string>& args, const std::string& value);
std::string format_code(int attr, int fg, int bg);
std::string format_reset();
std::string format(const std::string& value);
void display_table(std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups = 1, std::vector<size_t> lines = {});
void display_table(std::ostream& os, std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups = 1, std::vector<size_t> lines = {});
template<typename T>
bool check(const T&){
return true;
}
template<typename T, typename CheckerA, typename ...Checker>
bool check(const T& value, CheckerA first, Checker... checkers){
if(!first(value)){
std::cout << first.message() << std::endl;
return false;
}
return check(value, checkers...);
}
template<typename ...Checker>
void edit_string(std::string& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = answer;
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_number(size_t& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = to_number<size_t>(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_double(double& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = to_number<double>(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_money(budget::money& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = parse_money(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_date(date& ref, const std::string& title, Checker... checkers){
bool checked;
do {
try {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
bool math = false;
if(answer[0] == '+'){
std::string str(std::next(answer.begin()), std::prev(answer.end()));
if(answer.back() == 'd'){
ref += days(std::stoi(str));
math = true;
} else if(answer.back() == 'm'){
ref += months(std::stoi(str));
math = true;
} else if(answer.back() == 'y'){
ref += years(std::stoi(str));
math = true;
}
} else if(answer[0] == '-'){
std::string str(std::next(answer.begin()), std::prev(answer.end()));
if(answer.back() == 'd'){
ref -= days(std::stoi(str));
math = true;
} else if(answer.back() == 'm'){
ref -= months(std::stoi(str));
math = true;
} else if(answer.back() == 'y'){
ref -= years(std::stoi(str));
math = true;
}
}
if(!math) {
ref = from_string(answer);
}
}
checked = check(ref, checkers...);
} catch(const date_exception& e){
std::cout << e.message() << std::endl;
checked = false;
}
} while(!checked);
}
struct not_empty_checker {
bool operator()(const std::string& value){
return !value.empty();
}
std::string message(){
return "This value cannot be empty";
}
};
struct not_negative_checker {
bool operator()(const budget::money& amount){
return !(amount.dollars() < 0 || amount.cents() < 0);
}
std::string message(){
return "The amount cannot be negative";
}
};
struct not_zero_checker {
bool operator()(const budget::money& amount){
return amount.dollars() > 0 || amount.cents() > 0;
}
std::string message(){
return "The amount cannot be negative";
}
};
struct account_checker {
bool operator()(const std::string& value){
return account_exists(value);
}
std::string message(){
return "The account does not exist";
}
};
struct asset_checker {
bool operator()(const std::string& value){
return asset_exists(value);
}
std::string message(){
return "The asset does not exist";
}
};
template<size_t First, size_t Last>
struct range_checker {
bool operator()(const size_t& value){
return value >= First && value <= Last;
}
std::string message(){
std::string m = "Value must in the range [";
m += to_string(First);
m += ", ";
m += to_string(Last);
m += "]";
return m;
}
};
struct one_of_checker {
std::vector<std::string> values;
one_of_checker(std::vector<std::string> values) : values(values){
//Nothing to init
}
bool operator()(const std::string& value){
for(auto& v : values){
if(value == v){
return true;
}
}
return false;
}
std::string message(){
std::string value = "This value can only be one of these values [";
std::string comma = "";
for(auto& v : values){
value += comma;
value += v;
comma = ", ";
}
value += "]";
return value;
}
};
} //end of namespace budget
#endif
<commit_msg>Add support for print_minimum_left<commit_after>//=======================================================================
// Copyright (c) 2013-2017 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef CONSOLE_H
#define CONSOLE_H
#include <vector>
#include <string>
#include <iostream>
#include "money.hpp"
#include "date.hpp"
#include "accounts.hpp"
#include "assets.hpp"
namespace budget {
inline std::string red(const std::string& str){
return "\033[0;31m" + str + "\033[0;3047m";
}
inline std::string green(const std::string& str){
return "\033[0;32m" + str + "\033[0;3047m";
}
inline std::string cyan(const std::string& str){
return "\033[0;33m" + str + "\033[0;3047m";
}
std::string format_money(const budget::money& m);
std::string format_money_no_color(const budget::money& m);
std::string format_money_reverse(const budget::money& m);
/**
* Returns the real size of a string. By default, accented characteres are
* represented by several chars and make the length of the string being bigger
* than its displayable length. This functionr returns only a size of 1 for an
* accented chars.
* \param value The string we want the real length for.
* \return The real length of the string.
*/
size_t rsize(const std::string& value);
size_t rsize_after(const std::string& value);
template<typename T>
void print_minimum(std::ostream& os, const T& value, size_t min_width){
auto str = to_string(value);
auto old_width = os.width();
os.width(min_width + (str.size() - rsize(str)));
os << str;
os.width(old_width);
}
template<typename T>
void print_minimum(const T& value, size_t min_width){
print_minimum(std::cout, value, min_width);
}
template<typename T>
void print_minimum_left(std::ostream& os, const T& value, size_t min_width){
auto str = to_string(value);
if(rsize(str) >= min_width){
os << str;
} else {
os << std::string(min_width - rsize(str), ' ');
os << str;
}
}
template<typename T>
void print_minimum_left(const T& value, size_t min_width){
print_minimum_left(std::cout, value, min_width);
}
/**
* Indicate if the given option was present in the list. If present, the option
* is removed from the list.
* \param option The full option name with any - included
* \param args The command line arguments
* \return true if the option was present, false otherwise.
*/
bool option(const std::string& option, std::vector<std::string>& args);
/**
* Return the value of the given option if present or the default value
* otherwise
* \param option The full option name with any - included
* \param args The command line arguments
* \return The string value of the option or the default value is not present.
*/
std::string option_value(const std::string& option, std::vector<std::string>& args, const std::string& value);
std::string format_code(int attr, int fg, int bg);
std::string format_reset();
std::string format(const std::string& value);
void display_table(std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups = 1, std::vector<size_t> lines = {});
void display_table(std::ostream& os, std::vector<std::string>& columns, std::vector<std::vector<std::string>>& contents, size_t groups = 1, std::vector<size_t> lines = {});
template<typename T>
bool check(const T&){
return true;
}
template<typename T, typename CheckerA, typename ...Checker>
bool check(const T& value, CheckerA first, Checker... checkers){
if(!first(value)){
std::cout << first.message() << std::endl;
return false;
}
return check(value, checkers...);
}
template<typename ...Checker>
void edit_string(std::string& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = answer;
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_number(size_t& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = to_number<size_t>(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_double(double& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = to_number<double>(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_money(budget::money& ref, const std::string& title, Checker... checkers){
bool checked;
do {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
ref = parse_money(answer);
}
checked = check(ref, checkers...);
} while(!checked);
}
template<typename ...Checker>
void edit_date(date& ref, const std::string& title, Checker... checkers){
bool checked;
do {
try {
std::string answer;
std::cout << title << " [" << ref << "]: ";
std::getline(std::cin, answer);
if(!answer.empty()){
bool math = false;
if(answer[0] == '+'){
std::string str(std::next(answer.begin()), std::prev(answer.end()));
if(answer.back() == 'd'){
ref += days(std::stoi(str));
math = true;
} else if(answer.back() == 'm'){
ref += months(std::stoi(str));
math = true;
} else if(answer.back() == 'y'){
ref += years(std::stoi(str));
math = true;
}
} else if(answer[0] == '-'){
std::string str(std::next(answer.begin()), std::prev(answer.end()));
if(answer.back() == 'd'){
ref -= days(std::stoi(str));
math = true;
} else if(answer.back() == 'm'){
ref -= months(std::stoi(str));
math = true;
} else if(answer.back() == 'y'){
ref -= years(std::stoi(str));
math = true;
}
}
if(!math) {
ref = from_string(answer);
}
}
checked = check(ref, checkers...);
} catch(const date_exception& e){
std::cout << e.message() << std::endl;
checked = false;
}
} while(!checked);
}
struct not_empty_checker {
bool operator()(const std::string& value){
return !value.empty();
}
std::string message(){
return "This value cannot be empty";
}
};
struct not_negative_checker {
bool operator()(const budget::money& amount){
return !(amount.dollars() < 0 || amount.cents() < 0);
}
std::string message(){
return "The amount cannot be negative";
}
};
struct not_zero_checker {
bool operator()(const budget::money& amount){
return amount.dollars() > 0 || amount.cents() > 0;
}
std::string message(){
return "The amount cannot be negative";
}
};
struct account_checker {
bool operator()(const std::string& value){
return account_exists(value);
}
std::string message(){
return "The account does not exist";
}
};
struct asset_checker {
bool operator()(const std::string& value){
return asset_exists(value);
}
std::string message(){
return "The asset does not exist";
}
};
template<size_t First, size_t Last>
struct range_checker {
bool operator()(const size_t& value){
return value >= First && value <= Last;
}
std::string message(){
std::string m = "Value must in the range [";
m += to_string(First);
m += ", ";
m += to_string(Last);
m += "]";
return m;
}
};
struct one_of_checker {
std::vector<std::string> values;
one_of_checker(std::vector<std::string> values) : values(values){
//Nothing to init
}
bool operator()(const std::string& value){
for(auto& v : values){
if(value == v){
return true;
}
}
return false;
}
std::string message(){
std::string value = "This value can only be one of these values [";
std::string comma = "";
for(auto& v : values){
value += comma;
value += v;
comma = ", ";
}
value += "]";
return value;
}
};
} //end of namespace budget
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/meta_index.hpp"
#include "vast/expression.hpp"
#include "vast/logger.hpp"
#include "vast/table_index.hpp"
#include "vast/table_slice.hpp"
#include "vast/time.hpp"
#include "vast/detail/overload.hpp"
#include "vast/detail/set_operations.hpp"
#include "vast/detail/string.hpp"
namespace vast {
meta_index::meta_index() : make_synopsis_{make_synopsis} {
}
void meta_index::add(const uuid& partition, const table_slice& slice) {
auto& part_synopsis = partition_synopses_[partition];
auto& layout = slice.layout();
if (blacklisted_layouts_.count(layout) == 1)
return;
auto i = part_synopsis.find(layout);
table_synopsis* table_syn;
if (i != part_synopsis.end()) {
table_syn = &i->second;
} else {
// Create new synopses for a layout we haven't seen before.
i = part_synopsis.emplace(layout, table_synopsis{}).first;
table_syn = &i->second;
for (auto& field : layout.fields)
if (i->second.emplace_back(make_synopsis_(field.type)))
VAST_DEBUG(this, "created new synopsis structure for type", field.type);
// If we couldn't create a single synopsis for the layout, we will no
// longer attempt to create synopses in the future.
auto is_nullptr = [](auto& x) { return x == nullptr; };
if (std::all_of(table_syn->begin(), table_syn->end(), is_nullptr)) {
VAST_DEBUG(this, "could not create a synopsis for layout:", layout);
blacklisted_layouts_.insert(layout);
}
}
VAST_ASSERT(table_syn->size() == slice.columns());
for (size_t col = 0; col < slice.columns(); ++col) {
if (auto& syn = (*table_syn)[col])
for (size_t row = 0; row < slice.rows(); ++row)
syn->add(*slice.at(row, col));
}
}
std::vector<uuid> meta_index::lookup(const expression& expr) const {
VAST_ASSERT(!caf::holds_alternative<caf::none_t>(expr));
using result_type = std::vector<uuid>;
auto all_partitions = [&] {
result_type result;
result.reserve(partition_synopses_.size());
std::transform(partition_synopses_.begin(),
partition_synopses_.end(),
std::back_inserter(result),
[](auto& x) { return x.first; });
std::sort(result.begin(), result.end());
return result;
};
return caf::visit(detail::overload(
[&](const conjunction& x) -> result_type {
VAST_ASSERT(!x.empty());
auto i = x.begin();
auto result = lookup(*i);
if (!result.empty())
for (++i; i != x.end(); ++i) {
auto xs = lookup(*i);
if (xs.empty())
return xs; // short-circuit
detail::inplace_intersect(result, xs);
}
return result;
},
[&](const disjunction& x) -> result_type {
result_type result;
for (auto& op : x) {
auto xs = lookup(op);
if (xs.size() == partition_synopses_.size())
return xs; // short-circuit
detail::inplace_unify(result, xs);
}
return result;
},
[&](const negation&) -> result_type {
// We cannot handle negations, because a synopsis may return false
// positives, and negating such a result may cause false negatives.
return all_partitions();
},
[&](const predicate& x) -> result_type {
// Performs a lookup on all *matching* synopses with operator and data
// from the predicate of the expression. A match is determined according
// to a given function that uses the record field to determine whether
// the synopsis should be queried.
auto search = [&](auto match) {
VAST_ASSERT(caf::holds_alternative<data>(x.rhs));
auto& rhs = caf::get<data>(x.rhs);
result_type result;
for (auto& [part_id, part_syn] : partition_synopses_)
for (auto& [layout, table_syn] : part_syn)
for (size_t i = 0; i < table_syn.size(); ++i)
if (table_syn[i] && match(layout.fields[i]))
if (table_syn[i]->lookup(x.op, make_view(rhs)))
if (result.empty() || result.back() != part_id)
result.push_back(part_id);
std::sort(result.begin(), result.end());
return result;
};
return caf::visit(detail::overload(
[&](const attribute_extractor& lhs, const data&) -> result_type {
if (lhs.attr == "time") {
auto pred = [](auto& field) {
// FIXME: we should really just look at the ×tamp attribute
// and not all fields of type time. [ch3843]
return caf::holds_alternative<timestamp_type>(field.type);
};
return search(pred);
}
VAST_WARNING(this, "cannot process attribute extractor:", lhs.attr);
return all_partitions();
},
[&](const key_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) {
return detail::ends_with(field.name, lhs.key);
};
return search(pred);
},
[&](const type_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) { return field.type == lhs.type; };
return search(pred);
},
[&](const auto&, const auto&) -> result_type {
VAST_WARNING(this, "cannot process predicate:", x);
return all_partitions();
}
), x.lhs, x.rhs);
},
[&](caf::none_t) -> result_type {
VAST_ERROR(this, "received an empty expression");
VAST_ASSERT(!"invalid expression");
return all_partitions();
}
), expr);
}
void meta_index::factory(synopsis_factory f) {
make_synopsis_ = f;
blacklisted_layouts_.clear();
}
bool set_synopsis_factory(meta_index& x, caf::actor_system& sys) {
if (auto f = find_synopsis_factory(sys)) {
x.factory(f);
return true;
}
return false;
}
} // namespace vast
<commit_msg>Do not return no results when no synopsis matches<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include "vast/meta_index.hpp"
#include "vast/expression.hpp"
#include "vast/logger.hpp"
#include "vast/table_index.hpp"
#include "vast/table_slice.hpp"
#include "vast/time.hpp"
#include "vast/detail/overload.hpp"
#include "vast/detail/set_operations.hpp"
#include "vast/detail/string.hpp"
namespace vast {
meta_index::meta_index() : make_synopsis_{make_synopsis} {
}
void meta_index::add(const uuid& partition, const table_slice& slice) {
auto& part_synopsis = partition_synopses_[partition];
auto& layout = slice.layout();
if (blacklisted_layouts_.count(layout) == 1)
return;
auto i = part_synopsis.find(layout);
table_synopsis* table_syn;
if (i != part_synopsis.end()) {
table_syn = &i->second;
} else {
// Create new synopses for a layout we haven't seen before.
i = part_synopsis.emplace(layout, table_synopsis{}).first;
table_syn = &i->second;
for (auto& field : layout.fields)
if (i->second.emplace_back(make_synopsis_(field.type)))
VAST_DEBUG(this, "created new synopsis structure for type", field.type);
// If we couldn't create a single synopsis for the layout, we will no
// longer attempt to create synopses in the future.
auto is_nullptr = [](auto& x) { return x == nullptr; };
if (std::all_of(table_syn->begin(), table_syn->end(), is_nullptr)) {
VAST_DEBUG(this, "could not create a synopsis for layout:", layout);
blacklisted_layouts_.insert(layout);
}
}
VAST_ASSERT(table_syn->size() == slice.columns());
for (size_t col = 0; col < slice.columns(); ++col) {
if (auto& syn = (*table_syn)[col])
for (size_t row = 0; row < slice.rows(); ++row)
syn->add(*slice.at(row, col));
}
}
std::vector<uuid> meta_index::lookup(const expression& expr) const {
VAST_ASSERT(!caf::holds_alternative<caf::none_t>(expr));
using result_type = std::vector<uuid>;
auto all_partitions = [&] {
result_type result;
result.reserve(partition_synopses_.size());
std::transform(partition_synopses_.begin(),
partition_synopses_.end(),
std::back_inserter(result),
[](auto& x) { return x.first; });
std::sort(result.begin(), result.end());
return result;
};
return caf::visit(detail::overload(
[&](const conjunction& x) -> result_type {
VAST_ASSERT(!x.empty());
auto i = x.begin();
auto result = lookup(*i);
if (!result.empty())
for (++i; i != x.end(); ++i) {
auto xs = lookup(*i);
if (xs.empty())
return xs; // short-circuit
detail::inplace_intersect(result, xs);
}
return result;
},
[&](const disjunction& x) -> result_type {
result_type result;
for (auto& op : x) {
auto xs = lookup(op);
if (xs.size() == partition_synopses_.size())
return xs; // short-circuit
detail::inplace_unify(result, xs);
}
return result;
},
[&](const negation&) -> result_type {
// We cannot handle negations, because a synopsis may return false
// positives, and negating such a result may cause false negatives.
return all_partitions();
},
[&](const predicate& x) -> result_type {
// Performs a lookup on all *matching* synopses with operator and data
// from the predicate of the expression. The match function uses a record
// field to determine whether the synopsis should be queried.
auto search = [&](auto match) {
VAST_ASSERT(caf::holds_alternative<data>(x.rhs));
auto& rhs = caf::get<data>(x.rhs);
result_type result;
auto found_matching_synopsis = false;
for (auto& [part_id, part_syn] : partition_synopses_)
for (auto& [layout, table_syn] : part_syn)
for (size_t i = 0; i < table_syn.size(); ++i)
if (table_syn[i] && match(layout.fields[i])) {
found_matching_synopsis = true;
if (table_syn[i]->lookup(x.op, make_view(rhs)))
if (result.empty() || result.back() != part_id)
result.push_back(part_id);
}
std::sort(result.begin(), result.end());
return found_matching_synopsis ? result : all_partitions();
};
return caf::visit(detail::overload(
[&](const attribute_extractor& lhs, const data&) -> result_type {
if (lhs.attr == "time") {
auto pred = [](auto& field) {
// FIXME: we should really just look at the ×tamp attribute
// and not all fields of type time. [ch3843]
return caf::holds_alternative<timestamp_type>(field.type);
};
return search(pred);
}
VAST_WARNING(this, "cannot process attribute extractor:", lhs.attr);
return all_partitions();
},
[&](const key_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) {
return detail::ends_with(field.name, lhs.key);
};
return search(pred);
},
[&](const type_extractor& lhs, const data&) -> result_type {
auto pred = [&](auto& field) { return field.type == lhs.type; };
return search(pred);
},
[&](const auto&, const auto&) -> result_type {
VAST_WARNING(this, "cannot process predicate:", x);
return all_partitions();
}
), x.lhs, x.rhs);
},
[&](caf::none_t) -> result_type {
VAST_ERROR(this, "received an empty expression");
VAST_ASSERT(!"invalid expression");
return all_partitions();
}
), expr);
}
void meta_index::factory(synopsis_factory f) {
make_synopsis_ = f;
blacklisted_layouts_.clear();
}
bool set_synopsis_factory(meta_index& x, caf::actor_system& sys) {
if (auto f = find_synopsis_factory(sys)) {
x.factory(f);
return true;
}
return false;
}
} // namespace vast
<|endoftext|>
|
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Bertrand Martel
*
* 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.
*/
/**
main.cpp
Main test programm
@author Bertrand Martel
@version 1.0
*/
#include <QCoreApplication>
#include <protocol/websocket/websocketserver.h>
#include <iostream>
#include <QStringList>
#include <QDebug>
#include "string"
#include <sys/param.h>
#include "ClientSockethandler.h"
#include "SslHandler.h"
#define PUBLIC_CERT "/home/abathur/Bureau/open_source/websocketcpp/libwebsocket-test/certs/server/server.crt"
#define PRIVATE_CERT "/home/abathur/Bureau/open_source/websocketcpp/libwebsocket-test/certs/server/server.key"
#define CA_CERTS "/home/abathur/Bureau/open_source/websocketcpp/libwebsocket-test/certs/ca.crt"
#define PRIVATE_CERT_PASS "12345"
using namespace std;
static int port = 8443;
static string ip="127.0.0.1";
static bool useSSL = true;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//ignore SIGPIPE signal (broken pipe issue)
signal(SIGPIPE, SIG_IGN);
QStringList args = a.arguments();
string ip ="127.0.0.1";
if (args.size() >2)
{
ip=args[1].toStdString();
bool ok = false;
int dec = args[2].toInt(&ok, 10);
if (ok)
port = dec;
}
ClientSocketHandler *clientHandler = new ClientSocketHandler();
//instance of websocket server
WebsocketServer server;
if (useSSL)
{
//set secured websocket server
server.setSSL(true);
cout << "setting server certs ..." << endl;
//set public / private and certification authority list into websocket server object
server.setPublicCert(SslHandler::retrieveCertFromFile(PUBLIC_CERT));
server.setPrivateCert(SslHandler::retrieveKeyCertFile(PRIVATE_CERT,PRIVATE_CERT_PASS));
server.setCaCert(SslHandler::retrieveveCaCertListFromFile(CA_CERTS));
}
server.addClientEventListener(clientHandler);
if (!server.listen(QHostAddress(ip.data()),port)) {
qDebug() << "An error occured while initializing hope proxy server... Maybe another instance is already running on "<< ip.data() << ":" << port << endl;
return -1;
}
cout << "Starting Websocket server on port " << port << endl;
return a.exec();
}
<commit_msg>remove static cert path<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Bertrand Martel
*
* 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.
*/
/**
main.cpp
Main test programm
@author Bertrand Martel
@version 1.0
*/
#include <QCoreApplication>
#include <protocol/websocket/websocketserver.h>
#include <iostream>
#include <QStringList>
#include <QDebug>
#include "string"
#include <sys/param.h>
#include "ClientSockethandler.h"
#include "SslHandler.h"
#define PUBLIC_CERT "~/websocket-non-blocking/libwebsocket-test/certs/server/server.crt"
#define PRIVATE_CERT "~/websocket-non-blocking/libwebsocket-test/certs/server/server.key"
#define CA_CERTS "~/websocket-non-blocking/libwebsocket-test/certs/ca.crt"
#define PRIVATE_CERT_PASS "12345"
using namespace std;
static int port = 8443;
static string ip="127.0.0.1";
static bool useSSL = false;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//ignore SIGPIPE signal (broken pipe issue)
signal(SIGPIPE, SIG_IGN);
QStringList args = a.arguments();
string ip ="127.0.0.1";
if (args.size() >2)
{
ip=args[1].toStdString();
bool ok = false;
int dec = args[2].toInt(&ok, 10);
if (ok)
port = dec;
}
ClientSocketHandler *clientHandler = new ClientSocketHandler();
//instance of websocket server
WebsocketServer server;
if (useSSL)
{
//set secured websocket server
server.setSSL(true);
cout << "setting server certs ..." << endl;
//set public / private and certification authority list into websocket server object
server.setPublicCert(SslHandler::retrieveCertFromFile(PUBLIC_CERT));
server.setPrivateCert(SslHandler::retrieveKeyCertFile(PRIVATE_CERT,PRIVATE_CERT_PASS));
server.setCaCert(SslHandler::retrieveveCaCertListFromFile(CA_CERTS));
}
server.addClientEventListener(clientHandler);
if (!server.listen(QHostAddress(ip.data()),port)) {
qDebug() << "An error occured while initializing hope proxy server... Maybe another instance is already running on "<< ip.data() << ":" << port << endl;
return -1;
}
cout << "Starting Websocket server on port " << port << endl;
return a.exec();
}
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "statuswebserver.h"
#include <vespa/storageframework/storageframework.h>
#include <vespa/storageapi/message/persistence.h>
#include <vespa/fastlib/net/url.h>
#include <vespa/vespalib/util/host_name.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/component/vtag.h>
#include <vespa/vespalib/net/crypto_engine.h>
#include <functional>
#include <vespa/log/log.h>
LOG_SETUP(".status");
namespace storage {
StatusWebServer::StatusWebServer(
framework::ComponentRegister& componentRegister,
framework::StatusReporterMap& reporterMap,
const config::ConfigUri & configUri)
: _reporterMap(reporterMap),
_workerMonitor(),
_port(0),
_httpServer(),
_configFetcher(configUri.getContext()),
_component(std::make_unique<framework::Component>(componentRegister, "Status"))
{
_configFetcher.subscribe<vespa::config::content::core::StorStatusConfig>(configUri.getConfigId(), this);
_configFetcher.start();
}
StatusWebServer::~StatusWebServer()
{
// Avoid getting config during shutdown
_configFetcher.close();
if (_httpServer.get() != 0) {
LOG(debug, "Shutting down status web server on port %u", _httpServer->getListenPort());
}
// Delete http server to ensure that no more incoming requests reach us.
_httpServer.reset(0);
}
void StatusWebServer::configure(std::unique_ptr<vespa::config::content::core::StorStatusConfig> config)
{
int newPort = config->httpport;
// If server is already running, ignore config updates that doesn't
// alter port, or suggests random port.
if (_httpServer) {
if (newPort == 0 || newPort == _port) return;
}
// Try to create new server before destroying old.
LOG(info, "Starting status web server on port %u.", newPort);
std::unique_ptr<WebServer> server;
// Negative port number means don't run the web server
if (newPort >= 0) {
server.reset(new WebServer(*this, newPort));
// Now that we know config update went well, update internal state
_port = server->getListenPort();
LOG(config, "Status pages now available on port %u", _port);
if (_httpServer) {
LOG(debug, "Shutting down old status server.");
_httpServer.reset();
LOG(debug, "Done shutting down old status server.");
}
} else if (_httpServer) {
LOG(info, "No longer running status server as negative port was given "
"in config, indicating not to run a server.");
}
_httpServer = std::move(server);
}
StatusWebServer::WebServer::WebServer(StatusWebServer& status, uint16_t port)
: _status(status),
_server(vespalib::Portal::create(vespalib::CryptoEngine::get_default(), port)),
_executor(1, 256 * 1024),
_root(_server->bind("/", *this))
{
}
StatusWebServer::WebServer::~WebServer()
{
_root.reset();
_executor.shutdown().sync();
}
namespace {
struct HandleGetTask : vespalib::Executor::Task {
vespalib::Portal::GetRequest request;
std::function<void(vespalib::Portal::GetRequest)> fun;
HandleGetTask(vespalib::Portal::GetRequest request_in,
std::function<void(vespalib::Portal::GetRequest)> fun_in)
: request(std::move(request_in)), fun(fun_in) {}
void run() override { fun(std::move(request)); }
};
}
void
StatusWebServer::WebServer::get(vespalib::Portal::GetRequest request)
{
auto fun = [this](vespalib::Portal::GetRequest req)
{
handle_get(std::move(req));
};
_executor.execute(std::make_unique<HandleGetTask>(std::move(request), std::move(fun)));
}
void
StatusWebServer::WebServer::handle_get(vespalib::Portal::GetRequest request)
{
const vespalib::string &tmpurl = request.get_uri();
Fast_URL urlCodec;
int bufLength = tmpurl.length() * 2 + 10;
char * encodedUrl = new char[bufLength];
strcpy(encodedUrl, tmpurl.c_str());
char decodedUrl[bufLength];
urlCodec.DecodeQueryString(encodedUrl);
urlCodec.decode(encodedUrl, decodedUrl, bufLength);
delete [] encodedUrl;
vespalib::string url = decodedUrl;
LOG(debug, "Status got get request '%s'", url.c_str());
framework::HttpUrlPath urlpath(url.c_str(), request.get_host());
_status.handlePage(urlpath, std::move(request));
}
namespace {
class IndexPageReporter : public framework::HtmlStatusReporter {
std::ostringstream ost;
void reportHtmlStatus(std::ostream& out,const framework::HttpUrlPath&) const override {
out << ost.str();
}
public:
IndexPageReporter() : framework::HtmlStatusReporter("", "Index page") {}
template<typename T>
IndexPageReporter& operator<<(const T& t) { ost << t; return *this; }
};
}
int
StatusWebServer::getListenPort() const
{
return _httpServer ? _httpServer->getListenPort() : -1;
}
void
StatusWebServer::handlePage(const framework::HttpUrlPath& urlpath, vespalib::Portal::GetRequest request)
{
vespalib::string link(urlpath.getPath());
if (link.size() > 0 && link[0] == '/') link = link.substr(1);
size_t slashPos = link.find('/');
if (slashPos != std::string::npos) link = link.substr(0, slashPos);
if ( ! link.empty()) {
const framework::StatusReporter *reporter = _reporterMap.getStatusReporter(link);
if (reporter != nullptr) {
try {
std::ostringstream content;
auto content_type = reporter->getReportContentType(urlpath);
if (reporter->reportStatus(content, urlpath)) {
request.respond_with_content(content_type, content.str());
} else {
request.respond_with_error(404, "Not Found");
}
} catch (std::exception &e) {
request.respond_with_error(500, "Internal Server Error");
}
} else {
request.respond_with_error(404, "Not Found");
}
} else {
IndexPageReporter indexRep;
indexRep << "<p><b>Binary version of Vespa:</b> "
<< vespalib::Vtag::currentVersion.toString()
<< "</p>\n";
{
for (const framework::StatusReporter * reporter : _reporterMap.getStatusReporters()) {
indexRep << "<a href=\"" << reporter->getId() << "\">"
<< reporter->getName() << "</a><br>\n";
}
}
std::ostringstream content;
auto content_type = indexRep.getReportContentType(urlpath);
indexRep.reportStatus(content, urlpath);
request.respond_with_content(content_type, content.str());
}
LOG(spam, "Status finished request");
}
} // storage
<commit_msg>move-construct function member<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "statuswebserver.h"
#include <vespa/storageframework/storageframework.h>
#include <vespa/storageapi/message/persistence.h>
#include <vespa/fastlib/net/url.h>
#include <vespa/vespalib/util/host_name.h>
#include <vespa/vespalib/util/exceptions.h>
#include <vespa/vespalib/component/vtag.h>
#include <vespa/vespalib/net/crypto_engine.h>
#include <functional>
#include <vespa/log/log.h>
LOG_SETUP(".status");
namespace storage {
StatusWebServer::StatusWebServer(
framework::ComponentRegister& componentRegister,
framework::StatusReporterMap& reporterMap,
const config::ConfigUri & configUri)
: _reporterMap(reporterMap),
_workerMonitor(),
_port(0),
_httpServer(),
_configFetcher(configUri.getContext()),
_component(std::make_unique<framework::Component>(componentRegister, "Status"))
{
_configFetcher.subscribe<vespa::config::content::core::StorStatusConfig>(configUri.getConfigId(), this);
_configFetcher.start();
}
StatusWebServer::~StatusWebServer()
{
// Avoid getting config during shutdown
_configFetcher.close();
if (_httpServer.get() != 0) {
LOG(debug, "Shutting down status web server on port %u", _httpServer->getListenPort());
}
// Delete http server to ensure that no more incoming requests reach us.
_httpServer.reset(0);
}
void StatusWebServer::configure(std::unique_ptr<vespa::config::content::core::StorStatusConfig> config)
{
int newPort = config->httpport;
// If server is already running, ignore config updates that doesn't
// alter port, or suggests random port.
if (_httpServer) {
if (newPort == 0 || newPort == _port) return;
}
// Try to create new server before destroying old.
LOG(info, "Starting status web server on port %u.", newPort);
std::unique_ptr<WebServer> server;
// Negative port number means don't run the web server
if (newPort >= 0) {
server.reset(new WebServer(*this, newPort));
// Now that we know config update went well, update internal state
_port = server->getListenPort();
LOG(config, "Status pages now available on port %u", _port);
if (_httpServer) {
LOG(debug, "Shutting down old status server.");
_httpServer.reset();
LOG(debug, "Done shutting down old status server.");
}
} else if (_httpServer) {
LOG(info, "No longer running status server as negative port was given "
"in config, indicating not to run a server.");
}
_httpServer = std::move(server);
}
StatusWebServer::WebServer::WebServer(StatusWebServer& status, uint16_t port)
: _status(status),
_server(vespalib::Portal::create(vespalib::CryptoEngine::get_default(), port)),
_executor(1, 256 * 1024),
_root(_server->bind("/", *this))
{
}
StatusWebServer::WebServer::~WebServer()
{
_root.reset();
_executor.shutdown().sync();
}
namespace {
struct HandleGetTask : vespalib::Executor::Task {
vespalib::Portal::GetRequest request;
std::function<void(vespalib::Portal::GetRequest)> fun;
HandleGetTask(vespalib::Portal::GetRequest request_in,
std::function<void(vespalib::Portal::GetRequest)> fun_in)
: request(std::move(request_in)), fun(std::move(fun_in)) {}
void run() override { fun(std::move(request)); }
};
}
void
StatusWebServer::WebServer::get(vespalib::Portal::GetRequest request)
{
auto fun = [this](vespalib::Portal::GetRequest req)
{
handle_get(std::move(req));
};
_executor.execute(std::make_unique<HandleGetTask>(std::move(request), std::move(fun)));
}
void
StatusWebServer::WebServer::handle_get(vespalib::Portal::GetRequest request)
{
const vespalib::string &tmpurl = request.get_uri();
Fast_URL urlCodec;
int bufLength = tmpurl.length() * 2 + 10;
char * encodedUrl = new char[bufLength];
strcpy(encodedUrl, tmpurl.c_str());
char decodedUrl[bufLength];
urlCodec.DecodeQueryString(encodedUrl);
urlCodec.decode(encodedUrl, decodedUrl, bufLength);
delete [] encodedUrl;
vespalib::string url = decodedUrl;
LOG(debug, "Status got get request '%s'", url.c_str());
framework::HttpUrlPath urlpath(url.c_str(), request.get_host());
_status.handlePage(urlpath, std::move(request));
}
namespace {
class IndexPageReporter : public framework::HtmlStatusReporter {
std::ostringstream ost;
void reportHtmlStatus(std::ostream& out,const framework::HttpUrlPath&) const override {
out << ost.str();
}
public:
IndexPageReporter() : framework::HtmlStatusReporter("", "Index page") {}
template<typename T>
IndexPageReporter& operator<<(const T& t) { ost << t; return *this; }
};
}
int
StatusWebServer::getListenPort() const
{
return _httpServer ? _httpServer->getListenPort() : -1;
}
void
StatusWebServer::handlePage(const framework::HttpUrlPath& urlpath, vespalib::Portal::GetRequest request)
{
vespalib::string link(urlpath.getPath());
if (link.size() > 0 && link[0] == '/') link = link.substr(1);
size_t slashPos = link.find('/');
if (slashPos != std::string::npos) link = link.substr(0, slashPos);
if ( ! link.empty()) {
const framework::StatusReporter *reporter = _reporterMap.getStatusReporter(link);
if (reporter != nullptr) {
try {
std::ostringstream content;
auto content_type = reporter->getReportContentType(urlpath);
if (reporter->reportStatus(content, urlpath)) {
request.respond_with_content(content_type, content.str());
} else {
request.respond_with_error(404, "Not Found");
}
} catch (std::exception &e) {
request.respond_with_error(500, "Internal Server Error");
}
} else {
request.respond_with_error(404, "Not Found");
}
} else {
IndexPageReporter indexRep;
indexRep << "<p><b>Binary version of Vespa:</b> "
<< vespalib::Vtag::currentVersion.toString()
<< "</p>\n";
{
for (const framework::StatusReporter * reporter : _reporterMap.getStatusReporters()) {
indexRep << "<a href=\"" << reporter->getId() << "\">"
<< reporter->getName() << "</a><br>\n";
}
}
std::ostringstream content;
auto content_type = indexRep.getReportContentType(urlpath);
indexRep.reportStatus(content, urlpath);
request.respond_with_content(content_type, content.str());
}
LOG(spam, "Status finished request");
}
} // storage
<|endoftext|>
|
<commit_before>//============================================================================
// MCKL/include/mckl/random/threefry_generic.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// 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.
//============================================================================
template <typename T, std::size_t K, std::size_t N, typename,
bool = (N % 4 == 0)>
class ThreefryKBox
{
public:
static void eval(std::array<T, K> &, const std::array<T, K + 1> &) {}
}; // class ThreefryKBox
template <typename T, std::size_t K, std::size_t N, typename Constants>
class ThreefryKBox<T, K, N, Constants, true>
{
public:
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par)
{
eval<0>(state, par, std::integral_constant<bool, 0 < K>());
state.back() += s_;
}
private:
static constexpr T s_ = N / 4;
template <std::size_t>
static void eval(
std::array<T, K> &, const std::array<T, K + 1> &, std::false_type)
{
}
template <std::size_t I>
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par,
std::true_type)
{
std::get<I>(state) += std::get<(s_ + I) % (K + 1)>(par);
eval<I + 1>(state, par, std::integral_constant<bool, I + 1 < K>());
}
}; // class ThreefryKBox
template <typename T, std::size_t K, std::size_t N, typename, bool = (N > 0)>
class ThreefrySBox
{
public:
static void eval(std::array<T, K> &) {}
}; // class ThreefrySBox
template <typename T, std::size_t K, std::size_t N, typename Constants>
class ThreefrySBox<T, K, N, Constants, true>
{
public:
static void eval(std::array<T, K> &state)
{
eval<0>(state, std::integral_constant<bool, 1 < K>());
}
private:
template <std::size_t>
static void eval(std::array<T, K> &, std::false_type)
{
}
template <std::size_t I>
static void eval(std::array<T, K> &state, std::true_type)
{
static constexpr int L = Constants::rotate[I / 2][(N - 1) % 8];
static constexpr int R = std::numeric_limits<T>::digits - L;
T x = std::get<I + 1>(state);
std::get<I>(state) += x;
x = (x << L) | (x >> R);
x ^= std::get<I>(state);
std::get<I + 1>(state) = x;
eval<I + 2>(state, std::integral_constant<bool, I + 3 < K>());
}
}; // class ThreefrySBox
template <typename T, std::size_t K, std::size_t N, typename, bool = (N > 0)>
class ThreefryPBox
{
public:
static void eval(std::array<T, K> &) {}
}; // class ThreefryPBox
template <typename T, std::size_t K, std::size_t N, typename Constants>
class ThreefryPBox<T, K, N, Constants, true>
{
public:
static void eval(std::array<T, K> &state)
{
std::array<T, K> tmp;
eval<0>(state, tmp, std::integral_constant<bool, 0 < N>());
state = tmp;
}
private:
template <std::size_t>
static void eval(
const std::array<T, K> &, std::array<T, K> &, std::false_type)
{
}
template <std::size_t I>
static void eval(
const std::array<T, K> &state, std::array<T, K> &tmp, std::true_type)
{
static constexpr std::size_t P = Constants::permute[I];
std::get<I>(tmp) = std::get<P>(state);
eval<I + 1>(state, tmp, std::integral_constant<bool, I + 1 < K>());
}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 2, N, ThreefryConstants<T, 2>, true>
{
public:
static void eval(std::array<T, 2> &) {}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 4, N, ThreefryConstants<T, 4>, true>
{
public:
static void eval(std::array<T, 4> &state)
{
std::swap(std::get<1>(state), std::get<3>(state));
}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 8, N, ThreefryConstants<T, 8>, true>
{
public:
static void eval(std::array<T, 8> &state)
{
T x0 = std::get<0>(state);
T x3 = std::get<3>(state);
std::get<0>(state) = std::get<2>(state);
std::get<2>(state) = std::get<4>(state);
std::get<3>(state) = std::get<7>(state);
std::get<4>(state) = std::get<6>(state);
std::get<6>(state) = x0;
std::get<7>(state) = x3;
}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 16, N, ThreefryConstants<T, 16>, true>
{
public:
static void eval(std::array<T, 16> &state)
{
T x1 = std::get<1>(state);
T x3 = std::get<3>(state);
T x4 = std::get<4>(state);
T x5 = std::get<5>(state);
T x7 = std::get<7>(state);
T x8 = std::get<8>(state);
std::get<1>(state) = std::get<9>(state);
std::get<3>(state) = std::get<13>(state);
std::get<4>(state) = std::get<6>(state);
std::get<5>(state) = std::get<11>(state);
std::get<6>(state) = x4;
std::get<7>(state) = std::get<15>(state);
std::get<8>(state) = std::get<10>(state);
std::get<9>(state) = x7;
std::get<10>(state) = std::get<12>(state);
std::get<11>(state) = x3;
std::get<12>(state) = std::get<14>(state);
std::get<13>(state) = x5;
std::get<14>(state) = x8;
std::get<15>(state) = x1;
}
}; // class ThreefryPBox
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
class ThreefryGeneratorGenericImpl
{
public:
static constexpr std::size_t blocks() { return 8; }
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par)
{
eval<0>(state, par, std::integral_constant<bool, 0 <= Rounds>());
}
static void eval(std::array<std::array<T, K>, blocks()> &state,
const std::array<T, K + 1> &par)
{
eval<0>(state, par, std::integral_constant<bool, 0 <= Rounds>());
}
private:
template <std::size_t>
static void eval(
std::array<T, K> &, const std::array<T, K + 1> &, std::false_type)
{
}
template <std::size_t N>
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par,
std::true_type)
{
ThreefrySBox<T, K, N, Constants>::eval(state);
ThreefryPBox<T, K, N, Constants>::eval(state);
ThreefryKBox<T, K, N, Constants>::eval(state, par);
eval<N + 1>(
state, par, std::integral_constant<bool, N + 1 <= Rounds>());
}
template <std::size_t>
static void eval(std::array<std::array<T, K>, blocks()> &,
const std::array<T, K + 1> &, std::false_type)
{
}
template <std::size_t N>
static void eval(std::array<std::array<T, K>, blocks()> &state,
const std::array<T, K + 1> &par, std::true_type)
{
sbox<N, 0>(state, std::integral_constant<bool, 0 < blocks()>());
pbox<N, 0>(state, std::integral_constant<bool, 0 < blocks()>());
kbox<N, 0>(state, par, std::integral_constant<bool, 0 < blocks()>());
eval<N + 1>(
state, par, std::integral_constant<bool, N + 1 <= Rounds>());
}
template <std::size_t, std::size_t>
static void kbox(std::array<std::array<T, K>, blocks()> &,
const std::array<T, K + 1> &, std::false_type)
{
}
template <std::size_t N, std::size_t I>
static void kbox(std::array<std::array<T, K>, blocks()> &state,
const std::array<T, K + 1> &par, std::true_type)
{
ThreefryKBox<T, K, N, Constants>::eval(std::get<I>(state), par);
kbox<N, I + 1>(
state, par, std::integral_constant<bool, I + 1 < blocks()>());
}
template <std::size_t, std::size_t>
static void sbox(std::array<std::array<T, K>, blocks()> &, std::false_type)
{
}
template <std::size_t N, std::size_t I>
static void sbox(
std::array<std::array<T, K>, blocks()> &state, std::true_type)
{
ThreefrySBox<T, K, N, Constants>::eval(std::get<I>(state));
sbox<N, I + 1>(
state, std::integral_constant<bool, I + 1 < blocks()>());
}
template <std::size_t, std::size_t>
static void pbox(std::array<std::array<T, K>, blocks()> &, std::false_type)
{
}
template <std::size_t N, std::size_t I>
static void pbox(
std::array<std::array<T, K>, blocks()> &state, std::true_type)
{
ThreefryPBox<T, K, N, Constants>::eval(std::get<I>(state));
pbox<N, I + 1>(
state, std::integral_constant<bool, I + 1 < blocks()>());
}
}; // class ThreefryGeneratorGenericImpl
<commit_msg>improve threefry generic performance<commit_after>//============================================================================
// MCKL/include/mckl/random/threefry_generic.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2016, Yan Zhou
// 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.
//============================================================================
template <typename T, std::size_t K, std::size_t N, typename Constants>
class ThreefryKBox
{
public:
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par)
{
eval<0>(state, par, std::integral_constant<bool, 0 < K>());
state.back() += s_;
}
private:
static constexpr T s_ = N / 4;
template <std::size_t>
static void eval(
std::array<T, K> &, const std::array<T, K + 1> &, std::false_type)
{
}
template <std::size_t I>
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par,
std::true_type)
{
std::get<I>(state) += std::get<(s_ + I) % (K + 1)>(par);
eval<I + 1>(state, par, std::integral_constant<bool, I + 1 < K>());
}
}; // class ThreefryKBox
template <typename T, std::size_t K, std::size_t N, typename Constants>
class ThreefrySBox
{
public:
static void eval(std::array<T, K> &state)
{
eval<0>(state, std::integral_constant<bool, 1 < K>());
}
private:
template <std::size_t>
static void eval(std::array<T, K> &, std::false_type)
{
}
template <std::size_t I>
static void eval(std::array<T, K> &state, std::true_type)
{
static constexpr int L = Constants::rotate[I / 2][(N - 1) % 8];
static constexpr int R = std::numeric_limits<T>::digits - L;
T x = std::get<I + 1>(state);
std::get<I>(state) += x;
x = (x << L) | (x >> R);
x ^= std::get<I>(state);
std::get<I + 1>(state) = x;
eval<I + 2>(state, std::integral_constant<bool, I + 3 < K>());
}
}; // class ThreefrySBox
template <typename T, std::size_t K, std::size_t N, typename Constants>
class ThreefryPBox
{
public:
static void eval(std::array<T, K> &state)
{
std::array<T, K> tmp;
eval<0>(state, tmp, std::integral_constant<bool, 0 < N>());
state = tmp;
}
private:
template <std::size_t>
static void eval(
const std::array<T, K> &, std::array<T, K> &, std::false_type)
{
}
template <std::size_t I>
static void eval(
const std::array<T, K> &state, std::array<T, K> &tmp, std::true_type)
{
static constexpr std::size_t P = Constants::permute[I];
std::get<I>(tmp) = std::get<P>(state);
eval<I + 1>(state, tmp, std::integral_constant<bool, I + 1 < K>());
}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 2, N, ThreefryConstants<T, 2>>
{
public:
static void eval(std::array<T, 2> &) {}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 4, N, ThreefryConstants<T, 4>>
{
public:
static void eval(std::array<T, 4> &state)
{
std::swap(std::get<1>(state), std::get<3>(state));
}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 8, N, ThreefryConstants<T, 8>>
{
public:
static void eval(std::array<T, 8> &state)
{
T x0 = std::get<0>(state);
T x3 = std::get<3>(state);
std::get<0>(state) = std::get<2>(state);
std::get<2>(state) = std::get<4>(state);
std::get<3>(state) = std::get<7>(state);
std::get<4>(state) = std::get<6>(state);
std::get<6>(state) = x0;
std::get<7>(state) = x3;
}
}; // class ThreefryPBox
template <typename T, std::size_t N>
class ThreefryPBox<T, 16, N, ThreefryConstants<T, 16>>
{
public:
static void eval(std::array<T, 16> &state)
{
T x1 = std::get<1>(state);
T x3 = std::get<3>(state);
T x4 = std::get<4>(state);
T x5 = std::get<5>(state);
T x7 = std::get<7>(state);
T x8 = std::get<8>(state);
std::get<1>(state) = std::get<9>(state);
std::get<3>(state) = std::get<13>(state);
std::get<4>(state) = std::get<6>(state);
std::get<5>(state) = std::get<11>(state);
std::get<6>(state) = x4;
std::get<7>(state) = std::get<15>(state);
std::get<8>(state) = std::get<10>(state);
std::get<9>(state) = x7;
std::get<10>(state) = std::get<12>(state);
std::get<11>(state) = x3;
std::get<12>(state) = std::get<14>(state);
std::get<13>(state) = x5;
std::get<14>(state) = x8;
std::get<15>(state) = x1;
}
}; // class ThreefryPBox
template <typename T, std::size_t K, std::size_t Rounds, typename Constants>
class ThreefryGeneratorGenericImpl
{
public:
static constexpr std::size_t blocks() { return 8; }
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par)
{
// clang-format off
sbox<0x00>(state); pbox<0x00>(state); kbox<0x00>(state, par);
sbox<0x01>(state); pbox<0x01>(state); kbox<0x01>(state, par);
sbox<0x02>(state); pbox<0x02>(state); kbox<0x02>(state, par);
sbox<0x03>(state); pbox<0x03>(state); kbox<0x03>(state, par);
sbox<0x04>(state); pbox<0x04>(state); kbox<0x04>(state, par);
sbox<0x05>(state); pbox<0x05>(state); kbox<0x05>(state, par);
sbox<0x06>(state); pbox<0x06>(state); kbox<0x06>(state, par);
sbox<0x07>(state); pbox<0x07>(state); kbox<0x07>(state, par);
sbox<0x08>(state); pbox<0x08>(state); kbox<0x08>(state, par);
sbox<0x09>(state); pbox<0x09>(state); kbox<0x09>(state, par);
sbox<0x0A>(state); pbox<0x0A>(state); kbox<0x0A>(state, par);
sbox<0x0B>(state); pbox<0x0B>(state); kbox<0x0B>(state, par);
sbox<0x0C>(state); pbox<0x0C>(state); kbox<0x0C>(state, par);
sbox<0x0D>(state); pbox<0x0D>(state); kbox<0x0D>(state, par);
sbox<0x0E>(state); pbox<0x0E>(state); kbox<0x0E>(state, par);
sbox<0x0F>(state); pbox<0x0F>(state); kbox<0x0F>(state, par);
sbox<0x10>(state); pbox<0x10>(state); kbox<0x10>(state, par);
sbox<0x11>(state); pbox<0x11>(state); kbox<0x11>(state, par);
sbox<0x12>(state); pbox<0x12>(state); kbox<0x12>(state, par);
sbox<0x13>(state); pbox<0x13>(state); kbox<0x13>(state, par);
sbox<0x14>(state); pbox<0x14>(state); kbox<0x14>(state, par);
sbox<0x15>(state); pbox<0x15>(state); kbox<0x15>(state, par);
sbox<0x16>(state); pbox<0x16>(state); kbox<0x16>(state, par);
sbox<0x17>(state); pbox<0x17>(state); kbox<0x17>(state, par);
sbox<0x18>(state); pbox<0x18>(state); kbox<0x18>(state, par);
sbox<0x19>(state); pbox<0x19>(state); kbox<0x19>(state, par);
sbox<0x1A>(state); pbox<0x1A>(state); kbox<0x1A>(state, par);
sbox<0x1B>(state); pbox<0x1B>(state); kbox<0x1B>(state, par);
sbox<0x1C>(state); pbox<0x1C>(state); kbox<0x1C>(state, par);
sbox<0x1D>(state); pbox<0x1D>(state); kbox<0x1D>(state, par);
sbox<0x1E>(state); pbox<0x1E>(state); kbox<0x1E>(state, par);
sbox<0x1F>(state); pbox<0x1F>(state); kbox<0x1F>(state, par);
// clang-format on
eval<0x20>(state, par, std::integral_constant<bool, 0x20 <= Rounds>());
}
static void eval(std::array<std::array<T, K>, blocks()> &state,
const std::array<T, K + 1> &par)
{
eval(std::get<0>(state), par);
eval(std::get<1>(state), par);
eval(std::get<2>(state), par);
eval(std::get<3>(state), par);
eval(std::get<4>(state), par);
eval(std::get<5>(state), par);
eval(std::get<6>(state), par);
eval(std::get<7>(state), par);
}
private:
template <std::size_t>
static void eval(
std::array<T, K> &, const std::array<T, K + 1> &, std::false_type)
{
}
template <std::size_t N>
static void eval(std::array<T, K> &state, const std::array<T, K + 1> &par,
std::true_type)
{
sbox(state);
pbox(state);
kbox(state, par);
eval<N + 1>(
state, par, std::integral_constant<bool, N + 1 <= Rounds>());
}
template <std::size_t N>
static void kbox(std::array<T, K> &state, const std::array<T, K + 1> &par)
{
kbox<N>(state, par,
std::integral_constant<bool, (N % 4 == 0 && N <= Rounds)>());
}
template <std::size_t N>
static void kbox(
std::array<T, K> &, const std::array<T, K + 1> &, std::false_type)
{
}
template <std::size_t N>
static void kbox(std::array<T, K> &state, const std::array<T, K + 1> &par,
std::true_type)
{
ThreefryKBox<T, K, N, Constants>::eval(state, par);
}
template <std::size_t N>
static void sbox(std::array<T, K> &state)
{
sbox<N>(state, std::integral_constant<bool, (N > 0 && N <= Rounds)>());
}
template <std::size_t N>
static void sbox(std::array<T, K> &, std::false_type)
{
}
template <std::size_t N>
static void sbox(std::array<T, K> &state, std::true_type)
{
ThreefrySBox<T, K, N, Constants>::eval(state);
}
template <std::size_t N>
static void pbox(std::array<T, K> &state)
{
pbox<N>(state, std::integral_constant<bool, (N > 0 && N <= Rounds)>());
}
template <std::size_t N>
static void pbox(std::array<T, K> &, std::false_type)
{
}
template <std::size_t N>
static void pbox(std::array<T, K> &state, std::true_type)
{
ThreefryPBox<T, K, N, Constants>::eval(state);
}
}; // class ThreefryGeneratorGenericImpl
<|endoftext|>
|
<commit_before>
#include "../../Flare.h"
#include "FlarePlanetaryBox.h"
void SFlarePlanetaryBox::Construct(const SFlarePlanetaryBox::FArguments& InArgs)
{
Radius = 200;
PlanetImage = NULL;
ClearChildren();
// Add slots
const int32 NumSlots = InArgs.Slots.Num();
for (int32 SlotIndex = 0; SlotIndex < NumSlots; ++SlotIndex)
{
Children.Add(InArgs.Slots[SlotIndex]);
}
}
void SFlarePlanetaryBox::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
for (int32 ChildIndex = 0; ChildIndex < Children.Num(); ++ChildIndex)
{
// Get all required data
const SFlarePlanetaryBox::FSlot& CurChild = Children[ChildIndex];
const EVisibility ChildVisibility = CurChild.GetWidget()->GetVisibility();
FVector2D WidgetSize = CurChild.GetWidget()->GetDesiredSize();
FVector2D Offset = FVector2D::ZeroVector;
// Child with index 0 is the main body, index 1 is probably the name but we don't care, others are sectors
if (ChildIndex > 0)
{
float X, Y;
float Angle = (360 / (Children.Num() - 1)) * (ChildIndex - 1) - 90;
FMath::PolarToCartesian(Radius, FMath::DegreesToRadians(Angle), X, Y);
Offset = FVector2D(X, Y);
WidgetSize = FVector2D(CurChild.GetWidget()->GetDesiredSize().X, Theme.SectorButtonHeight);
}
// Arrange the child
FVector2D Location = (AllottedGeometry.GetLocalSize() - WidgetSize) / 2 + Offset;
ArrangedChildren.AddWidget(ChildVisibility, AllottedGeometry.MakeChild(
CurChild.GetWidget(),
Location,
CurChild.GetWidget()->GetDesiredSize()
));
}
}
FVector2D SFlarePlanetaryBox::ComputeDesiredSize(float) const
{
return 2.5 * FVector2D(Radius, Radius);
}
FChildren* SFlarePlanetaryBox::GetChildren()
{
return &Children;
}
int32 SFlarePlanetaryBox::RemoveSlot(const TSharedRef<SWidget>& SlotWidget)
{
for (int32 SlotIdx = 0; SlotIdx < Children.Num(); ++SlotIdx)
{
if (SlotWidget == Children[SlotIdx].GetWidget())
{
Children.RemoveAt(SlotIdx);
return SlotIdx;
}
}
return -1;
}
void SFlarePlanetaryBox::ClearChildren()
{
Children.Empty();
if (PlanetImage)
{
AddSlot()
[
SNew(SImage).Image(PlanetImage)
];
}
}
<commit_msg>#228 Fixed planetary layout<commit_after>
#include "../../Flare.h"
#include "FlarePlanetaryBox.h"
void SFlarePlanetaryBox::Construct(const SFlarePlanetaryBox::FArguments& InArgs)
{
Radius = 200;
PlanetImage = NULL;
ClearChildren();
// Add slots
const int32 NumSlots = InArgs.Slots.Num();
for (int32 SlotIndex = 0; SlotIndex < NumSlots; ++SlotIndex)
{
Children.Add(InArgs.Slots[SlotIndex]);
}
}
void SFlarePlanetaryBox::OnArrangeChildren(const FGeometry& AllottedGeometry, FArrangedChildren& ArrangedChildren) const
{
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
for (int32 ChildIndex = 0; ChildIndex < Children.Num(); ++ChildIndex)
{
// Get all required data
const SFlarePlanetaryBox::FSlot& CurChild = Children[ChildIndex];
const EVisibility ChildVisibility = CurChild.GetWidget()->GetVisibility();
FVector2D WidgetSize = CurChild.GetWidget()->GetDesiredSize();
FVector2D Offset = FVector2D::ZeroVector;
// Child with index 0 is the main body, index 1 is probably the name but we don't care, others are sectors
if (ChildIndex > 0)
{
float X, Y;
float Angle = (360 / (Children.Num() - 1)) * (ChildIndex - 1) - 90;
FMath::PolarToCartesian(Radius, FMath::DegreesToRadians(Angle), X, Y);
Offset = FVector2D(X, Y);
WidgetSize = FVector2D(CurChild.GetWidget()->GetDesiredSize().X, Theme.SectorButtonHeight);
}
// Arrange the child
FVector2D Location = (AllottedGeometry.GetLocalSize() - WidgetSize) / 2 + Offset;
ArrangedChildren.AddWidget(ChildVisibility, AllottedGeometry.MakeChild(
CurChild.GetWidget(),
Location,
CurChild.GetWidget()->GetDesiredSize()
));
}
}
FVector2D SFlarePlanetaryBox::ComputeDesiredSize(float) const
{
return 2.6 * FVector2D(Radius, Radius);
}
FChildren* SFlarePlanetaryBox::GetChildren()
{
return &Children;
}
int32 SFlarePlanetaryBox::RemoveSlot(const TSharedRef<SWidget>& SlotWidget)
{
for (int32 SlotIdx = 0; SlotIdx < Children.Num(); ++SlotIdx)
{
if (SlotWidget == Children[SlotIdx].GetWidget())
{
Children.RemoveAt(SlotIdx);
return SlotIdx;
}
}
return -1;
}
void SFlarePlanetaryBox::ClearChildren()
{
Children.Empty();
if (PlanetImage)
{
AddSlot()
[
SNew(SImage).Image(PlanetImage)
];
}
}
<|endoftext|>
|
<commit_before>#include "fenwick/fenwick_tree.hpp"
#include "fenwick/typef.hpp"
#include "fenwick/typel.hpp"
#include "fenwick/bytef.hpp"
#include "fenwick/bytel.hpp"
#include "fenwick/bitf.hpp"
#include "fenwick/bitl.hpp"
#include "fenwick/hybrid.hpp"
<commit_msg>Added FixedF and FixedL<commit_after>#include "fenwick/fenwick_tree.hpp"
#include "fenwick/fixedf.hpp"
#include "fenwick/fixedl.hpp"
#include "fenwick/typef.hpp"
#include "fenwick/typel.hpp"
#include "fenwick/bytef.hpp"
#include "fenwick/bytel.hpp"
#include "fenwick/bitf.hpp"
#include "fenwick/bitl.hpp"
#include "fenwick/hybrid.hpp"
<|endoftext|>
|
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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 GCN_GUICHAN_HPP
#define GCN_GUICHAN_HPP
#include <guichan/actionevent.hpp>
#include <guichan/actionlistener.hpp>
#include <guichan/cliprectangle.hpp>
#include <guichan/color.hpp>
#include <guichan/deathlistener.hpp>
#include <guichan/event.hpp>
#include <guichan/exception.hpp>
#include <guichan/focushandler.hpp>
#include <guichan/focuslistener.hpp>
#include <guichan/font.hpp>
#include <guichan/genericinput.hpp>
#include <guichan/graphics.hpp>
#include <guichan/gui.hpp>
#include <guichan/image.hpp>
#include <guichan/imagefont.hpp>
#include <guichan/imageloader.hpp>
#include <guichan/input.hpp>
#include <guichan/inputevent.hpp>
#include <guichan/key.hpp>
#include <guichan/keyevent.hpp>
#include <guichan/keyinput.hpp>
#include <guichan/keylistener.hpp>
#include <guichan/listmodel.hpp>
#include <guichan/mouseevent.hpp>
#include <guichan/mouseinput.hpp>
#include <guichan/mouselistener.hpp>
#include <guichan/rectangle.hpp>
#include <guichan/selectionevent.hpp>
#include <guichan/selectionlistener.hpp>
#include <guichan/widget.hpp>
#include <guichan/widgetlistener.hpp>
#include <guichan/widgets/button.hpp>
#include <guichan/widgets/checkbox.hpp>
#include <guichan/widgets/container.hpp>
#include <guichan/widgets/dropdown.hpp>
#include <guichan/widgets/icon.hpp>
#include <guichan/widgets/imagebutton.hpp>
#include <guichan/widgets/label.hpp>
#include <guichan/widgets/listbox.hpp>
#include <guichan/widgets/scrollarea.hpp>
#include <guichan/widgets/slider.hpp>
#include <guichan/widgets/radiobutton.hpp>
#include <guichan/widgets/tab.hpp>
#include <guichan/widgets/tabbedarea.hpp>
#include <guichan/widgets/textbox.hpp>
#include <guichan/widgets/textfield.hpp>
#include <guichan/widgets/window.hpp>
#include "guichan/platform.hpp"
class Widget;
extern "C"
{
/**
* Gets the the version of Guichan. As it is a C function
* it can be used to check for Guichan with autotools.
*
* @return the version of Guichan.
*/
GCN_CORE_DECLSPEC extern const char* gcnGuichanVersion();
}
#endif // end GCN_GUICHAN_HPP
<commit_msg>Dummy commit to test the mailing list.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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 GCN_GUICHAN_HPP
#define GCN_GUICHAN_HPP
#include <guichan/actionevent.hpp>
#include <guichan/actionlistener.hpp>
#include <guichan/cliprectangle.hpp>
#include <guichan/color.hpp>
#include <guichan/deathlistener.hpp>
#include <guichan/event.hpp>
#include <guichan/exception.hpp>
#include <guichan/focushandler.hpp>
#include <guichan/focuslistener.hpp>
#include <guichan/font.hpp>
#include <guichan/genericinput.hpp>
#include <guichan/graphics.hpp>
#include <guichan/gui.hpp>
#include <guichan/image.hpp>
#include <guichan/imagefont.hpp>
#include <guichan/imageloader.hpp>
#include <guichan/input.hpp>
#include <guichan/inputevent.hpp>
#include <guichan/key.hpp>
#include <guichan/keyevent.hpp>
#include <guichan/keyinput.hpp>
#include <guichan/keylistener.hpp>
#include <guichan/listmodel.hpp>
#include <guichan/mouseevent.hpp>
#include <guichan/mouseinput.hpp>
#include <guichan/mouselistener.hpp>
#include <guichan/rectangle.hpp>
#include <guichan/selectionevent.hpp>
#include <guichan/selectionlistener.hpp>
#include <guichan/widget.hpp>
#include <guichan/widgetlistener.hpp>
#include <guichan/widgets/button.hpp>
#include <guichan/widgets/checkbox.hpp>
#include <guichan/widgets/container.hpp>
#include <guichan/widgets/dropdown.hpp>
#include <guichan/widgets/icon.hpp>
#include <guichan/widgets/imagebutton.hpp>
#include <guichan/widgets/label.hpp>
#include <guichan/widgets/listbox.hpp>
#include <guichan/widgets/scrollarea.hpp>
#include <guichan/widgets/slider.hpp>
#include <guichan/widgets/radiobutton.hpp>
#include <guichan/widgets/tab.hpp>
#include <guichan/widgets/tabbedarea.hpp>
#include <guichan/widgets/textbox.hpp>
#include <guichan/widgets/textfield.hpp>
#include <guichan/widgets/window.hpp>
#include "guichan/platform.hpp"
class Widget;
extern "C"
{
/**
* Gets the the version of Guichan. As it is a C function
* it can be used to check for Guichan with autotools.
*
* @return the version of Guichan.
*/
GCN_CORE_DECLSPEC extern const char* gcnGuichanVersion();
}
#endif // end GCN_GUICHAN_HPP
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include <qllcpserver.h>
#include <qllcpsocket.h>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"
QTM_USE_NAMESPACE
QString TestUri("urn:nfc:xsn:nokia:symbiantest");
class tst_QLlcpServer : public QObject
{
Q_OBJECT
public:
tst_QLlcpServer();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void newConnection();
void newConnection_data();
void newConnection_wait();
void newConnection_wait_data();
};
tst_QLlcpServer::tst_QLlcpServer()
{
}
void tst_QLlcpServer::initTestCase()
{
}
void tst_QLlcpServer::cleanupTestCase()
{
}
void tst_QLlcpServer::newConnection_data()
{
QTest::addColumn<QString>("uri");
QTest::addColumn<QString>("hint");
QTest::newRow("0") << TestUri
<< "QLlcpServer enabled: uri = " + TestUri;
}
/*!
Description: Unit test for NFC LLCP server async functions
TestScenario: 1. Server will listen to a pre-defined URI
2. Wait client to connect.
3. Read message from client.
4. Echo the same message back to client
5. Wait client disconnect event.
TestExpectedResults:
1. The listen successfully set up.
2. The message has be received from client.
3. The echoed message has been sent to client.
4. Connection disconnected and NO error signals emitted.
*/
void tst_QLlcpServer::newConnection()
{
QFETCH(QString, uri);
QFETCH(QString, hint);
QLlcpServer server;
qDebug() << "Create QLlcpServer completed";
qDebug() << "Start listening...";
QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));
QSignalSpy readyReadSpy(socket, SIGNAL(readyRead()));
QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::Error)));
bool ret = server.listen(uri);
QVERIFY(ret);
qDebug() << "Listen() return ok";
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!connectionSpy.isEmpty());
qDebug() << "try to call nextPendingConnection()";
QLlcpSocket *socket = server.nextPendingConnection();
QVERIFY(socket != NULL);
//Get data from client
QTRY_VERIFY(!readyReadSpy.isEmpty());
quint16 blockSize = 0;
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while (socket->bytesAvailable() < (int)sizeof(quint16)){
QSignalSpy readyRead(socket, SIGNAL(readyRead()));
QTRY_VERIFY(!readyRead.isEmpty());
}
in >> blockSize;
while (socket ->bytesAvailable() < blockSize){
QSignalSpy readyRead(socket, SIGNAL(readyRead()));
QTRY_VERIFY(!readyRead.isEmpty());
}
QString echo;
in >> echo;
//Send data to client
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << (quint16)echo.length();
out << echo;
socket->write(block);
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
qint64 written = bytesWrittenSpy.first().at(0).value<qint64>();
while (written < echo.length())
{
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
written = bytesWrittenSpy.first().at(0).value<qint64>();
}
//Now data has been sent,check the if existing error
QVERIFY(errorSpy.isEmpty());
server.close();
}
/*!
Description: Unit test for NFC LLCP server sync(waitXXX) functions
TestScenario: 1. Server will listen to a pre-defined URI
2. Wait client to connect.
3. Read message from client.
4. Echo the same message back to client
5. Wait client disconnect event.
TestExpectedResults:
1. The listen successfully set up.
2. The message has be received from client.
3. The echoed message has been sent to client.
4. Connection disconnected and NO error signals emitted.
*/
void tst_QLlcpServer::newConnection_wait()
{
QFETCH(QString, uri);
QFETCH(QString, hint);
QLlcpServer server;
bool ret = server.listen(uri);
QVERIFY(ret);
QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!connectionSpy.isEmpty());
QLlcpSocket *socket = server.nextPendingConnection();
QVERIFY(socket != NULL);
QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::Error)));
//Get data from client
const int Timeout = 10 * 1000;
quint16 blockSize = 0;
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while (socket->bytesAvailable() < (int)sizeof(quint16)) {
bool ret = socket->waitForReadyRead(Timeout);
QVERIFY(ret);
}
in >> blockSize;
while (socket ->bytesAvailable() < blockSize){
bool ret = socket->waitForReadyRead(Timeout);
QVERIFY(ret);
}
QString echo;
in >> echo;
//Send data to client
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << (quint16)echo.length();
out << echo;
socket->write(block);
ret = socket->waitForBytesWritten(Timeout);
QVERIFY(ret);
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
qint64 written = bytesWrittenSpy.first().at(0).value<qint64>();
while (written < echo.length())
{
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
bool ret = socket->waitForBytesWritten(Timeout);
QVERIFY(ret);
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
written = bytesWrittenSpy.first().at(0).value<qint64>();
}
//Now data has been sent,check the if existing error
QVERIFY(errorSpy.isEmpty());
server.close();
}
void tst_QLlcpServer::newConnection_wait_data()
{
QTest::addColumn<QString>("uri");
QTest::addColumn<QString>("hint");
QTest::newRow("0") << TestUri
<< "Please touch a NFC device with llcp client enabled: uri = " + TestUri;
}
QTEST_MAIN(tst_QLlcpServer);
#include "tst_qllcpserver.moc"
<commit_msg>Fix build error<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>
#include <qllcpserver.h>
#include <qllcpsocket.h>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"
QTM_USE_NAMESPACE
QString TestUri("urn:nfc:xsn:nokia:symbiantest");
class tst_QLlcpServer : public QObject
{
Q_OBJECT
public:
tst_QLlcpServer();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void newConnection();
void newConnection_data();
void newConnection_wait();
void newConnection_wait_data();
};
tst_QLlcpServer::tst_QLlcpServer()
{
}
void tst_QLlcpServer::initTestCase()
{
}
void tst_QLlcpServer::cleanupTestCase()
{
}
void tst_QLlcpServer::newConnection_data()
{
QTest::addColumn<QString>("uri");
QTest::addColumn<QString>("hint");
QTest::newRow("0") << TestUri
<< "QLlcpServer enabled: uri = " + TestUri;
}
/*!
Description: Unit test for NFC LLCP server async functions
TestScenario: 1. Server will listen to a pre-defined URI
2. Wait client to connect.
3. Read message from client.
4. Echo the same message back to client
5. Wait client disconnect event.
TestExpectedResults:
1. The listen successfully set up.
2. The message has be received from client.
3. The echoed message has been sent to client.
4. Connection disconnected and NO error signals emitted.
*/
void tst_QLlcpServer::newConnection()
{
QFETCH(QString, uri);
QFETCH(QString, hint);
QLlcpServer server;
qDebug() << "Create QLlcpServer completed";
qDebug() << "Start listening...";
QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));
bool ret = server.listen(uri);
QVERIFY(ret);
qDebug() << "Listen() return ok";
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!connectionSpy.isEmpty());
qDebug() << "try to call nextPendingConnection()";
QLlcpSocket *socket = server.nextPendingConnection();
QVERIFY(socket != NULL);
QSignalSpy readyReadSpy(socket, SIGNAL(readyRead()));
QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::Error)));
//Get data from client
QTRY_VERIFY(!readyReadSpy.isEmpty());
quint16 blockSize = 0;
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while (socket->bytesAvailable() < (int)sizeof(quint16)){
QSignalSpy readyRead(socket, SIGNAL(readyRead()));
QTRY_VERIFY(!readyRead.isEmpty());
}
in >> blockSize;
while (socket ->bytesAvailable() < blockSize){
QSignalSpy readyRead(socket, SIGNAL(readyRead()));
QTRY_VERIFY(!readyRead.isEmpty());
}
QString echo;
in >> echo;
//Send data to client
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << (quint16)echo.length();
out << echo;
socket->write(block);
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
qint64 written = bytesWrittenSpy.first().at(0).value<qint64>();
while (written < echo.length())
{
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
written = bytesWrittenSpy.first().at(0).value<qint64>();
}
//Now data has been sent,check the if existing error
QVERIFY(errorSpy.isEmpty());
server.close();
}
/*!
Description: Unit test for NFC LLCP server sync(waitXXX) functions
TestScenario: 1. Server will listen to a pre-defined URI
2. Wait client to connect.
3. Read message from client.
4. Echo the same message back to client
5. Wait client disconnect event.
TestExpectedResults:
1. The listen successfully set up.
2. The message has be received from client.
3. The echoed message has been sent to client.
4. Connection disconnected and NO error signals emitted.
*/
void tst_QLlcpServer::newConnection_wait()
{
QFETCH(QString, uri);
QFETCH(QString, hint);
QLlcpServer server;
bool ret = server.listen(uri);
QVERIFY(ret);
QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));
QNfcTestUtil::ShowMessage(hint);
QTRY_VERIFY(!connectionSpy.isEmpty());
QLlcpSocket *socket = server.nextPendingConnection();
QVERIFY(socket != NULL);
QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::Error)));
//Get data from client
const int Timeout = 10 * 1000;
quint16 blockSize = 0;
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_6);
while (socket->bytesAvailable() < (int)sizeof(quint16)) {
bool ret = socket->waitForReadyRead(Timeout);
QVERIFY(ret);
}
in >> blockSize;
while (socket ->bytesAvailable() < blockSize){
bool ret = socket->waitForReadyRead(Timeout);
QVERIFY(ret);
}
QString echo;
in >> echo;
//Send data to client
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_6);
out << (quint16)echo.length();
out << echo;
socket->write(block);
ret = socket->waitForBytesWritten(Timeout);
QVERIFY(ret);
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
qint64 written = bytesWrittenSpy.first().at(0).value<qint64>();
while (written < echo.length())
{
QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
bool ret = socket->waitForBytesWritten(Timeout);
QVERIFY(ret);
QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
written = bytesWrittenSpy.first().at(0).value<qint64>();
}
//Now data has been sent,check the if existing error
QVERIFY(errorSpy.isEmpty());
server.close();
}
void tst_QLlcpServer::newConnection_wait_data()
{
QTest::addColumn<QString>("uri");
QTest::addColumn<QString>("hint");
QTest::newRow("0") << TestUri
<< "Please touch a NFC device with llcp client enabled: uri = " + TestUri;
}
QTEST_MAIN(tst_QLlcpServer);
#include "tst_qllcpserver.moc"
<|endoftext|>
|
<commit_before>/*
CS 3306
Chris Chan
Last updated 9/30/14
Write a program using C++ to find the minimal spanning tree of a graph. The graph is
represented by an adjacency matrix.
*/
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
bool isInMST(int, int[], int); //first param is what wer're looking for, 2nd is the array we're checking, 3rd is size.
int main(){
fstream inFile;
string filePath;
bool complete=false;
int adjMatrix[10][10]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
}, minSpanMatrix[10][10]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
}, minSpanVertices[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; //will not have matrix bigger than 10x10
int numVertices=-1, minVertex=-1, minEdge=-1;
//- Prompt user for input filepath name.
cout << "Where is the file located?" << endl;
cin >> filePath;
cin.get();
inFile.open(filePath, ios::in);
if(!inFile){
cout << "Error! Missing File! Please try again with a proper filepath." << endl <<"Press enter to close the window...";
cin.get();
return 0;
}
else{
inFile >> numVertices;
inFile >> minSpanVertices[0];
minSpanVertices[0]-=1;
minSpanMatrix[minSpanVertices[0]][minSpanVertices[0]]=0;
inFile.get(); //grabs rest of the line.
for(int i=0; i<numVertices;i++){
for(int j=0; j<numVertices;j++){
inFile >> adjMatrix[i][j];
}
inFile.get();
}
}
cout << "File found!" << endl;
cout << "Adjacency matrix of the input is as follows:" << endl << endl;
for(int i=0; i<numVertices;i++){
for(int j=0; j<numVertices;j++){
cout << adjMatrix[i][j] << "\t";
}
cout << endl << endl;
}
cout << endl;
cout << "Calculating minimal spanning tree..." << endl;
while(!complete){
//determine if the process is complete; e.g. all vertices have been added to the min span tree
complete=true;
for(int i=0; i<numVertices; i++){
if(minSpanVertices[i]==-1){
complete=false;
}
}
if(!complete){
//find the closest vertex to the existing minimal spanning tree
int row, col, minRow, minCol;
for(row=0; row<numVertices;row++){
if(!isInMST(row,minSpanVertices,numVertices)){
for(col=0; col<numVertices;col++){
if(isInMST(col,minSpanVertices,numVertices)){
if(minEdge<1||(adjMatrix[row][col]<minEdge && adjMatrix[row][col]!=-1)){
minEdge=adjMatrix[row][col];
minVertex=row;
minRow=row;
minCol=col;
}
}
}
}
}
//add the found vertex to the min span tree
//cout << "Adding this vertex to MST: " << minVertex << endl;
int count=0;
while(minSpanVertices[count]!=-1){
count++;
}
minSpanVertices[count]=minVertex;
//add edge to min span tree
//cout << "adding this edge to row " << minRow << " and col " << minCol << ":" << minEdge << endl;
minSpanMatrix[minRow][minCol]=minEdge;
minSpanMatrix[minCol][minRow]=minEdge;
minSpanMatrix[minRow][minRow]=0;
//reset min edge to undefined;
minEdge=-1;
}
}
cout << "Minimal spanning tree of the given input is as follows:" << endl << endl;
for(int i=0; i<numVertices;i++){
for(int j=0; j<numVertices;j++){
cout << minSpanMatrix[i][j] << "\t";
}
cout << endl << endl;
}
cout << "Press enter to close the window...";
cin.get();
return 0;
}
bool isInMST(int x, int intArr[], int size){
for(int i=0; i<size; i++)
if(x==intArr[i])
return true;
return false;
}
<commit_msg>Update MinSpanTree.cpp<commit_after>/*
CS 3306
Chris Chan
Last updated 9/30/14
Write a program using C++ to find the minimal spanning tree of a graph. The graph is
represented by an adjacency matrix.
*/
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
bool isInMST(int, int[], int); //first param is what wer're looking for, 2nd is the array we're checking, 3rd is size.
int main(){
fstream inFile;
string filePath;
bool complete=false;
int adjMatrix[10][10]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
}, minSpanMatrix[10][10]={
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
}, minSpanVertices[10]={-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; //will not have matrix bigger than 10x10
int numVertices=-1, minVertex=-1, minEdge=-1;
//- Prompt user for input filepath name.
cout << "Where is the file located?" << endl;
cin >> filePath;
cin.get();
inFile.open(filePath, ios::in);
if(!inFile){
cout << "Error! Missing File! Please try again with a proper filepath." << endl <<"Press enter to close the window...";
cin.get();
return 0;
}
else{
inFile >> numVertices;
inFile >> minSpanVertices[0];
minSpanVertices[0]-=1;
minSpanMatrix[minSpanVertices[0]][minSpanVertices[0]]=0;
inFile.get(); //grabs rest of the line.
for(int i=0; i<numVertices;i++){
for(int j=0; j<numVertices;j++){
inFile >> adjMatrix[i][j];
}
inFile.get();
}
}
//cout << "File found!" << endl;
cout << "Adjacency matrix of the input is as follows:" << endl;
cout << numVertices << " vertices, beginning at vertex " << minSpanVertices[0]+1 << endl << endl;
for(int i=0; i<numVertices;i++){
for(int j=0; j<numVertices;j++){
cout << adjMatrix[i][j] << "\t";
}
cout << endl << endl;
}
cout << endl;
cout << "Calculating minimal spanning tree..." << endl;
while(!complete){
//determine if the process is complete; e.g. all vertices have been added to the min span tree
complete=true;
for(int i=0; i<numVertices; i++){
if(minSpanVertices[i]==-1){
complete=false;
}
}
if(!complete){
//find the closest vertex to the existing minimal spanning tree
int row, col, minRow, minCol;
for(row=0; row<numVertices;row++){
if(!isInMST(row,minSpanVertices,numVertices)){
for(col=0; col<numVertices;col++){
if(isInMST(col,minSpanVertices,numVertices)){
if(minEdge<1||(adjMatrix[row][col]<minEdge && adjMatrix[row][col]!=-1)){
minEdge=adjMatrix[row][col];
minVertex=row;
minRow=row;
minCol=col;
}
}
}
}
}
//add the found vertex to the min span tree
//cout << "Adding this vertex to MST: " << minVertex << endl;
int count=0;
while(minSpanVertices[count]!=-1){
count++;
}
minSpanVertices[count]=minVertex;
//add edge to min span tree
//cout << "adding this edge to row " << minRow << " and col " << minCol << ":" << minEdge << endl;
minSpanMatrix[minRow][minCol]=minEdge;
minSpanMatrix[minCol][minRow]=minEdge;
minSpanMatrix[minRow][minRow]=0;
//reset min edge to undefined;
minEdge=-1;
}
}
cout << "Minimal spanning tree of the given input is as follows:" << endl << endl;
for(int i=0; i<numVertices;i++){
for(int j=0; j<numVertices;j++){
cout << minSpanMatrix[i][j] << "\t";
}
cout << endl << endl;
}
cout << "Press enter to close the window...";
cin.get();
return 0;
}
bool isInMST(int x, int intArr[], int size){
for(int i=0; i<size; i++)
if(x==intArr[i])
return true;
return false;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "AlembicModel.h"
#include "AlembicXform.h"
#include "sceneGraph.h"
using namespace XSI;
using namespace MATH;
AlembicModel::AlembicModel(SceneNodePtr eNode, AlembicWriteJob * in_Job, Abc::OObject oParent)
: AlembicObject(eNode, in_Job, oParent)
{
AbcG::OXform xform(GetMyParent(), eNode->name, GetJob()->GetAnimatedTs());
// create the generic properties
mOVisibility = CreateVisibilityProperty(xform,GetJob()->GetAnimatedTs());
mXformSchema = xform.getSchema();
XSI::CRef parentGlobalTransRef;
SceneNode* parent = mExoSceneNode->parent;
while(parent){
if(parent->selected){
break;
}
parent = parent->parent;
}
if(parent){
XSI::CRef nodeRef;
nodeRef.Set(mExoSceneNode->parent->dccIdentifier.c_str());
XSI::X3DObject xObj(nodeRef);
parentGlobalTransRef = xObj.GetKinematics().GetGlobal().GetRef();
}
AddRef(parentGlobalTransRef);//global transform of parent - ref 3
}
AlembicModel::~AlembicModel()
{
// we have to clear this prior to destruction
// this is a workaround for issue-171
mOVisibility.reset();
}
Abc::OCompoundProperty AlembicModel::GetCompound()
{
return mXformSchema;
}
XSI::CStatus AlembicModel::Save(double time)
{
// access the model
Primitive prim(GetRef(REF_PRIMITIVE));
const bool bTransCache = GetJob()->GetOption("transformCache");
bool bGlobalSpace = GetJob()->GetOption(L"globalSpace");
const bool bFlatten = GetJob()->GetOption(L"flattenHierarchy");
if(bFlatten && mExoSceneNode->type == SceneNode::NAMESPACE_TRANSFORM){
bGlobalSpace = true;
}
// store the transform
SaveXformSample(GetRef(REF_PARENT_GLOBAL_TRANS), GetRef(REF_GLOBAL_TRANS),mXformSchema, mXformSample, time, bTransCache, bGlobalSpace, bFlatten);
if(mNumSamples == 0){
if(!mXformXSINodeType.valid()){
mXformXSINodeType = Abc::OUcharProperty(mXformSchema.getArbGeomParams(), ".xsiNodeType", mXformSchema.getMetaData(), GetJob()->GetAnimatedTs() );
}
if(mExoSceneNode->type == SceneNode::NAMESPACE_TRANSFORM){
mXformXSINodeType.set(XSI_XformTypes::XMODEL);
}
else{
mXformXSINodeType.set(XSI_XformTypes::XNULL);
}
}
// set the visibility
Property visProp;
prim.GetParent3DObject().GetPropertyFromName(L"Visibility",visProp);
if(isRefAnimated(visProp.GetRef()) || mNumSamples == 0)
{
bool visibility = visProp.GetParameterValue(L"rendvis",time);
mOVisibility.set(visibility ?AbcG::kVisibilityVisible :AbcG::kVisibilityHidden);
}
// store the metadata
SaveMetaData(GetRef(REF_NODE),this);
mNumSamples++;
return CStatus::OK;
}
<commit_msg>#296 - fixed bug in parent skipping code<commit_after>#include "stdafx.h"
#include "AlembicModel.h"
#include "AlembicXform.h"
#include "sceneGraph.h"
using namespace XSI;
using namespace MATH;
AlembicModel::AlembicModel(SceneNodePtr eNode, AlembicWriteJob * in_Job, Abc::OObject oParent)
: AlembicObject(eNode, in_Job, oParent)
{
AbcG::OXform xform(GetMyParent(), eNode->name, GetJob()->GetAnimatedTs());
// create the generic properties
mOVisibility = CreateVisibilityProperty(xform,GetJob()->GetAnimatedTs());
mXformSchema = xform.getSchema();
XSI::CRef parentGlobalTransRef;
SceneNode* parent = mExoSceneNode->parent;
while(parent){
if(parent->selected){
break;
}
parent = parent->parent;
}
if(parent){
XSI::CRef nodeRef;
nodeRef.Set(parent->dccIdentifier.c_str());
XSI::X3DObject xObj(nodeRef);
parentGlobalTransRef = xObj.GetKinematics().GetGlobal().GetRef();
}
AddRef(parentGlobalTransRef);//global transform of parent - ref 3
}
AlembicModel::~AlembicModel()
{
// we have to clear this prior to destruction
// this is a workaround for issue-171
mOVisibility.reset();
}
Abc::OCompoundProperty AlembicModel::GetCompound()
{
return mXformSchema;
}
XSI::CStatus AlembicModel::Save(double time)
{
// access the model
Primitive prim(GetRef(REF_PRIMITIVE));
const bool bTransCache = GetJob()->GetOption("transformCache");
bool bGlobalSpace = GetJob()->GetOption(L"globalSpace");
const bool bFlatten = GetJob()->GetOption(L"flattenHierarchy");
if(bFlatten && mExoSceneNode->type == SceneNode::NAMESPACE_TRANSFORM){
bGlobalSpace = true;
}
// store the transform
SaveXformSample(GetRef(REF_PARENT_GLOBAL_TRANS), GetRef(REF_GLOBAL_TRANS),mXformSchema, mXformSample, time, bTransCache, bGlobalSpace, bFlatten);
if(mNumSamples == 0){
if(!mXformXSINodeType.valid()){
mXformXSINodeType = Abc::OUcharProperty(mXformSchema.getArbGeomParams(), ".xsiNodeType", mXformSchema.getMetaData(), GetJob()->GetAnimatedTs() );
}
if(mExoSceneNode->type == SceneNode::NAMESPACE_TRANSFORM){
mXformXSINodeType.set(XSI_XformTypes::XMODEL);
}
else{
mXformXSINodeType.set(XSI_XformTypes::XNULL);
}
}
// set the visibility
Property visProp;
prim.GetParent3DObject().GetPropertyFromName(L"Visibility",visProp);
if(isRefAnimated(visProp.GetRef()) || mNumSamples == 0)
{
bool visibility = visProp.GetParameterValue(L"rendvis",time);
mOVisibility.set(visibility ?AbcG::kVisibilityVisible :AbcG::kVisibilityHidden);
}
// store the metadata
SaveMetaData(GetRef(REF_NODE),this);
mNumSamples++;
return CStatus::OK;
}
<|endoftext|>
|
<commit_before>#include "SoundPlayer.h"
#include <Windows.h>
#include <dshow.h>
#pragma comment(lib, "Strmiids.lib")
SoundPlayer::SoundPlayer(std::wstring filePath) {
HRESULT hr;
hr = CoCreateInstance(
CLSID_FilterGraph,
NULL,
CLSCTX_INPROC_SERVER,
IID_IGraphBuilder,
(void **) &_graphBuilder);
if (FAILED(hr)) {
OutputDebugString(L"gb failed");
}
hr = _graphBuilder->QueryInterface(IID_IMediaControl, (void **) &_mediaCtrl);
hr = _graphBuilder->QueryInterface(IID_IMediaEventEx, (void **) &_mediaEv);
hr = _graphBuilder->QueryInterface(IID_IMediaSeeking, (void **) &_mediaSeek);
hr = _graphBuilder->RenderFile(filePath.c_str(), NULL);
_thread = std::thread(&SoundPlayer::PlayerThread, this);
}
SoundPlayer::~SoundPlayer() {
_mediaSeek->Release();
_mediaEv->Release();
_mediaCtrl->Release();
_graphBuilder->Release();
}
bool SoundPlayer::Play() {
if (_playing) {
return false;
}
_mutex.lock();
_playing = true;
_cv.notify_all();
_mutex.unlock();
return true;
}
void SoundPlayer::PlayerThread() {
long evCode;
REFERENCE_TIME start = 0;
std::unique_lock<std::mutex> lock(_mutex);
while (true) {
_cv.wait(lock);
if (!_playing) {
continue;
}
_mediaCtrl->Run();
_mediaEv->WaitForCompletion(INFINITE, &evCode);
_mediaCtrl->Pause();
_mediaSeek->SetPositions(
&start, AM_SEEKING_AbsolutePositioning,
NULL, AM_SEEKING_NoPositioning);
_playing = false;
}
}<commit_msg>Lock doesn't need to be acquired to call notify<commit_after>#include "SoundPlayer.h"
#include <Windows.h>
#include <dshow.h>
#pragma comment(lib, "Strmiids.lib")
SoundPlayer::SoundPlayer(std::wstring filePath) {
HRESULT hr;
hr = CoCreateInstance(
CLSID_FilterGraph,
NULL,
CLSCTX_INPROC_SERVER,
IID_IGraphBuilder,
(void **) &_graphBuilder);
if (FAILED(hr)) {
OutputDebugString(L"gb failed");
}
hr = _graphBuilder->QueryInterface(IID_IMediaControl, (void **) &_mediaCtrl);
hr = _graphBuilder->QueryInterface(IID_IMediaEventEx, (void **) &_mediaEv);
hr = _graphBuilder->QueryInterface(IID_IMediaSeeking, (void **) &_mediaSeek);
hr = _graphBuilder->RenderFile(filePath.c_str(), NULL);
_thread = std::thread(&SoundPlayer::PlayerThread, this);
}
SoundPlayer::~SoundPlayer() {
_mediaSeek->Release();
_mediaEv->Release();
_mediaCtrl->Release();
_graphBuilder->Release();
}
bool SoundPlayer::Play() {
bool alreadyPlaying;
_mutex.lock();
alreadyPlaying = _playing;
_playing = true;
_mutex.unlock();
_cv.notify_all();
return alreadyPlaying;
}
void SoundPlayer::PlayerThread() {
long evCode;
REFERENCE_TIME start = 0;
std::unique_lock<std::mutex> lock(_mutex);
while (true) {
_cv.wait(lock);
if (!_playing) {
continue;
}
_mediaCtrl->Run();
_mediaEv->WaitForCompletion(INFINITE, &evCode);
_mediaCtrl->Pause();
_mediaSeek->SetPositions(
&start, AM_SEEKING_AbsolutePositioning,
NULL, AM_SEEKING_NoPositioning);
_playing = false;
}
}<|endoftext|>
|
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
using namespace cv;
using namespace std;
TEST(MultiBandBlender, CanBlendTwoImages)
{
Mat image1 = imread(string(cvtest::TS::ptr()->get_data_path()) + "cv/shared/baboon.jpg");
Mat image2 = imread(string(cvtest::TS::ptr()->get_data_path()) + "cv/shared/lena.jpg");
EXPECT_EQ(image1.rows, image2.rows); EXPECT_EQ(image1.cols, image2.cols);
Mat image1s, image2s;
image1.convertTo(image1s, CV_16S);
image2.convertTo(image2s, CV_16S);
Mat mask1(image1s.size(), CV_8U);
mask1(Rect(0, 0, mask1.cols/2, mask1.rows)).setTo(255);
mask1(Rect(mask1.cols/2, 0, mask1.cols - mask1.cols/2, mask1.rows)).setTo(0);
Mat mask2(image2s.size(), CV_8U);
mask2(Rect(0, 0, mask2.cols/2, mask2.rows)).setTo(0);
mask2(Rect(mask2.cols/2, 0, mask2.cols - mask2.cols/2, mask2.rows)).setTo(255);
detail::MultiBandBlender blender(false, 5);
blender.prepare(Rect(0, 0, max(image1s.cols, image2s.cols), max(image1s.rows, image2s.rows)));
blender.feed(image1s, mask1, Point(0,0));
blender.feed(image2s, mask2, Point(0,0));
Mat result_s, result_mask;
blender.blend(result_s, result_mask);
Mat result; result_s.convertTo(result, CV_8U);
Mat expected = imread(string(cvtest::TS::ptr()->get_data_path()) + "stitching/baboon_lena.png");
double error = norm(expected, result, NORM_L2) / expected.size().area();
ASSERT_LT(error, 1e-3);
}
<commit_msg>Updated the multi-band blending test<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
using namespace cv;
using namespace std;
TEST(MultiBandBlender, CanBlendTwoImages)
{
Mat image1 = imread(string(cvtest::TS::ptr()->get_data_path()) + "cv/shared/baboon.jpg");
Mat image2 = imread(string(cvtest::TS::ptr()->get_data_path()) + "cv/shared/lena.jpg");
ASSERT_EQ(image1.rows, image2.rows); ASSERT_EQ(image1.cols, image2.cols);
Mat image1s, image2s;
image1.convertTo(image1s, CV_16S);
image2.convertTo(image2s, CV_16S);
Mat mask1(image1s.size(), CV_8U);
mask1(Rect(0, 0, mask1.cols/2, mask1.rows)).setTo(255);
mask1(Rect(mask1.cols/2, 0, mask1.cols - mask1.cols/2, mask1.rows)).setTo(0);
Mat mask2(image2s.size(), CV_8U);
mask2(Rect(0, 0, mask2.cols/2, mask2.rows)).setTo(0);
mask2(Rect(mask2.cols/2, 0, mask2.cols - mask2.cols/2, mask2.rows)).setTo(255);
detail::MultiBandBlender blender(false, 5);
blender.prepare(Rect(0, 0, max(image1s.cols, image2s.cols), max(image1s.rows, image2s.rows)));
blender.feed(image1s, mask1, Point(0,0));
blender.feed(image2s, mask2, Point(0,0));
Mat result_s, result_mask;
blender.blend(result_s, result_mask);
Mat result; result_s.convertTo(result, CV_8U);
Mat expected = imread(string(cvtest::TS::ptr()->get_data_path()) + "stitching/baboon_lena.png");
double rmsErr = norm(expected, result, NORM_L2) / sqrt(expected.size().area());
ASSERT_LT(rmsErr, 1e-3);
}
<|endoftext|>
|
<commit_before>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "../ui_module.h"
namespace ti {
void menu_callback(gpointer data);
GtkMenuItemImpl::GtkMenuItemImpl()
: parent(NULL)
{
}
void GtkMenuItemImpl::SetParent(GtkMenuItemImpl* parent)
{
this->parent = parent;
}
GtkMenuItemImpl* GtkMenuItemImpl::GetParent()
{
return this->parent;
}
SharedValue GtkMenuItemImpl::AddSeparator()
{
GtkMenuItemImpl* item = new GtkMenuItemImpl();
item->MakeSeparator();
return this->AppendItem(item);
}
SharedValue GtkMenuItemImpl::AddItem(SharedValue label,
SharedValue callback,
SharedValue icon_url)
{
GtkMenuItemImpl* item = new GtkMenuItemImpl();
item->MakeItem(label, callback, icon_url);
return this->AppendItem(item);
}
SharedValue GtkMenuItemImpl::AddSubMenu(SharedValue label,
SharedValue icon_url)
{
GtkMenuItemImpl* item = new GtkMenuItemImpl();
item->MakeSubMenu(label, icon_url);
return this->AppendItem(item);
}
SharedValue GtkMenuItemImpl::AppendItem(GtkMenuItemImpl* item)
{
item->SetParent(this);
this->children.push_back(item);
return MenuItem::AppendItem(item);
}
GtkWidget* GtkMenuItemImpl::GetMenu()
{
if (this->parent == NULL) // top-level
{
MenuPieces* pieces = this->Realize(false);
return pieces->menu;
}
else
{
// For now we do not support using a submenu as a menu,
// as that makes determining parent-child relationships
// really hard, so just return NULL and check above.
return NULL;
}
}
GtkWidget* GtkMenuItemImpl::GetMenuBar()
{
if (this->parent == NULL) // top level
{
MenuPieces* pieces = this->Realize(true);
return pieces->menu;
}
else
{
// For now we do not support using a submenu as a menu,
// as that makes determining parent-child relationships
// really hard, so just return NULL and check above.
return NULL;
}
}
void GtkMenuItemImpl::AddChildrenTo(GtkWidget* menu)
{
std::vector<GtkMenuItemImpl*>::iterator c;
for (c = this->children.begin(); c != this->children.end(); c++)
{
MenuPieces* pieces = new MenuPieces();
(*c)->MakeMenuPieces(*pieces);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), pieces->item);
gtk_widget_show(pieces->item);
if (this->IsSubMenu() || this->parent == NULL)
{
(*c)->AddChildrenTo(pieces->menu);
}
delete pieces;
}
}
void GtkMenuItemImpl::ClearRealization(GtkWidget *parent_menu)
{
std::vector<MenuPieces*>::iterator i;
std::vector<GtkMenuItemImpl*>::iterator c;
// Find the instance which is contained in parent_menu or,
// if we are the root, find the instance which uses this
// menu to contain it's children.
for (i = this->instances.begin(); i != this->instances.end(); i++)
{
if ((*i)->parent_menu == parent_menu
|| (this->parent == NULL && (*i)->menu == parent_menu))
break;
}
// Could not find an instance which uses the menu.
if (i == this->instances.end()) return;
// Erase all children which use
// the sub-menu as their parent.
for (c = this->children.begin(); c != this->children.end(); c++)
{
(*c)->ClearRealization((*i)->menu);
}
this->instances.erase(i); // Erase the instance
}
GtkMenuItemImpl::MenuPieces* GtkMenuItemImpl::Realize(bool is_menu_bar)
{
MenuPieces* pieces = new MenuPieces();
if (this->parent == NULL) // top-level
{
if (is_menu_bar)
pieces->menu = gtk_menu_bar_new();
else
pieces->menu = gtk_menu_new();
}
else
{
this->MakeMenuPieces(*pieces);
}
/* Realize this widget's children */
if (this->IsSubMenu() || this->parent == NULL)
{
std::vector<GtkMenuItemImpl*>::iterator i = this->children.begin();
while (i != this->children.end())
{
MenuPieces* child_pieces = (*i)->Realize(false);
child_pieces->parent_menu = pieces->menu;
gtk_menu_shell_append(
GTK_MENU_SHELL(pieces->menu),
child_pieces->item);
gtk_widget_show(child_pieces->item);
i++;
}
}
this->instances.push_back(pieces);
return pieces;
}
void GtkMenuItemImpl::MakeMenuPieces(MenuPieces& pieces)
{
const char* label = this->GetLabel();
const char* icon_url = this->GetIconURL();
SharedString icon_path = UIModule::GetResourcePath(icon_url);
SharedValue callback_val = this->RawGet("callback");
if (this->IsSeparator())
{
pieces.item = gtk_separator_menu_item_new();
}
else if (icon_path.isNull())
{
pieces.item = gtk_menu_item_new_with_label(label);
}
else
{
pieces.item = gtk_image_menu_item_new_with_label(label);
GtkWidget* image = gtk_image_new_from_file(icon_path->c_str());
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(pieces.item), image);
}
if (callback_val->IsMethod())
{
// The callback is stored as a property of this MenuItem
// so we do not need to worry about the pointer being freed
// out from under us. At some point, in threaded code we will
// have to protect it with a mutex though, in the case that
// the callback is fired after it has been reassigned.
BoundMethod* cb = callback_val->ToMethod().get();
g_signal_connect_swapped(
G_OBJECT (pieces.item), "activate",
G_CALLBACK(menu_callback),
(gpointer) cb);
}
if (this->IsSubMenu())
{
pieces.menu = gtk_menu_new();
gtk_menu_item_set_submenu(GTK_MENU_ITEM(pieces.item), pieces.menu);
}
}
/* Crazy mutations below */
void GtkMenuItemImpl::Enable()
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL)
gtk_widget_set_sensitive(w, TRUE);
i++;
}
}
void GtkMenuItemImpl::Disable()
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL)
gtk_widget_set_sensitive(w, FALSE);
i++;
}
}
void GtkMenuItemImpl::SetLabel(std::string label)
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL)
{
GtkWidget *menu_label = gtk_bin_get_child(GTK_BIN(w));
gtk_label_set_text(GTK_LABEL(menu_label), label.c_str());
}
i++;
}
}
void GtkMenuItemImpl::SetIcon(std::string icon_url)
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
SharedString icon_path = UIModule::GetResourcePath(icon_url.c_str());
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL && G_TYPE_FROM_INSTANCE(w) == GTK_TYPE_IMAGE_MENU_ITEM)
{
GtkWidget* image = gtk_image_new_from_file(icon_path->c_str());
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(w), image);
}
i++;
}
}
/* Le callback */
void menu_callback(gpointer data)
{
BoundMethod* cb = (BoundMethod*) data;
// TODO: Handle exceptions in some way
try
{
ValueList args;
cb->Call(args);
}
catch(...)
{
std::cout << "Menu callback failed" << std::endl;
}
}
}
<commit_msg>rename MenuItem::AppendItem to MenuItem::CreateSharedObject<commit_after>/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "../ui_module.h"
namespace ti {
void menu_callback(gpointer data);
GtkMenuItemImpl::GtkMenuItemImpl()
: parent(NULL)
{
}
void GtkMenuItemImpl::SetParent(GtkMenuItemImpl* parent)
{
this->parent = parent;
}
GtkMenuItemImpl* GtkMenuItemImpl::GetParent()
{
return this->parent;
}
SharedValue GtkMenuItemImpl::AddSeparator()
{
GtkMenuItemImpl* item = new GtkMenuItemImpl();
item->MakeSeparator();
return this->AppendItem(item);
}
SharedValue GtkMenuItemImpl::AddItem(SharedValue label,
SharedValue callback,
SharedValue icon_url)
{
GtkMenuItemImpl* item = new GtkMenuItemImpl();
item->MakeItem(label, callback, icon_url);
return this->AppendItem(item);
}
SharedValue GtkMenuItemImpl::AddSubMenu(SharedValue label,
SharedValue icon_url)
{
GtkMenuItemImpl* item = new GtkMenuItemImpl();
item->MakeSubMenu(label, icon_url);
return this->AppendItem(item);
}
SharedValue GtkMenuItemImpl::AppendItem(GtkMenuItemImpl* item)
{
item->SetParent(this);
this->children.push_back(item);
return MenuItem::CreateSharedObject(item);
}
GtkWidget* GtkMenuItemImpl::GetMenu()
{
if (this->parent == NULL) // top-level
{
MenuPieces* pieces = this->Realize(false);
return pieces->menu;
}
else
{
// For now we do not support using a submenu as a menu,
// as that makes determining parent-child relationships
// really hard, so just return NULL and check above.
return NULL;
}
}
GtkWidget* GtkMenuItemImpl::GetMenuBar()
{
if (this->parent == NULL) // top level
{
MenuPieces* pieces = this->Realize(true);
return pieces->menu;
}
else
{
// For now we do not support using a submenu as a menu,
// as that makes determining parent-child relationships
// really hard, so just return NULL and check above.
return NULL;
}
}
void GtkMenuItemImpl::AddChildrenTo(GtkWidget* menu)
{
std::vector<GtkMenuItemImpl*>::iterator c;
for (c = this->children.begin(); c != this->children.end(); c++)
{
MenuPieces* pieces = new MenuPieces();
(*c)->MakeMenuPieces(*pieces);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), pieces->item);
gtk_widget_show(pieces->item);
if (this->IsSubMenu() || this->parent == NULL)
{
(*c)->AddChildrenTo(pieces->menu);
}
delete pieces;
}
}
void GtkMenuItemImpl::ClearRealization(GtkWidget *parent_menu)
{
std::vector<MenuPieces*>::iterator i;
std::vector<GtkMenuItemImpl*>::iterator c;
// Find the instance which is contained in parent_menu or,
// if we are the root, find the instance which uses this
// menu to contain it's children.
for (i = this->instances.begin(); i != this->instances.end(); i++)
{
if ((*i)->parent_menu == parent_menu
|| (this->parent == NULL && (*i)->menu == parent_menu))
break;
}
// Could not find an instance which uses the menu.
if (i == this->instances.end()) return;
// Erase all children which use
// the sub-menu as their parent.
for (c = this->children.begin(); c != this->children.end(); c++)
{
(*c)->ClearRealization((*i)->menu);
}
this->instances.erase(i); // Erase the instance
}
GtkMenuItemImpl::MenuPieces* GtkMenuItemImpl::Realize(bool is_menu_bar)
{
MenuPieces* pieces = new MenuPieces();
if (this->parent == NULL) // top-level
{
if (is_menu_bar)
pieces->menu = gtk_menu_bar_new();
else
pieces->menu = gtk_menu_new();
}
else
{
this->MakeMenuPieces(*pieces);
}
/* Realize this widget's children */
if (this->IsSubMenu() || this->parent == NULL)
{
std::vector<GtkMenuItemImpl*>::iterator i = this->children.begin();
while (i != this->children.end())
{
MenuPieces* child_pieces = (*i)->Realize(false);
child_pieces->parent_menu = pieces->menu;
gtk_menu_shell_append(
GTK_MENU_SHELL(pieces->menu),
child_pieces->item);
gtk_widget_show(child_pieces->item);
i++;
}
}
this->instances.push_back(pieces);
return pieces;
}
void GtkMenuItemImpl::MakeMenuPieces(MenuPieces& pieces)
{
const char* label = this->GetLabel();
const char* icon_url = this->GetIconURL();
SharedString icon_path = UIModule::GetResourcePath(icon_url);
SharedValue callback_val = this->RawGet("callback");
if (this->IsSeparator())
{
pieces.item = gtk_separator_menu_item_new();
}
else if (icon_path.isNull())
{
pieces.item = gtk_menu_item_new_with_label(label);
}
else
{
pieces.item = gtk_image_menu_item_new_with_label(label);
GtkWidget* image = gtk_image_new_from_file(icon_path->c_str());
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(pieces.item), image);
}
if (callback_val->IsMethod())
{
// The callback is stored as a property of this MenuItem
// so we do not need to worry about the pointer being freed
// out from under us. At some point, in threaded code we will
// have to protect it with a mutex though, in the case that
// the callback is fired after it has been reassigned.
BoundMethod* cb = callback_val->ToMethod().get();
g_signal_connect_swapped(
G_OBJECT (pieces.item), "activate",
G_CALLBACK(menu_callback),
(gpointer) cb);
}
if (this->IsSubMenu())
{
pieces.menu = gtk_menu_new();
gtk_menu_item_set_submenu(GTK_MENU_ITEM(pieces.item), pieces.menu);
}
}
/* Crazy mutations below */
void GtkMenuItemImpl::Enable()
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL)
gtk_widget_set_sensitive(w, TRUE);
i++;
}
}
void GtkMenuItemImpl::Disable()
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL)
gtk_widget_set_sensitive(w, FALSE);
i++;
}
}
void GtkMenuItemImpl::SetLabel(std::string label)
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL)
{
GtkWidget *menu_label = gtk_bin_get_child(GTK_BIN(w));
gtk_label_set_text(GTK_LABEL(menu_label), label.c_str());
}
i++;
}
}
void GtkMenuItemImpl::SetIcon(std::string icon_url)
{
std::vector<MenuPieces*>::iterator i = this->instances.begin();
SharedString icon_path = UIModule::GetResourcePath(icon_url.c_str());
while (i != this->instances.end())
{
GtkWidget *w = (*i)->item;
if (w != NULL && G_TYPE_FROM_INSTANCE(w) == GTK_TYPE_IMAGE_MENU_ITEM)
{
GtkWidget* image = gtk_image_new_from_file(icon_path->c_str());
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(w), image);
}
i++;
}
}
/* Le callback */
void menu_callback(gpointer data)
{
BoundMethod* cb = (BoundMethod*) data;
// TODO: Handle exceptions in some way
try
{
ValueList args;
cb->Call(args);
}
catch(...)
{
std::cout << "Menu callback failed" << std::endl;
}
}
}
<|endoftext|>
|
<commit_before> // Time: O(c * n + n), n is length of string, c is count of "++"
// Space: O(1), no extra space excluding that result requires at most O(n^2) space
class Solution {
public:
vector<string> generatePossibleNextMoves(string s) {
vector<string> res;
int n = s.length();
for (int i = 0; i < n - 1; ++i) { // O(n) times
if (s[i] == '+') {
for (;i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) times
s[i] = s[i + 1] = '-';
res.emplace_back(s); // O(n) to copy a string
s[i] = s[i + 1] = '+';
}
}
}
return res;
}
};
<commit_msg>Update flip-game.cpp<commit_after> // Time: O(c * n + n), n is length of string, c is count of "++"
// Space: O(1), no extra space excluding the result which requires at most O(n^2) space
class Solution {
public:
vector<string> generatePossibleNextMoves(string s) {
vector<string> res;
int n = s.length();
for (int i = 0; i < n - 1; ++i) { // O(n) time
if (s[i] == '+') {
for (;i < n - 1 && s[i + 1] == '+'; ++i) { // O(c) time
s[i] = s[i + 1] = '-';
res.emplace_back(s); // O(n) to copy a string
s[i] = s[i + 1] = '+';
}
}
}
return res;
}
};
<|endoftext|>
|
<commit_before>#include <iostream>
#include <arpa/inet.h>
#include "radix_tree.hpp"
class rtentry {
public:
in_addr_t addr;
int prefix_len;
rtentry() : addr(0), prefix_len(0) { }
in_addr_t operator[] (int n) const
{
in_addr_t bit;
if (addr & (0x80000000 >> n))
bit = 1;
else
bit = 0;
return bit;
}
bool operator== (const rtentry &rhs) const
{
return prefix_len == rhs.prefix_len && addr == rhs.addr;
}
bool operator< (const rtentry &rhs) const
{
if (prefix_len == rhs.prefix_len) {
return addr < rhs.addr;
} else {
if (addr == rhs.addr) {
return prefix_len < rhs.prefix_len;
} else {
return addr < rhs.addr;
}
}
}
};
rtentry
radix_substr(const rtentry &entry, int begin, int num)
{
rtentry ret;
in_addr_t mask;
int shift;
mask = (1 << num) - 1;
mask <<= 32 - num - begin;
ret.addr = (entry.addr & mask) << begin;
ret.prefix_len = num;
return ret;
}
rtentry
radix_join(const rtentry &entry1, const rtentry &entry2)
{
rtentry ret;
ret.addr = entry1.addr;
ret.addr |= entry2.addr >> entry1.prefix_len;
ret.prefix_len = entry1.prefix_len + entry2.prefix_len;
return ret;
}
int
radix_length(const rtentry &entry)
{
return entry.prefix_len;
}
radix_tree<rtentry, in_addr> rttable;
void
add_rtentry(const char *network, int prefix_len, const char *dst)
{
rtentry entry;
in_addr nw_addr;
in_addr dst_addr;
in_addr_t mask;
int shift;
if (prefix_len > 32)
return;
if (inet_aton(network, &nw_addr) == 0)
return;
if (inet_aton(dst, &dst_addr) == 0)
return;
shift = 32 - prefix_len;
if (shift >= 32)
mask = 0;
else
mask = ~((1 << shift) - 1);
entry.addr = ntohl(nw_addr.s_addr) & mask;
entry.prefix_len = prefix_len;
rttable[entry] = dst_addr;
}
void
find_route(const char *dst)
{
in_addr addr_dst;
rtentry entry;
if (inet_aton(dst, &addr_dst) == 0) {
std::cout << "invalid address: dst = " << dst
<< std::endl;
return;
}
entry.addr = ntohl(addr_dst.s_addr);
entry.prefix_len = 32;
radix_tree<rtentry, in_addr>::iterator it;
it = rttable.longest_match(entry);
if (it == rttable.end()) {
std::cout << "no route to " << dst << std::endl;
return;
}
char *addr = inet_ntoa(it->second);
std::cout << dst << " -> " << addr << std::endl;
}
int
main(int argc, char *argv)
{
// add entries to the routing table
add_rtentry("0.0.0.0", 0, "192.168.0.1"); // default route
add_rtentry("10.0.0.0", 8, "192.168.0.2");
add_rtentry("172.16.0.0", 16, "192.168.0.3");
add_rtentry("172.17.0.0", 16, "192.168.0.4");
add_rtentry("172.18.0.0", 16, "192.168.0.5");
add_rtentry("172.19.0.0", 16, "192.168.0.6");
add_rtentry("192.168.1.0", 24, "192.168.0.7");
add_rtentry("192.168.2.0", 24, "192.168.0.8");
add_rtentry("192.168.3.0", 24, "192.168.0.9");
add_rtentry("192.168.4.0", 24, "192.168.0.10");
// lookup the routing table
find_route("10.1.1.1");
find_route("172.16.0.3");
find_route("172.17.0.5");
find_route("172.18.10.5");
find_route("172.19.200.70");
find_route("192.168.1.10");
find_route("192.168.2.220");
find_route("192.168.3.80");
find_route("192.168.4.100");
find_route("172.20.0.1");
return true;
}
<commit_msg>fixed operator< ()<commit_after>#include <iostream>
#include <arpa/inet.h>
#include "radix_tree.hpp"
class rtentry {
public:
in_addr_t addr;
int prefix_len;
rtentry() : addr(0), prefix_len(0) { }
in_addr_t operator[] (int n) const
{
in_addr_t bit;
if (addr & (0x80000000 >> n))
bit = 1;
else
bit = 0;
return bit;
}
bool operator== (const rtentry &rhs) const
{
return prefix_len == rhs.prefix_len && addr == rhs.addr;
}
bool operator< (const rtentry &rhs) const
{
if (addr == rhs.addr) {
return prefix_len < rhs.prefix_len;
} else {
return addr < rhs.addr;
}
}
};
rtentry
radix_substr(const rtentry &entry, int begin, int num)
{
rtentry ret;
in_addr_t mask;
int shift;
mask = (1 << num) - 1;
mask <<= 32 - num - begin;
ret.addr = (entry.addr & mask) << begin;
ret.prefix_len = num;
return ret;
}
rtentry
radix_join(const rtentry &entry1, const rtentry &entry2)
{
rtentry ret;
ret.addr = entry1.addr;
ret.addr |= entry2.addr >> entry1.prefix_len;
ret.prefix_len = entry1.prefix_len + entry2.prefix_len;
return ret;
}
int
radix_length(const rtentry &entry)
{
return entry.prefix_len;
}
radix_tree<rtentry, in_addr> rttable;
void
add_rtentry(const char *network, int prefix_len, const char *dst)
{
rtentry entry;
in_addr nw_addr;
in_addr dst_addr;
in_addr_t mask;
int shift;
if (prefix_len > 32)
return;
if (inet_aton(network, &nw_addr) == 0)
return;
if (inet_aton(dst, &dst_addr) == 0)
return;
shift = 32 - prefix_len;
if (shift >= 32)
mask = 0;
else
mask = ~((1 << shift) - 1);
entry.addr = ntohl(nw_addr.s_addr) & mask;
entry.prefix_len = prefix_len;
rttable[entry] = dst_addr;
}
void
find_route(const char *dst)
{
in_addr addr_dst;
rtentry entry;
if (inet_aton(dst, &addr_dst) == 0) {
std::cout << "invalid address: dst = " << dst
<< std::endl;
return;
}
entry.addr = ntohl(addr_dst.s_addr);
entry.prefix_len = 32;
radix_tree<rtentry, in_addr>::iterator it;
it = rttable.longest_match(entry);
if (it == rttable.end()) {
std::cout << "no route to " << dst << std::endl;
return;
}
char *addr = inet_ntoa(it->second);
std::cout << dst << " -> " << addr << std::endl;
}
int
main(int argc, char *argv)
{
// add entries to the routing table
add_rtentry("0.0.0.0", 0, "192.168.0.1"); // default route
add_rtentry("10.0.0.0", 8, "192.168.0.2");
add_rtentry("172.16.0.0", 16, "192.168.0.3");
add_rtentry("172.17.0.0", 16, "192.168.0.4");
add_rtentry("172.18.0.0", 16, "192.168.0.5");
add_rtentry("172.19.0.0", 16, "192.168.0.6");
add_rtentry("192.168.1.0", 24, "192.168.0.7");
add_rtentry("192.168.2.0", 24, "192.168.0.8");
add_rtentry("192.168.3.0", 24, "192.168.0.9");
add_rtentry("192.168.4.0", 24, "192.168.0.10");
// lookup the routing table
find_route("10.1.1.1");
find_route("172.16.0.3");
find_route("172.17.0.5");
find_route("172.18.10.5");
find_route("172.19.200.70");
find_route("192.168.1.10");
find_route("192.168.2.220");
find_route("192.168.3.80");
find_route("192.168.4.100");
find_route("172.20.0.1");
return true;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BConnection.cxx,v $
* $Revision: 1.26 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include <cppuhelper/typeprovider.hxx>
#include "adabas/BConnection.hxx"
#include "adabas/BDriver.hxx"
#include "adabas/BCatalog.hxx"
#include "odbc/OFunctions.hxx"
#include "odbc/OTools.hxx"
#ifndef _CONNECTIVITY_ODBC_ODATABASEMETADATA_HXX_
#include "adabas/BDatabaseMetaData.hxx"
#endif
#include "adabas/BStatement.hxx"
#include "adabas/BPreparedStatement.hxx"
#include <com/sun/star/lang/DisposedException.hpp>
#include <connectivity/dbcharset.hxx>
#include "connectivity/sqliterator.hxx"
#include <connectivity/sqlparse.hxx>
#include <string.h>
using namespace connectivity::adabas;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//------------------------------------------------------------------------------
namespace starlang = ::com::sun::star::lang;
// --------------------------------------------------------------------------------
OAdabasConnection::OAdabasConnection(const SQLHANDLE _pDriverHandle, connectivity::odbc::ODBCDriver* _pDriver)
: OConnection_BASE2(_pDriverHandle,_pDriver)
{
m_bUseOldDateFormat = sal_True;
}
//-----------------------------------------------------------------------------
SQLRETURN OAdabasConnection::Construct( const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException)
{
::osl::MutexGuard aGuard( m_aMutex );
m_aConnectionHandle = SQL_NULL_HANDLE;
setURL(url);
setConnectionInfo(info);
// Connection allozieren
N3SQLAllocHandle(SQL_HANDLE_DBC,m_pDriverHandleCopy,&m_aConnectionHandle);
if(m_aConnectionHandle == SQL_NULL_HANDLE)
throw SQLException();
const PropertyValue *pBegin = info.getConstArray();
const PropertyValue *pEnd = pBegin + info.getLength();
::rtl::OUString sHostName;
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aDSN(url.copy(nLen+1)),aUID,aPWD;
sal_Int32 nTimeout = 20;
for(;pBegin != pEnd;++pBegin)
{
if ( !pBegin->Name.compareToAscii("Timeout") )
pBegin->Value >>= nTimeout;
else if(!pBegin->Name.compareToAscii("user"))
pBegin->Value >>= aUID;
else if(!pBegin->Name.compareToAscii("password"))
pBegin->Value >>= aPWD;
else if(!pBegin->Name.compareToAscii("HostName"))
pBegin->Value >>= sHostName;
else if(0 == pBegin->Name.compareToAscii("CharSet"))
{
::rtl::OUString sIanaName;
OSL_VERIFY( pBegin->Value >>= sIanaName );
::dbtools::OCharsetMap aLookupIanaName;
::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(sIanaName, ::dbtools::OCharsetMap::IANA());
if (aLookup != aLookupIanaName.end())
m_nTextEncoding = (*aLookup).getEncoding();
else
m_nTextEncoding = RTL_TEXTENCODING_DONTKNOW;
if(m_nTextEncoding == RTL_TEXTENCODING_DONTKNOW)
m_nTextEncoding = osl_getThreadTextEncoding();
}
}
m_sUser = aUID;
if ( sHostName.getLength() )
aDSN = sHostName + ':' + aDSN;
SQLRETURN nSQLRETURN = openConnectionWithAuth(aDSN,nTimeout, aUID,aPWD);
return nSQLRETURN;
}
//-----------------------------------------------------------------------------
SQLRETURN OAdabasConnection::openConnectionWithAuth(const ::rtl::OUString& aConnectStr,sal_Int32 nTimeOut, const ::rtl::OUString& _uid,const ::rtl::OUString& _pwd)
{
if (m_aConnectionHandle == SQL_NULL_HANDLE)
return -1;
SQLRETURN nSQLRETURN = 0;
SDB_ODBC_CHAR szDSN[4096];
SDB_ODBC_CHAR szUID[20];
SDB_ODBC_CHAR szPWD[20];
memset(szDSN,'\0',4096);
memset(szUID,'\0',20);
memset(szPWD,'\0',20);
::rtl::OString aConStr(::rtl::OUStringToOString(aConnectStr,getTextEncoding()));
::rtl::OString aUID(::rtl::OUStringToOString(_uid,getTextEncoding()));
::rtl::OString aPWD(::rtl::OUStringToOString(_pwd,getTextEncoding()));
memcpy(szDSN, (SDB_ODBC_CHAR*) aConStr.getStr(), ::std::min<sal_Int32>((sal_Int32)2048,aConStr.getLength()));
memcpy(szUID, (SDB_ODBC_CHAR*) aUID.getStr(), ::std::min<sal_Int32>((sal_Int32)20,aUID.getLength()));
memcpy(szPWD, (SDB_ODBC_CHAR*) aPWD.getStr(), ::std::min<sal_Int32>((sal_Int32)20,aPWD.getLength()));
N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_LOGIN_TIMEOUT,(SQLPOINTER)nTimeOut,SQL_IS_INTEGER);
// Verbindung aufbauen
nSQLRETURN = N3SQLConnect(m_aConnectionHandle,
szDSN,
(SQLSMALLINT) ::std::min<sal_Int32>((sal_Int32)2048,aConStr.getLength()),
szUID,
(SQLSMALLINT) ::std::min<sal_Int32>((sal_Int32)20,aUID.getLength()),
szPWD,
(SQLSMALLINT) ::std::min<sal_Int32>((sal_Int32)20,aPWD.getLength()));
if (nSQLRETURN == SQL_ERROR || nSQLRETURN == SQL_NO_DATA)
return nSQLRETURN;
m_bClosed = sal_False;
// autocoomit ist immer default
N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_AUTOCOMMIT,(SQLPOINTER)SQL_AUTOCOMMIT_ON,SQL_IS_INTEGER);
return nSQLRETURN;
}
//------------------------------------------------------------------------------
void OAdabasConnection::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
Reference< XTablesSupplier > xTableSupplier(m_xCatalog);
::comphelper::disposeComponent(xTableSupplier);
m_xCatalog = WeakReference< XTablesSupplier >();
OConnection_BASE2::disposing();
}
//------------------------------------------------------------------------------
Reference< XTablesSupplier > OAdabasConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if(!xTab.is())
{
xTab = new OAdabasCatalog(m_aConnectionHandle,this);
m_xCatalog = xTab;
}
return xTab;
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OAdabasConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE2::rBHelper.bDisposed);
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new OAdabasDatabaseMetaData(m_aConnectionHandle,this);
m_xMetaData = xMetaData;
}
return xMetaData;
}
//------------------------------------------------------------------------------
sal_Bool OAdabasConnection::isStarted()
{
return sal_True;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OAdabasConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE2::rBHelper.bDisposed);
Reference< XStatement > xReturn = new OAdabasStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OAdabasConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE2::rBHelper.bDisposed);
if(m_aTypeInfo.empty())
buildTypeInfo();
Reference< XPreparedStatement > xReturn = new OAdabasPreparedStatement(this,m_aTypeInfo,sql);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// -----------------------------------------------------------------------------
sal_Int64 SAL_CALL OAdabasConnection::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rId ) throw (::com::sun::star::uno::RuntimeException)
{
return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) )
? reinterpret_cast< sal_Int64 >( this )
: OConnection_BASE2::getSomething(rId);
}
// -----------------------------------------------------------------------------
Sequence< sal_Int8 > OAdabasConnection::getUnoTunnelImplementationId()
{
static ::cppu::OImplementationId * pId = 0;
if (! pId)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (! pId)
{
static ::cppu::OImplementationId aId;
pId = &aId;
}
}
return pId->getImplementationId();
}
// -----------------------------------------------------------------------------
::connectivity::odbc::OConnection* OAdabasConnection::cloneConnection()
{
return new OAdabasConnection(m_pDriverHandleCopy,m_pDriver);
}
// -----------------------------------------------------------------------------
::vos::ORef<OSQLColumns> OAdabasConnection::createSelectColumns(const ::rtl::OUString& _rSql)
{
::vos::ORef<OSQLColumns> aRet;
OSQLParser aParser(getDriver()->getORB());
::rtl::OUString sErrorMessage;
OSQLParseNode* pNode = aParser.parseTree(sErrorMessage,_rSql);
if(pNode)
{
Reference< XTablesSupplier> xCata = createCatalog();
OSQLParseTreeIterator aParseIter(this, xCata->getTables(),
aParser, pNode);
aParseIter.traverseAll();
aRet = aParseIter.getSelectColumns();
}
return aRet;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba31a (1.26.32); FILE MERGED 2008/07/04 15:21:24 oj 1.26.32.1: #i89558# remove unused code<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BConnection.cxx,v $
* $Revision: 1.27 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include <cppuhelper/typeprovider.hxx>
#include "adabas/BConnection.hxx"
#include "adabas/BDriver.hxx"
#include "adabas/BCatalog.hxx"
#include "odbc/OFunctions.hxx"
#include "odbc/OTools.hxx"
#ifndef _CONNECTIVITY_ODBC_ODATABASEMETADATA_HXX_
#include "adabas/BDatabaseMetaData.hxx"
#endif
#include "adabas/BStatement.hxx"
#include "adabas/BPreparedStatement.hxx"
#include <com/sun/star/lang/DisposedException.hpp>
#include <connectivity/dbcharset.hxx>
#include "connectivity/sqliterator.hxx"
#include <connectivity/sqlparse.hxx>
#include <string.h>
using namespace connectivity::adabas;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
//------------------------------------------------------------------------------
namespace starlang = ::com::sun::star::lang;
// --------------------------------------------------------------------------------
OAdabasConnection::OAdabasConnection(const SQLHANDLE _pDriverHandle, connectivity::odbc::ODBCDriver* _pDriver)
: OConnection_BASE2(_pDriverHandle,_pDriver)
{
m_bUseOldDateFormat = sal_True;
}
//-----------------------------------------------------------------------------
SQLRETURN OAdabasConnection::Construct( const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException)
{
::osl::MutexGuard aGuard( m_aMutex );
m_aConnectionHandle = SQL_NULL_HANDLE;
setURL(url);
setConnectionInfo(info);
// Connection allozieren
N3SQLAllocHandle(SQL_HANDLE_DBC,m_pDriverHandleCopy,&m_aConnectionHandle);
if(m_aConnectionHandle == SQL_NULL_HANDLE)
throw SQLException();
const PropertyValue *pBegin = info.getConstArray();
const PropertyValue *pEnd = pBegin + info.getLength();
::rtl::OUString sHostName;
sal_Int32 nLen = url.indexOf(':');
nLen = url.indexOf(':',nLen+1);
::rtl::OUString aDSN(url.copy(nLen+1)),aUID,aPWD;
sal_Int32 nTimeout = 20;
for(;pBegin != pEnd;++pBegin)
{
if ( !pBegin->Name.compareToAscii("Timeout") )
pBegin->Value >>= nTimeout;
else if(!pBegin->Name.compareToAscii("user"))
pBegin->Value >>= aUID;
else if(!pBegin->Name.compareToAscii("password"))
pBegin->Value >>= aPWD;
else if(!pBegin->Name.compareToAscii("HostName"))
pBegin->Value >>= sHostName;
else if(0 == pBegin->Name.compareToAscii("CharSet"))
{
::rtl::OUString sIanaName;
OSL_VERIFY( pBegin->Value >>= sIanaName );
::dbtools::OCharsetMap aLookupIanaName;
::dbtools::OCharsetMap::const_iterator aLookup = aLookupIanaName.find(sIanaName, ::dbtools::OCharsetMap::IANA());
if (aLookup != aLookupIanaName.end())
m_nTextEncoding = (*aLookup).getEncoding();
else
m_nTextEncoding = RTL_TEXTENCODING_DONTKNOW;
if(m_nTextEncoding == RTL_TEXTENCODING_DONTKNOW)
m_nTextEncoding = osl_getThreadTextEncoding();
}
}
m_sUser = aUID;
if ( sHostName.getLength() )
aDSN = sHostName + ':' + aDSN;
SQLRETURN nSQLRETURN = openConnectionWithAuth(aDSN,nTimeout, aUID,aPWD);
return nSQLRETURN;
}
//-----------------------------------------------------------------------------
SQLRETURN OAdabasConnection::openConnectionWithAuth(const ::rtl::OUString& aConnectStr,sal_Int32 nTimeOut, const ::rtl::OUString& _uid,const ::rtl::OUString& _pwd)
{
if (m_aConnectionHandle == SQL_NULL_HANDLE)
return -1;
SQLRETURN nSQLRETURN = 0;
SDB_ODBC_CHAR szDSN[4096];
SDB_ODBC_CHAR szUID[20];
SDB_ODBC_CHAR szPWD[20];
memset(szDSN,'\0',4096);
memset(szUID,'\0',20);
memset(szPWD,'\0',20);
::rtl::OString aConStr(::rtl::OUStringToOString(aConnectStr,getTextEncoding()));
::rtl::OString aUID(::rtl::OUStringToOString(_uid,getTextEncoding()));
::rtl::OString aPWD(::rtl::OUStringToOString(_pwd,getTextEncoding()));
memcpy(szDSN, (SDB_ODBC_CHAR*) aConStr.getStr(), ::std::min<sal_Int32>((sal_Int32)2048,aConStr.getLength()));
memcpy(szUID, (SDB_ODBC_CHAR*) aUID.getStr(), ::std::min<sal_Int32>((sal_Int32)20,aUID.getLength()));
memcpy(szPWD, (SDB_ODBC_CHAR*) aPWD.getStr(), ::std::min<sal_Int32>((sal_Int32)20,aPWD.getLength()));
N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_LOGIN_TIMEOUT,(SQLPOINTER)nTimeOut,SQL_IS_INTEGER);
// Verbindung aufbauen
nSQLRETURN = N3SQLConnect(m_aConnectionHandle,
szDSN,
(SQLSMALLINT) ::std::min<sal_Int32>((sal_Int32)2048,aConStr.getLength()),
szUID,
(SQLSMALLINT) ::std::min<sal_Int32>((sal_Int32)20,aUID.getLength()),
szPWD,
(SQLSMALLINT) ::std::min<sal_Int32>((sal_Int32)20,aPWD.getLength()));
if (nSQLRETURN == SQL_ERROR || nSQLRETURN == SQL_NO_DATA)
return nSQLRETURN;
m_bClosed = sal_False;
// autocoomit ist immer default
N3SQLSetConnectAttr(m_aConnectionHandle,SQL_ATTR_AUTOCOMMIT,(SQLPOINTER)SQL_AUTOCOMMIT_ON,SQL_IS_INTEGER);
return nSQLRETURN;
}
//------------------------------------------------------------------------------
void OAdabasConnection::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
Reference< XTablesSupplier > xTableSupplier(m_xCatalog);
::comphelper::disposeComponent(xTableSupplier);
m_xCatalog = WeakReference< XTablesSupplier >();
OConnection_BASE2::disposing();
}
//------------------------------------------------------------------------------
Reference< XTablesSupplier > OAdabasConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if(!xTab.is())
{
xTab = new OAdabasCatalog(m_aConnectionHandle,this);
m_xCatalog = xTab;
}
return xTab;
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OAdabasConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE2::rBHelper.bDisposed);
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if(!xMetaData.is())
{
xMetaData = new OAdabasDatabaseMetaData(m_aConnectionHandle,this);
m_xMetaData = xMetaData;
}
return xMetaData;
}
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OAdabasConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE2::rBHelper.bDisposed);
Reference< XStatement > xReturn = new OAdabasStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OAdabasConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(OConnection_BASE2::rBHelper.bDisposed);
if(m_aTypeInfo.empty())
buildTypeInfo();
Reference< XPreparedStatement > xReturn = new OAdabasPreparedStatement(this,m_aTypeInfo,sql);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// -----------------------------------------------------------------------------
sal_Int64 SAL_CALL OAdabasConnection::getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rId ) throw (::com::sun::star::uno::RuntimeException)
{
return (rId.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), rId.getConstArray(), 16 ) )
? reinterpret_cast< sal_Int64 >( this )
: OConnection_BASE2::getSomething(rId);
}
// -----------------------------------------------------------------------------
Sequence< sal_Int8 > OAdabasConnection::getUnoTunnelImplementationId()
{
static ::cppu::OImplementationId * pId = 0;
if (! pId)
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if (! pId)
{
static ::cppu::OImplementationId aId;
pId = &aId;
}
}
return pId->getImplementationId();
}
// -----------------------------------------------------------------------------
::connectivity::odbc::OConnection* OAdabasConnection::cloneConnection()
{
return new OAdabasConnection(m_pDriverHandleCopy,m_pDriver);
}
// -----------------------------------------------------------------------------
::vos::ORef<OSQLColumns> OAdabasConnection::createSelectColumns(const ::rtl::OUString& _rSql)
{
::vos::ORef<OSQLColumns> aRet;
OSQLParser aParser(getDriver()->getORB());
::rtl::OUString sErrorMessage;
OSQLParseNode* pNode = aParser.parseTree(sErrorMessage,_rSql);
if(pNode)
{
Reference< XTablesSupplier> xCata = createCatalog();
OSQLParseTreeIterator aParseIter(this, xCata->getTables(),
aParser, pNode);
aParseIter.traverseAll();
aRet = aParseIter.getSelectColumns();
}
return aRet;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// playHistoryTracker.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <string>
#include <map>
BZ_GET_PLUGIN_VERSION
// event handler callback
class PlayHistoryTracker : public bz_EventHandler
{
public:
PlayHistoryTracker();
virtual ~PlayHistoryTracker();
virtual void process ( bz_EventData *eventData );
virtual bool autoDelete ( void ) { return false;} // this will be used for more then one event
protected:
typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList;
};
PlayHistoryTracker historyTracker;
BZF_PLUGIN_CALL int bz_Load ( const char* commandLine )
{
bz_debugMessage(4,"PlayHistoryTracker plugin loaded");
bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
bz_registerEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
bz_registerEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
bz_removeEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
bz_removeEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
bz_removeEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
bz_debugMessage(4,"PlayHistoryTracker plugin unloaded");
return 0;
}
// ----------------- SpreeTracker-----------------
/*typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList; */
PlayHistoryTracker::PlayHistoryTracker()
{
}
PlayHistoryTracker::~PlayHistoryTracker()
{
}
void PlayHistoryTracker::process ( bz_EventData *eventData )
{
switch (eventData->eventType)
{
default:
// really WTF!!!!
break;
case bz_ePlayerDieEvent:
{
bz_PlayerDieEventData *deathRecord = ( bz_PlayerDieEventData*)eventData;
bz_PlayerRecord *killerData;
killerData = bz_getPlayerByIndex(deathRecord->killerID);
std::string soundToPlay;
// clear out the dude who got shot, since he won't be having any SPREEs
if (playerList.find(deathRecord->playerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->playerID)->second;
std::string message;
if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
message = record.callsign + std::string("'s rampage was stoped by ") + killerData->callsign.c_str();
if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
message = record.callsign + std::string("'s killing spree was halted by ") + killerData->callsign.c_str();
if ( record.spreeTotal >= 20 )
message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + killerData->callsign.c_str();
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
soundToPlay = "spree4";
}
record.spreeTotal = 0;
record.startTime = deathRecord->time;
record.lastUpdateTime = deathRecord->time;
}
// chock up another win for our killer
// if they weren't the same as the killer ( suicide ).
if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->killerID)->second;
record.spreeTotal++;
record.lastUpdateTime = deathRecord->time;
std::string message;
if ( record.spreeTotal == 5 )
{
message = record.callsign + std::string(" is on a Rampage!");
if (!soundToPlay.size())
soundToPlay = "spree1";
}
if ( record.spreeTotal == 10 )
{
message = record.callsign + std::string(" is on a Killing Spree!");
if (!soundToPlay.size())
soundToPlay = "spree2";
}
if ( record.spreeTotal == 20 )
{
message = record.callsign + std::string(" is Unstoppable!!");
if (!soundToPlay.size())
soundToPlay = "spree3";
}
if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
{
message = record.callsign + std::string("'s continues to rage on");
if (!soundToPlay.size())
soundToPlay = "spree4";
}
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
}
}
bz_freePlayerRecord(killerData);
if (soundToPlay.size())
bz_sendPlayCustomLocalSound(BZ_ALL_USERS,soundToPlay.c_str());
}
break;
case bz_ePlayerSpawnEvent:
// really WTF!!!!
break;
case bz_ePlayerJoinEvent:
{
trPlayerHistoryRecord playerRecord;
playerRecord.playerID = (( bz_PlayerJoinPartEventData*)eventData)->playerID;
playerRecord.callsign = (( bz_PlayerJoinPartEventData*)eventData)->callsign.c_str();
playerRecord.spreeTotal = 0;
playerRecord.lastUpdateTime = (( bz_PlayerJoinPartEventData*)eventData)->time;
playerRecord.startTime = playerRecord.lastUpdateTime;
playerList[(( bz_PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
}
break;
case bz_ePlayerPartEvent:
{
std::map<int, trPlayerHistoryRecord >::iterator itr = playerList.find( (( bz_PlayerJoinPartEventData*)eventData)->playerID );
if (itr != playerList.end())
playerList.erase(itr);
}
break;
}
}
<commit_msg>typo fixing<commit_after>// playHistoryTracker.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <string>
#include <map>
BZ_GET_PLUGIN_VERSION
// event handler callback
class PlayHistoryTracker : public bz_EventHandler
{
public:
PlayHistoryTracker();
virtual ~PlayHistoryTracker();
virtual void process ( bz_EventData *eventData );
virtual bool autoDelete ( void ) { return false;} // this will be used for more then one event
protected:
typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList;
};
PlayHistoryTracker historyTracker;
BZF_PLUGIN_CALL int bz_Load ( const char* commandLine )
{
bz_debugMessage(4,"PlayHistoryTracker plugin loaded");
bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
bz_registerEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
bz_registerEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
bz_registerEvent(bz_ePlayerJoinEvent,BZ_ALL_USERS,&historyTracker);
return 0;
}
BZF_PLUGIN_CALL int bz_Unload ( void )
{
bz_removeEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&historyTracker);
bz_removeEvent(bz_ePlayerPartEvent,BZ_ALL_USERS,&historyTracker);
bz_removeEvent(bz_ePlayerSpawnEvent,BZ_ALL_USERS,&historyTracker);
bz_removeEvent(bz_ePlayerJoinEvent,BZ_ALL_USERS,&historyTracker);
bz_debugMessage(4,"PlayHistoryTracker plugin unloaded");
return 0;
}
// ----------------- SpreeTracker-----------------
/*typedef struct
{
int playerID;
std::string callsign;
double startTime;
double lastUpdateTime;
int spreeTotal;
}trPlayerHistoryRecord;
std::map<int, trPlayerHistoryRecord > playerList; */
PlayHistoryTracker::PlayHistoryTracker()
{
}
PlayHistoryTracker::~PlayHistoryTracker()
{
}
void PlayHistoryTracker::process ( bz_EventData *eventData )
{
switch (eventData->eventType)
{
default:
// really WTF!!!!
break;
case bz_ePlayerDieEvent:
{
bz_PlayerDieEventData *deathRecord = ( bz_PlayerDieEventData*)eventData;
bz_PlayerRecord *killerData;
killerData = bz_getPlayerByIndex(deathRecord->killerID);
std::string soundToPlay;
// clear out the dude who got shot, since he won't be having any SPREEs
if (playerList.find(deathRecord->playerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->playerID)->second;
std::string message;
if ( record.spreeTotal >= 5 && record.spreeTotal < 10 )
message = record.callsign + std::string("'s rampage was stoped by ") + killerData->callsign.c_str();
if ( record.spreeTotal >= 10 && record.spreeTotal < 20 )
message = record.callsign + std::string("'s killing spree was halted by ") + killerData->callsign.c_str();
if ( record.spreeTotal >= 20 )
message = std::string("The unstopable reign of ") + record.callsign + std::string(" was ended by ") + killerData->callsign.c_str();
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
soundToPlay = "spree4";
}
record.spreeTotal = 0;
record.startTime = deathRecord->time;
record.lastUpdateTime = deathRecord->time;
}
// chock up another win for our killer
// if they weren't the same as the killer ( suicide ).
if ( (deathRecord->playerID != deathRecord->killerID) && playerList.find(deathRecord->killerID) != playerList.end())
{
trPlayerHistoryRecord &record = playerList.find(deathRecord->killerID)->second;
record.spreeTotal++;
record.lastUpdateTime = deathRecord->time;
std::string message;
if ( record.spreeTotal == 5 )
{
message = record.callsign + std::string(" is on a Rampage!");
if (!soundToPlay.size())
soundToPlay = "spree1";
}
if ( record.spreeTotal == 10 )
{
message = record.callsign + std::string(" is on a Killing Spree!");
if (!soundToPlay.size())
soundToPlay = "spree2";
}
if ( record.spreeTotal == 20 )
{
message = record.callsign + std::string(" is Unstoppable!!");
if (!soundToPlay.size())
soundToPlay = "spree3";
}
if ( record.spreeTotal > 20 && record.spreeTotal%5 == 0 )
{
message = record.callsign + std::string("'s continues to rage on");
if (!soundToPlay.size())
soundToPlay = "spree4";
}
if (message.size())
{
bz_sendTextMessage(BZ_SERVER, BZ_ALL_USERS, message.c_str());
}
}
bz_freePlayerRecord(killerData);
if (soundToPlay.size())
bz_sendPlayCustomLocalSound(BZ_ALL_USERS,soundToPlay.c_str());
}
break;
case bz_ePlayerSpawnEvent:
// really WTF!!!!
break;
case bz_ePlayerJoinEvent:
{
trPlayerHistoryRecord playerRecord;
playerRecord.playerID = (( bz_PlayerJoinPartEventData*)eventData)->playerID;
playerRecord.callsign = (( bz_PlayerJoinPartEventData*)eventData)->callsign.c_str();
playerRecord.spreeTotal = 0;
playerRecord.lastUpdateTime = (( bz_PlayerJoinPartEventData*)eventData)->time;
playerRecord.startTime = playerRecord.lastUpdateTime;
playerList[(( bz_PlayerJoinPartEventData*)eventData)->playerID] = playerRecord;
}
break;
case bz_ePlayerPartEvent:
{
std::map<int, trPlayerHistoryRecord >::iterator itr = playerList.find( (( bz_PlayerJoinPartEventData*)eventData)->playerID );
if (itr != playerList.end())
playerList.erase(itr);
}
break;
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: HStorageMap.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:30:16 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "hsqldb/HStorageMap.hxx"
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTIONBROADCASTER_HPP_
#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef CONNECTIVITY_DIAGNOSE_EX_H
#include "diagnose_ex.h"
#endif
#include <osl/thread.h>
//........................................................................
namespace connectivity
{
//........................................................................
namespace hsqldb
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
#define ThrowException(env, type, msg) { \
env->ThrowNew(env->FindClass(type), msg); }
StreamHelper::StreamHelper(const Reference< XStream>& _xStream)
: m_xStream(_xStream)
{
}
// -----------------------------------------------------------------------------
StreamHelper::~StreamHelper()
{
try
{
m_xStream = NULL;
m_xSeek = NULL;
if ( m_xInputStream.is() )
{
m_xInputStream->closeInput();
m_xInputStream = NULL;
}
if ( m_xOutputStream.is() )
{
m_xOutputStream->closeOutput();
try
{
::comphelper::disposeComponent(m_xOutputStream);
}
catch(DisposedException&)
{
}
catch(const Exception& e)
{
OSL_UNUSED( e );
OSL_ENSURE(0,"Could not dispose OutputStream");
}
m_xOutputStream = NULL;
}
}
catch(Exception& )
{
OSL_ENSURE(0,"Exception catched!");
}
}
// -----------------------------------------------------------------------------
Reference< XInputStream> StreamHelper::getInputStream()
{
if ( !m_xInputStream.is() )
m_xInputStream = m_xStream->getInputStream();
return m_xInputStream;
}
// -----------------------------------------------------------------------------
Reference< XOutputStream> StreamHelper::getOutputStream()
{
if ( !m_xOutputStream.is() )
m_xOutputStream = m_xStream->getOutputStream();
return m_xOutputStream;
}
// -----------------------------------------------------------------------------
Reference< XStream> StreamHelper::getStream()
{
return m_xStream;
}
// -----------------------------------------------------------------------------
Reference< XSeekable> StreamHelper::getSeek()
{
if ( !m_xSeek.is() )
m_xSeek.set(m_xStream,UNO_QUERY);
return m_xSeek;
}
// -----------------------------------------------------------------------------
TStorages& lcl_getStorageMap()
{
static TStorages s_aMap;
return s_aMap;
}
// -----------------------------------------------------------------------------
::rtl::OUString lcl_getNextCount()
{
static sal_Int32 s_nCount = 0;
return ::rtl::OUString::valueOf(s_nCount++);
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::removeURLPrefix(const ::rtl::OUString& _sURL,const ::rtl::OUString& _sFileURL)
{
return _sURL.copy(_sFileURL.getLength()+1);
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::removeOldURLPrefix(const ::rtl::OUString& _sURL)
{
::rtl::OUString sRet = _sURL;
#if defined(WIN) || defined(WNT)
sal_Int32 nIndex = sRet.lastIndexOf('\\');
#else
sal_Int32 nIndex = sRet.lastIndexOf('/');
#endif
if ( nIndex != -1 )
{
sRet = _sURL.copy(nIndex+1);
}
return sRet;
}
/*****************************************************************************/
/* convert jstring to rtl_uString */
::rtl::OUString StorageContainer::jstring2ustring(JNIEnv * env, jstring jstr)
{
if (JNI_FALSE != env->ExceptionCheck())
{
env->ExceptionClear();
OSL_ENSURE(0,"ExceptionClear");
}
::rtl::OUString aStr;
if ( jstr )
{
jboolean bCopy(sal_True);
const jchar* pChar = env->GetStringChars(jstr,&bCopy);
jsize len = env->GetStringLength(jstr);
aStr = ::rtl::OUString(pChar,len);
if(bCopy)
env->ReleaseStringChars(jstr,pChar);
}
if (JNI_FALSE != env->ExceptionCheck())
{
env->ExceptionClear();
OSL_ENSURE(0,"ExceptionClear");
}
return aStr;
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::registerStorage(const Reference< XStorage>& _xStorage,const ::rtl::OUString& _sURL)
{
OSL_ENSURE(_xStorage.is(),"Storage is NULL!");
TStorages& rMap = lcl_getStorageMap();
// check if the storage is already in our map
TStorages::iterator aFind = ::std::find_if(rMap.begin(),rMap.end(),
::std::compose1(
::std::bind2nd(::std::equal_to<Reference<XStorage> >(),_xStorage)
,::std::compose1(::std::select1st<TStorageURLPair>(),::std::compose1(::std::select1st<TStorages::mapped_type>(),::std::select2nd<TStorages::value_type>())))
);
if ( aFind == rMap.end() )
{
aFind = rMap.insert(TStorages::value_type(lcl_getNextCount(),TStorages::mapped_type(TStorageURLPair(_xStorage,_sURL),TStreamMap()))).first;
}
return aFind->first;
}
// -----------------------------------------------------------------------------
TStorages::mapped_type StorageContainer::getRegisteredStorage(const ::rtl::OUString& _sKey)
{
TStorages::mapped_type aRet;
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(_sKey);
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
aRet = aFind->second;
return aRet;
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::getRegisteredKey(const Reference< XStorage>& _xStorage)
{
::rtl::OUString sKey;
OSL_ENSURE(_xStorage.is(),"Storage is NULL!");
TStorages& rMap = lcl_getStorageMap();
// check if the storage is already in our map
TStorages::iterator aFind = ::std::find_if(rMap.begin(),rMap.end(),
::std::compose1(
::std::bind2nd(::std::equal_to<Reference<XStorage> >(),_xStorage)
,::std::compose1(::std::select1st<TStorageURLPair>(),::std::compose1(::std::select1st<TStorages::mapped_type>(),::std::select2nd<TStorages::value_type>())))
);
if ( aFind != rMap.end() )
sKey = aFind->first;
return sKey;
}
// -----------------------------------------------------------------------------
void StorageContainer::revokeStorage(const ::rtl::OUString& _sKey,const Reference<XTransactionListener>& _xListener)
{
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(_sKey);
if ( aFind != rMap.end() )
{
try
{
if ( _xListener.is() )
{
Reference<XTransactionBroadcaster> xBroad(aFind->second.first.first,UNO_QUERY);
if ( xBroad.is() )
xBroad->removeTransactionListener(_xListener);
Reference<XTransactedObject> xTrans(aFind->second.first.first,UNO_QUERY);
if ( xTrans.is() )
xTrans->commit();
}
}
catch(Exception&)
{
}
rMap.erase(aFind);
}
}
// -----------------------------------------------------------------------------
TStreamMap::mapped_type StorageContainer::registerStream(JNIEnv * env,jstring name, jstring key,sal_Int32 _nMode)
{
TStreamMap::mapped_type pHelper;
TStorages& rMap = lcl_getStorageMap();
::rtl::OUString sKey = jstring2ustring(env,key);
TStorages::iterator aFind = rMap.find(sKey);
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
{
TStorages::mapped_type aStoragePair = StorageContainer::getRegisteredStorage(sKey);
OSL_ENSURE(aStoragePair.first.first.is(),"No Storage available!");
if ( aStoragePair.first.first.is() )
{
::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
::rtl::OUString sName = removeURLPrefix(sOrgName,aStoragePair.first.second);
TStreamMap::iterator aStreamFind = aFind->second.second.find(sName);
OSL_ENSURE( aStreamFind == aFind->second.second.end(),"A Stream was already registered for this object!");
if ( aStreamFind != aFind->second.second.end() )
{
pHelper = aStreamFind->second;
}
else
{
try
{
try
{
/* if ( _nMode == ElementModes::READ )
_nMode |= ElementModes::SEEKABLE;
*/
pHelper.reset(new StreamHelper(aStoragePair.first.first->openStreamElement(sName,_nMode)));
}
catch(Exception& )
{
::rtl::OUString sStrippedName = removeOldURLPrefix(sOrgName);
pHelper.reset( new StreamHelper(aStoragePair.first.first->openStreamElement( sStrippedName, _nMode ) ) );
}
aFind->second.second.insert(TStreamMap::value_type(sName,pHelper));
}
catch(Exception& e)
{
#if OSL_DEBUG_LEVEL > 0
::rtl::OString sMessage( "[HSQLDB-SDBC] caught an exception while opening a stream\n" );
sMessage += "Name: ";
sMessage += ::rtl::OString( sName.getStr(), sName.getLength(), osl_getThreadTextEncoding() );
sMessage += "\nMode: 0x";
if ( _nMode < 16 )
sMessage += "0";
sMessage += ::rtl::OString::valueOf( _nMode, 16 ).toAsciiUpperCase();
OSL_ENSURE( false, sMessage.getStr() );
#endif
StorageContainer::throwJavaException(e,env);
}
}
}
}
return pHelper;
}
// -----------------------------------------------------------------------------
void StorageContainer::revokeStream( JNIEnv * env,jstring name, jstring key)
{
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
aFind->second.second.erase(removeURLPrefix(jstring2ustring(env,name),aFind->second.first.second));
}
// -----------------------------------------------------------------------------
TStreamMap::mapped_type StorageContainer::getRegisteredStream( JNIEnv * env,jstring name, jstring key)
{
TStreamMap::mapped_type pRet;
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
{
TStreamMap::iterator aStreamFind = aFind->second.second.find(removeURLPrefix(jstring2ustring(env,name),aFind->second.first.second));
if ( aStreamFind != aFind->second.second.end() )
pRet = aStreamFind->second;
}
return pRet;
}
// -----------------------------------------------------------------------------
void StorageContainer::throwJavaException(const Exception& _aException,JNIEnv * env)
{
if (JNI_FALSE != env->ExceptionCheck())
env->ExceptionClear();
::rtl::OString cstr( ::rtl::OUStringToOString(_aException.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
env->ThrowNew(env->FindClass("java/io/IOException"), cstr.getStr());
}
//........................................................................
} // namespace hsqldb
//........................................................................
//........................................................................
}
// namespace connectivity
//........................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.10.58); FILE MERGED 2006/09/01 17:22:16 kaib 1.10.58.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: HStorageMap.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:40:55 $
*
* 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_connectivity.hxx"
#include "hsqldb/HStorageMap.hxx"
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTIONBROADCASTER_HPP_
#include <com/sun/star/embed/XTransactionBroadcaster.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef CONNECTIVITY_DIAGNOSE_EX_H
#include "diagnose_ex.h"
#endif
#include <osl/thread.h>
//........................................................................
namespace connectivity
{
//........................................................................
namespace hsqldb
{
//........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
#define ThrowException(env, type, msg) { \
env->ThrowNew(env->FindClass(type), msg); }
StreamHelper::StreamHelper(const Reference< XStream>& _xStream)
: m_xStream(_xStream)
{
}
// -----------------------------------------------------------------------------
StreamHelper::~StreamHelper()
{
try
{
m_xStream = NULL;
m_xSeek = NULL;
if ( m_xInputStream.is() )
{
m_xInputStream->closeInput();
m_xInputStream = NULL;
}
if ( m_xOutputStream.is() )
{
m_xOutputStream->closeOutput();
try
{
::comphelper::disposeComponent(m_xOutputStream);
}
catch(DisposedException&)
{
}
catch(const Exception& e)
{
OSL_UNUSED( e );
OSL_ENSURE(0,"Could not dispose OutputStream");
}
m_xOutputStream = NULL;
}
}
catch(Exception& )
{
OSL_ENSURE(0,"Exception catched!");
}
}
// -----------------------------------------------------------------------------
Reference< XInputStream> StreamHelper::getInputStream()
{
if ( !m_xInputStream.is() )
m_xInputStream = m_xStream->getInputStream();
return m_xInputStream;
}
// -----------------------------------------------------------------------------
Reference< XOutputStream> StreamHelper::getOutputStream()
{
if ( !m_xOutputStream.is() )
m_xOutputStream = m_xStream->getOutputStream();
return m_xOutputStream;
}
// -----------------------------------------------------------------------------
Reference< XStream> StreamHelper::getStream()
{
return m_xStream;
}
// -----------------------------------------------------------------------------
Reference< XSeekable> StreamHelper::getSeek()
{
if ( !m_xSeek.is() )
m_xSeek.set(m_xStream,UNO_QUERY);
return m_xSeek;
}
// -----------------------------------------------------------------------------
TStorages& lcl_getStorageMap()
{
static TStorages s_aMap;
return s_aMap;
}
// -----------------------------------------------------------------------------
::rtl::OUString lcl_getNextCount()
{
static sal_Int32 s_nCount = 0;
return ::rtl::OUString::valueOf(s_nCount++);
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::removeURLPrefix(const ::rtl::OUString& _sURL,const ::rtl::OUString& _sFileURL)
{
return _sURL.copy(_sFileURL.getLength()+1);
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::removeOldURLPrefix(const ::rtl::OUString& _sURL)
{
::rtl::OUString sRet = _sURL;
#if defined(WIN) || defined(WNT)
sal_Int32 nIndex = sRet.lastIndexOf('\\');
#else
sal_Int32 nIndex = sRet.lastIndexOf('/');
#endif
if ( nIndex != -1 )
{
sRet = _sURL.copy(nIndex+1);
}
return sRet;
}
/*****************************************************************************/
/* convert jstring to rtl_uString */
::rtl::OUString StorageContainer::jstring2ustring(JNIEnv * env, jstring jstr)
{
if (JNI_FALSE != env->ExceptionCheck())
{
env->ExceptionClear();
OSL_ENSURE(0,"ExceptionClear");
}
::rtl::OUString aStr;
if ( jstr )
{
jboolean bCopy(sal_True);
const jchar* pChar = env->GetStringChars(jstr,&bCopy);
jsize len = env->GetStringLength(jstr);
aStr = ::rtl::OUString(pChar,len);
if(bCopy)
env->ReleaseStringChars(jstr,pChar);
}
if (JNI_FALSE != env->ExceptionCheck())
{
env->ExceptionClear();
OSL_ENSURE(0,"ExceptionClear");
}
return aStr;
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::registerStorage(const Reference< XStorage>& _xStorage,const ::rtl::OUString& _sURL)
{
OSL_ENSURE(_xStorage.is(),"Storage is NULL!");
TStorages& rMap = lcl_getStorageMap();
// check if the storage is already in our map
TStorages::iterator aFind = ::std::find_if(rMap.begin(),rMap.end(),
::std::compose1(
::std::bind2nd(::std::equal_to<Reference<XStorage> >(),_xStorage)
,::std::compose1(::std::select1st<TStorageURLPair>(),::std::compose1(::std::select1st<TStorages::mapped_type>(),::std::select2nd<TStorages::value_type>())))
);
if ( aFind == rMap.end() )
{
aFind = rMap.insert(TStorages::value_type(lcl_getNextCount(),TStorages::mapped_type(TStorageURLPair(_xStorage,_sURL),TStreamMap()))).first;
}
return aFind->first;
}
// -----------------------------------------------------------------------------
TStorages::mapped_type StorageContainer::getRegisteredStorage(const ::rtl::OUString& _sKey)
{
TStorages::mapped_type aRet;
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(_sKey);
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
aRet = aFind->second;
return aRet;
}
// -----------------------------------------------------------------------------
::rtl::OUString StorageContainer::getRegisteredKey(const Reference< XStorage>& _xStorage)
{
::rtl::OUString sKey;
OSL_ENSURE(_xStorage.is(),"Storage is NULL!");
TStorages& rMap = lcl_getStorageMap();
// check if the storage is already in our map
TStorages::iterator aFind = ::std::find_if(rMap.begin(),rMap.end(),
::std::compose1(
::std::bind2nd(::std::equal_to<Reference<XStorage> >(),_xStorage)
,::std::compose1(::std::select1st<TStorageURLPair>(),::std::compose1(::std::select1st<TStorages::mapped_type>(),::std::select2nd<TStorages::value_type>())))
);
if ( aFind != rMap.end() )
sKey = aFind->first;
return sKey;
}
// -----------------------------------------------------------------------------
void StorageContainer::revokeStorage(const ::rtl::OUString& _sKey,const Reference<XTransactionListener>& _xListener)
{
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(_sKey);
if ( aFind != rMap.end() )
{
try
{
if ( _xListener.is() )
{
Reference<XTransactionBroadcaster> xBroad(aFind->second.first.first,UNO_QUERY);
if ( xBroad.is() )
xBroad->removeTransactionListener(_xListener);
Reference<XTransactedObject> xTrans(aFind->second.first.first,UNO_QUERY);
if ( xTrans.is() )
xTrans->commit();
}
}
catch(Exception&)
{
}
rMap.erase(aFind);
}
}
// -----------------------------------------------------------------------------
TStreamMap::mapped_type StorageContainer::registerStream(JNIEnv * env,jstring name, jstring key,sal_Int32 _nMode)
{
TStreamMap::mapped_type pHelper;
TStorages& rMap = lcl_getStorageMap();
::rtl::OUString sKey = jstring2ustring(env,key);
TStorages::iterator aFind = rMap.find(sKey);
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
{
TStorages::mapped_type aStoragePair = StorageContainer::getRegisteredStorage(sKey);
OSL_ENSURE(aStoragePair.first.first.is(),"No Storage available!");
if ( aStoragePair.first.first.is() )
{
::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
::rtl::OUString sName = removeURLPrefix(sOrgName,aStoragePair.first.second);
TStreamMap::iterator aStreamFind = aFind->second.second.find(sName);
OSL_ENSURE( aStreamFind == aFind->second.second.end(),"A Stream was already registered for this object!");
if ( aStreamFind != aFind->second.second.end() )
{
pHelper = aStreamFind->second;
}
else
{
try
{
try
{
/* if ( _nMode == ElementModes::READ )
_nMode |= ElementModes::SEEKABLE;
*/
pHelper.reset(new StreamHelper(aStoragePair.first.first->openStreamElement(sName,_nMode)));
}
catch(Exception& )
{
::rtl::OUString sStrippedName = removeOldURLPrefix(sOrgName);
pHelper.reset( new StreamHelper(aStoragePair.first.first->openStreamElement( sStrippedName, _nMode ) ) );
}
aFind->second.second.insert(TStreamMap::value_type(sName,pHelper));
}
catch(Exception& e)
{
#if OSL_DEBUG_LEVEL > 0
::rtl::OString sMessage( "[HSQLDB-SDBC] caught an exception while opening a stream\n" );
sMessage += "Name: ";
sMessage += ::rtl::OString( sName.getStr(), sName.getLength(), osl_getThreadTextEncoding() );
sMessage += "\nMode: 0x";
if ( _nMode < 16 )
sMessage += "0";
sMessage += ::rtl::OString::valueOf( _nMode, 16 ).toAsciiUpperCase();
OSL_ENSURE( false, sMessage.getStr() );
#endif
StorageContainer::throwJavaException(e,env);
}
}
}
}
return pHelper;
}
// -----------------------------------------------------------------------------
void StorageContainer::revokeStream( JNIEnv * env,jstring name, jstring key)
{
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
aFind->second.second.erase(removeURLPrefix(jstring2ustring(env,name),aFind->second.first.second));
}
// -----------------------------------------------------------------------------
TStreamMap::mapped_type StorageContainer::getRegisteredStream( JNIEnv * env,jstring name, jstring key)
{
TStreamMap::mapped_type pRet;
TStorages& rMap = lcl_getStorageMap();
TStorages::iterator aFind = rMap.find(jstring2ustring(env,key));
OSL_ENSURE(aFind != rMap.end(),"Storage could not be found in list!");
if ( aFind != rMap.end() )
{
TStreamMap::iterator aStreamFind = aFind->second.second.find(removeURLPrefix(jstring2ustring(env,name),aFind->second.first.second));
if ( aStreamFind != aFind->second.second.end() )
pRet = aStreamFind->second;
}
return pRet;
}
// -----------------------------------------------------------------------------
void StorageContainer::throwJavaException(const Exception& _aException,JNIEnv * env)
{
if (JNI_FALSE != env->ExceptionCheck())
env->ExceptionClear();
::rtl::OString cstr( ::rtl::OUStringToOString(_aException.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
env->ThrowNew(env->FindClass("java/io/IOException"), cstr.getStr());
}
//........................................................................
} // namespace hsqldb
//........................................................................
//........................................................................
}
// namespace connectivity
//........................................................................
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ConnectionLog.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ihi $ $Date: 2007-11-21 15:07:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONNECTIVITY_CONNECTIONLOG_HXX
#define CONNECTIVITY_CONNECTIONLOG_HXX
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_LOGGING_LOGLEVEL_HPP_
#include <com/sun/star/logging/LogLevel.hpp>
#endif
/** === end UNO includes === **/
#include <rtl/ustring.hxx>
// Strange enough, GCC requires the following forward declarations of the various
// convertLogArgToString flavors to be *before* the inclusion of comphelper/logging.hxx
namespace com { namespace sun { namespace star { namespace util
{
struct Date;
struct Time;
struct DateTime;
} } } }
//........................................................................
namespace comphelper { namespace log { namespace convert
{
//........................................................................
// helpers for logging more data types than are defined in comphelper/logging.hxx
::rtl::OUString convertLogArgToString( const ::com::sun::star::util::Date& _rDate );
::rtl::OUString convertLogArgToString( const ::com::sun::star::util::Time& _rTime );
::rtl::OUString convertLogArgToString( const ::com::sun::star::util::DateTime& _rDateTime );
//........................................................................
} } }
//........................................................................
#include <comphelper/logging.hxx>
namespace connectivity
{
namespace LogLevel = ::com::sun::star::logging::LogLevel;
}
//........................................................................
namespace connectivity { namespace java { namespace sql {
//........................................................................
//====================================================================
//= ConnectionLog
//====================================================================
typedef ::comphelper::ResourceBasedEventLogger ConnectionLog_Base;
class ConnectionLog : public ConnectionLog_Base
{
public:
enum ObjectType
{
CONNECTION = 0,
STATEMENT,
RESULTSET,
ObjectTypeCount = RESULTSET + 1
};
private:
const sal_Int32 m_nObjectID;
public:
/// will construct an instance of ObjectType CONNECTION
ConnectionLog( const ::comphelper::ResourceBasedEventLogger& _rDriverLog );
/// will create an instance with the same object ID / ObjectType as a given source instance
ConnectionLog( const ConnectionLog& _rSourceLog );
/// will create an instance of arbitrary ObjectType
ConnectionLog( const ConnectionLog& _rSourceLog, ObjectType _eType );
sal_Int32 getObjectID() const { return m_nObjectID; }
/// logs a given message, without any arguments, or source class/method names
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID )
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID );
}
template< typename ARGTYPE1 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1 );
}
template< typename ARGTYPE1, typename ARGTYPE2 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2 );
}
template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2, _argument3 );
}
template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2, _argument3, _argument4 );
}
template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2, _argument3, _argument4, _argument5 );
}
};
//........................................................................
} } } // namespace connectivity::java::sql
//........................................................................
#endif // CONNECTIVITY_CONNECTIONLOG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.64); FILE MERGED 2008/04/01 10:53:36 thb 1.3.64.2: #i85898# Stripping all external header guards 2008/03/28 15:24:30 rt 1.3.64.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ConnectionLog.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CONNECTIVITY_CONNECTIONLOG_HXX
#define CONNECTIVITY_CONNECTIONLOG_HXX
/** === begin UNO includes === **/
#include <com/sun/star/logging/LogLevel.hpp>
/** === end UNO includes === **/
#include <rtl/ustring.hxx>
// Strange enough, GCC requires the following forward declarations of the various
// convertLogArgToString flavors to be *before* the inclusion of comphelper/logging.hxx
namespace com { namespace sun { namespace star { namespace util
{
struct Date;
struct Time;
struct DateTime;
} } } }
//........................................................................
namespace comphelper { namespace log { namespace convert
{
//........................................................................
// helpers for logging more data types than are defined in comphelper/logging.hxx
::rtl::OUString convertLogArgToString( const ::com::sun::star::util::Date& _rDate );
::rtl::OUString convertLogArgToString( const ::com::sun::star::util::Time& _rTime );
::rtl::OUString convertLogArgToString( const ::com::sun::star::util::DateTime& _rDateTime );
//........................................................................
} } }
//........................................................................
#include <comphelper/logging.hxx>
namespace connectivity
{
namespace LogLevel = ::com::sun::star::logging::LogLevel;
}
//........................................................................
namespace connectivity { namespace java { namespace sql {
//........................................................................
//====================================================================
//= ConnectionLog
//====================================================================
typedef ::comphelper::ResourceBasedEventLogger ConnectionLog_Base;
class ConnectionLog : public ConnectionLog_Base
{
public:
enum ObjectType
{
CONNECTION = 0,
STATEMENT,
RESULTSET,
ObjectTypeCount = RESULTSET + 1
};
private:
const sal_Int32 m_nObjectID;
public:
/// will construct an instance of ObjectType CONNECTION
ConnectionLog( const ::comphelper::ResourceBasedEventLogger& _rDriverLog );
/// will create an instance with the same object ID / ObjectType as a given source instance
ConnectionLog( const ConnectionLog& _rSourceLog );
/// will create an instance of arbitrary ObjectType
ConnectionLog( const ConnectionLog& _rSourceLog, ObjectType _eType );
sal_Int32 getObjectID() const { return m_nObjectID; }
/// logs a given message, without any arguments, or source class/method names
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID )
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID );
}
template< typename ARGTYPE1 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1 );
}
template< typename ARGTYPE1, typename ARGTYPE2 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2 );
}
template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2, _argument3 );
}
template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2, _argument3, _argument4 );
}
template< typename ARGTYPE1, typename ARGTYPE2, typename ARGTYPE3, typename ARGTYPE4, typename ARGTYPE5 >
bool log( const sal_Int32 _nLogLevel, const sal_Int32 _nMessageResID, ARGTYPE1 _argument1, ARGTYPE2 _argument2, ARGTYPE3 _argument3, ARGTYPE4 _argument4, ARGTYPE5 _argument5 ) const
{
return ConnectionLog_Base::log( _nLogLevel, _nMessageResID, m_nObjectID, _argument1, _argument2, _argument3, _argument4, _argument5 );
}
};
//........................................................................
} } } // namespace connectivity::java::sql
//........................................................................
#endif // CONNECTIVITY_CONNECTIONLOG_HXX
<|endoftext|>
|
<commit_before>//
// Created by Ray Jenkins on 4/20/15.
//
#include "ConservatorFramework.h"
#include "SetDataBuilderImpl.h"
#include "GetChildrenBuilderImpl.h"
#include "GetACLBuilderImpl.h"
#include "SetACLBuilderImpl.h"
void watcher(zhandle_t *zzh, int type, int state, const char *path,
void *watcherCtx) {
ConservatorFramework* framework = (ConservatorFramework *) watcherCtx;
if(state == ZOO_CONNECTED_STATE) {
unique_lock<std::mutex> connectLock(framework->connectMutex);
framework->connected = true;
framework->connectCondition.notify_all();
connectLock.unlock();
}
};
ConservatorFramework::ConservatorFramework(string connectString) {
this->connectString = connectString;
}
ConservatorFramework::ConservatorFramework(string connectString, int timeout) {
this->connectString = connectString;
this->timeout = timeout;
}
ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid) {
this->connectString = connectString;
this->timeout = timeout;
this->cid = cid;
}
ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid, int znode_size) {
this->connectString = connectString;
this->timeout = timeout;
this->cid = cid;
this->znode_size = znode_size;
}
void ConservatorFramework::start() {
unique_lock<std::mutex> connectLock(connectMutex);
this->zk = zookeeper_init(connectString.c_str(), watcher, timeout, cid, (void *) this, 0);
if(!connected) {
if(connectCondition.wait_for(connectLock, chrono::seconds(15)) == cv_status::timeout) {
throw "timed out waiting to connect to zookeeper";
}
}
started = true;
connectLock.unlock();
}
void ConservatorFramework::close() {
zookeeper_close(this->zk);
started = false;
}
ZOOAPI int ConservatorFramework::getState() {
return zoo_state(zk);
}
bool ConservatorFramework::isStarted() {
return started;
}
unique_ptr<GetDataBuilder<string>> ConservatorFramework::getData() {
unique_ptr<GetDataBuilder<string>> p(new GetDataBuilderImpl(zk, znode_size));
return p;
}
unique_ptr<SetDataBuilder<int>> ConservatorFramework::setData() {
unique_ptr<SetDataBuilder<int>> p(new SetDataBuilderImpl(zk));
return p;
}
unique_ptr<ExistsBuilder<int>> ConservatorFramework::checkExists() {
unique_ptr<ExistsBuilder<int>> p(new ExistsBuilderImpl(zk));
return p;
}
unique_ptr<CreateBuilder<int>> ConservatorFramework::create() {
unique_ptr<CreateBuilder<int>> p(new CreateBuilderImpl(zk));
return p;
}
unique_ptr<DeleteBuilder<int>> ConservatorFramework::deleteNode() {
unique_ptr<DeleteBuilder<int>> p(new DeleteBuilderImpl(zk));
return p;
}
unique_ptr<GetChildrenBuilder<string>> ConservatorFramework::getChildren() {
unique_ptr<GetChildrenBuilder<string>> p(new GetChildrenBuilderImpl(zk));
return p;
}
unique_ptr<GetACLBuilder<int>> ConservatorFramework::getACL(ACL_vector *vector) {
unique_ptr<GetACLBuilder<int>> p(new GetACLBuilderImpl(zk, vector));
return p;
}
unique_ptr<SetACLBuilder<int>> ConservatorFramework::setACL(ACL_vector *vector) {
unique_ptr<SetACLBuilder<int>> p(new SetACLBuilderImpl(zk, vector));
return p;
}
string ConservatorFramework::get(string path) {
return get(path, znode_size);
}
string ConservatorFramework::get(string path, int length) {
char buff[length];
struct Stat stat;
zoo_get(zk, path.c_str(), 0, buff, &length, &stat);
return string(buff);
}
<commit_msg>move lock into while loop for connected<commit_after>//
// Created by Ray Jenkins on 4/20/15.
//
#include "ConservatorFramework.h"
#include "SetDataBuilderImpl.h"
#include "GetChildrenBuilderImpl.h"
#include "GetACLBuilderImpl.h"
#include "SetACLBuilderImpl.h"
void watcher(zhandle_t *zzh, int type, int state, const char *path,
void *watcherCtx) {
ConservatorFramework* framework = (ConservatorFramework *) watcherCtx;
if(state == ZOO_CONNECTED_STATE) {
unique_lock<std::mutex> connectLock(framework->connectMutex);
framework->connected = true;
framework->connectCondition.notify_all();
connectLock.unlock();
}
};
ConservatorFramework::ConservatorFramework(string connectString) {
this->connectString = connectString;
}
ConservatorFramework::ConservatorFramework(string connectString, int timeout) {
this->connectString = connectString;
this->timeout = timeout;
}
ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid) {
this->connectString = connectString;
this->timeout = timeout;
this->cid = cid;
}
ConservatorFramework::ConservatorFramework(string connectString, int timeout, clientid_t *cid, int znode_size) {
this->connectString = connectString;
this->timeout = timeout;
this->cid = cid;
this->znode_size = znode_size;
}
void ConservatorFramework::start() {
this->zk = zookeeper_init(connectString.c_str(), watcher, timeout, cid, (void *) this, 0);
while(!connected) {
unique_lock<std::mutex> connectLock(connectMutex);
if(connectCondition.wait_for(connectLock, chrono::seconds(15)) == cv_status::timeout) {
throw "timed out waiting to connect to zookeeper";
}
connectLock.unlock();
}
started = true;
}
void ConservatorFramework::close() {
zookeeper_close(this->zk);
started = false;
}
ZOOAPI int ConservatorFramework::getState() {
return zoo_state(zk);
}
bool ConservatorFramework::isStarted() {
return started;
}
unique_ptr<GetDataBuilder<string>> ConservatorFramework::getData() {
unique_ptr<GetDataBuilder<string>> p(new GetDataBuilderImpl(zk, znode_size));
return p;
}
unique_ptr<SetDataBuilder<int>> ConservatorFramework::setData() {
unique_ptr<SetDataBuilder<int>> p(new SetDataBuilderImpl(zk));
return p;
}
unique_ptr<ExistsBuilder<int>> ConservatorFramework::checkExists() {
unique_ptr<ExistsBuilder<int>> p(new ExistsBuilderImpl(zk));
return p;
}
unique_ptr<CreateBuilder<int>> ConservatorFramework::create() {
unique_ptr<CreateBuilder<int>> p(new CreateBuilderImpl(zk));
return p;
}
unique_ptr<DeleteBuilder<int>> ConservatorFramework::deleteNode() {
unique_ptr<DeleteBuilder<int>> p(new DeleteBuilderImpl(zk));
return p;
}
unique_ptr<GetChildrenBuilder<string>> ConservatorFramework::getChildren() {
unique_ptr<GetChildrenBuilder<string>> p(new GetChildrenBuilderImpl(zk));
return p;
}
unique_ptr<GetACLBuilder<int>> ConservatorFramework::getACL(ACL_vector *vector) {
unique_ptr<GetACLBuilder<int>> p(new GetACLBuilderImpl(zk, vector));
return p;
}
unique_ptr<SetACLBuilder<int>> ConservatorFramework::setACL(ACL_vector *vector) {
unique_ptr<SetACLBuilder<int>> p(new SetACLBuilderImpl(zk, vector));
return p;
}
string ConservatorFramework::get(string path) {
return get(path, znode_size);
}
string ConservatorFramework::get(string path, int length) {
char buff[length];
struct Stat stat;
zoo_get(zk, path.c_str(), 0, buff, &length, &stat);
return string(buff);
}
<|endoftext|>
|
<commit_before>//! @Alan
//!
//! Exercise 10.34:
//! Use reverse_iterators to print a vector in reverse order.
//!
//! Exercise 10.35:
//! Now print the elements in reverse order using ordinary iterators.
//!
//! Exercise 10.36:
//! Use find to find the last element in a list of ints with value 0.
//!
//! Exercise 10.37:
//! Given a vector that has ten elements, copy the elements from positions
//! 3 through 7 in reverse order to a list.
//!
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <string>
#include <list>
//! Exercise 10.34
void
r_print(const std::vector<std::string> &v);
//! Exercise 10.35
void
r_withOrdinary_print(const std::vector<std::string> &v);
//! Exercise 10.36
std::list<int>::iterator
find_last_0(std::list<int> &l);
//! Exercise 10.37
void
vec2list_3_7_reverse(const std::vector<int> &v, std::list<int> &l);
int main()
{
std::vector<std::string> v={"aa","bb","cc"};
//! test for 10.34
r_print(v);
std::cout << "\n";
//! test for 10.35
r_withOrdinary_print(v);
std::cout << "\n";
//! test for 10.36
std::list<int> l = {1,2,3,4,0,5,6};
auto it = find_last_0(l);
std::cout << *it << "\n";
//! test for 10.37
std::vector<int> vi = {1,2,3,4,5,6,7,8,9,10};
std::list<int> lst;
vec2list_3_7_reverse(vi,lst);
for(auto e : lst)
std::cout << e <<" ";
std::cout << std::endl;
return 0;
}
//! Exercise 10.34
inline void
r_print(const std::vector<std::string> &v)
{
std::for_each(v.crbegin(), v.crend(), [](const std::string &s)
{
std::cout << s << " ";
});
}
//! Exercise 10.35
inline void
r_withOrdinary_print(const std::vector<std::string> &v)
{
for (auto it = std::prev(v.cend()); it != std::prev(v.cbegin()); --it)
std::cout << *it << " ";
}
//! Exercise 10.36
//! @note reverse iterator can not conver to oridinary directly
//! it may be done via the member base().
inline std::list<int>::iterator
find_last_0(std::list<int> &l)
{
//! assumimg : 1 2 3 4 0 5 6
//! 1 2 3 4 0 5 6
//! ^
//! to which r_it refer.
auto r_it = std::find(l.rbegin(), l.rend(), 0);
//! 1 2 3 4 0 5 6
//! ^
//! to which it refer.
auto it = r_it.base();
//! 1 2 3 4 0 5 6
//! ^
//! to which --it refer.
return std::prev(it);
}
//! Exercise 10.37:
//! Given a vector that has ten elements, copy the elements from positions
//! 3 through 7 in reverse order to a list.
inline void
vec2list_3_7_reverse(const std::vector<int> &v, std::list<int> &l)
{
//! 1 2 3 4 5 6 7 8 9 10
//! ^ ^^
//! rend rbegin
std::copy(v.crbegin() + 3, v.crbegin() + 8, std::back_inserter(l));
//! ^
//! @note: std::copy copies the range [first,last) into result.
//! hence, the arguments here denote:
//! [7 6 5 4 3 2)
//! ^ this one is specified but not included.
//! @note: also const vecrions if functions can be used. v.crbegin() and v.crbegin()
}
<commit_msg>fixed Mooophy/Cpp-Primer#193<commit_after>//! @Alan @pezy
//!
//! Exercise 10.34:
//! Use reverse_iterators to print a vector in reverse order.
//!
//! Exercise 10.35:
//! Now print the elements in reverse order using ordinary iterators.
//!
//! Exercise 10.36:
//! Use find to find the last element in a list of ints with value 0.
//!
//! Exercise 10.37:
//! Given a vector that has ten elements, copy the elements from positions
//! 3 through 7 in reverse order to a list.
//!
#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> vec = {0,1,2,3,4,5,6,7,8,9};
// 10.34
for (auto rit = vec.crbegin(); rit != vec.crend(); ++rit)
std::cout << *rit << " ";
std::cout << std::endl;
// 10.35
for (auto it = std::prev(vec.cend()); true; --it) {
std::cout << *it << " ";
if (it == vec.cbegin()) break;
}
std::cout << std::endl;
// 10.36
std::list<int> lst = {1,2,3,4,0,5,6};
auto found_0 = std::find(lst.crbegin(), lst.crend(), 0);
std::cout << std::distance(found_0, lst.crend()) << std::endl;
// 10.37
std::list<int> ret_lst;
std::copy(vec.crbegin()+3, vec.crbegin()+8, std::back_inserter(ret_lst));
//! 0,1,2,3,4,5,6,7,8,9
//! ^ ^
//! rend rbegin
//! @note: std::copy copies the range [first,last) into result.
//! hence, the arguments here denote:
//! [6 5 4 3 2 1)
//! ^ this one is specified but not included.
for (auto i : ret_lst) std::cout << i << " ";
std::cout << std::endl;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009 Brent Fulgham. All rights reserved.
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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 "config.h"
#include "net/websocket/SocketStreamHandle.h"
#include "third_party/WebKit/Source/platform/Logging.h"
#include "third_party/WebKit/Source/platform/weborigin/KURL.h"
#include "net/websocket/SocketStreamHandleClient.h"
#include "third_party/WebKit/Source/wtf/MainThread.h"
#include "base/thread.h"
#include <process.h>
using namespace blink;
namespace net {
SocketStreamHandle::SocketStreamHandle(const KURL& url, SocketStreamHandleClient* client)
: SocketStreamHandleBase(url, client)
, m_workerThread(0)
, m_stopThread(0)
{
WTF_LOG(Network, "SocketStreamHandle %p new client %p", this, m_client);
ASSERT(isMainThread());
startThread();
}
SocketStreamHandle::~SocketStreamHandle()
{
WTF_LOG(Network, "SocketStreamHandle %p delete", this);
ASSERT(!m_workerThread);
}
int SocketStreamHandle::platformSend(const char* data, int length)
{
WTF_LOG(Network, "SocketStreamHandle %p platformSend", this);
ASSERT(isMainThread());
startThread();
auto copy = createCopy(data, length);
WTF::Locker<WTF::Mutex> lock(m_mutexSend);
m_sendData.append(adoptPtr(new SocketData(copy, length)));
return length;
}
void SocketStreamHandle::platformClose()
{
WTF_LOG(Network, "SocketStreamHandle %p platformClose", this);
ASSERT(isMainThread());
stopThread();
if (m_client)
m_client->didCloseSocketStream(this);
}
static void s_mainThreadReadData(void* param)
{
SocketStreamHandle* hanlde = (SocketStreamHandle*)param;
hanlde->mainThreadReadData();
}
void SocketStreamHandle::mainThreadReadData()
{
didReceiveData();
deref();
}
bool SocketStreamHandle::readData(CURL* curlHandle)
{
ASSERT(!isMainThread());
const int bufferSize = 1024;
char* data = new char[bufferSize];
size_t bytesRead = 0;
CURLcode ret = curl_easy_recv(curlHandle, data, bufferSize, &bytesRead);
ASSERT(bytesRead <= bufferSize);
if (ret == CURLE_OK && bytesRead >= 0) {
m_mutexReceive.lock();
m_receiveData.append(adoptPtr(new SocketData(data, static_cast<int>(bytesRead))));
m_mutexReceive.unlock();
ref();
WTF::internal::callOnMainThread(s_mainThreadReadData, this);
return true;
}
delete[] data;
if (ret == CURLE_AGAIN)
return true;
return false;
}
bool SocketStreamHandle::sendData(CURL* curlHandle)
{
ASSERT(!isMainThread());
while (true) {
m_mutexSend.lock();
if (!m_sendData.size()) {
m_mutexSend.unlock();
break;
}
PassOwnPtr<SocketData> sendData = m_sendData.takeFirst();
m_mutexSend.unlock();
int totalBytesSent = 0;
while (totalBytesSent < sendData->size) {
size_t bytesSent = 0;
CURLcode ret = curl_easy_send(curlHandle, sendData->data + totalBytesSent, sendData->size - totalBytesSent, &bytesSent);
if (ret == CURLE_OK)
totalBytesSent += bytesSent;
else
break;
}
// Insert remaining data into send queue.
if (totalBytesSent < sendData->size) {
const int restLength = sendData->size - totalBytesSent;
auto copy = createCopy(sendData->data + totalBytesSent, restLength);
WTF::Locker<WTF::Mutex> lock(m_mutexSend);
m_sendData.prepend(adoptPtr(new SocketData(copy, restLength)));
return false;
}
}
return true;
}
// in microseconds
bool SocketStreamHandle::waitForAvailableData(CURL* curlHandle, long long selectTimeout)
{
ASSERT(!isMainThread());
long long usec = selectTimeout * 1000;
struct timeval timeout;
if (usec <= (0)) {
timeout.tv_sec = 0;
timeout.tv_usec = 0;
} else {
timeout.tv_sec = usec / 1000000;
timeout.tv_usec = usec % 1000000;
}
long socket;
if (curl_easy_getinfo(curlHandle, CURLINFO_LASTSOCKET, &socket) != CURLE_OK)
return false;
::Sleep(50);
fd_set fdread;
FD_ZERO(&fdread);
FD_SET(socket, &fdread);
int rc = ::select(0, &fdread, nullptr, nullptr, &timeout);
return rc == 1;
}
static unsigned __stdcall webSocketThread(void* param)
{
base::SetThreadName("WebSocketThread");
SocketStreamHandle* invocation = (static_cast<SocketStreamHandle*>(param));
invocation->threadFunction();
return 0;
}
static void s_mainThreadRun(void* param)
{
SocketStreamHandle* hanlde = (SocketStreamHandle*)param;
hanlde->mainThreadRun();
}
void SocketStreamHandle::mainThreadRun()
{
// Check reference count to fix a crash.
// When the call is invoked on the main thread after all other references are released, the SocketStreamClient
// is already deleted. Accessing the SocketStreamClient in didOpenSocket() will then cause a crash.
if (refCount() > 1)
didOpenSocket();
deref();
}
void SocketStreamHandle::threadFunction()
{
ASSERT(!isMainThread());
CURL* curlHandle = curl_easy_init();
if (!curlHandle)
return;
String url = m_url.host();
unsigned short port = m_url.port();
if (0 == port) {
port = 80;
if (!m_url.protocolIs("ws")) {
port = 443;
url = "https://" + url;
}
}
//curl_easy_setopt(curlHandle, CURLOPT_URL, m_url.host().utf8().data());
curl_easy_setopt(curlHandle, CURLOPT_URL, url.utf8().data());
curl_easy_setopt(curlHandle, CURLOPT_PORT, port);
curl_easy_setopt(curlHandle, CURLOPT_CONNECT_ONLY);
curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT, 5000);
static const int kAllowedProtocols = CURLPROTO_FILE | CURLPROTO_FTP | CURLPROTO_FTPS | CURLPROTO_HTTP | CURLPROTO_HTTPS;
curl_easy_setopt(curlHandle, CURLOPT_SSL_VERIFYPEER, false); // ignoreSSLErrors
curl_easy_setopt(curlHandle, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_easy_setopt(curlHandle, CURLOPT_DNS_CACHE_TIMEOUT, 60 * 5); // 5 minutes
curl_easy_setopt(curlHandle, CURLOPT_PROTOCOLS, kAllowedProtocols);
curl_easy_setopt(curlHandle, CURLOPT_REDIR_PROTOCOLS, kAllowedProtocols);
// Connect to host
if (curl_easy_perform(curlHandle) != CURLE_OK)
return;
ref();
WTF::internal::callOnMainThread(s_mainThreadRun, this);
while (!m_stopThread) {
// Send queued data
sendData(curlHandle);
// Wait until socket has available data
if (waitForAvailableData(curlHandle, 50))
readData(curlHandle);
}
curl_easy_cleanup(curlHandle);
}
void SocketStreamHandle::startThread()
{
ASSERT(isMainThread());
if (m_workerThread)
return;
ref(); // stopThread() will call deref().
m_workerThread = static_cast<ThreadIdentifier>(_beginthreadex(0, 0, webSocketThread, this, 0, nullptr));
}
int waitForThreadCompletion(ThreadIdentifier threadID)
{
ASSERT(threadID);
HANDLE threadHandle = (HANDLE)(threadID);
// if (!threadHandle)
// WTF_LOG("ThreadIdentifier %u did not correspond to an active thread when trying to quit", threadID);
DWORD joinResult = ::WaitForSingleObject(threadHandle, INFINITE);
// if (joinResult == WAIT_FAILED)
// WTF_LOG("ThreadIdentifier %u was found to be deadlocked trying to quit", threadID);
CloseHandle(threadHandle);
//clearThreadHandleForIdentifier(threadID);
return joinResult;
}
void SocketStreamHandle::stopThread()
{
ASSERT(isMainThread());
if (!m_workerThread)
return;
InterlockedExchange(reinterpret_cast<long volatile*>(&m_stopThread), 1);
waitForThreadCompletion(m_workerThread);
m_workerThread = 0;
deref();
}
void SocketStreamHandle::didReceiveData()
{
ASSERT(isMainThread());
m_mutexReceive.lock();
Deque<OwnPtr<SocketData>> receiveData;
receiveData.swap(m_receiveData);
m_mutexReceive.unlock();
for (auto& socketData : receiveData) {
if (socketData->size > 0) {
if (m_client && state() == Open)
m_client->didReceiveSocketStreamData(this, socketData->data, socketData->size);
} else
platformClose();
}
}
void SocketStreamHandle::didOpenSocket()
{
ASSERT(isMainThread());
m_state = Open;
if (m_client)
m_client->didOpenSocketStream(this);
}
char* SocketStreamHandle::createCopy(const char* data, int length)
{
char* copy = (new char[length]);
memcpy(copy, data, length);
return copy;
}
void SocketStreamHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedCredential(const AuthenticationChallenge&, const Credential&)
{
notImplemented();
}
void SocketStreamHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedCancellation(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedRequestToPerformDefaultHandling(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedChallengeRejection(const AuthenticationChallenge&)
{
notImplemented();
}
} // namespace net<commit_msg>* 修复https://m.lehuipay.com/login没显示验证码的bug。原因是wss协议没加https的url头<commit_after>/*
* Copyright (C) 2009 Brent Fulgham. All rights reserved.
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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 "config.h"
#include "net/websocket/SocketStreamHandle.h"
#include "third_party/WebKit/Source/platform/Logging.h"
#include "third_party/WebKit/Source/platform/weborigin/KURL.h"
#include "net/websocket/SocketStreamHandleClient.h"
#include "third_party/WebKit/Source/wtf/MainThread.h"
#include "base/thread.h"
#include <process.h>
using namespace blink;
namespace net {
SocketStreamHandle::SocketStreamHandle(const KURL& url, SocketStreamHandleClient* client)
: SocketStreamHandleBase(url, client)
, m_workerThread(0)
, m_stopThread(0)
{
WTF_LOG(Network, "SocketStreamHandle %p new client %p", this, m_client);
ASSERT(isMainThread());
startThread();
}
SocketStreamHandle::~SocketStreamHandle()
{
WTF_LOG(Network, "SocketStreamHandle %p delete", this);
ASSERT(!m_workerThread);
}
int SocketStreamHandle::platformSend(const char* data, int length)
{
WTF_LOG(Network, "SocketStreamHandle %p platformSend", this);
ASSERT(isMainThread());
startThread();
auto copy = createCopy(data, length);
WTF::Locker<WTF::Mutex> lock(m_mutexSend);
m_sendData.append(adoptPtr(new SocketData(copy, length)));
return length;
}
void SocketStreamHandle::platformClose()
{
WTF_LOG(Network, "SocketStreamHandle %p platformClose", this);
ASSERT(isMainThread());
stopThread();
if (m_client)
m_client->didCloseSocketStream(this);
}
static void s_mainThreadReadData(void* param)
{
SocketStreamHandle* hanlde = (SocketStreamHandle*)param;
hanlde->mainThreadReadData();
}
void SocketStreamHandle::mainThreadReadData()
{
didReceiveData();
deref();
}
bool SocketStreamHandle::readData(CURL* curlHandle)
{
ASSERT(!isMainThread());
const int bufferSize = 1024;
char* data = new char[bufferSize];
size_t bytesRead = 0;
CURLcode ret = curl_easy_recv(curlHandle, data, bufferSize, &bytesRead);
ASSERT(bytesRead <= bufferSize);
if (ret == CURLE_OK && bytesRead >= 0) {
m_mutexReceive.lock();
m_receiveData.append(adoptPtr(new SocketData(data, static_cast<int>(bytesRead))));
m_mutexReceive.unlock();
ref();
WTF::internal::callOnMainThread(s_mainThreadReadData, this);
return true;
}
delete[] data;
if (ret == CURLE_AGAIN)
return true;
return false;
}
bool SocketStreamHandle::sendData(CURL* curlHandle)
{
ASSERT(!isMainThread());
while (true) {
m_mutexSend.lock();
if (!m_sendData.size()) {
m_mutexSend.unlock();
break;
}
PassOwnPtr<SocketData> sendData = m_sendData.takeFirst();
m_mutexSend.unlock();
int totalBytesSent = 0;
while (totalBytesSent < sendData->size) {
size_t bytesSent = 0;
CURLcode ret = curl_easy_send(curlHandle, sendData->data + totalBytesSent, sendData->size - totalBytesSent, &bytesSent);
if (ret == CURLE_OK)
totalBytesSent += bytesSent;
else
break;
}
// Insert remaining data into send queue.
if (totalBytesSent < sendData->size) {
const int restLength = sendData->size - totalBytesSent;
auto copy = createCopy(sendData->data + totalBytesSent, restLength);
WTF::Locker<WTF::Mutex> lock(m_mutexSend);
m_sendData.prepend(adoptPtr(new SocketData(copy, restLength)));
return false;
}
}
return true;
}
// in microseconds
bool SocketStreamHandle::waitForAvailableData(CURL* curlHandle, long long selectTimeout)
{
ASSERT(!isMainThread());
long long usec = selectTimeout * 1000;
struct timeval timeout;
if (usec <= (0)) {
timeout.tv_sec = 0;
timeout.tv_usec = 0;
} else {
timeout.tv_sec = usec / 1000000;
timeout.tv_usec = usec % 1000000;
}
long socket;
if (curl_easy_getinfo(curlHandle, CURLINFO_LASTSOCKET, &socket) != CURLE_OK)
return false;
::Sleep(50);
fd_set fdread;
FD_ZERO(&fdread);
FD_SET(socket, &fdread);
int rc = ::select(0, &fdread, nullptr, nullptr, &timeout);
return rc == 1;
}
static unsigned __stdcall webSocketThread(void* param)
{
base::SetThreadName("WebSocketThread");
SocketStreamHandle* invocation = (static_cast<SocketStreamHandle*>(param));
invocation->threadFunction();
return 0;
}
static void s_mainThreadRun(void* param)
{
SocketStreamHandle* hanlde = (SocketStreamHandle*)param;
hanlde->mainThreadRun();
}
void SocketStreamHandle::mainThreadRun()
{
// Check reference count to fix a crash.
// When the call is invoked on the main thread after all other references are released, the SocketStreamClient
// is already deleted. Accessing the SocketStreamClient in didOpenSocket() will then cause a crash.
if (refCount() > 1)
didOpenSocket();
deref();
}
void SocketStreamHandle::threadFunction()
{
ASSERT(!isMainThread());
CURL* curlHandle = curl_easy_init();
if (!curlHandle)
return;
String url = m_url.host();
unsigned short port = m_url.port();
bool isSSL = !m_url.protocolIs("ws");
if (0 == port)
port = isSSL ? 443 : 80;
if (isSSL)
url = "https://" + url;
//curl_easy_setopt(curlHandle, CURLOPT_URL, m_url.host().utf8().data());
curl_easy_setopt(curlHandle, CURLOPT_URL, url.utf8().data());
curl_easy_setopt(curlHandle, CURLOPT_PORT, port);
curl_easy_setopt(curlHandle, CURLOPT_CONNECT_ONLY);
curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT, 5000);
static const int kAllowedProtocols = CURLPROTO_FILE | CURLPROTO_FTP | CURLPROTO_FTPS | CURLPROTO_HTTP | CURLPROTO_HTTPS;
curl_easy_setopt(curlHandle, CURLOPT_SSL_VERIFYPEER, false); // ignoreSSLErrors
curl_easy_setopt(curlHandle, CURLOPT_SSL_VERIFYHOST, 2L);
curl_easy_setopt(curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_easy_setopt(curlHandle, CURLOPT_DNS_CACHE_TIMEOUT, 60 * 5); // 5 minutes
curl_easy_setopt(curlHandle, CURLOPT_PROTOCOLS, kAllowedProtocols);
curl_easy_setopt(curlHandle, CURLOPT_REDIR_PROTOCOLS, kAllowedProtocols);
// Connect to host
if (curl_easy_perform(curlHandle) != CURLE_OK)
return;
ref();
WTF::internal::callOnMainThread(s_mainThreadRun, this);
while (!m_stopThread) {
// Send queued data
sendData(curlHandle);
// Wait until socket has available data
if (waitForAvailableData(curlHandle, 50))
readData(curlHandle);
}
curl_easy_cleanup(curlHandle);
}
void SocketStreamHandle::startThread()
{
ASSERT(isMainThread());
if (m_workerThread)
return;
ref(); // stopThread() will call deref().
m_workerThread = static_cast<ThreadIdentifier>(_beginthreadex(0, 0, webSocketThread, this, 0, nullptr));
}
int waitForThreadCompletion(ThreadIdentifier threadID)
{
ASSERT(threadID);
HANDLE threadHandle = (HANDLE)(threadID);
// if (!threadHandle)
// WTF_LOG("ThreadIdentifier %u did not correspond to an active thread when trying to quit", threadID);
DWORD joinResult = ::WaitForSingleObject(threadHandle, INFINITE);
// if (joinResult == WAIT_FAILED)
// WTF_LOG("ThreadIdentifier %u was found to be deadlocked trying to quit", threadID);
CloseHandle(threadHandle);
//clearThreadHandleForIdentifier(threadID);
return joinResult;
}
void SocketStreamHandle::stopThread()
{
ASSERT(isMainThread());
if (!m_workerThread)
return;
InterlockedExchange(reinterpret_cast<long volatile*>(&m_stopThread), 1);
waitForThreadCompletion(m_workerThread);
m_workerThread = 0;
deref();
}
void SocketStreamHandle::didReceiveData()
{
ASSERT(isMainThread());
m_mutexReceive.lock();
Deque<OwnPtr<SocketData>> receiveData;
receiveData.swap(m_receiveData);
m_mutexReceive.unlock();
for (auto& socketData : receiveData) {
if (socketData->size > 0) {
if (m_client && state() == Open)
m_client->didReceiveSocketStreamData(this, socketData->data, socketData->size);
} else
platformClose();
}
}
void SocketStreamHandle::didOpenSocket()
{
ASSERT(isMainThread());
m_state = Open;
if (m_client)
m_client->didOpenSocketStream(this);
}
char* SocketStreamHandle::createCopy(const char* data, int length)
{
char* copy = (new char[length]);
memcpy(copy, data, length);
return copy;
}
void SocketStreamHandle::didReceiveAuthenticationChallenge(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedCredential(const AuthenticationChallenge&, const Credential&)
{
notImplemented();
}
void SocketStreamHandle::receivedRequestToContinueWithoutCredential(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedCancellation(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedRequestToPerformDefaultHandling(const AuthenticationChallenge&)
{
notImplemented();
}
void SocketStreamHandle::receivedChallengeRejection(const AuthenticationChallenge&)
{
notImplemented();
}
} // namespace net<|endoftext|>
|
<commit_before><commit_msg>cyber: fix compile warning<commit_after><|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "messaging.h"
#include "utilities.h"
#pragma warning (disable: 4091)
#include <dbghelp.h>
LONG CALLBACK unhandled_handler(::EXCEPTION_POINTERS* e)
{
auto hDbgHelp = ::LoadLibraryA("dbghelp");
if (hDbgHelp == nullptr)
return EXCEPTION_CONTINUE_SEARCH;
auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))::GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
if (pMiniDumpWriteDump == nullptr)
return EXCEPTION_CONTINUE_SEARCH;
char name[MAX_PATH];
{
auto nameEnd = name + ::GetModuleFileNameA(::GetModuleHandleA(0), name, MAX_PATH);
::SYSTEMTIME t;
::GetLocalTime(&t);
wsprintfA(nameEnd - strlen(".exe"),
"_crashdump_%4d%02d%02d_%02d%02d%02d.dmp",
t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
}
auto hFile = ::CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
return EXCEPTION_CONTINUE_SEARCH;
::MINIDUMP_EXCEPTION_INFORMATION exceptionInfo;
exceptionInfo.ThreadId = ::GetCurrentThreadId();
exceptionInfo.ExceptionPointers = e;
exceptionInfo.ClientPointers = FALSE;
auto dumped = pMiniDumpWriteDump(
::GetCurrentProcess(),
::GetCurrentProcessId(),
hFile,
::MINIDUMP_TYPE(::MiniDumpWithIndirectlyReferencedMemory | ::MiniDumpScanMemory),
e ? &exceptionInfo : nullptr,
nullptr,
nullptr);
::CloseHandle(hFile);
return EXCEPTION_CONTINUE_SEARCH;
}
HWND Hwnd;
WNDPROC BaseWindowProc;
PCOPYDATASTRUCT pDane;
LRESULT APIENTRY WndProc( HWND hWnd, // handle for this window
UINT uMsg, // message for this window
WPARAM wParam, // additional message information
LPARAM lParam) // additional message information
{
switch( uMsg ) // check for windows messages
{
case WM_COPYDATA: {
// obsługa danych przesłanych przez program sterujący
pDane = (PCOPYDATASTRUCT)lParam;
if( pDane->dwData == MAKE_ID4('E', 'U', '0', '7')) // sygnatura danych
multiplayer::OnCommandGet( ( multiplayer::DaneRozkaz *)( pDane->lpData ) );
break;
}
case WM_KEYDOWN:
case WM_KEYUP: {
if (wParam == VK_INSERT || wParam == VK_DELETE || wParam == VK_HOME || wParam == VK_END ||
wParam == VK_PRIOR || wParam == VK_NEXT || wParam == VK_SNAPSHOT)
lParam &= ~0x1ff0000;
if (wParam == VK_INSERT)
lParam |= 0x152 << 16;
else if (wParam == VK_DELETE)
lParam |= 0x153 << 16;
else if (wParam == VK_HOME)
lParam |= 0x147 << 16;
else if (wParam == VK_END)
lParam |= 0x14F << 16;
else if (wParam == VK_PRIOR)
lParam |= 0x149 << 16;
else if (wParam == VK_NEXT)
lParam |= 0x151 << 16;
else if (wParam == VK_SNAPSHOT)
lParam |= 0x137 << 16;
break;
}
}
// pass all messages to DefWindowProc
return CallWindowProc( BaseWindowProc, Hwnd, uMsg, wParam, lParam );
};
<commit_msg>use magic symbols to hint amd/nvidia driver to use dedicated gpu<commit_after>#include "stdafx.h"
#include "messaging.h"
#include "utilities.h"
#pragma warning (disable: 4091)
#include <dbghelp.h>
extern "C"
{
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
__declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
}
LONG CALLBACK unhandled_handler(::EXCEPTION_POINTERS* e)
{
auto hDbgHelp = ::LoadLibraryA("dbghelp");
if (hDbgHelp == nullptr)
return EXCEPTION_CONTINUE_SEARCH;
auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))::GetProcAddress(hDbgHelp, "MiniDumpWriteDump");
if (pMiniDumpWriteDump == nullptr)
return EXCEPTION_CONTINUE_SEARCH;
char name[MAX_PATH];
{
auto nameEnd = name + ::GetModuleFileNameA(::GetModuleHandleA(0), name, MAX_PATH);
::SYSTEMTIME t;
::GetLocalTime(&t);
wsprintfA(nameEnd - strlen(".exe"),
"_crashdump_%4d%02d%02d_%02d%02d%02d.dmp",
t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
}
auto hFile = ::CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
return EXCEPTION_CONTINUE_SEARCH;
::MINIDUMP_EXCEPTION_INFORMATION exceptionInfo;
exceptionInfo.ThreadId = ::GetCurrentThreadId();
exceptionInfo.ExceptionPointers = e;
exceptionInfo.ClientPointers = FALSE;
auto dumped = pMiniDumpWriteDump(
::GetCurrentProcess(),
::GetCurrentProcessId(),
hFile,
::MINIDUMP_TYPE(::MiniDumpWithIndirectlyReferencedMemory | ::MiniDumpScanMemory),
e ? &exceptionInfo : nullptr,
nullptr,
nullptr);
::CloseHandle(hFile);
return EXCEPTION_CONTINUE_SEARCH;
}
HWND Hwnd;
WNDPROC BaseWindowProc;
PCOPYDATASTRUCT pDane;
LRESULT APIENTRY WndProc( HWND hWnd, // handle for this window
UINT uMsg, // message for this window
WPARAM wParam, // additional message information
LPARAM lParam) // additional message information
{
switch( uMsg ) // check for windows messages
{
case WM_COPYDATA: {
// obsługa danych przesłanych przez program sterujący
pDane = (PCOPYDATASTRUCT)lParam;
if( pDane->dwData == MAKE_ID4('E', 'U', '0', '7')) // sygnatura danych
multiplayer::OnCommandGet( ( multiplayer::DaneRozkaz *)( pDane->lpData ) );
break;
}
case WM_KEYDOWN:
case WM_KEYUP: {
if (wParam == VK_INSERT || wParam == VK_DELETE || wParam == VK_HOME || wParam == VK_END ||
wParam == VK_PRIOR || wParam == VK_NEXT || wParam == VK_SNAPSHOT)
lParam &= ~0x1ff0000;
if (wParam == VK_INSERT)
lParam |= 0x152 << 16;
else if (wParam == VK_DELETE)
lParam |= 0x153 << 16;
else if (wParam == VK_HOME)
lParam |= 0x147 << 16;
else if (wParam == VK_END)
lParam |= 0x14F << 16;
else if (wParam == VK_PRIOR)
lParam |= 0x149 << 16;
else if (wParam == VK_NEXT)
lParam |= 0x151 << 16;
else if (wParam == VK_SNAPSHOT)
lParam |= 0x137 << 16;
break;
}
}
// pass all messages to DefWindowProc
return CallWindowProc( BaseWindowProc, Hwnd, uMsg, wParam, lParam );
};
<|endoftext|>
|
<commit_before>
#include "mitkManualSegmentationToSurfaceFilter.h"
#include <fstream>
int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])
{
mitk::ManualSegmentationToSurfaceFilter::Pointer filter;
std::cout << "Testing mitk::ManualSegmentationToSurfaceFilter::New(): ";
filter = mitk::ManualSegmentationToSurfaceFilter::New();
if (filter.IsNull())
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
else {
std::cout<<"[PASSED]"<<std::endl;
}
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}<commit_msg>FIX: warnings<commit_after>
#include "mitkManualSegmentationToSurfaceFilter.h"
#include <fstream>
int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[])
{
mitk::ManualSegmentationToSurfaceFilter::Pointer filter;
std::cout << "Testing mitk::ManualSegmentationToSurfaceFilter::New(): ";
filter = mitk::ManualSegmentationToSurfaceFilter::New();
if (filter.IsNull())
{
std::cout<<"[FAILED]"<<std::endl;
return EXIT_FAILURE;
}
else {
std::cout<<"[PASSED]"<<std::endl;
}
std::cout<<"[TEST DONE]"<<std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "TextureUploader.hpp"
#include "TestingEnvironment.hpp"
#include "gtest/gtest.h"
#include <atomic>
#include <thread>
using namespace Diligent;
using namespace Diligent::Testing;
namespace
{
Uint32 WriteOrVerifyRGBAData(MappedTextureSubresource& MappedData,
const UploadBufferDesc& UploadBuffDesc,
Uint32 Mip,
Uint32 Slice,
Uint32& cnt,
bool Verify)
{
Uint8* pRGBAData = reinterpret_cast<Uint8*>(MappedData.pData);
Uint32 NumInvalidPixels = 0;
const Uint32 Width = UploadBuffDesc.Width >> Mip;
const Uint32 Height = UploadBuffDesc.Height >> Mip;
if (Verify)
{
for (Uint32 y = 0; y < Height; ++y)
{
for (Uint32 x = 0; x < Width; ++x)
{
const Uint8* pRGBA = pRGBAData + x * 4 + MappedData.Stride * y;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 13) & 0xFF)) ? 1 : 0;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 27) & 0xFF)) ? 1 : 0;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 7) & 0xFF)) ? 1 : 0;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 3) & 0xFF)) ? 1 : 0;
}
}
if (NumInvalidPixels != 0)
{
ADD_FAILURE() << "Found " << NumInvalidPixels << " invalid pixels in mip level " << Mip << ", slice " << Slice;
}
}
else
{
for (Uint32 y = 0; y < Height; ++y)
{
for (Uint32 x = 0; x < Width; ++x)
{
Uint8* pRGBA = pRGBAData + x * 4 + MappedData.Stride * y;
*(pRGBA++) = (cnt += 13) & 0xFF;
*(pRGBA++) = (cnt += 27) & 0xFF;
*(pRGBA++) = (cnt += 7) & 0xFF;
*(pRGBA++) = (cnt += 3) & 0xFF;
}
}
}
return NumInvalidPixels;
}
void TextureUploaderTest(bool IsRenderThread)
{
auto* pEnv = TestingEnvironment::GetInstance();
auto* pDevice = pEnv->GetDevice();
auto* pContext = pEnv->GetDeviceContext();
TextureUploaderDesc UploaderDesc;
RefCntAutoPtr<ITextureUploader> pTexUploader;
CreateTextureUploader(pDevice, UploaderDesc, &pTexUploader);
ASSERT_TRUE(pTexUploader);
TextureDesc TexDesc;
TexDesc.Name = "Texture uploading dst texture";
TexDesc.Type = RESOURCE_DIM_TEX_2D_ARRAY;
TexDesc.Width = 256;
TexDesc.Height = 128;
TexDesc.MipLevels = 0;
TexDesc.ArraySize = 8;
TexDesc.BindFlags = BIND_SHADER_RESOURCE;
TexDesc.Format = TEX_FORMAT_RGBA8_UNORM;
RefCntAutoPtr<ITexture> pDstTexture;
pDevice->CreateTexture(TexDesc, nullptr, &pDstTexture);
TexDesc.Name = "Texture uploading staging texture";
TexDesc.Usage = USAGE_STAGING;
TexDesc.CPUAccessFlags = CPU_ACCESS_READ;
TexDesc.BindFlags = BIND_NONE;
RefCntAutoPtr<ITexture> pStagingTexture;
pDevice->CreateTexture(TexDesc, nullptr, &pStagingTexture);
constexpr Uint32 StartDstSlice = 2;
constexpr Uint32 StartDstMip = 1;
UploadBufferDesc UploadBuffDesc;
UploadBuffDesc.Width = TexDesc.Width >> StartDstMip;
UploadBuffDesc.Height = TexDesc.Height >> StartDstMip;
UploadBuffDesc.Format = TEX_FORMAT_RGBA8_UNORM;
UploadBuffDesc.MipLevels = 2;
UploadBuffDesc.ArraySize = 4;
Uint32 cnt = 0;
for (Uint32 i = 0; i < 3; ++i)
{
auto ref_cnt = cnt;
std::atomic_bool BufferPopulated = false;
auto PopulateBuffer = [&](IDeviceContext* pCtx) //
{
RefCntAutoPtr<IUploadBuffer> pUploadBuffer;
pTexUploader->AllocateUploadBuffer(pCtx, UploadBuffDesc, &pUploadBuffer);
for (Uint32 slice = 0; slice < UploadBuffDesc.ArraySize; ++slice)
{
for (Uint32 mip = 0; mip < UploadBuffDesc.MipLevels; ++mip)
{
auto MappedData = pUploadBuffer->GetMappedData(mip, slice);
WriteOrVerifyRGBAData(MappedData, UploadBuffDesc, mip, slice, cnt, false);
}
}
pTexUploader->ScheduleGPUCopy(pCtx, pDstTexture, StartDstSlice, StartDstMip, pUploadBuffer);
if (pCtx == nullptr)
{
pUploadBuffer->WaitForCopyScheduled();
}
pTexUploader->RecycleBuffer(pUploadBuffer);
BufferPopulated = true;
};
if (IsRenderThread)
{
PopulateBuffer(pContext);
}
else
{
std::thread WokerThread{PopulateBuffer, nullptr};
while (!BufferPopulated)
{
pTexUploader->RenderThreadUpdate(pContext);
}
WokerThread.join();
}
for (Uint32 slice = StartDstSlice; slice < StartDstSlice + UploadBuffDesc.ArraySize; ++slice)
{
for (Uint32 mip = StartDstMip; mip < StartDstMip + UploadBuffDesc.MipLevels; ++mip)
{
CopyTextureAttribs CopyAttribs{pDstTexture, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, pStagingTexture, RESOURCE_STATE_TRANSITION_MODE_TRANSITION};
CopyAttribs.SrcMipLevel = mip;
CopyAttribs.SrcSlice = slice;
CopyAttribs.DstMipLevel = mip;
CopyAttribs.DstSlice = slice;
pContext->CopyTexture(CopyAttribs);
}
}
pContext->WaitForIdle();
for (Uint32 slice = 0; slice < UploadBuffDesc.ArraySize; ++slice)
{
for (Uint32 mip = 0; mip < UploadBuffDesc.MipLevels; ++mip)
{
MappedTextureSubresource MappedData;
pContext->MapTextureSubresource(pStagingTexture, StartDstMip + mip, StartDstSlice + slice, MAP_READ, MAP_FLAG_DO_NOT_WAIT, nullptr, MappedData);
WriteOrVerifyRGBAData(MappedData, UploadBuffDesc, mip, slice, ref_cnt, true);
pContext->UnmapTextureSubresource(pStagingTexture, StartDstMip + mip, StartDstSlice + slice);
}
}
}
}
TEST(TextureUploaderTest, RenderThread)
{
TextureUploaderTest(true);
}
TEST(TextureUploaderTest, WorkerThread)
{
TextureUploaderTest(false);
}
} // namespace
<commit_msg>Fixed Mac/Linux build error<commit_after>/*
* Copyright 2019-2020 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "TextureUploader.hpp"
#include "TestingEnvironment.hpp"
#include "gtest/gtest.h"
#include <atomic>
#include <thread>
using namespace Diligent;
using namespace Diligent::Testing;
namespace
{
Uint32 WriteOrVerifyRGBAData(MappedTextureSubresource& MappedData,
const UploadBufferDesc& UploadBuffDesc,
Uint32 Mip,
Uint32 Slice,
Uint32& cnt,
bool Verify)
{
Uint8* pRGBAData = reinterpret_cast<Uint8*>(MappedData.pData);
Uint32 NumInvalidPixels = 0;
const Uint32 Width = UploadBuffDesc.Width >> Mip;
const Uint32 Height = UploadBuffDesc.Height >> Mip;
if (Verify)
{
for (Uint32 y = 0; y < Height; ++y)
{
for (Uint32 x = 0; x < Width; ++x)
{
const Uint8* pRGBA = pRGBAData + x * 4 + MappedData.Stride * y;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 13) & 0xFF)) ? 1 : 0;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 27) & 0xFF)) ? 1 : 0;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 7) & 0xFF)) ? 1 : 0;
NumInvalidPixels += (*(pRGBA++) != ((cnt += 3) & 0xFF)) ? 1 : 0;
}
}
if (NumInvalidPixels != 0)
{
ADD_FAILURE() << "Found " << NumInvalidPixels << " invalid pixels in mip level " << Mip << ", slice " << Slice;
}
}
else
{
for (Uint32 y = 0; y < Height; ++y)
{
for (Uint32 x = 0; x < Width; ++x)
{
Uint8* pRGBA = pRGBAData + x * 4 + MappedData.Stride * y;
*(pRGBA++) = (cnt += 13) & 0xFF;
*(pRGBA++) = (cnt += 27) & 0xFF;
*(pRGBA++) = (cnt += 7) & 0xFF;
*(pRGBA++) = (cnt += 3) & 0xFF;
}
}
}
return NumInvalidPixels;
}
void TextureUploaderTest(bool IsRenderThread)
{
auto* pEnv = TestingEnvironment::GetInstance();
auto* pDevice = pEnv->GetDevice();
auto* pContext = pEnv->GetDeviceContext();
TextureUploaderDesc UploaderDesc;
RefCntAutoPtr<ITextureUploader> pTexUploader;
CreateTextureUploader(pDevice, UploaderDesc, &pTexUploader);
ASSERT_TRUE(pTexUploader);
TextureDesc TexDesc;
TexDesc.Name = "Texture uploading dst texture";
TexDesc.Type = RESOURCE_DIM_TEX_2D_ARRAY;
TexDesc.Width = 256;
TexDesc.Height = 128;
TexDesc.MipLevels = 0;
TexDesc.ArraySize = 8;
TexDesc.BindFlags = BIND_SHADER_RESOURCE;
TexDesc.Format = TEX_FORMAT_RGBA8_UNORM;
RefCntAutoPtr<ITexture> pDstTexture;
pDevice->CreateTexture(TexDesc, nullptr, &pDstTexture);
TexDesc.Name = "Texture uploading staging texture";
TexDesc.Usage = USAGE_STAGING;
TexDesc.CPUAccessFlags = CPU_ACCESS_READ;
TexDesc.BindFlags = BIND_NONE;
RefCntAutoPtr<ITexture> pStagingTexture;
pDevice->CreateTexture(TexDesc, nullptr, &pStagingTexture);
constexpr Uint32 StartDstSlice = 2;
constexpr Uint32 StartDstMip = 1;
UploadBufferDesc UploadBuffDesc;
UploadBuffDesc.Width = TexDesc.Width >> StartDstMip;
UploadBuffDesc.Height = TexDesc.Height >> StartDstMip;
UploadBuffDesc.Format = TEX_FORMAT_RGBA8_UNORM;
UploadBuffDesc.MipLevels = 2;
UploadBuffDesc.ArraySize = 4;
Uint32 cnt = 0;
for (Uint32 i = 0; i < 3; ++i)
{
auto ref_cnt = cnt;
std::atomic_bool BufferPopulated;
BufferPopulated.store(false);
auto PopulateBuffer = [&](IDeviceContext* pCtx) //
{
RefCntAutoPtr<IUploadBuffer> pUploadBuffer;
pTexUploader->AllocateUploadBuffer(pCtx, UploadBuffDesc, &pUploadBuffer);
for (Uint32 slice = 0; slice < UploadBuffDesc.ArraySize; ++slice)
{
for (Uint32 mip = 0; mip < UploadBuffDesc.MipLevels; ++mip)
{
auto MappedData = pUploadBuffer->GetMappedData(mip, slice);
WriteOrVerifyRGBAData(MappedData, UploadBuffDesc, mip, slice, cnt, false);
}
}
pTexUploader->ScheduleGPUCopy(pCtx, pDstTexture, StartDstSlice, StartDstMip, pUploadBuffer);
if (pCtx == nullptr)
{
pUploadBuffer->WaitForCopyScheduled();
}
pTexUploader->RecycleBuffer(pUploadBuffer);
BufferPopulated.store(true);
};
if (IsRenderThread)
{
PopulateBuffer(pContext);
}
else
{
std::thread WokerThread{PopulateBuffer, nullptr};
while (!BufferPopulated)
{
pTexUploader->RenderThreadUpdate(pContext);
}
WokerThread.join();
}
for (Uint32 slice = StartDstSlice; slice < StartDstSlice + UploadBuffDesc.ArraySize; ++slice)
{
for (Uint32 mip = StartDstMip; mip < StartDstMip + UploadBuffDesc.MipLevels; ++mip)
{
CopyTextureAttribs CopyAttribs{pDstTexture, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, pStagingTexture, RESOURCE_STATE_TRANSITION_MODE_TRANSITION};
CopyAttribs.SrcMipLevel = mip;
CopyAttribs.SrcSlice = slice;
CopyAttribs.DstMipLevel = mip;
CopyAttribs.DstSlice = slice;
pContext->CopyTexture(CopyAttribs);
}
}
pContext->WaitForIdle();
for (Uint32 slice = 0; slice < UploadBuffDesc.ArraySize; ++slice)
{
for (Uint32 mip = 0; mip < UploadBuffDesc.MipLevels; ++mip)
{
MappedTextureSubresource MappedData;
pContext->MapTextureSubresource(pStagingTexture, StartDstMip + mip, StartDstSlice + slice, MAP_READ, MAP_FLAG_DO_NOT_WAIT, nullptr, MappedData);
WriteOrVerifyRGBAData(MappedData, UploadBuffDesc, mip, slice, ref_cnt, true);
pContext->UnmapTextureSubresource(pStagingTexture, StartDstMip + mip, StartDstSlice + slice);
}
}
}
}
TEST(TextureUploaderTest, RenderThread)
{
TextureUploaderTest(true);
}
TEST(TextureUploaderTest, WorkerThread)
{
TextureUploaderTest(false);
}
} // namespace
<|endoftext|>
|
<commit_before>#include "Halide.h"
#include <cstdio>
#include <algorithm>
#include "benchmark.h"
using namespace Halide;
// 32-bit windows defines powf as a macro, which won't work for us.
#ifdef _WIN32
extern "C" __declspec(dllexport) float pow_ref(float x, float y) {
return pow(x, y);
}
#else
extern "C" float pow_ref(float x, float y) {
return powf(x, y);
}
#endif
HalideExtern_2(float, pow_ref, float, float);
int main(int argc, char **argv) {
Func f, g, h;
Var x, y;
Param<int> pows_per_pixel;
RDom s(0, pows_per_pixel);
f(x, y) = sum(pow_ref((x+1)/512.0f, (y+1+s)/512.0f));
g(x, y) = sum(pow((x+1)/512.0f, (y+1+s)/512.0f));
h(x, y) = sum(fast_pow((x+1)/512.0f, (y+1+s)/512.0f));
f.vectorize(x, 8);
g.vectorize(x, 8);
h.vectorize(x, 8);
Image<float> correct_result(2048, 768);
Image<float> fast_result(2048, 768);
Image<float> faster_result(2048, 768);
pows_per_pixel.set(1);
f.realize(correct_result);
g.realize(fast_result);
h.realize(faster_result);
const int trials = 5;
const int iterations = 5;
pows_per_pixel.set(10);
// All profiling runs are done into the same buffer, to avoid
// cache weirdness.
Image<float> timing_scratch(256, 256);
double t1 = 1e3 * benchmark(trials, iterations, [&]() { f.realize(timing_scratch); });
double t2 = 1e3 * benchmark(trials, iterations, [&]() { g.realize(timing_scratch); });
double t3 = 1e3 * benchmark(trials, iterations, [&]() { h.realize(timing_scratch); });
RDom r(correct_result);
Func fast_error, faster_error;
Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y);
Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y);
fast_error() += cast<double>(fast_delta * fast_delta);
faster_error() += cast<double>(faster_delta * faster_delta);
Image<double> fast_err = fast_error.realize();
Image<double> faster_err = faster_error.realize();
int timing_N = timing_scratch.width() * timing_scratch.height() * 10;
int correctness_N = fast_result.width() * fast_result.height();
fast_err(0) = sqrt(fast_err(0)/correctness_N);
faster_err(0) = sqrt(faster_err(0)/correctness_N);
printf("powf: %f ns per pixel\n"
"Halide's pow: %f ns per pixel (rms error = %0.10f)\n"
"Halide's fast_pow: %f ns per pixel (rms error = %0.10f)\n",
1000000*t1 / timing_N,
1000000*t2 / timing_N, fast_err(0),
1000000*t3 / timing_N, faster_err(0));
if (fast_err(0) > 0.000001) {
printf("Error for pow too large\n");
return -1;
}
if (faster_err(0) > 0.0001) {
printf("Error for fast_pow too large\n");
return -1;
}
if (t1 < t2) {
printf("powf is faster than Halide's pow\n");
return -1;
}
if (t2 < t3) {
printf("pow is faster than fast_pow\n");
return -1;
}
printf("Success!\n");
return 0;
}
<commit_msg>Make fast_pow test less flaky<commit_after>#include "Halide.h"
#include <cstdio>
#include <algorithm>
#include "benchmark.h"
using namespace Halide;
// 32-bit windows defines powf as a macro, which won't work for us.
#ifdef _WIN32
extern "C" __declspec(dllexport) float pow_ref(float x, float y) {
return pow(x, y);
}
#else
extern "C" float pow_ref(float x, float y) {
return powf(x, y);
}
#endif
HalideExtern_2(float, pow_ref, float, float);
int main(int argc, char **argv) {
Func f, g, h;
Var x, y;
Param<int> pows_per_pixel;
RDom s(0, pows_per_pixel);
f(x, y) = sum(pow_ref((x+1)/512.0f, (y+1+s)/512.0f));
g(x, y) = sum(pow((x+1)/512.0f, (y+1+s)/512.0f));
h(x, y) = sum(fast_pow((x+1)/512.0f, (y+1+s)/512.0f));
f.vectorize(x, 8);
g.vectorize(x, 8);
h.vectorize(x, 8);
Image<float> correct_result(2048, 768);
Image<float> fast_result(2048, 768);
Image<float> faster_result(2048, 768);
pows_per_pixel.set(1);
f.realize(correct_result);
g.realize(fast_result);
h.realize(faster_result);
const int trials = 5;
const int iterations = 5;
pows_per_pixel.set(20);
// All profiling runs are done into the same buffer, to avoid
// cache weirdness.
Image<float> timing_scratch(256, 256);
double t1 = 1e3 * benchmark(trials, iterations, [&]() { f.realize(timing_scratch); });
double t2 = 1e3 * benchmark(trials, iterations, [&]() { g.realize(timing_scratch); });
double t3 = 1e3 * benchmark(trials, iterations, [&]() { h.realize(timing_scratch); });
RDom r(correct_result);
Func fast_error, faster_error;
Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y);
Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y);
fast_error() += cast<double>(fast_delta * fast_delta);
faster_error() += cast<double>(faster_delta * faster_delta);
Image<double> fast_err = fast_error.realize();
Image<double> faster_err = faster_error.realize();
int timing_N = timing_scratch.width() * timing_scratch.height() * 10;
int correctness_N = fast_result.width() * fast_result.height();
fast_err(0) = sqrt(fast_err(0)/correctness_N);
faster_err(0) = sqrt(faster_err(0)/correctness_N);
printf("powf: %f ns per pixel\n"
"Halide's pow: %f ns per pixel (rms error = %0.10f)\n"
"Halide's fast_pow: %f ns per pixel (rms error = %0.10f)\n",
1000000*t1 / timing_N,
1000000*t2 / timing_N, fast_err(0),
1000000*t3 / timing_N, faster_err(0));
if (fast_err(0) > 0.000001) {
printf("Error for pow too large\n");
return -1;
}
if (faster_err(0) > 0.0001) {
printf("Error for fast_pow too large\n");
return -1;
}
if (t1 < t2) {
printf("powf is faster than Halide's pow\n");
return -1;
}
if (t2*1.5 < t3) {
printf("pow is more than 1.5x faster than fast_pow\n");
return -1;
}
printf("Success!\n");
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2022-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
#include <utility>
#include <seastar/core/future.hh>
#include "utils/result.hh"
namespace utils {
// Converts a result into either a ready or an exceptional future.
// Supports only results which has an exception_container as their error type.
template<typename R>
requires ExceptionContainerResult<R>
seastar::future<typename R::value_type> result_into_future(R&& res) {
if (res) {
if constexpr (std::is_void_v<typename R::value_type>) {
return seastar::make_ready_future<>();
} else {
return seastar::make_ready_future<typename R::value_type>(std::move(res).assume_value());
}
} else {
return std::move(res).assume_error().template into_exception_future<typename R::value_type>();
}
}
// Converts a non-result future to return a successful result.
// It _does not_ convert exceptional futures to failed results.
template<typename R>
requires ExceptionContainerResult<R>
seastar::future<R> then_ok_result(seastar::future<typename R::value_type>&& f) {
using T = typename R::value_type;
if constexpr (std::is_void_v<T>) {
return f.then([] {
return seastar::make_ready_future<R>(bo::success());
});
} else {
return f.then([] (T&& t) {
return seastar::make_ready_future<R>(bo::success(std::move(t)));
});
}
}
namespace internal {
template<typename C, typename Arg>
struct result_wrapped_call_traits {
static_assert(ExceptionContainerResult<Arg>);
using return_type = decltype(seastar::futurize_invoke(std::declval<C>(), std::declval<typename Arg::value_type>()));
static auto invoke_with_value(C& c, Arg&& arg) {
// Arg must have a value
return seastar::futurize_invoke(c, std::move(arg).value());
}
};
template<typename C, typename... Exs>
struct result_wrapped_call_traits<C, result_with_exception<void, Exs...>> {
using return_type = decltype(seastar::futurize_invoke(std::declval<C>()));
static auto invoke_with_value(C& c, result_with_exception<void, Exs...>&& arg) {
return seastar::futurize_invoke(c);
}
};
template<typename C>
struct result_wrapper {
C c;
result_wrapper(C&& c) : c(std::move(c)) {}
template<typename InputResult>
requires ExceptionContainerResult<InputResult>
auto operator()(InputResult arg) {
using traits = internal::result_wrapped_call_traits<C, InputResult>;
using return_type = typename traits::return_type;
static_assert(ExceptionContainerResultFuture<return_type>,
"the return type of the call must be a future<result<T>> for some T");
using return_result_type = typename return_type::value_type;
static_assert(std::is_same_v<typename InputResult::error_type, typename return_result_type::error_type>,
"the error type of accepted result and returned result are not the same");
if (arg) {
return traits::invoke_with_value(c, std::move(arg));
} else {
return seastar::make_ready_future<return_result_type>(bo::failure(std::move(arg).assume_error()));
}
}
};
}
// Converts a callable to accept a result<T> instead of T.
// Given a callable which can be called with following arguments and return type:
//
// (T) -> future<result<U>>
//
// ...returns a new callable which can be called with the following signature:
//
// (result<T>) -> future<result<U>>
//
// On call, the adapted callable is run only if the result<T> contains a value.
// Otherwise, the adapted callable is not called and the error is returned immediately.
// The resulting callable must receive result<> as an argument when being called,
// it won't be automatically converted to result<>.
template<typename C>
auto result_wrap(C&& c) {
return internal::result_wrapper<C>(std::move(c));
}
}
<commit_msg>result_combinators: add result_discard_value<commit_after>/*
* Copyright 2022-present ScyllaDB
*/
/*
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#pragma once
#include <utility>
#include <seastar/core/future.hh>
#include "utils/result.hh"
namespace utils {
// Converts a result into either a ready or an exceptional future.
// Supports only results which has an exception_container as their error type.
template<typename R>
requires ExceptionContainerResult<R>
seastar::future<typename R::value_type> result_into_future(R&& res) {
if (res) {
if constexpr (std::is_void_v<typename R::value_type>) {
return seastar::make_ready_future<>();
} else {
return seastar::make_ready_future<typename R::value_type>(std::move(res).assume_value());
}
} else {
return std::move(res).assume_error().template into_exception_future<typename R::value_type>();
}
}
// Converts a non-result future to return a successful result.
// It _does not_ convert exceptional futures to failed results.
template<typename R>
requires ExceptionContainerResult<R>
seastar::future<R> then_ok_result(seastar::future<typename R::value_type>&& f) {
using T = typename R::value_type;
if constexpr (std::is_void_v<T>) {
return f.then([] {
return seastar::make_ready_future<R>(bo::success());
});
} else {
return f.then([] (T&& t) {
return seastar::make_ready_future<R>(bo::success(std::move(t)));
});
}
}
// Takes a result<T>, discards the inner value and returns result<>.
template<ExceptionContainerResult R>
rebind_result<void, R> result_discard_value(R&& res) {
if (res) {
return bo::success();
} else {
return std::move(res).as_failure();
}
}
namespace internal {
template<typename C, typename Arg>
struct result_wrapped_call_traits {
static_assert(ExceptionContainerResult<Arg>);
using return_type = decltype(seastar::futurize_invoke(std::declval<C>(), std::declval<typename Arg::value_type>()));
static auto invoke_with_value(C& c, Arg&& arg) {
// Arg must have a value
return seastar::futurize_invoke(c, std::move(arg).value());
}
};
template<typename C, typename... Exs>
struct result_wrapped_call_traits<C, result_with_exception<void, Exs...>> {
using return_type = decltype(seastar::futurize_invoke(std::declval<C>()));
static auto invoke_with_value(C& c, result_with_exception<void, Exs...>&& arg) {
return seastar::futurize_invoke(c);
}
};
template<typename C>
struct result_wrapper {
C c;
result_wrapper(C&& c) : c(std::move(c)) {}
template<typename InputResult>
requires ExceptionContainerResult<InputResult>
auto operator()(InputResult arg) {
using traits = internal::result_wrapped_call_traits<C, InputResult>;
using return_type = typename traits::return_type;
static_assert(ExceptionContainerResultFuture<return_type>,
"the return type of the call must be a future<result<T>> for some T");
using return_result_type = typename return_type::value_type;
static_assert(std::is_same_v<typename InputResult::error_type, typename return_result_type::error_type>,
"the error type of accepted result and returned result are not the same");
if (arg) {
return traits::invoke_with_value(c, std::move(arg));
} else {
return seastar::make_ready_future<return_result_type>(bo::failure(std::move(arg).assume_error()));
}
}
};
}
// Converts a callable to accept a result<T> instead of T.
// Given a callable which can be called with following arguments and return type:
//
// (T) -> future<result<U>>
//
// ...returns a new callable which can be called with the following signature:
//
// (result<T>) -> future<result<U>>
//
// On call, the adapted callable is run only if the result<T> contains a value.
// Otherwise, the adapted callable is not called and the error is returned immediately.
// The resulting callable must receive result<> as an argument when being called,
// it won't be automatically converted to result<>.
template<typename C>
auto result_wrap(C&& c) {
return internal::result_wrapper<C>(std::move(c));
}
}
<|endoftext|>
|
<commit_before>/*
* AudioInputAccessor.cpp
*
* Created on: Mar 13, 2014
* Author: Jimin
*/
#include "AudioInputAccessor.h"
static const float kShortMax = (float)(SHRT_MAX);
void recorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{
((AudioInputAccessor *)context)->newInputBuffer();
};
AudioInputAccessor::AudioInputAccessor(int frameSize, Tapir::SignalDetector * detector)
:m_frameSize(frameSize),
m_frameByteSize(m_frameSize * sizeof(short)),
m_detector(detector),
m_objEngine(nullptr),
m_engine(nullptr),
m_objRecorder(nullptr),
m_recorder(nullptr),
m_bufferQueue(nullptr),
m_curBufferIdx(0),
m_noBuffer(3),
m_buffer(nullptr),
m_floatBuffer(new float[m_frameSize])
{
//Allocate Buffer
m_buffer = new short*[m_noBuffer];
for(int i=0; i<m_noBuffer; ++i)
{ m_buffer[i] = new short[m_frameSize]; }
// create engine
slCreateEngine(&m_objEngine, 0, nullptr, 0, nullptr, nullptr);
// realize the engine
(*m_objEngine)->Realize(m_objEngine, SL_BOOLEAN_FALSE);
// get the engine interface, which is needed in order to create other objects
(*m_objEngine)->GetInterface(m_objEngine, SL_IID_ENGINE, &m_engine);
// configure audio source
SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT,
SL_DEFAULTDEVICEID_AUDIOINPUT, NULL};
SLDataSource audioSrc = {&loc_dev, NULL};
// configure audio sink
SLDataLocator_AndroidSimpleBufferQueue loc_bq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<unsigned int>(m_noBuffer)};
SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_44_1,
SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
SL_SPEAKER_FRONT_CENTER, SL_BYTEORDER_LITTLEENDIAN};
SLDataSink audioSnk = {&loc_bq, &format_pcm};
// create audio recorder
// (requires the RECORD_AUDIO permission)
const SLInterfaceID id[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE};
const SLboolean req[1] = {SL_BOOLEAN_TRUE};
(*m_engine)->CreateAudioRecorder(m_engine, &m_objRecorder, &audioSrc, &audioSnk, 1, id, req);
// realize the audio recorder
(*m_objRecorder)->Realize(m_objRecorder, SL_BOOLEAN_FALSE);
// get the record interface
(*m_objRecorder)->GetInterface(m_objRecorder, SL_IID_RECORD, &m_recorder);
// get the buffer queue interface
(*m_objRecorder)->GetInterface(m_objRecorder, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
&m_bufferQueue);
// register callback on the buffer queue
(*m_bufferQueue)->RegisterCallback(m_bufferQueue, recorderCallback, this);
//Enqueue Buffer
for(int i=0; i<m_noBuffer; ++i)
{
(*m_bufferQueue)->Enqueue(m_bufferQueue, m_buffer[i], m_frameByteSize);
}
};
AudioInputAccessor::~AudioInputAccessor()
{
// destroy audio recorder object, and invalidate all associated interfaces
if (m_objRecorder != nullptr) {
(*m_objRecorder)->Destroy(m_objRecorder);
m_objRecorder = nullptr;
m_recorder = nullptr;
m_bufferQueue = nullptr;
}
// destroy engine object, and invalidate all associated interfaces
if (m_objEngine != nullptr) {
(*m_objEngine)->Destroy(m_objEngine);
m_objEngine = nullptr;
m_engine = nullptr;
}
for(int i=0; i<m_noBuffer; ++i)
{ delete [] m_buffer[i]; }
delete [] m_buffer;
delete [] m_floatBuffer;
};
void AudioInputAccessor::startAudioInput()
{
(*m_recorder)->SetRecordState(m_recorder, SL_RECORDSTATE_RECORDING);
};
void AudioInputAccessor::stopAudioInput()
{
(*m_recorder)->SetRecordState(m_recorder, SL_RECORDSTATE_STOPPED);
};
void AudioInputAccessor::newInputBuffer()
{
//recorderBuffer[currentbuffer] contains (the lastly filled) buffer data
//do correlation check, decoding, or whatsoever with this array BEFORE enqueueing
TapirDSP::vflt16(m_buffer[m_curBufferIdx], m_floatBuffer, m_frameSize);
TapirDSP::vsdiv(m_floatBuffer, &kShortMax, m_floatBuffer, m_frameSize);
m_detector->detect(m_floatBuffer);
(*m_bufferQueue)->Enqueue(m_bufferQueue, m_buffer[m_curBufferIdx], m_frameByteSize);
if((++m_curBufferIdx) >= m_noBuffer) { m_curBufferIdx = 0;}
};
<commit_msg>Fixed Audio input route to the built-in microphone by force.<commit_after>/*
* AudioInputAccessor.cpp
*
* Created on: Mar 13, 2014
* Author: Jimin
*/
#include "AudioInputAccessor.h"
static const float kShortMax = (float)(SHRT_MAX);
void recorderCallback(SLAndroidSimpleBufferQueueItf bq, void *context)
{
((AudioInputAccessor *)context)->newInputBuffer();
};
AudioInputAccessor::AudioInputAccessor(int frameSize, Tapir::SignalDetector * detector)
:m_frameSize(frameSize),
m_frameByteSize(m_frameSize * sizeof(short)),
m_detector(detector),
m_objEngine(nullptr),
m_engine(nullptr),
m_objRecorder(nullptr),
m_recorder(nullptr),
m_bufferQueue(nullptr),
m_curBufferIdx(0),
m_noBuffer(3),
m_buffer(nullptr),
m_floatBuffer(new float[m_frameSize])
{
//Allocate Buffer
m_buffer = new short*[m_noBuffer];
for(int i=0; i<m_noBuffer; ++i)
{ m_buffer[i] = new short[m_frameSize]; }
// create engine
slCreateEngine(&m_objEngine, 0, nullptr, 0, nullptr, nullptr);
// realize the engine
(*m_objEngine)->Realize(m_objEngine, SL_BOOLEAN_FALSE);
// get the engine interface, which is needed in order to create other objects
(*m_objEngine)->GetInterface(m_objEngine, SL_IID_ENGINE, &m_engine);
// configure audio source
SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT,
SL_DEFAULTDEVICEID_AUDIOINPUT, NULL};
SLDataSource audioSrc = {&loc_dev, NULL};
// configure audio sink
SLDataLocator_AndroidSimpleBufferQueue loc_bq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, static_cast<unsigned int>(m_noBuffer)};
SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 1, SL_SAMPLINGRATE_44_1,
SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16,
SL_SPEAKER_FRONT_CENTER, SL_BYTEORDER_LITTLEENDIAN};
SLDataSink audioSnk = {&loc_bq, &format_pcm};
// create audio recorder
// (requires the RECORD_AUDIO permission)
const SLInterfaceID id[2] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION};
const SLboolean req[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};
(*m_engine)->CreateAudioRecorder(m_engine, &m_objRecorder, &audioSrc, &audioSnk, 2, id, req);
SLAndroidConfigurationItf recorderConfig;
SLint32 streamType = SL_ANDROID_RECORDING_PRESET_CAMCORDER;
(*m_objRecorder)->GetInterface(m_objRecorder, SL_IID_ANDROIDCONFIGURATION, &recorderConfig);
(*recorderConfig)->SetConfiguration(recorderConfig, SL_ANDROID_KEY_RECORDING_PRESET, &streamType, sizeof(SLint32));
// realize the audio recorder
(*m_objRecorder)->Realize(m_objRecorder, SL_BOOLEAN_FALSE);
// get the record interface
(*m_objRecorder)->GetInterface(m_objRecorder, SL_IID_RECORD, &m_recorder);
// get the buffer queue interface
(*m_objRecorder)->GetInterface(m_objRecorder, SL_IID_ANDROIDSIMPLEBUFFERQUEUE,
&m_bufferQueue);
// register callback on the buffer queue
(*m_bufferQueue)->RegisterCallback(m_bufferQueue, recorderCallback, this);
//Enqueue Buffer
for(int i=0; i<m_noBuffer; ++i)
{
(*m_bufferQueue)->Enqueue(m_bufferQueue, m_buffer[i], m_frameByteSize);
}
};
AudioInputAccessor::~AudioInputAccessor()
{
// destroy audio recorder object, and invalidate all associated interfaces
if (m_objRecorder != nullptr) {
(*m_objRecorder)->Destroy(m_objRecorder);
m_objRecorder = nullptr;
m_recorder = nullptr;
m_bufferQueue = nullptr;
}
// destroy engine object, and invalidate all associated interfaces
if (m_objEngine != nullptr) {
(*m_objEngine)->Destroy(m_objEngine);
m_objEngine = nullptr;
m_engine = nullptr;
}
for(int i=0; i<m_noBuffer; ++i)
{ delete [] m_buffer[i]; }
delete [] m_buffer;
delete [] m_floatBuffer;
};
void AudioInputAccessor::startAudioInput()
{
(*m_recorder)->SetRecordState(m_recorder, SL_RECORDSTATE_RECORDING);
};
void AudioInputAccessor::stopAudioInput()
{
(*m_recorder)->SetRecordState(m_recorder, SL_RECORDSTATE_STOPPED);
};
void AudioInputAccessor::newInputBuffer()
{
//recorderBuffer[currentbuffer] contains (the lastly filled) buffer data
//do correlation check, decoding, or whatsoever with this array BEFORE enqueueing
TapirDSP::vflt16(m_buffer[m_curBufferIdx], m_floatBuffer, m_frameSize);
TapirDSP::vsdiv(m_floatBuffer, &kShortMax, m_floatBuffer, m_frameSize);
m_detector->detect(m_floatBuffer);
(*m_bufferQueue)->Enqueue(m_bufferQueue, m_buffer[m_curBufferIdx], m_frameByteSize);
if((++m_curBufferIdx) >= m_noBuffer) { m_curBufferIdx = 0;}
};
<|endoftext|>
|
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* 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 "RDTweakedNativeStyle.h"
#include <QDebug>
#include <QFontMetrics>
#include <QPainter>
#include <QPen>
#include <QStyleOption>
namespace Constants
{
static const int MenuBarItemHPadding = 4;
static const int MenuBarItemVPadding = 2;
static const int MenuBarItemSpacing = 4;
};
RDTweakedNativeStyle::RDTweakedNativeStyle(QStyle *parent) : QProxyStyle(parent)
{
}
RDTweakedNativeStyle::~RDTweakedNativeStyle()
{
}
QRect RDTweakedNativeStyle::subElementRect(SubElement element, const QStyleOption *opt,
const QWidget *widget) const
{
QRect ret = QProxyStyle::subElementRect(element, opt, widget);
if(element == QStyle::SE_DockWidgetCloseButton || element == QStyle::SE_DockWidgetFloatButton)
{
int width = pixelMetric(QStyle::PM_TabCloseIndicatorWidth, opt, widget);
int height = pixelMetric(QStyle::PM_TabCloseIndicatorHeight, opt, widget);
QPoint c = ret.center();
ret.setSize(QSize(width, height));
ret.moveCenter(c);
}
return ret;
}
QSize RDTweakedNativeStyle::sizeFromContents(ContentsType type, const QStyleOption *opt,
const QSize &size, const QWidget *widget) const
{
QSize sz = size;
// Toolbuttons are always at least icon sized, for consistency.
if(type == QStyle::CT_ToolButton)
{
const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(opt);
if(toolbutton)
sz = sz.expandedTo(toolbutton->iconSize);
}
// menu bar items can be sized for both the icon *and* the text
if(type == CT_MenuBarItem)
{
const QStyleOptionMenuItem *menuopt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
int iconSize = pixelMetric(QStyle::PM_SmallIconSize, opt, widget);
sz = menuopt->fontMetrics.size(Qt::TextShowMnemonic, menuopt->text);
if(!menuopt->icon.isNull())
{
sz.setWidth(sz.width() + Constants::MenuBarItemSpacing + iconSize);
sz = sz.expandedTo(QSize(1, iconSize));
}
sz += QSize(Constants::MenuBarItemHPadding * 2 + Constants::MenuBarItemSpacing * 2,
Constants::MenuBarItemVPadding * 2);
return sz;
}
return QProxyStyle::sizeFromContents(type, opt, sz, widget);
}
int RDTweakedNativeStyle::pixelMetric(PixelMetric metric, const QStyleOption *opt,
const QWidget *widget) const
{
// toolbuttons don't shift their text when clicked.
if(metric == QStyle::PM_ButtonShiftHorizontal || metric == QStyle::PM_ButtonShiftVertical)
{
if(opt && (opt->state & State_AutoRaise))
return 0;
}
return QProxyStyle::pixelMetric(metric, opt, widget);
}
int RDTweakedNativeStyle::styleHint(StyleHint stylehint, const QStyleOption *opt,
const QWidget *widget, QStyleHintReturn *returnData) const
{
if(stylehint == QStyle::SH_Menu_Scrollable)
return 1;
return QProxyStyle::styleHint(stylehint, opt, widget, returnData);
}
QIcon RDTweakedNativeStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *opt,
const QWidget *widget) const
{
if(standardIcon == QStyle::SP_TitleBarCloseButton)
{
int sz = pixelMetric(QStyle::PM_SmallIconSize);
return QIcon(QPixmap(QSize(sz, sz)));
}
return QProxyStyle::standardIcon(standardIcon, opt, widget);
}
void RDTweakedNativeStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *opt,
QPainter *p, const QWidget *widget) const
{
// autoraise toolbuttons are rendered flat with a semi-transparent highlight to show their state.
if(control == QStyle::CC_ToolButton && (opt->state & State_AutoRaise))
{
const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(opt);
QPen oldPen = p->pen();
QColor backCol = opt->palette.color(QPalette::Normal, QPalette::Highlight);
backCol.setAlphaF(0.2);
QStyleOptionToolButton menu;
// draw the menu arrow, if there is one
if((toolbutton->subControls & SC_ToolButtonMenu) ||
(toolbutton->features & QStyleOptionToolButton::MenuButtonPopup))
{
menu = *toolbutton;
menu.rect = subControlRect(control, opt, SC_ToolButtonMenu, widget);
}
QStyle::State masked = opt->state & (State_On | State_MouseOver);
if(!(opt->state & State_Enabled))
masked &= ~State_MouseOver;
if(masked)
{
QRect rect = opt->rect.adjusted(0, 0, -1, -1);
p->setPen(opt->palette.color(QPalette::Shadow));
p->drawRect(rect);
if(menu.rect.isValid())
p->drawLine(menu.rect.topLeft(), menu.rect.bottomLeft());
// when the mouse is over, make it a little stronger
if(masked & State_MouseOver)
backCol.setAlphaF(0.4);
p->fillRect(rect, QBrush(backCol));
}
p->setPen(oldPen);
QStyleOptionToolButton labelTextIcon = *toolbutton;
labelTextIcon.rect = subControlRect(control, opt, SC_ToolButton, widget);
// draw the label text/icon
drawControl(CE_ToolButtonLabel, &labelTextIcon, p, widget);
if(menu.rect.isValid())
{
menu.rect.adjust(2, 0, 0, 0);
drawPrimitive(PE_IndicatorArrowDown, &menu, p, widget);
}
return;
}
return QProxyStyle::drawComplexControl(control, opt, p, widget);
}
void RDTweakedNativeStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *opt,
QPainter *p, const QWidget *widget) const
{
if(element == QStyle::PE_IndicatorBranch)
{
QPen oldPen = p->pen();
if(opt->state & State_Children)
{
bool aa = p->testRenderHint(QPainter::Antialiasing);
p->setRenderHint(QPainter::Antialiasing);
QColor col = opt->palette.color(QPalette::Text);
if(opt->state & State_MouseOver)
{
QColor highlightCol = opt->palette.color(QPalette::Highlight);
col.setRedF(col.redF() * 0.6 + highlightCol.redF() * 0.4);
col.setGreenF(col.greenF() * 0.6 + highlightCol.greenF() * 0.4);
col.setBlueF(col.blueF() * 0.6 + highlightCol.blueF() * 0.4);
}
p->setPen(QPen(col, 2.0));
QPainterPath path;
QPolygonF poly;
QRectF rect = opt->rect;
{
qreal newdim = qMin(14.0, qMin(rect.height(), rect.width()));
QPointF c = rect.center();
rect.setTop(c.y() - newdim / 2);
rect.setLeft(c.x() - newdim / 2);
rect.setWidth(newdim);
rect.setHeight(newdim);
}
rect = rect.adjusted(2, 2, -2, -2);
if(opt->state & State_Open)
{
QPointF pt = rect.center();
pt.setX(rect.left());
poly << pt;
pt = rect.center();
pt.setY(rect.bottom());
poly << pt;
pt = rect.center();
pt.setX(rect.right());
poly << pt;
path.addPolygon(poly);
p->drawPath(path);
}
else
{
QPointF pt = rect.center();
pt.setY(rect.top());
poly << pt;
pt = rect.center();
pt.setX(rect.right());
poly << pt;
pt = rect.center();
pt.setY(rect.bottom());
poly << pt;
path.addPolygon(poly);
p->drawPath(path);
}
if(!aa)
p->setRenderHint(QPainter::Antialiasing, false);
}
else if(opt->state & (State_Sibling | State_Item))
{
p->setPen(QPen(opt->palette.color(QPalette::Midlight), 1.0));
int bottomY = opt->rect.center().y();
if(opt->state & State_Sibling)
bottomY = opt->rect.bottom();
p->drawLine(QLine(opt->rect.center().x(), opt->rect.top(), opt->rect.center().x(), bottomY));
if(opt->state & State_Item)
p->drawLine(opt->rect.center(), QPoint(opt->rect.right(), opt->rect.center().y()));
}
p->setPen(oldPen);
return;
}
else if(element == PE_IndicatorTabClose)
{
QPen oldPen = p->pen();
bool aa = p->testRenderHint(QPainter::Antialiasing);
p->setRenderHint(QPainter::Antialiasing);
QColor col = opt->palette.color(QPalette::Text);
QRectF rect = opt->rect.adjusted(1, 1, -1, -1);
if(opt->state & (QStyle::State_Raised | QStyle::State_Sunken | QStyle::State_MouseOver))
{
QPointF c = rect.center();
qreal radius = rect.width() / 2.0;
col = opt->palette.color(QPalette::Base);
QPainterPath path;
path.addEllipse(c, radius, radius);
QColor fillCol = QColor(Qt::red).darker(120);
if(opt->state & QStyle::State_Sunken)
fillCol = fillCol.darker(120);
p->fillPath(path, fillCol);
}
p->setPen(QPen(col, 1.5));
QPointF c = rect.center();
qreal crossrad = rect.width() / 4.0;
p->drawLine(c + QPointF(-crossrad, -crossrad), c + QPointF(crossrad, crossrad));
p->drawLine(c + QPointF(-crossrad, crossrad), c + QPointF(crossrad, -crossrad));
p->setPen(oldPen);
if(!aa)
p->setRenderHint(QPainter::Antialiasing, false);
return;
}
QProxyStyle::drawPrimitive(element, opt, p, widget);
}
void RDTweakedNativeStyle::drawControl(ControlElement control, const QStyleOption *opt, QPainter *p,
const QWidget *widget) const
{
if(control == QStyle::CE_MenuBarItem)
{
// we can't take over control of just rendering the icon/text, so we call down to common style
// to draw the background since then we know how to render matching text over the top.
const QStyleOptionMenuItem *menuopt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
QRect rect =
menuopt->rect.adjusted(Constants::MenuBarItemSpacing, 0, -Constants::MenuBarItemSpacing, 0);
const bool selected = menuopt->state & State_Selected;
const bool hovered = menuopt->state & State_MouseOver;
const bool enabled = menuopt->state & State_Enabled;
QPalette::ColorRole textRole = QPalette::ButtonText;
if(enabled && (selected || hovered))
{
p->fillRect(rect, opt->palette.brush(QPalette::Highlight));
textRole = QPalette::HighlightedText;
}
int flags = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
if(!styleHint(SH_UnderlineShortcut, opt, widget))
flags |= Qt::TextHideMnemonic;
rect.adjust(Constants::MenuBarItemHPadding, Constants::MenuBarItemVPadding,
-Constants::MenuBarItemHPadding, -Constants::MenuBarItemVPadding);
int iconSize = pixelMetric(QStyle::PM_SmallIconSize, opt, widget);
QPixmap pix = menuopt->icon.pixmap(
iconSize, iconSize, (menuopt->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
if(!pix.isNull())
{
QRect iconRect = rect;
iconRect.setWidth(iconSize);
drawItemPixmap(p, iconRect, flags, pix);
rect.adjust(Constants::MenuBarItemSpacing + iconSize, 0, 0, 0);
}
drawItemText(p, rect, flags, menuopt->palette, enabled, menuopt->text, textRole);
return;
}
// https://bugreports.qt.io/browse/QTBUG-14949
// work around itemview rendering bug - the first line in a multi-line text that is elided stops
// all subsequent text from rendering. Should be fixed in 5.11, but for all other versions we need
// to manually step in. We manually elide the text before calling down to the style
#if(QT_VERSION < QT_VERSION_CHECK(5, 11, 0))
if(control == QStyle::CE_ItemViewItem)
{
const QStyleOptionViewItem *viewopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt);
// only if we're eliding, not wrapping, and we have multiple lines
if((viewopt->features & QStyleOptionViewItem::WrapText) == 0 &&
viewopt->text.contains(QChar::LineSeparator))
{
const int hmargin = pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1;
QRect textRect =
subElementRect(SE_ItemViewItemText, viewopt, widget).adjusted(hmargin, 0, -hmargin, 0);
QFontMetrics metrics(viewopt->font);
QStringList lines = viewopt->text.split(QChar::LineSeparator);
for(QString &line : lines)
line = metrics.elidedText(line, viewopt->textElideMode, textRect.width(), 0);
QStyleOptionViewItem elided = *viewopt;
elided.text = lines.join(QChar::LineSeparator);
QProxyStyle::drawControl(control, &elided, p, widget);
return;
}
}
#endif
QProxyStyle::drawControl(control, opt, p, widget);
}
<commit_msg>Don't disable itemview wordwarp workaround for QTBUG-14949 in 5.11<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* 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 "RDTweakedNativeStyle.h"
#include <QDebug>
#include <QFontMetrics>
#include <QPainter>
#include <QPen>
#include <QStyleOption>
namespace Constants
{
static const int MenuBarItemHPadding = 4;
static const int MenuBarItemVPadding = 2;
static const int MenuBarItemSpacing = 4;
};
RDTweakedNativeStyle::RDTweakedNativeStyle(QStyle *parent) : QProxyStyle(parent)
{
}
RDTweakedNativeStyle::~RDTweakedNativeStyle()
{
}
QRect RDTweakedNativeStyle::subElementRect(SubElement element, const QStyleOption *opt,
const QWidget *widget) const
{
QRect ret = QProxyStyle::subElementRect(element, opt, widget);
if(element == QStyle::SE_DockWidgetCloseButton || element == QStyle::SE_DockWidgetFloatButton)
{
int width = pixelMetric(QStyle::PM_TabCloseIndicatorWidth, opt, widget);
int height = pixelMetric(QStyle::PM_TabCloseIndicatorHeight, opt, widget);
QPoint c = ret.center();
ret.setSize(QSize(width, height));
ret.moveCenter(c);
}
return ret;
}
QSize RDTweakedNativeStyle::sizeFromContents(ContentsType type, const QStyleOption *opt,
const QSize &size, const QWidget *widget) const
{
QSize sz = size;
// Toolbuttons are always at least icon sized, for consistency.
if(type == QStyle::CT_ToolButton)
{
const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(opt);
if(toolbutton)
sz = sz.expandedTo(toolbutton->iconSize);
}
// menu bar items can be sized for both the icon *and* the text
if(type == CT_MenuBarItem)
{
const QStyleOptionMenuItem *menuopt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
int iconSize = pixelMetric(QStyle::PM_SmallIconSize, opt, widget);
sz = menuopt->fontMetrics.size(Qt::TextShowMnemonic, menuopt->text);
if(!menuopt->icon.isNull())
{
sz.setWidth(sz.width() + Constants::MenuBarItemSpacing + iconSize);
sz = sz.expandedTo(QSize(1, iconSize));
}
sz += QSize(Constants::MenuBarItemHPadding * 2 + Constants::MenuBarItemSpacing * 2,
Constants::MenuBarItemVPadding * 2);
return sz;
}
return QProxyStyle::sizeFromContents(type, opt, sz, widget);
}
int RDTweakedNativeStyle::pixelMetric(PixelMetric metric, const QStyleOption *opt,
const QWidget *widget) const
{
// toolbuttons don't shift their text when clicked.
if(metric == QStyle::PM_ButtonShiftHorizontal || metric == QStyle::PM_ButtonShiftVertical)
{
if(opt && (opt->state & State_AutoRaise))
return 0;
}
return QProxyStyle::pixelMetric(metric, opt, widget);
}
int RDTweakedNativeStyle::styleHint(StyleHint stylehint, const QStyleOption *opt,
const QWidget *widget, QStyleHintReturn *returnData) const
{
if(stylehint == QStyle::SH_Menu_Scrollable)
return 1;
return QProxyStyle::styleHint(stylehint, opt, widget, returnData);
}
QIcon RDTweakedNativeStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *opt,
const QWidget *widget) const
{
if(standardIcon == QStyle::SP_TitleBarCloseButton)
{
int sz = pixelMetric(QStyle::PM_SmallIconSize);
return QIcon(QPixmap(QSize(sz, sz)));
}
return QProxyStyle::standardIcon(standardIcon, opt, widget);
}
void RDTweakedNativeStyle::drawComplexControl(ComplexControl control, const QStyleOptionComplex *opt,
QPainter *p, const QWidget *widget) const
{
// autoraise toolbuttons are rendered flat with a semi-transparent highlight to show their state.
if(control == QStyle::CC_ToolButton && (opt->state & State_AutoRaise))
{
const QStyleOptionToolButton *toolbutton = qstyleoption_cast<const QStyleOptionToolButton *>(opt);
QPen oldPen = p->pen();
QColor backCol = opt->palette.color(QPalette::Normal, QPalette::Highlight);
backCol.setAlphaF(0.2);
QStyleOptionToolButton menu;
// draw the menu arrow, if there is one
if((toolbutton->subControls & SC_ToolButtonMenu) ||
(toolbutton->features & QStyleOptionToolButton::MenuButtonPopup))
{
menu = *toolbutton;
menu.rect = subControlRect(control, opt, SC_ToolButtonMenu, widget);
}
QStyle::State masked = opt->state & (State_On | State_MouseOver);
if(!(opt->state & State_Enabled))
masked &= ~State_MouseOver;
if(masked)
{
QRect rect = opt->rect.adjusted(0, 0, -1, -1);
p->setPen(opt->palette.color(QPalette::Shadow));
p->drawRect(rect);
if(menu.rect.isValid())
p->drawLine(menu.rect.topLeft(), menu.rect.bottomLeft());
// when the mouse is over, make it a little stronger
if(masked & State_MouseOver)
backCol.setAlphaF(0.4);
p->fillRect(rect, QBrush(backCol));
}
p->setPen(oldPen);
QStyleOptionToolButton labelTextIcon = *toolbutton;
labelTextIcon.rect = subControlRect(control, opt, SC_ToolButton, widget);
// draw the label text/icon
drawControl(CE_ToolButtonLabel, &labelTextIcon, p, widget);
if(menu.rect.isValid())
{
menu.rect.adjust(2, 0, 0, 0);
drawPrimitive(PE_IndicatorArrowDown, &menu, p, widget);
}
return;
}
return QProxyStyle::drawComplexControl(control, opt, p, widget);
}
void RDTweakedNativeStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *opt,
QPainter *p, const QWidget *widget) const
{
if(element == QStyle::PE_IndicatorBranch)
{
QPen oldPen = p->pen();
if(opt->state & State_Children)
{
bool aa = p->testRenderHint(QPainter::Antialiasing);
p->setRenderHint(QPainter::Antialiasing);
QColor col = opt->palette.color(QPalette::Text);
if(opt->state & State_MouseOver)
{
QColor highlightCol = opt->palette.color(QPalette::Highlight);
col.setRedF(col.redF() * 0.6 + highlightCol.redF() * 0.4);
col.setGreenF(col.greenF() * 0.6 + highlightCol.greenF() * 0.4);
col.setBlueF(col.blueF() * 0.6 + highlightCol.blueF() * 0.4);
}
p->setPen(QPen(col, 2.0));
QPainterPath path;
QPolygonF poly;
QRectF rect = opt->rect;
{
qreal newdim = qMin(14.0, qMin(rect.height(), rect.width()));
QPointF c = rect.center();
rect.setTop(c.y() - newdim / 2);
rect.setLeft(c.x() - newdim / 2);
rect.setWidth(newdim);
rect.setHeight(newdim);
}
rect = rect.adjusted(2, 2, -2, -2);
if(opt->state & State_Open)
{
QPointF pt = rect.center();
pt.setX(rect.left());
poly << pt;
pt = rect.center();
pt.setY(rect.bottom());
poly << pt;
pt = rect.center();
pt.setX(rect.right());
poly << pt;
path.addPolygon(poly);
p->drawPath(path);
}
else
{
QPointF pt = rect.center();
pt.setY(rect.top());
poly << pt;
pt = rect.center();
pt.setX(rect.right());
poly << pt;
pt = rect.center();
pt.setY(rect.bottom());
poly << pt;
path.addPolygon(poly);
p->drawPath(path);
}
if(!aa)
p->setRenderHint(QPainter::Antialiasing, false);
}
else if(opt->state & (State_Sibling | State_Item))
{
p->setPen(QPen(opt->palette.color(QPalette::Midlight), 1.0));
int bottomY = opt->rect.center().y();
if(opt->state & State_Sibling)
bottomY = opt->rect.bottom();
p->drawLine(QLine(opt->rect.center().x(), opt->rect.top(), opt->rect.center().x(), bottomY));
if(opt->state & State_Item)
p->drawLine(opt->rect.center(), QPoint(opt->rect.right(), opt->rect.center().y()));
}
p->setPen(oldPen);
return;
}
else if(element == PE_IndicatorTabClose)
{
QPen oldPen = p->pen();
bool aa = p->testRenderHint(QPainter::Antialiasing);
p->setRenderHint(QPainter::Antialiasing);
QColor col = opt->palette.color(QPalette::Text);
QRectF rect = opt->rect.adjusted(1, 1, -1, -1);
if(opt->state & (QStyle::State_Raised | QStyle::State_Sunken | QStyle::State_MouseOver))
{
QPointF c = rect.center();
qreal radius = rect.width() / 2.0;
col = opt->palette.color(QPalette::Base);
QPainterPath path;
path.addEllipse(c, radius, radius);
QColor fillCol = QColor(Qt::red).darker(120);
if(opt->state & QStyle::State_Sunken)
fillCol = fillCol.darker(120);
p->fillPath(path, fillCol);
}
p->setPen(QPen(col, 1.5));
QPointF c = rect.center();
qreal crossrad = rect.width() / 4.0;
p->drawLine(c + QPointF(-crossrad, -crossrad), c + QPointF(crossrad, crossrad));
p->drawLine(c + QPointF(-crossrad, crossrad), c + QPointF(crossrad, -crossrad));
p->setPen(oldPen);
if(!aa)
p->setRenderHint(QPainter::Antialiasing, false);
return;
}
QProxyStyle::drawPrimitive(element, opt, p, widget);
}
void RDTweakedNativeStyle::drawControl(ControlElement control, const QStyleOption *opt, QPainter *p,
const QWidget *widget) const
{
if(control == QStyle::CE_MenuBarItem)
{
// we can't take over control of just rendering the icon/text, so we call down to common style
// to draw the background since then we know how to render matching text over the top.
const QStyleOptionMenuItem *menuopt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt);
QRect rect =
menuopt->rect.adjusted(Constants::MenuBarItemSpacing, 0, -Constants::MenuBarItemSpacing, 0);
const bool selected = menuopt->state & State_Selected;
const bool hovered = menuopt->state & State_MouseOver;
const bool enabled = menuopt->state & State_Enabled;
QPalette::ColorRole textRole = QPalette::ButtonText;
if(enabled && (selected || hovered))
{
p->fillRect(rect, opt->palette.brush(QPalette::Highlight));
textRole = QPalette::HighlightedText;
}
int flags = Qt::AlignCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
if(!styleHint(SH_UnderlineShortcut, opt, widget))
flags |= Qt::TextHideMnemonic;
rect.adjust(Constants::MenuBarItemHPadding, Constants::MenuBarItemVPadding,
-Constants::MenuBarItemHPadding, -Constants::MenuBarItemVPadding);
int iconSize = pixelMetric(QStyle::PM_SmallIconSize, opt, widget);
QPixmap pix = menuopt->icon.pixmap(
iconSize, iconSize, (menuopt->state & State_Enabled) ? QIcon::Normal : QIcon::Disabled);
if(!pix.isNull())
{
QRect iconRect = rect;
iconRect.setWidth(iconSize);
drawItemPixmap(p, iconRect, flags, pix);
rect.adjust(Constants::MenuBarItemSpacing + iconSize, 0, 0, 0);
}
drawItemText(p, rect, flags, menuopt->palette, enabled, menuopt->text, textRole);
return;
}
// https://bugreports.qt.io/browse/QTBUG-14949
// work around itemview rendering bug - the first line in a multi-line text that is elided stops
// all subsequent text from rendering. Should be fixed in 5.11, but for all other versions we need
// to manually step in. We manually elide the text before calling down to the style
//
// However in 5.11.1 at least on macOS it still seems to be broken
#if 1 //(QT_VERSION < QT_VERSION_CHECK(5, 11, 0))
if(control == QStyle::CE_ItemViewItem)
{
const QStyleOptionViewItem *viewopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt);
// only if we're eliding, not wrapping, and we have multiple lines
if((viewopt->features & QStyleOptionViewItem::WrapText) == 0 &&
viewopt->text.contains(QChar::LineSeparator))
{
const int hmargin = pixelMetric(QStyle::PM_FocusFrameHMargin, 0, widget) + 1;
QRect textRect =
subElementRect(SE_ItemViewItemText, viewopt, widget).adjusted(hmargin, 0, -hmargin, 0);
QFontMetrics metrics(viewopt->font);
QStringList lines = viewopt->text.split(QChar::LineSeparator);
for(QString &line : lines)
line = metrics.elidedText(line, viewopt->textElideMode, textRect.width(), 0);
QStyleOptionViewItem elided = *viewopt;
elided.text = lines.join(QChar::LineSeparator);
QProxyStyle::drawControl(control, &elided, p, widget);
return;
}
}
#endif
QProxyStyle::drawControl(control, opt, p, widget);
}
<|endoftext|>
|
<commit_before><commit_msg>Add a reference I forgot to add. I didn't mean to copy this string. Review URL: http://codereview.chromium.org/14171<commit_after><|endoftext|>
|
<commit_before>/**
* Copyright 2012 FAU (Friedrich Alexander University of Erlangen-Nuremberg)
*
* 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 "i6engine/modules/audio/AudioMailbox.h"
#include <boost/shared_ptr.hpp>
#include "i6engine/api/FrontendMessageTypes.h"
#include "i6engine/modules/audio/AudioManager.h"
namespace i6engine {
namespace modules {
AudioMailbox::AudioMailbox(AudioManager * m) : _manager(m) {
ASSERT_THREAD_SAFETY_CONSTRUCTOR
}
void AudioMailbox::News(const api::GameMessage::Ptr & msg) const {
ASSERT_THREAD_SAFETY_FUNCTION
std::cout << msg->getMessageInfo() << std::endl;
if (msg->getMessageType() == api::messages::AudioMessageType) {
if (msg->getMethod() == core::Method::Create) {
_manager->NewsCreate(msg);
} else if (msg->getMethod() == core::Method::Update) {
_manager->NewsUpdate(msg);
} else if (msg->getMethod() == core::Method::Delete) {
_manager->NewsDelete(msg);
}
} else if (msg->getMessageType() == api::messages::AudioNodeMessageType) {
if (msg->getMethod() == core::Method::Create) {
_manager->NewsNodeCreate(msg);
} else if (msg->getMethod() == core::Method::Update) {
_manager->NewsNodeUpdate(msg);
} else if (msg->getMethod() == core::Method::Delete) {
_manager->NewsNodeDelete(msg);
}
}
}
} /* namespace modules */
} /* namespace i6engine */
<commit_msg>ISIXE-909 removed debug<commit_after>/**
* Copyright 2012 FAU (Friedrich Alexander University of Erlangen-Nuremberg)
*
* 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 "i6engine/modules/audio/AudioMailbox.h"
#include <boost/shared_ptr.hpp>
#include "i6engine/api/FrontendMessageTypes.h"
#include "i6engine/modules/audio/AudioManager.h"
namespace i6engine {
namespace modules {
AudioMailbox::AudioMailbox(AudioManager * m) : _manager(m) {
ASSERT_THREAD_SAFETY_CONSTRUCTOR
}
void AudioMailbox::News(const api::GameMessage::Ptr & msg) const {
ASSERT_THREAD_SAFETY_FUNCTION
if (msg->getMessageType() == api::messages::AudioMessageType) {
if (msg->getMethod() == core::Method::Create) {
_manager->NewsCreate(msg);
} else if (msg->getMethod() == core::Method::Update) {
_manager->NewsUpdate(msg);
} else if (msg->getMethod() == core::Method::Delete) {
_manager->NewsDelete(msg);
}
} else if (msg->getMessageType() == api::messages::AudioNodeMessageType) {
if (msg->getMethod() == core::Method::Create) {
_manager->NewsNodeCreate(msg);
} else if (msg->getMethod() == core::Method::Update) {
_manager->NewsNodeUpdate(msg);
} else if (msg->getMethod() == core::Method::Delete) {
_manager->NewsNodeDelete(msg);
}
}
}
} /* namespace modules */
} /* namespace i6engine */
<|endoftext|>
|
<commit_before>// puss_module_linenoise_ng.c
#include "puss_plugin.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <stdlib.h>
#include <string.h>
#include "linenoise.h"
#define PUSS_LINENOISE_NG_LIB_NAME "[PussLinenoiseNGLib]"
static lua_State* linenoiseCompletionState = NULL;
static linenoiseCompletions* linenoiseCompletionContent = NULL;
static void linenoiseCompletionCallbackWrapper(const char* s, linenoiseCompletions* lc) {
lua_State* L = linenoiseCompletionState;
if( L && lua_isfunction(L, lua_upvalueindex(1)) ) {
int top = lua_gettop(L);
lua_pushvalue(L, lua_upvalueindex(1));
lua_pushstring(L, s ? s : "");
linenoiseCompletionContent = lc;
lua_pcall(L, 1, 0, 0);
linenoiseCompletionContent = NULL;
lua_settop(L, top);
}
}
static int lua_linenoiseAddCompletion(lua_State* L) {
const char* s = luaL_checkstring(L, 1);
if( linenoiseCompletionState==L && linenoiseCompletionContent ) {
linenoiseAddCompletion(linenoiseCompletionContent, s);
lua_pushboolean(L, 1);
} else {
lua_pushboolean(L, 0);
}
return 1;
}
static int lua_linenoiseSetCompletionCallback(lua_State* L) {
lua_settop(L, 1);
lua_setupvalue(L, lua_upvalueindex(1), 1); // set (up[1] linenoise. up[1] cb) = cb
return 0;
}
static int lua_linenoise(lua_State* L) {
void linenoiseAddCompletion(linenoiseCompletions* lc, const char* str);
const char* prompt = luaL_optstring(L, 1, "");
int setup = (linenoiseCompletionState==NULL) && lua_isfunction(L, lua_upvalueindex(1));
char* result;
if( setup ) linenoiseCompletionState = L;
result = linenoise(prompt);
if( setup ) linenoiseCompletionState = NULL;
if( result ) {
lua_pushstring(L, result);
free(result);
return 1;
}
return 0;
}
static int lua_linenoisePreloadBuffer(lua_State* L) {
linenoisePreloadBuffer(luaL_checkstring(L, 1));
return 0;
}
static int lua_linenoiseHistoryAdd(lua_State* L) {
lua_pushboolean(L, linenoiseHistoryAdd(luaL_checkstring(L, 1)));
return 1;
}
static int lua_linenoiseHistorySetMaxLen(lua_State* L) {
lua_pushboolean(L, linenoiseHistorySetMaxLen((int)luaL_checkinteger(L, 1)));
return 1;
}
static int lua_linenoiseHistoryLine(lua_State* L) {
char* result = linenoiseHistoryLine((int)luaL_checkinteger(L, 1));
if( result ) {
lua_pushstring(L, result);
free(result);
return 1;
}
return 0;
}
static int lua_linenoiseHistorySave(lua_State* L) {
lua_pushboolean(L, linenoiseHistorySave(luaL_checkstring(L, 1)));
return 1;
}
static int lua_linenoiseHistoryLoad(lua_State* L) {
lua_pushboolean(L, linenoiseHistoryLoad(luaL_checkstring(L, 1)));
return 1;
}
static int lua_linenoiseHistoryFree(lua_State* L) {
linenoiseHistoryFree();
return 0;
}
static int lua_linenoiseClearScreen(lua_State* L) {
linenoiseClearScreen();
return 0;
}
static int lua_linenoiseSetMultiLine(lua_State* L) {
linenoiseSetMultiLine(lua_toboolean(L, 1));
return 0;
}
static int lua_linenoisePrintKeyCodes(lua_State* L) {
linenoisePrintKeyCodes();
return 0;
}
static int lua_linenoiseInstallWindowChangeHandler(lua_State* L) {
lua_pushboolean(L, linenoiseInstallWindowChangeHandler());
return 1;
}
static int lua_linenoiseKeyType(lua_State* L) {
lua_pushinteger(L, linenoiseKeyType());
return 1;
}
static luaL_Reg lib_methods[] =
{ {"linenoiseAddCompletion", lua_linenoiseAddCompletion}
, {"linenoisePreloadBuffer", lua_linenoisePreloadBuffer}
, {"linenoiseHistoryAdd", lua_linenoiseHistoryAdd}
, {"linenoiseHistorySetMaxLen", lua_linenoiseHistorySetMaxLen}
, {"linenoiseHistoryLine", lua_linenoiseHistoryLine}
, {"linenoiseHistorySave", lua_linenoiseHistorySave}
, {"linenoiseHistoryLoad", lua_linenoiseHistoryLoad}
, {"linenoiseHistoryFree", lua_linenoiseHistoryFree}
, {"linenoiseClearScreen", lua_linenoiseClearScreen}
, {"linenoiseSetMultiLine", lua_linenoiseSetMultiLine}
, {"linenoisePrintKeyCodes", lua_linenoisePrintKeyCodes}
, {"linenoiseInstallWindowChangeHandler", lua_linenoiseInstallWindowChangeHandler}
, {"linenoiseKeyType", lua_linenoiseKeyType}
, {NULL, NULL}
};
PussInterface* __puss_iface__ = NULL;
PUSS_PLUGIN_EXPORT int __puss_plugin_init__(lua_State* L, PussInterface* puss) {
#ifdef _WIN32
HWND hWnd = GetConsoleWindow();
if (!hWnd) {
AllocConsole();
if( (hWnd = GetConsoleWindow())!=NULL ) {
ShowWindow(hWnd, SW_SHOW);
freopen("CONIN$", "r+t", stdin);
freopen("CONOUT$", "w+t", stdout);
freopen("CONOUT$", "w+t", stderr);
}
}
#endif
__puss_iface__ = puss;
if( lua_getfield(L, LUA_REGISTRYINDEX, PUSS_LINENOISE_NG_LIB_NAME)==LUA_TTABLE ) {
return 1;
}
lua_pop(L, 1);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, PUSS_LINENOISE_NG_LIB_NAME);
luaL_setfuncs(L, lib_methods, 0);
lua_pushboolean(L, 0);
lua_pushcclosure(L, lua_linenoise, 1);
lua_pushvalue(L, -1);
lua_setfield(L, -3, "linenoise");
lua_pushcclosure(L, lua_linenoiseSetCompletionCallback, 1);
lua_setfield(L, -2, "linenoiseSetCompletionCallback");
return 1;
}
<commit_msg>Update puss_module_linenoise_ng.cpp<commit_after>// puss_module_linenoise_ng.c
#include "puss_plugin.h"
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <stdlib.h>
#include <string.h>
#include "linenoise.h"
#define PUSS_LINENOISE_NG_LIB_NAME "[PussLinenoiseNGLib]"
static lua_State* linenoiseCompletionState = NULL;
static linenoiseCompletions* linenoiseCompletionContent = NULL;
static void linenoiseCompletionCallbackWrapper(const char* s, linenoiseCompletions* lc) {
lua_State* L = linenoiseCompletionState;
if( L && lua_isfunction(L, lua_upvalueindex(1)) ) {
int top = lua_gettop(L);
lua_pushvalue(L, lua_upvalueindex(1));
lua_pushstring(L, s ? s : "");
linenoiseCompletionContent = lc;
lua_pcall(L, 1, 0, 0);
linenoiseCompletionContent = NULL;
lua_settop(L, top);
}
}
static int lua_linenoiseAddCompletion(lua_State* L) {
const char* s = luaL_checkstring(L, 1);
if( linenoiseCompletionState==L && linenoiseCompletionContent ) {
linenoiseAddCompletion(linenoiseCompletionContent, s);
lua_pushboolean(L, 1);
} else {
lua_pushboolean(L, 0);
}
return 1;
}
static int lua_linenoiseSetCompletionCallback(lua_State* L) {
lua_settop(L, 1);
lua_setupvalue(L, lua_upvalueindex(1), 1); // set (up[1] linenoise. up[1] cb) = cb
return 0;
}
static int lua_linenoise(lua_State* L) {
const char* prompt = luaL_optstring(L, 1, "");
int setup = (linenoiseCompletionState==NULL) && lua_isfunction(L, lua_upvalueindex(1));
char* result;
#ifdef _WIN32
if (!GetConsoleWindow()) return 0;
#endif
if( setup ) linenoiseCompletionState = L;
result = linenoise(prompt);
if( setup ) linenoiseCompletionState = NULL;
if( result ) {
lua_pushstring(L, result);
free(result);
return 1;
}
return 0;
}
static int lua_linenoisePreloadBuffer(lua_State* L) {
linenoisePreloadBuffer(luaL_checkstring(L, 1));
return 0;
}
static int lua_linenoiseHistoryAdd(lua_State* L) {
lua_pushboolean(L, linenoiseHistoryAdd(luaL_checkstring(L, 1)));
return 1;
}
static int lua_linenoiseHistorySetMaxLen(lua_State* L) {
lua_pushboolean(L, linenoiseHistorySetMaxLen((int)luaL_checkinteger(L, 1)));
return 1;
}
static int lua_linenoiseHistoryLine(lua_State* L) {
char* result = linenoiseHistoryLine((int)luaL_checkinteger(L, 1));
if( result ) {
lua_pushstring(L, result);
free(result);
return 1;
}
return 0;
}
static int lua_linenoiseHistorySave(lua_State* L) {
lua_pushboolean(L, linenoiseHistorySave(luaL_checkstring(L, 1)));
return 1;
}
static int lua_linenoiseHistoryLoad(lua_State* L) {
lua_pushboolean(L, linenoiseHistoryLoad(luaL_checkstring(L, 1)));
return 1;
}
static int lua_linenoiseHistoryFree(lua_State* L) {
linenoiseHistoryFree();
return 0;
}
static int lua_linenoiseClearScreen(lua_State* L) {
#ifdef _WIN32
if (!GetConsoleWindow()) return 0;
#endif
linenoiseClearScreen();
return 0;
}
static int lua_linenoiseSetMultiLine(lua_State* L) {
linenoiseSetMultiLine(lua_toboolean(L, 1));
return 0;
}
static int lua_linenoisePrintKeyCodes(lua_State* L) {
#ifdef _WIN32
if (!GetConsoleWindow()) return 0;
#endif
linenoisePrintKeyCodes();
return 0;
}
static int lua_linenoiseInstallWindowChangeHandler(lua_State* L) {
lua_pushboolean(L, linenoiseInstallWindowChangeHandler());
return 1;
}
static int lua_linenoiseKeyType(lua_State* L) {
lua_pushinteger(L, linenoiseKeyType());
return 1;
}
static luaL_Reg lib_methods[] =
{ {"linenoiseAddCompletion", lua_linenoiseAddCompletion}
, {"linenoisePreloadBuffer", lua_linenoisePreloadBuffer}
, {"linenoiseHistoryAdd", lua_linenoiseHistoryAdd}
, {"linenoiseHistorySetMaxLen", lua_linenoiseHistorySetMaxLen}
, {"linenoiseHistoryLine", lua_linenoiseHistoryLine}
, {"linenoiseHistorySave", lua_linenoiseHistorySave}
, {"linenoiseHistoryLoad", lua_linenoiseHistoryLoad}
, {"linenoiseHistoryFree", lua_linenoiseHistoryFree}
, {"linenoiseClearScreen", lua_linenoiseClearScreen}
, {"linenoiseSetMultiLine", lua_linenoiseSetMultiLine}
, {"linenoisePrintKeyCodes", lua_linenoisePrintKeyCodes}
, {"linenoiseInstallWindowChangeHandler", lua_linenoiseInstallWindowChangeHandler}
, {"linenoiseKeyType", lua_linenoiseKeyType}
, {NULL, NULL}
};
PussInterface* __puss_iface__ = NULL;
PUSS_PLUGIN_EXPORT int __puss_plugin_init__(lua_State* L, PussInterface* puss) {
__puss_iface__ = puss;
if( lua_getfield(L, LUA_REGISTRYINDEX, PUSS_LINENOISE_NG_LIB_NAME)==LUA_TTABLE ) {
return 1;
}
lua_pop(L, 1);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, PUSS_LINENOISE_NG_LIB_NAME);
luaL_setfuncs(L, lib_methods, 0);
lua_pushboolean(L, 0);
lua_pushcclosure(L, lua_linenoise, 1);
lua_pushvalue(L, -1);
lua_setfield(L, -3, "linenoise");
lua_pushcclosure(L, lua_linenoiseSetCompletionCallback, 1);
lua_setfield(L, -2, "linenoiseSetCompletionCallback");
return 1;
}
<|endoftext|>
|
<commit_before>/* vim: set ts=4 sw=4 tw=79 et :*/
/* 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/. */
#include "TestHarness.h"
#include "base/io/Path.h"
int main(int argc, char* argv[]) {
int rv = 0;
/// Path::isAbsolute Tests
rv +=
runTest("Test empty string !isAbsolute", []() {
return !Path::isAbsolute("");
});
rv +=
runPosixOnlyTest("Test isAbsolute('/a/b/c')", []() {
return Path::isAbsolute("/a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('a/b/c')", []() {
return !Path::isAbsolute("a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('../a/b')", []() {
return !Path::isAbsolute("../a/b");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('./a/b'", []() {
return !Path::isAbsolute("./a/b");
});
rv +=
runWindowsOnlyTest("Test short/invalid path", []() {
return
!Path::isAbsolute("C:") &&
!Path::isAbsolute("C") &&
!Path::isAbsolute("F:F");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:\\Hello')", []() {
return
Path::isAbsolute("a:\\Hello") &&
Path::isAbsolute("A:\\Hello") &&
Path::isAbsolute("z:\\Hello") &&
Path::isAbsolute("Z:\\Hello");
});
// Windows supports forward slashes with this form of path
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:/Hello')", []() {
return
Path::isAbsolute("a:/Hello") &&
Path::isAbsolute("A:/Hello") &&
Path::isAbsolute("z:/Hello") &&
Path::isAbsolute("Z:/Hello");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\Path')", []() {
return Path::isAbsolute("\\\\Path");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('//Path/')", []() {
return Path::isAbsolute("//Path/");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\Single\\Slash')", []() {
return Path::isAbsolute("\\Single\\Slash");
});
/*
* This '\\?\' prefix is not used as part of the path itself. They indicate
* that the path should be passed to the system with minimal modification,
* which means that you cannot use forward slashes to represent path
* separators, or a period to represent the current directory, or double
* dots to represent the parent directory. Basically, anything using this
* prefix kind of has to be an absolute path for it to work.
*/
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\?\\a:\\Long\\Path')", []() {
return
Path::isAbsolute("\\\\?\\a:\\Long\\Path") &&
Path::isAbsolute("\\\\?\\UNC\\Long\\Path");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('..\\File.ext')", []() {
return !Path::isAbsolute("..\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('.\\File.ext')", []() {
return !Path::isAbsolute(".\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('<driveletter>:RelativePath')", []() {
return
!Path::isAbsolute("A:RelativePath") &&
!Path::isAbsolute("a:RelativePath") &&
!Path::isAbsolute("z:RelativePath") &&
!Path::isAbsolute("Z:RelativePath");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('A\\F\\ile.ext')", []() {
return !Path::isAbsolute("A\\F\\ile.ext");
});
}
<commit_msg>Return the result value in the test to get real output on the command line.<commit_after>/* vim: set ts=4 sw=4 tw=79 et :*/
/* 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/. */
#include "TestHarness.h"
#include "base/io/Path.h"
int main(int argc, char* argv[]) {
int rv = 0;
/// Path::isAbsolute Tests
rv +=
runTest("Test empty string !isAbsolute", []() {
return !Path::isAbsolute("");
});
rv +=
runPosixOnlyTest("Test isAbsolute('/a/b/c')", []() {
return Path::isAbsolute("/a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('a/b/c')", []() {
return !Path::isAbsolute("a/b/c");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('../a/b')", []() {
return !Path::isAbsolute("../a/b");
});
rv +=
runPosixOnlyTest("Test !isAbsolute('./a/b'", []() {
return !Path::isAbsolute("./a/b");
});
rv +=
runWindowsOnlyTest("Test short/invalid path", []() {
return
!Path::isAbsolute("C:") &&
!Path::isAbsolute("C") &&
!Path::isAbsolute("F:F");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:\\Hello')", []() {
return
Path::isAbsolute("a:\\Hello") &&
Path::isAbsolute("A:\\Hello") &&
Path::isAbsolute("z:\\Hello") &&
Path::isAbsolute("Z:\\Hello");
});
// Windows supports forward slashes with this form of path
rv +=
runWindowsOnlyTest("Test isAbsolute('<driveletter>:/Hello')", []() {
return
Path::isAbsolute("a:/Hello") &&
Path::isAbsolute("A:/Hello") &&
Path::isAbsolute("z:/Hello") &&
Path::isAbsolute("Z:/Hello");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\Path')", []() {
return Path::isAbsolute("\\\\Path");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('//Path/')", []() {
return Path::isAbsolute("//Path/");
});
rv +=
runWindowsOnlyTest("Test isAbsolute('\\Single\\Slash')", []() {
return Path::isAbsolute("\\Single\\Slash");
});
/*
* This '\\?\' prefix is not used as part of the path itself. They indicate
* that the path should be passed to the system with minimal modification,
* which means that you cannot use forward slashes to represent path
* separators, or a period to represent the current directory, or double
* dots to represent the parent directory. Basically, anything using this
* prefix kind of has to be an absolute path for it to work.
*/
rv +=
runWindowsOnlyTest("Test isAbsolute('\\\\?\\a:\\Long\\Path')", []() {
return
Path::isAbsolute("\\\\?\\a:\\Long\\Path") &&
Path::isAbsolute("\\\\?\\UNC\\Long\\Path");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('..\\File.ext')", []() {
return !Path::isAbsolute("..\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('.\\File.ext')", []() {
return !Path::isAbsolute(".\\File.ext");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('<driveletter>:RelativePath')", []() {
return
!Path::isAbsolute("A:RelativePath") &&
!Path::isAbsolute("a:RelativePath") &&
!Path::isAbsolute("z:RelativePath") &&
!Path::isAbsolute("Z:RelativePath");
});
rv +=
runWindowsOnlyTest("Test !isAbsolute('A\\F\\ile.ext')", []() {
return !Path::isAbsolute("A\\F\\ile.ext");
});
return rv;
}
<|endoftext|>
|
<commit_before><commit_msg>Launcher: support multi-URLs in cmd line whether using --cdata or not<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Jeongseok Lee <[email protected]>
*
* Geoorgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <[email protected]> <[email protected]>
*
* This file is provided under the following "BSD-style" License:
* 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.
*/
#include "dart/constraint/JointCoulombFrictionConstraint.h"
#include <iostream>
#include "dart/common/Console.h"
#include "dart/dynamics/BodyNode.h"
#include "dart/dynamics/Joint.h"
#include "dart/dynamics/Skeleton.h"
#include "dart/lcpsolver/lcp.h"
#define DART_ERROR_ALLOWANCE 0.0
#define DART_ERP 0.0
#define DART_MAX_ERV 0.0
#define DART_CFM 1e-9
namespace dart {
namespace constraint {
double JointCoulombFrictionConstraint::mConstraintForceMixing = DART_CFM;
//==============================================================================
JointCoulombFrictionConstraint::JointCoulombFrictionConstraint(
dynamics::Joint* _joint)
: Constraint(),
mJoint(_joint),
mBodyNode(_joint->getChildBodyNode()),
mAppliedImpulseIndex(0)
{
assert(_joint);
assert(mBodyNode);
mLifeTime[0] = 0;
mLifeTime[1] = 0;
mLifeTime[2] = 0;
mLifeTime[3] = 0;
mLifeTime[4] = 0;
mLifeTime[5] = 0;
mActive[0] = false;
mActive[1] = false;
mActive[2] = false;
mActive[3] = false;
mActive[4] = false;
mActive[5] = false;
}
//==============================================================================
JointCoulombFrictionConstraint::~JointCoulombFrictionConstraint()
{
}
//==============================================================================
void JointCoulombFrictionConstraint::setConstraintForceMixing(double _cfm)
{
// Clamp constraint force mixing parameter if it is out of the range
if (_cfm < 1e-9)
{
dtwarn << "Constraint force mixing parameter[" << _cfm
<< "] is lower than 1e-9. " << "It is set to 1e-9." << std::endl;
mConstraintForceMixing = 1e-9;
}
if (_cfm > 1.0)
{
dtwarn << "Constraint force mixing parameter[" << _cfm
<< "] is greater than 1.0. " << "It is set to 1.0." << std::endl;
mConstraintForceMixing = 1.0;
}
mConstraintForceMixing = _cfm;
}
//==============================================================================
double JointCoulombFrictionConstraint::getConstraintForceMixing()
{
return mConstraintForceMixing;
}
//==============================================================================
void JointCoulombFrictionConstraint::update()
{
// Reset dimention
mDim = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof; ++i)
{
mNegativeVel[i] = -mJoint->getVelocity(i);
if (mNegativeVel[i] != 0.0)
{
mUpperBound[i] = mJoint->getCoulombFriction(i);;
mLowerBound[i] = -mUpperBound[i];
if (mActive[i])
{
++(mLifeTime[i]);
}
else
{
mActive[i] = true;
mLifeTime[i] = 0;
}
++mDim;
}
else
{
mActive[i] = false;
}
}
}
//==============================================================================
void JointCoulombFrictionConstraint::getInformation(ConstraintInfo* _lcp)
{
size_t index = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof; ++i)
{
if (mActive[i] == false)
continue;
assert(_lcp->w[index] == 0.0);
_lcp->b[index] = mNegativeVel[i];
_lcp->lo[index] = mLowerBound[i];
_lcp->hi[index] = mUpperBound[i];
assert(_lcp->findex[index] == -1);
if (mLifeTime[i])
_lcp->x[index] = mOldX[i];
else
_lcp->x[index] = 0.0;
index++;
}
}
//==============================================================================
void JointCoulombFrictionConstraint::applyUnitImpulse(size_t _index)
{
assert(_index < mDim && "Invalid Index.");
size_t localIndex = 0;
dynamics::Skeleton* skeleton = mJoint->getSkeleton();
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof; ++i)
{
if (mActive[i] == false)
continue;
if (localIndex == _index)
{
skeleton->clearConstraintImpulses();
mJoint->setConstraintImpulse(i, 1.0);
skeleton->updateBiasImpulse(mBodyNode);
skeleton->updateVelocityChange();
}
++localIndex;
}
mAppliedImpulseIndex = _index;
}
//==============================================================================
void JointCoulombFrictionConstraint::getVelocityChange(double* _delVel,
bool _withCfm)
{
assert(_delVel != NULL && "Null pointer is not allowed.");
size_t localIndex = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof ; ++i)
{
if (mActive[i] == false)
continue;
if (mJoint->getSkeleton()->isImpulseApplied())
_delVel[localIndex] = mJoint->getVelocityChange(i);
else
_delVel[localIndex] = 0.0;
++localIndex;
}
// Add small values to diagnal to keep it away from singular, similar to cfm
// varaible in ODE
if (_withCfm)
{
_delVel[mAppliedImpulseIndex] += _delVel[mAppliedImpulseIndex]
* mConstraintForceMixing;
}
assert(localIndex == mDim);
}
//==============================================================================
void JointCoulombFrictionConstraint::excite()
{
mJoint->getSkeleton()->setImpulseApplied(true);
}
//==============================================================================
void JointCoulombFrictionConstraint::unexcite()
{
mJoint->getSkeleton()->setImpulseApplied(false);
}
//==============================================================================
void JointCoulombFrictionConstraint::applyImpulse(double* _lambda)
{
size_t localIndex = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof ; ++i)
{
if (mActive[i] == false)
continue;
mJoint->setConstraintImpulse(i, _lambda[localIndex]);
mOldX[i] = _lambda[localIndex];
++localIndex;
}
}
//==============================================================================
dynamics::Skeleton* JointCoulombFrictionConstraint::getRootSkeleton() const
{
return mJoint->getSkeleton()->mUnionRootSkeleton;
}
//==============================================================================
bool JointCoulombFrictionConstraint::isActive() const
{
for (size_t i = 0; i < 6; ++i)
{
if (mActive[i])
return true;
}
return false;
}
} // namespace constraint
} // namespace dart
<commit_msg>Remove unused defines in JointCoulombFrcitionConstraint.cpp<commit_after>/*
* Copyright (c) 2015, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Jeongseok Lee <[email protected]>
*
* Geoorgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <[email protected]> <[email protected]>
*
* This file is provided under the following "BSD-style" License:
* 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.
*/
#include "dart/constraint/JointCoulombFrictionConstraint.h"
#include <iostream>
#include "dart/common/Console.h"
#include "dart/dynamics/BodyNode.h"
#include "dart/dynamics/Joint.h"
#include "dart/dynamics/Skeleton.h"
#include "dart/lcpsolver/lcp.h"
#define DART_CFM 1e-9
namespace dart {
namespace constraint {
double JointCoulombFrictionConstraint::mConstraintForceMixing = DART_CFM;
//==============================================================================
JointCoulombFrictionConstraint::JointCoulombFrictionConstraint(
dynamics::Joint* _joint)
: Constraint(),
mJoint(_joint),
mBodyNode(_joint->getChildBodyNode()),
mAppliedImpulseIndex(0)
{
assert(_joint);
assert(mBodyNode);
mLifeTime[0] = 0;
mLifeTime[1] = 0;
mLifeTime[2] = 0;
mLifeTime[3] = 0;
mLifeTime[4] = 0;
mLifeTime[5] = 0;
mActive[0] = false;
mActive[1] = false;
mActive[2] = false;
mActive[3] = false;
mActive[4] = false;
mActive[5] = false;
}
//==============================================================================
JointCoulombFrictionConstraint::~JointCoulombFrictionConstraint()
{
}
//==============================================================================
void JointCoulombFrictionConstraint::setConstraintForceMixing(double _cfm)
{
// Clamp constraint force mixing parameter if it is out of the range
if (_cfm < 1e-9)
{
dtwarn << "Constraint force mixing parameter[" << _cfm
<< "] is lower than 1e-9. " << "It is set to 1e-9." << std::endl;
mConstraintForceMixing = 1e-9;
}
if (_cfm > 1.0)
{
dtwarn << "Constraint force mixing parameter[" << _cfm
<< "] is greater than 1.0. " << "It is set to 1.0." << std::endl;
mConstraintForceMixing = 1.0;
}
mConstraintForceMixing = _cfm;
}
//==============================================================================
double JointCoulombFrictionConstraint::getConstraintForceMixing()
{
return mConstraintForceMixing;
}
//==============================================================================
void JointCoulombFrictionConstraint::update()
{
// Reset dimention
mDim = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof; ++i)
{
mNegativeVel[i] = -mJoint->getVelocity(i);
if (mNegativeVel[i] != 0.0)
{
mUpperBound[i] = mJoint->getCoulombFriction(i);;
mLowerBound[i] = -mUpperBound[i];
if (mActive[i])
{
++(mLifeTime[i]);
}
else
{
mActive[i] = true;
mLifeTime[i] = 0;
}
++mDim;
}
else
{
mActive[i] = false;
}
}
}
//==============================================================================
void JointCoulombFrictionConstraint::getInformation(ConstraintInfo* _lcp)
{
size_t index = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof; ++i)
{
if (mActive[i] == false)
continue;
assert(_lcp->w[index] == 0.0);
_lcp->b[index] = mNegativeVel[i];
_lcp->lo[index] = mLowerBound[i];
_lcp->hi[index] = mUpperBound[i];
assert(_lcp->findex[index] == -1);
if (mLifeTime[i])
_lcp->x[index] = mOldX[i];
else
_lcp->x[index] = 0.0;
index++;
}
}
//==============================================================================
void JointCoulombFrictionConstraint::applyUnitImpulse(size_t _index)
{
assert(_index < mDim && "Invalid Index.");
size_t localIndex = 0;
dynamics::Skeleton* skeleton = mJoint->getSkeleton();
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof; ++i)
{
if (mActive[i] == false)
continue;
if (localIndex == _index)
{
skeleton->clearConstraintImpulses();
mJoint->setConstraintImpulse(i, 1.0);
skeleton->updateBiasImpulse(mBodyNode);
skeleton->updateVelocityChange();
}
++localIndex;
}
mAppliedImpulseIndex = _index;
}
//==============================================================================
void JointCoulombFrictionConstraint::getVelocityChange(double* _delVel,
bool _withCfm)
{
assert(_delVel != NULL && "Null pointer is not allowed.");
size_t localIndex = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof ; ++i)
{
if (mActive[i] == false)
continue;
if (mJoint->getSkeleton()->isImpulseApplied())
_delVel[localIndex] = mJoint->getVelocityChange(i);
else
_delVel[localIndex] = 0.0;
++localIndex;
}
// Add small values to diagnal to keep it away from singular, similar to cfm
// varaible in ODE
if (_withCfm)
{
_delVel[mAppliedImpulseIndex] += _delVel[mAppliedImpulseIndex]
* mConstraintForceMixing;
}
assert(localIndex == mDim);
}
//==============================================================================
void JointCoulombFrictionConstraint::excite()
{
mJoint->getSkeleton()->setImpulseApplied(true);
}
//==============================================================================
void JointCoulombFrictionConstraint::unexcite()
{
mJoint->getSkeleton()->setImpulseApplied(false);
}
//==============================================================================
void JointCoulombFrictionConstraint::applyImpulse(double* _lambda)
{
size_t localIndex = 0;
size_t dof = mJoint->getNumDofs();
for (size_t i = 0; i < dof ; ++i)
{
if (mActive[i] == false)
continue;
mJoint->setConstraintImpulse(i, _lambda[localIndex]);
mOldX[i] = _lambda[localIndex];
++localIndex;
}
}
//==============================================================================
dynamics::Skeleton* JointCoulombFrictionConstraint::getRootSkeleton() const
{
return mJoint->getSkeleton()->mUnionRootSkeleton;
}
//==============================================================================
bool JointCoulombFrictionConstraint::isActive() const
{
for (size_t i = 0; i < 6; ++i)
{
if (mActive[i])
return true;
}
return false;
}
} // namespace constraint
} // namespace dart
<|endoftext|>
|
<commit_before><commit_msg>Restore disable-sync flag.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Linux: switch red and blue channels<commit_after><|endoftext|>
|
<commit_before>#ifdef LINUX_PLATFORM
#include "LinuxEventLoop.hpp"
#include "ActivityHandler.hpp"
#include "Context.hpp"
#include "InputService.hpp"
#include "TimeService.hpp"
#include "Global.hpp"
#include "Profiler.hpp"
#include "Render.hpp"
#include "Log.hpp"
using namespace std;
namespace MPACK
{
namespace Core
{
typedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
LinuxEventLoop::LinuxEventLoop(void *data)
: m_isFullscreen(false), m_isRunning(false), m_width(0), m_height(0), m_enabled(false)
{
}
ReturnValue LinuxEventLoop::Run(ActivityHandler* pActivityHandler)
{
m_pActivityHandler = pActivityHandler;
m_isRunning=true;
if(InitializeDisplay() == RETURN_VALUE_KO)
{
LOGE("LinuxEventLoop::Run failed to InitializeDisplay()");
return RETURN_VALUE_KO;
}
m_pActivityHandler->onActivate();
// Global step loop.
while(m_isRunning)
{
ProcessEvents();
if(m_pActivityHandler->onStep() != RETURN_VALUE_OK)
{
m_isRunning=false;
}
SwapBuffers();
}
m_pActivityHandler->onDeactivate();
DestroyDisplay();
return RETURN_VALUE_OK;
}
void LinuxEventLoop::ShowCursor()
{
Display* mainDisplay = XOpenDisplay(NULL);
XUndefineCursor(mainDisplay, m_XWindow);
XCloseDisplay(mainDisplay);
}
void LinuxEventLoop::HideCursor()
{
Display* mainDisplay = XOpenDisplay(NULL);
Pixmap blank;
XColor dummy;
char data[1] = {0};
/* make a blank cursor */
blank = XCreateBitmapFromData (mainDisplay, m_XWindow, data, 1, 1);
Cursor m_cursor = XCreatePixmapCursor(mainDisplay, blank, blank, &dummy, &dummy, 0, 0);
XFreePixmap (mainDisplay, blank);
XDefineCursor(mainDisplay, m_XWindow, m_cursor);
XCloseDisplay(mainDisplay);
}
void* LinuxEventLoop::GetWindowHandle() const
{
return (void *)(&m_XWindow);
}
ReturnValue LinuxEventLoop::InitializeDisplay()
{
int width=800;
int height=600;
int bpp=32;
bool fullscreen=false;
m_display = XOpenDisplay(0);
if (m_display == NULL)
{
LOGE("Could not open the display");
return RETURN_VALUE_KO;
}
m_screenID = DefaultScreen(m_display); //Get the default screen id
Window root = RootWindow(m_display, m_screenID);
int n = 0, modeNum = 0;
//Get a framebuffer config using the default attributes
GLXFBConfig framebufferConfig = (*glXChooseFBConfig(m_display, m_screenID, 0, &n));
XF86VidModeModeInfo **modes;
if (!XF86VidModeGetAllModeLines(m_display, m_screenID, &modeNum, &modes))
{
LOGE("Could not query the video modes");
return RETURN_VALUE_KO;
}
m_XF86DeskMode = *modes[0];
int bestMode = -1;
for (int i = 0; i < modeNum; i++)
{
if ((modes[i]->hdisplay == width) &&
(modes[i]->vdisplay == height))
{
bestMode = i;
}
}
if (bestMode == -1)
{
LOGE("Could not find a suitable graphics mode");
return RETURN_VALUE_KO;
}
int doubleBufferedAttribList [] = {
GLX_RGBA, GLX_DOUBLEBUFFER,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_ALPHA_SIZE, 4,
GLX_DEPTH_SIZE, 16,
None
};
XVisualInfo* vi = NULL;
//Attempt to create a double buffered window
vi = glXChooseVisual(m_display, m_screenID, doubleBufferedAttribList);
if (vi == NULL)
{
LOGE("Could not create a double buffered window");
return RETURN_VALUE_KO;
}
Colormap cmap = XCreateColormap(m_display, root, vi->visual, AllocNone);
m_XSetAttr.background_pixel = 0;
m_XSetAttr.border_pixel = 0;
m_XSetAttr.colormap = cmap;
m_XSetAttr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
StructureNotifyMask;
m_XSetAttr.override_redirect = False;
unsigned long windowAttributes = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;
if (fullscreen)
{
windowAttributes = CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;
XF86VidModeSwitchToMode(m_display, m_screenID, modes[bestMode]);
XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
m_XSetAttr.override_redirect = True;
}
m_XWindow = XCreateWindow(m_display, root,
0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,
windowAttributes, &m_XSetAttr);
{
XSizeHints sizehints;
sizehints.x = 0;
sizehints.y = 0;
sizehints.width = width;
sizehints.height = height;
sizehints.flags = USSize | USPosition;
XSetNormalHints(m_display, m_XWindow, &sizehints);
}
//Create a GL 2.1 context
GLXContext m_glContext = glXCreateContext(m_display, vi, 0, GL_TRUE);
if (m_glContext == NULL)
{
LOGE("Could not create a GL 2.1 context, please check your graphics drivers");
return RETURN_VALUE_KO;
}
m_GL3Supported = false; //we're not using GL3.0 here!
string title = "MPACK";
if (fullscreen)
{
XWarpPointer(m_display, None, m_XWindow, 0, 0, 0, 0, 0, 0);
XMapRaised(m_display, m_XWindow);
XGrabKeyboard(m_display, m_XWindow, True, GrabModeAsync, GrabModeAsync, CurrentTime);
XGrabPointer(m_display, m_XWindow, True, ButtonPressMask,
GrabModeAsync, GrabModeAsync, m_XWindow, None, CurrentTime);
m_isFullscreen = true;
}
else
{
Atom wmDelete = XInternAtom(m_display, "WM_DELETE_WINDOW", True);
XSetWMProtocols(m_display, m_XWindow, &wmDelete, 1);
XSetStandardProperties(m_display, m_XWindow, title.c_str(), None, 0, NULL, 0, NULL);
XMapRaised(m_display, m_XWindow);
}
XFree(modes);
//Make the new context current
glXMakeCurrent(m_display, m_XWindow, m_glContext);
typedef int (*PFNGLXSWAPINTERVALMESA)(int interval);
PFNGLXSWAPINTERVALMESA glXSwapIntervalMESA = NULL;
glXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESA)glXGetProcAddress((unsigned char*)"glXSwapIntervalMESA");
if( !glXSwapIntervalMESA )
{
return RETURN_VALUE_KO;
}
glXSwapIntervalMESA(0);
return RETURN_VALUE_OK;
}
void LinuxEventLoop::DestroyDisplay()
{
if(m_glContext)
{
glXMakeCurrent(m_display, None, NULL);
glXDestroyContext(m_display, m_glContext);
m_glContext = NULL;
}
if(m_isFullscreen)
{
XF86VidModeSwitchToMode(m_display, m_screenID, &m_XF86DeskMode);
XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
}
}
void LinuxEventLoop::ProcessEvents()
{
Global::pContext->pTimeService->Update();
Global::pContext->pInputService->Update();
XEvent event;
while (XPending(m_display) > 0)
{
XNextEvent(m_display, &event);
switch (event.type)
{
case Expose:
break;
case ConfigureNotify:
{
int width = event.xconfigure.width;
int height = event.xconfigure.height;
if(width!=m_width || height!=m_height)
{
m_width=width;
m_height=height;
m_pActivityHandler->onDeactivate();
Graphics::Render::SetScreenSize(m_width,m_height);
m_pActivityHandler->onActivate();
}
}
break;
case KeyPress:
{
Global::pContext->pInputService->GetKeyboard()->HandleKeyDown(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
}
break;
case KeyRelease:
{
Global::pContext->pInputService->GetKeyboard()->HandleKeyUp(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
}
break;
case ClientMessage:
if (string(XGetAtomName(m_display, event.xclient.message_type)) == string("WM_PROTOCOLS"))
{
std::cout << "Closing the Window!" << std::endl;
m_isRunning = false;
return;
}
break;
default:
break;
}
}
}
void LinuxEventLoop::SwapBuffers()
{
Profiler::Begin("SwapBuffers");
glXSwapBuffers(m_display, m_XWindow);
Profiler::End();
}
}
}
#endif
<commit_msg>Fix memory leak for Linux build<commit_after>#ifdef LINUX_PLATFORM
#include "LinuxEventLoop.hpp"
#include "ActivityHandler.hpp"
#include "Context.hpp"
#include "InputService.hpp"
#include "TimeService.hpp"
#include "Global.hpp"
#include "Profiler.hpp"
#include "Render.hpp"
#include "Log.hpp"
using namespace std;
namespace MPACK
{
namespace Core
{
typedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);
LinuxEventLoop::LinuxEventLoop(void *data)
: m_isFullscreen(false), m_isRunning(false), m_width(0), m_height(0),
m_enabled(false), m_glContext(NULL)
{
}
ReturnValue LinuxEventLoop::Run(ActivityHandler* pActivityHandler)
{
m_pActivityHandler = pActivityHandler;
m_isRunning=true;
if(InitializeDisplay() == RETURN_VALUE_KO)
{
LOGE("LinuxEventLoop::Run failed to InitializeDisplay()");
return RETURN_VALUE_KO;
}
m_pActivityHandler->onActivate();
// Global step loop.
while(m_isRunning)
{
ProcessEvents();
if(m_pActivityHandler->onStep() != RETURN_VALUE_OK)
{
m_isRunning=false;
}
SwapBuffers();
}
m_pActivityHandler->onDeactivate();
DestroyDisplay();
return RETURN_VALUE_OK;
}
void LinuxEventLoop::ShowCursor()
{
Display* mainDisplay = XOpenDisplay(NULL);
XUndefineCursor(mainDisplay, m_XWindow);
XCloseDisplay(mainDisplay);
}
void LinuxEventLoop::HideCursor()
{
Display* mainDisplay = XOpenDisplay(NULL);
Pixmap blank;
XColor dummy;
char data[1] = {0};
/* make a blank cursor */
blank = XCreateBitmapFromData (mainDisplay, m_XWindow, data, 1, 1);
Cursor m_cursor = XCreatePixmapCursor(mainDisplay, blank, blank, &dummy, &dummy, 0, 0);
XFreePixmap (mainDisplay, blank);
XDefineCursor(mainDisplay, m_XWindow, m_cursor);
XCloseDisplay(mainDisplay);
}
void* LinuxEventLoop::GetWindowHandle() const
{
return (void *)(&m_XWindow);
}
ReturnValue LinuxEventLoop::InitializeDisplay()
{
int width=800;
int height=600;
int bpp=32;
bool fullscreen=false;
m_display = XOpenDisplay(0);
if (m_display == NULL)
{
LOGE("Could not open the display");
return RETURN_VALUE_KO;
}
m_screenID = DefaultScreen(m_display); //Get the default screen id
Window root = RootWindow(m_display, m_screenID);
int n = 0, modeNum = 0;
//Get a framebuffer config using the default attributes
GLXFBConfig framebufferConfig = (*glXChooseFBConfig(m_display, m_screenID, 0, &n));
XF86VidModeModeInfo **modes;
if (!XF86VidModeGetAllModeLines(m_display, m_screenID, &modeNum, &modes))
{
LOGE("Could not query the video modes");
return RETURN_VALUE_KO;
}
m_XF86DeskMode = *modes[0];
int bestMode = -1;
for (int i = 0; i < modeNum; i++)
{
if ((modes[i]->hdisplay == width) &&
(modes[i]->vdisplay == height))
{
bestMode = i;
}
}
if (bestMode == -1)
{
LOGE("Could not find a suitable graphics mode");
return RETURN_VALUE_KO;
}
int doubleBufferedAttribList [] = {
GLX_RGBA, GLX_DOUBLEBUFFER,
GLX_RED_SIZE, 4,
GLX_GREEN_SIZE, 4,
GLX_BLUE_SIZE, 4,
GLX_ALPHA_SIZE, 4,
GLX_DEPTH_SIZE, 16,
None
};
XVisualInfo* vi = NULL;
//Attempt to create a double buffered window
vi = glXChooseVisual(m_display, m_screenID, doubleBufferedAttribList);
if (vi == NULL)
{
LOGE("Could not create a double buffered window");
return RETURN_VALUE_KO;
}
Colormap cmap = XCreateColormap(m_display, root, vi->visual, AllocNone);
m_XSetAttr.background_pixel = 0;
m_XSetAttr.border_pixel = 0;
m_XSetAttr.colormap = cmap;
m_XSetAttr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
StructureNotifyMask;
m_XSetAttr.override_redirect = False;
unsigned long windowAttributes = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;
if (fullscreen)
{
windowAttributes = CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;
XF86VidModeSwitchToMode(m_display, m_screenID, modes[bestMode]);
XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
m_XSetAttr.override_redirect = True;
}
m_XWindow = XCreateWindow(m_display, root,
0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,
windowAttributes, &m_XSetAttr);
{
XSizeHints sizehints;
sizehints.x = 0;
sizehints.y = 0;
sizehints.width = width;
sizehints.height = height;
sizehints.flags = USSize | USPosition;
XSetNormalHints(m_display, m_XWindow, &sizehints);
}
//Create a GL 2.1 context
GLXContext m_glContext = glXCreateContext(m_display, vi, 0, GL_TRUE);
if (m_glContext == NULL)
{
LOGE("Could not create a GL 2.1 context, please check your graphics drivers");
return RETURN_VALUE_KO;
}
m_GL3Supported = false; //we're not using GL3.0 here!
string title = "MPACK";
if (fullscreen)
{
XWarpPointer(m_display, None, m_XWindow, 0, 0, 0, 0, 0, 0);
XMapRaised(m_display, m_XWindow);
XGrabKeyboard(m_display, m_XWindow, True, GrabModeAsync, GrabModeAsync, CurrentTime);
XGrabPointer(m_display, m_XWindow, True, ButtonPressMask,
GrabModeAsync, GrabModeAsync, m_XWindow, None, CurrentTime);
m_isFullscreen = true;
}
else
{
Atom wmDelete = XInternAtom(m_display, "WM_DELETE_WINDOW", True);
XSetWMProtocols(m_display, m_XWindow, &wmDelete, 1);
XSetStandardProperties(m_display, m_XWindow, title.c_str(), None, 0, NULL, 0, NULL);
XMapRaised(m_display, m_XWindow);
}
XFree(modes);
//Make the new context current
glXMakeCurrent(m_display, m_XWindow, m_glContext);
typedef int (*PFNGLXSWAPINTERVALMESA)(int interval);
PFNGLXSWAPINTERVALMESA glXSwapIntervalMESA = NULL;
glXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESA)glXGetProcAddress((unsigned char*)"glXSwapIntervalMESA");
if( !glXSwapIntervalMESA )
{
return RETURN_VALUE_KO;
}
glXSwapIntervalMESA(0);
return RETURN_VALUE_OK;
}
void LinuxEventLoop::DestroyDisplay()
{
if(m_glContext)
{
glXMakeCurrent(m_display, None, NULL);
glXDestroyContext(m_display, m_glContext);
m_glContext = NULL;
}
if(m_isFullscreen)
{
XF86VidModeSwitchToMode(m_display, m_screenID, &m_XF86DeskMode);
XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
}
XCloseDisplay(m_display);
}
void LinuxEventLoop::ProcessEvents()
{
Global::pContext->pTimeService->Update();
Global::pContext->pInputService->Update();
XEvent event;
while (XPending(m_display) > 0)
{
XNextEvent(m_display, &event);
switch (event.type)
{
case Expose:
break;
case ConfigureNotify:
{
int width = event.xconfigure.width;
int height = event.xconfigure.height;
if(width!=m_width || height!=m_height)
{
m_width=width;
m_height=height;
m_pActivityHandler->onDeactivate();
Graphics::Render::SetScreenSize(m_width,m_height);
m_pActivityHandler->onActivate();
}
}
break;
case KeyPress:
{
Global::pContext->pInputService->GetKeyboard()->HandleKeyDown(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
}
break;
case KeyRelease:
{
Global::pContext->pInputService->GetKeyboard()->HandleKeyUp(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
}
break;
case ClientMessage:
if (string(XGetAtomName(m_display, event.xclient.message_type)) == string("WM_PROTOCOLS"))
{
std::cout << "Closing the Window!" << std::endl;
m_isRunning = false;
return;
}
break;
default:
break;
}
}
}
void LinuxEventLoop::SwapBuffers()
{
PROFILE_BEGIN("SwapBuffers");
glXSwapBuffers(m_display, m_XWindow);
PROFILE_END();
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCanvas.h"
#include "SkDocument.h"
#include "SkFontMgr.h"
#include "SkGradientShader.h"
#include "SkPaint.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTextBlob.h"
#include "SkTypeface.h"
#include <hb.h>
#include <hb-ot.h>
#include <cassert>
#include <iostream>
#include <map>
struct BaseOption {
std::string selector;
std::string description;
virtual void set(std::string _value) = 0;
virtual std::string valueToString() = 0;
BaseOption(std::string _selector, std::string _description) :
selector(_selector),
description(_description) {}
virtual ~BaseOption() {}
};
template <class T> struct Option : BaseOption {
T value;
Option(std::string selector, std::string description, T defaultValue) :
BaseOption(selector, description),
value(defaultValue) {}
};
struct DoubleOption : Option<double> {
virtual void set(std::string _value) {
value = atof(_value.c_str());
}
virtual std::string valueToString() {
return std::to_string(value);
}
DoubleOption(std::string selector, std::string description, double defaultValue) :
Option<double>(selector, description, defaultValue) {}
};
struct SkStringOption : Option<SkString> {
virtual void set(std::string _value) {
value = _value.c_str();
}
virtual std::string valueToString() {
return value.c_str();
}
SkStringOption(std::string selector, std::string description, SkString defaultValue) :
Option<SkString>(selector, description, defaultValue) {}
};
struct StdStringOption : Option<std::string> {
virtual void set(std::string _value) {
value = _value;
}
virtual std::string valueToString() {
return value;
}
StdStringOption(std::string selector, std::string description, std::string defaultValue) :
Option<std::string>(selector, description, defaultValue) {}
};
struct Config {
DoubleOption *page_width = new DoubleOption("-w", "Page width", 600.0f);
DoubleOption *page_height = new DoubleOption("-h", "Page height", 800.0f);
SkStringOption *title = new SkStringOption("-t", "PDF title", SkString("---"));
SkStringOption *author = new SkStringOption("-a", "PDF author", SkString("---"));
SkStringOption *subject = new SkStringOption("-k", "PDF subject", SkString("---"));
SkStringOption *keywords = new SkStringOption("-c", "PDF keywords", SkString("---"));
SkStringOption *creator = new SkStringOption("-t", "PDF creator", SkString("---"));
StdStringOption *font_file = new StdStringOption("-f", ".ttf font file", "fonts/DejaVuSans.ttf");
DoubleOption *font_size = new DoubleOption("-z", "Font size", 8.0f);
DoubleOption *left_margin = new DoubleOption("-m", "Left margin", 20.0f);
DoubleOption *line_spacing_ratio = new DoubleOption("-h", "Line spacing ratio", 1.5f);
StdStringOption *output_file_name = new StdStringOption("-o", ".pdf output file name", "out-skiahf.pdf");
std::map<std::string, BaseOption*> options = {
{ page_width->selector, page_width },
{ page_height->selector, page_height },
{ title->selector, title },
{ author->selector, author },
{ subject->selector, subject },
{ keywords->selector, keywords },
{ creator->selector, creator },
{ font_file->selector, font_file },
{ font_size->selector, font_size },
{ left_margin->selector, left_margin },
{ line_spacing_ratio->selector, line_spacing_ratio },
{ output_file_name->selector, output_file_name },
};
Config(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::string option_selector(argv[i]);
auto it = options.find(option_selector);
if (it != options.end()) {
if (i >= argc) {
break;
}
const char *option_value = argv[i + 1];
it->second->set(option_value);
i++;
} else {
printf("Ignoring unrecognized option: %s.\n", argv[i]);
printf("Usage: %s {option value}\n", argv[0]);
printf("\tTakes text from stdin and produces pdf file.\n");
printf("Supported options:\n");
for (auto it = options.begin(); it != options.end(); ++it) {
printf("\t%s\t%s (%s)\n", it->first.c_str(),
it->second->description.c_str(),
it->second->valueToString().c_str());
}
exit(-1);
}
}
} // end of Config::Config
};
const double FONT_SIZE_SCALE = 64.0f;
struct Face {
struct HBFDel { void operator()(hb_face_t* f) { hb_face_destroy(f); } };
std::unique_ptr<hb_face_t, HBFDel> fHarfBuzzFace;
sk_sp<SkTypeface> fSkiaTypeface;
Face(const char* path, int index) {
// fairly portable mmap impl
auto data = SkData::MakeFromFileName(path);
assert(data);
if (!data) { return; }
fSkiaTypeface.reset(
SkTypeface::CreateFromStream(
new SkMemoryStream(data), index));
assert(fSkiaTypeface);
if (!fSkiaTypeface) { return; }
auto destroy = [](void *d) { static_cast<SkData*>(d)->unref(); };
const char* bytes = (const char*)data->data();
unsigned int size = (unsigned int)data->size();
hb_blob_t* blob = hb_blob_create(bytes,
size,
HB_MEMORY_MODE_READONLY,
data.release(),
destroy);
assert(blob);
hb_blob_make_immutable(blob);
hb_face_t* face = hb_face_create(blob, (unsigned)index);
hb_blob_destroy(blob);
assert(face);
if (!face) {
fSkiaTypeface.reset();
return;
}
hb_face_set_index(face, (unsigned)index);
hb_face_set_upem(face, fSkiaTypeface->getUnitsPerEm());
fHarfBuzzFace.reset(face);
}
};
class Placement {
public:
Placement(Config &_config, SkWStream* outputStream) : config(_config) {
face = new Face(config.font_file->value.c_str(), 0 /* index */);
hb_font = hb_font_create(face->fHarfBuzzFace.get());
hb_font_set_scale(hb_font,
FONT_SIZE_SCALE * config.font_size->value,
FONT_SIZE_SCALE * config.font_size->value);
hb_ot_font_set_funcs(hb_font);
SkDocument::PDFMetadata pdf_info;
pdf_info.fTitle = config.title->value;
pdf_info.fAuthor = config.author->value;
pdf_info.fSubject = config.subject->value;
pdf_info.fKeywords = config.keywords->value;
pdf_info.fCreator = config.creator->value;
SkTime::DateTime now;
SkTime::GetDateTime(&now);
pdf_info.fCreation.fEnabled = true;
pdf_info.fCreation.fDateTime = now;
pdf_info.fModified.fEnabled = true;
pdf_info.fModified.fDateTime = now;
pdfDocument = SkDocument::MakePDF(outputStream, SK_ScalarDefaultRasterDPI,
pdf_info, nullptr, true);
assert(pdfDocument);
white_paint.setColor(SK_ColorWHITE);
glyph_paint.setFlags(
SkPaint::kAntiAlias_Flag |
SkPaint::kSubpixelText_Flag); // ... avoid waggly text when rotating.
glyph_paint.setColor(SK_ColorBLACK);
glyph_paint.setTextSize(config.font_size->value);
SkAutoTUnref<SkFontMgr> fm(SkFontMgr::RefDefault());
glyph_paint.setTypeface(face->fSkiaTypeface);
glyph_paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
NewPage();
} // end of Placement
~Placement() {
delete face;
hb_font_destroy (hb_font);
}
void WriteLine(const char *text) {
/* Create hb-buffer and populate. */
hb_buffer_t *hb_buffer = hb_buffer_create ();
hb_buffer_add_utf8 (hb_buffer, text, -1, 0, -1);
hb_buffer_guess_segment_properties (hb_buffer);
/* Shape it! */
hb_shape (hb_font, hb_buffer, NULL, 0);
DrawGlyphs(hb_buffer);
hb_buffer_destroy (hb_buffer);
// Advance to the next line.
current_y += config.line_spacing_ratio->value * config.font_size->value;
if (current_y > config.page_height->value) {
pdfDocument->endPage();
NewPage();
}
}
bool Close() {
return pdfDocument->close();
}
private:
Config config;
Face *face;
hb_font_t *hb_font;
sk_sp<SkDocument> pdfDocument;
SkCanvas* pageCanvas;
SkPaint white_paint;
SkPaint glyph_paint;
double current_x;
double current_y;
void NewPage() {
pageCanvas = pdfDocument->beginPage(config.page_width->value, config.page_height->value);
pageCanvas->drawPaint(white_paint);
current_x = config.left_margin->value;
current_y = config.line_spacing_ratio->value * config.font_size->value;
}
bool DrawGlyphs(hb_buffer_t *hb_buffer) {
SkTextBlobBuilder textBlobBuilder;
unsigned len = hb_buffer_get_length (hb_buffer);
if (len == 0) {
return true;
}
hb_glyph_info_t *info = hb_buffer_get_glyph_infos (hb_buffer, NULL);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (hb_buffer, NULL);
auto runBuffer = textBlobBuilder.allocRunPos(glyph_paint, len);
double x = 0;
double y = 0;
for (unsigned int i = 0; i < len; i++)
{
runBuffer.glyphs[i] = info[i].codepoint;
reinterpret_cast<SkPoint*>(runBuffer.pos)[i] = SkPoint::Make(
x + pos[i].x_offset / FONT_SIZE_SCALE,
y - pos[i].y_offset / FONT_SIZE_SCALE);
x += pos[i].x_advance / FONT_SIZE_SCALE;
y += pos[i].y_advance / FONT_SIZE_SCALE;
}
pageCanvas->drawTextBlob(textBlobBuilder.build(), current_x, current_y, glyph_paint);
return true;
} // end of DrawGlyphs
}; // end of Placement class
int main(int argc, char** argv) {
Config config(argc, argv);
Placement placement(config, new SkFILEWStream(config.output_file_name->value.c_str()));
for (std::string line; std::getline(std::cin, line);) {
placement.WriteLine(line.c_str());
}
placement.Close();
return 0;
}
<commit_msg>Minor cleanup, comments<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This sample progam demonstrates how to use Skia and HarfBuzz to
// produce a PDF file from UTF-8 text in stdin.
#include <cassert>
#include <iostream>
#include <map>
#include <string>
#include <hb-ot.h>
#include "SkCanvas.h"
#include "SkDocument.h"
#include "SkStream.h"
#include "SkTextBlob.h"
#include "SkTypeface.h"
struct BaseOption {
std::string selector;
std::string description;
virtual void set(std::string _value) = 0;
virtual std::string valueToString() = 0;
BaseOption(std::string _selector, std::string _description) :
selector(_selector),
description(_description) {}
virtual ~BaseOption() {}
};
template <class T> struct Option : BaseOption {
T value;
Option(std::string selector, std::string description, T defaultValue) :
BaseOption(selector, description),
value(defaultValue) {}
};
struct DoubleOption : Option<double> {
virtual void set(std::string _value) {
value = atof(_value.c_str());
}
virtual std::string valueToString() {
return std::to_string(value);
}
DoubleOption(std::string selector, std::string description, double defaultValue) :
Option<double>(selector, description, defaultValue) {}
};
struct SkStringOption : Option<SkString> {
virtual void set(std::string _value) {
value = _value.c_str();
}
virtual std::string valueToString() {
return value.c_str();
}
SkStringOption(std::string selector, std::string description, SkString defaultValue) :
Option<SkString>(selector, description, defaultValue) {}
};
struct StdStringOption : Option<std::string> {
virtual void set(std::string _value) {
value = _value;
}
virtual std::string valueToString() {
return value;
}
StdStringOption(std::string selector, std::string description, std::string defaultValue) :
Option<std::string>(selector, description, defaultValue) {}
};
struct Config {
DoubleOption *page_width = new DoubleOption("-w", "Page width", 600.0f);
DoubleOption *page_height = new DoubleOption("-h", "Page height", 800.0f);
SkStringOption *title = new SkStringOption("-t", "PDF title", SkString("---"));
SkStringOption *author = new SkStringOption("-a", "PDF author", SkString("---"));
SkStringOption *subject = new SkStringOption("-k", "PDF subject", SkString("---"));
SkStringOption *keywords = new SkStringOption("-c", "PDF keywords", SkString("---"));
SkStringOption *creator = new SkStringOption("-t", "PDF creator", SkString("---"));
StdStringOption *font_file = new StdStringOption("-f", ".ttf font file", "fonts/DejaVuSans.ttf");
DoubleOption *font_size = new DoubleOption("-z", "Font size", 8.0f);
DoubleOption *left_margin = new DoubleOption("-m", "Left margin", 20.0f);
DoubleOption *line_spacing_ratio = new DoubleOption("-h", "Line spacing ratio", 1.5f);
StdStringOption *output_file_name = new StdStringOption("-o", ".pdf output file name", "out-skiahf.pdf");
std::map<std::string, BaseOption*> options = {
{ page_width->selector, page_width },
{ page_height->selector, page_height },
{ title->selector, title },
{ author->selector, author },
{ subject->selector, subject },
{ keywords->selector, keywords },
{ creator->selector, creator },
{ font_file->selector, font_file },
{ font_size->selector, font_size },
{ left_margin->selector, left_margin },
{ line_spacing_ratio->selector, line_spacing_ratio },
{ output_file_name->selector, output_file_name },
};
Config(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::string option_selector(argv[i]);
auto it = options.find(option_selector);
if (it != options.end()) {
if (i >= argc) {
break;
}
const char *option_value = argv[i + 1];
it->second->set(option_value);
i++;
} else {
printf("Ignoring unrecognized option: %s.\n", argv[i]);
printf("Usage: %s {option value}\n", argv[0]);
printf("\tTakes text from stdin and produces pdf file.\n");
printf("Supported options:\n");
for (auto it = options.begin(); it != options.end(); ++it) {
printf("\t%s\t%s (%s)\n", it->first.c_str(),
it->second->description.c_str(),
it->second->valueToString().c_str());
}
exit(-1);
}
}
} // end of Config::Config
};
const double FONT_SIZE_SCALE = 64.0f;
struct Face {
struct HBFDel { void operator()(hb_face_t* f) { hb_face_destroy(f); } };
std::unique_ptr<hb_face_t, HBFDel> fHarfBuzzFace;
sk_sp<SkTypeface> fSkiaTypeface;
Face(const char* path, int index) {
// fairly portable mmap impl
auto data = SkData::MakeFromFileName(path);
assert(data);
if (!data) { return; }
fSkiaTypeface.reset(
SkTypeface::CreateFromStream(
new SkMemoryStream(data), index));
assert(fSkiaTypeface);
if (!fSkiaTypeface) { return; }
auto destroy = [](void *d) { static_cast<SkData*>(d)->unref(); };
const char* bytes = (const char*)data->data();
unsigned int size = (unsigned int)data->size();
hb_blob_t* blob = hb_blob_create(bytes,
size,
HB_MEMORY_MODE_READONLY,
data.release(),
destroy);
assert(blob);
hb_blob_make_immutable(blob);
hb_face_t* face = hb_face_create(blob, (unsigned)index);
hb_blob_destroy(blob);
assert(face);
if (!face) {
fSkiaTypeface.reset();
return;
}
hb_face_set_index(face, (unsigned)index);
hb_face_set_upem(face, fSkiaTypeface->getUnitsPerEm());
fHarfBuzzFace.reset(face);
}
};
class Placement {
public:
Placement(Config &_config, SkWStream* outputStream) : config(_config) {
face = new Face(config.font_file->value.c_str(), 0 /* index */);
hb_font = hb_font_create(face->fHarfBuzzFace.get());
hb_font_set_scale(hb_font,
FONT_SIZE_SCALE * config.font_size->value,
FONT_SIZE_SCALE * config.font_size->value);
hb_ot_font_set_funcs(hb_font);
SkDocument::PDFMetadata pdf_info;
pdf_info.fTitle = config.title->value;
pdf_info.fAuthor = config.author->value;
pdf_info.fSubject = config.subject->value;
pdf_info.fKeywords = config.keywords->value;
pdf_info.fCreator = config.creator->value;
SkTime::DateTime now;
SkTime::GetDateTime(&now);
pdf_info.fCreation.fEnabled = true;
pdf_info.fCreation.fDateTime = now;
pdf_info.fModified.fEnabled = true;
pdf_info.fModified.fDateTime = now;
pdfDocument = SkDocument::MakePDF(outputStream, SK_ScalarDefaultRasterDPI,
pdf_info, nullptr, true);
assert(pdfDocument);
white_paint.setColor(SK_ColorWHITE);
glyph_paint.setFlags(
SkPaint::kAntiAlias_Flag |
SkPaint::kSubpixelText_Flag); // ... avoid waggly text when rotating.
glyph_paint.setColor(SK_ColorBLACK);
glyph_paint.setTextSize(config.font_size->value);
glyph_paint.setTypeface(face->fSkiaTypeface);
glyph_paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
NewPage();
} // end of Placement
~Placement() {
delete face;
hb_font_destroy (hb_font);
}
void WriteLine(const char *text) {
/* Create hb-buffer and populate. */
hb_buffer_t *hb_buffer = hb_buffer_create ();
hb_buffer_add_utf8 (hb_buffer, text, -1, 0, -1);
hb_buffer_guess_segment_properties (hb_buffer);
/* Shape it! */
hb_shape (hb_font, hb_buffer, NULL, 0);
DrawGlyphs(hb_buffer);
hb_buffer_destroy (hb_buffer);
// Advance to the next line.
current_y += config.line_spacing_ratio->value * config.font_size->value;
if (current_y > config.page_height->value) {
pdfDocument->endPage();
NewPage();
}
}
bool Close() {
return pdfDocument->close();
}
private:
Config config;
Face *face;
hb_font_t *hb_font;
sk_sp<SkDocument> pdfDocument;
SkCanvas* pageCanvas;
SkPaint white_paint;
SkPaint glyph_paint;
double current_x;
double current_y;
void NewPage() {
pageCanvas = pdfDocument->beginPage(config.page_width->value, config.page_height->value);
pageCanvas->drawPaint(white_paint);
current_x = config.left_margin->value;
current_y = config.line_spacing_ratio->value * config.font_size->value;
}
bool DrawGlyphs(hb_buffer_t *hb_buffer) {
SkTextBlobBuilder textBlobBuilder;
unsigned len = hb_buffer_get_length (hb_buffer);
if (len == 0) {
return true;
}
hb_glyph_info_t *info = hb_buffer_get_glyph_infos (hb_buffer, NULL);
hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (hb_buffer, NULL);
auto runBuffer = textBlobBuilder.allocRunPos(glyph_paint, len);
double x = 0;
double y = 0;
for (unsigned int i = 0; i < len; i++)
{
runBuffer.glyphs[i] = info[i].codepoint;
reinterpret_cast<SkPoint*>(runBuffer.pos)[i] = SkPoint::Make(
x + pos[i].x_offset / FONT_SIZE_SCALE,
y - pos[i].y_offset / FONT_SIZE_SCALE);
x += pos[i].x_advance / FONT_SIZE_SCALE;
y += pos[i].y_advance / FONT_SIZE_SCALE;
}
pageCanvas->drawTextBlob(textBlobBuilder.build(), current_x, current_y, glyph_paint);
return true;
} // end of DrawGlyphs
}; // end of Placement class
int main(int argc, char** argv) {
Config config(argc, argv);
Placement placement(config, new SkFILEWStream(config.output_file_name->value.c_str()));
for (std::string line; std::getline(std::cin, line);) {
placement.WriteLine(line.c_str());
}
placement.Close();
return 0;
}
<|endoftext|>
|
<commit_before>#include <math.h>
#include <tgmath.h>
#define ISINT(x) !(fabs((x) - std::nearbyint(x)) > 1e-7)
// double lfastchoose(double n, double k)
// {
// double tmp = log(boost::math::beta(n - k + 1., k + 1.));
// return -log(n + 1.) - tmp;
// }
/* mathematically the same:
less stable typically, but useful if n-k+1 < 0 : */
static
double lfastchoose2(double n, double k)
{
double r;
r = lgamma(n - k + 1.);
return std::lgamma(n + 1.) - std::lgamma(k + 1.) - r;
}
double lbeta_cpp(double a, double b)
{
double r;
r = std::lgamma(a+b);
return std::lgamma(a) + std::lgamma(b) - r;
}
double lchoose_cpp(double n, double k)
{
double k0 = k;
k = nearbyint(k);
/* NaNs propagated correctly */
static_assert(std::numeric_limits<double>::is_iec559, "IEEE 754 required");
if(isnan(n) || isnan(k)) return n + k;
if (fabs(k - k0) > 1e-7)
// std::cout<<"'k' "<<k0<<" must be integer, rounded to "<<k;
if (k < 2) {
if (k < 0) return -std::numeric_limits<double>::infinity();
if (k == 0) return 0.;
/* else: k == 1 */
return log(fabs(n));
}
/* else: k >= 2 */
if (n < 0) {
return lchoose_cpp(-n+ k-1, k);
}
else if (ISINT(n)) {
n = std::nearbyint(n);
if(n < k) return -std::numeric_limits<double>::infinity();
/* k <= n :*/
if(n - k < 2) return lchoose_cpp(n, n-k); /* <- Symmetry */
/* else: n >= k+2 */
return lfastchoose2(n, k);
}
/* else non-integer n >= 0 : */
if (n < k-1) {
return lfastchoose2(n, k);
}
return lfastchoose2(n, k);
}
<commit_msg>add limits header for linux<commit_after>#include <math.h>
#include <tgmath.h>
#include <limits>
#define ISINT(x) !(fabs((x) - std::nearbyint(x)) > 1e-7)
// double lfastchoose(double n, double k)
// {
// double tmp = log(boost::math::beta(n - k + 1., k + 1.));
// return -log(n + 1.) - tmp;
// }
/* mathematically the same:
less stable typically, but useful if n-k+1 < 0 : */
static
double lfastchoose2(double n, double k)
{
double r;
r = lgamma(n - k + 1.);
return std::lgamma(n + 1.) - std::lgamma(k + 1.) - r;
}
double lbeta_cpp(double a, double b)
{
double r;
r = std::lgamma(a+b);
return std::lgamma(a) + std::lgamma(b) - r;
}
double lchoose_cpp(double n, double k)
{
double k0 = k;
k = nearbyint(k);
/* NaNs propagated correctly */
static_assert(std::numeric_limits<double>::is_iec559, "IEEE 754 required");
if(isnan(n) || isnan(k)) return n + k;
if (fabs(k - k0) > 1e-7)
// std::cout<<"'k' "<<k0<<" must be integer, rounded to "<<k;
if (k < 2) {
if (k < 0) return -std::numeric_limits<double>::infinity();
if (k == 0) return 0.;
/* else: k == 1 */
return log(fabs(n));
}
/* else: k >= 2 */
if (n < 0) {
return lchoose_cpp(-n+ k-1, k);
}
else if (ISINT(n)) {
n = std::nearbyint(n);
if(n < k) return -std::numeric_limits<double>::infinity();
/* k <= n :*/
if(n - k < 2) return lchoose_cpp(n, n-k); /* <- Symmetry */
/* else: n >= k+2 */
return lfastchoose2(n, k);
}
/* else non-integer n >= 0 : */
if (n < k-1) {
return lfastchoose2(n, k);
}
return lfastchoose2(n, k);
}
<|endoftext|>
|
<commit_before>/**
* A program performing detection of obstacles in the given file feed
* and visualizing their approximations.
*/
#include <iostream>
#include <pcl/io/openni2_grabber.h>
#include <pcl/io/pcd_grabber.h>
#include "lepp2/BaseObstacleDetector.hpp"
#include "lepp2/GrabberVideoSource.hpp"
#include "lepp2/BaseVideoSource.hpp"
#include "lepp2/VideoObserver.hpp"
#include "lepp2/FilteredVideoSource.hpp"
#include "lepp2/SmoothObstacleAggregator.hpp"
#include "lepp2/visualization/EchoObserver.hpp"
#include "lepp2/visualization/ObstacleVisualizer.hpp"
#include "lepp2/filter/TruncateFilter.hpp"
#include "lepp2/filter/SensorCalibrationFilter.hpp"
#include "lola/OdoCoordinateTransformer.hpp"
#include "lola/LolaAggregator.h"
#include "lola/PoseService.h"
#include "lola/RobotService.h"
using namespace lepp;
/**
* Prints out the expected CLI usage of the program.
*/
void PrintUsage() {
std::cout << "usage: detector [--pcd file | --oni file | --stream] [--live]"
<< std::endl;
std::cout << "--pcd : " << "read the input from a .pcd file" << std::endl;
std::cout << "--oni : " << "read the input from an .oni file" << std::endl;
std::cout << "--stream : " << "read the input from a live stream based on a"
<< " sensor attached to the computer" << std::endl;
std::cout << "--live : " << "whether kinematics data is obtained from the robot"
<< std::endl;
}
/**
* Builds a `FilteredVideoSource` instance that wraps the given raw source.
*/
template<class PointT>
boost::shared_ptr<FilteredVideoSource<PointT> >
buildFilteredSource(boost::shared_ptr<VideoSource<PointT> > raw, bool live) {
// Wrap the given raw source.
boost::shared_ptr<FilteredVideoSource<SimplePoint> > source(
new SimpleFilteredVideoSource<SimplePoint>(raw));
// Now set the point filters that should be used.
{
double const a = 1.0117;
double const b = -0.0100851;
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new SensorCalibrationFilter<SimplePoint>(a, b));
source->addFilter(filter);
}
if (!live) {
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new FileOdoTransformer<SimplePoint>("in.log"));
source->addFilter(filter);
} else {
// TODO The reference to the service should eventually be obtained from some
// sort of IOC container.
boost::shared_ptr<PoseService> service(new PoseService("127.0.0.1", 5000));
service->start();
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new RobotOdoTransformer<SimplePoint>(service));
source->addFilter(filter);
}
{
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new TruncateFilter<SimplePoint>(2));
source->addFilter(filter);
}
return source;
}
/**
* Parses the command line arguments received by the program and chooses
* the appropriate video source based on those.
*/
boost::shared_ptr<SimpleVideoSource> GetVideoSource(int argc, char* argv[]) {
if (argc < 2) {
return boost::shared_ptr<SimpleVideoSource>();
}
std::string const option = argv[1];
if (option == "--stream") {
return boost::shared_ptr<SimpleVideoSource>(
new LiveStreamSource<SimplePoint>());
} else if (option == "--pcd" && argc >= 3) {
std::string const file_path = argv[2];
boost::shared_ptr<pcl::Grabber> interface(new pcl::PCDGrabber<SimplePoint>(
file_path,
20.,
true));
return boost::shared_ptr<SimpleVideoSource>(
new GeneralGrabberVideoSource<SimplePoint>(interface));
} else if (option == "--oni" && argc >= 3) {
std::string const file_path = argv[2];
boost::shared_ptr<pcl::Grabber> interface(new pcl::io::OpenNI2Grabber(
file_path,
pcl::io::OpenNI2Grabber::OpenNI_Default_Mode,
pcl::io::OpenNI2Grabber::OpenNI_Default_Mode));
return boost::shared_ptr<SimpleVideoSource>(
new GeneralGrabberVideoSource<SimplePoint>(interface));
}
// Unknown option: return a "null" pointer.
return boost::shared_ptr<SimpleVideoSource>();
}
/**
* Checks whether the CLI parameters indicate that the detector should run with
* a live robot.
*
* This is true iff a `--live` flag was passed to the executable.
*/
bool isLive(int argc, char* argv[]) {
for (int i = 0; i < argc; ++i) {
if (std::string(argv[i]) == "--live") return true;
}
return false;
}
int main(int argc, char* argv[]) {
// Obtain a video source based on the command line arguments received
boost::shared_ptr<SimpleVideoSource> raw_source(GetVideoSource(argc, argv));
if (!raw_source) {
PrintUsage();
return 1;
}
bool live = isLive(argc, argv);
// Wrap the raw source in a filter
boost::shared_ptr<FilteredVideoSource<SimplePoint> > source(
buildFilteredSource(raw_source, live));
// Prepare the detector
boost::shared_ptr<BaseObstacleDetector<SimplePoint> > detector(
new BaseObstacleDetector<SimplePoint>());
// Attaching the detector to the source: process the point clouds obtained
// by the source.
source->attachObserver(detector);
// Prepare the result visualizer...
boost::shared_ptr<ObstacleVisualizer<SimplePoint> > visualizer(
new ObstacleVisualizer<SimplePoint>());
// Attaching the visualizer to the source: allow it to display the original
// point cloud.
source->attachObserver(visualizer);
// Attach the obstacle postprocessor.
boost::shared_ptr<SmoothObstacleAggregator> smooth_decorator(
new SmoothObstacleAggregator);
detector->attachObstacleAggregator(smooth_decorator);
// Now attach various aggregators that are only interested in postprocessed
// obstacles.
boost::shared_ptr<LolaAggregator> lola(
new LolaAggregator("127.0.0.1", 53250));
smooth_decorator->attachObstacleAggregator(lola);
smooth_decorator->attachObstacleAggregator(visualizer);
AsyncRobotService robot_service("127.0.0.1", 1337, 10);
robot_service.start();
boost::shared_ptr<RobotAggregator> robot(new RobotAggregator(robot_service, 10));
smooth_decorator->attachObstacleAggregator(robot);
// Starts capturing new frames and forwarding them to attached observers.
source->open();
std::cout << "Waiting forever..." << std::endl;
std::cout << "(^C to exit)" << std::endl;
while (true)
boost::this_thread::sleep(boost::posix_time::milliseconds(8000));
return 0;
}
<commit_msg>LOLA: Fix usage output<commit_after>/**
* A program performing detection of obstacles in the given file feed
* and visualizing their approximations.
*/
#include <iostream>
#include <pcl/io/openni2_grabber.h>
#include <pcl/io/pcd_grabber.h>
#include "lepp2/BaseObstacleDetector.hpp"
#include "lepp2/GrabberVideoSource.hpp"
#include "lepp2/BaseVideoSource.hpp"
#include "lepp2/VideoObserver.hpp"
#include "lepp2/FilteredVideoSource.hpp"
#include "lepp2/SmoothObstacleAggregator.hpp"
#include "lepp2/visualization/EchoObserver.hpp"
#include "lepp2/visualization/ObstacleVisualizer.hpp"
#include "lepp2/filter/TruncateFilter.hpp"
#include "lepp2/filter/SensorCalibrationFilter.hpp"
#include "lola/OdoCoordinateTransformer.hpp"
#include "lola/LolaAggregator.h"
#include "lola/PoseService.h"
#include "lola/RobotService.h"
using namespace lepp;
/**
* Prints out the expected CLI usage of the program.
*/
void PrintUsage() {
std::cout << "usage: lola [--pcd file | --oni file | --stream] [--live]"
<< std::endl;
std::cout << "--pcd : " << "read the input from a .pcd file" << std::endl;
std::cout << "--oni : " << "read the input from an .oni file" << std::endl;
std::cout << "--stream : " << "read the input from a live stream based on a"
<< " sensor attached to the computer" << std::endl;
std::cout << "--live : " << "whether kinematics data is obtained from the robot"
<< std::endl;
}
/**
* Builds a `FilteredVideoSource` instance that wraps the given raw source.
*/
template<class PointT>
boost::shared_ptr<FilteredVideoSource<PointT> >
buildFilteredSource(boost::shared_ptr<VideoSource<PointT> > raw, bool live) {
// Wrap the given raw source.
boost::shared_ptr<FilteredVideoSource<SimplePoint> > source(
new SimpleFilteredVideoSource<SimplePoint>(raw));
// Now set the point filters that should be used.
{
double const a = 1.0117;
double const b = -0.0100851;
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new SensorCalibrationFilter<SimplePoint>(a, b));
source->addFilter(filter);
}
if (!live) {
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new FileOdoTransformer<SimplePoint>("in.log"));
source->addFilter(filter);
} else {
// TODO The reference to the service should eventually be obtained from some
// sort of IOC container.
boost::shared_ptr<PoseService> service(new PoseService("127.0.0.1", 5000));
service->start();
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new RobotOdoTransformer<SimplePoint>(service));
source->addFilter(filter);
}
{
boost::shared_ptr<PointFilter<SimplePoint> > filter(
new TruncateFilter<SimplePoint>(2));
source->addFilter(filter);
}
return source;
}
/**
* Parses the command line arguments received by the program and chooses
* the appropriate video source based on those.
*/
boost::shared_ptr<SimpleVideoSource> GetVideoSource(int argc, char* argv[]) {
if (argc < 2) {
return boost::shared_ptr<SimpleVideoSource>();
}
std::string const option = argv[1];
if (option == "--stream") {
return boost::shared_ptr<SimpleVideoSource>(
new LiveStreamSource<SimplePoint>());
} else if (option == "--pcd" && argc >= 3) {
std::string const file_path = argv[2];
boost::shared_ptr<pcl::Grabber> interface(new pcl::PCDGrabber<SimplePoint>(
file_path,
20.,
true));
return boost::shared_ptr<SimpleVideoSource>(
new GeneralGrabberVideoSource<SimplePoint>(interface));
} else if (option == "--oni" && argc >= 3) {
std::string const file_path = argv[2];
boost::shared_ptr<pcl::Grabber> interface(new pcl::io::OpenNI2Grabber(
file_path,
pcl::io::OpenNI2Grabber::OpenNI_Default_Mode,
pcl::io::OpenNI2Grabber::OpenNI_Default_Mode));
return boost::shared_ptr<SimpleVideoSource>(
new GeneralGrabberVideoSource<SimplePoint>(interface));
}
// Unknown option: return a "null" pointer.
return boost::shared_ptr<SimpleVideoSource>();
}
/**
* Checks whether the CLI parameters indicate that the detector should run with
* a live robot.
*
* This is true iff a `--live` flag was passed to the executable.
*/
bool isLive(int argc, char* argv[]) {
for (int i = 0; i < argc; ++i) {
if (std::string(argv[i]) == "--live") return true;
}
return false;
}
int main(int argc, char* argv[]) {
// Obtain a video source based on the command line arguments received
boost::shared_ptr<SimpleVideoSource> raw_source(GetVideoSource(argc, argv));
if (!raw_source) {
PrintUsage();
return 1;
}
bool live = isLive(argc, argv);
// Wrap the raw source in a filter
boost::shared_ptr<FilteredVideoSource<SimplePoint> > source(
buildFilteredSource(raw_source, live));
// Prepare the detector
boost::shared_ptr<BaseObstacleDetector<SimplePoint> > detector(
new BaseObstacleDetector<SimplePoint>());
// Attaching the detector to the source: process the point clouds obtained
// by the source.
source->attachObserver(detector);
// Prepare the result visualizer...
boost::shared_ptr<ObstacleVisualizer<SimplePoint> > visualizer(
new ObstacleVisualizer<SimplePoint>());
// Attaching the visualizer to the source: allow it to display the original
// point cloud.
source->attachObserver(visualizer);
// Attach the obstacle postprocessor.
boost::shared_ptr<SmoothObstacleAggregator> smooth_decorator(
new SmoothObstacleAggregator);
detector->attachObstacleAggregator(smooth_decorator);
// Now attach various aggregators that are only interested in postprocessed
// obstacles.
boost::shared_ptr<LolaAggregator> lola(
new LolaAggregator("127.0.0.1", 53250));
smooth_decorator->attachObstacleAggregator(lola);
smooth_decorator->attachObstacleAggregator(visualizer);
AsyncRobotService robot_service("127.0.0.1", 1337, 10);
robot_service.start();
boost::shared_ptr<RobotAggregator> robot(new RobotAggregator(robot_service, 10));
smooth_decorator->attachObstacleAggregator(robot);
// Starts capturing new frames and forwarding them to attached observers.
source->open();
std::cout << "Waiting forever..." << std::endl;
std::cout << "(^C to exit)" << std::endl;
while (true)
boost::this_thread::sleep(boost::posix_time::milliseconds(8000));
return 0;
}
<|endoftext|>
|
<commit_before>#include "machine.h"
void Machine::set_id(int i){
id = i;
}
void Machine::set_start(int i){
stopt = i;
}
void Machine::set_stop(int i){
startt = i;
}
int Machine::get_id(){
return id;
}
int Machine::get_srt(){
return startt;
}
int Machine::get_sop(){
return stopt;
}
bool Machine::add(int task_id, vector<Task> task_v, vector<Maitenance> maitenance_v){
if (id == 1){ //machine 1
Task_t new_task(task_v[task_id].get_id());
for (vector<Maitenance>::size_type i = 0; i < maitenance_v.size() ; i++ ){
if (stopt == maitenance_v[i].get_mt()){
stopt += maitenance_v[i].get_opt();
new_task.set_op_stime(stopt);
}
}
if (stopt < task_v[task_id].get_rt()){
return false;
}
for(vector<Maitenance>::size_type i = 0; i < maitenance_v.size(); i++){
if(stopt < maitenance_v[i].get_mt() &&
(stopt + task_v[task_id].get_op_time(1))>maitenance_v[i].get_mt()){
new_task.punishit(task_v[i].get_op_time(1));
if(task_v[i].get_op_time(1) % 5 == 0){
new_task.punish();
}
new_task.set_op_stime(stopt);
stopt += maitenance_v[i].get_opt();
}
}
mtasks_v.push_back(new_task);
stopt += task_v[task_id].get_op_time(1)+new_task.get_punish();
}else{ // machine 2
Task_t new_task(task_v[task_id].get_id());
new_task.set_op_stime(stopt);
mtasks_v.push_back(new_task);
stopt += task_v[task_id].get_op_time(2);
}
return true;
}
void Machine::addt(int t, int task_id, vector<Task> task_v){
if (id == 2){
Task_t new_task(task_v[task_id].get_id());
new_task.set_op_stime(stopt);
mtasks_v.push_back(new_task);
stopt += t + task_v[task_id].get_op_time(2);
}
}<commit_msg>fixed set_start and set_stop methods<commit_after>#include "machine.h"
void Machine::set_id(int i){
id = i;
}
void Machine::set_start(int i){
startt = i;
}
void Machine::set_stop(int i){
stopt = i;
}
int Machine::get_id(){
return id;
}
int Machine::get_srt(){
return startt;
}
int Machine::get_sop(){
return stopt;
}
bool Machine::add(int task_id, vector<Task> task_v, vector<Maitenance> maitenance_v){
if (id == 1){ //machine 1
Task_t new_task(task_v[task_id].get_id());
for (vector<Maitenance>::size_type i = 0; i < maitenance_v.size() ; i++ ){
if (stopt == maitenance_v[i].get_mt()){
stopt += maitenance_v[i].get_opt();
new_task.set_op_stime(stopt);
}
}
if (stopt < task_v[task_id].get_rt()){
return false;
}
for(vector<Maitenance>::size_type i = 0; i < maitenance_v.size(); i++){
if(stopt < maitenance_v[i].get_mt() &&
(stopt + task_v[task_id].get_op_time(1))>maitenance_v[i].get_mt()){
new_task.punishit(task_v[i].get_op_time(1));
if(task_v[i].get_op_time(1) % 5 == 0){
new_task.punish();
}
new_task.set_op_stime(stopt);
stopt += maitenance_v[i].get_opt();
}
}
mtasks_v.push_back(new_task);
stopt += task_v[task_id].get_op_time(1)+new_task.get_punish();
}else{ // machine 2
Task_t new_task(task_v[task_id].get_id());
new_task.set_op_stime(stopt);
mtasks_v.push_back(new_task);
stopt += task_v[task_id].get_op_time(2);
}
return true;
}
void Machine::addt(int t, int task_id, vector<Task> task_v){
if (id == 2){
Task_t new_task(task_v[task_id].get_id());
new_task.set_op_stime(stopt);
mtasks_v.push_back(new_task);
stopt += t + task_v[task_id].get_op_time(2);
}
}
<|endoftext|>
|
<commit_before>/*
* Source MUD
* Copyright (C) 2000-2005 Sean Middleditch
* See the file COPYING for license details
* http://www.sourcemud.org
*/
#include "common.h"
#include "common/mail.h"
#include "common/log.h"
#include "mud/settings.h"
#ifdef HAVE_SENDMAIL
void MailMessage::append(const std::string& data)
{
body << data;
}
void MailMessage::header(const std::string& name, const std::string& value)
{
Header h;
h.name = name;
h.value = value;
headers.push_back(h);
}
int MailMessage::send() const
{
// sanity
if (!to || !subject) {
Log::Error << "Attempt to send a message without both a recipient and a subject.";
return -1;
}
// configuration
std::string sendmail = MSettings.get_sendmail_bin();
if (!sendmail) {
Log::Error << "No sendmail binary configured";
return -1;
}
// pipes
int files[2];
if (pipe(files)) {
Log::Error << "pipe() failed: " << strerror(errno);
return -1;
}
// fork
pid_t pid;
if ((pid = fork()) == 0) {
// file handles - erg
close(files[1]);
close(0); // stdin
close(1); // stdout
close(2); // stderr
dup2(files[0], 0);
// exec sendmail
if (execl(sendmail.c_str(), sendmail.c_str(), "-oi", "-t", "-FSource MUD", NULL))
exit(1);
}
close(files[0]);
// failure on fork
if (pid < 0) {
Log::Error << "fork() failed: " << strerror(errno);
return -1;
}
// write out data
FILE* fout = fdopen(files[1], "w");
if (fout == NULL) {
Log::Error << "fdopen() failed: " << strerror(errno);
// wait for child
do {
waitpid(pid, NULL, WNOHANG);
} while (errno == EINTR);
return -1;
}
// print
fprintf(fout, "Subject: %s\n", subject.c_str());
fprintf(fout, "To: %s\n", to.c_str());
fprintf(fout, "X-Source MUD: YES\n");
for (std::vector<Header>::const_iterator i = headers.begin(); i != headers.end(); ++i)
fprintf(fout, "%s: %s\n", i->name.c_str(), i->value.c_str());
fprintf(fout, "\n%s\n", body.c_str());
fclose(fout);
// wait for child
do {
waitpid(pid, NULL, WNOHANG);
} while (errno == EINTR);
return 0;
}
#endif // HAVE_SENDMAIL
<commit_msg>fix compilation<commit_after>/*
* Source MUD
* Copyright (C) 2000-2005 Sean Middleditch
* See the file COPYING for license details
* http://www.sourcemud.org
*/
#include "common.h"
#include "common/mail.h"
#include "common/log.h"
#include "mud/settings.h"
#ifdef HAVE_SENDMAIL
void MailMessage::append(const std::string& data)
{
body << data;
}
void MailMessage::header(const std::string& name, const std::string& value)
{
Header h;
h.name = name;
h.value = value;
headers.push_back(h);
}
int MailMessage::send() const
{
// sanity
if (to.empty() || subject.empty()) {
Log::Error << "Attempt to send a message without both a recipient and a subject.";
return -1;
}
// configuration
std::string sendmail = MSettings.get_sendmail_bin();
if (sendmail.empty()) {
Log::Error << "No sendmail binary configured";
return -1;
}
// pipes
int files[2];
if (pipe(files)) {
Log::Error << "pipe() failed: " << strerror(errno);
return -1;
}
// fork
pid_t pid;
if ((pid = fork()) == 0) {
// file handles - erg
close(files[1]);
close(0); // stdin
close(1); // stdout
close(2); // stderr
dup2(files[0], 0);
// exec sendmail
if (execl(sendmail.c_str(), sendmail.c_str(), "-oi", "-t", "-FSource MUD", NULL))
exit(1);
}
close(files[0]);
// failure on fork
if (pid < 0) {
Log::Error << "fork() failed: " << strerror(errno);
return -1;
}
// write out data
FILE* fout = fdopen(files[1], "w");
if (fout == NULL) {
Log::Error << "fdopen() failed: " << strerror(errno);
// wait for child
do {
waitpid(pid, NULL, WNOHANG);
} while (errno == EINTR);
return -1;
}
// print
fprintf(fout, "Subject: %s\n", subject.c_str());
fprintf(fout, "To: %s\n", to.c_str());
fprintf(fout, "X-Source MUD: YES\n");
for (std::vector<Header>::const_iterator i = headers.begin(); i != headers.end(); ++i)
fprintf(fout, "%s: %s\n", i->name.c_str(), i->value.c_str());
fprintf(fout, "\n%s\n", body.c_str());
fclose(fout);
// wait for child
do {
waitpid(pid, NULL, WNOHANG);
} while (errno == EINTR);
return 0;
}
#endif // HAVE_SENDMAIL
<|endoftext|>
|
<commit_before>/*
* Source MUD
* Copyright (C) 2000-2005 Sean Middleditch
* See the file COPYING for license details
* http://www.sourcemud.org
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <ctype.h>
#include <netdb.h>
#include <fcntl.h>
#include "common/log.h"
#include "net/socket.h"
#include "net/util.h"
#include <vector>
#include "config.h"
/********************
* Misc Helper Code *
********************/
// apply mask to an IP address
// math/algorithm found in FreeBSD 'route' command - thanks guys!
namespace {
void
addr_apply_mask (uint8* addr, uint size, uint mask)
{
assert(mask <= size * 8);
// buffer to hold mask
uint8 maskbuf[size];
memset(maskbuf, 0, size);
// number of whole bytes
uint q = mask >> 3;
if (q > 0) memset(maskbuf, 0xff, q);
// remainder bytes
uint r = mask & 7;
if (r > 0) *(maskbuf + q) = (0xff00 >> r) & 0xff;
// apply to addr
for (uint i = 0; i < size; ++i)
addr[i] &= maskbuf[i];
}
}
// compare addresses
int
Network::addrcmp (const SockStorage& addr1, const SockStorage& addr2)
{
// same family, yes?
if (addr1.ss_family != addr2.ss_family)
return -1;
switch (addr1.ss_family) {
/* IPv4 */
case AF_INET: {
const sockaddr_in* sin1 = (sockaddr_in*)&addr1;
const sockaddr_in* sin2 = (sockaddr_in*)&addr2;
return *(uint32*)&sin1->sin_addr != *(uint32*)&sin2->sin_addr;
}
/* IPv6 */
#ifdef HAVE_IPV6
case AF_INET6: {
const sockaddr_in6* sin1 = (sockaddr_in6*)&addr1;
const sockaddr_in6* sin2 = (sockaddr_in6*)&addr2;
return !IN6_ARE_ADDR_EQUAL(&sin1->sin6_addr, &sin2->sin6_addr);
}
#endif
/* Unknown */
default:
return -1;
}
}
// compare addresses - with mask applied to *first* address (only)
int
Network::addrcmp_mask (const SockStorage& in_addr1, const SockStorage& addr2, uint mask)
{
// same family, yes?
if (in_addr1.ss_family != addr2.ss_family)
return -1;
SockStorage addr1 = in_addr1;
switch (addr1.ss_family) {
/* IPv4 */
case AF_INET: {
sockaddr_in sin1 = *(sockaddr_in*)&addr1;
const sockaddr_in sin2 = *(sockaddr_in*)&addr2;
addr_apply_mask((uint8*)&sin1.sin_addr, sizeof(sin1.sin_addr), mask);
return memcmp(&sin1.sin_addr, &sin2.sin_addr, sizeof(sin1.sin_addr));
}
/* IPv6 */
#ifdef HAVE_IPV6
case AF_INET6: {
sockaddr_in6 sin1 = *(sockaddr_in6*)&addr1;
const sockaddr_in6 sin2 = *(sockaddr_in6*)&addr2;
addr_apply_mask((uint8*)&sin1.sin6_addr, sizeof(sin1.sin6_addr), mask);
return !IN6_ARE_ADDR_EQUAL(&sin1.sin6_addr, &sin2.sin6_addr);
}
#endif
/* Unknown */
default:
return -1;
}
}
// get name of socket
std::string
Network::get_addr_name(const SockStorage& addr)
{
char hostbuf[512];
char servbuf[512];
char buffer[512];
// get the info
#if HAVE_GETNAMEINFO
getnameinfo((sockaddr*)&addr, sizeof(addr), hostbuf, sizeof(hostbuf), servbuf, sizeof(servbuf), NI_NUMERICHOST | NI_NUMERICSERV);
#elif defined(HAVE_INET_PTON)
struct sockaddr_in* sin = (struct sockaddr_in*)&addr;
inet_ntop(AF_INET, &sin->sin_addr, hostbuf, sizeof(hostbuf));
snprintf(servbuf, sizeof(servbuf), "%d", ntohs(sin->sin_port));
#else
return "<unknown>";
#endif
// no port? just return the address
if (!strlen(servbuf))
return std::string(hostbuf);
// host have a : (*cough* IPv6 *cough*) ? format [addr]:port
if (strchr(hostbuf, ':'))
snprintf(buffer, sizeof(buffer), "[%s]:%s", hostbuf, servbuf);
else
snprintf(buffer, sizeof(buffer), "%s:%s", hostbuf, servbuf);
return std::string(buffer);
}
// get peer uid on AF_UNIX sockets
int
Network::get_peer_uid (int sock, uid_t& uid)
{
#if defined(HAVE_GETPEEREID)
// use getpeereid
uid_t gid;
if (getpeereid(sock, &uid, &gid) != 0) {
Log::Error << "getpeereid() failed: " << strerror(errno);
return errno;
}
return 0;
#elif defined(SO_PEERCRED)
// use Linux SO_PEERCRED getsockopt ability
struct ucred peercred;
socklen_t cred_len = sizeof(peercred);
if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &cred_len)) {
Log::Error << "getsockopt() failed: " << strerror(errno);
return errno;
}
uid = peercred.uid;
return 0;
#else
// not supported - fail
return EOPNOTSUPP;
#endif
}
// listen/server connection
int
Network::listen_tcp (int port, int family)
{
SockStorage ss;
size_t ss_len = sizeof(ss);
int i_opt;
int sock;
#ifdef HAVE_IPV6
assert(family == AF_INET6 || family == AF_INET);
#else
assert(family == AF_INET);
#endif // HAVE_IPV6
// create socket
if ((sock = socket(family, SOCK_STREAM, 0)) < 0) {
Log::Error << "socket() failed: " << strerror(errno);
return errno;
}
// set reuse timeout thingy
i_opt = 1;
setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &i_opt, sizeof (i_opt));
// setup and config
#ifdef HAVE_IPV6
if (family == AF_INET6) {
// IPv6
ss_len = sizeof(sockaddr_in6);
ss.ss_family = AF_INET6;
((sockaddr_in6*)&ss)->sin6_port = htons (port);
memset (&((sockaddr_in6*)&ss)->sin6_addr, 0, sizeof (((sockaddr_in6*)&ss)->sin6_addr));
#ifdef IPV6_V6ONLY
// set IPV6-only
i_opt = 1;
setsockopt (sock, SOL_SOCKET, IPV6_V6ONLY, &i_opt, sizeof (i_opt));
#endif
} else
#endif // HAVE_IPV6
if (family == AF_INET) {
// IPv4
ss_len = sizeof(sockaddr_in);
ss.ss_family = AF_INET;
((sockaddr_in*)&ss)->sin_port = htons (port);
memset (&((sockaddr_in*)&ss)->sin_addr, 0, sizeof (((sockaddr_in*)&ss)->sin_addr));
}
// bind socket
if (bind (sock, (struct sockaddr *)&ss, ss_len) == -1) {
Log::Error << "bind() failed: " << strerror(errno);
close(sock);
return -1;;
}
// start listening
if (::listen (sock, 5)) {
Log::Error << "listen() failed: " << strerror(errno);
close(sock);
return -1;
}
return sock;
}
// accept incoming connections
int
Network::accept_tcp (int sock, SockStorage& addr)
{
// accept socket
socklen_t sslen = sizeof(addr);
int client = accept(sock, (struct sockaddr*)&addr, &sslen);
if (client == -1)
return -1;
// set non-blocking flag
fcntl(client, F_SETFL, O_NONBLOCK);
return client;
}
// true if address is local
bool
Network::is_addr_local (const SockStorage& addr)
{
if (addr.ss_family == AF_INET) {
if (((const sockaddr_in*)&addr)->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
return true;
}
#ifdef HAVE_IPV6
else if (addr.ss_family == AF_INET6) {
if (IN6_IS_ADDR_LOOPBACK(&((const sockaddr_in6*)&addr)->sin6_addr))
return true;
}
#endif // HAVE_IPV6
return false;
}
// listen/server connection
int
Network::listen_unix (std::string s_path)
{
struct sockaddr_un address;
size_t sa_len = sizeof(address);
int sock;
mode_t mode;
// path too long?
if (s_path.size() >= sizeof(address.sun_path)) {
Log::Error << "UNIX socket path '" << s_path << " is too long (>" << sizeof(address.sun_path) << ")";
return -1;
}
// create socket
if ((sock = socket (PF_UNIX, SOCK_STREAM, 0)) < 0) {
Log::Error << "socket() failed: " << strerror(errno);
return -1;
}
// unlink previous socket
unlink(s_path.c_str());
// setup and config
address.sun_family = AF_UNIX;
snprintf(address.sun_path, sizeof(address.sun_path), "%s", s_path.c_str());
sa_len = sizeof(address.sun_family) + strlen(address.sun_path) + 1;
// bind socket
mode = umask(077);
if (bind (sock, (struct sockaddr *)&address, sa_len) == -1) {
Log::Error << "bind() failed: " << strerror(errno);
umask(mode);
close(sock);
return -1;
}
umask(mode);
// start listening
if (::listen (sock, 5)) {
Log::Error << "listen() failed: " << strerror(errno);
unlink(s_path.c_str());
close(sock);
return -1;
}
return sock;
}
// accept incoming connections
int
Network::accept_unix (int sock, uid_t& uid)
{
// do accept
struct sockaddr_un address;
socklen_t sslen = sizeof(address);
int client = accept(sock, (struct sockaddr*)&address, (socklen_t*)&sslen);
if (client == -1)
return -1;
// get peer UID
uid = 0;
if (get_peer_uid(client, uid)) {
close(client);
return -1;
}
// set non-blocking flag
fcntl(client, F_SETFL, O_NONBLOCK);
return client;
}
int Network::parse_addr(const char* item, SockStorage* host, uint* mask)
{
char buffer[128];
// put in buffer, snprintf() guarnatees NUL byte
snprintf (buffer, sizeof(buffer), "%s", item);
// get mask - have we a mask?
int inmask = -1;
char* slash = strchr(buffer, '/');
if (slash != NULL) {
*slash = '\0';
++ slash;
// don't use atoi or strtol, guarantee we parse it right
inmask = 0;
while (*slash != '\0') {
if (!isdigit(*slash))
break;
inmask *= 10;
inmask += *slash - '0';
++ slash;
}
// only numbers, rights?
if (*slash != '\0')
return -1; // FAIL
}
// parse address
SockStorage ss;
#ifdef HAVE_IPV6
// try IPv6 first
if (inet_pton(AF_INET6, buffer, &((sockaddr_in6*)&ss)->sin6_addr) > 0) { // match
// check mask
if (inmask > 128)
return -1; // FAIL
else if (inmask < 0)
inmask = 128;
addr_apply_mask((uint8*)&((sockaddr_in6*)&ss)->sin6_addr, 16, inmask);
ss.ss_family = AF_INET6;
*host = SockStorage(ss);
*mask = inmask;
return 0;
} else
#endif // HAVE_IPV6
// try IPv4 parsing
#ifdef HAVE_INET_PTON
if (inet_pton(AF_INET, buffer, &((sockaddr_in*)&ss)->sin_addr) > 0) { // match
// check mask
if (inmask > 32)
return -1; // FAIL
else if (inmask < 0)
inmask = 32;
addr_apply_mask((uint8*)&((sockaddr_in*)&ss)->sin_addr, 4, inmask);
ss.ss_family = AF_INET;
*host = SockStorage(ss);
*mask = inmask;
return 0;
#else // HAVE_INET_PTON
if (inet_aton(buffer, &((sockaddr_in*)&ss)->sin_addr) != 0) { // match
// check mask
if (inmask > 32)
return -1; // FAIL
else if (inmask < 0)
inmask = 32;
addr_apply_mask((uint8*)&((sockaddr_in*)&ss)->sin_addr, 4, inmask);
ss.ss_family = AF_INET;
*host = SockStorage(ss);
*mask = inmask;
return 0;
#endif
} else {
// no match
return -1; // FAIL
}
}
<commit_msg>memset ealier<commit_after>/*
* Source MUD
* Copyright (C) 2000-2005 Sean Middleditch
* See the file COPYING for license details
* http://www.sourcemud.org
*/
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <ctype.h>
#include <netdb.h>
#include <fcntl.h>
#include "common/log.h"
#include "net/socket.h"
#include "net/util.h"
#include <vector>
#include "config.h"
/********************
* Misc Helper Code *
********************/
// apply mask to an IP address
// math/algorithm found in FreeBSD 'route' command - thanks guys!
namespace {
void
addr_apply_mask (uint8* addr, uint size, uint mask)
{
assert(mask <= size * 8);
// buffer to hold mask
uint8 maskbuf[size];
memset(maskbuf, 0, size);
// number of whole bytes
uint q = mask >> 3;
if (q > 0) memset(maskbuf, 0xff, q);
// remainder bytes
uint r = mask & 7;
if (r > 0) *(maskbuf + q) = (0xff00 >> r) & 0xff;
// apply to addr
for (uint i = 0; i < size; ++i)
addr[i] &= maskbuf[i];
}
}
// compare addresses
int
Network::addrcmp (const SockStorage& addr1, const SockStorage& addr2)
{
// same family, yes?
if (addr1.ss_family != addr2.ss_family)
return -1;
switch (addr1.ss_family) {
/* IPv4 */
case AF_INET: {
const sockaddr_in* sin1 = (sockaddr_in*)&addr1;
const sockaddr_in* sin2 = (sockaddr_in*)&addr2;
return *(uint32*)&sin1->sin_addr != *(uint32*)&sin2->sin_addr;
}
/* IPv6 */
#ifdef HAVE_IPV6
case AF_INET6: {
const sockaddr_in6* sin1 = (sockaddr_in6*)&addr1;
const sockaddr_in6* sin2 = (sockaddr_in6*)&addr2;
return !IN6_ARE_ADDR_EQUAL(&sin1->sin6_addr, &sin2->sin6_addr);
}
#endif
/* Unknown */
default:
return -1;
}
}
// compare addresses - with mask applied to *first* address (only)
int
Network::addrcmp_mask (const SockStorage& in_addr1, const SockStorage& addr2, uint mask)
{
// same family, yes?
if (in_addr1.ss_family != addr2.ss_family)
return -1;
SockStorage addr1 = in_addr1;
switch (addr1.ss_family) {
/* IPv4 */
case AF_INET: {
sockaddr_in sin1 = *(sockaddr_in*)&addr1;
const sockaddr_in sin2 = *(sockaddr_in*)&addr2;
addr_apply_mask((uint8*)&sin1.sin_addr, sizeof(sin1.sin_addr), mask);
return memcmp(&sin1.sin_addr, &sin2.sin_addr, sizeof(sin1.sin_addr));
}
/* IPv6 */
#ifdef HAVE_IPV6
case AF_INET6: {
sockaddr_in6 sin1 = *(sockaddr_in6*)&addr1;
const sockaddr_in6 sin2 = *(sockaddr_in6*)&addr2;
addr_apply_mask((uint8*)&sin1.sin6_addr, sizeof(sin1.sin6_addr), mask);
return !IN6_ARE_ADDR_EQUAL(&sin1.sin6_addr, &sin2.sin6_addr);
}
#endif
/* Unknown */
default:
return -1;
}
}
// get name of socket
std::string
Network::get_addr_name(const SockStorage& addr)
{
char hostbuf[512];
char servbuf[512];
char buffer[512];
// get the info
#if HAVE_GETNAMEINFO
getnameinfo((sockaddr*)&addr, sizeof(addr), hostbuf, sizeof(hostbuf), servbuf, sizeof(servbuf), NI_NUMERICHOST | NI_NUMERICSERV);
#elif defined(HAVE_INET_PTON)
struct sockaddr_in* sin = (struct sockaddr_in*)&addr;
inet_ntop(AF_INET, &sin->sin_addr, hostbuf, sizeof(hostbuf));
snprintf(servbuf, sizeof(servbuf), "%d", ntohs(sin->sin_port));
#else
return "<unknown>";
#endif
// no port? just return the address
if (!strlen(servbuf))
return std::string(hostbuf);
// host have a : (*cough* IPv6 *cough*) ? format [addr]:port
if (strchr(hostbuf, ':'))
snprintf(buffer, sizeof(buffer), "[%s]:%s", hostbuf, servbuf);
else
snprintf(buffer, sizeof(buffer), "%s:%s", hostbuf, servbuf);
return std::string(buffer);
}
// get peer uid on AF_UNIX sockets
int
Network::get_peer_uid (int sock, uid_t& uid)
{
#if defined(HAVE_GETPEEREID)
// use getpeereid
uid_t gid;
if (getpeereid(sock, &uid, &gid) != 0) {
Log::Error << "getpeereid() failed: " << strerror(errno);
return errno;
}
return 0;
#elif defined(SO_PEERCRED)
// use Linux SO_PEERCRED getsockopt ability
struct ucred peercred;
socklen_t cred_len = sizeof(peercred);
if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &cred_len)) {
Log::Error << "getsockopt() failed: " << strerror(errno);
return errno;
}
uid = peercred.uid;
return 0;
#else
// not supported - fail
return EOPNOTSUPP;
#endif
}
// listen/server connection
int
Network::listen_tcp (int port, int family)
{
SockStorage ss;
size_t ss_len = sizeof(ss);
int i_opt;
int sock;
#ifdef HAVE_IPV6
assert(family == AF_INET6 || family == AF_INET);
#else
assert(family == AF_INET);
#endif // HAVE_IPV6
// create socket
if ((sock = socket(family, SOCK_STREAM, 0)) < 0) {
Log::Error << "socket() failed: " << strerror(errno);
return errno;
}
// set reuse timeout thingy
i_opt = 1;
setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, &i_opt, sizeof (i_opt));
// setup and config
#ifdef HAVE_IPV6
if (family == AF_INET6) {
// IPv6
ss_len = sizeof(sockaddr_in6);
memset(&ss, 0, sizeof(ss));
ss.ss_family = AF_INET6;
((sockaddr_in6*)&ss)->sin6_port = htons (port);
#ifdef IPV6_V6ONLY
// set IPV6-only
i_opt = 1;
setsockopt (sock, SOL_SOCKET, IPV6_V6ONLY, &i_opt, sizeof (i_opt));
#endif
} else
#endif // HAVE_IPV6
if (family == AF_INET) {
// IPv4
ss_len = sizeof(sockaddr_in);
memset(&ss, 0, sizeof(ss));
ss.ss_family = AF_INET;
((sockaddr_in*)&ss)->sin_port = htons (port);
}
// bind socket
if (bind (sock, (struct sockaddr *)&ss, ss_len) == -1) {
Log::Error << "bind() failed: " << strerror(errno);
close(sock);
return -1;;
}
// start listening
if (::listen (sock, 5)) {
Log::Error << "listen() failed: " << strerror(errno);
close(sock);
return -1;
}
return sock;
}
// accept incoming connections
int
Network::accept_tcp (int sock, SockStorage& addr)
{
// accept socket
socklen_t sslen = sizeof(addr);
int client = accept(sock, (struct sockaddr*)&addr, &sslen);
if (client == -1)
return -1;
// set non-blocking flag
fcntl(client, F_SETFL, O_NONBLOCK);
return client;
}
// true if address is local
bool
Network::is_addr_local (const SockStorage& addr)
{
if (addr.ss_family == AF_INET) {
if (((const sockaddr_in*)&addr)->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
return true;
}
#ifdef HAVE_IPV6
else if (addr.ss_family == AF_INET6) {
if (IN6_IS_ADDR_LOOPBACK(&((const sockaddr_in6*)&addr)->sin6_addr))
return true;
}
#endif // HAVE_IPV6
return false;
}
// listen/server connection
int
Network::listen_unix (std::string s_path)
{
struct sockaddr_un address;
size_t sa_len = sizeof(address);
int sock;
mode_t mode;
// path too long?
if (s_path.size() >= sizeof(address.sun_path)) {
Log::Error << "UNIX socket path '" << s_path << " is too long (>" << sizeof(address.sun_path) << ")";
return -1;
}
// create socket
if ((sock = socket (PF_UNIX, SOCK_STREAM, 0)) < 0) {
Log::Error << "socket() failed: " << strerror(errno);
return -1;
}
// unlink previous socket
unlink(s_path.c_str());
// setup and config
address.sun_family = AF_UNIX;
snprintf(address.sun_path, sizeof(address.sun_path), "%s", s_path.c_str());
sa_len = sizeof(address.sun_family) + strlen(address.sun_path) + 1;
// bind socket
mode = umask(077);
if (bind (sock, (struct sockaddr *)&address, sa_len) == -1) {
Log::Error << "bind() failed: " << strerror(errno);
umask(mode);
close(sock);
return -1;
}
umask(mode);
// start listening
if (::listen (sock, 5)) {
Log::Error << "listen() failed: " << strerror(errno);
unlink(s_path.c_str());
close(sock);
return -1;
}
return sock;
}
// accept incoming connections
int
Network::accept_unix (int sock, uid_t& uid)
{
// do accept
struct sockaddr_un address;
socklen_t sslen = sizeof(address);
int client = accept(sock, (struct sockaddr*)&address, (socklen_t*)&sslen);
if (client == -1)
return -1;
// get peer UID
uid = 0;
if (get_peer_uid(client, uid)) {
close(client);
return -1;
}
// set non-blocking flag
fcntl(client, F_SETFL, O_NONBLOCK);
return client;
}
int Network::parse_addr(const char* item, SockStorage* host, uint* mask)
{
char buffer[128];
// put in buffer, snprintf() guarnatees NUL byte
snprintf (buffer, sizeof(buffer), "%s", item);
// get mask - have we a mask?
int inmask = -1;
char* slash = strchr(buffer, '/');
if (slash != NULL) {
*slash = '\0';
++ slash;
// don't use atoi or strtol, guarantee we parse it right
inmask = 0;
while (*slash != '\0') {
if (!isdigit(*slash))
break;
inmask *= 10;
inmask += *slash - '0';
++ slash;
}
// only numbers, rights?
if (*slash != '\0')
return -1; // FAIL
}
// parse address
SockStorage ss;
#ifdef HAVE_IPV6
// try IPv6 first
if (inet_pton(AF_INET6, buffer, &((sockaddr_in6*)&ss)->sin6_addr) > 0) { // match
// check mask
if (inmask > 128)
return -1; // FAIL
else if (inmask < 0)
inmask = 128;
addr_apply_mask((uint8*)&((sockaddr_in6*)&ss)->sin6_addr, 16, inmask);
ss.ss_family = AF_INET6;
*host = SockStorage(ss);
*mask = inmask;
return 0;
} else
#endif // HAVE_IPV6
// try IPv4 parsing
#ifdef HAVE_INET_PTON
if (inet_pton(AF_INET, buffer, &((sockaddr_in*)&ss)->sin_addr) > 0) { // match
// check mask
if (inmask > 32)
return -1; // FAIL
else if (inmask < 0)
inmask = 32;
addr_apply_mask((uint8*)&((sockaddr_in*)&ss)->sin_addr, 4, inmask);
ss.ss_family = AF_INET;
*host = SockStorage(ss);
*mask = inmask;
return 0;
#else // HAVE_INET_PTON
if (inet_aton(buffer, &((sockaddr_in*)&ss)->sin_addr) != 0) { // match
// check mask
if (inmask > 32)
return -1; // FAIL
else if (inmask < 0)
inmask = 32;
addr_apply_mask((uint8*)&((sockaddr_in*)&ss)->sin_addr, 4, inmask);
ss.ss_family = AF_INET;
*host = SockStorage(ss);
*mask = inmask;
return 0;
#endif
} else {
// no match
return -1; // FAIL
}
}
<|endoftext|>
|
<commit_before>#include "options.h"
Options* Options::instance()
{
static Options* _instance = 0;
if (!_instance)
_instance = new Options;
return _instance;
}
Options::Options()
: m_errorLimit(20)
, m_readFromStdin(false)
{
}
Options::~Options()
{
}
void Options::parseCommandLine()
{
QCommandLineParser parser;
parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("files", "Files to compile.", "[files...]");
QCommandLineOption include(QStringList() << "i" << "include", "Include directories.", "include", "");
parser.addOption(include);
QCommandLineOption errorLimit("error-limit", "Stop after N errors. [Default: 20]", "N", "20");
parser.addOption(errorLimit);
QCommandLineOption outputFile(QStringList() << "o" << "out",
"Output to file or stdout if empty.", "file", "");
parser.addOption(outputFile);
QCommandLineOption outputType(QStringList() << "e" << "emit",
"Specify the type of output. [Default: obj]\n type=obj|llvm|ast", "type", "obj");
parser.addOption(outputType);
QCommandLineOption readFromStdin("stdin", "Read from stdin.");
parser.addOption(readFromStdin);
parser.process(*QCoreApplication::instance());
m_files = parser.positionalArguments();
m_includeDirs = parser.values(include);
m_errorLimit = parser.value(errorLimit).toInt();
m_outputFile = parser.value(outputFile);
m_outputType = parser.value(outputType);
if (m_outputType != "obj" && m_outputType != "llvm" && m_outputType != "ast")
m_outputType = "obj";
m_readFromStdin = parser.isSet(readFromStdin);
}
<commit_msg>Show help if no command line arguments<commit_after>#include "options.h"
Options* Options::instance()
{
static Options* _instance = 0;
if (!_instance)
_instance = new Options;
return _instance;
}
Options::Options()
: m_errorLimit(20)
, m_readFromStdin(false)
{
}
Options::~Options()
{
}
void Options::parseCommandLine()
{
QCommandLineParser parser;
parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("files", "Files to compile.", "[files...]");
QCommandLineOption include(QStringList() << "i" << "include", "Include directories.", "include", "");
parser.addOption(include);
QCommandLineOption errorLimit("error-limit", "Stop after N errors. [Default: 20]", "N", "20");
parser.addOption(errorLimit);
QCommandLineOption outputFile(QStringList() << "o" << "out",
"Output to file or stdout if empty.", "file", "");
parser.addOption(outputFile);
QCommandLineOption outputType(QStringList() << "e" << "emit",
"Specify the type of output. [Default: obj]\n type=obj|llvm|ast", "type", "obj");
parser.addOption(outputType);
QCommandLineOption readFromStdin("stdin", "Read from stdin.");
parser.addOption(readFromStdin);
parser.process(*QCoreApplication::instance());
m_files = parser.positionalArguments();
m_includeDirs = parser.values(include);
m_errorLimit = parser.value(errorLimit).toInt();
m_outputFile = parser.value(outputFile);
m_outputType = parser.value(outputType);
if (m_outputType != "obj" && m_outputType != "llvm" && m_outputType != "ast")
m_outputType = "obj";
m_readFromStdin = parser.isSet(readFromStdin);
if (m_files.isEmpty() && !m_readFromStdin)
parser.showHelp();
}
<|endoftext|>
|
<commit_before>// Copyright 2018, OpenCensus Authors
//
// 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 <grpcpp/grpcpp.h>
#include <grpcpp/opencensus.h>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/time/clock.h"
#include "examples/grpc/exporters.h"
#include "examples/grpc/hello.grpc.pb.h"
#include "examples/grpc/hello.pb.h"
#include "opencensus/tags/context_util.h"
#include "opencensus/tags/tag_key.h"
#include "opencensus/tags/tag_map.h"
#include "opencensus/tags/with_tag_map.h"
#include "opencensus/trace/context_util.h"
#include "opencensus/trace/sampler.h"
#include "opencensus/trace/trace_config.h"
#include "opencensus/trace/with_span.h"
namespace {
using examples::HelloReply;
using examples::HelloRequest;
using examples::HelloService;
} // namespace
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " host:port [name]\n";
return 1;
}
const std::string hostport = argv[1];
std::string name = "world";
if (argc >= 3) {
name = argv[2];
}
// Register the OpenCensus gRPC plugin to enable stats and tracing in gRPC.
grpc::RegisterOpenCensusPlugin();
RegisterExporters();
// Create a Channel to send RPCs over.
std::shared_ptr<grpc::Channel> channel =
grpc::CreateChannel(hostport, grpc::InsecureChannelCredentials());
std::unique_ptr<HelloService::Stub> stub = HelloService::NewStub(channel);
// Create a span, this will be the parent of the RPC span.
static opencensus::trace::AlwaysSampler sampler;
auto span = opencensus::trace::Span::StartSpan(
"HelloClient", /*parent=*/nullptr, {&sampler});
std::cout << "HelloClient span context is " << span.context().ToString()
<< "\n";
// Extend the current tag map.
// (in this example, there are no tags currently present, but in real code we
// wouldn't want to drop tags)
static const auto key = opencensus::tags::TagKey::Register("my_key");
std::vector<std::pair<opencensus::tags::TagKey, std::string>> tags(
opencensus::tags::GetCurrentTagMap().tags());
tags.emplace_back(key, "my_value");
opencensus::tags::TagMap tag_map(std::move(tags));
{
opencensus::trace::WithSpan ws(span);
opencensus::tags::WithTagMap wt(tag_map);
// The client Span ends when ctx falls out of scope.
grpc::ClientContext ctx;
ctx.AddMetadata("key1", "value1");
HelloRequest request;
HelloReply reply;
request.set_name(name);
std::cout << "Sending request: \"" << request.ShortDebugString() << "\"\n";
opencensus::trace::GetCurrentSpan().AddAnnotation("Sending request.");
// Send the RPC.
grpc::Status status = stub->SayHello(&ctx, request, &reply);
std::cout << "Got status: " << status.error_code() << ": \""
<< status.error_message() << "\"\n";
std::cout << "Got reply: \"" << reply.ShortDebugString() << "\"\n";
opencensus::trace::GetCurrentSpan().AddAnnotation(
"Got reply.", {{"status", absl::StrCat(status.error_code(), ": ",
status.error_message())}});
if (!status.ok()) {
// TODO: Map grpc::StatusCode to trace::StatusCode.
opencensus::trace::GetCurrentSpan().SetStatus(
opencensus::trace::StatusCode::UNKNOWN, status.error_message());
}
// Don't forget to explicitly end the span!
opencensus::trace::GetCurrentSpan().End();
}
// Disable tracing any further RPCs (which will be sent by exporters).
opencensus::trace::TraceConfig::SetCurrentTraceParams(
{128, 128, 128, 128, opencensus::trace::ProbabilitySampler(0.0)});
// Sleep while exporters run in the background.
std::cout << "Client sleeping, ^C to exit.\n";
while (true) {
absl::SleepFor(absl::Seconds(10));
}
}
<commit_msg>gRPC example: export stats from client as well as server. (#415)<commit_after>// Copyright 2018, OpenCensus Authors
//
// 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 <grpcpp/grpcpp.h>
#include <grpcpp/opencensus.h>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/time/clock.h"
#include "examples/grpc/exporters.h"
#include "examples/grpc/hello.grpc.pb.h"
#include "examples/grpc/hello.pb.h"
#include "opencensus/stats/aggregation.h"
#include "opencensus/stats/bucket_boundaries.h"
#include "opencensus/stats/view_descriptor.h"
#include "opencensus/tags/context_util.h"
#include "opencensus/tags/tag_key.h"
#include "opencensus/tags/tag_map.h"
#include "opencensus/tags/with_tag_map.h"
#include "opencensus/trace/context_util.h"
#include "opencensus/trace/sampler.h"
#include "opencensus/trace/trace_config.h"
#include "opencensus/trace/with_span.h"
namespace {
using examples::HelloReply;
using examples::HelloRequest;
using examples::HelloService;
opencensus::tags::TagKey MyKey() {
static const auto key = opencensus::tags::TagKey::Register("my_key");
return key;
}
opencensus::stats::Aggregation MillisDistributionAggregation() {
return opencensus::stats::Aggregation::Distribution(
opencensus::stats::BucketBoundaries::Explicit(
{0, 0.1, 1, 10, 100, 1000}));
}
ABSL_CONST_INIT const absl::string_view kRpcClientRoundtripLatencyMeasureName =
"grpc.io/client/roundtrip_latency";
::opencensus::tags::TagKey ClientMethodTagKey() {
static const auto method_tag_key =
::opencensus::tags::TagKey::Register("grpc_client_method");
return method_tag_key;
}
::opencensus::tags::TagKey ClientStatusTagKey() {
static const auto status_tag_key =
::opencensus::tags::TagKey::Register("grpc_client_status");
return status_tag_key;
}
} // namespace
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "Usage: " << argv[0] << " host:port [name]\n";
return 1;
}
const std::string hostport = argv[1];
std::string name = "world";
if (argc >= 3) {
name = argv[2];
}
// Register the OpenCensus gRPC plugin to enable stats and tracing in gRPC.
grpc::RegisterOpenCensusPlugin();
// Add a view of client RPC latency broken down by our custom key.
opencensus::stats::ViewDescriptor()
.set_name("example/client/roundtrip_latency/cumulative")
.set_measure(kRpcClientRoundtripLatencyMeasureName)
.set_aggregation(MillisDistributionAggregation())
.add_column(ClientMethodTagKey())
.add_column(ClientStatusTagKey())
.add_column(MyKey())
.RegisterForExport();
RegisterExporters();
// Create a Channel to send RPCs over.
std::shared_ptr<grpc::Channel> channel =
grpc::CreateChannel(hostport, grpc::InsecureChannelCredentials());
std::unique_ptr<HelloService::Stub> stub = HelloService::NewStub(channel);
// Create a span, this will be the parent of the RPC span.
static opencensus::trace::AlwaysSampler sampler;
auto span = opencensus::trace::Span::StartSpan(
"HelloClient", /*parent=*/nullptr, {&sampler});
std::cout << "HelloClient span context is " << span.context().ToString()
<< "\n";
// Extend the current tag map.
// (in this example, there are no tags currently present, but in real code we
// wouldn't want to drop tags)
static const auto key = opencensus::tags::TagKey::Register("my_key");
std::vector<std::pair<opencensus::tags::TagKey, std::string>> tags(
opencensus::tags::GetCurrentTagMap().tags());
tags.emplace_back(key, "my_value");
opencensus::tags::TagMap tag_map(std::move(tags));
{
opencensus::trace::WithSpan ws(span);
opencensus::tags::WithTagMap wt(tag_map);
// The client Span ends when ctx falls out of scope.
grpc::ClientContext ctx;
ctx.AddMetadata("key1", "value1");
HelloRequest request;
HelloReply reply;
request.set_name(name);
std::cout << "Sending request: \"" << request.ShortDebugString() << "\"\n";
opencensus::trace::GetCurrentSpan().AddAnnotation("Sending request.");
// Send the RPC.
grpc::Status status = stub->SayHello(&ctx, request, &reply);
std::cout << "Got status: " << status.error_code() << ": \""
<< status.error_message() << "\"\n";
std::cout << "Got reply: \"" << reply.ShortDebugString() << "\"\n";
opencensus::trace::GetCurrentSpan().AddAnnotation(
"Got reply.", {{"status", absl::StrCat(status.error_code(), ": ",
status.error_message())}});
if (!status.ok()) {
// TODO: Map grpc::StatusCode to trace::StatusCode.
opencensus::trace::GetCurrentSpan().SetStatus(
opencensus::trace::StatusCode::UNKNOWN, status.error_message());
}
// Don't forget to explicitly end the span!
opencensus::trace::GetCurrentSpan().End();
}
// Disable tracing any further RPCs (which will be sent by exporters).
opencensus::trace::TraceConfig::SetCurrentTraceParams(
{128, 128, 128, 128, opencensus::trace::ProbabilitySampler(0.0)});
// Sleep while exporters run in the background.
std::cout << "Client sleeping, ^C to exit.\n";
while (true) {
absl::SleepFor(absl::Seconds(10));
}
}
<|endoftext|>
|
<commit_before>//
// Eltwise.cpp
// CoreML
//
// Created by Srikrishna Sridhar on 11/13/16.
// Copyright © 2016 Apple Inc. All rights reserved.
//
#include "CaffeConverter.hpp"
#include "Utils-inl.hpp"
#include <stdio.h>
#include <string>
#include <sstream>
#include <iostream>
using namespace CoreML;
void CoreMLConverter::convertCaffeEltwise(CoreMLConverter::ConvertLayerParameters layerParameters) {
int layerId = *layerParameters.layerId;
const caffe::LayerParameter& caffeLayer = layerParameters.prototxt.layer(layerId);
std::map<std::string, std::string>& mappingDataBlobNames = layerParameters.mappingDataBlobNames;
//Write Layer metadata
auto* nnWrite = layerParameters.nnWrite;
Specification::NeuralNetworkLayer* specLayer = nnWrite->Add();
if (caffeLayer.bottom_size() <= 1 || caffeLayer.top_size() != 1) {
CoreMLConverter::errorInCaffeProto("Must have more than 1 input and exactly 1 output",caffeLayer.name(),caffeLayer.type());
}
std::vector<std::string> bottom;
std::vector<std::string> top;
for (const auto& bottomName: caffeLayer.bottom()){
bottom.push_back(bottomName);
}
for (const auto& topName: caffeLayer.top()){
top.push_back(topName);
}
CoreMLConverter::convertCaffeMetadata(caffeLayer.name(),
bottom, top,
nnWrite, mappingDataBlobNames);
const caffe::EltwiseParameter& caffeLayerParams = caffeLayer.eltwise_param();
//***************** Some Error Checking in Caffe Proto **********
if (caffeLayerParams.operation()==caffe::EltwiseParameter::MAX){
CoreMLConverter::unsupportedCaffeParrameterWithOption("operation",caffeLayer.name(), "Elementwise","Max");
}
if (caffeLayerParams.coeff_size()!=0) {
CoreMLConverter::unsupportedCaffeParrameter("coeff", caffeLayer.name(), "Elementwise");
}
//***************************************************************
if (caffeLayerParams.operation()==caffe::EltwiseParameter::SUM){
(void) specLayer->mutable_add();
} else if (caffeLayerParams.operation()==caffe::EltwiseParameter::PROD) {
(void) specLayer->mutable_multiply();
} else {
//default
(void) specLayer->mutable_add();
}
}
<commit_msg>fix in eltwise.cpp: handle max operation<commit_after>//
// Eltwise.cpp
// CoreML
//
// Created by Srikrishna Sridhar on 11/13/16.
// Copyright © 2016 Apple Inc. All rights reserved.
//
#include "CaffeConverter.hpp"
#include "Utils-inl.hpp"
#include <stdio.h>
#include <string>
#include <sstream>
#include <iostream>
using namespace CoreML;
void CoreMLConverter::convertCaffeEltwise(CoreMLConverter::ConvertLayerParameters layerParameters) {
int layerId = *layerParameters.layerId;
const caffe::LayerParameter& caffeLayer = layerParameters.prototxt.layer(layerId);
std::map<std::string, std::string>& mappingDataBlobNames = layerParameters.mappingDataBlobNames;
//Write Layer metadata
auto* nnWrite = layerParameters.nnWrite;
Specification::NeuralNetworkLayer* specLayer = nnWrite->Add();
if (caffeLayer.bottom_size() <= 1 || caffeLayer.top_size() != 1) {
CoreMLConverter::errorInCaffeProto("Must have more than 1 input and exactly 1 output",caffeLayer.name(),caffeLayer.type());
}
std::vector<std::string> bottom;
std::vector<std::string> top;
for (const auto& bottomName: caffeLayer.bottom()){
bottom.push_back(bottomName);
}
for (const auto& topName: caffeLayer.top()){
top.push_back(topName);
}
CoreMLConverter::convertCaffeMetadata(caffeLayer.name(),
bottom, top,
nnWrite, mappingDataBlobNames);
const caffe::EltwiseParameter& caffeLayerParams = caffeLayer.eltwise_param();
//***************** Some Error Checking in Caffe Proto **********
if (caffeLayerParams.coeff_size()!=0) {
CoreMLConverter::unsupportedCaffeParrameter("coeff", caffeLayer.name(), "Elementwise");
}
//***************************************************************
if (caffeLayerParams.operation()==caffe::EltwiseParameter::SUM){
(void) specLayer->mutable_add();
} else if (caffeLayerParams.operation()==caffe::EltwiseParameter::PROD) {
(void) specLayer->mutable_multiply();
} else if (caffeLayerParams.operation()==caffe::EltwiseParameter::MAX) {
(void) specLayer->mutable_max();
} else {
CoreMLConverter::errorInCaffeProto("Operation type should be one of 'sum', 'prod' or 'max' ",caffeLayer.name(),caffeLayer.type());
}
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "SmoothSuperellipsoidBaseIC.h"
#include "MooseMesh.h"
template<>
InputParameters validParams<SmoothSuperellipsoidBaseIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addRequiredParam<Real>("invalue", "The variable value inside the superellipsoid");
params.addRequiredParam<Real>("outvalue", "The variable value outside the superellipsoid");
params.addParam<Real>("int_width", 0.0, "The interfacial width of the void surface. Defaults to sharp interface");
params.addParam<bool>("zero_gradient", false, "Set the gradient DOFs to zero. This can avoid numerical problems with higher order shape functions.");
params.addParam<unsigned int>("rand_seed", 12345, "Seed value for the random number generator");
return params;
}
SmoothSuperellipsoidBaseIC::SmoothSuperellipsoidBaseIC(const InputParameters & parameters) :
InitialCondition(parameters),
_mesh(_fe_problem.mesh()),
_invalue(parameters.get<Real>("invalue")),
_outvalue(parameters.get<Real>("outvalue")),
_int_width(parameters.get<Real>("int_width")),
_zero_gradient(parameters.get<bool>("zero_gradient"))
{
_random.seed(_tid, getParam<unsigned int>("rand_seed"));
}
void
SmoothSuperellipsoidBaseIC::initialSetup()
{
//Compute centers, semiaxes, exponents, and initialize vector sizes
computeSuperellipsoidCenters();
computeSuperellipsoidSemiaxes();
computeSuperellipsoidExponents();
if (_centers.size() != _as.size())
mooseError("_center and semiaxis _as vectors are not the same size in the Superellipsoid IC");
if (_centers.size() != _bs.size())
mooseError("_center and semiaxis _bs vectors are not the same size in the Superellipsoid IC");
if (_centers.size() != _cs.size())
mooseError("_center and semiaxis _cs vectors are not the same size in the Superellipsoid IC");
if (_centers.size() != _ns.size())
mooseError("_center and exponent _ns vectors are not the same size in the Superellipsoid IC");
if (_centers.size() < 1)
mooseError("_centers, _as, _bs, _cs, and _ns were not initialized in the Superellipsoid IC");
}
Real
SmoothSuperellipsoidBaseIC::value(const Point & p)
{
Real value = _outvalue;
Real val2 = 0.0;
for (unsigned int ellip = 0; ellip < _centers.size() && value != _invalue; ++ellip)
{
val2 = computeSuperellipsoidValue(p, _centers[ellip], _as[ellip], _bs[ellip], _cs[ellip], _ns[ellip]);
if ( (val2 > value && _invalue > _outvalue) || (val2 < value && _outvalue > _invalue) )
value = val2;
}
return value;
}
RealGradient
SmoothSuperellipsoidBaseIC::gradient(const Point & p)
{
if (_zero_gradient)
return 0.0;
RealGradient gradient = 0.0;
Real value = _outvalue;
Real val2 = 0.0;
for (unsigned int ellip = 0; ellip < _centers.size(); ++ellip)
{
val2 = computeSuperellipsoidValue(p, _centers[ellip], _as[ellip], _bs[ellip], _cs[ellip], _ns[ellip]);
if ( (val2 > value && _invalue > _outvalue) || (val2 < value && _outvalue > _invalue) )
{
value = val2;
gradient = computeSuperellipsoidGradient(p, _centers[ellip], _as[ellip], _bs[ellip], _cs[ellip], _ns[ellip]);
}
}
return gradient;
}
Real
SmoothSuperellipsoidBaseIC::computeSuperellipsoidValue(const Point & p, const Point & center, const Real & a, const Real & b, const Real & c, const Real & n)
{
Point l_center = center;
Point l_p = p;
//Compute the distance between the current point and the center
Real dist = _mesh.minPeriodicDistance(_var.number(), l_p, l_center);
//When dist is 0 we are exactly at the center of the superellipsoid so return _invalue
//Handle this case independently because we cannot calculate polar angles at this point
if (dist == 0.0) return _invalue;
//Compute the distance r from the center of the superellipsoid to its outside edge
//along the vector from the center to the current point
//This uses the equation for a superellipse in polar coordinates and substitutes
//distances for sin, cos functions
Point dist_vec = _mesh.minPeriodicVector(_var.number(), center, p);
//First calculate rmn = r^(-n), replacing sin, cos functions with distances
Real rmn = (std::pow(std::abs(dist_vec(0) / dist / a), n)
+ std::pow(std::abs(dist_vec(1) / dist / b), n)
+ std::pow(std::abs(dist_vec(2) / dist / c), n) );
//Then calculate r from rmn
Real r = std::pow(rmn, (-1.0/n));
Real value = _outvalue; //Outside superellipsoid
if (dist <= r - _int_width/2.0) //Inside superellipsoid
value = _invalue;
else if (dist < r + _int_width/2.0) //Smooth interface
{
Real int_pos = (dist - r + _int_width/2.0)/_int_width;
value = _outvalue + (_invalue - _outvalue) * (1.0 + std::cos(int_pos * libMesh::pi)) / 2.0;
}
return value;
}
RealGradient
SmoothSuperellipsoidBaseIC::computeSuperellipsoidGradient(const Point & p, const Point & center, const Real & a, const Real & b, const Real & /*c*/, const Real & n)
{
Point l_center = center;
Point l_p = p;
//Compute the distance between the current point and the center
Real dist = _mesh.minPeriodicDistance(_var.number(), l_p, l_center);
//Compute the distance r from the center of the superellipsoid to its outside edge
//along the vector from the center to the current point
//This uses the equation for a superellipse in polar coordinates and substitutes
//distances for sin, cos functions
Point dist_vec = _mesh.minPeriodicVector(_var.number(), center, p);
//First calculate rmn = r^(-n)
Real rmn = (std::pow(std::abs(dist_vec(0)/dist/a), n) + std::pow(std::abs(dist_vec(1)/dist/b), n));
//Then calculate r
Real r = std::pow(rmn, (-1.0/n));
Real DvalueDr = 0.0;
if (dist < r + _int_width/2.0 && dist > r - _int_width/2.0)
{
Real int_pos = (dist - r + _int_width / 2.0) / _int_width;
Real Dint_posDr = 1.0 / _int_width;
DvalueDr = Dint_posDr * (_invalue - _outvalue) * (-std::sin(int_pos * libMesh::pi) * libMesh::pi) / 2.0;
}
//Set gradient over the smooth interface
if (dist != 0.0)
return dist_vec * (DvalueDr / dist);
else
return 0.0;
}
<commit_msg>Add 3D capability to computeSuperellipsoidGradient Ref #6742<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* All contents are licensed under LGPL V2.1 */
/* See LICENSE for full restrictions */
/****************************************************************/
#include "SmoothSuperellipsoidBaseIC.h"
#include "MooseMesh.h"
template<>
InputParameters validParams<SmoothSuperellipsoidBaseIC>()
{
InputParameters params = validParams<InitialCondition>();
params.addRequiredParam<Real>("invalue", "The variable value inside the superellipsoid");
params.addRequiredParam<Real>("outvalue", "The variable value outside the superellipsoid");
params.addParam<Real>("int_width", 0.0, "The interfacial width of the void surface. Defaults to sharp interface");
params.addParam<bool>("zero_gradient", false, "Set the gradient DOFs to zero. This can avoid numerical problems with higher order shape functions.");
params.addParam<unsigned int>("rand_seed", 12345, "Seed value for the random number generator");
return params;
}
SmoothSuperellipsoidBaseIC::SmoothSuperellipsoidBaseIC(const InputParameters & parameters) :
InitialCondition(parameters),
_mesh(_fe_problem.mesh()),
_invalue(parameters.get<Real>("invalue")),
_outvalue(parameters.get<Real>("outvalue")),
_int_width(parameters.get<Real>("int_width")),
_zero_gradient(parameters.get<bool>("zero_gradient"))
{
_random.seed(_tid, getParam<unsigned int>("rand_seed"));
}
void
SmoothSuperellipsoidBaseIC::initialSetup()
{
//Compute centers, semiaxes, exponents, and initialize vector sizes
computeSuperellipsoidCenters();
computeSuperellipsoidSemiaxes();
computeSuperellipsoidExponents();
if (_centers.size() != _as.size())
mooseError("_center and semiaxis _as vectors are not the same size in the Superellipsoid IC");
if (_centers.size() != _bs.size())
mooseError("_center and semiaxis _bs vectors are not the same size in the Superellipsoid IC");
if (_centers.size() != _cs.size())
mooseError("_center and semiaxis _cs vectors are not the same size in the Superellipsoid IC");
if (_centers.size() != _ns.size())
mooseError("_center and exponent _ns vectors are not the same size in the Superellipsoid IC");
if (_centers.size() < 1)
mooseError("_centers, _as, _bs, _cs, and _ns were not initialized in the Superellipsoid IC");
}
Real
SmoothSuperellipsoidBaseIC::value(const Point & p)
{
Real value = _outvalue;
Real val2 = 0.0;
for (unsigned int ellip = 0; ellip < _centers.size() && value != _invalue; ++ellip)
{
val2 = computeSuperellipsoidValue(p, _centers[ellip], _as[ellip], _bs[ellip], _cs[ellip], _ns[ellip]);
if ( (val2 > value && _invalue > _outvalue) || (val2 < value && _outvalue > _invalue) )
value = val2;
}
return value;
}
RealGradient
SmoothSuperellipsoidBaseIC::gradient(const Point & p)
{
if (_zero_gradient)
return 0.0;
RealGradient gradient = 0.0;
Real value = _outvalue;
Real val2 = 0.0;
for (unsigned int ellip = 0; ellip < _centers.size(); ++ellip)
{
val2 = computeSuperellipsoidValue(p, _centers[ellip], _as[ellip], _bs[ellip], _cs[ellip], _ns[ellip]);
if ( (val2 > value && _invalue > _outvalue) || (val2 < value && _outvalue > _invalue) )
{
value = val2;
gradient = computeSuperellipsoidGradient(p, _centers[ellip], _as[ellip], _bs[ellip], _cs[ellip], _ns[ellip]);
}
}
return gradient;
}
Real
SmoothSuperellipsoidBaseIC::computeSuperellipsoidValue(const Point & p, const Point & center, const Real & a, const Real & b, const Real & c, const Real & n)
{
Point l_center = center;
Point l_p = p;
//Compute the distance between the current point and the center
Real dist = _mesh.minPeriodicDistance(_var.number(), l_p, l_center);
//When dist is 0 we are exactly at the center of the superellipsoid so return _invalue
//Handle this case independently because we cannot calculate polar angles at this point
if (dist == 0.0) return _invalue;
//Compute the distance r from the center of the superellipsoid to its outside edge
//along the vector from the center to the current point
//This uses the equation for a superellipse in polar coordinates and substitutes
//distances for sin, cos functions
Point dist_vec = _mesh.minPeriodicVector(_var.number(), center, p);
//First calculate rmn = r^(-n), replacing sin, cos functions with distances
Real rmn = (std::pow(std::abs(dist_vec(0) / dist / a), n)
+ std::pow(std::abs(dist_vec(1) / dist / b), n)
+ std::pow(std::abs(dist_vec(2) / dist / c), n) );
//Then calculate r from rmn
Real r = std::pow(rmn, (-1.0/n));
Real value = _outvalue; //Outside superellipsoid
if (dist <= r - _int_width/2.0) //Inside superellipsoid
value = _invalue;
else if (dist < r + _int_width/2.0) //Smooth interface
{
Real int_pos = (dist - r + _int_width/2.0)/_int_width;
value = _outvalue + (_invalue - _outvalue) * (1.0 + std::cos(int_pos * libMesh::pi)) / 2.0;
}
return value;
}
RealGradient
SmoothSuperellipsoidBaseIC::computeSuperellipsoidGradient(const Point & p, const Point & center, const Real & a, const Real & b, const Real & c, const Real & n)
{
Point l_center = center;
Point l_p = p;
//Compute the distance between the current point and the center
Real dist = _mesh.minPeriodicDistance(_var.number(), l_p, l_center);
//When dist is 0 we are exactly at the center of the superellipsoid so return 0
//Handle this case independently because we cannot calculate polar angles at this point
if (dist == 0.0) return 0.0;
//Compute the distance r from the center of the superellipsoid to its outside edge
//along the vector from the center to the current point
//This uses the equation for a superellipse in polar coordinates and substitutes
//distances for sin, cos functions
Point dist_vec = _mesh.minPeriodicVector(_var.number(), center, p);
//First calculate rmn = r^(-n)
Real rmn = (std::pow(std::abs(dist_vec(0) / dist / a), n)
+ std::pow(std::abs(dist_vec(1) / dist / b), n)
+ std::pow(std::abs(dist_vec(2) / dist / c), n) );
//Then calculate r from rmn
Real r = std::pow(rmn, (-1.0/n));
Real DvalueDr = 0.0;
if (dist < r + _int_width/2.0 && dist > r - _int_width/2.0) //in interfacial region
{
Real int_pos = (dist - r + _int_width / 2.0) / _int_width;
Real Dint_posDr = 1.0 / _int_width;
DvalueDr = Dint_posDr * (_invalue - _outvalue) * (-std::sin(int_pos * libMesh::pi) * libMesh::pi) / 2.0;
}
return dist_vec * (DvalueDr / dist);
}
<|endoftext|>
|
<commit_before>/*
Copyright 2013 SINTEF ICT, Applied Mathematics.
*/
#pragma once
#include <opm/autodiff/AutoDiffHelpers.hpp>
#include <opm/core/utility/parameters/ParameterGroup.hpp>
#include <opm/core/grid/GridManager.hpp>
#include <opm/core/linalg/LinearSolverFactory.hpp>
#include <vector>
#include <string>
#include <map>
#include "equelle/equelleTypes.hpp"
namespace equelle {
/// The Equelle runtime class.
/// Contains methods corresponding to Equelle built-ins to make
/// it easy to generate C++ code for an Equelle program.
class EquelleRuntimeCPU
{
public:
/// Constructor.
EquelleRuntimeCPU( const Opm::parameter::ParameterGroup& param );
EquelleRuntimeCPU( const UnstructuredGrid* grid, const Opm::parameter::ParameterGroup& param );
///@{ Topology and geometry related.
CollOfCell allCells() const;
CollOfCell boundaryCells() const;
CollOfCell interiorCells() const;
CollOfFace allFaces() const;
CollOfFace boundaryFaces() const;
CollOfFace interiorFaces() const;
CollOfCell firstCell(const CollOfFace& faces) const;
CollOfCell secondCell(const CollOfFace& faces) const;
CollOfScalar norm(const CollOfFace& faces) const;
CollOfScalar norm(const CollOfCell& cells) const;
CollOfScalar norm(const CollOfVector& vectors) const;
CollOfVector centroid(const CollOfFace& faces) const;
CollOfVector centroid(const CollOfCell& cells) const;
CollOfVector normal(const CollOfFace& faces) const;
///@}
///@{ Operators and math functions.
CollOfScalar sqrt(const CollOfScalar& x) const;
CollOfScalar dot(const CollOfVector& v1, const CollOfVector& v2) const;
CollOfScalar gradient(const CollOfScalar& cell_scalarfield) const;
CollOfScalar negGradient(const CollOfScalar& cell_scalarfield) const;
CollOfScalar divergence(const CollOfScalar& face_fluxes) const;
CollOfScalar interiorDivergence(const CollOfScalar& face_fluxes) const;
CollOfBool isEmpty(const CollOfCell& cells) const;
CollOfBool isEmpty(const CollOfFace& faces) const;
template <class EntityCollection>
CollOfScalar operatorExtend(const Scalar data, const EntityCollection& to_set);
template <class SomeCollection, class EntityCollection>
SomeCollection operatorExtend(const SomeCollection& data, const EntityCollection& from_set, const EntityCollection& to_set);
template <class SomeCollection, class EntityCollection>
typename CollType<SomeCollection>::Type operatorOn(const SomeCollection& data, const EntityCollection& from_set, const EntityCollection& to_set);
template <class SomeCollection1, class SomeCollection2>
typename CollType<SomeCollection1>::Type
trinaryIf(const CollOfBool& predicate,
const SomeCollection1& iftrue,
const SomeCollection2& iffalse) const;
///@}
///@{ Reductions.
Scalar minReduce(const CollOfScalar& x) const;
Scalar maxReduce(const CollOfScalar& x) const;
Scalar sumReduce(const CollOfScalar& x) const;
Scalar prodReduce(const CollOfScalar& x) const;
///@}
///@{ Solver functions.
template <class ResidualFunctor>
CollOfScalar newtonSolve(const ResidualFunctor& rescomp,
const CollOfScalar& u_initialguess);
template <int Num>
std::array<CollOfScalar, Num> newtonSolveSystem(const std::array<typename ResCompType<Num>::type, Num>& rescomp,
const std::array<CollOfScalar, Num>& u_initialguess);
///@}
///@{ Output.
void output(const String& tag, Scalar val) const;
void output(const String& tag, const CollOfScalar& vals);
///@}
///@{ Input.
Scalar inputScalarWithDefault(const String& name,
const Scalar default_value);
CollOfFace inputDomainSubsetOf(const String& name,
const CollOfFace& superset);
CollOfCell inputDomainSubsetOf(const String& name,
const CollOfCell& superset);
template <class SomeCollection>
CollOfScalar inputCollectionOfScalar(const String& name,
const SomeCollection& coll);
SeqOfScalar inputSequenceOfScalar(const String& name);
///@}
/// Ensuring requirements that may be imposed by Equelle programs.
void ensureGridDimensionMin(const int minimum_grid_dimension) const;
private:
/// Topology helpers
bool boundaryCell(const int cell_index) const;
/// Creating primary variables.
static CollOfScalar singlePrimaryVariable(const CollOfScalar& initial_values);
/// Solver helper.
CollOfScalar solveForUpdate(const CollOfScalar& residual) const;
/// Norms.
Scalar twoNorm(const CollOfScalar& vals) const;
/// Data members.
std::unique_ptr<Opm::GridManager> grid_manager_;
const UnstructuredGrid& grid_;
Opm::HelperOps ops_;
Opm::LinearSolverFactory linsolver_;
bool output_to_file_;
int verbose_;
const Opm::parameter::ParameterGroup& param_;
std::map<std::string, int> outputcount_;
// For newtonSolve().
int max_iter_;
double abs_res_tol_;
};
Opm::GridManager* createGridManager(const Opm::parameter::ParameterGroup& param);
} // namespace equelle
// Include the implementations of template members.
#include "EquelleRuntimeCPU_impl.hpp"
<commit_msg>Doxygen documentation fixes.<commit_after>/*
Copyright 2013 SINTEF ICT, Applied Mathematics.
*/
#pragma once
#include <opm/autodiff/AutoDiffHelpers.hpp>
#include <opm/core/utility/parameters/ParameterGroup.hpp>
#include <opm/core/grid/GridManager.hpp>
#include <opm/core/linalg/LinearSolverFactory.hpp>
#include <vector>
#include <string>
#include <map>
#include "equelle/equelleTypes.hpp"
namespace equelle {
/// The Equelle runtime class.
/// Contains methods corresponding to Equelle built-ins to make
/// it easy to generate C++ code for an Equelle program.
class EquelleRuntimeCPU
{
public:
/// Constructor.
EquelleRuntimeCPU( const Opm::parameter::ParameterGroup& param );
EquelleRuntimeCPU( const UnstructuredGrid* grid, const Opm::parameter::ParameterGroup& param );
/** @name Topology
* Topology and geometry related. */
///@{
CollOfCell allCells() const;
CollOfCell boundaryCells() const;
CollOfCell interiorCells() const;
CollOfFace allFaces() const;
CollOfFace boundaryFaces() const;
CollOfFace interiorFaces() const;
CollOfCell firstCell(const CollOfFace& faces) const;
CollOfCell secondCell(const CollOfFace& faces) const;
CollOfScalar norm(const CollOfFace& faces) const;
CollOfScalar norm(const CollOfCell& cells) const;
CollOfScalar norm(const CollOfVector& vectors) const;
CollOfVector centroid(const CollOfFace& faces) const;
CollOfVector centroid(const CollOfCell& cells) const;
CollOfVector normal(const CollOfFace& faces) const;
///@}
/** @name Math
* Operators and math functions. */
///@{
CollOfScalar sqrt(const CollOfScalar& x) const;
CollOfScalar dot(const CollOfVector& v1, const CollOfVector& v2) const;
CollOfScalar gradient(const CollOfScalar& cell_scalarfield) const;
CollOfScalar negGradient(const CollOfScalar& cell_scalarfield) const;
CollOfScalar divergence(const CollOfScalar& face_fluxes) const;
CollOfScalar interiorDivergence(const CollOfScalar& face_fluxes) const;
CollOfBool isEmpty(const CollOfCell& cells) const;
CollOfBool isEmpty(const CollOfFace& faces) const;
template <class EntityCollection>
CollOfScalar operatorExtend(const Scalar data, const EntityCollection& to_set);
template <class SomeCollection, class EntityCollection>
SomeCollection operatorExtend(const SomeCollection& data, const EntityCollection& from_set, const EntityCollection& to_set);
template <class SomeCollection, class EntityCollection>
typename CollType<SomeCollection>::Type operatorOn(const SomeCollection& data, const EntityCollection& from_set, const EntityCollection& to_set);
template <class SomeCollection1, class SomeCollection2>
typename CollType<SomeCollection1>::Type
trinaryIf(const CollOfBool& predicate,
const SomeCollection1& iftrue,
const SomeCollection2& iffalse) const;
///@}
/** @name Reductions. */
///@{
Scalar minReduce(const CollOfScalar& x) const;
Scalar maxReduce(const CollOfScalar& x) const;
Scalar sumReduce(const CollOfScalar& x) const;
Scalar prodReduce(const CollOfScalar& x) const;
///@}
/// @name Solver functions.
///@{
template <class ResidualFunctor>
CollOfScalar newtonSolve(const ResidualFunctor& rescomp,
const CollOfScalar& u_initialguess);
template <int Num>
std::array<CollOfScalar, Num> newtonSolveSystem(const std::array<typename ResCompType<Num>::type, Num>& rescomp,
const std::array<CollOfScalar, Num>& u_initialguess);
///@}
/// @name Output
///@{
void output(const String& tag, Scalar val) const;
void output(const String& tag, const CollOfScalar& vals);
///@}
/// @name Input
///@{
Scalar inputScalarWithDefault(const String& name,
const Scalar default_value);
CollOfFace inputDomainSubsetOf(const String& name,
const CollOfFace& superset);
CollOfCell inputDomainSubsetOf(const String& name,
const CollOfCell& superset);
template <class SomeCollection>
CollOfScalar inputCollectionOfScalar(const String& name,
const SomeCollection& coll);
SeqOfScalar inputSequenceOfScalar(const String& name);
///@}
/// Ensuring requirements that may be imposed by Equelle programs.
void ensureGridDimensionMin(const int minimum_grid_dimension) const;
private:
/// Topology helpers
bool boundaryCell(const int cell_index) const;
/// Creating primary variables.
static CollOfScalar singlePrimaryVariable(const CollOfScalar& initial_values);
/// Solver helper.
CollOfScalar solveForUpdate(const CollOfScalar& residual) const;
/// Norms.
Scalar twoNorm(const CollOfScalar& vals) const;
/// Data members.
std::unique_ptr<Opm::GridManager> grid_manager_;
const UnstructuredGrid& grid_;
Opm::HelperOps ops_;
Opm::LinearSolverFactory linsolver_;
bool output_to_file_;
int verbose_;
const Opm::parameter::ParameterGroup& param_;
std::map<std::string, int> outputcount_;
// For newtonSolve().
int max_iter_;
double abs_res_tol_;
};
Opm::GridManager* createGridManager(const Opm::parameter::ParameterGroup& param);
} // namespace equelle
// Include the implementations of template members.
#include "EquelleRuntimeCPU_impl.hpp"
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "pyinterp.h"
#include "account.h"
#include "xact.h"
#include "post.h"
namespace ledger {
using namespace python;
shared_ptr<python_interpreter_t> python_session;
char * argv0;
void export_account();
void export_amount();
void export_balance();
void export_commodity();
void export_expr();
void export_format();
void export_item();
void export_journal();
void export_post();
void export_times();
void export_utils();
void export_value();
void export_xact();
void initialize_for_python()
{
export_account();
export_amount();
export_balance();
export_commodity();
export_expr();
export_format();
export_item();
export_journal();
export_post();
export_times();
export_utils();
export_value();
export_xact();
}
struct python_run
{
object result;
python_run(python_interpreter_t * intepreter,
const string& str, int input_mode)
: result(handle<>(borrowed(PyRun_String(str.c_str(), input_mode,
intepreter->main_nspace.ptr(),
intepreter->main_nspace.ptr())))) {}
operator object() {
return result;
}
};
void python_interpreter_t::initialize()
{
TRACE_START(python_init, 1, "Initialized Python");
try {
DEBUG("python.interp", "Initializing Python");
Py_Initialize();
assert(Py_IsInitialized());
hack_system_paths();
object main_module = python::import("__main__");
if (! main_module)
throw_(std::runtime_error,
_("Python failed to initialize (couldn't find __main__)"));
main_nspace = extract<dict>(main_module.attr("__dict__"));
if (! main_nspace)
throw_(std::runtime_error,
_("Python failed to initialize (couldn't find __dict__)"));
python::detail::init_module("ledger", &initialize_for_python);
is_initialized = true;
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error, _("Python failed to initialize"));
}
TRACE_FINISH(python_init, 1);
}
void python_interpreter_t::hack_system_paths()
{
// Hack ledger.__path__ so it points to a real location
python::object sys_module = python::import("sys");
python::object sys_dict = sys_module.attr("__dict__");
python::list paths(sys_dict["path"]);
#if defined(DEBUG_ON)
bool path_initialized = false;
#endif
int n = python::extract<int>(paths.attr("__len__")());
for (int i = 0; i < n; i++) {
python::extract<std::string> str(paths[i]);
path pathname(str);
DEBUG("python.interp", "sys.path = " << pathname);
if (exists(pathname / "ledger" / "__init__.py")) {
if (python::object module_ledger = python::import("ledger")) {
DEBUG("python.interp",
"Setting ledger.__path__ = " << (pathname / "ledger"));
python::object ledger_dict = module_ledger.attr("__dict__");
python::list temp_list;
temp_list.append((pathname / "ledger").string());
ledger_dict["__path__"] = temp_list;
} else {
throw_(std::runtime_error,
_("Python failed to initialize (couldn't find ledger)"));
}
#if defined(DEBUG_ON)
path_initialized = true;
#endif
break;
}
}
#if defined(DEBUG_ON)
if (! path_initialized)
DEBUG("python.init",
"Ledger failed to find 'ledger/__init__.py' on the PYTHONPATH");
#endif
}
object python_interpreter_t::import_into_main(const string& str)
{
if (! is_initialized)
initialize();
try {
object mod = python::import(str.c_str());
if (! mod)
throw_(std::runtime_error,
_("Failed to import Python module %1") << str);
// Import all top-level entries directly into the main namespace
main_nspace.update(mod.attr("__dict__"));
return mod;
}
catch (const error_already_set&) {
PyErr_Print();
}
return object();
}
object python_interpreter_t::import_option(const string& str)
{
path file(str);
python::object sys_module = python::import("sys");
python::object sys_dict = sys_module.attr("__dict__");
python::list paths(sys_dict["path"]);
#if BOOST_VERSION >= 103700
paths.insert(0, file.parent_path().string());
sys_dict["path"] = paths;
string name = file.filename();
if (contains(name, ".py"))
name = file.stem();
#else // BOOST_VERSION >= 103700
paths.insert(0, file.branch_path().string());
sys_dict["path"] = paths;
string name = file.leaf();
#endif // BOOST_VERSION >= 103700
return python::import(python::str(name.c_str()));
}
object python_interpreter_t::eval(std::istream& in, py_eval_mode_t mode)
{
bool first = true;
string buffer;
buffer.reserve(4096);
while (! in.eof()) {
char buf[256];
in.getline(buf, 255);
if (buf[0] == '!')
break;
if (first)
first = false;
else
buffer += "\n";
buffer += buf;
}
if (! is_initialized)
initialize();
try {
int input_mode = -1;
switch (mode) {
case PY_EVAL_EXPR: input_mode = Py_eval_input; break;
case PY_EVAL_STMT: input_mode = Py_single_input; break;
case PY_EVAL_MULTI: input_mode = Py_file_input; break;
}
return python_run(this, buffer, input_mode);
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error, _("Failed to evaluate Python code"));
}
return object();
}
object python_interpreter_t::eval(const string& str, py_eval_mode_t mode)
{
if (! is_initialized)
initialize();
try {
int input_mode = -1;
switch (mode) {
case PY_EVAL_EXPR: input_mode = Py_eval_input; break;
case PY_EVAL_STMT: input_mode = Py_single_input; break;
case PY_EVAL_MULTI: input_mode = Py_file_input; break;
}
return python_run(this, str, input_mode);
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error, _("Failed to evaluate Python code"));
}
return object();
}
value_t python_interpreter_t::python_command(call_scope_t& args)
{
if (! is_initialized)
initialize();
char ** argv(new char *[args.size() + 1]);
argv[0] = new char[std::strlen(argv0) + 1];
std::strcpy(argv[0], argv0);
for (std::size_t i = 0; i < args.size(); i++) {
string arg = args[i].as_string();
argv[i + 1] = new char[arg.length() + 1];
std::strcpy(argv[i + 1], arg.c_str());
}
int status = 1;
try {
status = Py_Main(static_cast<int>(args.size()) + 1, argv);
}
catch (...) {
for (std::size_t i = 0; i < args.size() + 1; i++)
delete[] argv[i];
delete[] argv;
throw;
}
for (std::size_t i = 0; i < args.size() + 1; i++)
delete[] argv[i];
delete[] argv;
if (status != 0)
throw status;
return NULL_VALUE;
}
value_t python_interpreter_t::server_command(call_scope_t& args)
{
if (! is_initialized)
initialize();
python::object server_module;
try {
server_module = python::import("ledger.server");
if (! server_module)
throw_(std::runtime_error,
_("Could not import ledger.server; please check your PYTHONPATH"));
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error,
_("Could not import ledger.server; please check your PYTHONPATH"));
}
if (python::object main_function = server_module.attr("main")) {
functor_t func(main_function, "main");
try {
func(args);
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error,
_("Error while invoking ledger.server's main() function"));
}
return true;
} else {
throw_(std::runtime_error,
_("The ledger.server module is missing its main() function!"));
}
return false;
}
option_t<python_interpreter_t> *
python_interpreter_t::lookup_option(const char * p)
{
switch (*p) {
case 'i':
OPT(import_);
break;
}
return NULL;
}
expr_t::ptr_op_t python_interpreter_t::lookup(const symbol_t::kind_t kind,
const string& name)
{
// Give our superclass first dibs on symbol definitions
if (expr_t::ptr_op_t op = session_t::lookup(kind, name))
return op;
switch (kind) {
case symbol_t::FUNCTION:
if (option_t<python_interpreter_t> * handler = lookup_option(name.c_str()))
return MAKE_OPT_FUNCTOR(python_interpreter_t, handler);
if (is_initialized && main_nspace.has_key(name.c_str())) {
DEBUG("python.interp", "Python lookup: " << name);
if (python::object obj = main_nspace.get(name.c_str()))
return WRAP_FUNCTOR(functor_t(obj, name));
}
break;
case symbol_t::OPTION:
if (option_t<python_interpreter_t> * handler = lookup_option(name.c_str()))
return MAKE_OPT_HANDLER(python_interpreter_t, handler);
break;
case symbol_t::PRECOMMAND: {
const char * p = name.c_str();
switch (*p) {
case 'p':
if (is_eq(p, "python"))
return MAKE_FUNCTOR(python_interpreter_t::python_command);
break;
case 's':
if (is_eq(p, "server"))
return MAKE_FUNCTOR(python_interpreter_t::server_command);
break;
}
}
default:
break;
}
return NULL;
}
namespace {
void append_value(list& lst, const value_t& value)
{
if (value.is_scope()) {
const scope_t * scope = value.as_scope();
if (const post_t * post = dynamic_cast<const post_t *>(scope))
lst.append(ptr(post));
else if (const xact_t * xact = dynamic_cast<const xact_t *>(scope))
lst.append(ptr(xact));
else if (const account_t * account =
dynamic_cast<const account_t *>(scope))
lst.append(ptr(account));
else if (const period_xact_t * period_xact =
dynamic_cast<const period_xact_t *>(scope))
lst.append(ptr(period_xact));
else if (const auto_xact_t * auto_xact =
dynamic_cast<const auto_xact_t *>(scope))
lst.append(ptr(auto_xact));
else
throw_(std::logic_error,
_("Cannot downcast scoped object to specific type"));
} else {
lst.append(value);
}
}
}
value_t python_interpreter_t::functor_t::operator()(call_scope_t& args)
{
try {
std::signal(SIGINT, SIG_DFL);
if (! PyCallable_Check(func.ptr())) {
extract<value_t> val(func);
std::signal(SIGINT, sigint_handler);
if (val.check())
return val();
return NULL_VALUE;
}
else if (args.size() > 0) {
list arglist;
// jww (2009-11-05): What about a single argument which is a sequence,
// rather than a sequence of arguments?
if (args.value().is_sequence())
foreach (const value_t& value, args.value().as_sequence())
append_value(arglist, value);
else
append_value(arglist, args.value());
if (PyObject * val =
PyObject_CallObject(func.ptr(), python::tuple(arglist).ptr())) {
extract<value_t> xval(val);
value_t result;
if (xval.check()) {
result = xval();
Py_DECREF(val);
} else {
Py_DECREF(val);
throw_(calc_error,
_("Could not evaluate Python variable '%1'") << name);
}
std::signal(SIGINT, sigint_handler);
return result;
}
else if (PyErr_Occurred()) {
PyErr_Print();
throw_(calc_error, _("Failed call to Python function '%1'") << name);
} else {
assert(false);
}
}
else {
std::signal(SIGINT, sigint_handler);
return call<value_t>(func.ptr());
}
}
catch (const error_already_set&) {
std::signal(SIGINT, sigint_handler);
PyErr_Print();
throw_(calc_error, _("Failed call to Python function '%1'") << name);
}
catch (...) {
std::signal(SIGINT, sigint_handler);
}
std::signal(SIGINT, sigint_handler);
return NULL_VALUE;
}
} // namespace ledger
<commit_msg>Reordered the export_ calls in pyinterp.cc<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of New Artisans LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <system.hh>
#include "pyinterp.h"
#include "account.h"
#include "xact.h"
#include "post.h"
namespace ledger {
using namespace python;
shared_ptr<python_interpreter_t> python_session;
char * argv0;
void export_account();
void export_amount();
void export_balance();
void export_commodity();
void export_expr();
void export_format();
void export_item();
void export_journal();
void export_post();
void export_times();
void export_utils();
void export_value();
void export_xact();
void initialize_for_python()
{
export_times();
export_utils();
export_commodity();
export_amount();
export_value();
export_account();
export_balance();
export_expr();
export_format();
export_item();
export_post();
export_xact();
export_journal();
}
struct python_run
{
object result;
python_run(python_interpreter_t * intepreter,
const string& str, int input_mode)
: result(handle<>(borrowed(PyRun_String(str.c_str(), input_mode,
intepreter->main_nspace.ptr(),
intepreter->main_nspace.ptr())))) {}
operator object() {
return result;
}
};
void python_interpreter_t::initialize()
{
TRACE_START(python_init, 1, "Initialized Python");
try {
DEBUG("python.interp", "Initializing Python");
Py_Initialize();
assert(Py_IsInitialized());
hack_system_paths();
object main_module = python::import("__main__");
if (! main_module)
throw_(std::runtime_error,
_("Python failed to initialize (couldn't find __main__)"));
main_nspace = extract<dict>(main_module.attr("__dict__"));
if (! main_nspace)
throw_(std::runtime_error,
_("Python failed to initialize (couldn't find __dict__)"));
python::detail::init_module("ledger", &initialize_for_python);
is_initialized = true;
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error, _("Python failed to initialize"));
}
TRACE_FINISH(python_init, 1);
}
void python_interpreter_t::hack_system_paths()
{
// Hack ledger.__path__ so it points to a real location
python::object sys_module = python::import("sys");
python::object sys_dict = sys_module.attr("__dict__");
python::list paths(sys_dict["path"]);
#if defined(DEBUG_ON)
bool path_initialized = false;
#endif
int n = python::extract<int>(paths.attr("__len__")());
for (int i = 0; i < n; i++) {
python::extract<std::string> str(paths[i]);
path pathname(str);
DEBUG("python.interp", "sys.path = " << pathname);
if (exists(pathname / "ledger" / "__init__.py")) {
if (python::object module_ledger = python::import("ledger")) {
DEBUG("python.interp",
"Setting ledger.__path__ = " << (pathname / "ledger"));
python::object ledger_dict = module_ledger.attr("__dict__");
python::list temp_list;
temp_list.append((pathname / "ledger").string());
ledger_dict["__path__"] = temp_list;
} else {
throw_(std::runtime_error,
_("Python failed to initialize (couldn't find ledger)"));
}
#if defined(DEBUG_ON)
path_initialized = true;
#endif
break;
}
}
#if defined(DEBUG_ON)
if (! path_initialized)
DEBUG("python.init",
"Ledger failed to find 'ledger/__init__.py' on the PYTHONPATH");
#endif
}
object python_interpreter_t::import_into_main(const string& str)
{
if (! is_initialized)
initialize();
try {
object mod = python::import(str.c_str());
if (! mod)
throw_(std::runtime_error,
_("Failed to import Python module %1") << str);
// Import all top-level entries directly into the main namespace
main_nspace.update(mod.attr("__dict__"));
return mod;
}
catch (const error_already_set&) {
PyErr_Print();
}
return object();
}
object python_interpreter_t::import_option(const string& str)
{
path file(str);
python::object sys_module = python::import("sys");
python::object sys_dict = sys_module.attr("__dict__");
python::list paths(sys_dict["path"]);
#if BOOST_VERSION >= 103700
paths.insert(0, file.parent_path().string());
sys_dict["path"] = paths;
string name = file.filename();
if (contains(name, ".py"))
name = file.stem();
#else // BOOST_VERSION >= 103700
paths.insert(0, file.branch_path().string());
sys_dict["path"] = paths;
string name = file.leaf();
#endif // BOOST_VERSION >= 103700
return python::import(python::str(name.c_str()));
}
object python_interpreter_t::eval(std::istream& in, py_eval_mode_t mode)
{
bool first = true;
string buffer;
buffer.reserve(4096);
while (! in.eof()) {
char buf[256];
in.getline(buf, 255);
if (buf[0] == '!')
break;
if (first)
first = false;
else
buffer += "\n";
buffer += buf;
}
if (! is_initialized)
initialize();
try {
int input_mode = -1;
switch (mode) {
case PY_EVAL_EXPR: input_mode = Py_eval_input; break;
case PY_EVAL_STMT: input_mode = Py_single_input; break;
case PY_EVAL_MULTI: input_mode = Py_file_input; break;
}
return python_run(this, buffer, input_mode);
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error, _("Failed to evaluate Python code"));
}
return object();
}
object python_interpreter_t::eval(const string& str, py_eval_mode_t mode)
{
if (! is_initialized)
initialize();
try {
int input_mode = -1;
switch (mode) {
case PY_EVAL_EXPR: input_mode = Py_eval_input; break;
case PY_EVAL_STMT: input_mode = Py_single_input; break;
case PY_EVAL_MULTI: input_mode = Py_file_input; break;
}
return python_run(this, str, input_mode);
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error, _("Failed to evaluate Python code"));
}
return object();
}
value_t python_interpreter_t::python_command(call_scope_t& args)
{
if (! is_initialized)
initialize();
char ** argv(new char *[args.size() + 1]);
argv[0] = new char[std::strlen(argv0) + 1];
std::strcpy(argv[0], argv0);
for (std::size_t i = 0; i < args.size(); i++) {
string arg = args[i].as_string();
argv[i + 1] = new char[arg.length() + 1];
std::strcpy(argv[i + 1], arg.c_str());
}
int status = 1;
try {
status = Py_Main(static_cast<int>(args.size()) + 1, argv);
}
catch (...) {
for (std::size_t i = 0; i < args.size() + 1; i++)
delete[] argv[i];
delete[] argv;
throw;
}
for (std::size_t i = 0; i < args.size() + 1; i++)
delete[] argv[i];
delete[] argv;
if (status != 0)
throw status;
return NULL_VALUE;
}
value_t python_interpreter_t::server_command(call_scope_t& args)
{
if (! is_initialized)
initialize();
python::object server_module;
try {
server_module = python::import("ledger.server");
if (! server_module)
throw_(std::runtime_error,
_("Could not import ledger.server; please check your PYTHONPATH"));
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error,
_("Could not import ledger.server; please check your PYTHONPATH"));
}
if (python::object main_function = server_module.attr("main")) {
functor_t func(main_function, "main");
try {
func(args);
}
catch (const error_already_set&) {
PyErr_Print();
throw_(std::runtime_error,
_("Error while invoking ledger.server's main() function"));
}
return true;
} else {
throw_(std::runtime_error,
_("The ledger.server module is missing its main() function!"));
}
return false;
}
option_t<python_interpreter_t> *
python_interpreter_t::lookup_option(const char * p)
{
switch (*p) {
case 'i':
OPT(import_);
break;
}
return NULL;
}
expr_t::ptr_op_t python_interpreter_t::lookup(const symbol_t::kind_t kind,
const string& name)
{
// Give our superclass first dibs on symbol definitions
if (expr_t::ptr_op_t op = session_t::lookup(kind, name))
return op;
switch (kind) {
case symbol_t::FUNCTION:
if (option_t<python_interpreter_t> * handler = lookup_option(name.c_str()))
return MAKE_OPT_FUNCTOR(python_interpreter_t, handler);
if (is_initialized && main_nspace.has_key(name.c_str())) {
DEBUG("python.interp", "Python lookup: " << name);
if (python::object obj = main_nspace.get(name.c_str()))
return WRAP_FUNCTOR(functor_t(obj, name));
}
break;
case symbol_t::OPTION:
if (option_t<python_interpreter_t> * handler = lookup_option(name.c_str()))
return MAKE_OPT_HANDLER(python_interpreter_t, handler);
break;
case symbol_t::PRECOMMAND: {
const char * p = name.c_str();
switch (*p) {
case 'p':
if (is_eq(p, "python"))
return MAKE_FUNCTOR(python_interpreter_t::python_command);
break;
case 's':
if (is_eq(p, "server"))
return MAKE_FUNCTOR(python_interpreter_t::server_command);
break;
}
}
default:
break;
}
return NULL;
}
namespace {
void append_value(list& lst, const value_t& value)
{
if (value.is_scope()) {
const scope_t * scope = value.as_scope();
if (const post_t * post = dynamic_cast<const post_t *>(scope))
lst.append(ptr(post));
else if (const xact_t * xact = dynamic_cast<const xact_t *>(scope))
lst.append(ptr(xact));
else if (const account_t * account =
dynamic_cast<const account_t *>(scope))
lst.append(ptr(account));
else if (const period_xact_t * period_xact =
dynamic_cast<const period_xact_t *>(scope))
lst.append(ptr(period_xact));
else if (const auto_xact_t * auto_xact =
dynamic_cast<const auto_xact_t *>(scope))
lst.append(ptr(auto_xact));
else
throw_(std::logic_error,
_("Cannot downcast scoped object to specific type"));
} else {
lst.append(value);
}
}
}
value_t python_interpreter_t::functor_t::operator()(call_scope_t& args)
{
try {
std::signal(SIGINT, SIG_DFL);
if (! PyCallable_Check(func.ptr())) {
extract<value_t> val(func);
std::signal(SIGINT, sigint_handler);
if (val.check())
return val();
return NULL_VALUE;
}
else if (args.size() > 0) {
list arglist;
// jww (2009-11-05): What about a single argument which is a sequence,
// rather than a sequence of arguments?
if (args.value().is_sequence())
foreach (const value_t& value, args.value().as_sequence())
append_value(arglist, value);
else
append_value(arglist, args.value());
if (PyObject * val =
PyObject_CallObject(func.ptr(), python::tuple(arglist).ptr())) {
extract<value_t> xval(val);
value_t result;
if (xval.check()) {
result = xval();
Py_DECREF(val);
} else {
Py_DECREF(val);
throw_(calc_error,
_("Could not evaluate Python variable '%1'") << name);
}
std::signal(SIGINT, sigint_handler);
return result;
}
else if (PyErr_Occurred()) {
PyErr_Print();
throw_(calc_error, _("Failed call to Python function '%1'") << name);
} else {
assert(false);
}
}
else {
std::signal(SIGINT, sigint_handler);
return call<value_t>(func.ptr());
}
}
catch (const error_already_set&) {
std::signal(SIGINT, sigint_handler);
PyErr_Print();
throw_(calc_error, _("Failed call to Python function '%1'") << name);
}
catch (...) {
std::signal(SIGINT, sigint_handler);
}
std::signal(SIGINT, sigint_handler);
return NULL_VALUE;
}
} // namespace ledger
<|endoftext|>
|
<commit_before>//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass lowers instrprof_increment intrinsics emitted by a frontend for
// profiling. It also builds the data structures and initialization code needed
// for updating execution counts and emitting the profile at runtime.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
using namespace llvm;
#define DEBUG_TYPE "instrprof"
namespace {
class InstrProfiling : public ModulePass {
public:
static char ID;
InstrProfiling() : ModulePass(ID) {}
InstrProfiling(const InstrProfOptions &Options)
: ModulePass(ID), Options(Options) {}
const char *getPassName() const override {
return "Frontend instrumentation-based coverage lowering";
}
bool runOnModule(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
}
private:
InstrProfOptions Options;
Module *M;
DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters;
std::vector<Value *> UsedVars;
bool isMachO() const {
return Triple(M->getTargetTriple()).isOSBinFormatMachO();
}
/// Get the section name for the counter variables.
StringRef getCountersSection() const {
return isMachO() ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
}
/// Get the section name for the name variables.
StringRef getNameSection() const {
return isMachO() ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
}
/// Get the section name for the profile data variables.
StringRef getDataSection() const {
return isMachO() ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
}
/// Get the section name for the coverage mapping data.
StringRef getCoverageSection() const {
return isMachO() ? "__DATA,__llvm_covmap" : "__llvm_covmap";
}
/// Replace instrprof_increment with an increment of the appropriate value.
void lowerIncrement(InstrProfIncrementInst *Inc);
/// Set up the section and uses for coverage data and its references.
void lowerCoverageData(GlobalVariable *CoverageData);
/// Get the region counters for an increment, creating them if necessary.
///
/// If the counter array doesn't yet exist, the profile data variables
/// referring to them will also be created.
GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc);
/// Emit runtime registration functions for each profile data variable.
void emitRegistration();
/// Emit the necessary plumbing to pull in the runtime initialization.
void emitRuntimeHook();
/// Add uses of our data variables and runtime hook.
void emitUses();
/// Create a static initializer for our data, on platforms that need it,
/// and for any profile output file that was specified.
void emitInitialization();
};
} // anonymous namespace
char InstrProfiling::ID = 0;
INITIALIZE_PASS(InstrProfiling, "instrprof",
"Frontend instrumentation-based coverage lowering.", false,
false)
ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) {
return new InstrProfiling(Options);
}
bool InstrProfiling::runOnModule(Module &M) {
bool MadeChange = false;
this->M = &M;
RegionCounters.clear();
UsedVars.clear();
for (Function &F : M)
for (BasicBlock &BB : F)
for (auto I = BB.begin(), E = BB.end(); I != E;)
if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) {
lowerIncrement(Inc);
MadeChange = true;
}
if (GlobalVariable *Coverage = M.getNamedGlobal("__llvm_coverage_mapping")) {
lowerCoverageData(Coverage);
MadeChange = true;
}
if (!MadeChange)
return false;
emitRegistration();
emitRuntimeHook();
emitUses();
emitInitialization();
return true;
}
void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
IRBuilder<> Builder(Inc->getParent(), *Inc);
uint64_t Index = Inc->getIndex()->getZExtValue();
Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
Value *Count = Builder.CreateLoad(Addr, "pgocount");
Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
Inc->eraseFromParent();
}
void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) {
CoverageData->setSection(getCoverageSection());
CoverageData->setAlignment(8);
Constant *Init = CoverageData->getInitializer();
// We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] }
// for some C. If not, the frontend's given us something broken.
assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map");
assert(isa<ConstantArray>(Init->getAggregateElement(4)) &&
"invalid function list in coverage map");
ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4));
for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) {
Constant *Record = Records->getOperand(I);
Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts();
assert(isa<GlobalVariable>(V) && "Missing reference to function name");
GlobalVariable *Name = cast<GlobalVariable>(V);
// If we have region counters for this name, we've already handled it.
auto It = RegionCounters.find(Name);
if (It != RegionCounters.end())
continue;
// Move the name variable to the right section.
Name->setSection(getNameSection());
Name->setAlignment(1);
}
}
/// Get the name of a profiling variable for a particular function.
static std::string getVarName(InstrProfIncrementInst *Inc, StringRef VarName) {
auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer());
StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
return ("__llvm_profile_" + VarName + "_" + Name).str();
}
GlobalVariable *
InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
GlobalVariable *Name = Inc->getName();
auto It = RegionCounters.find(Name);
if (It != RegionCounters.end())
return It->second;
// Move the name variable to the right section. Make sure it is placed in the
// same comdat as its associated function. Otherwise, we may get multiple
// counters for the same function in certain cases.
Function *Fn = Inc->getParent()->getParent();
Name->setSection(getNameSection());
Name->setAlignment(1);
Name->setComdat(Fn->getComdat());
uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
LLVMContext &Ctx = M->getContext();
ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
// Create the counters variable.
auto *Counters = new GlobalVariable(*M, CounterTy, false, Name->getLinkage(),
Constant::getNullValue(CounterTy),
getVarName(Inc, "counters"));
Counters->setVisibility(Name->getVisibility());
Counters->setSection(getCountersSection());
Counters->setAlignment(8);
Counters->setComdat(Fn->getComdat());
RegionCounters[Inc->getName()] = Counters;
// Create data variable.
auto *NameArrayTy = Name->getType()->getPointerElementType();
auto *Int32Ty = Type::getInt32Ty(Ctx);
auto *Int64Ty = Type::getInt64Ty(Ctx);
auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
auto *Int64PtrTy = Type::getInt64PtrTy(Ctx);
Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy};
auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Constant *DataVals[] = {
ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()),
ConstantInt::get(Int32Ty, NumCounters),
ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()),
ConstantExpr::getBitCast(Name, Int8PtrTy),
ConstantExpr::getBitCast(Counters, Int64PtrTy)};
auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(),
ConstantStruct::get(DataTy, DataVals),
getVarName(Inc, "data"));
Data->setVisibility(Name->getVisibility());
Data->setSection(getDataSection());
Data->setAlignment(8);
Data->setComdat(Fn->getComdat());
// Mark the data variable as used so that it isn't stripped out.
UsedVars.push_back(Data);
return Counters;
}
void InstrProfiling::emitRegistration() {
// Don't do this for Darwin. compiler-rt uses linker magic.
if (Triple(M->getTargetTriple()).isOSDarwin())
return;
// Construct the function.
auto *VoidTy = Type::getVoidTy(M->getContext());
auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
auto *RegisterFTy = FunctionType::get(VoidTy, false);
auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
"__llvm_profile_register_functions", M);
RegisterF->setUnnamedAddr(true);
if (Options.NoRedZone)
RegisterF->addFnAttr(Attribute::NoRedZone);
auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
auto *RuntimeRegisterF =
Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
"__llvm_profile_register_function", M);
IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
for (Value *Data : UsedVars)
IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
IRB.CreateRetVoid();
}
void InstrProfiling::emitRuntimeHook() {
const char *const RuntimeVarName = "__llvm_profile_runtime";
const char *const RuntimeUserName = "__llvm_profile_runtime_user";
// If the module's provided its own runtime, we don't need to do anything.
if (M->getGlobalVariable(RuntimeVarName))
return;
// Declare an external variable that will pull in the runtime initialization.
auto *Int32Ty = Type::getInt32Ty(M->getContext());
auto *Var =
new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
nullptr, RuntimeVarName);
// Make a function that uses it.
auto *User =
Function::Create(FunctionType::get(Int32Ty, false),
GlobalValue::LinkOnceODRLinkage, RuntimeUserName, M);
User->addFnAttr(Attribute::NoInline);
if (Options.NoRedZone)
User->addFnAttr(Attribute::NoRedZone);
User->setVisibility(GlobalValue::HiddenVisibility);
IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
auto *Load = IRB.CreateLoad(Var);
IRB.CreateRet(Load);
// Mark the user variable as used so that it isn't stripped out.
UsedVars.push_back(User);
}
void InstrProfiling::emitUses() {
if (UsedVars.empty())
return;
GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
std::vector<Constant *> MergedVars;
if (LLVMUsed) {
// Collect the existing members of llvm.used.
ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
MergedVars.push_back(Inits->getOperand(I));
LLVMUsed->eraseFromParent();
}
Type *i8PTy = Type::getInt8PtrTy(M->getContext());
// Add uses for our data.
for (auto *Value : UsedVars)
MergedVars.push_back(
ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
// Recreate llvm.used.
ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
LLVMUsed =
new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
ConstantArray::get(ATy, MergedVars), "llvm.used");
LLVMUsed->setSection("llvm.metadata");
}
void InstrProfiling::emitInitialization() {
std::string InstrProfileOutput = Options.InstrProfileOutput;
Constant *RegisterF = M->getFunction("__llvm_profile_register_functions");
if (!RegisterF && InstrProfileOutput.empty())
return;
// Create the initialization function.
auto *VoidTy = Type::getVoidTy(M->getContext());
auto *F =
Function::Create(FunctionType::get(VoidTy, false),
GlobalValue::InternalLinkage, "__llvm_profile_init", M);
F->setUnnamedAddr(true);
F->addFnAttr(Attribute::NoInline);
if (Options.NoRedZone)
F->addFnAttr(Attribute::NoRedZone);
// Add the basic block and the necessary calls.
IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
if (RegisterF)
IRB.CreateCall(RegisterF, {});
if (!InstrProfileOutput.empty()) {
auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
auto *SetNameF =
Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
"__llvm_profile_override_default_filename", M);
// Create variable for profile name
Constant *ProfileNameConst =
ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
GlobalVariable *ProfileName =
new GlobalVariable(*M, ProfileNameConst->getType(), true,
GlobalValue::PrivateLinkage, ProfileNameConst);
IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
}
IRB.CreateRetVoid();
appendToGlobalCtors(*M, F, 0);
}
<commit_msg>Tidy comment.<commit_after>//===-- InstrProfiling.cpp - Frontend instrumentation based profiling -----===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass lowers instrprof_increment intrinsics emitted by a frontend for
// profiling. It also builds the data structures and initialization code needed
// for updating execution counts and emitting the profile at runtime.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/Triple.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
using namespace llvm;
#define DEBUG_TYPE "instrprof"
namespace {
class InstrProfiling : public ModulePass {
public:
static char ID;
InstrProfiling() : ModulePass(ID) {}
InstrProfiling(const InstrProfOptions &Options)
: ModulePass(ID), Options(Options) {}
const char *getPassName() const override {
return "Frontend instrumentation-based coverage lowering";
}
bool runOnModule(Module &M) override;
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
}
private:
InstrProfOptions Options;
Module *M;
DenseMap<GlobalVariable *, GlobalVariable *> RegionCounters;
std::vector<Value *> UsedVars;
bool isMachO() const {
return Triple(M->getTargetTriple()).isOSBinFormatMachO();
}
/// Get the section name for the counter variables.
StringRef getCountersSection() const {
return isMachO() ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
}
/// Get the section name for the name variables.
StringRef getNameSection() const {
return isMachO() ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
}
/// Get the section name for the profile data variables.
StringRef getDataSection() const {
return isMachO() ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
}
/// Get the section name for the coverage mapping data.
StringRef getCoverageSection() const {
return isMachO() ? "__DATA,__llvm_covmap" : "__llvm_covmap";
}
/// Replace instrprof_increment with an increment of the appropriate value.
void lowerIncrement(InstrProfIncrementInst *Inc);
/// Set up the section and uses for coverage data and its references.
void lowerCoverageData(GlobalVariable *CoverageData);
/// Get the region counters for an increment, creating them if necessary.
///
/// If the counter array doesn't yet exist, the profile data variables
/// referring to them will also be created.
GlobalVariable *getOrCreateRegionCounters(InstrProfIncrementInst *Inc);
/// Emit runtime registration functions for each profile data variable.
void emitRegistration();
/// Emit the necessary plumbing to pull in the runtime initialization.
void emitRuntimeHook();
/// Add uses of our data variables and runtime hook.
void emitUses();
/// Create a static initializer for our data, on platforms that need it,
/// and for any profile output file that was specified.
void emitInitialization();
};
} // anonymous namespace
char InstrProfiling::ID = 0;
INITIALIZE_PASS(InstrProfiling, "instrprof",
"Frontend instrumentation-based coverage lowering.", false,
false)
ModulePass *llvm::createInstrProfilingPass(const InstrProfOptions &Options) {
return new InstrProfiling(Options);
}
bool InstrProfiling::runOnModule(Module &M) {
bool MadeChange = false;
this->M = &M;
RegionCounters.clear();
UsedVars.clear();
for (Function &F : M)
for (BasicBlock &BB : F)
for (auto I = BB.begin(), E = BB.end(); I != E;)
if (auto *Inc = dyn_cast<InstrProfIncrementInst>(I++)) {
lowerIncrement(Inc);
MadeChange = true;
}
if (GlobalVariable *Coverage = M.getNamedGlobal("__llvm_coverage_mapping")) {
lowerCoverageData(Coverage);
MadeChange = true;
}
if (!MadeChange)
return false;
emitRegistration();
emitRuntimeHook();
emitUses();
emitInitialization();
return true;
}
void InstrProfiling::lowerIncrement(InstrProfIncrementInst *Inc) {
GlobalVariable *Counters = getOrCreateRegionCounters(Inc);
IRBuilder<> Builder(Inc->getParent(), *Inc);
uint64_t Index = Inc->getIndex()->getZExtValue();
Value *Addr = Builder.CreateConstInBoundsGEP2_64(Counters, 0, Index);
Value *Count = Builder.CreateLoad(Addr, "pgocount");
Count = Builder.CreateAdd(Count, Builder.getInt64(1));
Inc->replaceAllUsesWith(Builder.CreateStore(Count, Addr));
Inc->eraseFromParent();
}
void InstrProfiling::lowerCoverageData(GlobalVariable *CoverageData) {
CoverageData->setSection(getCoverageSection());
CoverageData->setAlignment(8);
Constant *Init = CoverageData->getInitializer();
// We're expecting { i32, i32, i32, i32, [n x { i8*, i32, i32 }], [m x i8] }
// for some C. If not, the frontend's given us something broken.
assert(Init->getNumOperands() == 6 && "bad number of fields in coverage map");
assert(isa<ConstantArray>(Init->getAggregateElement(4)) &&
"invalid function list in coverage map");
ConstantArray *Records = cast<ConstantArray>(Init->getAggregateElement(4));
for (unsigned I = 0, E = Records->getNumOperands(); I < E; ++I) {
Constant *Record = Records->getOperand(I);
Value *V = const_cast<Value *>(Record->getOperand(0))->stripPointerCasts();
assert(isa<GlobalVariable>(V) && "Missing reference to function name");
GlobalVariable *Name = cast<GlobalVariable>(V);
// If we have region counters for this name, we've already handled it.
auto It = RegionCounters.find(Name);
if (It != RegionCounters.end())
continue;
// Move the name variable to the right section.
Name->setSection(getNameSection());
Name->setAlignment(1);
}
}
/// Get the name of a profiling variable for a particular function.
static std::string getVarName(InstrProfIncrementInst *Inc, StringRef VarName) {
auto *Arr = cast<ConstantDataArray>(Inc->getName()->getInitializer());
StringRef Name = Arr->isCString() ? Arr->getAsCString() : Arr->getAsString();
return ("__llvm_profile_" + VarName + "_" + Name).str();
}
GlobalVariable *
InstrProfiling::getOrCreateRegionCounters(InstrProfIncrementInst *Inc) {
GlobalVariable *Name = Inc->getName();
auto It = RegionCounters.find(Name);
if (It != RegionCounters.end())
return It->second;
// Move the name variable to the right section. Make sure it is placed in the
// same comdat as its associated function. Otherwise, we may get multiple
// counters for the same function in certain cases.
Function *Fn = Inc->getParent()->getParent();
Name->setSection(getNameSection());
Name->setAlignment(1);
Name->setComdat(Fn->getComdat());
uint64_t NumCounters = Inc->getNumCounters()->getZExtValue();
LLVMContext &Ctx = M->getContext();
ArrayType *CounterTy = ArrayType::get(Type::getInt64Ty(Ctx), NumCounters);
// Create the counters variable.
auto *Counters = new GlobalVariable(*M, CounterTy, false, Name->getLinkage(),
Constant::getNullValue(CounterTy),
getVarName(Inc, "counters"));
Counters->setVisibility(Name->getVisibility());
Counters->setSection(getCountersSection());
Counters->setAlignment(8);
Counters->setComdat(Fn->getComdat());
RegionCounters[Inc->getName()] = Counters;
// Create data variable.
auto *NameArrayTy = Name->getType()->getPointerElementType();
auto *Int32Ty = Type::getInt32Ty(Ctx);
auto *Int64Ty = Type::getInt64Ty(Ctx);
auto *Int8PtrTy = Type::getInt8PtrTy(Ctx);
auto *Int64PtrTy = Type::getInt64PtrTy(Ctx);
Type *DataTypes[] = {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy};
auto *DataTy = StructType::get(Ctx, makeArrayRef(DataTypes));
Constant *DataVals[] = {
ConstantInt::get(Int32Ty, NameArrayTy->getArrayNumElements()),
ConstantInt::get(Int32Ty, NumCounters),
ConstantInt::get(Int64Ty, Inc->getHash()->getZExtValue()),
ConstantExpr::getBitCast(Name, Int8PtrTy),
ConstantExpr::getBitCast(Counters, Int64PtrTy)};
auto *Data = new GlobalVariable(*M, DataTy, true, Name->getLinkage(),
ConstantStruct::get(DataTy, DataVals),
getVarName(Inc, "data"));
Data->setVisibility(Name->getVisibility());
Data->setSection(getDataSection());
Data->setAlignment(8);
Data->setComdat(Fn->getComdat());
// Mark the data variable as used so that it isn't stripped out.
UsedVars.push_back(Data);
return Counters;
}
void InstrProfiling::emitRegistration() {
// Don't do this for Darwin. compiler-rt uses linker magic.
if (Triple(M->getTargetTriple()).isOSDarwin())
return;
// Construct the function.
auto *VoidTy = Type::getVoidTy(M->getContext());
auto *VoidPtrTy = Type::getInt8PtrTy(M->getContext());
auto *RegisterFTy = FunctionType::get(VoidTy, false);
auto *RegisterF = Function::Create(RegisterFTy, GlobalValue::InternalLinkage,
"__llvm_profile_register_functions", M);
RegisterF->setUnnamedAddr(true);
if (Options.NoRedZone)
RegisterF->addFnAttr(Attribute::NoRedZone);
auto *RuntimeRegisterTy = FunctionType::get(VoidTy, VoidPtrTy, false);
auto *RuntimeRegisterF =
Function::Create(RuntimeRegisterTy, GlobalVariable::ExternalLinkage,
"__llvm_profile_register_function", M);
IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", RegisterF));
for (Value *Data : UsedVars)
IRB.CreateCall(RuntimeRegisterF, IRB.CreateBitCast(Data, VoidPtrTy));
IRB.CreateRetVoid();
}
void InstrProfiling::emitRuntimeHook() {
const char *const RuntimeVarName = "__llvm_profile_runtime";
const char *const RuntimeUserName = "__llvm_profile_runtime_user";
// If the module's provided its own runtime, we don't need to do anything.
if (M->getGlobalVariable(RuntimeVarName))
return;
// Declare an external variable that will pull in the runtime initialization.
auto *Int32Ty = Type::getInt32Ty(M->getContext());
auto *Var =
new GlobalVariable(*M, Int32Ty, false, GlobalValue::ExternalLinkage,
nullptr, RuntimeVarName);
// Make a function that uses it.
auto *User =
Function::Create(FunctionType::get(Int32Ty, false),
GlobalValue::LinkOnceODRLinkage, RuntimeUserName, M);
User->addFnAttr(Attribute::NoInline);
if (Options.NoRedZone)
User->addFnAttr(Attribute::NoRedZone);
User->setVisibility(GlobalValue::HiddenVisibility);
IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", User));
auto *Load = IRB.CreateLoad(Var);
IRB.CreateRet(Load);
// Mark the user variable as used so that it isn't stripped out.
UsedVars.push_back(User);
}
void InstrProfiling::emitUses() {
if (UsedVars.empty())
return;
GlobalVariable *LLVMUsed = M->getGlobalVariable("llvm.used");
std::vector<Constant *> MergedVars;
if (LLVMUsed) {
// Collect the existing members of llvm.used.
ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
for (unsigned I = 0, E = Inits->getNumOperands(); I != E; ++I)
MergedVars.push_back(Inits->getOperand(I));
LLVMUsed->eraseFromParent();
}
Type *i8PTy = Type::getInt8PtrTy(M->getContext());
// Add uses for our data.
for (auto *Value : UsedVars)
MergedVars.push_back(
ConstantExpr::getBitCast(cast<Constant>(Value), i8PTy));
// Recreate llvm.used.
ArrayType *ATy = ArrayType::get(i8PTy, MergedVars.size());
LLVMUsed =
new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
ConstantArray::get(ATy, MergedVars), "llvm.used");
LLVMUsed->setSection("llvm.metadata");
}
void InstrProfiling::emitInitialization() {
std::string InstrProfileOutput = Options.InstrProfileOutput;
Constant *RegisterF = M->getFunction("__llvm_profile_register_functions");
if (!RegisterF && InstrProfileOutput.empty())
return;
// Create the initialization function.
auto *VoidTy = Type::getVoidTy(M->getContext());
auto *F =
Function::Create(FunctionType::get(VoidTy, false),
GlobalValue::InternalLinkage, "__llvm_profile_init", M);
F->setUnnamedAddr(true);
F->addFnAttr(Attribute::NoInline);
if (Options.NoRedZone)
F->addFnAttr(Attribute::NoRedZone);
// Add the basic block and the necessary calls.
IRBuilder<> IRB(BasicBlock::Create(M->getContext(), "", F));
if (RegisterF)
IRB.CreateCall(RegisterF, {});
if (!InstrProfileOutput.empty()) {
auto *Int8PtrTy = Type::getInt8PtrTy(M->getContext());
auto *SetNameTy = FunctionType::get(VoidTy, Int8PtrTy, false);
auto *SetNameF =
Function::Create(SetNameTy, GlobalValue::ExternalLinkage,
"__llvm_profile_override_default_filename", M);
// Create variable for profile name.
Constant *ProfileNameConst =
ConstantDataArray::getString(M->getContext(), InstrProfileOutput, true);
GlobalVariable *ProfileName =
new GlobalVariable(*M, ProfileNameConst->getType(), true,
GlobalValue::PrivateLinkage, ProfileNameConst);
IRB.CreateCall(SetNameF, IRB.CreatePointerCast(ProfileName, Int8PtrTy));
}
IRB.CreateRetVoid();
appendToGlobalCtors(*M, F, 0);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlencryption_nssimpl.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 17:35:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLENCRYPTION_NSSIMPL_HXX_
#define _XMLENCRYPTION_NSSIMPL_HXX_
#ifndef _SAL_CONFIG_H_
#include <sal/config.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HPP_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSECVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLENCRYPTION_HPP_
#include <com/sun/star/xml/crypto/XXMLEncryption.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLENCRYPTIONTEMPLATE_HPP_
#include <com/sun/star/xml/crypto/XXMLEncryptionTemplate.hpp>
#endif
#ifndef _COM_SUN_STAR_XML_CRYPTO_XXMLSECURITYCONTEXT_HPP_
#include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
#endif
class XMLEncryption_NssImpl : public ::cppu::WeakImplHelper3<
::com::sun::star::xml::crypto::XXMLEncryption ,
::com::sun::star::lang::XInitialization ,
::com::sun::star::lang::XServiceInfo >
{
private :
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager ;
public :
XMLEncryption_NssImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aFactory ) ;
virtual ~XMLEncryption_NssImpl() ;
//Methods from XXMLEncryption
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate > SAL_CALL encrypt(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate >& aTemplate ,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment >& aEnvironment)
// ) throw( ::com::sun::star::uno::Exception , ::com::sun::star::uno::RuntimeException ) ;
throw ( com::sun::star::xml::crypto::XMLEncryptionException ,
com::sun::star::uno::SecurityException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate > SAL_CALL decrypt(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate >& aTemplate ,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLSecurityContext >& aContext
) throw( com::sun::star::xml::crypto::XMLEncryptionException ,
com::sun::star::uno::SecurityException) ;
//Methods from XInitialization
virtual void SAL_CALL initialize(
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments
) throw( ::com::sun::star::uno::Exception , ::com::sun::star::uno::RuntimeException ) ;
//Methods from XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ) ;
virtual sal_Bool SAL_CALL supportsService(
const ::rtl::OUString& ServiceName
) throw( ::com::sun::star::uno::RuntimeException ) ;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ) ;
//Helper for XServiceInfo
static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getSupportedServiceNames() ;
static ::rtl::OUString impl_getImplementationName() throw( ::com::sun::star::uno::RuntimeException ) ;
//Helper for registry
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager ) throw( ::com::sun::star::uno::RuntimeException ) ;
static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager ) ;
} ;
#endif // _XMLENCRYPTION_NSSIMPL_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.4.190); FILE MERGED 2008/04/01 16:11:08 thb 1.4.190.3: #i85898# Stripping all external header guards 2008/04/01 13:06:27 thb 1.4.190.2: #i85898# Stripping all external header guards 2008/03/31 16:31:05 rt 1.4.190.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlencryption_nssimpl.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XMLENCRYPTION_NSSIMPL_HXX_
#define _XMLENCRYPTION_NSSIMPL_HXX_
#include <sal/config.h>
#include <rtl/ustring.hxx>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implbase3.hxx>
#include <com/sun/star/uno/Exception.hpp>
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HPP_
#include <com/sun/star/uno/Reference.hxx>
#endif
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#ifndef _COM_SUN_STAR_LANG_XSECVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/xml/crypto/XXMLEncryption.hpp>
#include <com/sun/star/xml/crypto/XXMLEncryptionTemplate.hpp>
#include <com/sun/star/xml/crypto/XXMLSecurityContext.hpp>
class XMLEncryption_NssImpl : public ::cppu::WeakImplHelper3<
::com::sun::star::xml::crypto::XXMLEncryption ,
::com::sun::star::lang::XInitialization ,
::com::sun::star::lang::XServiceInfo >
{
private :
::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceManager ;
public :
XMLEncryption_NssImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aFactory ) ;
virtual ~XMLEncryption_NssImpl() ;
//Methods from XXMLEncryption
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate > SAL_CALL encrypt(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate >& aTemplate ,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment >& aEnvironment)
// ) throw( ::com::sun::star::uno::Exception , ::com::sun::star::uno::RuntimeException ) ;
throw ( com::sun::star::xml::crypto::XMLEncryptionException ,
com::sun::star::uno::SecurityException);
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate > SAL_CALL decrypt(
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLEncryptionTemplate >& aTemplate ,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XXMLSecurityContext >& aContext
) throw( com::sun::star::xml::crypto::XMLEncryptionException ,
com::sun::star::uno::SecurityException) ;
//Methods from XInitialization
virtual void SAL_CALL initialize(
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments
) throw( ::com::sun::star::uno::Exception , ::com::sun::star::uno::RuntimeException ) ;
//Methods from XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ) ;
virtual sal_Bool SAL_CALL supportsService(
const ::rtl::OUString& ServiceName
) throw( ::com::sun::star::uno::RuntimeException ) ;
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ) ;
//Helper for XServiceInfo
static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getSupportedServiceNames() ;
static ::rtl::OUString impl_getImplementationName() throw( ::com::sun::star::uno::RuntimeException ) ;
//Helper for registry
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager ) throw( ::com::sun::star::uno::RuntimeException ) ;
static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& aServiceManager ) ;
} ;
#endif // _XMLENCRYPTION_NSSIMPL_HXX_
<|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 DelayCalc& dc, const NodeId node_id);
template<class DelayCalc>
void do_required_traverse_node(const TimingGraph& tg, 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 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);
};
/*
* 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(node_type == NodeType::CONSTANT_GEN_SOURCE) 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::INPAD_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
*/
auto node_type = tg.node_type(node_id);
TATUM_ASSERT(node_type == NodeType::OUTPAD_SINK || node_type == NodeType::FF_SINK);
//Sinks corresponding to FF sinks will have propagated clock tags,
//while those corresponding to outpads will not.
if(node_clock_tags.empty()) {
//Initialize the outpad's clock tags based on the specified 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 << " " << node_type << " has no incomming clock tags, and no output constraint. No required time will be calculated\n";
#if 1
//Debug trace-back
//TODO: remove debug code!
if(node_type == NodeType::FF_SINK) {
std::cerr << "\tClock path:\n";
int i = 0;
NodeId curr_node = node_id;
while(tg.node_type(curr_node) != NodeType::INPAD_SOURCE &&
tg.node_type(curr_node) != NodeType::CLOCK_SOURCE &&
tg.node_type(curr_node) != NodeType::CONSTANT_GEN_SOURCE &&
i < 100) {
//Look throught the fanin for a clock or other node to follow
//
//Typically the first hop from node_id will be to either the IPIN or CLOCK pin
//the following preferentially prefers the CLOCK pin to show the clock path
EdgeId best_edge;
for(auto edge_id : tg.node_in_edges(curr_node)) {
if(!best_edge) {
best_edge = edge_id;
}
NodeId src_node = tg.edge_src_node(edge_id);
auto src_node_type = tg.node_type(src_node);
if(src_node_type == NodeType::FF_CLOCK) {
best_edge = edge_id;
}
}
//Step back
curr_node = tg.edge_src_node(best_edge);
auto curr_node_type = tg.node_type(curr_node);
std::cerr << "\tNode " << curr_node << " Type: " << curr_node_type << "\n";
if(++i >= 100) {
std::cerr << "\tStopping backtrace\n";
}
}
}
#endif
} 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 stage both FF and outpad sinks now have the relevant clock
//tags and we can process them equivalently
//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 DelayCalc& dc, NodeId node_id) {
//Pull from upstream sources to current node
for(EdgeId edge_id : tg.node_in_edges(node_id)) {
do_arrival_traverse_edge(tg, dc, node_id, edge_id);
}
}
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_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);
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);
/*
* Clock tags
*/
if(tg.node_type(src_node_id) != NodeType::FF_SOURCE) {
//We do not propagate clock tags from an FF_SOURCE.
//The clock arrival will have already been converted to a
//data tag when the previous level was traversed.
const TimingTags& src_clk_tags = ops_.get_clock_tags(src_node_id);
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(tg.node_type(node_id) == NodeType::FF_SOURCE) {
//We are traversing a clock to data launch edge.
//
//We convert the clock arrival time to a data
//arrival time at this node (since the clock
//arrival launches the data).
//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
*/
const TimingTags& src_data_tags = ops_.get_data_tags(src_node_id);
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 DelayCalc& dc, const NodeId node_id) {
//Pull from downstream sinks to current node
//We don't propagate required times past FF_CLOCK nodes,
//since anything upstream is part of the clock network
//
//TODO: if performing optimization on a clock network this may actually be useful
if(tg.node_type(node_id) == NodeType::FF_CLOCK) {
return;
}
//Each back-edge from down stream 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);
}
}
}
}} //namepsace
#endif
<commit_msg>Remove most type-checks from required time traversal<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 DelayCalc& dc, const NodeId node_id);
template<class DelayCalc>
void do_required_traverse_node(const TimingGraph& tg, 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 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);
};
/*
* 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(node_type == NodeType::CONSTANT_GEN_SOURCE) 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::INPAD_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
*/
auto node_type = tg.node_type(node_id);
TATUM_ASSERT(node_type == NodeType::OUTPAD_SINK || node_type == NodeType::FF_SINK);
//Sinks corresponding to FF sinks will have propagated clock tags,
//while those corresponding to outpads will not.
if(node_clock_tags.empty()) {
//Initialize the outpad's clock tags based on the specified 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 << " " << node_type << " has no incomming clock tags, and no output constraint. No required time will be calculated\n";
#if 1
//Debug trace-back
//TODO: remove debug code!
if(node_type == NodeType::FF_SINK) {
std::cerr << "\tClock path:\n";
int i = 0;
NodeId curr_node = node_id;
while(tg.node_type(curr_node) != NodeType::INPAD_SOURCE &&
tg.node_type(curr_node) != NodeType::CLOCK_SOURCE &&
tg.node_type(curr_node) != NodeType::CONSTANT_GEN_SOURCE &&
i < 100) {
//Look throught the fanin for a clock or other node to follow
//
//Typically the first hop from node_id will be to either the IPIN or CLOCK pin
//the following preferentially prefers the CLOCK pin to show the clock path
EdgeId best_edge;
for(auto edge_id : tg.node_in_edges(curr_node)) {
if(!best_edge) {
best_edge = edge_id;
}
NodeId src_node = tg.edge_src_node(edge_id);
auto src_node_type = tg.node_type(src_node);
if(src_node_type == NodeType::FF_CLOCK) {
best_edge = edge_id;
}
}
//Step back
curr_node = tg.edge_src_node(best_edge);
auto curr_node_type = tg.node_type(curr_node);
std::cerr << "\tNode " << curr_node << " Type: " << curr_node_type << "\n";
if(++i >= 100) {
std::cerr << "\tStopping backtrace\n";
}
}
}
#endif
} 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 stage both FF and outpad sinks now have the relevant clock
//tags and we can process them equivalently
//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 DelayCalc& dc, NodeId node_id) {
//Pull from upstream sources to current node
for(EdgeId edge_id : tg.node_in_edges(node_id)) {
do_arrival_traverse_edge(tg, dc, node_id, edge_id);
}
}
template<class AnalysisOps>
template<class DelayCalc>
void CommonAnalysisVisitor<AnalysisOps>::do_arrival_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);
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(src_data_tags.empty()) {
//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(tg.node_type(node_id) == NodeType::FF_SOURCE) { //FIXME: Should be any source type
//We are traversing a clock to data launch edge.
//
//We convert the clock arrival time to a data
//arrival time at this node (since the clock
//arrival launches the data).
//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 DelayCalc& dc, const NodeId node_id) {
//Pull from downstream sinks to current node
//Each back-edge from down stream 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);
}
}
}
}} //namepsace
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_iface.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:01:48 $
*
* 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 ADC_UIDL_PE_IFACE_HXX
#define ADC_UIDL_PE_IFACE_HXX
// USED SERVICES
// BASE CLASSES
#include <s2_luidl/parsenv2.hxx>
#include <s2_luidl/pestate.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
class Interface;
}
}
namespace csi
{
namespace uidl
{
class PE_Function;
class PE_Attribute;
class PE_Type;
class PE_Interface : public UnoIDL_PE,
public ParseEnvState
{
public:
PE_Interface();
virtual ~PE_Interface();
virtual void EstablishContacts(
UnoIDL_PE * io_pParentPE,
ary::n22::Repository & io_rRepository,
TokenProcessing_Result &
o_rResult );
virtual void ProcessToken(
const Token & i_rToken );
virtual void Process_MetaType(
const TokMetaType & i_rToken );
virtual void Process_Identifier(
const TokIdentifier &
i_rToken );
virtual void Process_Punctuation(
const TokPunctuation &
i_rToken );
virtual void Process_NameSeparator();
virtual void Process_BuiltInType(
const TokBuiltInType &
i_rToken );
virtual void Process_TypeModifier(
const TokTypeModifier &
i_rToken );
virtual void Process_Stereotype(
const TokStereotype &
i_rToken );
virtual void Process_Default();
private:
enum E_State /// @ATTENTION Do not change existing values (except of e_STATES_MAX) !!! Else array-indices will break.
{
e_none = 0,
need_uik,
uik,
need_ident,
ident,
need_interface,
need_name,
wait_for_base,
in_base, // in header, after ":"
need_curlbr_open,
e_std,
in_function,
in_attribute,
need_finish,
in_base_interface, // in body, after "interface"
e_STATES_MAX
};
enum E_TokenType /// @ATTENTION Do not change existing values (except of tt_MAX) !!! Else array-indices will break.
{
tt_metatype = 0,
tt_identifier = 1,
tt_punctuation = 2,
tt_startoftype = 3,
tt_stereotype = 4,
tt_MAX
};
typedef void (PE_Interface::*F_TOK)(const char *);
void On_need_uik_MetaType(const char * i_sText);
void On_uik_Identifier(const char * i_sText);
void On_uik_Punctuation(const char * i_sText);
void On_need_ident_MetaType(const char * i_sText);
void On_ident_Identifier(const char * i_sText);
void On_ident_Punctuation(const char * i_sText);
void On_need_interface_MetaType(const char * i_sText);
void On_need_name_Identifer(const char * i_sText);
void On_wait_for_base_Punctuation(const char * i_sText);
void On_need_curlbr_open_Punctuation(const char * i_sText);
void On_std_Metatype(const char * i_sText);
void On_std_Punctuation(const char * i_sText);
void On_std_Stereotype(const char * i_sText);
void On_std_GotoFunction(const char * i_sText);
void On_std_GotoAttribute(const char * i_sText);
void On_std_GotoBaseInterface(const char * i_sText);
void On_need_finish_Punctuation(const char * i_sText);
void On_Default(const char * i_sText);
void CallHandler(
const char * i_sTokenText,
E_TokenType i_eTokenType );
virtual void InitData();
virtual void TransferData();
virtual void ReceiveData();
virtual UnoIDL_PE & MyPE();
void store_Interface();
// DATA
static F_TOK aDispatcher[e_STATES_MAX][tt_MAX];
E_State eState;
String sData_Name;
bool bIsPreDeclaration;
ary::idl::Interface *
pCurInterface;
ary::idl::Ce_id nCurInterface;
Dyn<PE_Function> pPE_Function;
Dyn<PE_Attribute> pPE_Attribute;
Dyn<PE_Type> pPE_Type;
ary::idl::Type_id nCurParsed_Base;
bool bOptional;
};
// IMPLEMENTATION
} // namespace uidl
} // namespace csi
#endif
<commit_msg>INTEGRATION: CWS adc16 (1.4.48); FILE MERGED 2007/07/27 12:05:51 np 1.4.48.1: #i78740#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pe_iface.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-07-31 16:10:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef ADC_UIDL_PE_IFACE_HXX
#define ADC_UIDL_PE_IFACE_HXX
// USED SERVICES
// BASE CLASSES
#include <s2_luidl/parsenv2.hxx>
#include <s2_luidl/pestate.hxx>
// COMPONENTS
// PARAMETERS
namespace ary
{
namespace idl
{
class Interface;
}
}
namespace csi
{
namespace uidl
{
class PE_Function;
class PE_Attribute;
class PE_Type;
class PE_Interface : public UnoIDL_PE,
public ParseEnvState
{
public:
PE_Interface();
virtual ~PE_Interface();
virtual void EstablishContacts(
UnoIDL_PE * io_pParentPE,
ary::n22::Repository & io_rRepository,
TokenProcessing_Result &
o_rResult );
virtual void ProcessToken(
const Token & i_rToken );
virtual void Process_MetaType(
const TokMetaType & i_rToken );
virtual void Process_Identifier(
const TokIdentifier &
i_rToken );
virtual void Process_Punctuation(
const TokPunctuation &
i_rToken );
virtual void Process_NameSeparator();
virtual void Process_BuiltInType(
const TokBuiltInType &
i_rToken );
virtual void Process_TypeModifier(
const TokTypeModifier &
i_rToken );
virtual void Process_Stereotype(
const TokStereotype &
i_rToken );
virtual void Process_Default();
private:
enum E_State /// @ATTENTION Do not change existing values (except of e_STATES_MAX) !!! Else array-indices will break.
{
e_none = 0,
need_uik,
uik,
need_ident,
ident,
need_interface,
need_name,
wait_for_base,
in_base, // in header, after ":"
need_curlbr_open,
e_std,
in_function,
in_attribute,
need_finish,
in_base_interface, // in body, after "interface"
e_STATES_MAX
};
enum E_TokenType /// @ATTENTION Do not change existing values (except of tt_MAX) !!! Else array-indices will break.
{
tt_metatype = 0,
tt_identifier = 1,
tt_punctuation = 2,
tt_startoftype = 3,
tt_stereotype = 4,
tt_MAX
};
typedef void (PE_Interface::*F_TOK)(const char *);
void On_need_uik_MetaType(const char * i_sText);
void On_uik_Identifier(const char * i_sText);
void On_uik_Punctuation(const char * i_sText);
void On_need_ident_MetaType(const char * i_sText);
void On_ident_Identifier(const char * i_sText);
void On_ident_Punctuation(const char * i_sText);
void On_need_interface_MetaType(const char * i_sText);
void On_need_name_Identifer(const char * i_sText);
void On_wait_for_base_Punctuation(const char * i_sText);
void On_need_curlbr_open_Punctuation(const char * i_sText);
void On_std_Metatype(const char * i_sText);
void On_std_Punctuation(const char * i_sText);
void On_std_Stereotype(const char * i_sText);
void On_std_GotoFunction(const char * i_sText);
void On_std_GotoAttribute(const char * i_sText);
void On_std_GotoBaseInterface(const char * i_sText);
void On_need_finish_Punctuation(const char * i_sText);
void On_Default(const char * i_sText);
void CallHandler(
const char * i_sTokenText,
E_TokenType i_eTokenType );
virtual void InitData();
virtual void TransferData();
virtual void ReceiveData();
virtual UnoIDL_PE & MyPE();
void store_Interface();
// DATA
static F_TOK aDispatcher[e_STATES_MAX][tt_MAX];
E_State eState;
String sData_Name;
bool bIsPreDeclaration;
ary::idl::Interface *
pCurInterface;
ary::idl::Ce_id nCurInterface;
Dyn<PE_Function> pPE_Function;
Dyn<PE_Attribute> pPE_Attribute;
Dyn<PE_Type> pPE_Type;
ary::idl::Type_id nCurParsed_Base;
bool bOptionalMember;
};
// IMPLEMENTATION
} // namespace uidl
} // namespace csi
#endif
<|endoftext|>
|
<commit_before>#include <ACGL/Utils/Log.hh>
#include <ACGL/OpenGL/GL.hh> // this has to be included before glfw.h !
#include <ACGL/OpenGL/Debug.hh>
#include <ACGL/HardwareSupport/SimpleRiftController.hh>
#include <ACGL/OpenGL/Objects.hh>
#include <GLFW/glfw3.h>
#include "world/world.hh"
using namespace std;
using namespace ACGL::Utils;
using namespace ACGL::OpenGL;
using namespace ACGL::Scene;
// see main.cc:
extern World *gWorld;
//
// Global variables for the rendering:
// You can move the whole rendering code into a class and make this variables
// members. This was not done here to keep the example code a bit simpler.
//
ACGL::HardwareSupport::SimpleRiftController *gSimpleRiftControllerRenderer;
SharedTexture2D gLeftEyeRendering;
SharedTexture2D gRightEyeRendering;
SharedTexture2D gAnyEyeDepthBuffer;
SharedFrameBufferObject gLeftEyeFBO;
SharedFrameBufferObject gRightEyeFBO;
// in case of stereo rendering store the render size per eye:
glm::uvec2 gPerEyeRenderSize;
// the output size in 2D or the resolition of the HMD:
glm::uvec2 gOutputWindowSize;
// 3D Rift rendering or 2D?
bool gRenderForTheRift = true;
//
// A debug callback gets called for each OpenGL error and also for some warnings and even hints.
// Here it just prints those messages.
//
// If you set a brackpoint in here, you can see where the gl error came from and in which state your application is.
//
void APIENTRY ogl_debug_callback( GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar *_message, void* /* _userParam*/ )
{
if (_type == GL_DEBUG_TYPE_ERROR) {
error() << "<" << _id << "> severity: " << debugSeverityName(_severity) << " source: " << debugSourceName(_source) << ": " << _message << endl;
// Set a breakpoint in the line above! This way you get a stack trace in case something fails!
} else {
debug() << "<" << _id << "> severity: " << debugSeverityName(_severity) << " source: " << debugSourceName(_source) << ": " << _message << endl;
}
// delete all errors to not create another error log for the same problem:
while ( glGetError() != GL_NO_ERROR ) {}
}
//
// Will get called for each window resize, but not for window creation!
//
void resizeCallback( GLFWwindow*, int newWidth, int newHeight )
{
gOutputWindowSize = glm::uvec2( newWidth, newHeight );
if (gRenderForTheRift) {
// update raster size:
gSimpleRiftControllerRenderer->setOutputViewportSize( gOutputWindowSize );
} else {
// Update projection matrix (as the aspect ratio might have changed) in case of 2D rendering:
gSimpleRiftControllerRenderer->getCamera()->setAspectRatio( (float)newWidth / (float)newHeight );
gSimpleRiftControllerRenderer->getCamera()->setVerticalFieldOfView( 75.0f );
}
}
//
// Stuff that has to be done only once:
//
void initRenderer( GLFWwindow *window, ACGL::HardwareSupport::SimpleRiftController *simpleRiftController )
{
//
// Register our own OpenGL debug callback:
//
GLint v;
glGetIntegerv( GL_CONTEXT_FLAGS, &v );
if ((v & GL_CONTEXT_FLAG_DEBUG_BIT) != 0) {
glDebugMessageCallback( ogl_debug_callback, NULL );
}
// Enable V-Sync (e.g. limit rendering to 60 FPS in case the screen is a 60 Hz screen):
// Increases lag but removes tearing (if only one screen is present), often the best option for VR.
glfwSwapInterval( 1 );
// Get the current window size (we don't want to communicate that as global variables):
int width, height;
glfwGetWindowSize( window, &width, &height );
// Set up the Rift.
// store a pointer to the RiftController which we will use for the final render pass each frame:
gSimpleRiftControllerRenderer = simpleRiftController;
// use the render size to init offscreen textures etc.
// calculate a good offscreen render size:
gPerEyeRenderSize = gSimpleRiftControllerRenderer->getPhysicalScreenResolution();
gPerEyeRenderSize.x = gPerEyeRenderSize.x / 2; // for one eye only!
// 1.5 times higher resolution to decrease sampling artefacts when rendering the distortion.
// Much higher won't increase quality much, lower might increase the performance but looks worse:
gPerEyeRenderSize = glm::uvec2( glm::vec2(gPerEyeRenderSize) * 1.5f );
// note that all intermediate textures for the rendering except for the final images
// can be shared between the two framebuffers (reuse them):
// (TextureRectangle would also work, but the ACGL Rift post-process does not support them yet - it's on my TODO)
gLeftEyeRendering = SharedTexture2D( new Texture2D( gPerEyeRenderSize ) );
gRightEyeRendering = SharedTexture2D( new Texture2D( gPerEyeRenderSize ) );
gAnyEyeDepthBuffer = SharedTexture2D( new Texture2D( gPerEyeRenderSize, GL_DEPTH24_STENCIL8 ) );
// These textures are used as offscreen renderbuffers and don't need MipMaps
// Note that the filtering default is assuming MipMaps but you need to generate them
// manually!
gLeftEyeRendering->setMinFilter( GL_LINEAR );
gRightEyeRendering->setMinFilter( GL_LINEAR );
gAnyEyeDepthBuffer->setMinFilter( GL_LINEAR );
gLeftEyeFBO = SharedFrameBufferObject( new FrameBufferObject() );
gLeftEyeFBO->attachColorTexture( "oColor", gLeftEyeRendering );
gLeftEyeFBO->setDepthTexture( gAnyEyeDepthBuffer );
gRightEyeFBO = SharedFrameBufferObject( new FrameBufferObject() );
gRightEyeFBO->attachColorTexture( "oColor", gRightEyeRendering );
gRightEyeFBO->setDepthTexture( gAnyEyeDepthBuffer );
//
// More complex engines will need more textures as render targets and more framebuffers.
// Note that only the last renderpass needs two framebuffers for both eyes, everything else
// can be shared.
//
//
// Stuff that is window size dependent and has to be updated if the window resizes,
// to prevent code dublication, just call the resize function once:
//
resizeCallback( window, width, height );
// Get informed if the window gets resized later on again.
// Starting in fullscreen can trigger additional resizes right at the beginning (seen on KDE).
glfwSetWindowSizeCallback( window, resizeCallback );
// define the color the glClear should draw:
glClearColor( 0.8f, 0.8f, 1.0f, 1.0f );
glEnable( GL_DEPTH_TEST );
}
void shutdownRenderer()
{
// delete all resources:
// all resources with Shared* pointers are reference counted and don't need an explicit delete!
}
// assumes a framebuffer is bound to render into and glViewport is set correctly
void renderScene()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
gWorld->render();
}
//
// Does all the rendering for the frame. A more complex application
// would render (and prepare to render) everything that is independent on
// the head rotation before the head rotation gets read out of the Rift to minimize
// latency (every millisecond counts!). For simplicity reasons we don't do this here.
void renderFrame()
{
//
// Render shadow maps and other stuff that has to be updated each frame but is
// independent on the exact camera position ( == independent on the eye) first
// ( and only once! )
//
if (gRenderForTheRift) {
// as the viewport gets changed during rendering onto the screen
// (gSimpleRiftControllerRenderer->renderDistorted), this has to be reset each
// frame:
glViewport( 0, 0, gPerEyeRenderSize.x, gPerEyeRenderSize.y );
//
// Now render the left eye into a texture:
//
gSimpleRiftControllerRenderer->getCamera()->setEye( GenericCamera::EYE_LEFT );
gLeftEyeFBO->bind();
renderScene();
//
// Now render the right eye into a texture:
//
gSimpleRiftControllerRenderer->getCamera()->setEye( GenericCamera::EYE_RIGHT );
gRightEyeFBO->bind();
renderScene();
//
// Now combine both views into a distorted, Rift compatible view:
//
gSimpleRiftControllerRenderer->renderDistorted( gLeftEyeRendering, gRightEyeRendering );
} else {
glViewport( 0, 0, gOutputWindowSize.x, gOutputWindowSize.y );
//
// Render the left eye onto the screen as the only eye:
// (note: this mode is not complete ;-) it would be better to also deactivate
// the stereo option of the camera)
//
gSimpleRiftControllerRenderer->getCamera()->setEye( GenericCamera::EYE_LEFT );
// the screen is framebuffer 0, bind that:
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
renderScene();
}
}
<commit_msg>Disabled usage of rift to see something on screen<commit_after>#include <ACGL/Utils/Log.hh>
#include <ACGL/OpenGL/GL.hh> // this has to be included before glfw.h !
#include <ACGL/OpenGL/Debug.hh>
#include <ACGL/HardwareSupport/SimpleRiftController.hh>
#include <ACGL/OpenGL/Objects.hh>
#include <GLFW/glfw3.h>
#include "world/world.hh"
using namespace std;
using namespace ACGL::Utils;
using namespace ACGL::OpenGL;
using namespace ACGL::Scene;
// see main.cc:
extern World *gWorld;
//
// Global variables for the rendering:
// You can move the whole rendering code into a class and make this variables
// members. This was not done here to keep the example code a bit simpler.
//
ACGL::HardwareSupport::SimpleRiftController *gSimpleRiftControllerRenderer;
SharedTexture2D gLeftEyeRendering;
SharedTexture2D gRightEyeRendering;
SharedTexture2D gAnyEyeDepthBuffer;
SharedFrameBufferObject gLeftEyeFBO;
SharedFrameBufferObject gRightEyeFBO;
// in case of stereo rendering store the render size per eye:
glm::uvec2 gPerEyeRenderSize;
// the output size in 2D or the resolition of the HMD:
glm::uvec2 gOutputWindowSize;
// 3D Rift rendering or 2D?
bool gRenderForTheRift = false;
//
// A debug callback gets called for each OpenGL error and also for some warnings and even hints.
// Here it just prints those messages.
//
// If you set a brackpoint in here, you can see where the gl error came from and in which state your application is.
//
void APIENTRY ogl_debug_callback( GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar *_message, void* /* _userParam*/ )
{
if (_type == GL_DEBUG_TYPE_ERROR) {
error() << "<" << _id << "> severity: " << debugSeverityName(_severity) << " source: " << debugSourceName(_source) << ": " << _message << endl;
// Set a breakpoint in the line above! This way you get a stack trace in case something fails!
} else {
debug() << "<" << _id << "> severity: " << debugSeverityName(_severity) << " source: " << debugSourceName(_source) << ": " << _message << endl;
}
// delete all errors to not create another error log for the same problem:
while ( glGetError() != GL_NO_ERROR ) {}
}
//
// Will get called for each window resize, but not for window creation!
//
void resizeCallback( GLFWwindow*, int newWidth, int newHeight )
{
gOutputWindowSize = glm::uvec2( newWidth, newHeight );
if (gRenderForTheRift) {
// update raster size:
gSimpleRiftControllerRenderer->setOutputViewportSize( gOutputWindowSize );
} else {
// Update projection matrix (as the aspect ratio might have changed) in case of 2D rendering:
gSimpleRiftControllerRenderer->getCamera()->setAspectRatio( (float)newWidth / (float)newHeight );
gSimpleRiftControllerRenderer->getCamera()->setVerticalFieldOfView( 75.0f );
}
}
//
// Stuff that has to be done only once:
//
void initRenderer( GLFWwindow *window, ACGL::HardwareSupport::SimpleRiftController *simpleRiftController )
{
//
// Register our own OpenGL debug callback:
//
GLint v;
glGetIntegerv( GL_CONTEXT_FLAGS, &v );
if ((v & GL_CONTEXT_FLAG_DEBUG_BIT) != 0) {
glDebugMessageCallback( ogl_debug_callback, NULL );
}
// Enable V-Sync (e.g. limit rendering to 60 FPS in case the screen is a 60 Hz screen):
// Increases lag but removes tearing (if only one screen is present), often the best option for VR.
glfwSwapInterval( 1 );
// Get the current window size (we don't want to communicate that as global variables):
int width, height;
glfwGetWindowSize( window, &width, &height );
// Set up the Rift.
// store a pointer to the RiftController which we will use for the final render pass each frame:
gSimpleRiftControllerRenderer = simpleRiftController;
// use the render size to init offscreen textures etc.
// calculate a good offscreen render size:
gPerEyeRenderSize = gSimpleRiftControllerRenderer->getPhysicalScreenResolution();
gPerEyeRenderSize.x = gPerEyeRenderSize.x / 2; // for one eye only!
// 1.5 times higher resolution to decrease sampling artefacts when rendering the distortion.
// Much higher won't increase quality much, lower might increase the performance but looks worse:
gPerEyeRenderSize = glm::uvec2( glm::vec2(gPerEyeRenderSize) * 1.5f );
// note that all intermediate textures for the rendering except for the final images
// can be shared between the two framebuffers (reuse them):
// (TextureRectangle would also work, but the ACGL Rift post-process does not support them yet - it's on my TODO)
gLeftEyeRendering = SharedTexture2D( new Texture2D( gPerEyeRenderSize ) );
gRightEyeRendering = SharedTexture2D( new Texture2D( gPerEyeRenderSize ) );
gAnyEyeDepthBuffer = SharedTexture2D( new Texture2D( gPerEyeRenderSize, GL_DEPTH24_STENCIL8 ) );
// These textures are used as offscreen renderbuffers and don't need MipMaps
// Note that the filtering default is assuming MipMaps but you need to generate them
// manually!
gLeftEyeRendering->setMinFilter( GL_LINEAR );
gRightEyeRendering->setMinFilter( GL_LINEAR );
gAnyEyeDepthBuffer->setMinFilter( GL_LINEAR );
gLeftEyeFBO = SharedFrameBufferObject( new FrameBufferObject() );
gLeftEyeFBO->attachColorTexture( "oColor", gLeftEyeRendering );
gLeftEyeFBO->setDepthTexture( gAnyEyeDepthBuffer );
gRightEyeFBO = SharedFrameBufferObject( new FrameBufferObject() );
gRightEyeFBO->attachColorTexture( "oColor", gRightEyeRendering );
gRightEyeFBO->setDepthTexture( gAnyEyeDepthBuffer );
//
// More complex engines will need more textures as render targets and more framebuffers.
// Note that only the last renderpass needs two framebuffers for both eyes, everything else
// can be shared.
//
//
// Stuff that is window size dependent and has to be updated if the window resizes,
// to prevent code dublication, just call the resize function once:
//
resizeCallback( window, width, height );
// Get informed if the window gets resized later on again.
// Starting in fullscreen can trigger additional resizes right at the beginning (seen on KDE).
glfwSetWindowSizeCallback( window, resizeCallback );
// define the color the glClear should draw:
glClearColor( 0.8f, 0.8f, 1.0f, 1.0f );
glEnable( GL_DEPTH_TEST );
}
void shutdownRenderer()
{
// delete all resources:
// all resources with Shared* pointers are reference counted and don't need an explicit delete!
}
// assumes a framebuffer is bound to render into and glViewport is set correctly
void renderScene()
{
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
gWorld->render();
}
//
// Does all the rendering for the frame. A more complex application
// would render (and prepare to render) everything that is independent on
// the head rotation before the head rotation gets read out of the Rift to minimize
// latency (every millisecond counts!). For simplicity reasons we don't do this here.
void renderFrame()
{
//
// Render shadow maps and other stuff that has to be updated each frame but is
// independent on the exact camera position ( == independent on the eye) first
// ( and only once! )
//
if (gRenderForTheRift) {
// as the viewport gets changed during rendering onto the screen
// (gSimpleRiftControllerRenderer->renderDistorted), this has to be reset each
// frame:
glViewport( 0, 0, gPerEyeRenderSize.x, gPerEyeRenderSize.y );
//
// Now render the left eye into a texture:
//
gSimpleRiftControllerRenderer->getCamera()->setEye( GenericCamera::EYE_LEFT );
gLeftEyeFBO->bind();
renderScene();
//
// Now render the right eye into a texture:
//
gSimpleRiftControllerRenderer->getCamera()->setEye( GenericCamera::EYE_RIGHT );
gRightEyeFBO->bind();
renderScene();
//
// Now combine both views into a distorted, Rift compatible view:
//
gSimpleRiftControllerRenderer->renderDistorted( gLeftEyeRendering, gRightEyeRendering );
} else {
glViewport( 0, 0, gOutputWindowSize.x, gOutputWindowSize.y );
//
// Render the left eye onto the screen as the only eye:
// (note: this mode is not complete ;-) it would be better to also deactivate
// the stereo option of the camera)
//
gSimpleRiftControllerRenderer->getCamera()->setEye( GenericCamera::EYE_LEFT );
// the screen is framebuffer 0, bind that:
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
renderScene();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: simplereferenceobject.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: sb $ $Date: 2001-06-05 15:20:37 $
*
* 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 _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#define _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#ifndef _OSL_INTERLCK_H_
#include "osl/interlck.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef INCLUDED_CSTDDEF
#include <cstddef>
#define INCLUDED_CSTDDEF
#endif
#ifndef INCLUDED_NEW
#include <new>
#define INCLUDED_NEW
#endif
namespace salhelper {
class SimpleReferenceObject
{
public:
inline SimpleReferenceObject() SAL_THROW(()): m_nCount(0) {}
/** @ATTENTION
The results are undefined if, for any individual instance of
SimpleReferenceObject, the total number of calls to acquire() exceeds
the total number of calls to release() by a plattform dependent amount
(which, hopefully, is quite large).
*/
inline void acquire() SAL_THROW(())
{ osl_incrementInterlockedCount(&m_nCount); }
inline void release() SAL_THROW(())
{ if (osl_decrementInterlockedCount(&m_nCount) == 0) delete this; }
/** @descr
The reason to have class local operators new and delete here is
technical. Imagine a class D derived from SimpleReferenceObject, but
implemented in another shared library that happens to use different
global operators new and delete from those used in this shared library
(which, sadly, seems to be possible with shared libraries...). Now,
without the class local operators new and delete here, a code sequence
like "new D" would use the global operator new as found in the other
shared library, while the code sequence "delete this" in release()
would use the global operator delete as found in this shared library
---and these two operators would not be guaranteed to match.
@descr
There are no overloaded operators new and delete for placement new
here, because it is felt that the concept of placement new does not
work well with the concept of a reference counted object; so it seems
best to simply leave those operators out.
@descr
The same problem as with operators new and delete would also be there
with operators new[] and delete[]. But since arrays of reference
counted objects are of no use, anyway, it seems best to simply declare
and not define (private) operators new[] and delete[].
*/
static void * operator new(std::size_t nSize) SAL_THROW((std::bad_alloc));
static void * operator new(std::size_t nSize,
std::nothrow_t const & rNothrow)
SAL_THROW(());
static void operator delete(void * pPtr) SAL_THROW(());
static void operator delete(void * pPtr, std::nothrow_t const & rNothrow)
SAL_THROW(());
protected:
virtual ~SimpleReferenceObject() SAL_THROW(());
private:
oslInterlockedCount m_nCount;
SimpleReferenceObject(SimpleReferenceObject &); // not implemented
void operator =(SimpleReferenceObject); // not implemented
static void * operator new[](std::size_t); // not implemented
static void operator delete[](void * pPtr); // not implemented
};
}
#endif // _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
<commit_msg>#88337# Minor documentation improvements.<commit_after>/*************************************************************************
*
* $RCSfile: simplereferenceobject.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: sb $ $Date: 2001-10-29 12:42:54 $
*
* 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 _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#define _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#ifndef _OSL_INTERLCK_H_
#include "osl/interlck.h"
#endif
#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef INCLUDED_CSTDDEF
#include <cstddef>
#define INCLUDED_CSTDDEF
#endif
#ifndef INCLUDED_NEW
#include <new>
#define INCLUDED_NEW
#endif
namespace salhelper {
/** A simple base implementation for reference-counted objects.
Classes that want to implement a reference-counting mechanism based on the
acquire()/release() interface should derive from this class.
The reason to have class local operators new and delete here is technical.
Imagine a class D derived from SimpleReferenceObject, but implemented in
another shared library that happens to use different global operators new
and delete from those used in this shared library (which, sadly, seems to
be possible with shared libraries). Now, without the class local
operators new and delete here, a code sequence like "new D" would use the
global operator new as found in the other shared library, while the code
sequence "delete this" in release() would use the global operator delete
as found in this shared library---and these two operators would not be
guaranteed to match.
There are no overloaded operators new and delete for placement new here,
because it is felt that the concept of placement new does not work well
with the concept of reference-counted objects; so it seems best to simply
leave those operators out.
The same problem as with operators new and delete would also be there with
operators new[] and delete[]. But since arrays of reference-counted
objects are of no use, anyway, it seems best to simply declare and not
define (private) operators new[] and delete[].
*/
class SimpleReferenceObject
{
public:
inline SimpleReferenceObject() SAL_THROW(()): m_nCount(0) {}
/** @ATTENTION
The results are undefined if, for any individual instance of
SimpleReferenceObject, the total number of calls to acquire() exceeds
the total number of calls to release() by a plattform dependent amount
(which, hopefully, is quite large).
*/
inline void acquire() SAL_THROW(())
{ osl_incrementInterlockedCount(&m_nCount); }
inline void release() SAL_THROW(())
{ if (osl_decrementInterlockedCount(&m_nCount) == 0) delete this; }
/** see general class documentation
*/
static void * operator new(std::size_t nSize) SAL_THROW((std::bad_alloc));
/** see general class documentation
*/
static void * operator new(std::size_t nSize,
std::nothrow_t const & rNothrow)
SAL_THROW(());
/** see general class documentation
*/
static void operator delete(void * pPtr) SAL_THROW(());
/** see general class documentation
*/
static void operator delete(void * pPtr, std::nothrow_t const & rNothrow)
SAL_THROW(());
protected:
virtual ~SimpleReferenceObject() SAL_THROW(());
private:
oslInterlockedCount m_nCount;
/** not implemented
@internal
*/
SimpleReferenceObject(SimpleReferenceObject &);
/** not implemented
@internal
*/
void operator =(SimpleReferenceObject);
/** not implemented (see general class documentation)
@internal
*/
static void * operator new[](std::size_t);
/** not implemented (see general class documentation)
@internal
*/
static void operator delete[](void * pPtr);
};
}
#endif // _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
<|endoftext|>
|
<commit_before>#pragma once
/*
* Covariant Mozart Utility Library: Any
*
* 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
* 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/>.
*
* Copyright (C) 2016 Michael Lee(李登淳)
* Email: [email protected]
* Github: https://github.com/mikecovlee
* Website: http://ldc.atd3.cn
*
* Version: 17.2.1
*/
#include "./base.hpp"
#include <iostream>
namespace std {
template<typename T> std::string to_string(const T&)
{
throw cov::error("E000D");
}
template<> std::string to_string<std::string>(const std::string& str)
{
return str;
}
template<> std::string to_string<bool>(const bool& v)
{
if(v)
return "True";
else
return "False";
}
}
namespace cov {
template < typename _Tp > class compare_helper {
template < typename T,typename X=bool >struct matcher;
template < typename T > static constexpr bool match(T*)
{
return false;
}
template < typename T > static constexpr bool match(matcher < T, decltype(std::declval<T>()==std::declval<T>()) > *)
{
return true;
}
public:
static constexpr bool value = match < _Tp > (nullptr);
};
template<typename,bool> struct compare_if;
template<typename T>struct compare_if<T,true> {
static bool compare(const T& a,const T& b)
{
return a==b;
}
};
template<typename T>struct compare_if<T,false> {
static bool compare(const T& a,const T& b)
{
return &a==&b;
}
};
template<typename T>bool compare(const T& a,const T& b)
{
return compare_if<T,compare_helper<T>::value>::compare(a,b);
}
class any final {
class baseHolder {
public:
baseHolder() = default;
virtual ~ baseHolder() = default;
virtual const std::type_info & type() const = 0;
virtual baseHolder *duplicate() = 0;
virtual bool compare(const baseHolder *) const = 0;
virtual std::string to_string() const = 0;
};
template < typename T > class holder:public baseHolder {
protected:
T mDat;
public:
holder() = default;
holder(const T& dat):mDat(dat) {}
virtual ~ holder() = default;
virtual const std::type_info & type() const override
{
return typeid(T);
}
virtual baseHolder *duplicate() override
{
return new holder(mDat);
}
virtual bool compare(const baseHolder * obj)const override
{
if (obj->type() == this->type()) {
const holder < T > *ptr = dynamic_cast < const holder < T > *>(obj);
return ptr!=nullptr?cov::compare(mDat,ptr->data()):false;
}
return false;
}
virtual std::string to_string() const override
{
return std::move(std::to_string(mDat));
}
T & data()
{
return mDat;
}
const T & data() const
{
return mDat;
}
void data(const T & dat)
{
mDat = dat;
}
};
using size_t=unsigned long;
struct proxy {
mutable size_t refcount=1;
baseHolder* data=nullptr;
proxy()=default;
proxy(size_t rc,baseHolder* d):refcount(rc),data(d) {}
~proxy()
{
delete data;
}
};
proxy* mDat=nullptr;
proxy* duplicate() const noexcept
{
if(mDat!=nullptr) {
++mDat->refcount;
}
return mDat;
}
void recycle() noexcept
{
if(mDat!=nullptr) {
--mDat->refcount;
if(mDat->refcount==0) {
delete mDat;
mDat=nullptr;
}
}
}
public:
static any infer_value(const std::string&);
void swap(any& obj) noexcept
{
proxy* tmp=this->mDat;
this->mDat=obj.mDat;
obj.mDat=tmp;
}
void swap(any&& obj) noexcept
{
proxy* tmp=this->mDat;
this->mDat=obj.mDat;
obj.mDat=tmp;
}
void clone() noexcept
{
if(mDat!=nullptr) {
proxy* dat=new proxy(1,mDat->data->duplicate());
recycle();
mDat=dat;
}
}
bool usable() const noexcept
{
return mDat != nullptr;
}
any()=default;
template < typename T > any(const T & dat):mDat(new proxy(1,new holder < T > (dat))) {}
any(const any & v):mDat(v.duplicate()) {}
any(any&& v) noexcept
{
swap(std::forward<any>(v));
}
~any()
{
recycle();
}
const std::type_info & type() const
{
return this->mDat != nullptr?this->mDat->data->type():typeid(void);
}
std::string to_string() const
{
if(this->mDat == nullptr)
return "Null";
return std::move(this->mDat->data->to_string());
}
any & operator=(const any & var)
{
if(&var!=this) {
recycle();
mDat = var.duplicate();
}
return *this;
}
any & operator=(any&& var) noexcept
{
if(&var!=this)
swap(std::forward<any>(var));
return *this;
}
bool operator==(const any & var) const
{
return usable()?this->mDat->data->compare(var.mDat->data):!var.usable();
}
bool operator!=(const any & var)const
{
return usable()?!this->mDat->data->compare(var.mDat->data):var.usable();
}
template < typename T > T & val(bool raw=false)
{
if(typeid(T) != this->type())
throw cov::error("E0006");
if(this->mDat == nullptr)
throw cov::error("E0005");
if(!raw)
clone();
return dynamic_cast < holder < T > *>(this->mDat->data)->data();
}
template < typename T > const T & val(bool raw=false) const
{
if(typeid(T) != this->type())
throw cov::error("E0006");
if(this->mDat == nullptr)
throw cov::error("E0005");
return dynamic_cast < const holder < T > *>(this->mDat->data)->data();
}
template < typename T > const T& const_val() const
{
if(typeid(T) != this->type())
throw cov::error("E0006");
if(this->mDat == nullptr)
throw cov::error("E0005");
return dynamic_cast < const holder < T > *>(this->mDat->data)->data();
}
template < typename T > operator T&()
{
return this->val<T>();
}
template < typename T > operator const T&() const
{
return this->const_val<T>();
}
void assign(const any& obj,bool raw=false)
{
if(&obj!=this) {
if(mDat!=nullptr&&obj.mDat!=nullptr&&raw) {
delete mDat->data;
mDat->data=obj.mDat->data->duplicate();
} else {
recycle();
if(obj.mDat!=nullptr)
mDat=new proxy(1,obj.mDat->data->duplicate());
else
mDat=nullptr;
}
}
}
template < typename T > void assign(const T & dat,bool raw=false)
{
if(raw) {
delete mDat->data;
mDat->data=new holder < T > (dat);
} else {
recycle();
mDat = new proxy(1,new holder < T > (dat));
}
}
template < typename T > any & operator=(const T & dat)
{
assign(dat);
return *this;
}
};
template<int N> class any::holder<char[N]>:public any::holder<std::string> {
public:
using holder<std::string>::holder;
};
template<> class any::holder<std::type_info>:public any::holder<std::type_index> {
public:
using holder<std::type_index>::holder;
};
}
cov::any cov::any::infer_value(const std::string& str)
{
if(str=="true"||str=="True"||str=="TRUE")
return true;
if(str=="false"||str=="False"||str=="FALSE")
return false;
enum types {
interger,floating,other
} type=types::interger;
for(auto& it:str) {
if(!std::isdigit(it)&&it!='.') {
type=other;
break;
}
if(!std::isdigit(it)&&it=='.') {
if(type==interger) {
type=floating;
continue;
}
if(type==floating) {
type=other;
break;
}
}
}
switch(type) {
case interger:
try {
return std::stoi(str);
} catch(std::out_of_range) {
try {
return std::stol(str);
} catch(std::out_of_range) {
try {
return std::stoll(str);
} catch(std::out_of_range) {
return str;
}
}
}
case floating:
return std::stod(str);
case other:
break;
}
return str;
}
std::istream& operator>>(std::istream& in,cov::any& val)
{
static std::string str;
in>>str;
val=cov::any::infer_value(str);
return in;
}
std::ostream& operator<<(std::ostream& out,const cov::any& val)
{
out<<val.to_string();
return out;
}
<commit_msg>增加判定是否指向同一数据<commit_after>#pragma once
/*
* Covariant Mozart Utility Library: Any
*
* 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
* 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/>.
*
* Copyright (C) 2016 Michael Lee(李登淳)
* Email: [email protected]
* Github: https://github.com/mikecovlee
* Website: http://ldc.atd3.cn
*
* Version: 17.2.1
*/
#include "./base.hpp"
#include <iostream>
namespace std {
template<typename T> std::string to_string(const T&)
{
throw cov::error("E000D");
}
template<> std::string to_string<std::string>(const std::string& str)
{
return str;
}
template<> std::string to_string<bool>(const bool& v)
{
if(v)
return "True";
else
return "False";
}
}
namespace cov {
template < typename _Tp > class compare_helper {
template < typename T,typename X=bool >struct matcher;
template < typename T > static constexpr bool match(T*)
{
return false;
}
template < typename T > static constexpr bool match(matcher < T, decltype(std::declval<T>()==std::declval<T>()) > *)
{
return true;
}
public:
static constexpr bool value = match < _Tp > (nullptr);
};
template<typename,bool> struct compare_if;
template<typename T>struct compare_if<T,true> {
static bool compare(const T& a,const T& b)
{
return a==b;
}
};
template<typename T>struct compare_if<T,false> {
static bool compare(const T& a,const T& b)
{
return &a==&b;
}
};
template<typename T>bool compare(const T& a,const T& b)
{
return compare_if<T,compare_helper<T>::value>::compare(a,b);
}
class any final {
class baseHolder {
public:
baseHolder() = default;
virtual ~ baseHolder() = default;
virtual const std::type_info & type() const = 0;
virtual baseHolder *duplicate() = 0;
virtual bool compare(const baseHolder *) const = 0;
virtual std::string to_string() const = 0;
};
template < typename T > class holder:public baseHolder {
protected:
T mDat;
public:
holder() = default;
holder(const T& dat):mDat(dat) {}
virtual ~ holder() = default;
virtual const std::type_info & type() const override
{
return typeid(T);
}
virtual baseHolder *duplicate() override
{
return new holder(mDat);
}
virtual bool compare(const baseHolder * obj)const override
{
if (obj->type() == this->type()) {
const holder < T > *ptr = dynamic_cast < const holder < T > *>(obj);
return ptr!=nullptr?cov::compare(mDat,ptr->data()):false;
}
return false;
}
virtual std::string to_string() const override
{
return std::move(std::to_string(mDat));
}
T & data()
{
return mDat;
}
const T & data() const
{
return mDat;
}
void data(const T & dat)
{
mDat = dat;
}
};
using size_t=unsigned long;
struct proxy {
mutable size_t refcount=1;
baseHolder* data=nullptr;
proxy()=default;
proxy(size_t rc,baseHolder* d):refcount(rc),data(d) {}
~proxy()
{
delete data;
}
};
proxy* mDat=nullptr;
proxy* duplicate() const noexcept
{
if(mDat!=nullptr) {
++mDat->refcount;
}
return mDat;
}
void recycle() noexcept
{
if(mDat!=nullptr) {
--mDat->refcount;
if(mDat->refcount==0) {
delete mDat;
mDat=nullptr;
}
}
}
public:
static any infer_value(const std::string&);
void swap(any& obj) noexcept
{
proxy* tmp=this->mDat;
this->mDat=obj.mDat;
obj.mDat=tmp;
}
void swap(any&& obj) noexcept
{
proxy* tmp=this->mDat;
this->mDat=obj.mDat;
obj.mDat=tmp;
}
void clone() noexcept
{
if(mDat!=nullptr) {
proxy* dat=new proxy(1,mDat->data->duplicate());
recycle();
mDat=dat;
}
}
bool usable() const noexcept
{
return mDat != nullptr;
}
any()=default;
template < typename T > any(const T & dat):mDat(new proxy(1,new holder < T > (dat))) {}
any(const any & v):mDat(v.duplicate()) {}
any(any&& v) noexcept
{
swap(std::forward<any>(v));
}
~any()
{
recycle();
}
const std::type_info & type() const
{
return this->mDat != nullptr?this->mDat->data->type():typeid(void);
}
std::string to_string() const
{
if(this->mDat == nullptr)
return "Null";
return std::move(this->mDat->data->to_string());
}
any & operator=(const any & var)
{
if(&var!=this) {
recycle();
mDat = var.duplicate();
}
return *this;
}
any & operator=(any&& var) noexcept
{
if(&var!=this)
swap(std::forward<any>(var));
return *this;
}
bool operator==(const any & var) const
{
return usable()?this->mDat->data->compare(var.mDat->data):!var.usable();
}
bool operator!=(const any & var)const
{
return usable()?!this->mDat->data->compare(var.mDat->data):var.usable();
}
template < typename T > T & val(bool raw=false)
{
if(typeid(T) != this->type())
throw cov::error("E0006");
if(this->mDat == nullptr)
throw cov::error("E0005");
if(!raw)
clone();
return dynamic_cast < holder < T > *>(this->mDat->data)->data();
}
template < typename T > const T & val(bool raw=false) const
{
if(typeid(T) != this->type())
throw cov::error("E0006");
if(this->mDat == nullptr)
throw cov::error("E0005");
return dynamic_cast < const holder < T > *>(this->mDat->data)->data();
}
template < typename T > const T& const_val() const
{
if(typeid(T) != this->type())
throw cov::error("E0006");
if(this->mDat == nullptr)
throw cov::error("E0005");
return dynamic_cast < const holder < T > *>(this->mDat->data)->data();
}
template < typename T > operator T&()
{
return this->val<T>();
}
template < typename T > operator const T&() const
{
return this->const_val<T>();
}
void assign(const any& obj,bool raw=false)
{
if(&obj!=this) {
if(mDat!=nullptr&&obj.mDat!=nullptr&&raw) {
delete mDat->data;
mDat->data=obj.mDat->data->duplicate();
} else {
recycle();
if(obj.mDat!=nullptr)
mDat=new proxy(1,obj.mDat->data->duplicate());
else
mDat=nullptr;
}
}
}
template < typename T > void assign(const T & dat,bool raw=false)
{
if(raw) {
delete mDat->data;
mDat->data=new holder < T > (dat);
} else {
recycle();
mDat = new proxy(1,new holder < T > (dat));
}
}
template < typename T > any & operator=(const T & dat)
{
assign(dat);
return *this;
}
bool is_same(const any& obj) const
{
return this->mDat==obj.mDat;
}
};
template<int N> class any::holder<char[N]>:public any::holder<std::string> {
public:
using holder<std::string>::holder;
};
template<> class any::holder<std::type_info>:public any::holder<std::type_index> {
public:
using holder<std::type_index>::holder;
};
}
cov::any cov::any::infer_value(const std::string& str)
{
if(str=="true"||str=="True"||str=="TRUE")
return true;
if(str=="false"||str=="False"||str=="FALSE")
return false;
enum types {
interger,floating,other
} type=types::interger;
for(auto& it:str) {
if(!std::isdigit(it)&&it!='.') {
type=other;
break;
}
if(!std::isdigit(it)&&it=='.') {
if(type==interger) {
type=floating;
continue;
}
if(type==floating) {
type=other;
break;
}
}
}
switch(type) {
case interger:
try {
return std::stoi(str);
} catch(std::out_of_range) {
try {
return std::stol(str);
} catch(std::out_of_range) {
try {
return std::stoll(str);
} catch(std::out_of_range) {
return str;
}
}
}
case floating:
return std::stod(str);
case other:
break;
}
return str;
}
std::istream& operator>>(std::istream& in,cov::any& val)
{
static std::string str;
in>>str;
val=cov::any::infer_value(str);
return in;
}
std::ostream& operator<<(std::ostream& out,const cov::any& val)
{
out<<val.to_string();
return out;
}
<|endoftext|>
|
<commit_before>#ifndef RUBY_ALLOCATOR_HH
#define RUBY_ALLOCATOR_HH
#include <ruby/defines.h>
template <class T> class ruby_allocator
{
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
template <class U>
struct rebind { typedef ruby_allocator<U> other; };
ruby_allocator() {}
ruby_allocator(const ruby_allocator&) {}
template <class U>
ruby_allocator(const ruby_allocator<U>&) {}
~ruby_allocator() {}
pointer address(reference x) const { return &x; }
const_pointer address(const_reference x) const {
return x;
}
pointer allocate(size_type n, const_pointer = 0) {
void* p = ruby_xmalloc(n * sizeof(T));
if (!p)
throw std::bad_alloc();
return static_cast<pointer>(p);
}
void deallocate(pointer p, size_type) { ruby_xfree(p); }
size_type max_size() const {
return static_cast<size_type>(-1) / sizeof(T);
}
void construct(pointer p, const value_type& x) {
new(p) value_type(x);
}
void destroy(pointer p) { p->~value_type(); }
private:
void operator=(const ruby_allocator&);
};
template<> class ruby_allocator<void>
{
typedef void value_type;
typedef void* pointer;
typedef const void* const_pointer;
template <class U>
struct rebind { typedef ruby_allocator<U> other; };
};
template <class T>
inline bool operator==(const ruby_allocator<T>&,
const ruby_allocator<T>&) {
return true;
}
template <class T>
inline bool operator!=(const ruby_allocator<T>&,
const ruby_allocator<T>&) {
return false;
}
#endif
<commit_msg>fix for Ruby 1.8<commit_after>#ifndef RUBY_ALLOCATOR_HH
#define RUBY_ALLOCATOR_HH
#include <defines.h>
template <class T> class ruby_allocator
{
public:
typedef T value_type;
typedef value_type* pointer;
typedef const value_type* const_pointer;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
template <class U>
struct rebind { typedef ruby_allocator<U> other; };
ruby_allocator() {}
ruby_allocator(const ruby_allocator&) {}
template <class U>
ruby_allocator(const ruby_allocator<U>&) {}
~ruby_allocator() {}
pointer address(reference x) const { return &x; }
const_pointer address(const_reference x) const {
return x;
}
pointer allocate(size_type n, const_pointer = 0) {
void* p = ruby_xmalloc(n * sizeof(T));
if (!p)
throw std::bad_alloc();
return static_cast<pointer>(p);
}
void deallocate(pointer p, size_type) { ruby_xfree(p); }
size_type max_size() const {
return static_cast<size_type>(-1) / sizeof(T);
}
void construct(pointer p, const value_type& x) {
new(p) value_type(x);
}
void destroy(pointer p) { p->~value_type(); }
private:
void operator=(const ruby_allocator&);
};
template<> class ruby_allocator<void>
{
typedef void value_type;
typedef void* pointer;
typedef const void* const_pointer;
template <class U>
struct rebind { typedef ruby_allocator<U> other; };
};
template <class T>
inline bool operator==(const ruby_allocator<T>&,
const ruby_allocator<T>&) {
return true;
}
template <class T>
inline bool operator!=(const ruby_allocator<T>&,
const ruby_allocator<T>&) {
return false;
}
#endif
<|endoftext|>
|
<commit_before>/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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.
*
*/
#ifndef GRPC_UV
#include "server.h"
#include <nan.h>
#include <node.h>
#include "grpc/grpc.h"
#include "grpc/support/time.h"
namespace grpc {
namespace node {
Server::Server(grpc_server *server) : wrapped_server(server) {
grpc_completion_queue_attributes attrs = {
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_NON_LISTENING};
shutdown_queue = grpc_completion_queue_create(
grpc_completion_queue_factory_lookup(&attrs), &attrs, NULL);
grpc_server_completion_queue(server, shutdown_queue, NULL);
}
Server::~Server() {
this->ShutdownServer();
grpc_completion_queue_shutdown(this->shutdown_queue);
grpc_completion_queue_destroy(this->shutdown_queue);
}
void Server::ShutdownServer() {
if (this->wrapped_server != NULL) {
grpc_server_shutdown_and_notify(this->wrapped_server, this->shutdown_queue,
NULL);
grpc_server_cancel_all_calls(this->wrapped_server);
grpc_completion_queue_pluck(this->shutdown_queue, NULL,
gpr_inf_future(GPR_CLOCK_REALTIME), NULL);
grpc_server_destroy(this->wrapped_server);
this->wrapped_server = NULL;
}
}
} // namespace grpc
} // namespace node
#endif /* GRPC_UV */
<commit_msg>Fix typo<commit_after>/*
*
* Copyright 2017, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 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.
*
*/
#ifndef GRPC_UV
#include "server.h"
#include <nan.h>
#include <node.h>
#include "grpc/grpc.h"
#include "grpc/support/time.h"
namespace grpc {
namespace node {
Server::Server(grpc_server *server) : wrapped_server(server) {
grpc_completion_queue_attributes attrs = {
GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_NON_LISTENING};
shutdown_queue = grpc_completion_queue_create(
grpc_completion_queue_factory_lookup(&attrs), &attrs, NULL);
grpc_server_register_completion_queue(server, shutdown_queue, NULL);
}
Server::~Server() {
this->ShutdownServer();
grpc_completion_queue_shutdown(this->shutdown_queue);
grpc_completion_queue_destroy(this->shutdown_queue);
}
void Server::ShutdownServer() {
if (this->wrapped_server != NULL) {
grpc_server_shutdown_and_notify(this->wrapped_server, this->shutdown_queue,
NULL);
grpc_server_cancel_all_calls(this->wrapped_server);
grpc_completion_queue_pluck(this->shutdown_queue, NULL,
gpr_inf_future(GPR_CLOCK_REALTIME), NULL);
grpc_server_destroy(this->wrapped_server);
this->wrapped_server = NULL;
}
}
} // namespace grpc
} // namespace node
#endif /* GRPC_UV */
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/predictor/free_move/free_move_predictor.h"
#include "modules/prediction/predictor/junction/junction_predictor.h"
#include "modules/prediction/predictor/lane_sequence/lane_sequence_predictor.h"
#include "modules/prediction/predictor/move_sequence/move_sequence_predictor.h"
#include "modules/prediction/predictor/regional/regional_predictor.h"
#include "modules/prediction/predictor/single_lane/single_lane_predictor.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
using apollo::perception::PerceptionObstacle;
PredictorManager::PredictorManager() { RegisterPredictors(); }
void PredictorManager::RegisterPredictors() {
RegisterPredictor(ObstacleConf::LANE_SEQUENCE_PREDICTOR);
RegisterPredictor(ObstacleConf::MOVE_SEQUENCE_PREDICTOR);
RegisterPredictor(ObstacleConf::SINGLE_LANE_PREDICTOR);
RegisterPredictor(ObstacleConf::FREE_MOVE_PREDICTOR);
RegisterPredictor(ObstacleConf::REGIONAL_PREDICTOR);
RegisterPredictor(ObstacleConf::EMPTY_PREDICTOR);
RegisterPredictor(ObstacleConf::JUNCTION_PREDICTOR);
}
void PredictorManager::Init(const PredictionConf& config) {
for (const auto& obstacle_conf : config.obstacle_conf()) {
if (!obstacle_conf.has_obstacle_type()) {
AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
<< "] has not defined obstacle type.";
continue;
}
if (!obstacle_conf.has_predictor_type()) {
AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
<< "] has not defined predictor type.";
continue;
}
switch (obstacle_conf.obstacle_type()) {
case PerceptionObstacle::VEHICLE: {
if (obstacle_conf.has_obstacle_status()) {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
vehicle_on_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::OFF_LANE) {
vehicle_off_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::IN_JUNCTION) {
vehicle_in_junction_predictor_ = obstacle_conf.predictor_type();
}
}
break;
}
case PerceptionObstacle::BICYCLE: {
if (obstacle_conf.has_obstacle_status()) {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
cyclist_on_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::OFF_LANE) {
cyclist_off_lane_predictor_ = obstacle_conf.predictor_type();
}
}
break;
}
case PerceptionObstacle::PEDESTRIAN: {
pedestrian_predictor_ = obstacle_conf.predictor_type();
break;
}
case PerceptionObstacle::UNKNOWN: {
if (obstacle_conf.has_obstacle_status()) {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
default_on_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::OFF_LANE) {
default_off_lane_predictor_ = obstacle_conf.predictor_type();
}
}
break;
}
default: { break; }
}
}
AINFO << "Defined vehicle on lane obstacle predictor ["
<< vehicle_on_lane_predictor_ << "].";
AINFO << "Defined vehicle off lane obstacle predictor ["
<< vehicle_off_lane_predictor_ << "].";
AINFO << "Defined bicycle on lane obstacle predictor ["
<< cyclist_on_lane_predictor_ << "].";
AINFO << "Defined bicycle off lane obstacle predictor ["
<< cyclist_off_lane_predictor_ << "].";
AINFO << "Defined pedestrian obstacle predictor [" << pedestrian_predictor_
<< "].";
AINFO << "Defined default on lane obstacle predictor ["
<< default_on_lane_predictor_ << "].";
AINFO << "Defined default off lane obstacle predictor ["
<< default_off_lane_predictor_ << "].";
}
Predictor* PredictorManager::GetPredictor(
const ObstacleConf::PredictorType& type) {
auto it = predictors_.find(type);
return it != predictors_.end() ? it->second.get() : nullptr;
}
void PredictorManager::Run() {
prediction_obstacles_.Clear();
auto obstacles_container =
ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
auto adc_trajectory_container =
ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
CHECK_NOTNULL(obstacles_container);
for (const int id : obstacles_container->curr_frame_obstacle_ids()) {
if (id < 0) {
ADEBUG << "The obstacle has invalid id [" << id << "].";
continue;
}
PredictionObstacle prediction_obstacle;
Obstacle* obstacle = obstacles_container->GetObstacle(id);
PerceptionObstacle perception_obstacle =
obstacles_container->GetPerceptionObstacle(id);
// if obstacle == nullptr, that means obstacle is not predictable
// Checkout the logic of non-predictable in obstacle.cc
if (obstacle != nullptr) {
PredictObstacle(obstacle, &prediction_obstacle, adc_trajectory_container);
} else { // obstacle == nullptr
prediction_obstacle.set_timestamp(perception_obstacle.timestamp());
prediction_obstacle.set_is_static(true);
}
prediction_obstacle.set_predicted_period(
FLAGS_prediction_trajectory_time_length);
prediction_obstacle.mutable_perception_obstacle()->CopyFrom(
perception_obstacle);
prediction_obstacles_.add_prediction_obstacle()->CopyFrom(
prediction_obstacle);
}
}
void PredictorManager::PredictObstacle(
Obstacle* obstacle, PredictionObstacle* const prediction_obstacle,
ADCTrajectoryContainer* adc_trajectory_container) {
CHECK_NOTNULL(obstacle);
Predictor* predictor = nullptr;
prediction_obstacle->set_timestamp(obstacle->timestamp());
if (obstacle->ToIgnore()) {
ADEBUG << "Ignore obstacle [" << obstacle->id() << "]";
predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
prediction_obstacle->mutable_priority()->set_priority(
ObstaclePriority::IGNORE);
} else if (obstacle->IsStill()) {
ADEBUG << "Still obstacle [" << obstacle->id() << "]";
predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
} else {
switch (obstacle->type()) {
case PerceptionObstacle::VEHICLE: {
if (obstacle->HasJunctionFeatureWithExits() &&
!obstacle->IsCloseToJunctionExit()) {
predictor = GetPredictor(vehicle_in_junction_predictor_);
CHECK_NOTNULL(predictor);
} else if (obstacle->IsOnLane()) {
predictor = GetPredictor(vehicle_on_lane_predictor_);
CHECK_NOTNULL(predictor);
} else {
predictor = GetPredictor(vehicle_off_lane_predictor_);
CHECK_NOTNULL(predictor);
}
break;
}
case PerceptionObstacle::PEDESTRIAN: {
predictor = GetPredictor(pedestrian_predictor_);
break;
}
case PerceptionObstacle::BICYCLE: {
if (obstacle->IsOnLane()) {
predictor = GetPredictor(cyclist_on_lane_predictor_);
// TODO(kechxu) add a specific predictor in junction
} else {
predictor = GetPredictor(cyclist_off_lane_predictor_);
}
break;
}
default: {
if (obstacle->IsOnLane()) {
predictor = GetPredictor(default_on_lane_predictor_);
} else {
predictor = GetPredictor(default_off_lane_predictor_);
}
break;
}
}
}
if (predictor != nullptr) {
predictor->Predict(obstacle);
if (FLAGS_enable_trim_prediction_trajectory &&
obstacle->type() == PerceptionObstacle::VEHICLE) {
CHECK_NOTNULL(adc_trajectory_container);
predictor->TrimTrajectories(obstacle, adc_trajectory_container);
}
for (const auto& trajectory : predictor->trajectories()) {
prediction_obstacle->add_trajectory()->CopyFrom(trajectory);
}
}
prediction_obstacle->set_timestamp(obstacle->timestamp());
prediction_obstacle->set_is_static(obstacle->IsStill());
if (FLAGS_prediction_offline_mode == 3) {
FeatureOutput::InsertPredictionResult(obstacle->id(), *prediction_obstacle);
}
}
std::unique_ptr<Predictor> PredictorManager::CreatePredictor(
const ObstacleConf::PredictorType& type) {
std::unique_ptr<Predictor> predictor_ptr(nullptr);
switch (type) {
case ObstacleConf::LANE_SEQUENCE_PREDICTOR: {
predictor_ptr.reset(new LaneSequencePredictor());
break;
}
case ObstacleConf::MOVE_SEQUENCE_PREDICTOR: {
predictor_ptr.reset(new MoveSequencePredictor());
break;
}
case ObstacleConf::SINGLE_LANE_PREDICTOR: {
predictor_ptr.reset(new SingleLanePredictor());
break;
}
case ObstacleConf::FREE_MOVE_PREDICTOR: {
predictor_ptr.reset(new FreeMovePredictor());
break;
}
case ObstacleConf::REGIONAL_PREDICTOR: {
predictor_ptr.reset(new RegionalPredictor());
break;
}
case ObstacleConf::JUNCTION_PREDICTOR: {
predictor_ptr.reset(new JunctionPredictor());
break;
}
default: { break; }
}
return predictor_ptr;
}
void PredictorManager::RegisterPredictor(
const ObstacleConf::PredictorType& type) {
predictors_[type] = CreatePredictor(type);
AINFO << "Predictor [" << type << "] is registered.";
}
const PredictionObstacles& PredictorManager::prediction_obstacles() {
return prediction_obstacles_;
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: add priority in prediction_obstacle<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/predictor/free_move/free_move_predictor.h"
#include "modules/prediction/predictor/junction/junction_predictor.h"
#include "modules/prediction/predictor/lane_sequence/lane_sequence_predictor.h"
#include "modules/prediction/predictor/move_sequence/move_sequence_predictor.h"
#include "modules/prediction/predictor/regional/regional_predictor.h"
#include "modules/prediction/predictor/single_lane/single_lane_predictor.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
using apollo::perception::PerceptionObstacle;
PredictorManager::PredictorManager() { RegisterPredictors(); }
void PredictorManager::RegisterPredictors() {
RegisterPredictor(ObstacleConf::LANE_SEQUENCE_PREDICTOR);
RegisterPredictor(ObstacleConf::MOVE_SEQUENCE_PREDICTOR);
RegisterPredictor(ObstacleConf::SINGLE_LANE_PREDICTOR);
RegisterPredictor(ObstacleConf::FREE_MOVE_PREDICTOR);
RegisterPredictor(ObstacleConf::REGIONAL_PREDICTOR);
RegisterPredictor(ObstacleConf::EMPTY_PREDICTOR);
RegisterPredictor(ObstacleConf::JUNCTION_PREDICTOR);
}
void PredictorManager::Init(const PredictionConf& config) {
for (const auto& obstacle_conf : config.obstacle_conf()) {
if (!obstacle_conf.has_obstacle_type()) {
AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
<< "] has not defined obstacle type.";
continue;
}
if (!obstacle_conf.has_predictor_type()) {
AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
<< "] has not defined predictor type.";
continue;
}
switch (obstacle_conf.obstacle_type()) {
case PerceptionObstacle::VEHICLE: {
if (obstacle_conf.has_obstacle_status()) {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
vehicle_on_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::OFF_LANE) {
vehicle_off_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::IN_JUNCTION) {
vehicle_in_junction_predictor_ = obstacle_conf.predictor_type();
}
}
break;
}
case PerceptionObstacle::BICYCLE: {
if (obstacle_conf.has_obstacle_status()) {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
cyclist_on_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::OFF_LANE) {
cyclist_off_lane_predictor_ = obstacle_conf.predictor_type();
}
}
break;
}
case PerceptionObstacle::PEDESTRIAN: {
pedestrian_predictor_ = obstacle_conf.predictor_type();
break;
}
case PerceptionObstacle::UNKNOWN: {
if (obstacle_conf.has_obstacle_status()) {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
default_on_lane_predictor_ = obstacle_conf.predictor_type();
} else if (obstacle_conf.obstacle_status() ==
ObstacleConf::OFF_LANE) {
default_off_lane_predictor_ = obstacle_conf.predictor_type();
}
}
break;
}
default: { break; }
}
}
AINFO << "Defined vehicle on lane obstacle predictor ["
<< vehicle_on_lane_predictor_ << "].";
AINFO << "Defined vehicle off lane obstacle predictor ["
<< vehicle_off_lane_predictor_ << "].";
AINFO << "Defined bicycle on lane obstacle predictor ["
<< cyclist_on_lane_predictor_ << "].";
AINFO << "Defined bicycle off lane obstacle predictor ["
<< cyclist_off_lane_predictor_ << "].";
AINFO << "Defined pedestrian obstacle predictor [" << pedestrian_predictor_
<< "].";
AINFO << "Defined default on lane obstacle predictor ["
<< default_on_lane_predictor_ << "].";
AINFO << "Defined default off lane obstacle predictor ["
<< default_off_lane_predictor_ << "].";
}
Predictor* PredictorManager::GetPredictor(
const ObstacleConf::PredictorType& type) {
auto it = predictors_.find(type);
return it != predictors_.end() ? it->second.get() : nullptr;
}
void PredictorManager::Run() {
prediction_obstacles_.Clear();
auto obstacles_container =
ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
auto adc_trajectory_container =
ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
CHECK_NOTNULL(obstacles_container);
for (const int id : obstacles_container->curr_frame_obstacle_ids()) {
if (id < 0) {
ADEBUG << "The obstacle has invalid id [" << id << "].";
continue;
}
PredictionObstacle prediction_obstacle;
Obstacle* obstacle = obstacles_container->GetObstacle(id);
PerceptionObstacle perception_obstacle =
obstacles_container->GetPerceptionObstacle(id);
// if obstacle == nullptr, that means obstacle is not predictable
// Checkout the logic of non-predictable in obstacle.cc
if (obstacle != nullptr) {
PredictObstacle(obstacle, &prediction_obstacle, adc_trajectory_container);
} else { // obstacle == nullptr
prediction_obstacle.set_timestamp(perception_obstacle.timestamp());
prediction_obstacle.set_is_static(true);
}
prediction_obstacle.set_predicted_period(
FLAGS_prediction_trajectory_time_length);
prediction_obstacle.mutable_perception_obstacle()->CopyFrom(
perception_obstacle);
prediction_obstacles_.add_prediction_obstacle()->CopyFrom(
prediction_obstacle);
}
}
void PredictorManager::PredictObstacle(
Obstacle* obstacle, PredictionObstacle* const prediction_obstacle,
ADCTrajectoryContainer* adc_trajectory_container) {
CHECK_NOTNULL(obstacle);
Predictor* predictor = nullptr;
prediction_obstacle->set_timestamp(obstacle->timestamp());
if (obstacle->ToIgnore()) {
ADEBUG << "Ignore obstacle [" << obstacle->id() << "]";
predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
prediction_obstacle->mutable_priority()->set_priority(
ObstaclePriority::IGNORE);
} else if (obstacle->IsStill()) {
ADEBUG << "Still obstacle [" << obstacle->id() << "]";
predictor = GetPredictor(ObstacleConf::EMPTY_PREDICTOR);
} else {
switch (obstacle->type()) {
case PerceptionObstacle::VEHICLE: {
if (obstacle->HasJunctionFeatureWithExits() &&
!obstacle->IsCloseToJunctionExit()) {
predictor = GetPredictor(vehicle_in_junction_predictor_);
CHECK_NOTNULL(predictor);
} else if (obstacle->IsOnLane()) {
predictor = GetPredictor(vehicle_on_lane_predictor_);
CHECK_NOTNULL(predictor);
} else {
predictor = GetPredictor(vehicle_off_lane_predictor_);
CHECK_NOTNULL(predictor);
}
break;
}
case PerceptionObstacle::PEDESTRIAN: {
predictor = GetPredictor(pedestrian_predictor_);
break;
}
case PerceptionObstacle::BICYCLE: {
if (obstacle->IsOnLane()) {
predictor = GetPredictor(cyclist_on_lane_predictor_);
// TODO(kechxu) add a specific predictor in junction
} else {
predictor = GetPredictor(cyclist_off_lane_predictor_);
}
break;
}
default: {
if (obstacle->IsOnLane()) {
predictor = GetPredictor(default_on_lane_predictor_);
} else {
predictor = GetPredictor(default_off_lane_predictor_);
}
break;
}
}
}
if (predictor != nullptr) {
predictor->Predict(obstacle);
if (FLAGS_enable_trim_prediction_trajectory &&
obstacle->type() == PerceptionObstacle::VEHICLE) {
CHECK_NOTNULL(adc_trajectory_container);
predictor->TrimTrajectories(obstacle, adc_trajectory_container);
}
for (const auto& trajectory : predictor->trajectories()) {
prediction_obstacle->add_trajectory()->CopyFrom(trajectory);
}
}
prediction_obstacle->set_timestamp(obstacle->timestamp());
prediction_obstacle->mutable_priority()->CopyFrom(
obstacle->latest_feature().priority());
prediction_obstacle->set_is_static(obstacle->IsStill());
if (FLAGS_prediction_offline_mode == 3) {
FeatureOutput::InsertPredictionResult(obstacle->id(), *prediction_obstacle);
}
}
std::unique_ptr<Predictor> PredictorManager::CreatePredictor(
const ObstacleConf::PredictorType& type) {
std::unique_ptr<Predictor> predictor_ptr(nullptr);
switch (type) {
case ObstacleConf::LANE_SEQUENCE_PREDICTOR: {
predictor_ptr.reset(new LaneSequencePredictor());
break;
}
case ObstacleConf::MOVE_SEQUENCE_PREDICTOR: {
predictor_ptr.reset(new MoveSequencePredictor());
break;
}
case ObstacleConf::SINGLE_LANE_PREDICTOR: {
predictor_ptr.reset(new SingleLanePredictor());
break;
}
case ObstacleConf::FREE_MOVE_PREDICTOR: {
predictor_ptr.reset(new FreeMovePredictor());
break;
}
case ObstacleConf::REGIONAL_PREDICTOR: {
predictor_ptr.reset(new RegionalPredictor());
break;
}
case ObstacleConf::JUNCTION_PREDICTOR: {
predictor_ptr.reset(new JunctionPredictor());
break;
}
default: { break; }
}
return predictor_ptr;
}
void PredictorManager::RegisterPredictor(
const ObstacleConf::PredictorType& type) {
predictors_[type] = CreatePredictor(type);
AINFO << "Predictor [" << type << "] is registered.";
}
const PredictionObstacles& PredictorManager::prediction_obstacles() {
return prediction_obstacles_;
}
} // namespace prediction
} // namespace apollo
<|endoftext|>
|
<commit_before>/* Copyright (C) 2004 MySQL AB
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Utility program that encapsulates process creation, monitoring
and bulletproof process cleanup
Usage:
safe_process [options to safe_process] -- progname arg1 ... argn
To safeguard mysqld you would invoke safe_process with a few options
for safe_process itself followed by a double dash to indicate start
of the command line for the program you really want to start
$> safe_process --output=output.log -- mysqld --datadir=var/data1 ...
This would redirect output to output.log and then start mysqld,
once it has done that it will continue to monitor the child as well
as the parent.
The safe_process then checks the follwing things:
1. Child exits, propagate the childs return code to the parent
by exiting with the same return code as the child.
2. Parent dies, immediately kill the child and exit, thus the
parent does not need to properly cleanup any child, it is handled
automatically.
3. Signal's recieced by the process will trigger same action as 2)
4. The named event "safe_process[pid]" can be signaled and will
trigger same action as 2)
WARNING! Be careful when using ProcessExplorer, since it will open
a handle to each process(and maybe also the Job), the process
spawned by safe_process will not be closed off when safe_process
is killed.
*/
/* Requires Windows 2000 or higher */
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <signal.h>
static int verbose= 0;
static char safe_process_name[32]= {0};
static void message(const char* fmt, ...)
{
if (!verbose)
return;
va_list args;
fprintf(stderr, "%s: ", safe_process_name);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
fflush(stderr);
}
static void die(const char* fmt, ...)
{
va_list args;
fprintf(stderr, "%s: FATAL ERROR, ", safe_process_name);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
if (int last_err= GetLastError())
fprintf(stderr, "error: %d, %s\n", last_err, strerror(last_err));
fflush(stderr);
exit(1);
}
DWORD get_parent_pid(DWORD pid)
{
HANDLE snapshot;
DWORD parent_pid= -1;
PROCESSENTRY32 pe32;
pe32.dwSize= sizeof(PROCESSENTRY32);
snapshot= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
die("CreateToolhelp32Snapshot failed");
if (!Process32First(snapshot, &pe32))
{
CloseHandle(snapshot);
die("Process32First failed");
}
do
{
if (pe32.th32ProcessID == pid)
parent_pid= pe32.th32ParentProcessID;
} while(Process32Next( snapshot, &pe32));
CloseHandle(snapshot);
if (parent_pid == -1)
die("Could not find parent pid");
return parent_pid;
}
enum {
PARENT,
CHILD,
EVENT,
NUM_HANDLES
};
HANDLE shutdown_event;
void handle_signal (int signal)
{
message("Got signal: %d", signal);
if(SetEvent(shutdown_event) == 0) {
/* exit safe_process and (hopefully) kill off the child */
die("Failed to SetEvent");
}
}
int main(int argc, const char** argv )
{
char child_args[4096]= {0};
DWORD pid= GetCurrentProcessId();
DWORD parent_pid= get_parent_pid(pid);
HANDLE job_handle;
HANDLE wait_handles[NUM_HANDLES]= {0};
PROCESS_INFORMATION process_info= {0};
sprintf(safe_process_name, "safe_process[%d]", pid);
/* Create an event for the signal handler */
if ((shutdown_event=
CreateEvent(NULL, TRUE, FALSE, safe_process_name)) == NULL)
die("Failed to create shutdown_event");
wait_handles[EVENT]= shutdown_event;
signal(SIGINT, handle_signal);
signal(SIGBREAK, handle_signal);
signal(SIGTERM, handle_signal);
message("Started");
/* Parse arguments */
for (int i= 1; i < argc; i++) {
const char* arg= argv[i];
char* to= child_args;
if (strcmp(arg, "--") == 0 && strlen(arg) == 2) {
/* Got the "--" delimiter */
if (i >= argc)
die("No real args -> nothing to do");
/* Copy the remaining args to child_arg */
for (int j= i+1; j < argc; j++) {
to+= _snprintf(to, child_args + sizeof(child_args) - to, "%s ", argv[j]);
}
break;
} else {
if ( strcmp(arg, "--verbose") == 0 )
verbose++;
else if ( strncmp(arg, "--parent-pid", 10) == 0 )
{
/* Override parent_pid with a value provided by user */
const char* start;
if ((start= strstr(arg, "=")) == NULL)
die("Could not find start of option value in '%s'", arg);
start++; /* Step past = */
if ((parent_pid= atoi(start)) == 0)
die("Invalid value '%s' passed to --parent-id", start);
}
else
die("Unknown option: %s", arg);
}
}
if (*child_args == '\0')
die("nothing to do");
/* Open a handle to the parent process */
message("parent_pid: %d", parent_pid);
if (parent_pid == pid)
die("parent_pid is equal to own pid!");
if ((wait_handles[PARENT]=
OpenProcess(SYNCHRONIZE, FALSE, parent_pid)) == NULL)
die("Failed to open parent process with pid: %d", parent_pid);
/* Create the child process in a job */
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
/*
Create the job object to make it possible to kill the process
and all of it's children in one go
*/
if ((job_handle= CreateJobObject(NULL, NULL)) == NULL)
die("CreateJobObject failed");
/*
Make all processes associated with the job terminate when the
last handle to the job is closed.
*/
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if (SetInformationJobObject(job_handle, JobObjectExtendedLimitInformation,
&jeli, sizeof(jeli)) == 0)
message("SetInformationJobObject failed, continue anyway...");
#if 0
/* Setup stdin, stdout and stderr redirect */
si.dwFlags= STARTF_USESTDHANDLES;
si.hStdInput= GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput= GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError= GetStdHandle(STD_ERROR_HANDLE);
#endif
/*
Create the process suspended to make sure it's assigned to the
Job before it creates any process of it's own
*/
if (CreateProcess(NULL, (LPSTR)child_args,
NULL,
NULL,
TRUE, /* inherit handles */
CREATE_SUSPENDED,
NULL,
NULL,
&si,
&process_info) == 0)
die("CreateProcess failed");
if (AssignProcessToJobObject(job_handle, process_info.hProcess) == 0)
{
TerminateProcess(process_info.hProcess, 200);
die("AssignProcessToJobObject failed");
}
ResumeThread(process_info.hThread);
CloseHandle(process_info.hThread);
wait_handles[CHILD]= process_info.hProcess;
message("Started child %d", process_info.dwProcessId);
/* Monitor loop */
DWORD child_exit_code= 1;
DWORD wait_res= WaitForMultipleObjects(NUM_HANDLES, wait_handles,
FALSE, INFINITE);
switch (wait_res)
{
case WAIT_OBJECT_0 + PARENT:
message("Parent exit");
break;
case WAIT_OBJECT_0 + CHILD:
if (GetExitCodeProcess(wait_handles[CHILD], &child_exit_code) == 0)
message("Child exit: could not get exit_code");
else
message("Child exit: exit_code: %d", child_exit_code);
break;
case WAIT_OBJECT_0 + EVENT:
message("Wake up from shutdown_event");
break;
default:
message("Unexpected result %d from WaitForMultipleObjects", wait_res);
break;
}
message("Exiting, child: %d", process_info.dwProcessId);
if (TerminateJobObject(job_handle, 201) == 0)
message("TerminateJobObject failed");
CloseHandle(job_handle);
if (wait_res != WAIT_OBJECT_0 + CHILD)
{
/* The child has not yet returned, wait for it */
message("waiting for child to exit");
if ((wait_res= WaitForSingleObject(wait_handles[CHILD], INFINITE)) != WAIT_OBJECT_0)
{
message("child wait failed: %d", wait_res);
}
else
{
message("child wait succeeded");
}
/* Child's exit code should now be 201, no need to get it */
}
for (int i= 0; i < NUM_HANDLES; i++)
CloseHandle(wait_handles[i]);
exit(child_exit_code);
}
<commit_msg>Add additional printouts Fix formatting<commit_after>/* Copyright (C) 2004 MySQL AB
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; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
Utility program that encapsulates process creation, monitoring
and bulletproof process cleanup
Usage:
safe_process [options to safe_process] -- progname arg1 ... argn
To safeguard mysqld you would invoke safe_process with a few options
for safe_process itself followed by a double dash to indicate start
of the command line for the program you really want to start
$> safe_process --output=output.log -- mysqld --datadir=var/data1 ...
This would redirect output to output.log and then start mysqld,
once it has done that it will continue to monitor the child as well
as the parent.
The safe_process then checks the follwing things:
1. Child exits, propagate the childs return code to the parent
by exiting with the same return code as the child.
2. Parent dies, immediately kill the child and exit, thus the
parent does not need to properly cleanup any child, it is handled
automatically.
3. Signal's recieced by the process will trigger same action as 2)
4. The named event "safe_process[pid]" can be signaled and will
trigger same action as 2)
WARNING! Be careful when using ProcessExplorer, since it will open
a handle to each process(and maybe also the Job), the process
spawned by safe_process will not be closed off when safe_process
is killed.
*/
/* Requires Windows 2000 or higher */
#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <signal.h>
static int verbose= 0;
static char safe_process_name[32]= {0};
static void message(const char* fmt, ...)
{
if (!verbose)
return;
va_list args;
fprintf(stderr, "%s: ", safe_process_name);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
fflush(stderr);
}
static void die(const char* fmt, ...)
{
va_list args;
fprintf(stderr, "%s: FATAL ERROR, ", safe_process_name);
va_start(args, fmt);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
if (int last_err= GetLastError())
fprintf(stderr, "error: %d, %s\n", last_err, strerror(last_err));
fflush(stderr);
exit(1);
}
DWORD get_parent_pid(DWORD pid)
{
HANDLE snapshot;
DWORD parent_pid= -1;
PROCESSENTRY32 pe32;
pe32.dwSize= sizeof(PROCESSENTRY32);
snapshot= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
die("CreateToolhelp32Snapshot failed");
if (!Process32First(snapshot, &pe32))
{
CloseHandle(snapshot);
die("Process32First failed");
}
do
{
if (pe32.th32ProcessID == pid)
parent_pid= pe32.th32ParentProcessID;
} while(Process32Next( snapshot, &pe32));
CloseHandle(snapshot);
if (parent_pid == -1)
die("Could not find parent pid");
return parent_pid;
}
enum {
PARENT,
CHILD,
EVENT,
NUM_HANDLES
};
HANDLE shutdown_event;
void handle_signal (int signal)
{
message("Got signal: %d", signal);
if(SetEvent(shutdown_event) == 0) {
/* exit safe_process and (hopefully) kill off the child */
die("Failed to SetEvent");
}
}
int main(int argc, const char** argv )
{
char child_args[4096]= {0};
DWORD pid= GetCurrentProcessId();
DWORD parent_pid= get_parent_pid(pid);
HANDLE job_handle;
HANDLE wait_handles[NUM_HANDLES]= {0};
PROCESS_INFORMATION process_info= {0};
sprintf(safe_process_name, "safe_process[%d]", pid);
/* Create an event for the signal handler */
if ((shutdown_event=
CreateEvent(NULL, TRUE, FALSE, safe_process_name)) == NULL)
die("Failed to create shutdown_event");
wait_handles[EVENT]= shutdown_event;
signal(SIGINT, handle_signal);
signal(SIGBREAK, handle_signal);
signal(SIGTERM, handle_signal);
message("Started");
/* Parse arguments */
for (int i= 1; i < argc; i++) {
const char* arg= argv[i];
char* to= child_args;
if (strcmp(arg, "--") == 0 && strlen(arg) == 2) {
/* Got the "--" delimiter */
if (i >= argc)
die("No real args -> nothing to do");
/* Copy the remaining args to child_arg */
for (int j= i+1; j < argc; j++) {
to+= _snprintf(to, child_args + sizeof(child_args) - to, "%s ", argv[j]);
}
break;
} else {
if ( strcmp(arg, "--verbose") == 0 )
verbose++;
else if ( strncmp(arg, "--parent-pid", 10) == 0 )
{
/* Override parent_pid with a value provided by user */
const char* start;
if ((start= strstr(arg, "=")) == NULL)
die("Could not find start of option value in '%s'", arg);
start++; /* Step past = */
if ((parent_pid= atoi(start)) == 0)
die("Invalid value '%s' passed to --parent-id", start);
}
else
die("Unknown option: %s", arg);
}
}
if (*child_args == '\0')
die("nothing to do");
/* Open a handle to the parent process */
message("parent_pid: %d", parent_pid);
if (parent_pid == pid)
die("parent_pid is equal to own pid!");
if ((wait_handles[PARENT]=
OpenProcess(SYNCHRONIZE, FALSE, parent_pid)) == NULL)
die("Failed to open parent process with pid: %d", parent_pid);
/* Create the child process in a job */
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
/*
Create the job object to make it possible to kill the process
and all of it's children in one go
*/
if ((job_handle= CreateJobObject(NULL, NULL)) == NULL)
die("CreateJobObject failed");
/*
Make all processes associated with the job terminate when the
last handle to the job is closed.
*/
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if (SetInformationJobObject(job_handle, JobObjectExtendedLimitInformation,
&jeli, sizeof(jeli)) == 0)
message("SetInformationJobObject failed, continue anyway...");
#if 0
/* Setup stdin, stdout and stderr redirect */
si.dwFlags= STARTF_USESTDHANDLES;
si.hStdInput= GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput= GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError= GetStdHandle(STD_ERROR_HANDLE);
#endif
/*
Create the process suspended to make sure it's assigned to the
Job before it creates any process of it's own
*/
if (CreateProcess(NULL, (LPSTR)child_args,
NULL,
NULL,
TRUE, /* inherit handles */
CREATE_SUSPENDED,
NULL,
NULL,
&si,
&process_info) == 0)
die("CreateProcess failed");
if (AssignProcessToJobObject(job_handle, process_info.hProcess) == 0)
{
TerminateProcess(process_info.hProcess, 200);
die("AssignProcessToJobObject failed");
}
ResumeThread(process_info.hThread);
CloseHandle(process_info.hThread);
wait_handles[CHILD]= process_info.hProcess;
message("Started child %d", process_info.dwProcessId);
/* Monitor loop */
DWORD child_exit_code= 1;
DWORD wait_res= WaitForMultipleObjects(NUM_HANDLES, wait_handles,
FALSE, INFINITE);
switch (wait_res)
{
case WAIT_OBJECT_0 + PARENT:
message("Parent exit");
break;
case WAIT_OBJECT_0 + CHILD:
if (GetExitCodeProcess(wait_handles[CHILD], &child_exit_code) == 0)
message("Child exit: could not get exit_code");
else
message("Child exit: exit_code: %d", child_exit_code);
break;
case WAIT_OBJECT_0 + EVENT:
message("Wake up from shutdown_event");
break;
default:
message("Unexpected result %d from WaitForMultipleObjects", wait_res);
break;
}
message("Exiting, child: %d", process_info.dwProcessId);
if (TerminateJobObject(job_handle, 201) == 0)
message("TerminateJobObject failed");
CloseHandle(job_handle);
message("Job terminated and closed");
if (wait_res != WAIT_OBJECT_0 + CHILD)
{
/* The child has not yet returned, wait for it */
message("waiting for child to exit");
if ((wait_res= WaitForSingleObject(wait_handles[CHILD], INFINITE))
!= WAIT_OBJECT_0)
{
message("child wait failed: %d", wait_res);
}
else
{
message("child wait succeeded");
}
/* Child's exit code should now be 201, no need to get it */
}
message("Closing handles");
for (int i= 0; i < NUM_HANDLES; i++)
CloseHandle(wait_handles[i]);
message("Exiting, exit_code: %d", child_exit_code);
exit(child_exit_code);
}
<|endoftext|>
|
<commit_before>//===-- OperatingSystemPython.cpp --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/lldb-python.h"
#ifndef LLDB_DISABLE_PYTHON
#include "OperatingSystemPython.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/DataBufferHeap.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/RegisterValue.h"
#include "lldb/Core/ValueObjectVariable.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/PythonDataObjects.h"
#include "lldb/Symbol/ClangNamespaceDecl.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/ThreadList.h"
#include "lldb/Target/Thread.h"
#include "Plugins/Process/Utility/DynamicRegisterInfo.h"
#include "Plugins/Process/Utility/RegisterContextMemory.h"
#include "Plugins/Process/Utility/ThreadMemory.h"
using namespace lldb;
using namespace lldb_private;
void
OperatingSystemPython::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
}
void
OperatingSystemPython::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
OperatingSystem *
OperatingSystemPython::CreateInstance (Process *process, bool force)
{
// Python OperatingSystem plug-ins must be requested by name, so force must be true
FileSpec python_os_plugin_spec (process->GetPythonOSPluginPath());
if (python_os_plugin_spec && python_os_plugin_spec.Exists())
{
std::auto_ptr<OperatingSystemPython> os_ap (new OperatingSystemPython (process, python_os_plugin_spec));
if (os_ap.get() && os_ap->IsValid())
return os_ap.release();
}
return NULL;
}
const char *
OperatingSystemPython::GetPluginNameStatic()
{
return "python";
}
const char *
OperatingSystemPython::GetPluginDescriptionStatic()
{
return "Operating system plug-in that gathers OS information from a python class that implements the necessary OperatingSystem functionality.";
}
OperatingSystemPython::OperatingSystemPython (lldb_private::Process *process, const FileSpec &python_module_path) :
OperatingSystem (process),
m_thread_list_valobj_sp (),
m_register_info_ap (),
m_interpreter (NULL),
m_python_object_sp ()
{
if (!process)
return;
TargetSP target_sp = process->CalculateTarget();
if (!target_sp)
return;
m_interpreter = target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
if (m_interpreter)
{
std::string os_plugin_class_name (python_module_path.GetFilename().AsCString(""));
if (!os_plugin_class_name.empty())
{
const bool init_session = false;
const bool allow_reload = true;
char python_module_path_cstr[PATH_MAX];
python_module_path.GetPath(python_module_path_cstr, sizeof(python_module_path_cstr));
Error error;
if (m_interpreter->LoadScriptingModule (python_module_path_cstr, allow_reload, init_session, error))
{
// Strip the ".py" extension if there is one
size_t py_extension_pos = os_plugin_class_name.rfind(".py");
if (py_extension_pos != std::string::npos)
os_plugin_class_name.erase (py_extension_pos);
// Add ".OperatingSystemPlugIn" to the module name to get a string like "modulename.OperatingSystemPlugIn"
os_plugin_class_name += ".OperatingSystemPlugIn";
ScriptInterpreterObjectSP object_sp = m_interpreter->OSPlugin_CreatePluginObject(os_plugin_class_name.c_str(), process->CalculateProcess());
if (object_sp && object_sp->GetObject())
m_python_object_sp = object_sp;
}
}
}
}
OperatingSystemPython::~OperatingSystemPython ()
{
}
DynamicRegisterInfo *
OperatingSystemPython::GetDynamicRegisterInfo ()
{
if (m_register_info_ap.get() == NULL)
{
if (!m_interpreter || !m_python_object_sp)
return NULL;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
if (log)
log->Printf ("OperatingSystemPython::GetDynamicRegisterInfo() fetching thread register definitions from python for pid %" PRIu64, m_process->GetID());
PythonDictionary dictionary(m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp));
if (!dictionary)
return NULL;
m_register_info_ap.reset (new DynamicRegisterInfo (dictionary));
assert (m_register_info_ap->GetNumRegisters() > 0);
assert (m_register_info_ap->GetNumRegisterSets() > 0);
}
return m_register_info_ap.get();
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
OperatingSystemPython::GetPluginName()
{
return "OperatingSystemPython";
}
const char *
OperatingSystemPython::GetShortPluginName()
{
return GetPluginNameStatic();
}
uint32_t
OperatingSystemPython::GetPluginVersion()
{
return 1;
}
bool
OperatingSystemPython::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
{
if (!m_interpreter || !m_python_object_sp)
return false;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
// First thing we have to do is get the API lock, and the run lock. We're going to change the thread
// content of the process, and we're going to use python, which requires the API lock to do it.
// So get & hold that. This is a recursive lock so we can grant it to any Python code called on the stack below us.
Target &target = m_process->GetTarget();
Mutex::Locker api_locker (target.GetAPIMutex());
if (log)
log->Printf ("OperatingSystemPython::UpdateThreadList() fetching thread data from python for pid %" PRIu64, m_process->GetID());
// The threads that are in "new_thread_list" upon entry are the threads from the
// lldb_private::Process subclass, no memory threads will be in this list.
auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure threads_list stays alive
PythonList threads_list(m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp));
if (threads_list)
{
ThreadList core_thread_list(new_thread_list);
threads_list.Dump(); // REMOVE THIS
uint32_t i;
const uint32_t num_threads = threads_list.GetSize();
for (i=0; i<num_threads; ++i)
{
PythonDictionary thread_dict(threads_list.GetItemAtIndex(i));
if (thread_dict)
{
if (thread_dict.GetItemForKey("core"))
{
// We have some threads that are saying they are on a "core", which means
// they map the threads that are gotten from the lldb_private::Process subclass
// so clear the new threads list so the core threads don't show up
new_thread_list.Clear();
break;
}
}
}
for (i=0; i<num_threads; ++i)
{
PythonDictionary thread_dict(threads_list.GetItemAtIndex(i));
if (thread_dict)
{
ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_dict, core_thread_list, old_thread_list, NULL));
if (thread_sp)
new_thread_list.AddThread(thread_sp);
}
}
}
else
{
new_thread_list = old_thread_list;
}
return new_thread_list.GetSize(false) > 0;
}
ThreadSP
OperatingSystemPython::CreateThreadFromThreadInfo (PythonDictionary &thread_dict,
ThreadList &core_thread_list,
ThreadList &old_thread_list,
bool *did_create_ptr)
{
ThreadSP thread_sp;
if (thread_dict)
{
PythonString tid_pystr("tid");
const tid_t tid = thread_dict.GetItemForKeyAsInteger (tid_pystr, LLDB_INVALID_THREAD_ID);
if (tid != LLDB_INVALID_THREAD_ID)
{
PythonString core_pystr("core");
PythonString name_pystr("name");
PythonString queue_pystr("queue");
PythonString state_pystr("state");
PythonString stop_reason_pystr("stop_reason");
PythonString reg_data_addr_pystr ("register_data_addr");
const uint32_t core_number = thread_dict.GetItemForKeyAsInteger (core_pystr, UINT32_MAX);
const addr_t reg_data_addr = thread_dict.GetItemForKeyAsInteger (reg_data_addr_pystr, LLDB_INVALID_ADDRESS);
const char *name = thread_dict.GetItemForKeyAsString (name_pystr);
const char *queue = thread_dict.GetItemForKeyAsString (queue_pystr);
//const char *state = thread_dict.GetItemForKeyAsString (state_pystr);
//const char *stop_reason = thread_dict.GetItemForKeyAsString (stop_reason_pystr);
thread_sp = old_thread_list.FindThreadByID (tid, false);
if (!thread_sp)
{
if (did_create_ptr)
*did_create_ptr = true;
thread_sp.reset (new ThreadMemory (*m_process,
tid,
name,
queue,
reg_data_addr));
}
if (core_number < core_thread_list.GetSize(false))
{
thread_sp->SetBackingThread(core_thread_list.GetThreadAtIndex(core_number, false));
}
}
}
return thread_sp;
}
void
OperatingSystemPython::ThreadWasSelected (Thread *thread)
{
}
RegisterContextSP
OperatingSystemPython::CreateRegisterContextForThread (Thread *thread, addr_t reg_data_addr)
{
RegisterContextSP reg_ctx_sp;
if (!m_interpreter || !m_python_object_sp || !thread)
return RegisterContextSP();
// First thing we have to do is get the API lock, and the run lock. We're going to change the thread
// content of the process, and we're going to use python, which requires the API lock to do it.
// So get & hold that. This is a recursive lock so we can grant it to any Python code called on the stack below us.
Target &target = m_process->GetTarget();
Mutex::Locker api_locker (target.GetAPIMutex());
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure python objects stays alive
if (reg_data_addr != LLDB_INVALID_ADDRESS)
{
// The registers data is in contiguous memory, just create the register
// context using the address provided
if (log)
log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64 ") creating memory register context", thread->GetID(), reg_data_addr);
reg_ctx_sp.reset (new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), reg_data_addr));
}
else
{
// No register data address is provided, query the python plug-in to let
// it make up the data as it sees fit
if (log)
log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ") fetching register data from python", thread->GetID());
PythonString reg_context_data(m_interpreter->OSPlugin_RegisterContextData (m_python_object_sp, thread->GetID()));
if (reg_context_data)
{
DataBufferSP data_sp (new DataBufferHeap (reg_context_data.GetString(),
reg_context_data.GetSize()));
if (data_sp->GetByteSize())
{
RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), LLDB_INVALID_ADDRESS);
if (reg_ctx_memory)
{
reg_ctx_sp.reset(reg_ctx_memory);
reg_ctx_memory->SetAllRegisterData (data_sp);
}
}
}
}
return reg_ctx_sp;
}
StopInfoSP
OperatingSystemPython::CreateThreadStopReason (lldb_private::Thread *thread)
{
// We should have gotten the thread stop info from the dictionary of data for
// the thread in the initial call to get_thread_info(), this should have been
// cached so we can return it here
StopInfoSP stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
return stop_info_sp;
}
lldb::ThreadSP
OperatingSystemPython::CreateThread (lldb::tid_t tid, addr_t context)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
if (log)
log->Printf ("OperatingSystemPython::CreateThread (tid = 0x%" PRIx64 ", context = 0x%" PRIx64 ") fetching register data from python", tid, context);
if (m_interpreter && m_python_object_sp)
{
// First thing we have to do is get the API lock, and the run lock. We're going to change the thread
// content of the process, and we're going to use python, which requires the API lock to do it.
// So get & hold that. This is a recursive lock so we can grant it to any Python code called on the stack below us.
Target &target = m_process->GetTarget();
Mutex::Locker api_locker (target.GetAPIMutex());
auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure thread_info_dict stays alive
PythonDictionary thread_info_dict (m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context));
if (thread_info_dict)
{
ThreadList core_threads(m_process);
ThreadList &thread_list = m_process->GetThreadList();
bool did_create = false;
ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_info_dict, core_threads, thread_list, &did_create));
if (did_create)
thread_list.AddThread(thread_sp);
return thread_sp;
}
}
return ThreadSP();
}
#endif // #ifndef LLDB_DISABLE_PYTHON
<commit_msg>Remove a debug print statement that I left in.<commit_after>//===-- OperatingSystemPython.cpp --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/lldb-python.h"
#ifndef LLDB_DISABLE_PYTHON
#include "OperatingSystemPython.h"
// C Includes
// C++ Includes
// Other libraries and framework includes
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/DataBufferHeap.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/RegisterValue.h"
#include "lldb/Core/ValueObjectVariable.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/PythonDataObjects.h"
#include "lldb/Symbol/ClangNamespaceDecl.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/StopInfo.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/ThreadList.h"
#include "lldb/Target/Thread.h"
#include "Plugins/Process/Utility/DynamicRegisterInfo.h"
#include "Plugins/Process/Utility/RegisterContextMemory.h"
#include "Plugins/Process/Utility/ThreadMemory.h"
using namespace lldb;
using namespace lldb_private;
void
OperatingSystemPython::Initialize()
{
PluginManager::RegisterPlugin (GetPluginNameStatic(),
GetPluginDescriptionStatic(),
CreateInstance);
}
void
OperatingSystemPython::Terminate()
{
PluginManager::UnregisterPlugin (CreateInstance);
}
OperatingSystem *
OperatingSystemPython::CreateInstance (Process *process, bool force)
{
// Python OperatingSystem plug-ins must be requested by name, so force must be true
FileSpec python_os_plugin_spec (process->GetPythonOSPluginPath());
if (python_os_plugin_spec && python_os_plugin_spec.Exists())
{
std::auto_ptr<OperatingSystemPython> os_ap (new OperatingSystemPython (process, python_os_plugin_spec));
if (os_ap.get() && os_ap->IsValid())
return os_ap.release();
}
return NULL;
}
const char *
OperatingSystemPython::GetPluginNameStatic()
{
return "python";
}
const char *
OperatingSystemPython::GetPluginDescriptionStatic()
{
return "Operating system plug-in that gathers OS information from a python class that implements the necessary OperatingSystem functionality.";
}
OperatingSystemPython::OperatingSystemPython (lldb_private::Process *process, const FileSpec &python_module_path) :
OperatingSystem (process),
m_thread_list_valobj_sp (),
m_register_info_ap (),
m_interpreter (NULL),
m_python_object_sp ()
{
if (!process)
return;
TargetSP target_sp = process->CalculateTarget();
if (!target_sp)
return;
m_interpreter = target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
if (m_interpreter)
{
std::string os_plugin_class_name (python_module_path.GetFilename().AsCString(""));
if (!os_plugin_class_name.empty())
{
const bool init_session = false;
const bool allow_reload = true;
char python_module_path_cstr[PATH_MAX];
python_module_path.GetPath(python_module_path_cstr, sizeof(python_module_path_cstr));
Error error;
if (m_interpreter->LoadScriptingModule (python_module_path_cstr, allow_reload, init_session, error))
{
// Strip the ".py" extension if there is one
size_t py_extension_pos = os_plugin_class_name.rfind(".py");
if (py_extension_pos != std::string::npos)
os_plugin_class_name.erase (py_extension_pos);
// Add ".OperatingSystemPlugIn" to the module name to get a string like "modulename.OperatingSystemPlugIn"
os_plugin_class_name += ".OperatingSystemPlugIn";
ScriptInterpreterObjectSP object_sp = m_interpreter->OSPlugin_CreatePluginObject(os_plugin_class_name.c_str(), process->CalculateProcess());
if (object_sp && object_sp->GetObject())
m_python_object_sp = object_sp;
}
}
}
}
OperatingSystemPython::~OperatingSystemPython ()
{
}
DynamicRegisterInfo *
OperatingSystemPython::GetDynamicRegisterInfo ()
{
if (m_register_info_ap.get() == NULL)
{
if (!m_interpreter || !m_python_object_sp)
return NULL;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
if (log)
log->Printf ("OperatingSystemPython::GetDynamicRegisterInfo() fetching thread register definitions from python for pid %" PRIu64, m_process->GetID());
PythonDictionary dictionary(m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp));
if (!dictionary)
return NULL;
m_register_info_ap.reset (new DynamicRegisterInfo (dictionary));
assert (m_register_info_ap->GetNumRegisters() > 0);
assert (m_register_info_ap->GetNumRegisterSets() > 0);
}
return m_register_info_ap.get();
}
//------------------------------------------------------------------
// PluginInterface protocol
//------------------------------------------------------------------
const char *
OperatingSystemPython::GetPluginName()
{
return "OperatingSystemPython";
}
const char *
OperatingSystemPython::GetShortPluginName()
{
return GetPluginNameStatic();
}
uint32_t
OperatingSystemPython::GetPluginVersion()
{
return 1;
}
bool
OperatingSystemPython::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
{
if (!m_interpreter || !m_python_object_sp)
return false;
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
// First thing we have to do is get the API lock, and the run lock. We're going to change the thread
// content of the process, and we're going to use python, which requires the API lock to do it.
// So get & hold that. This is a recursive lock so we can grant it to any Python code called on the stack below us.
Target &target = m_process->GetTarget();
Mutex::Locker api_locker (target.GetAPIMutex());
if (log)
log->Printf ("OperatingSystemPython::UpdateThreadList() fetching thread data from python for pid %" PRIu64, m_process->GetID());
// The threads that are in "new_thread_list" upon entry are the threads from the
// lldb_private::Process subclass, no memory threads will be in this list.
auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure threads_list stays alive
PythonList threads_list(m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp));
if (threads_list)
{
ThreadList core_thread_list(new_thread_list);
uint32_t i;
const uint32_t num_threads = threads_list.GetSize();
for (i=0; i<num_threads; ++i)
{
PythonDictionary thread_dict(threads_list.GetItemAtIndex(i));
if (thread_dict)
{
if (thread_dict.GetItemForKey("core"))
{
// We have some threads that are saying they are on a "core", which means
// they map the threads that are gotten from the lldb_private::Process subclass
// so clear the new threads list so the core threads don't show up
new_thread_list.Clear();
break;
}
}
}
for (i=0; i<num_threads; ++i)
{
PythonDictionary thread_dict(threads_list.GetItemAtIndex(i));
if (thread_dict)
{
ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_dict, core_thread_list, old_thread_list, NULL));
if (thread_sp)
new_thread_list.AddThread(thread_sp);
}
}
}
else
{
new_thread_list = old_thread_list;
}
return new_thread_list.GetSize(false) > 0;
}
ThreadSP
OperatingSystemPython::CreateThreadFromThreadInfo (PythonDictionary &thread_dict,
ThreadList &core_thread_list,
ThreadList &old_thread_list,
bool *did_create_ptr)
{
ThreadSP thread_sp;
if (thread_dict)
{
PythonString tid_pystr("tid");
const tid_t tid = thread_dict.GetItemForKeyAsInteger (tid_pystr, LLDB_INVALID_THREAD_ID);
if (tid != LLDB_INVALID_THREAD_ID)
{
PythonString core_pystr("core");
PythonString name_pystr("name");
PythonString queue_pystr("queue");
PythonString state_pystr("state");
PythonString stop_reason_pystr("stop_reason");
PythonString reg_data_addr_pystr ("register_data_addr");
const uint32_t core_number = thread_dict.GetItemForKeyAsInteger (core_pystr, UINT32_MAX);
const addr_t reg_data_addr = thread_dict.GetItemForKeyAsInteger (reg_data_addr_pystr, LLDB_INVALID_ADDRESS);
const char *name = thread_dict.GetItemForKeyAsString (name_pystr);
const char *queue = thread_dict.GetItemForKeyAsString (queue_pystr);
//const char *state = thread_dict.GetItemForKeyAsString (state_pystr);
//const char *stop_reason = thread_dict.GetItemForKeyAsString (stop_reason_pystr);
thread_sp = old_thread_list.FindThreadByID (tid, false);
if (!thread_sp)
{
if (did_create_ptr)
*did_create_ptr = true;
thread_sp.reset (new ThreadMemory (*m_process,
tid,
name,
queue,
reg_data_addr));
}
if (core_number < core_thread_list.GetSize(false))
{
thread_sp->SetBackingThread(core_thread_list.GetThreadAtIndex(core_number, false));
}
}
}
return thread_sp;
}
void
OperatingSystemPython::ThreadWasSelected (Thread *thread)
{
}
RegisterContextSP
OperatingSystemPython::CreateRegisterContextForThread (Thread *thread, addr_t reg_data_addr)
{
RegisterContextSP reg_ctx_sp;
if (!m_interpreter || !m_python_object_sp || !thread)
return RegisterContextSP();
// First thing we have to do is get the API lock, and the run lock. We're going to change the thread
// content of the process, and we're going to use python, which requires the API lock to do it.
// So get & hold that. This is a recursive lock so we can grant it to any Python code called on the stack below us.
Target &target = m_process->GetTarget();
Mutex::Locker api_locker (target.GetAPIMutex());
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure python objects stays alive
if (reg_data_addr != LLDB_INVALID_ADDRESS)
{
// The registers data is in contiguous memory, just create the register
// context using the address provided
if (log)
log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64 ") creating memory register context", thread->GetID(), reg_data_addr);
reg_ctx_sp.reset (new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), reg_data_addr));
}
else
{
// No register data address is provided, query the python plug-in to let
// it make up the data as it sees fit
if (log)
log->Printf ("OperatingSystemPython::CreateRegisterContextForThread (tid = 0x%" PRIx64 ") fetching register data from python", thread->GetID());
PythonString reg_context_data(m_interpreter->OSPlugin_RegisterContextData (m_python_object_sp, thread->GetID()));
if (reg_context_data)
{
DataBufferSP data_sp (new DataBufferHeap (reg_context_data.GetString(),
reg_context_data.GetSize()));
if (data_sp->GetByteSize())
{
RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory (*thread, 0, *GetDynamicRegisterInfo (), LLDB_INVALID_ADDRESS);
if (reg_ctx_memory)
{
reg_ctx_sp.reset(reg_ctx_memory);
reg_ctx_memory->SetAllRegisterData (data_sp);
}
}
}
}
return reg_ctx_sp;
}
StopInfoSP
OperatingSystemPython::CreateThreadStopReason (lldb_private::Thread *thread)
{
// We should have gotten the thread stop info from the dictionary of data for
// the thread in the initial call to get_thread_info(), this should have been
// cached so we can return it here
StopInfoSP stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP));
return stop_info_sp;
}
lldb::ThreadSP
OperatingSystemPython::CreateThread (lldb::tid_t tid, addr_t context)
{
Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
if (log)
log->Printf ("OperatingSystemPython::CreateThread (tid = 0x%" PRIx64 ", context = 0x%" PRIx64 ") fetching register data from python", tid, context);
if (m_interpreter && m_python_object_sp)
{
// First thing we have to do is get the API lock, and the run lock. We're going to change the thread
// content of the process, and we're going to use python, which requires the API lock to do it.
// So get & hold that. This is a recursive lock so we can grant it to any Python code called on the stack below us.
Target &target = m_process->GetTarget();
Mutex::Locker api_locker (target.GetAPIMutex());
auto lock = m_interpreter->AcquireInterpreterLock(); // to make sure thread_info_dict stays alive
PythonDictionary thread_info_dict (m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context));
if (thread_info_dict)
{
ThreadList core_threads(m_process);
ThreadList &thread_list = m_process->GetThreadList();
bool did_create = false;
ThreadSP thread_sp (CreateThreadFromThreadInfo (thread_info_dict, core_threads, thread_list, &did_create));
if (did_create)
thread_list.AddThread(thread_sp);
return thread_sp;
}
}
return ThreadSP();
}
#endif // #ifndef LLDB_DISABLE_PYTHON
<|endoftext|>
|
<commit_before>//
// Main.cpp
//
#include "pch.h"
#include "Game.h"
#include <shellapi.h>
using namespace DirectX;
namespace
{
std::unique_ptr<Game> g_game;
#ifdef WM_DEVICECHANGE
HDEVNOTIFY g_hNewAudio;
#endif
};
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void ParseCommandLine(_In_ LPWSTR lpCmdLine);
// Indicates to hybrid graphics systems to prefer the discrete part by default
extern "C"
{
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
if (!XMVerifyCPUSupport())
return 1;
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#if (_WIN32_WINNT >= 0x0A00 /*_WIN32_WINNT_WIN10*/)
Microsoft::WRL::Wrappers::RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
if (FAILED(initialize))
return 1;
#else
HRESULT hr = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED);
if (FAILED(hr))
return 1;
#endif
ParseCommandLine(lpCmdLine);
g_game = std::make_unique<Game>();
// Register class and create window
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, L"IDI_ICON");
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = L"D3D11TestWindowClass";
wcex.hIconSm = LoadIcon(wcex.hInstance, L"IDI_ICON");
if (!RegisterClassEx(&wcex))
return 1;
// Create window
int w, h;
g_game->GetDefaultSize(w, h);
RECT rc;
rc.top = 0;
rc.left = 0;
rc.right = static_cast<LONG>(w);
rc.bottom = static_cast<LONG>(h);
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
HWND hwnd = CreateWindowEx(0, L"D3D11TestWindowClass", g_game->GetAppName(), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance,
nullptr);
if (!hwnd)
return 1;
ShowWindow(hwnd, nCmdShow);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_game.get()) );
GetClientRect(hwnd, &rc);
g_game->Initialize(hwnd, rc.right - rc.left, rc.bottom - rc.top, DXGI_MODE_ROTATION_IDENTITY);
#ifdef _DBT_H
DEV_BROADCAST_DEVICEINTERFACE filter = {};
filter.dbcc_size = sizeof(filter);
filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
filter.dbcc_classguid = KSCATEGORY_AUDIO;
g_hNewAudio = RegisterDeviceNotification(hwnd, &filter, DEVICE_NOTIFY_WINDOW_HANDLE);
#endif
}
// Main message loop
MSG msg = { 0 };
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
g_game->Tick();
}
}
g_game.reset();
#ifdef WM_DEVICECHANGE
UnregisterDeviceNotification(g_hNewAudio);
#endif
CoUninitialize();
return (int) msg.wParam;
}
// Windows procedure
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
static bool s_in_sizemove = false;
static bool s_in_suspend = false;
static bool s_minimized = false;
static bool s_fullscreen = false;
auto game = reinterpret_cast<Game*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_SIZE:
if (wParam == SIZE_MINIMIZED)
{
if (!s_minimized)
{
s_minimized = true;
if (!s_in_suspend && game)
game->OnSuspending();
s_in_suspend = true;
}
}
else if (s_minimized)
{
s_minimized = false;
if (s_in_suspend && game)
game->OnResuming();
s_in_suspend = false;
}
else if (!s_in_sizemove && game)
{
game->OnWindowSizeChanged(LOWORD(lParam), HIWORD(lParam), DXGI_MODE_ROTATION_IDENTITY);
}
break;
case WM_ENTERSIZEMOVE:
s_in_sizemove = true;
break;
case WM_EXITSIZEMOVE:
s_in_sizemove = false;
if (game)
{
RECT rc;
GetClientRect(hWnd, &rc);
game->OnWindowSizeChanged(rc.right - rc.left, rc.bottom - rc.top, DXGI_MODE_ROTATION_IDENTITY);
}
break;
case WM_GETMINMAXINFO:
{
auto info = reinterpret_cast<MINMAXINFO*>(lParam);
info->ptMinTrackSize.x = 320;
info->ptMinTrackSize.y = 200;
}
break;
case WM_ACTIVATEAPP:
Mouse::ProcessMessage(message, wParam, lParam);
if (game)
{
Keyboard::ProcessMessage(message, wParam, lParam);
if (wParam)
{
game->OnActivated();
}
else
{
game->OnDeactivated();
}
}
break;
case WM_POWERBROADCAST:
switch (wParam)
{
case PBT_APMQUERYSUSPEND:
if (!s_in_suspend && game)
game->OnSuspending();
s_in_suspend = true;
return true;
case PBT_APMRESUMESUSPEND:
if (!s_minimized)
{
if (s_in_suspend && game)
game->OnResuming();
s_in_suspend = false;
}
return true;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
Keyboard::ProcessMessage(message, wParam, lParam);
break;
case WM_SYSKEYDOWN:
if (wParam == VK_RETURN && (lParam & 0x60000000) == 0x20000000)
{
// Implements the classic ALT+ENTER fullscreen toggle
if (s_fullscreen)
{
SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, 0);
int width = 800;
int height = 600;
if (game)
game->GetDefaultSize(width, height);
ShowWindow(hWnd, SW_SHOWNORMAL);
SetWindowPos(hWnd, HWND_TOP, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
else
{
SetWindowLongPtr(hWnd, GWL_STYLE, 0);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
}
s_fullscreen = !s_fullscreen;
}
Keyboard::ProcessMessage(message, wParam, lParam);
break;
case WM_INPUT:
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MOUSEWHEEL:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_MOUSEHOVER:
Mouse::ProcessMessage(message, wParam, lParam);
break;
#ifdef _DBT_H
case WM_DEVICECHANGE:
if (wParam == DBT_DEVICEARRIVAL)
{
auto pDev = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
if (pDev)
{
if (pDev->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
auto pInter = reinterpret_cast<const PDEV_BROADCAST_DEVICEINTERFACE>(pDev);
if (pInter->dbcc_classguid == KSCATEGORY_AUDIO)
{
#ifdef _DEBUG
OutputDebugStringA("INFO: New audio device detected: ");
OutputDebugString(pInter->dbcc_name);
OutputDebugStringA("\n");
#endif
PostMessage(hWnd, WM_USER, 0, 0);
}
}
}
}
return 0;
case WM_USER:
if (g_game)
{
g_game->OnAudioDeviceChange();
}
break;
#endif
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void ParseCommandLine(_In_ LPWSTR lpCmdLine)
{
int argc = 0;
wchar_t** argv = CommandLineToArgvW(lpCmdLine, &argc);
for (int iArg = 0; iArg < argc; iArg++)
{
wchar_t* pArg = argv[iArg];
if (('-' == pArg[0]) || ('/' == pArg[0]))
{
pArg++;
wchar_t* pValue;
for (pValue = pArg; *pValue && (':' != *pValue); pValue++);
if (*pValue)
*pValue++ = 0;
if (!_wcsicmp(pArg, L"forcewarp"))
{
DX::DeviceResources::DebugForceWarp(true);
}
}
}
LocalFree(argv);
}
<commit_msg>Fixed mystery beep when using ALT+ENTER to toggle fullscreen on PC<commit_after>//
// Main.cpp
//
#include "pch.h"
#include "Game.h"
#include <shellapi.h>
using namespace DirectX;
namespace
{
std::unique_ptr<Game> g_game;
#ifdef WM_DEVICECHANGE
HDEVNOTIFY g_hNewAudio;
#endif
};
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void ParseCommandLine(_In_ LPWSTR lpCmdLine);
// Indicates to hybrid graphics systems to prefer the discrete part by default
extern "C"
{
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
}
// Entry point
int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
if (!XMVerifyCPUSupport())
return 1;
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#if (_WIN32_WINNT >= 0x0A00 /*_WIN32_WINNT_WIN10*/)
Microsoft::WRL::Wrappers::RoInitializeWrapper initialize(RO_INIT_MULTITHREADED);
if (FAILED(initialize))
return 1;
#else
HRESULT hr = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED);
if (FAILED(hr))
return 1;
#endif
ParseCommandLine(lpCmdLine);
g_game = std::make_unique<Game>();
// Register class and create window
{
// Register class
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, L"IDI_ICON");
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wcex.lpszMenuName = nullptr;
wcex.lpszClassName = L"D3D11TestWindowClass";
wcex.hIconSm = LoadIcon(wcex.hInstance, L"IDI_ICON");
if (!RegisterClassEx(&wcex))
return 1;
// Create window
int w, h;
g_game->GetDefaultSize(w, h);
RECT rc;
rc.top = 0;
rc.left = 0;
rc.right = static_cast<LONG>(w);
rc.bottom = static_cast<LONG>(h);
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
HWND hwnd = CreateWindowEx(0, L"D3D11TestWindowClass", g_game->GetAppName(), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance,
nullptr);
if (!hwnd)
return 1;
ShowWindow(hwnd, nCmdShow);
SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(g_game.get()) );
GetClientRect(hwnd, &rc);
g_game->Initialize(hwnd, rc.right - rc.left, rc.bottom - rc.top, DXGI_MODE_ROTATION_IDENTITY);
#ifdef _DBT_H
DEV_BROADCAST_DEVICEINTERFACE filter = {};
filter.dbcc_size = sizeof(filter);
filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
filter.dbcc_classguid = KSCATEGORY_AUDIO;
g_hNewAudio = RegisterDeviceNotification(hwnd, &filter, DEVICE_NOTIFY_WINDOW_HANDLE);
#endif
}
// Main message loop
MSG msg = { 0 };
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
g_game->Tick();
}
}
g_game.reset();
#ifdef WM_DEVICECHANGE
UnregisterDeviceNotification(g_hNewAudio);
#endif
CoUninitialize();
return (int) msg.wParam;
}
// Windows procedure
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
static bool s_in_sizemove = false;
static bool s_in_suspend = false;
static bool s_minimized = false;
static bool s_fullscreen = false;
auto game = reinterpret_cast<Game*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
switch (message)
{
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_SIZE:
if (wParam == SIZE_MINIMIZED)
{
if (!s_minimized)
{
s_minimized = true;
if (!s_in_suspend && game)
game->OnSuspending();
s_in_suspend = true;
}
}
else if (s_minimized)
{
s_minimized = false;
if (s_in_suspend && game)
game->OnResuming();
s_in_suspend = false;
}
else if (!s_in_sizemove && game)
{
game->OnWindowSizeChanged(LOWORD(lParam), HIWORD(lParam), DXGI_MODE_ROTATION_IDENTITY);
}
break;
case WM_ENTERSIZEMOVE:
s_in_sizemove = true;
break;
case WM_EXITSIZEMOVE:
s_in_sizemove = false;
if (game)
{
RECT rc;
GetClientRect(hWnd, &rc);
game->OnWindowSizeChanged(rc.right - rc.left, rc.bottom - rc.top, DXGI_MODE_ROTATION_IDENTITY);
}
break;
case WM_GETMINMAXINFO:
{
auto info = reinterpret_cast<MINMAXINFO*>(lParam);
info->ptMinTrackSize.x = 320;
info->ptMinTrackSize.y = 200;
}
break;
case WM_ACTIVATEAPP:
Mouse::ProcessMessage(message, wParam, lParam);
if (game)
{
Keyboard::ProcessMessage(message, wParam, lParam);
if (wParam)
{
game->OnActivated();
}
else
{
game->OnDeactivated();
}
}
break;
case WM_POWERBROADCAST:
switch (wParam)
{
case PBT_APMQUERYSUSPEND:
if (!s_in_suspend && game)
game->OnSuspending();
s_in_suspend = true;
return TRUE;
case PBT_APMRESUMESUSPEND:
if (!s_minimized)
{
if (s_in_suspend && game)
game->OnResuming();
s_in_suspend = false;
}
return TRUE;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
Keyboard::ProcessMessage(message, wParam, lParam);
break;
case WM_SYSKEYDOWN:
if (wParam == VK_RETURN && (lParam & 0x60000000) == 0x20000000)
{
// Implements the classic ALT+ENTER fullscreen toggle
if (s_fullscreen)
{
SetWindowLongPtr(hWnd, GWL_STYLE, WS_OVERLAPPEDWINDOW);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, 0);
int width = 800;
int height = 600;
if (game)
game->GetDefaultSize(width, height);
ShowWindow(hWnd, SW_SHOWNORMAL);
SetWindowPos(hWnd, HWND_TOP, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
else
{
SetWindowLongPtr(hWnd, GWL_STYLE, 0);
SetWindowLongPtr(hWnd, GWL_EXSTYLE, WS_EX_TOPMOST);
SetWindowPos(hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
ShowWindow(hWnd, SW_SHOWMAXIMIZED);
}
s_fullscreen = !s_fullscreen;
}
Keyboard::ProcessMessage(message, wParam, lParam);
break;
case WM_INPUT:
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MOUSEWHEEL:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_MOUSEHOVER:
Mouse::ProcessMessage(message, wParam, lParam);
break;
#ifdef _DBT_H
case WM_DEVICECHANGE:
if (wParam == DBT_DEVICEARRIVAL)
{
auto pDev = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
if (pDev)
{
if (pDev->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)
{
auto pInter = reinterpret_cast<const PDEV_BROADCAST_DEVICEINTERFACE>(pDev);
if (pInter->dbcc_classguid == KSCATEGORY_AUDIO)
{
#ifdef _DEBUG
OutputDebugStringA("INFO: New audio device detected: ");
OutputDebugString(pInter->dbcc_name);
OutputDebugStringA("\n");
#endif
PostMessage(hWnd, WM_USER, 0, 0);
}
}
}
}
return 0;
case WM_USER:
if (g_game)
{
g_game->OnAudioDeviceChange();
}
break;
#endif
case WM_MENUCHAR:
// A menu is active and the user presses a key that does not correspond
// to any mnemonic or accelerator key. Ignore so we don't produce an error beep.
return MAKELRESULT(0, MNC_CLOSE);
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void ParseCommandLine(_In_ LPWSTR lpCmdLine)
{
int argc = 0;
wchar_t** argv = CommandLineToArgvW(lpCmdLine, &argc);
for (int iArg = 0; iArg < argc; iArg++)
{
wchar_t* pArg = argv[iArg];
if (('-' == pArg[0]) || ('/' == pArg[0]))
{
pArg++;
wchar_t* pValue;
for (pValue = pArg; *pValue && (':' != *pValue); pValue++);
if (*pValue)
*pValue++ = 0;
if (!_wcsicmp(pArg, L"forcewarp"))
{
DX::DeviceResources::DebugForceWarp(true);
}
}
}
LocalFree(argv);
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @author Gav Wood <[email protected]>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <boost/algorithm/string.hpp>
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/InterfaceHandler.h>
#include <libdevcrypto/SHA3.h>
using namespace std;
namespace dev
{
namespace solidity
{
bool CompilerStack::addSource(string const& _name, string const& _content)
{
bool existed = m_sources.count(_name) != 0;
reset(true);
m_sources[_name].scanner = make_shared<Scanner>(CharStream(expanded(_content)), _name);
return existed;
}
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
addSource("", expanded(_sourceCode));
}
void CompilerStack::parse()
{
for (auto& sourcePair: m_sources)
{
sourcePair.second.scanner->reset();
sourcePair.second.ast = Parser().parse(sourcePair.second.scanner);
}
resolveImports();
m_globalContext = make_shared<GlobalContext>();
NameAndTypeResolver resolver(m_globalContext->getDeclarations());
for (Source const* source: m_sourceOrder)
resolver.registerDeclarations(*source->ast);
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
m_globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*m_globalContext->getCurrentThis());
resolver.resolveNamesAndTypes(*contract);
m_contracts[contract->getName()].contract = contract;
}
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
m_globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*m_globalContext->getCurrentThis());
resolver.checkTypeRequirements(*contract);
m_contracts[contract->getName()].contract = contract;
}
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
addSources(StandardSources);
parse();
}
vector<string> CompilerStack::getContractNames() const
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
vector<string> contractNames;
for (auto const& contract: m_contracts)
contractNames.push_back(contract.first);
return contractNames;
}
void CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
parse();
map<ContractDefinition const*, bytes const*> contractBytecode;
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
shared_ptr<Compiler> compiler = make_shared<Compiler>(_optimize);
compiler->compileContract(*contract, contractBytecode);
Contract& compiledContract = m_contracts[contract->getName()];
compiledContract.bytecode = compiler->getAssembledBytecode();
compiledContract.runtimeBytecode = compiler->getRuntimeBytecode();
compiledContract.compiler = move(compiler);
contractBytecode[compiledContract.contract] = &compiledContract.bytecode;
}
}
const map<string, string> StandardSources = map<string, string>{
/* { "Config", "contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}}" },
{ "owned", "contract owned{function owned(){owner = msg.sender;}address owner;}" },
{ "mortal", "import \"owned\";\ncontract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }}" },
{ "NameReg", "contract NameReg{function register(string32 name){}function addressOf(string32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(string32 name){}}" },
{ "named", "import \"Config\";\nimport \"NameReg\";\ncontract named {function named(string32 name) {NameReg(Config().lookup(1)).register(name);}}" },
{ "std", "import \"owned\";\nimport \"mortal\";\nimport \"Config\";\nimport \"NameReg\";\nimport \"named\";\n" },
*/};
////// BEGIN: TEMPORARY ONLY
/// remove once import works properly and we have genesis contracts
string CompilerStack::expanded(string const& _sourceCode)
{
const map<string, string> c_standardSources = map<string, string>{
{ "Config", "contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}}" },
{ "Coin", "contract Coin{function isApprovedFor(address _target,address _proxy)constant returns(bool _r){}function isApproved(address _proxy)constant returns(bool _r){}function sendCoinFrom(address _from,uint256 _val,address _to){}function coinBalanceOf(address _a)constant returns(uint256 _r){}function sendCoin(uint256 _val,address _to){}function coinBalance()constant returns(uint256 _r){}function approve(address _a){}}"},
{ "CoinReg", "contract CoinReg{function count()constant returns(uint256 r){}function info(uint256 i)constant returns(address addr,string3 name,uint256 denom){}function register(string3 name,uint256 denom){}function unregister(){}}" },
{ "coin", "#require CoinReg\ncontract coin {function coin(string3 name, uint denom) {CoinReg(Config().lookup(3)).register(name, denom);}}" },
{ "service", "#require Config\ncontract service{function service(uint _n){Config().register(_n, this);}}" },
{ "owned", "contract owned{function owned(){owner = msg.sender;}address owner;}" },
{ "mortal", "#require owned\ncontract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }}" },
{ "NameReg", "contract NameReg{function register(string32 name){}function addressOf(string32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(string32 name){}}" },
{ "named", "#require Config NameReg\ncontract named {function named(string32 name) {NameReg(Config().lookup(1)).register(name);}}" },
{ "std", "#require owned mortal Config NameReg named" },
};
string sub;
set<string> got;
function<string(string const&)> localExpanded;
localExpanded = [&](string const& s) -> string
{
string ret = s;
for (size_t p = 0; p != string::npos;)
if ((p = ret.find("#require ")) != string::npos)
{
string n = ret.substr(p + 9, ret.find_first_of('\n', p + 9) - p - 9);
ret.replace(p, n.size() + 9, "");
vector<string> rs;
boost::split(rs, n, boost::is_any_of(" \t,"), boost::token_compress_on);
for (auto const& r: rs)
if (!got.count(r))
{
if (c_standardSources.count(r))
sub.append("\n" + localExpanded(c_standardSources.at(r)) + "\n");
got.insert(r);
}
}
// TODO: remove once we have genesis contracts.
else if ((p = ret.find("Config()")) != string::npos)
ret.replace(p, 8, "Config(0xc6d9d2cd449a754c494264e1809c50e34d64562b)");
return ret;
};
return sub + localExpanded(_sourceCode);
}
////// END: TEMPORARY ONLY
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
compile(_optimize);
return getBytecode();
}
bytes const& CompilerStack::getBytecode(string const& _contractName) const
{
return getContract(_contractName).bytecode;
}
bytes const& CompilerStack::getRuntimeBytecode(string const& _contractName) const
{
return getContract(_contractName).runtimeBytecode;
}
dev::h256 CompilerStack::getContractCodeHash(string const& _contractName) const
{
return dev::sha3(getRuntimeBytecode(_contractName));
}
void CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName) const
{
getContract(_contractName).compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface(string const& _contractName) const
{
return getMetadata(_contractName, DocumentationType::ABI_INTERFACE);
}
string const& CompilerStack::getSolidityInterface(string const& _contractName) const
{
return getMetadata(_contractName, DocumentationType::ABI_SOLIDITY_INTERFACE);
}
string const& CompilerStack::getMetadata(string const& _contractName, DocumentationType _type) const
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
Contract const& contract = getContract(_contractName);
std::unique_ptr<string const>* doc;
switch (_type)
{
case DocumentationType::NATSPEC_USER:
doc = &contract.userDocumentation;
break;
case DocumentationType::NATSPEC_DEV:
doc = &contract.devDocumentation;
break;
case DocumentationType::ABI_INTERFACE:
doc = &contract.interface;
break;
case DocumentationType::ABI_SOLIDITY_INTERFACE:
doc = &contract.solidityInterface;
break;
default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type."));
}
if (!*doc)
*doc = contract.interfaceHandler->getDocumentation(*contract.contract, _type);
return *(*doc);
}
Scanner const& CompilerStack::getScanner(string const& _sourceName) const
{
return *getSource(_sourceName).scanner;
}
SourceUnit const& CompilerStack::getAST(string const& _sourceName) const
{
return *getSource(_sourceName).ast;
}
ContractDefinition const& CompilerStack::getContractDefinition(string const& _contractName) const
{
return *getContract(_contractName).contract;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
void CompilerStack::reset(bool _keepSources)
{
m_parseSuccessful = false;
if (_keepSources)
for (auto sourcePair: m_sources)
sourcePair.second.reset();
else
m_sources.clear();
m_globalContext.reset();
m_sourceOrder.clear();
m_contracts.clear();
}
void CompilerStack::resolveImports()
{
// topological sorting (depth first search) of the import graph, cutting potential cycles
vector<Source const*> sourceOrder;
set<Source const*> sourcesSeen;
function<void(Source const*)> toposort = [&](Source const* _source)
{
if (sourcesSeen.count(_source))
return;
sourcesSeen.insert(_source);
for (ASTPointer<ASTNode> const& node: _source->ast->getNodes())
if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get()))
{
string const& id = import->getIdentifier();
if (!m_sources.count(id))
BOOST_THROW_EXCEPTION(ParserError()
<< errinfo_sourceLocation(import->getLocation())
<< errinfo_comment("Source not found."));
toposort(&m_sources[id]);
}
sourceOrder.push_back(_source);
};
for (auto const& sourcePair: m_sources)
toposort(&sourcePair.second);
swap(m_sourceOrder, sourceOrder);
}
CompilerStack::Contract const& CompilerStack::getContract(string const& _contractName) const
{
if (m_contracts.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found."));
string contractName = _contractName;
if (_contractName.empty())
// try to find the "last contract"
for (ASTPointer<ASTNode> const& node: m_sourceOrder.back()->ast->getNodes())
if (auto contract = dynamic_cast<ContractDefinition const*>(node.get()))
contractName = contract->getName();
auto it = m_contracts.find(contractName);
if (it == m_contracts.end())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found."));
return it->second;
}
CompilerStack::Source const& CompilerStack::getSource(string const& _sourceName) const
{
auto it = m_sources.find(_sourceName);
if (it == m_sources.end())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Given source file not found."));
return it->second;
}
CompilerStack::Contract::Contract(): interfaceHandler(make_shared<InterfaceHandler>()) {}
}
}
<commit_msg>LogFilter supports new, better, filter mechanism. Exposed to JS API.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @author Gav Wood <[email protected]>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <boost/algorithm/string.hpp>
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/InterfaceHandler.h>
#include <libdevcrypto/SHA3.h>
using namespace std;
namespace dev
{
namespace solidity
{
bool CompilerStack::addSource(string const& _name, string const& _content)
{
bool existed = m_sources.count(_name) != 0;
reset(true);
m_sources[_name].scanner = make_shared<Scanner>(CharStream(expanded(_content)), _name);
return existed;
}
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
addSource("", expanded(_sourceCode));
}
void CompilerStack::parse()
{
for (auto& sourcePair: m_sources)
{
sourcePair.second.scanner->reset();
sourcePair.second.ast = Parser().parse(sourcePair.second.scanner);
}
resolveImports();
m_globalContext = make_shared<GlobalContext>();
NameAndTypeResolver resolver(m_globalContext->getDeclarations());
for (Source const* source: m_sourceOrder)
resolver.registerDeclarations(*source->ast);
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
m_globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*m_globalContext->getCurrentThis());
resolver.resolveNamesAndTypes(*contract);
m_contracts[contract->getName()].contract = contract;
}
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
m_globalContext->setCurrentContract(*contract);
resolver.updateDeclaration(*m_globalContext->getCurrentThis());
resolver.checkTypeRequirements(*contract);
m_contracts[contract->getName()].contract = contract;
}
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
addSources(StandardSources);
parse();
}
vector<string> CompilerStack::getContractNames() const
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
vector<string> contractNames;
for (auto const& contract: m_contracts)
contractNames.push_back(contract.first);
return contractNames;
}
void CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
parse();
map<ContractDefinition const*, bytes const*> contractBytecode;
for (Source const* source: m_sourceOrder)
for (ASTPointer<ASTNode> const& node: source->ast->getNodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
shared_ptr<Compiler> compiler = make_shared<Compiler>(_optimize);
compiler->compileContract(*contract, contractBytecode);
Contract& compiledContract = m_contracts[contract->getName()];
compiledContract.bytecode = compiler->getAssembledBytecode();
compiledContract.runtimeBytecode = compiler->getRuntimeBytecode();
compiledContract.compiler = move(compiler);
contractBytecode[compiledContract.contract] = &compiledContract.bytecode;
}
}
const map<string, string> StandardSources = map<string, string>{
/* { "Config", "contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}}" },
{ "owned", "contract owned{function owned(){owner = msg.sender;}address owner;}" },
{ "mortal", "import \"owned\";\ncontract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }}" },
{ "NameReg", "contract NameReg{function register(string32 name){}function addressOf(string32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(string32 name){}}" },
{ "named", "import \"Config\";\nimport \"NameReg\";\ncontract named {function named(string32 name) {NameReg(Config().lookup(1)).register(name);}}" },
{ "std", "import \"owned\";\nimport \"mortal\";\nimport \"Config\";\nimport \"NameReg\";\nimport \"named\";\n" },
*/};
////// BEGIN: TEMPORARY ONLY
/// remove once import works properly and we have genesis contracts
string CompilerStack::expanded(string const& _sourceCode)
{
const map<string, string> c_standardSources = map<string, string>{
{ "Config", "contract Config{function lookup(uint256 service)constant returns(address a){}function kill(){}function unregister(uint256 id){}function register(uint256 id,address service){}}" },
{ "Coin", "contract Coin{function isApprovedFor(address _target,address _proxy)constant returns(bool _r){}function isApproved(address _proxy)constant returns(bool _r){}function sendCoinFrom(address _from,uint256 _val,address _to){}function coinBalanceOf(address _a)constant returns(uint256 _r){}function sendCoin(uint256 _val,address _to){}function coinBalance()constant returns(uint256 _r){}function approve(address _a){}}"},
{ "CoinReg", "contract CoinReg{function count()constant returns(uint256 r){}function info(uint256 i)constant returns(address addr,string3 name,uint256 denom){}function register(string3 name,uint256 denom){}function unregister(){}}" },
{ "coin", "#require CoinReg\ncontract coin {function coin(string3 name, uint denom) {CoinReg(Config().lookup(3)).register(name, denom);}}" },
{ "service", "#require Config\ncontract service{function service(uint _n){Config().register(_n, this);}}" },
{ "owned", "contract owned{function owned(){owner = msg.sender;}modifier onlyowner(){if(msg.sender==owner)_}address owner;}" },
{ "mortal", "#require owned\ncontract mortal is owned {function kill() { if (msg.sender == owner) suicide(owner); }}" },
{ "NameReg", "contract NameReg{function register(string32 name){}function addressOf(string32 name)constant returns(address addr){}function unregister(){}function nameOf(address addr)constant returns(string32 name){}}" },
{ "named", "#require Config NameReg\ncontract named {function named(string32 name) {NameReg(Config().lookup(1)).register(name);}}" },
{ "std", "#require owned mortal Config NameReg named" },
};
string sub;
set<string> got;
function<string(string const&)> localExpanded;
localExpanded = [&](string const& s) -> string
{
string ret = s;
for (size_t p = 0; p != string::npos;)
if ((p = ret.find("#require ")) != string::npos)
{
string n = ret.substr(p + 9, ret.find_first_of('\n', p + 9) - p - 9);
ret.replace(p, n.size() + 9, "");
vector<string> rs;
boost::split(rs, n, boost::is_any_of(" \t,"), boost::token_compress_on);
for (auto const& r: rs)
if (!got.count(r))
{
if (c_standardSources.count(r))
sub.append("\n" + localExpanded(c_standardSources.at(r)) + "\n");
got.insert(r);
}
}
// TODO: remove once we have genesis contracts.
else if ((p = ret.find("Config()")) != string::npos)
ret.replace(p, 8, "Config(0xc6d9d2cd449a754c494264e1809c50e34d64562b)");
return ret;
};
return sub + localExpanded(_sourceCode);
}
////// END: TEMPORARY ONLY
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
compile(_optimize);
return getBytecode();
}
bytes const& CompilerStack::getBytecode(string const& _contractName) const
{
return getContract(_contractName).bytecode;
}
bytes const& CompilerStack::getRuntimeBytecode(string const& _contractName) const
{
return getContract(_contractName).runtimeBytecode;
}
dev::h256 CompilerStack::getContractCodeHash(string const& _contractName) const
{
return dev::sha3(getRuntimeBytecode(_contractName));
}
void CompilerStack::streamAssembly(ostream& _outStream, string const& _contractName) const
{
getContract(_contractName).compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface(string const& _contractName) const
{
return getMetadata(_contractName, DocumentationType::ABI_INTERFACE);
}
string const& CompilerStack::getSolidityInterface(string const& _contractName) const
{
return getMetadata(_contractName, DocumentationType::ABI_SOLIDITY_INTERFACE);
}
string const& CompilerStack::getMetadata(string const& _contractName, DocumentationType _type) const
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
Contract const& contract = getContract(_contractName);
std::unique_ptr<string const>* doc;
switch (_type)
{
case DocumentationType::NATSPEC_USER:
doc = &contract.userDocumentation;
break;
case DocumentationType::NATSPEC_DEV:
doc = &contract.devDocumentation;
break;
case DocumentationType::ABI_INTERFACE:
doc = &contract.interface;
break;
case DocumentationType::ABI_SOLIDITY_INTERFACE:
doc = &contract.solidityInterface;
break;
default:
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Illegal documentation type."));
}
if (!*doc)
*doc = contract.interfaceHandler->getDocumentation(*contract.contract, _type);
return *(*doc);
}
Scanner const& CompilerStack::getScanner(string const& _sourceName) const
{
return *getSource(_sourceName).scanner;
}
SourceUnit const& CompilerStack::getAST(string const& _sourceName) const
{
return *getSource(_sourceName).ast;
}
ContractDefinition const& CompilerStack::getContractDefinition(string const& _contractName) const
{
return *getContract(_contractName).contract;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
void CompilerStack::reset(bool _keepSources)
{
m_parseSuccessful = false;
if (_keepSources)
for (auto sourcePair: m_sources)
sourcePair.second.reset();
else
m_sources.clear();
m_globalContext.reset();
m_sourceOrder.clear();
m_contracts.clear();
}
void CompilerStack::resolveImports()
{
// topological sorting (depth first search) of the import graph, cutting potential cycles
vector<Source const*> sourceOrder;
set<Source const*> sourcesSeen;
function<void(Source const*)> toposort = [&](Source const* _source)
{
if (sourcesSeen.count(_source))
return;
sourcesSeen.insert(_source);
for (ASTPointer<ASTNode> const& node: _source->ast->getNodes())
if (ImportDirective const* import = dynamic_cast<ImportDirective*>(node.get()))
{
string const& id = import->getIdentifier();
if (!m_sources.count(id))
BOOST_THROW_EXCEPTION(ParserError()
<< errinfo_sourceLocation(import->getLocation())
<< errinfo_comment("Source not found."));
toposort(&m_sources[id]);
}
sourceOrder.push_back(_source);
};
for (auto const& sourcePair: m_sources)
toposort(&sourcePair.second);
swap(m_sourceOrder, sourceOrder);
}
CompilerStack::Contract const& CompilerStack::getContract(string const& _contractName) const
{
if (m_contracts.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("No compiled contracts found."));
string contractName = _contractName;
if (_contractName.empty())
// try to find the "last contract"
for (ASTPointer<ASTNode> const& node: m_sourceOrder.back()->ast->getNodes())
if (auto contract = dynamic_cast<ContractDefinition const*>(node.get()))
contractName = contract->getName();
auto it = m_contracts.find(contractName);
if (it == m_contracts.end())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Contract " + _contractName + " not found."));
return it->second;
}
CompilerStack::Source const& CompilerStack::getSource(string const& _sourceName) const
{
auto it = m_sources.find(_sourceName);
if (it == m_sources.end())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Given source file not found."));
return it->second;
}
CompilerStack::Contract::Contract(): interfaceHandler(make_shared<InterfaceHandler>()) {}
}
}
<|endoftext|>
|
<commit_before>#include <itkAffineTransform.h>
#include <itkTransformFileWriter.h>
#include <itkImageFileReader.h>
#include <string>
#include <itkPoint.h>
#include <itkVector.h>
#include "transforms.h"
#include <sstream>
void GetImageCenter( itk::Image<unsigned short, 3>::Pointer image,
itk::Image<unsigned short, 3>::PointType & center
)
{
typedef itk::Image<unsigned short, 3> ImageType;
// Get lower corner position
ImageType::PointType origin;
origin = image->GetOrigin();
// Get higher corner position
ImageType::SizeType size;
size = image->GetLargestPossibleRegion().GetSize();
ImageType::IndexType index;
for( int i = 0; i < 3; i++ )
{
index[i] = size[i] - 1;
}
ImageType::PointType corner;
image->TransformIndexToPhysicalPoint( index, corner );
// Compute image center position
for( int i = 0; i < 3; i++ )
{
center[i] = ( corner[i] + origin[i] ) / 2.0;
}
}
template <class Precision>
int ComputeTransform( const std::string doffile,
std::string sourceFileName,
const std::string targetFileName,
const std::string outputFileName,
bool rview_old
)
{
typedef itk::Image<unsigned short, 3> ImageType;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
ImageReaderType::Pointer reader = ImageReaderType::New();
reader->SetFileName( targetFileName.c_str() );
reader->UpdateOutputInformation();
// Get the target image information to set the center of transform
// to the center of the target image
ImageType::SpacingType spacing = reader->GetOutput()->GetSpacing();
ImageType::SizeType size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
ImageType::PointType origin = reader->GetOutput()->GetOrigin();
typedef itk::AffineTransform<Precision, 3> AffineTransformType;
typedef itk::TransformFileWriter TransformWriterType;
TransformWriterType::Pointer twriter = TransformWriterType::New();
typename AffineTransformType::Pointer aff;
// Handle the old version of rview (the one where the dof files were in ASCII)
if( rview_old )
{
RViewTransform<Precision> dof = readDOFFile<Precision>( doffile );
aff = createITKAffine( dof,
size,
spacing,
origin
);
}
// Handle the new version of rview (where the dof files are binary
// files and have to be converted into txt files with dof2mat)
else
{
newRViewTransform<Precision> dof = readDOF2MATFile<Precision>( doffile );
typedef itk::AffineTransform<Precision, 3> AffineTransformType;
aff = createnewITKAffine( dof,
size,
spacing,
origin
);
}
// If the source image is given, add a translation that moves
// the center of the target image to the center of the source image
if( sourceFileName.compare( "" ) )
{
ImageReaderType::Pointer sourceReader = ImageReaderType::New();
sourceReader->SetFileName( sourceFileName.c_str() );
sourceReader->UpdateOutputInformation();
ImageType::PointType targetCenter;
GetImageCenter( reader->GetOutput(), targetCenter );
ImageType::PointType sourceCenter;
GetImageCenter( sourceReader->GetOutput(), sourceCenter );
itk::Vector<Precision, 3> translation;
translation = sourceCenter - targetCenter;
translation += aff->GetTranslation();
aff->SetTranslation( translation );
}
twriter->AddTransform( aff );
twriter->SetFileName( outputFileName );
try
{
twriter->Update();
}
catch( ... )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
typedef float Precision;
typedef double doublePrecision;
std::string sourceFileName;
// Check if source is specified
bool sourceSet = false;
int numberOfArgs = argc;
int outFilePos = 3;
if( argc >= 6 && !strcmp( argv[3], "-s") )
{
sourceSet = true;
numberOfArgs -= 2;
sourceFileName.assign( argv[4] );
outFilePos = 5;
}
// check if old or new rview
bool rview_old = true;
int transformTypePos = outFilePos;
if( argc > outFilePos + 1 )
{
std::istringstream inputType;
inputType.str( argv[outFilePos + 1] );
inputType >> rview_old;
if( inputType.fail() )
{
transformTypePos = outFilePos + 1;
}
else
{
numberOfArgs--;
transformTypePos = outFilePos + 2;
}
}
// Check if float or double
bool doubleSet = false;
if( argc > transformTypePos && !strcmp( argv[transformTypePos], "-d" ) )
{
doubleSet = true;
numberOfArgs--;
}
if( numberOfArgs != 4 )
{
std::cerr << "Usage: " << argv[0]
<<
" doffile targetimagefile [-s sourceImageFileName] outputfile [inputtype] [-d (outputTransform as doubles instead of floats) ]"
<< std::endl;
std::cerr << "with inputtype = " << std::endl;
std::cerr << "0: new rview (output txt file of dof2mat)" << std::endl; // this was inverted
std::cerr << "1: old rview" << std::endl;
return EXIT_FAILURE;
}
const std::string doffile( argv[1] );
const std::string targetFileName( argv[2] );
const std::string outputFileName( argv[outFilePos] );
if( doubleSet )
{
return ComputeTransform<doublePrecision>( doffile,
sourceFileName,
targetFileName,
outputFileName,
rview_old
);
}
else
{
return ComputeTransform<Precision>( doffile,
sourceFileName,
targetFileName,
outputFileName,
rview_old
);
}
}
<commit_msg>COMP: TransformWriter is more strict in ITKv4.5 about type matching<commit_after>#include <itkAffineTransform.h>
#include <itkTransformFileWriter.h>
#include <itkImageFileReader.h>
#include <string>
#include <itkPoint.h>
#include <itkVector.h>
#include "transforms.h"
#include <sstream>
void GetImageCenter( itk::Image<unsigned short, 3>::Pointer image,
itk::Image<unsigned short, 3>::PointType & center
)
{
typedef itk::Image<unsigned short, 3> ImageType;
// Get lower corner position
ImageType::PointType origin;
origin = image->GetOrigin();
// Get higher corner position
ImageType::SizeType size;
size = image->GetLargestPossibleRegion().GetSize();
ImageType::IndexType index;
for( int i = 0; i < 3; i++ )
{
index[i] = size[i] - 1;
}
ImageType::PointType corner;
image->TransformIndexToPhysicalPoint( index, corner );
// Compute image center position
for( int i = 0; i < 3; i++ )
{
center[i] = ( corner[i] + origin[i] ) / 2.0;
}
}
template <class Precision>
int ComputeTransform( const std::string doffile,
std::string sourceFileName,
const std::string targetFileName,
const std::string outputFileName,
bool rview_old
)
{
typedef itk::Image<unsigned short, 3> ImageType;
typedef itk::ImageFileReader<ImageType> ImageReaderType;
ImageReaderType::Pointer reader = ImageReaderType::New();
reader->SetFileName( targetFileName.c_str() );
reader->UpdateOutputInformation();
// Get the target image information to set the center of transform
// to the center of the target image
ImageType::SpacingType spacing = reader->GetOutput()->GetSpacing();
ImageType::SizeType size = reader->GetOutput()->GetLargestPossibleRegion().GetSize();
ImageType::PointType origin = reader->GetOutput()->GetOrigin();
typedef itk::AffineTransform<Precision, 3> AffineTransformType;
// After ITK_VERSION 4.5 (Acutally after June 20th, 2013) the ITK Transform
// classes are now templated. This requires forward declarations to be defined
// differently.
#if ( ( ITK_VERSION_MAJOR == 4 ) && ( ITK_VERSION_MINOR < 5 ) )
//This is trying to use the double presion writer to write
//a single precision transform. This is not a robust operation
//and was not guaranteed to work in ITK v4.4 and less with
//all transform writer types. I think that the .txt writer
//would have worked, but .mat and .hdf5 should have thrown
//an exception.
typedef itk::TransformFileWriter TransformWriterType;
typedef itk::TransformFileWriter::Pointer TransformWriterTypePointer;
#else
// As of ITKv4.5 there are both double and single precision transform writers.
typedef itk::TransformFileWriterTemplate<Precision> TransformWriterType;
typedef typename itk::TransformFileWriterTemplate<Precision>::Pointer TransformWriterTypePointer;
#endif
TransformWriterTypePointer twriter = TransformWriterType::New();
typename AffineTransformType::Pointer aff;
// Handle the old version of rview (the one where the dof files were in ASCII)
if( rview_old )
{
RViewTransform<Precision> dof = readDOFFile<Precision>( doffile );
aff = createITKAffine( dof,
size,
spacing,
origin
);
}
// Handle the new version of rview (where the dof files are binary
// files and have to be converted into txt files with dof2mat)
else
{
newRViewTransform<Precision> dof = readDOF2MATFile<Precision>( doffile );
typedef itk::AffineTransform<Precision, 3> AffineTransformType;
aff = createnewITKAffine( dof,
size,
spacing,
origin
);
}
// If the source image is given, add a translation that moves
// the center of the target image to the center of the source image
if( sourceFileName.compare( "" ) )
{
ImageReaderType::Pointer sourceReader = ImageReaderType::New();
sourceReader->SetFileName( sourceFileName.c_str() );
sourceReader->UpdateOutputInformation();
ImageType::PointType targetCenter;
GetImageCenter( reader->GetOutput(), targetCenter );
ImageType::PointType sourceCenter;
GetImageCenter( sourceReader->GetOutput(), sourceCenter );
itk::Vector<Precision, 3> translation;
translation = sourceCenter - targetCenter;
translation += aff->GetTranslation();
aff->SetTranslation( translation );
}
twriter->AddTransform( aff );
twriter->SetFileName( outputFileName );
try
{
twriter->Update();
}
catch( ... )
{
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int main(int argc, char* argv[])
{
typedef float Precision;
typedef double doublePrecision;
std::string sourceFileName;
// Check if source is specified
bool sourceSet = false;
int numberOfArgs = argc;
int outFilePos = 3;
if( argc >= 6 && !strcmp( argv[3], "-s") )
{
sourceSet = true;
numberOfArgs -= 2;
sourceFileName.assign( argv[4] );
outFilePos = 5;
}
// check if old or new rview
bool rview_old = true;
int transformTypePos = outFilePos;
if( argc > outFilePos + 1 )
{
std::istringstream inputType;
inputType.str( argv[outFilePos + 1] );
inputType >> rview_old;
if( inputType.fail() )
{
transformTypePos = outFilePos + 1;
}
else
{
numberOfArgs--;
transformTypePos = outFilePos + 2;
}
}
// Check if float or double
bool doubleSet = false;
if( argc > transformTypePos && !strcmp( argv[transformTypePos], "-d" ) )
{
doubleSet = true;
numberOfArgs--;
}
if( numberOfArgs != 4 )
{
std::cerr << "Usage: " << argv[0]
<<
" doffile targetimagefile [-s sourceImageFileName] outputfile [inputtype] [-d (outputTransform as doubles instead of floats) ]"
<< std::endl;
std::cerr << "with inputtype = " << std::endl;
std::cerr << "0: new rview (output txt file of dof2mat)" << std::endl; // this was inverted
std::cerr << "1: old rview" << std::endl;
return EXIT_FAILURE;
}
const std::string doffile( argv[1] );
const std::string targetFileName( argv[2] );
const std::string outputFileName( argv[outFilePos] );
if( doubleSet )
{
return ComputeTransform<doublePrecision>( doffile,
sourceFileName,
targetFileName,
outputFileName,
rview_old
);
}
else
{
return ComputeTransform<Precision>( doffile,
sourceFileName,
targetFileName,
outputFileName,
rview_old
);
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: *
* Indranil Das <[email protected]> *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/** @file AliHLTMUONTriggerReconstructorComponent.cxx
@author Indranil Das
@date
@brief Implementation of the trigger DDL reconstructor component. */
#include "AliHLTMUONTriggerReconstructorComponent.h"
#include "AliHLTMUONTriggerReconstructor.h"
#include "AliHLTMUONHitReconstructor.h"
#include "AliHLTMUONConstants.h"
#include "AliHLTMUONDataBlockWriter.h"
#include <cstdlib>
#include <cerrno>
#include <cassert>
namespace
{
// This is a global object used for automatic component registration,
// do not use this for calculation.
AliHLTMUONTriggerReconstructorComponent gAliHLTMUONTriggerReconstructorComponent;
} // end of namespace
ClassImp(AliHLTMUONTriggerReconstructorComponent)
AliHLTMUONTriggerReconstructorComponent::AliHLTMUONTriggerReconstructorComponent() :
fTrigRec(NULL),
fDDLDir(""),
fDDL(0),
fWarnForUnexpecedBlock(false),
fSuppressPartialTrigs(false)
{
}
AliHLTMUONTriggerReconstructorComponent::~AliHLTMUONTriggerReconstructorComponent()
{
}
const char* AliHLTMUONTriggerReconstructorComponent::GetComponentID()
{
return AliHLTMUONConstants::TriggerReconstructorId();
}
void AliHLTMUONTriggerReconstructorComponent::GetInputDataTypes( std::vector<AliHLTComponentDataType>& list)
{
list.clear();
list.push_back( AliHLTMUONConstants::TriggerDDLRawDataType() );
}
AliHLTComponentDataType AliHLTMUONTriggerReconstructorComponent::GetOutputDataType()
{
return AliHLTMUONConstants::TriggerRecordsBlockDataType();
}
void AliHLTMUONTriggerReconstructorComponent::GetOutputDataSize(
unsigned long& constBase, double& inputMultiplier
)
{
constBase = sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType);
inputMultiplier = 1;
}
AliHLTComponent* AliHLTMUONTriggerReconstructorComponent::Spawn()
{
return new AliHLTMUONTriggerReconstructorComponent;
}
int AliHLTMUONTriggerReconstructorComponent::DoInit(int argc, const char** argv)
{
// perform initialization. We check whether our relative output size is
// specified in the arguments.
HLTInfo("Initialising DHLT Trigger Record Component");
fWarnForUnexpecedBlock = false;
fSuppressPartialTrigs = false;
fTrigRec = new AliHLTMUONTriggerReconstructor();
// this is just to get rid of the warning "unused parameter"
if (argc==0 && argv==NULL) {
HLTError("Arguments missing, no arguments" );
}
char lutFileName[500],reglocFileName[500];
int i = 0;
char* cpErr;
while ( i < argc )
{
HLTDebug("argv[%d] == %s", i, argv[i] );
if ( !strcmp( argv[i], "lut" ) ) {
if ( argc <= i+1 ) {
HLTError("LookupTable filename not specified" );
return EINVAL; /* Invalid argument */
}
sprintf(lutFileName,"%s",argv[i+1]);
i += 2;
continue;
}// lut argument
if ( !strcmp( argv[i], "ddl" ) ) {
if ( argc <= i+1 ) {
HLTError("DDL number not specified" );
return EINVAL; /* Invalid argument */
}
fDDL = strtoul( argv[i+1], &cpErr, 0 );
if ( *cpErr )
{
HLTError("Cannot convert '%s' to DDL Number ", argv[i+1] );
return EINVAL;
}
//fDDL = atoi(argv[i+1]);
i += 2;
continue;
}// ddl argument
if ( !strcmp( argv[i], "rawdir" ) ) {
if ( argc <= i+1 ) {
HLTError("DDL directory not specified" );
return EINVAL; /* Invalid argument */
}
fDDLDir = argv[i+1] ;
i += 2;
continue;
}// ddl directory argument
if ( !strcmp( argv[i], "reglocmap" ) ) {
if ( argc <= i+1 ) {
HLTError("Regional to Local Card mapping filename not specified" );
return EINVAL; /* Invalid argument */
}
sprintf(reglocFileName,"%s",argv[i+1]);
i += 2;
continue;
}// regtolocalmap argument
if ( !strcmp( argv[i], "-warn_on_unexpected_block" ) ) {
fWarnForUnexpecedBlock = true;
i++;
continue;
}
if ( !strcmp( argv[i], "-suppress_partial_triggers" ) ) {
fSuppressPartialTrigs = true;
i++;
continue;
}
HLTError("Unknown option '%s'", argv[i] );
return EINVAL;
}//while loop
int lutline = fTrigRec->GetLutLine();
AliHLTMUONHitReconstructor::DHLTLut* lookupTable = new AliHLTMUONHitReconstructor::DHLTLut[lutline];
if(!ReadLookUpTable(lookupTable,lutFileName)){
HLTError("Failed to read lut, lut cannot be read");
return ENOENT ; /* No such file or directory */
}else{
fTrigRec->LoadLookUpTable(lookupTable,fDDL+AliHLTMUONTriggerReconstructor::GetkDDLOffSet());
AliHLTMUONTriggerReconstructor::RegToLoc regToLocMap[128]; // 16(locCard)*8(regCard)
if(!ReadRegToLocMap(regToLocMap,reglocFileName)){
HLTError("Failed to read RegToLocMap file");
return ENOENT ; /* No such file or directory */
}
if(!(fTrigRec->SetRegToLocCardMap(regToLocMap))){
HLTError("Failed to assign RegToLocMap to TrigRec Class due to memory problem");
return ENOMEM ; /*cannot allocate memory*/
}
}// reading lut
delete []lookupTable;
HLTInfo("Initialisation of DHLT Trigger Record Component is done");
return 0;
}
int AliHLTMUONTriggerReconstructorComponent::DoDeinit()
{
HLTInfo("Deinitialising DHLT Trigger Record Component");
if(fTrigRec)
{
delete fTrigRec;
fTrigRec = NULL;
}
return 0;
}
int AliHLTMUONTriggerReconstructorComponent::DoEvent(
const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& trigData,
AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size,
std::vector<AliHLTComponentBlockData>& outputBlocks
)
{
// Process an event
unsigned long totalSize = 0; // Amount of memory currently consumed in bytes.
HLTDebug("Processing event %llu with %u input data blocks.",
evtData.fEventID, evtData.fBlockCnt
);
// Loop over all input blocks in the event and run the trigger DDL
// reconstruction algorithm on the raw data.
for (AliHLTUInt32_t n = 0; n < evtData.fBlockCnt; n++)
{
#ifdef __DEBUG
char id[kAliHLTComponentDataTypefIDsize+1];
for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
id[i] = blocks[n].fDataType.fID[i];
id[kAliHLTComponentDataTypefIDsize] = '\0';
char origin[kAliHLTComponentDataTypefOriginSize+1];
for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
origin[i] = blocks[n].fDataType.fOrigin[i];
origin[kAliHLTComponentDataTypefOriginSize] = '\0';
#endif // __DEBUG
HLTDebug("Handling block: %u, with fDataType.fID = '%s',"
" fDataType.fID = '%s', fPtr = %p and fSize = %u bytes.",
n, static_cast<char*>(id), static_cast<char*>(origin),
blocks[n].fPtr, blocks[n].fSize
);
if (blocks[n].fDataType != AliHLTMUONConstants::TriggerDDLRawDataType())
{
// Log a message indicating that we got a data block that we
// do not know how to handle.
char id[kAliHLTComponentDataTypefIDsize+1];
for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
id[i] = blocks[n].fDataType.fID[i];
id[kAliHLTComponentDataTypefIDsize] = '\0';
char origin[kAliHLTComponentDataTypefOriginSize+1];
for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
origin[i] = blocks[n].fDataType.fOrigin[i];
origin[kAliHLTComponentDataTypefOriginSize] = '\0';
if (fWarnForUnexpecedBlock)
HLTWarning("Received a data block of a type we can not handle: %s origin %s",
static_cast<char*>(id), static_cast<char*>(origin)
);
else
HLTDebug("Received a data block of a type we can not handle: %s origin %s",
static_cast<char*>(id), static_cast<char*>(origin)
);
continue;
}
// Create a new output data block and initialise the header.
AliHLTMUONTriggerRecordsBlockWriter block(outputPtr+totalSize, size-totalSize);
if (not block.InitCommonHeader())
{
HLTError("There is not enough space in the output buffer for the new data block.",
" We require at least %u bytes, but have %u bytes left.",
sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType),
block.BufferSize()
);
break;
}
AliHLTUInt32_t totalDDLSize = blocks[n].fSize / sizeof(AliHLTUInt32_t);
AliHLTUInt32_t ddlRawDataSize = totalDDLSize - fTrigRec->GetkDDLHeaderSize();
AliHLTUInt32_t* buffer = reinterpret_cast<AliHLTUInt32_t*>(blocks[n].fPtr)
+ fTrigRec->GetkDDLHeaderSize();
AliHLTUInt32_t nofTrigRec = block.MaxNumberOfEntries();
bool runOk = fTrigRec->Run(
buffer, ddlRawDataSize,
block.GetArray(), nofTrigRec,
fSuppressPartialTrigs
);
if (not runOk)
{
HLTError("Error while processing of trigger DDL reconstruction algorithm.");
size = totalSize; // Must tell the framework how much buffer space was used.
return EIO;
}
// nofTrigRec should now contain the number of triggers actually found
// and filled into the output data block, so we can set this number.
assert( nofTrigRec <= block.MaxNumberOfEntries() );
block.SetNumberOfEntries(nofTrigRec);
HLTDebug("Number of trigger records found is %d", nofTrigRec);
// Fill a block data structure for our output block.
AliHLTComponentBlockData bd;
FillBlockData(bd);
bd.fPtr = outputPtr;
// This block's start (offset) is after all other blocks written so far.
bd.fOffset = totalSize;
bd.fSize = block.BytesUsed();
bd.fDataType = AliHLTMUONConstants::TriggerRecordsBlockDataType();
bd.fSpecification = blocks[n].fSpecification;
outputBlocks.push_back(bd);
HLTDebug("Created a new output data block at fPtr = %p,"
" with fOffset = %u (0x%.X) and fSize = %u bytes.",
bd.fPtr, bd.fOffset, bd.fOffset, bd.fSize
);
// Increase the total amount of data written so far to our output memory.
totalSize += block.BytesUsed();
}
// Finally we set the total size of output memory we consumed.
size = totalSize;
return 0;
}
bool AliHLTMUONTriggerReconstructorComponent::ReadLookUpTable(AliHLTMUONHitReconstructor::DHLTLut* lookupTable, const char* lutpath)
{
if (fDDL < 0 || fDDL >= 2){
HLTError("DDL number is out of range");
return false;
}
int lutLine = fTrigRec->GetLutLine();
FILE* fin = fopen(lutpath, "r");
if (fin == NULL){
HLTError("Failed to open file: %s",lutpath);
return false;
}
for(int i=0;i<lutLine;i++){
fscanf(
fin,
"%d\t%d\t%d\t%f\t%f\t%f\t%d\t%d\n",
&lookupTable[i].fIdManuChannel,
&lookupTable[i].fIX,
&lookupTable[i].fIY,
&lookupTable[i].fRealX,
&lookupTable[i].fRealY,
&lookupTable[i].fRealZ,
&lookupTable[i].fPcbZone,
&lookupTable[i].fPlane
);
}
fclose(fin);
return true;
}
bool AliHLTMUONTriggerReconstructorComponent::ReadRegToLocMap(AliHLTMUONTriggerReconstructor::RegToLoc* regToLocMap,const char* reglocFileName)
{
int iTrigDDL,iReg,iLoc,locId,switchWord,detElemId[4];
int index;
memset(regToLocMap,-1,128*sizeof(AliHLTMUONTriggerReconstructor::RegToLoc));
char s[100];
ifstream fin(reglocFileName);
if(!fin){
HLTError("Failed to open file %s",reglocFileName);
return false;
}
while(fin.getline(s,100)){
sscanf(s,"%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d",
&iTrigDDL,&iReg,&iLoc,&locId,&switchWord,&detElemId[0],&detElemId[1],&detElemId[2],&detElemId[3]);
if(iTrigDDL==fDDL){
index = iReg*16 + iLoc;
regToLocMap[index].fTrigDDL = iTrigDDL ;
regToLocMap[index].fRegId = iReg ;
regToLocMap[index].fLoc = iLoc ;
regToLocMap[index].fLocId = locId ;
regToLocMap[index].fSwitch = switchWord ;
for(int idet = 0; idet<4; idet++)
regToLocMap[index].fDetElemId[idet] = detElemId[idet] ;
}// if matches with fDDL
}//file loop
fin.close();
return true;
}
<commit_msg>The multiplier for data volume estimation was too low.<commit_after>/**************************************************************************
* This file is property of and copyright by the ALICE HLT Project *
* All rights reserved. *
* *
* Primary Authors: *
* Indranil Das <[email protected]> *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/** @file AliHLTMUONTriggerReconstructorComponent.cxx
@author Indranil Das
@date
@brief Implementation of the trigger DDL reconstructor component. */
#include "AliHLTMUONTriggerReconstructorComponent.h"
#include "AliHLTMUONTriggerReconstructor.h"
#include "AliHLTMUONHitReconstructor.h"
#include "AliHLTMUONConstants.h"
#include "AliHLTMUONDataBlockWriter.h"
#include <cstdlib>
#include <cerrno>
#include <cassert>
namespace
{
// This is a global object used for automatic component registration,
// do not use this for calculation.
AliHLTMUONTriggerReconstructorComponent gAliHLTMUONTriggerReconstructorComponent;
} // end of namespace
ClassImp(AliHLTMUONTriggerReconstructorComponent)
AliHLTMUONTriggerReconstructorComponent::AliHLTMUONTriggerReconstructorComponent() :
fTrigRec(NULL),
fDDLDir(""),
fDDL(0),
fWarnForUnexpecedBlock(false),
fSuppressPartialTrigs(false)
{
}
AliHLTMUONTriggerReconstructorComponent::~AliHLTMUONTriggerReconstructorComponent()
{
}
const char* AliHLTMUONTriggerReconstructorComponent::GetComponentID()
{
return AliHLTMUONConstants::TriggerReconstructorId();
}
void AliHLTMUONTriggerReconstructorComponent::GetInputDataTypes( std::vector<AliHLTComponentDataType>& list)
{
list.clear();
list.push_back( AliHLTMUONConstants::TriggerDDLRawDataType() );
}
AliHLTComponentDataType AliHLTMUONTriggerReconstructorComponent::GetOutputDataType()
{
return AliHLTMUONConstants::TriggerRecordsBlockDataType();
}
void AliHLTMUONTriggerReconstructorComponent::GetOutputDataSize(
unsigned long& constBase, double& inputMultiplier
)
{
constBase = sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType);
inputMultiplier = 4;
}
AliHLTComponent* AliHLTMUONTriggerReconstructorComponent::Spawn()
{
return new AliHLTMUONTriggerReconstructorComponent;
}
int AliHLTMUONTriggerReconstructorComponent::DoInit(int argc, const char** argv)
{
// perform initialization. We check whether our relative output size is
// specified in the arguments.
HLTInfo("Initialising DHLT Trigger Record Component");
fWarnForUnexpecedBlock = false;
fSuppressPartialTrigs = false;
fTrigRec = new AliHLTMUONTriggerReconstructor();
// this is just to get rid of the warning "unused parameter"
if (argc==0 && argv==NULL) {
HLTError("Arguments missing, no arguments" );
}
char lutFileName[500],reglocFileName[500];
int i = 0;
char* cpErr;
while ( i < argc )
{
HLTDebug("argv[%d] == %s", i, argv[i] );
if ( !strcmp( argv[i], "lut" ) ) {
if ( argc <= i+1 ) {
HLTError("LookupTable filename not specified" );
return EINVAL; /* Invalid argument */
}
sprintf(lutFileName,"%s",argv[i+1]);
i += 2;
continue;
}// lut argument
if ( !strcmp( argv[i], "ddl" ) ) {
if ( argc <= i+1 ) {
HLTError("DDL number not specified" );
return EINVAL; /* Invalid argument */
}
fDDL = strtoul( argv[i+1], &cpErr, 0 );
if ( *cpErr )
{
HLTError("Cannot convert '%s' to DDL Number ", argv[i+1] );
return EINVAL;
}
//fDDL = atoi(argv[i+1]);
i += 2;
continue;
}// ddl argument
if ( !strcmp( argv[i], "rawdir" ) ) {
if ( argc <= i+1 ) {
HLTError("DDL directory not specified" );
return EINVAL; /* Invalid argument */
}
fDDLDir = argv[i+1] ;
i += 2;
continue;
}// ddl directory argument
if ( !strcmp( argv[i], "reglocmap" ) ) {
if ( argc <= i+1 ) {
HLTError("Regional to Local Card mapping filename not specified" );
return EINVAL; /* Invalid argument */
}
sprintf(reglocFileName,"%s",argv[i+1]);
i += 2;
continue;
}// regtolocalmap argument
if ( !strcmp( argv[i], "-warn_on_unexpected_block" ) ) {
fWarnForUnexpecedBlock = true;
i++;
continue;
}
if ( !strcmp( argv[i], "-suppress_partial_triggers" ) ) {
fSuppressPartialTrigs = true;
i++;
continue;
}
HLTError("Unknown option '%s'", argv[i] );
return EINVAL;
}//while loop
int lutline = fTrigRec->GetLutLine();
AliHLTMUONHitReconstructor::DHLTLut* lookupTable = new AliHLTMUONHitReconstructor::DHLTLut[lutline];
if(!ReadLookUpTable(lookupTable,lutFileName)){
HLTError("Failed to read lut, lut cannot be read");
return ENOENT ; /* No such file or directory */
}else{
fTrigRec->LoadLookUpTable(lookupTable,fDDL+AliHLTMUONTriggerReconstructor::GetkDDLOffSet());
AliHLTMUONTriggerReconstructor::RegToLoc regToLocMap[128]; // 16(locCard)*8(regCard)
if(!ReadRegToLocMap(regToLocMap,reglocFileName)){
HLTError("Failed to read RegToLocMap file");
return ENOENT ; /* No such file or directory */
}
if(!(fTrigRec->SetRegToLocCardMap(regToLocMap))){
HLTError("Failed to assign RegToLocMap to TrigRec Class due to memory problem");
return ENOMEM ; /*cannot allocate memory*/
}
}// reading lut
delete []lookupTable;
HLTInfo("Initialisation of DHLT Trigger Record Component is done");
return 0;
}
int AliHLTMUONTriggerReconstructorComponent::DoDeinit()
{
HLTInfo("Deinitialising DHLT Trigger Record Component");
if(fTrigRec)
{
delete fTrigRec;
fTrigRec = NULL;
}
return 0;
}
int AliHLTMUONTriggerReconstructorComponent::DoEvent(
const AliHLTComponentEventData& evtData,
const AliHLTComponentBlockData* blocks,
AliHLTComponentTriggerData& trigData,
AliHLTUInt8_t* outputPtr,
AliHLTUInt32_t& size,
std::vector<AliHLTComponentBlockData>& outputBlocks
)
{
// Process an event
unsigned long totalSize = 0; // Amount of memory currently consumed in bytes.
HLTDebug("Processing event %llu with %u input data blocks.",
evtData.fEventID, evtData.fBlockCnt
);
// Loop over all input blocks in the event and run the trigger DDL
// reconstruction algorithm on the raw data.
for (AliHLTUInt32_t n = 0; n < evtData.fBlockCnt; n++)
{
#ifdef __DEBUG
char id[kAliHLTComponentDataTypefIDsize+1];
for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
id[i] = blocks[n].fDataType.fID[i];
id[kAliHLTComponentDataTypefIDsize] = '\0';
char origin[kAliHLTComponentDataTypefOriginSize+1];
for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
origin[i] = blocks[n].fDataType.fOrigin[i];
origin[kAliHLTComponentDataTypefOriginSize] = '\0';
#endif // __DEBUG
HLTDebug("Handling block: %u, with fDataType.fID = '%s',"
" fDataType.fID = '%s', fPtr = %p and fSize = %u bytes.",
n, static_cast<char*>(id), static_cast<char*>(origin),
blocks[n].fPtr, blocks[n].fSize
);
if (blocks[n].fDataType != AliHLTMUONConstants::TriggerDDLRawDataType())
{
// Log a message indicating that we got a data block that we
// do not know how to handle.
char id[kAliHLTComponentDataTypefIDsize+1];
for (int i = 0; i < kAliHLTComponentDataTypefIDsize; i++)
id[i] = blocks[n].fDataType.fID[i];
id[kAliHLTComponentDataTypefIDsize] = '\0';
char origin[kAliHLTComponentDataTypefOriginSize+1];
for (int i = 0; i < kAliHLTComponentDataTypefOriginSize; i++)
origin[i] = blocks[n].fDataType.fOrigin[i];
origin[kAliHLTComponentDataTypefOriginSize] = '\0';
if (fWarnForUnexpecedBlock)
HLTWarning("Received a data block of a type we can not handle: %s origin %s",
static_cast<char*>(id), static_cast<char*>(origin)
);
else
HLTDebug("Received a data block of a type we can not handle: %s origin %s",
static_cast<char*>(id), static_cast<char*>(origin)
);
continue;
}
// Create a new output data block and initialise the header.
AliHLTMUONTriggerRecordsBlockWriter block(outputPtr+totalSize, size-totalSize);
if (not block.InitCommonHeader())
{
HLTError("There is not enough space in the output buffer for the new data block.",
" We require at least %u bytes, but have %u bytes left.",
sizeof(AliHLTMUONTriggerRecordsBlockWriter::HeaderType),
block.BufferSize()
);
break;
}
AliHLTUInt32_t totalDDLSize = blocks[n].fSize / sizeof(AliHLTUInt32_t);
AliHLTUInt32_t ddlRawDataSize = totalDDLSize - fTrigRec->GetkDDLHeaderSize();
AliHLTUInt32_t* buffer = reinterpret_cast<AliHLTUInt32_t*>(blocks[n].fPtr)
+ fTrigRec->GetkDDLHeaderSize();
AliHLTUInt32_t nofTrigRec = block.MaxNumberOfEntries();
bool runOk = fTrigRec->Run(
buffer, ddlRawDataSize,
block.GetArray(), nofTrigRec,
fSuppressPartialTrigs
);
if (not runOk)
{
HLTError("Error while processing of trigger DDL reconstruction algorithm.");
size = totalSize; // Must tell the framework how much buffer space was used.
return EIO;
}
// nofTrigRec should now contain the number of triggers actually found
// and filled into the output data block, so we can set this number.
assert( nofTrigRec <= block.MaxNumberOfEntries() );
block.SetNumberOfEntries(nofTrigRec);
HLTDebug("Number of trigger records found is %d", nofTrigRec);
// Fill a block data structure for our output block.
AliHLTComponentBlockData bd;
FillBlockData(bd);
bd.fPtr = outputPtr;
// This block's start (offset) is after all other blocks written so far.
bd.fOffset = totalSize;
bd.fSize = block.BytesUsed();
bd.fDataType = AliHLTMUONConstants::TriggerRecordsBlockDataType();
bd.fSpecification = blocks[n].fSpecification;
outputBlocks.push_back(bd);
HLTDebug("Created a new output data block at fPtr = %p,"
" with fOffset = %u (0x%.X) and fSize = %u bytes.",
bd.fPtr, bd.fOffset, bd.fOffset, bd.fSize
);
// Increase the total amount of data written so far to our output memory.
totalSize += block.BytesUsed();
}
// Finally we set the total size of output memory we consumed.
size = totalSize;
return 0;
}
bool AliHLTMUONTriggerReconstructorComponent::ReadLookUpTable(AliHLTMUONHitReconstructor::DHLTLut* lookupTable, const char* lutpath)
{
if (fDDL < 0 || fDDL >= 2){
HLTError("DDL number is out of range");
return false;
}
int lutLine = fTrigRec->GetLutLine();
FILE* fin = fopen(lutpath, "r");
if (fin == NULL){
HLTError("Failed to open file: %s",lutpath);
return false;
}
for(int i=0;i<lutLine;i++){
fscanf(
fin,
"%d\t%d\t%d\t%f\t%f\t%f\t%d\t%d\n",
&lookupTable[i].fIdManuChannel,
&lookupTable[i].fIX,
&lookupTable[i].fIY,
&lookupTable[i].fRealX,
&lookupTable[i].fRealY,
&lookupTable[i].fRealZ,
&lookupTable[i].fPcbZone,
&lookupTable[i].fPlane
);
}
fclose(fin);
return true;
}
bool AliHLTMUONTriggerReconstructorComponent::ReadRegToLocMap(AliHLTMUONTriggerReconstructor::RegToLoc* regToLocMap,const char* reglocFileName)
{
int iTrigDDL,iReg,iLoc,locId,switchWord,detElemId[4];
int index;
memset(regToLocMap,-1,128*sizeof(AliHLTMUONTriggerReconstructor::RegToLoc));
char s[100];
ifstream fin(reglocFileName);
if(!fin){
HLTError("Failed to open file %s",reglocFileName);
return false;
}
while(fin.getline(s,100)){
sscanf(s,"%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d",
&iTrigDDL,&iReg,&iLoc,&locId,&switchWord,&detElemId[0],&detElemId[1],&detElemId[2],&detElemId[3]);
if(iTrigDDL==fDDL){
index = iReg*16 + iLoc;
regToLocMap[index].fTrigDDL = iTrigDDL ;
regToLocMap[index].fRegId = iReg ;
regToLocMap[index].fLoc = iLoc ;
regToLocMap[index].fLocId = locId ;
regToLocMap[index].fSwitch = switchWord ;
for(int idet = 0; idet<4; idet++)
regToLocMap[index].fDetElemId[idet] = detElemId[idet] ;
}// if matches with fDDL
}//file loop
fin.close();
return true;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../../Foundation/Characters/Format.h"
#include "../../../../Foundation/Characters/String_Constant.h"
#include "../../../../Foundation/Containers/Sequence.h"
#include "../../../../Foundation/Debug/Trace.h"
#include "../../../../Foundation/Execution/Sleep.h"
#include "../../../../Foundation/Execution/Thread.h"
#include "../../../../Foundation/IO/Network/LinkMonitor.h"
#include "../../../../Foundation/IO/Network/Socket.h"
#include "../../../../Foundation/Streams/MemoryStream.h"
#include "../Advertisement.h"
#include "../Common.h"
#include "BasicServer.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::UPnP;
using namespace Stroika::Frameworks::UPnP::SSDP;
using namespace Stroika::Frameworks::UPnP::SSDP::Server;
/*
********************************************************************************
******************************* BasicServer::Rep_ ******************************
********************************************************************************
*/
class BasicServer::Rep_ {
public:
Sequence<Advertisement> fAdvertisements;
FrequencyInfo fFrequencyInfo;
URI fLocation;
Rep_ (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fAdvertisements ()
, fFrequencyInfo (fi)
, fLocation (d.fLocation)
{
{
SSDP::Advertisement dan;
dan.fLocation = d.fLocation;
dan.fServer = d.fServer;
{
dan.fTarget = kTarget_UPNPRootDevice;
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), kTarget_UPNPRootDevice.c_str ());
fAdvertisements.Append (dan);
}
{
dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
dan.fTarget = dan.fUSN;
fAdvertisements.Append (dan);
}
if (not dd.fDeviceType.empty ()) {
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), dd.fDeviceType.c_str ());
dan.fTarget = dd.fDeviceType;
fAdvertisements.Append (dan);
}
}
StartNotifier_ ();
StartResponder_ ();
IO::Network::LinkMonitor lm;
lm.AddCallback ([this] (IO::Network::LinkMonitor::LinkChange lc, String netName, String ipNum) {
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Basic SSDP server - LinkMonitor callback", L"lc = %d, netName=%s, ipNum=%s", lc, netName.c_str (), ipNum.c_str ())};
if (lc == IO::Network::LinkMonitor::LinkChange::eAdded) {
this->Restart_ ();
}
});
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wpessimizing-move\"");
fLinkMonitor_ = optional<IO::Network::LinkMonitor> (move (lm));
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wpessimizing-move\"");
}
Sequence<Advertisement> GetAdjustedAdvertisements_ () const
{
// @todo EXPLAIN THIS LOGIC? What its doing is - if NO LOCATION HOST SPECIFIED - picka good default (not so crazy) - but only
// in that case do we patch/replace the location for the advertisements? That makes little sense
if (fLocation.GetAuthority () and fLocation.GetAuthority ()->GetHost ()) {
return fAdvertisements;
}
else {
Sequence<Advertisement> revisedAdvertisements;
URI useURL = fLocation;
URI::Authority authority = useURL.GetAuthority ().value_or (URI::Authority{});
authority.SetHost (IO::Network::GetPrimaryInternetAddress ());
useURL.SetAuthority (authority);
for (auto ai : fAdvertisements) {
ai.fLocation = useURL; // !@todo MAYBE this would make more sense replacing just the HOST part of each advertisement?
revisedAdvertisements.Append (ai);
}
return revisedAdvertisements;
}
}
void StartNotifier_ ()
{
fNotifierThread_ = Thread::New (
[this] () {
PeriodicNotifier l;
l.Run (GetAdjustedAdvertisements_ (), PeriodicNotifier::FrequencyInfo ());
},
Thread::eAutoStart, String{L"SSDP Notifier"});
}
void StartResponder_ ()
{
fSearchResponderThread_ = Thread::New (
[this] () {
SearchResponder sr;
sr.Run (GetAdjustedAdvertisements_ ());
},
Thread::eAutoStart, String{L"SSDP Search Responder"});
}
void Restart_ ()
{
Debug::TraceContextBumper ctx ("Restarting Basic SSDP server threads");
{
Thread::SuppressInterruptionInContext suppressInterruption; // critical to wait til done cuz captures this
if (fNotifierThread_ != nullptr) {
fNotifierThread_.AbortAndWaitForDone ();
}
if (fSearchResponderThread_ != nullptr) {
fSearchResponderThread_.AbortAndWaitForDone ();
}
}
StartNotifier_ ();
StartResponder_ ();
}
Execution::Thread::CleanupPtr fNotifierThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
Execution::Thread::CleanupPtr fSearchResponderThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
optional<IO::Network::LinkMonitor> fLinkMonitor_; // optional so we can delete it first on shutdown (so no restart while stopping stuff)
};
/*
********************************************************************************
********************************** BasicServer *********************************
********************************************************************************
*/
BasicServer::BasicServer (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fRep_ (make_shared<Rep_> (d, dd, fi))
{
}
<commit_msg>minor cleanup<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved
*/
#include "../../../StroikaPreComp.h"
#include "../../../../Foundation/Characters/Format.h"
#include "../../../../Foundation/Characters/String_Constant.h"
#include "../../../../Foundation/Containers/Sequence.h"
#include "../../../../Foundation/Debug/Trace.h"
#include "../../../../Foundation/Execution/Sleep.h"
#include "../../../../Foundation/Execution/Thread.h"
#include "../../../../Foundation/IO/Network/LinkMonitor.h"
#include "../../../../Foundation/IO/Network/Socket.h"
#include "../../../../Foundation/Streams/MemoryStream.h"
#include "../Advertisement.h"
#include "../Common.h"
#include "BasicServer.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::IO;
using namespace Stroika::Foundation::IO::Network;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::UPnP;
using namespace Stroika::Frameworks::UPnP::SSDP;
using namespace Stroika::Frameworks::UPnP::SSDP::Server;
/*
********************************************************************************
******************************* BasicServer::Rep_ ******************************
********************************************************************************
*/
class BasicServer::Rep_ {
public:
Sequence<Advertisement> fAdvertisements;
FrequencyInfo fFrequencyInfo;
URI fLocation;
Rep_ (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fAdvertisements ()
, fFrequencyInfo (fi)
, fLocation (d.fLocation)
{
{
SSDP::Advertisement dan;
dan.fLocation = d.fLocation;
dan.fServer = d.fServer;
{
dan.fTarget = kTarget_UPNPRootDevice;
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), kTarget_UPNPRootDevice.c_str ());
fAdvertisements.Append (dan);
}
{
dan.fUSN = Format (L"uuid:%s", d.fDeviceID.c_str ());
dan.fTarget = dan.fUSN;
fAdvertisements.Append (dan);
}
if (not dd.fDeviceType.empty ()) {
dan.fUSN = Format (L"uuid:%s::%s", d.fDeviceID.c_str (), dd.fDeviceType.c_str ());
dan.fTarget = dd.fDeviceType;
fAdvertisements.Append (dan);
}
}
StartNotifier_ ();
StartResponder_ ();
IO::Network::LinkMonitor lm;
lm.AddCallback ([this] (IO::Network::LinkMonitor::LinkChange lc, String netName, String ipNum) {
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"Basic SSDP server - LinkMonitor callback", L"lc = %d, netName=%s, ipNum=%s", lc, netName.c_str (), ipNum.c_str ())};
if (lc == IO::Network::LinkMonitor::LinkChange::eAdded) {
this->Restart_ ();
}
});
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wpessimizing-move\"");
fLinkMonitor_ = optional<IO::Network::LinkMonitor> (move (lm));
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wpessimizing-move\"");
}
Sequence<Advertisement> GetAdjustedAdvertisements_ () const
{
// @todo EXPLAIN THIS LOGIC? What its doing is - if NO LOCATION HOST SPECIFIED - picka good default (not so crazy) - but only
// in that case do we patch/replace the location for the advertisements? That makes little sense
if (fLocation.GetAuthority () and fLocation.GetAuthority ()->GetHost ()) {
return fAdvertisements;
}
else {
Sequence<Advertisement> revisedAdvertisements;
URI useURL = fLocation;
URI::Authority authority = useURL.GetAuthority ().value_or (URI::Authority{});
authority.SetHost (IO::Network::GetPrimaryInternetAddress ());
useURL.SetAuthority (authority);
for (auto ai : fAdvertisements) {
ai.fLocation = useURL; // !@todo MAYBE this would make more sense replacing just the HOST part of each advertisement?
revisedAdvertisements.Append (ai);
}
return revisedAdvertisements;
}
}
void StartNotifier_ ()
{
fNotifierThread_ = Thread::New (
[this] () {
PeriodicNotifier l;
l.Run (GetAdjustedAdvertisements_ (), PeriodicNotifier::FrequencyInfo ());
},
Thread::eAutoStart, L"SSDP Notifier"sv);
}
void StartResponder_ ()
{
fSearchResponderThread_ = Thread::New (
[this] () {
SearchResponder sr;
sr.Run (GetAdjustedAdvertisements_ ());
},
Thread::eAutoStart, L"SSDP Search Responder"sv);
}
void Restart_ ()
{
Debug::TraceContextBumper ctx ("Restarting Basic SSDP server threads");
{
Thread::SuppressInterruptionInContext suppressInterruption; // critical to wait til done cuz captures this
if (fNotifierThread_ != nullptr) {
fNotifierThread_.AbortAndWaitForDone ();
}
if (fSearchResponderThread_ != nullptr) {
fSearchResponderThread_.AbortAndWaitForDone ();
}
}
StartNotifier_ ();
StartResponder_ ();
}
Execution::Thread::CleanupPtr fNotifierThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
Execution::Thread::CleanupPtr fSearchResponderThread_{Execution::Thread::CleanupPtr::eAbortBeforeWaiting};
optional<IO::Network::LinkMonitor> fLinkMonitor_; // optional so we can delete it first on shutdown (so no restart while stopping stuff)
};
/*
********************************************************************************
********************************** BasicServer *********************************
********************************************************************************
*/
BasicServer::BasicServer (const Device& d, const DeviceDescription& dd, const FrequencyInfo& fi)
: fRep_ (make_shared<Rep_> (d, dd, fi))
{
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <iostream>
#include "Stroika/Foundation/Characters/FloatConversion.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/DataExchange/Variant/JSON/Writer.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#include "Stroika/Foundation/Execution/Process.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#if qPlatform_POSIX
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#endif
#include "Stroika/Foundation/Execution/Synchronized.h"
#include "Stroika/Foundation/Execution/WaitableEvent.h"
#include "Stroika/Foundation/Streams/MemoryStream.h"
#include "Stroika/Frameworks/SystemPerformance/AllInstruments.h"
#include "Stroika/Frameworks/SystemPerformance/Capturer.h"
#include "Stroika/Frameworks/SystemPerformance/Instruments/CPU.h"
#include "Stroika/Frameworks/SystemPerformance/Instruments/Memory.h"
#include "Stroika/Frameworks/SystemPerformance/Instruments/Process.h"
#include "Stroika/Frameworks/SystemPerformance/Measurement.h"
using namespace std;
using std::byte;
using namespace Stroika::Foundation;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using Characters::Character;
using Characters::String;
using Containers::Sequence;
using Containers::Set;
using Execution::pid_t;
using Execution::Synchronized;
using Time::DateTime;
using Time::Duration;
namespace {
string Serialize_ (VariantValue v, bool oneLineMode)
{
Streams::MemoryStream<byte>::Ptr out = Streams::MemoryStream<byte>::New ();
DataExchange::Variant::JSON::Writer{}.Write (v, out);
// strip CRLF - so shows up on one line
String result = String::FromUTF8 (out.As<string> ());
if (oneLineMode) {
result = result.StripAll ([] (Character c) -> bool { return c == '\n' or c == '\r'; });
}
return result.AsNarrowSDKString ();
}
}
namespace {
void Demo_PrintInstruments_ ()
{
cout << "Instrument:" << endl;
for (const Instrument& i : SystemPerformance::GetAllInstruments ()) {
cout << " " << i.pInstrumentName ().GetPrintName ().AsNarrowSDKString () << endl;
// print measurements too?
}
}
}
namespace {
void Demo_UsingCapturerWithCallbacks_ (Set<InstrumentNameType> run, bool oneLineMode, Duration captureInterval, Duration runFor)
{
Capturer capturer;
{
CaptureSet cs;
cs.pRunPeriod = captureInterval;
for (const Instrument& i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.pInstrumentName)) {
continue;
}
}
cs.AddInstrument (i);
}
capturer.AddCaptureSet (cs);
}
capturer.AddMeasurementsCallback ([oneLineMode] (MeasurementSet ms) {
cout << " Measured-At: " << ms.fMeasuredAt.ToString ().AsNarrowSDKString () << endl;
for (const Measurement& mi : ms.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
});
// run til timeout and then fall out...
IgnoreExceptionsForCall (Execution::WaitableEvent{}.Wait (runFor));
}
}
namespace {
void Demo_Using_Direct_Capture_On_Instrument_ (Set<InstrumentNameType> run, bool oneLineMode, Duration captureInterval)
{
cout << "Results for each instrument:" << endl;
for (const Instrument& i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.pInstrumentName)) {
continue;
}
}
cout << " " << i.pInstrumentName ().GetPrintName ().AsNarrowSDKString () << endl;
Execution::Sleep (captureInterval);
MeasurementSet m = i.Capture ();
if (m.fMeasurements.empty ()) {
cout << " NO DATA" << endl;
}
else {
cout << " Measured-At: " << m.fMeasuredAt.ToString ().AsNarrowSDKString () << endl;
for (const Measurement& mi : m.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
}
}
}
}
namespace {
namespace Demo_Using_Capturer_GetMostRecentMeasurements__Private_ {
using namespace Stroika::Frameworks::SystemPerformance;
#if __cpp_designated_initializers < 201707L
Instruments::Process::Options mkProcessInstrumentOptions_ ()
{
auto o = Instruments::Process::Options{};
o.fRestrictToPIDs = Set<pid_t>{Execution::GetCurrentProcessID ()};
return o;
}
#endif
struct MyCapturer_ : Capturer {
public:
Instruments::CPU::Instrument fCPUInstrument;
Instruments::Process::Instrument fProcessInstrument;
MyCapturer_ ()
#if __cpp_designated_initializers >= 201707L
: fProcessInstrument
{
Instruments::Process::Options
{
.fRestrictToPIDs = Set<pid_t> { Execution::GetCurrentProcessID () }
}
}
#else
: fProcessInstrument
{
mkProcessInstrumentOptions_ ()
}
#endif
{
AddCaptureSet (CaptureSet{30s, {fCPUInstrument, fProcessInstrument}});
}
};
}
void Demo_Using_Capturer_GetMostRecentMeasurements_ ()
{
/*
* The idea here is that the capturer runs in the thread in the background capturing stuff (on a periodic schedule).
* and you can simply grab (ANYTIME) the most recently captured values.
*
* This also demos using 'MeasurementsAs' so you can see the measurements as a structured result, as opposed to as
* a variant value.
*/
using namespace Demo_Using_Capturer_GetMostRecentMeasurements__Private_;
static MyCapturer_ sCapturer_; // initialized threadsafe, but internally syncrhonized class
unsigned int pass{};
cout << "Printing most recent measurements (in loop):" << endl;
while (true) {
auto measurements = sCapturer_.pMostRecentMeasurements (); // capture results on a regular cadence with MyCapturer, and just report the latest stats
DateTime now = DateTime::Now ();
optional<double> runQLength;
optional<double> totalCPUUsage;
optional<double> totalCPURatio;
if (auto om = sCapturer_.fCPUInstrument.MeasurementAs<Instruments::CPU::Info> (measurements)) {
runQLength = om->fRunQLength;
totalCPUUsage = om->fTotalCPUUsage;
totalCPURatio = om->GetTotalCPURatio ();
}
optional<Duration> thisProcUptime;
optional<double> thisProcAverageCPUTimeUsed;
optional<uint64_t> thisProcWorkingOrResidentSetSize;
optional<double> thisProcCombinedIORate;
if (auto om = sCapturer_.fProcessInstrument.MeasurementAs<Instruments::Process::Info> (measurements)) {
// It might not be found for some instruments (not implemented?)
Assert (om->size () <= 1);
if (om->size () == 1) {
Instruments::Process::ProcessType thisProcess = (*om)[Execution::GetCurrentProcessID ()];
if (auto o = thisProcess.fProcessStartedAt) {
thisProcUptime = now - *o;
}
thisProcAverageCPUTimeUsed = thisProcess.fAverageCPUTimeUsed;
thisProcWorkingOrResidentSetSize = Memory::NullCoalesce (thisProcess.fWorkingSetSize, thisProcess.fResidentMemorySize);
thisProcCombinedIORate = thisProcess.fCombinedIOWriteRate;
}
}
using namespace Memory; // for optional operator overloads
cout << "\tPass: " << pass << endl;
cout << "\t\tSys: " << endl;
cout << "\t\t\tRun-Q Length: " << Characters::ToString (runQLength).AsNarrowSDKString () << endl;
cout << "\t\t\tTotal CPU Usage: " << Characters::ToString (totalCPUUsage).AsNarrowSDKString () << " (" << Characters::ToString (totalCPURatio * 100.0).AsNarrowSDKString () << "% of computer)" << endl;
cout << "\t\tThis Process: " << endl;
cout << "\t\t\tUptime: " << Characters::ToString (thisProcUptime).AsNarrowSDKString () << endl;
cout << "\t\t\tAverage CPU Time Used: " << Characters::ToString (thisProcAverageCPUTimeUsed).AsNarrowSDKString () << endl;
cout << "\t\t\tWorking Or Resident-Set Size: " << Characters::ToString (thisProcWorkingOrResidentSetSize).AsNarrowSDKString () << endl;
cout << "\t\t\tCombined IO Rate: " << Characters::ToString (thisProcCombinedIORate).AsNarrowSDKString () << endl;
Execution::Sleep (30s);
++pass;
}
}
}
int main (int argc, const char* argv[])
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*> (argv, argv + argc)).c_str ())};
#if qPlatform_POSIX
Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED);
#endif
bool printUsage = false;
bool mostRecentCaptureMode = false;
bool printNames = false;
bool oneLineMode = false;
Time::DurationSecondsType runFor = 0; // default to runfor 0, so we do each once.
Time::DurationSecondsType captureInterval = 15;
Set<InstrumentNameType> run;
Sequence<String> args = Execution::ParseCommandLine (argc, argv);
for (auto argi = args.begin (); argi != args.end (); ++argi) {
if (Execution::MatchesCommandLineArgument (*argi, L"h") or Execution::MatchesCommandLineArgument (*argi, L"help")) {
printUsage = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"l")) {
printNames = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"m")) {
mostRecentCaptureMode = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"o")) {
oneLineMode = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"r")) {
++argi;
if (argi != args.end ()) {
run.Add (*argi);
}
else {
cerr << "Expected arg to -r" << endl;
return EXIT_FAILURE;
}
}
if (Execution::MatchesCommandLineArgument (*argi, L"t")) {
++argi;
if (argi != args.end ()) {
runFor = Characters::FloatConversion::ToFloat<Time::DurationSecondsType> (*argi);
}
else {
cerr << "Expected arg to -t" << endl;
return EXIT_FAILURE;
}
}
if (Execution::MatchesCommandLineArgument (*argi, L"c")) {
++argi;
if (argi != args.end ()) {
captureInterval = Characters::FloatConversion::ToFloat<Time::DurationSecondsType> (*argi);
}
else {
cerr << "Expected arg to -c" << endl;
return EXIT_FAILURE;
}
}
}
if (printUsage) {
cerr << "Usage: SystemPerformanceClient [--help] [-h] [-l] [-f] [-r RUN-INSTRUMENT]*" << endl;
cerr << " --help prints this help" << endl;
cerr << " -h prints this help" << endl;
cerr << " -o prints instrument results (with newlines stripped)" << endl;
cerr << " -l prints only the instrument names" << endl;
cerr << " -m runs in most-recent-capture-mode" << endl;
cerr << " -r runs the given instrument (it can be repeated)" << endl;
cerr << " -t time to run for (if zero run each matching instrument once)" << endl;
cerr << " -c time interval between captures" << endl;
return EXIT_SUCCESS;
}
try {
if (printNames) {
Demo_PrintInstruments_ ();
}
else if (mostRecentCaptureMode) {
Demo_Using_Capturer_GetMostRecentMeasurements_ ();
}
else if (runFor > 0) {
Demo_UsingCapturerWithCallbacks_ (run, oneLineMode, Duration{captureInterval}, Duration{runFor});
}
else {
Demo_Using_Direct_Capture_On_Instrument_ (run, oneLineMode, Duration{captureInterval});
}
}
catch (...) {
String exceptMsg = Characters::ToString (current_exception ());
cerr << "Exception - " << exceptMsg.AsNarrowSDKString () << " - terminating..." << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>mostly cosmetic (I think) - but may have some performance implications (some +, some -) - use much more for (const T& or for (const auto& - replacing just for (T, or other things less clear / appropriate; haven't found clear docs on web about universally what is best here, but I if performance diff unclear (less a win for Stroika than other systems due to COW and maybe more cost due to how iterators return by value not reference)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "Stroika/Frameworks/StroikaPreComp.h"
#include <iostream>
#include "Stroika/Foundation/Characters/FloatConversion.h"
#include "Stroika/Foundation/Characters/ToString.h"
#include "Stroika/Foundation/DataExchange/Variant/JSON/Writer.h"
#include "Stroika/Foundation/Execution/CommandLine.h"
#include "Stroika/Foundation/Execution/Process.h"
#include "Stroika/Foundation/Execution/Sleep.h"
#if qPlatform_POSIX
#include "Stroika/Foundation/Execution/SignalHandlers.h"
#endif
#include "Stroika/Foundation/Execution/Synchronized.h"
#include "Stroika/Foundation/Execution/WaitableEvent.h"
#include "Stroika/Foundation/Streams/MemoryStream.h"
#include "Stroika/Frameworks/SystemPerformance/AllInstruments.h"
#include "Stroika/Frameworks/SystemPerformance/Capturer.h"
#include "Stroika/Frameworks/SystemPerformance/Instruments/CPU.h"
#include "Stroika/Frameworks/SystemPerformance/Instruments/Memory.h"
#include "Stroika/Frameworks/SystemPerformance/Instruments/Process.h"
#include "Stroika/Frameworks/SystemPerformance/Measurement.h"
using namespace std;
using std::byte;
using namespace Stroika::Foundation;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using Characters::Character;
using Characters::String;
using Containers::Sequence;
using Containers::Set;
using Execution::pid_t;
using Execution::Synchronized;
using Time::DateTime;
using Time::Duration;
namespace {
string Serialize_ (VariantValue v, bool oneLineMode)
{
Streams::MemoryStream<byte>::Ptr out = Streams::MemoryStream<byte>::New ();
DataExchange::Variant::JSON::Writer{}.Write (v, out);
// strip CRLF - so shows up on one line
String result = String::FromUTF8 (out.As<string> ());
if (oneLineMode) {
result = result.StripAll ([] (Character c) -> bool { return c == '\n' or c == '\r'; });
}
return result.AsNarrowSDKString ();
}
}
namespace {
void Demo_PrintInstruments_ ()
{
cout << "Instrument:" << endl;
for (const Instrument& i : SystemPerformance::GetAllInstruments ()) {
cout << " " << i.pInstrumentName ().GetPrintName ().AsNarrowSDKString () << endl;
// print measurements too?
}
}
}
namespace {
void Demo_UsingCapturerWithCallbacks_ (Set<InstrumentNameType> run, bool oneLineMode, Duration captureInterval, Duration runFor)
{
Capturer capturer;
{
CaptureSet cs;
cs.pRunPeriod = captureInterval;
for (const Instrument& i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.pInstrumentName)) {
continue;
}
}
cs.AddInstrument (i);
}
capturer.AddCaptureSet (cs);
}
capturer.AddMeasurementsCallback ([oneLineMode] (MeasurementSet ms) {
cout << " Measured-At: " << ms.fMeasuredAt.ToString ().AsNarrowSDKString () << endl;
for (const Measurement& mi : ms.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
});
// run til timeout and then fall out...
IgnoreExceptionsForCall (Execution::WaitableEvent{}.Wait (runFor));
}
}
namespace {
void Demo_Using_Direct_Capture_On_Instrument_ (Set<InstrumentNameType> run, bool oneLineMode, Duration captureInterval)
{
cout << "Results for each instrument:" << endl;
for (Instrument i : SystemPerformance::GetAllInstruments ()) {
if (not run.empty ()) {
if (not run.Contains (i.pInstrumentName)) {
continue;
}
}
cout << " " << i.pInstrumentName ().GetPrintName ().AsNarrowSDKString () << endl;
Execution::Sleep (captureInterval);
MeasurementSet m = i.Capture ();
if (m.fMeasurements.empty ()) {
cout << " NO DATA" << endl;
}
else {
cout << " Measured-At: " << m.fMeasuredAt.ToString ().AsNarrowSDKString () << endl;
for (const Measurement& mi : m.fMeasurements) {
cout << " " << mi.fType.GetPrintName ().AsNarrowSDKString () << ": " << Serialize_ (mi.fValue, oneLineMode) << endl;
}
}
}
}
}
namespace {
namespace Demo_Using_Capturer_GetMostRecentMeasurements__Private_ {
using namespace Stroika::Frameworks::SystemPerformance;
#if __cpp_designated_initializers < 201707L
Instruments::Process::Options mkProcessInstrumentOptions_ ()
{
auto o = Instruments::Process::Options{};
o.fRestrictToPIDs = Set<pid_t>{Execution::GetCurrentProcessID ()};
return o;
}
#endif
struct MyCapturer_ : Capturer {
public:
Instruments::CPU::Instrument fCPUInstrument;
Instruments::Process::Instrument fProcessInstrument;
MyCapturer_ ()
#if __cpp_designated_initializers >= 201707L
: fProcessInstrument
{
Instruments::Process::Options
{
.fRestrictToPIDs = Set<pid_t> { Execution::GetCurrentProcessID () }
}
}
#else
: fProcessInstrument
{
mkProcessInstrumentOptions_ ()
}
#endif
{
AddCaptureSet (CaptureSet{30s, {fCPUInstrument, fProcessInstrument}});
}
};
}
void Demo_Using_Capturer_GetMostRecentMeasurements_ ()
{
/*
* The idea here is that the capturer runs in the thread in the background capturing stuff (on a periodic schedule).
* and you can simply grab (ANYTIME) the most recently captured values.
*
* This also demos using 'MeasurementsAs' so you can see the measurements as a structured result, as opposed to as
* a variant value.
*/
using namespace Demo_Using_Capturer_GetMostRecentMeasurements__Private_;
static MyCapturer_ sCapturer_; // initialized threadsafe, but internally syncrhonized class
unsigned int pass{};
cout << "Printing most recent measurements (in loop):" << endl;
while (true) {
auto measurements = sCapturer_.pMostRecentMeasurements (); // capture results on a regular cadence with MyCapturer, and just report the latest stats
DateTime now = DateTime::Now ();
optional<double> runQLength;
optional<double> totalCPUUsage;
optional<double> totalCPURatio;
if (auto om = sCapturer_.fCPUInstrument.MeasurementAs<Instruments::CPU::Info> (measurements)) {
runQLength = om->fRunQLength;
totalCPUUsage = om->fTotalCPUUsage;
totalCPURatio = om->GetTotalCPURatio ();
}
optional<Duration> thisProcUptime;
optional<double> thisProcAverageCPUTimeUsed;
optional<uint64_t> thisProcWorkingOrResidentSetSize;
optional<double> thisProcCombinedIORate;
if (auto om = sCapturer_.fProcessInstrument.MeasurementAs<Instruments::Process::Info> (measurements)) {
// It might not be found for some instruments (not implemented?)
Assert (om->size () <= 1);
if (om->size () == 1) {
Instruments::Process::ProcessType thisProcess = (*om)[Execution::GetCurrentProcessID ()];
if (auto o = thisProcess.fProcessStartedAt) {
thisProcUptime = now - *o;
}
thisProcAverageCPUTimeUsed = thisProcess.fAverageCPUTimeUsed;
thisProcWorkingOrResidentSetSize = Memory::NullCoalesce (thisProcess.fWorkingSetSize, thisProcess.fResidentMemorySize);
thisProcCombinedIORate = thisProcess.fCombinedIOWriteRate;
}
}
using namespace Memory; // for optional operator overloads
cout << "\tPass: " << pass << endl;
cout << "\t\tSys: " << endl;
cout << "\t\t\tRun-Q Length: " << Characters::ToString (runQLength).AsNarrowSDKString () << endl;
cout << "\t\t\tTotal CPU Usage: " << Characters::ToString (totalCPUUsage).AsNarrowSDKString () << " (" << Characters::ToString (totalCPURatio * 100.0).AsNarrowSDKString () << "% of computer)" << endl;
cout << "\t\tThis Process: " << endl;
cout << "\t\t\tUptime: " << Characters::ToString (thisProcUptime).AsNarrowSDKString () << endl;
cout << "\t\t\tAverage CPU Time Used: " << Characters::ToString (thisProcAverageCPUTimeUsed).AsNarrowSDKString () << endl;
cout << "\t\t\tWorking Or Resident-Set Size: " << Characters::ToString (thisProcWorkingOrResidentSetSize).AsNarrowSDKString () << endl;
cout << "\t\t\tCombined IO Rate: " << Characters::ToString (thisProcCombinedIORate).AsNarrowSDKString () << endl;
Execution::Sleep (30s);
++pass;
}
}
}
int main (int argc, const char* argv[])
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"main", L"argv=%s", Characters::ToString (vector<const char*> (argv, argv + argc)).c_str ())};
#if qPlatform_POSIX
Execution::SignalHandlerRegistry::Get ().SetSignalHandlers (SIGPIPE, Execution::SignalHandlerRegistry::kIGNORED);
#endif
bool printUsage = false;
bool mostRecentCaptureMode = false;
bool printNames = false;
bool oneLineMode = false;
Time::DurationSecondsType runFor = 0; // default to runfor 0, so we do each once.
Time::DurationSecondsType captureInterval = 15;
Set<InstrumentNameType> run;
Sequence<String> args = Execution::ParseCommandLine (argc, argv);
for (auto argi = args.begin (); argi != args.end (); ++argi) {
if (Execution::MatchesCommandLineArgument (*argi, L"h") or Execution::MatchesCommandLineArgument (*argi, L"help")) {
printUsage = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"l")) {
printNames = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"m")) {
mostRecentCaptureMode = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"o")) {
oneLineMode = true;
}
if (Execution::MatchesCommandLineArgument (*argi, L"r")) {
++argi;
if (argi != args.end ()) {
run.Add (*argi);
}
else {
cerr << "Expected arg to -r" << endl;
return EXIT_FAILURE;
}
}
if (Execution::MatchesCommandLineArgument (*argi, L"t")) {
++argi;
if (argi != args.end ()) {
runFor = Characters::FloatConversion::ToFloat<Time::DurationSecondsType> (*argi);
}
else {
cerr << "Expected arg to -t" << endl;
return EXIT_FAILURE;
}
}
if (Execution::MatchesCommandLineArgument (*argi, L"c")) {
++argi;
if (argi != args.end ()) {
captureInterval = Characters::FloatConversion::ToFloat<Time::DurationSecondsType> (*argi);
}
else {
cerr << "Expected arg to -c" << endl;
return EXIT_FAILURE;
}
}
}
if (printUsage) {
cerr << "Usage: SystemPerformanceClient [--help] [-h] [-l] [-f] [-r RUN-INSTRUMENT]*" << endl;
cerr << " --help prints this help" << endl;
cerr << " -h prints this help" << endl;
cerr << " -o prints instrument results (with newlines stripped)" << endl;
cerr << " -l prints only the instrument names" << endl;
cerr << " -m runs in most-recent-capture-mode" << endl;
cerr << " -r runs the given instrument (it can be repeated)" << endl;
cerr << " -t time to run for (if zero run each matching instrument once)" << endl;
cerr << " -c time interval between captures" << endl;
return EXIT_SUCCESS;
}
try {
if (printNames) {
Demo_PrintInstruments_ ();
}
else if (mostRecentCaptureMode) {
Demo_Using_Capturer_GetMostRecentMeasurements_ ();
}
else if (runFor > 0) {
Demo_UsingCapturerWithCallbacks_ (run, oneLineMode, Duration{captureInterval}, Duration{runFor});
}
else {
Demo_Using_Direct_Capture_On_Instrument_ (run, oneLineMode, Duration{captureInterval});
}
}
catch (...) {
String exceptMsg = Characters::ToString (current_exception ());
cerr << "Exception - " << exceptMsg.AsNarrowSDKString () << " - terminating..." << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before><commit_msg>Don't crash when there is no mainGuiFactory.<commit_after><|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs00.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs00.C
/// @brief Run and manage the DDR4 MRS00 loading
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ddr4
{
///
/// @brief mrs0_data ctor
/// @param[in] a fapi2::TARGET_TYPE_DIMM target
/// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
///
mrs00_data::mrs00_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ):
iv_burst_length(0),
iv_read_burst_type(0),
iv_dll_reset(fapi2::ENUM_ATTR_EFF_DRAM_DLL_RESET_NO),
iv_test_mode(0),
iv_write_recovery(0),
iv_cas_latency(0)
{
FAPI_TRY( mss::eff_dram_bl(i_target, iv_burst_length) );
FAPI_TRY( mss::eff_dram_rbt(i_target, iv_read_burst_type) );
FAPI_TRY( mss::eff_dram_cl(i_target, iv_cas_latency) );
FAPI_TRY( mss::eff_dram_dll_reset(i_target, iv_dll_reset) );
FAPI_TRY( mss::eff_dram_tm(i_target, iv_test_mode) );
FAPI_TRY( mss::eff_dram_twr(i_target, iv_write_recovery) );
FAPI_INF("MR0 Attributes: BL: 0x%x, RBT: 0x%x, CL: 0x%x, TM: 0x%x, DLL_RESET: 0x%x, WR: 0x%x",
iv_burst_length, iv_read_burst_type, iv_cas_latency, iv_test_mode, iv_dll_reset, iv_write_recovery);
o_rc = fapi2::FAPI2_RC_SUCCESS;
return;
fapi_try_exit:
o_rc = fapi2::current_err;
FAPI_ERR("unable to get attributes for mrs0");
return;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs00
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs00(const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Check to make sure our ctor worked ok
mrs00_data l_data( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS00 data from attributes");
FAPI_TRY( mrs00(i_target, l_data, io_inst, i_rank) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs00, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs00_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs00(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs00_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Map from Write Recovery attribute value to bits in the MRS.
// Bit 4 is A13, bits 5:7 are A11:A9
constexpr uint64_t LOWEST_WR = 10;
constexpr uint64_t WR_COUNT = 17;
constexpr uint8_t wr_map[WR_COUNT] =
{
// 10 12 14 16 18 20 22 24 26
0b0000, 0, 0b0001, 0, 0b0001, 0, 0b0011, 0, 0b0100, 0, 0b0101, 0, 0b0111, 0, 0b0110, 0, 0b1000
};
// Map from the CAS Latency attribute to the bits in the MRS
constexpr uint64_t LOWEST_CL = 9;
constexpr uint64_t CL_COUNT = 25;
constexpr uint8_t cl_map[CL_COUNT] =
{
// 9 10 11 12 13 14 15 16
0b00000, 0b00001, 0b00010, 0b00011, 0b00100, 0b00101, 0b00110, 0b00111,
// 17, 18 19 20 21 22 23 24
0b01101, 0b01000, 0b01110, 0b01001, 0b01111, 0b01010, 0b01100, 0b01011,
// 25 26 27 28 29 30 31 32 33
0b10000, 0b10001, 0b10010, 0b10011, 0b10100, 0b10101, 0b10110, 0b10111, 0b11000
};
fapi2::buffer<uint8_t> l_cl;
fapi2::buffer<uint8_t> l_wr;
FAPI_ASSERT((i_data.iv_write_recovery >= LOWEST_WR) && (i_data.iv_write_recovery < (LOWEST_WR + WR_COUNT)),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(0)
.set_PARAMETER(WRITE_RECOVERY)
.set_PARAMETER_VALUE(i_data.iv_write_recovery)
.set_DIMM_IN_ERROR(i_target),
"Bad value for Write Recovery: %d (%s)", i_data.iv_write_recovery, mss::c_str(i_target));
FAPI_ASSERT((i_data.iv_cas_latency >= LOWEST_CL) && (i_data.iv_cas_latency < (LOWEST_CL + CL_COUNT)),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(0)
.set_PARAMETER(CAS_LATENCY)
.set_PARAMETER_VALUE(i_data.iv_cas_latency)
.set_DIMM_IN_ERROR(i_target),
"Bad value for CAS Latency: %d (%s)", i_data.iv_cas_latency, mss::c_str(i_target));
io_inst.arr0.insertFromRight<A0, 2>(i_data.iv_burst_length);
io_inst.arr0.writeBit<A3>(i_data.iv_read_burst_type);
io_inst.arr0.writeBit<A7>(i_data.iv_test_mode);
io_inst.arr0.writeBit<A8>(i_data.iv_dll_reset);
// CAS Latency takes a little effort - the bits aren't contiguous
l_cl = cl_map[i_data.iv_cas_latency - LOWEST_CL];
io_inst.arr0.writeBit<A12>(l_cl.getBit<3>());
io_inst.arr0.writeBit<A6>(l_cl.getBit<4>());
io_inst.arr0.writeBit<A5>(l_cl.getBit<5>());
io_inst.arr0.writeBit<A4>(l_cl.getBit<6>());
io_inst.arr0.writeBit<A2>(l_cl.getBit<7>());
// Write Recovery/Read to Precharge is not contiguous either.
l_wr = wr_map[i_data.iv_write_recovery - LOWEST_WR];
io_inst.arr0.writeBit<A13>(l_wr.getBit<4>());
io_inst.arr0.writeBit<A11>(l_wr.getBit<5>());
io_inst.arr0.writeBit<A10>(l_wr.getBit<6>());
io_inst.arr0.writeBit<A9>(l_wr.getBit<7>());
FAPI_INF("MR0: 0x%016llx", uint64_t(io_inst.arr0));
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Given a CCS instruction which contains address bits with an encoded MRS0,
/// decode and trace the contents
/// @param[in] i_inst the CCS instruction
/// @param[in] i_rank ths rank in question
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode mrs00_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank)
{
static const uint8_t wr_map[9] = { 10, 12, 14, 16, 18, 20, 24, 22, 26 };
uint8_t l_burst_length = 0;
uint8_t l_read_burst_type = 0;
uint8_t l_dll_reset = 0;
uint8_t l_test_mode = 0;
fapi2::buffer<uint8_t> l_wr_index;
fapi2::buffer<uint8_t> l_cas_latency;
i_inst.arr0.extractToRight<A0, 2>(l_burst_length);
l_read_burst_type = i_inst.arr0.getBit<A3>();
l_test_mode = i_inst.arr0.getBit<A7>();
l_dll_reset = i_inst.arr0.getBit<A8>();
// CAS Latency takes a little effort - the bits aren't contiguous
l_cas_latency.writeBit<3>(i_inst.arr0.getBit<A12>());
l_cas_latency.writeBit<4>(i_inst.arr0.getBit<A6>());
l_cas_latency.writeBit<5>(i_inst.arr0.getBit<A5>());
l_cas_latency.writeBit<6>(i_inst.arr0.getBit<A4>());
l_cas_latency.writeBit<7>(i_inst.arr0.getBit<A2>());
// Write Recovery/Read to Precharge is not contiguous either.
l_wr_index.writeBit<4>(i_inst.arr0.getBit<A13>());
l_wr_index.writeBit<5>(i_inst.arr0.getBit<A11>());
l_wr_index.writeBit<6>(i_inst.arr0.getBit<A10>());
l_wr_index.writeBit<7>(i_inst.arr0.getBit<A9>());
FAPI_INF("MR0 Decode BL: 0x%x, RBT: 0x%x, CL: 0x%x, TM: 0x%x, DLL_RESET: 0x%x, WR: (0x%x)0x%x",
l_burst_length, l_read_burst_type, uint8_t(l_cas_latency), l_test_mode, l_dll_reset,
wr_map[uint8_t(l_wr_index)], uint8_t(l_wr_index));
return FAPI2_RC_SUCCESS;
}
fapi2::ReturnCode (*mrs00_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs00_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank) = &mrs00;
fapi2::ReturnCode (*mrs00_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank) = &mrs00_decode;
} // ns ddr4
} // ns mss
<commit_msg>Fix eff_config, remove custom_dimm<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/mrs00.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file mrs00.C
/// @brief Run and manage the DDR4 MRS00 loading
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/ddr4/mrs_load_ddr4.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ddr4
{
///
/// @brief mrs0_data ctor
/// @param[in] a fapi2::TARGET_TYPE_DIMM target
/// @param[out] fapi2::ReturnCode FAPI2_RC_SUCCESS iff ok
/// @note Burst Length will always be set to fixed x8 (0)
/// @note Burst Chop (x4) is not supported
///
mrs00_data::mrs00_data( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, fapi2::ReturnCode& o_rc ):
iv_burst_length(0),
iv_read_burst_type(fapi2::ENUM_ATTR_EFF_DRAM_RBT_SEQUENTIAL),
iv_dll_reset(fapi2::ENUM_ATTR_EFF_DRAM_DLL_RESET_NO),
iv_test_mode(fapi2::ENUM_ATTR_EFF_DRAM_TM_NORMAL),
iv_write_recovery(0),
iv_cas_latency(0)
{
FAPI_TRY( mss::eff_dram_rbt(i_target, iv_read_burst_type) );
FAPI_TRY( mss::eff_dram_cl(i_target, iv_cas_latency) );
FAPI_TRY( mss::eff_dram_dll_reset(i_target, iv_dll_reset) );
FAPI_TRY( mss::eff_dram_tm(i_target, iv_test_mode) );
FAPI_TRY( mss::eff_dram_twr(i_target, iv_write_recovery) );
FAPI_INF("MR0 Attributes: BL: 0x%x, RBT: 0x%x, CL: 0x%x, TM: 0x%x, DLL_RESET: 0x%x, WR: 0x%x",
iv_burst_length, iv_read_burst_type, iv_cas_latency, iv_test_mode, iv_dll_reset, iv_write_recovery);
o_rc = fapi2::FAPI2_RC_SUCCESS;
return;
fapi_try_exit:
o_rc = fapi2::current_err;
FAPI_ERR("unable to get attributes for mrs0");
return;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs00
/// @param[in] i_target a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs00(const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
ccs::instruction_t<TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Check to make sure our ctor worked ok
mrs00_data l_data( i_target, fapi2::current_err );
FAPI_TRY( fapi2::current_err, "Unable to construct MRS00 data from attributes");
FAPI_TRY( mrs00(i_target, l_data, io_inst, i_rank) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Configure the ARR0 of the CCS instruction for mrs00, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs00_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs00(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs00_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank)
{
// Map from Write Recovery attribute value to bits in the MRS.
// Bit 4 is A13, bits 5:7 are A11:A9
constexpr uint64_t LOWEST_WR = 10;
constexpr uint64_t WR_COUNT = 17;
constexpr uint8_t wr_map[WR_COUNT] =
{
// 10 12 14 16 18 20 22 24 26
0b0000, 0, 0b0001, 0, 0b0001, 0, 0b0011, 0, 0b0100, 0, 0b0101, 0, 0b0111, 0, 0b0110, 0, 0b1000
};
// Map from the CAS Latency attribute to the bits in the MRS
constexpr uint64_t LOWEST_CL = 9;
constexpr uint64_t CL_COUNT = 25;
constexpr uint8_t cl_map[CL_COUNT] =
{
// 9 10 11 12 13 14 15 16
0b00000, 0b00001, 0b00010, 0b00011, 0b00100, 0b00101, 0b00110, 0b00111,
// 17, 18 19 20 21 22 23 24
0b01101, 0b01000, 0b01110, 0b01001, 0b01111, 0b01010, 0b01100, 0b01011,
// 25 26 27 28 29 30 31 32 33
0b10000, 0b10001, 0b10010, 0b10011, 0b10100, 0b10101, 0b10110, 0b10111, 0b11000
};
fapi2::buffer<uint8_t> l_cl;
fapi2::buffer<uint8_t> l_wr;
FAPI_ASSERT((i_data.iv_write_recovery >= LOWEST_WR) && (i_data.iv_write_recovery < (LOWEST_WR + WR_COUNT)),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(0)
.set_PARAMETER(WRITE_RECOVERY)
.set_PARAMETER_VALUE(i_data.iv_write_recovery)
.set_DIMM_IN_ERROR(i_target),
"Bad value for Write Recovery: %d (%s)", i_data.iv_write_recovery, mss::c_str(i_target));
FAPI_ASSERT((i_data.iv_cas_latency >= LOWEST_CL) && (i_data.iv_cas_latency < (LOWEST_CL + CL_COUNT)),
fapi2::MSS_BAD_MR_PARAMETER()
.set_MR_NUMBER(0)
.set_PARAMETER(CAS_LATENCY)
.set_PARAMETER_VALUE(i_data.iv_cas_latency)
.set_DIMM_IN_ERROR(i_target),
"Bad value for CAS Latency: %d (%s)", i_data.iv_cas_latency, mss::c_str(i_target));
io_inst.arr0.insertFromRight<A0, 2>(i_data.iv_burst_length);
io_inst.arr0.writeBit<A3>(i_data.iv_read_burst_type);
io_inst.arr0.writeBit<A7>(i_data.iv_test_mode);
io_inst.arr0.writeBit<A8>(i_data.iv_dll_reset);
// CAS Latency takes a little effort - the bits aren't contiguous
l_cl = cl_map[i_data.iv_cas_latency - LOWEST_CL];
io_inst.arr0.writeBit<A12>(l_cl.getBit<3>());
io_inst.arr0.writeBit<A6>(l_cl.getBit<4>());
io_inst.arr0.writeBit<A5>(l_cl.getBit<5>());
io_inst.arr0.writeBit<A4>(l_cl.getBit<6>());
io_inst.arr0.writeBit<A2>(l_cl.getBit<7>());
// Write Recovery/Read to Precharge is not contiguous either.
l_wr = wr_map[i_data.iv_write_recovery - LOWEST_WR];
io_inst.arr0.writeBit<A13>(l_wr.getBit<4>());
io_inst.arr0.writeBit<A11>(l_wr.getBit<5>());
io_inst.arr0.writeBit<A10>(l_wr.getBit<6>());
io_inst.arr0.writeBit<A9>(l_wr.getBit<7>());
FAPI_INF("MR0: 0x%016llx", uint64_t(io_inst.arr0));
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Given a CCS instruction which contains address bits with an encoded MRS0,
/// decode and trace the contents
/// @param[in] i_inst the CCS instruction
/// @param[in] i_rank ths rank in question
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode mrs00_decode(const ccs::instruction_t<TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank)
{
static const uint8_t wr_map[9] = { 10, 12, 14, 16, 18, 20, 24, 22, 26 };
uint8_t l_burst_length = 0;
uint8_t l_read_burst_type = 0;
uint8_t l_dll_reset = 0;
uint8_t l_test_mode = 0;
fapi2::buffer<uint8_t> l_wr_index;
fapi2::buffer<uint8_t> l_cas_latency;
i_inst.arr0.extractToRight<A0, 2>(l_burst_length);
l_read_burst_type = i_inst.arr0.getBit<A3>();
l_test_mode = i_inst.arr0.getBit<A7>();
l_dll_reset = i_inst.arr0.getBit<A8>();
// CAS Latency takes a little effort - the bits aren't contiguous
l_cas_latency.writeBit<3>(i_inst.arr0.getBit<A12>());
l_cas_latency.writeBit<4>(i_inst.arr0.getBit<A6>());
l_cas_latency.writeBit<5>(i_inst.arr0.getBit<A5>());
l_cas_latency.writeBit<6>(i_inst.arr0.getBit<A4>());
l_cas_latency.writeBit<7>(i_inst.arr0.getBit<A2>());
// Write Recovery/Read to Precharge is not contiguous either.
l_wr_index.writeBit<4>(i_inst.arr0.getBit<A13>());
l_wr_index.writeBit<5>(i_inst.arr0.getBit<A11>());
l_wr_index.writeBit<6>(i_inst.arr0.getBit<A10>());
l_wr_index.writeBit<7>(i_inst.arr0.getBit<A9>());
FAPI_INF("MR0 Decode BL: 0x%x, RBT: 0x%x, CL: 0x%x, TM: 0x%x, DLL_RESET: 0x%x, WR: (0x%x)0x%x",
l_burst_length, l_read_burst_type, uint8_t(l_cas_latency), l_test_mode, l_dll_reset,
wr_map[uint8_t(l_wr_index)], uint8_t(l_wr_index));
return FAPI2_RC_SUCCESS;
}
fapi2::ReturnCode (*mrs00_data::make_ccs_instruction)(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
const mrs00_data& i_data,
ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
const uint64_t i_rank) = &mrs00;
fapi2::ReturnCode (*mrs00_data::decode)(const ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& i_inst,
const uint64_t i_rank) = &mrs00_decode;
} // ns ddr4
} // ns mss
<|endoftext|>
|
<commit_before>#include <cstring>
#include <cassert>
#include <string>
#include <atomic>
#include <memory>
#include <set>
#include <boost/asio.hpp>
#include <mutex>
#include "I2PService.h"
#include "Destination.h"
#include "HTTPProxy.h"
#include "util.h"
#include "Identity.h"
#include "Streaming.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include "I2PTunnel.h"
#include "Config.h"
#include "HTTP.h"
namespace i2p {
namespace proxy {
bool str_rmatch(std::string & str, const char *suffix) {
auto pos = str.rfind (suffix);
if (pos == std::string::npos)
return false; /* not found */
if (str.length() == (pos + std::strlen(suffix)))
return true; /* match */
return false;
}
class HTTPReqHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPReqHandler>
{
private:
bool HandleRequest(std::size_t len);
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
void Terminate();
void AsyncSockRead();
void HTTPRequestFailed(const char *message);
void RedirectToJumpService(std::string & host);
bool ExtractAddressHelper(i2p::http::URL & url, std::string & b64);
void SanitizeHTTPRequest(i2p::http::HTTPReq & req);
void SentHTTPFailed(const boost::system::error_code & ecode);
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
std::vector<unsigned char> m_recv_buf; /* as "downstream recieve buffer", from client to me */
std::vector<unsigned char> m_send_buf; /* as "upstream send buffer", from me to remote host */
public:
HTTPReqHandler(HTTPProxy * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
I2PServiceHandler(parent), m_sock(sock), m_recv_buf(8192), m_send_buf(0) {};
~HTTPReqHandler() { Terminate(); }
void Handle () { AsyncSockRead(); }
};
void HTTPReqHandler::AsyncSockRead()
{
LogPrint(eLogDebug, "HTTPProxy: async sock read");
if (!m_sock) {
LogPrint(eLogError, "HTTPProxy: no socket for read");
return;
}
m_sock->async_receive(boost::asio::buffer(m_recv_buf),
std::bind(&HTTPReqHandler::HandleSockRecv, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
}
void HTTPReqHandler::Terminate() {
if (Kill()) return;
if (m_sock)
{
LogPrint(eLogDebug, "HTTPProxy: close sock");
m_sock->close();
m_sock = nullptr;
}
Done(shared_from_this());
}
void HTTPReqHandler::HTTPRequestFailed(const char *message)
{
i2p::http::HTTPRes res;
res.code = 500;
res.add_header("Content-Type", "text/plain");
res.add_header("Connection", "close");
res.body = message;
res.body += "\r\n";
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response, response.size()),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
void HTTPReqHandler::RedirectToJumpService(std::string & host)
{
i2p::http::HTTPRes res;
i2p::http::URL url;
i2p::config::GetOption("http.address", url.host);
i2p::config::GetOption("http.port", url.port);
url.schema = "http";
url.path = "/";
url.query = "page=jumpservices&address=";
url.query += host;
res.code = 302; /* redirect */
res.add_header("Location", url.to_string().c_str());
res.add_header("Connection", "close");
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response, response.length()),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
bool HTTPReqHandler::ExtractAddressHelper(i2p::http::URL & url, std::string & b64)
{
const char *param = "i2paddresshelper=";
std::size_t pos = url.query.find(param);
std::size_t len = std::strlen(param);
std::map<std::string, std::string> params;
if (pos == std::string::npos)
return false; /* not found */
if (!url.parse_query(params))
return false;
std::string value = params["i2paddresshelper"];
len += value.length();
b64 = i2p::http::UrlDecode(value);
url.query.replace(pos, len, "");
return true;
}
void HTTPReqHandler::SanitizeHTTPRequest(i2p::http::HTTPReq & req)
{
req.del_header("Referer");
req.add_header("Connection", "close", true);
req.add_header("User-Agent", "MYOB/6.66 (AN/ON)", true);
}
/**
* @param len length of data in m_recv_buf
* @return true on processed request or false if more data needed
*/
bool HTTPReqHandler::HandleRequest(std::size_t len)
{
i2p::http::HTTPReq req;
i2p::http::URL url;
std::string b64;
int req_len = 0;
req_len = req.parse((const char *) m_recv_buf.data(), len);
if (req_len == 0)
return false; /* need more data */
if (req_len < 0) {
LogPrint(eLogError, "HTTPProxy: unable to parse request");
HTTPRequestFailed("invalid request");
return true; /* parse error */
}
/* parsing success, now let's look inside request */
LogPrint(eLogDebug, "HTTPProxy: requested: ", req.uri);
url.parse(req.uri);
if (ExtractAddressHelper(url, b64)) {
i2p::client::context.GetAddressBook ().InsertAddress (url.host, b64);
std::string message = "added b64 from addresshelper for " + url.host + " to address book";
LogPrint (eLogInfo, "HTTPProxy: ", message);
message += ", please reload page";
HTTPRequestFailed(message.c_str());
return true; /* request processed */
}
i2p::data::IdentHash identHash;
if (str_rmatch(url.host, ".i2p")) {
if (!i2p::client::context.GetAddressBook ().GetIdentHash (url.host, identHash)) {
RedirectToJumpService(url.host);
return true; /* request processed */
}
/* TODO: outproxy handler here */
} else {
std::string message = "Host " + url.host + " not inside i2p network, but outproxy support still missing";
HTTPRequestFailed(message.c_str());
LogPrint (eLogWarning, "HTTPProxy: ", message);
return true;
}
SanitizeHTTPRequest(req);
std::string dest_host = url.host;
uint16_t dest_port = url.port;
/* convert proxy-style http req to ordinary one: */
/* 1) replace Host header, 2) make relative url */
req.add_header("Host", url.host, true);
url.schema = "";
url.host = "";
req.uri = url.to_string();
/* drop original request from input buffer */
m_recv_buf.erase(m_recv_buf.begin(), m_recv_buf.begin() + req_len);
/* build new buffer from modified request and data from original request */
std::string request = req.to_string();
m_send_buf.assign(request.begin(), request.end());
m_send_buf.insert(m_send_buf.end(), m_recv_buf.begin(), m_recv_buf.end());
/* connect to destination */
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete,
shared_from_this(), std::placeholders::_1), dest_host, dest_port);
return true;
}
void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{
LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes");
if(ecode)
{
LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode);
Terminate();
return;
}
if (HandleRequest(len)) {
m_recv_buf.clear();
return; /* request processed */
}
AsyncSockRead();
}
void HTTPReqHandler::SentHTTPFailed(const boost::system::error_code & ecode)
{
if (ecode)
LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ());
Terminate();
}
void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (!stream) {
LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info");
HTTPRequestFailed("error when creating the stream, check logs");
return;
}
if (Kill())
return;
LogPrint (eLogDebug, "HTTPProxy: New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream);
GetOwner()->AddHandler (connection);
connection->I2PConnect (m_send_buf.data(), m_send_buf.size());
Done (shared_from_this());
}
HTTPProxy::HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
{
}
std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxy::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
return std::make_shared<HTTPReqHandler> (this, socket);
}
} // http
} // i2p
<commit_msg>* HTTPProxy.cpp : allow "tranparent" proxy (#508)<commit_after>#include <cstring>
#include <cassert>
#include <string>
#include <atomic>
#include <memory>
#include <set>
#include <boost/asio.hpp>
#include <mutex>
#include "I2PService.h"
#include "Destination.h"
#include "HTTPProxy.h"
#include "util.h"
#include "Identity.h"
#include "Streaming.h"
#include "Destination.h"
#include "ClientContext.h"
#include "I2PEndian.h"
#include "I2PTunnel.h"
#include "Config.h"
#include "HTTP.h"
namespace i2p {
namespace proxy {
bool str_rmatch(std::string & str, const char *suffix) {
auto pos = str.rfind (suffix);
if (pos == std::string::npos)
return false; /* not found */
if (str.length() == (pos + std::strlen(suffix)))
return true; /* match */
return false;
}
class HTTPReqHandler: public i2p::client::I2PServiceHandler, public std::enable_shared_from_this<HTTPReqHandler>
{
private:
bool HandleRequest(std::size_t len);
void HandleSockRecv(const boost::system::error_code & ecode, std::size_t bytes_transfered);
void Terminate();
void AsyncSockRead();
void HTTPRequestFailed(const char *message);
void RedirectToJumpService(std::string & host);
bool ExtractAddressHelper(i2p::http::URL & url, std::string & b64);
void SanitizeHTTPRequest(i2p::http::HTTPReq & req);
void SentHTTPFailed(const boost::system::error_code & ecode);
void HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream);
std::shared_ptr<boost::asio::ip::tcp::socket> m_sock;
std::vector<unsigned char> m_recv_buf; /* as "downstream recieve buffer", from client to me */
std::vector<unsigned char> m_send_buf; /* as "upstream send buffer", from me to remote host */
public:
HTTPReqHandler(HTTPProxy * parent, std::shared_ptr<boost::asio::ip::tcp::socket> sock) :
I2PServiceHandler(parent), m_sock(sock), m_recv_buf(8192), m_send_buf(0) {};
~HTTPReqHandler() { Terminate(); }
void Handle () { AsyncSockRead(); }
};
void HTTPReqHandler::AsyncSockRead()
{
LogPrint(eLogDebug, "HTTPProxy: async sock read");
if (!m_sock) {
LogPrint(eLogError, "HTTPProxy: no socket for read");
return;
}
m_sock->async_receive(boost::asio::buffer(m_recv_buf),
std::bind(&HTTPReqHandler::HandleSockRecv, shared_from_this(),
std::placeholders::_1, std::placeholders::_2));
}
void HTTPReqHandler::Terminate() {
if (Kill()) return;
if (m_sock)
{
LogPrint(eLogDebug, "HTTPProxy: close sock");
m_sock->close();
m_sock = nullptr;
}
Done(shared_from_this());
}
void HTTPReqHandler::HTTPRequestFailed(const char *message)
{
i2p::http::HTTPRes res;
res.code = 500;
res.add_header("Content-Type", "text/plain");
res.add_header("Connection", "close");
res.body = message;
res.body += "\r\n";
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response, response.size()),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
void HTTPReqHandler::RedirectToJumpService(std::string & host)
{
i2p::http::HTTPRes res;
i2p::http::URL url;
i2p::config::GetOption("http.address", url.host);
i2p::config::GetOption("http.port", url.port);
url.schema = "http";
url.path = "/";
url.query = "page=jumpservices&address=";
url.query += host;
res.code = 302; /* redirect */
res.add_header("Location", url.to_string().c_str());
res.add_header("Connection", "close");
std::string response = res.to_string();
boost::asio::async_write(*m_sock, boost::asio::buffer(response, response.length()),
std::bind(&HTTPReqHandler::SentHTTPFailed, shared_from_this(), std::placeholders::_1));
}
bool HTTPReqHandler::ExtractAddressHelper(i2p::http::URL & url, std::string & b64)
{
const char *param = "i2paddresshelper=";
std::size_t pos = url.query.find(param);
std::size_t len = std::strlen(param);
std::map<std::string, std::string> params;
if (pos == std::string::npos)
return false; /* not found */
if (!url.parse_query(params))
return false;
std::string value = params["i2paddresshelper"];
len += value.length();
b64 = i2p::http::UrlDecode(value);
url.query.replace(pos, len, "");
return true;
}
void HTTPReqHandler::SanitizeHTTPRequest(i2p::http::HTTPReq & req)
{
req.del_header("Referer");
req.add_header("Connection", "close", true);
req.add_header("User-Agent", "MYOB/6.66 (AN/ON)", true);
}
/**
* @param len length of data in m_recv_buf
* @return true on processed request or false if more data needed
*/
bool HTTPReqHandler::HandleRequest(std::size_t len)
{
i2p::http::HTTPReq req;
i2p::http::URL url;
std::string b64;
int req_len = 0;
req_len = req.parse((const char *) m_recv_buf.data(), len);
if (req_len == 0)
return false; /* need more data */
if (req_len < 0) {
LogPrint(eLogError, "HTTPProxy: unable to parse request");
HTTPRequestFailed("invalid request");
return true; /* parse error */
}
/* parsing success, now let's look inside request */
LogPrint(eLogDebug, "HTTPProxy: requested: ", req.uri);
url.parse(req.uri);
if (ExtractAddressHelper(url, b64)) {
i2p::client::context.GetAddressBook ().InsertAddress (url.host, b64);
std::string message = "added b64 from addresshelper for " + url.host + " to address book";
LogPrint (eLogInfo, "HTTPProxy: ", message);
message += ", please reload page";
HTTPRequestFailed(message.c_str());
return true; /* request processed */
}
i2p::data::IdentHash identHash;
if (str_rmatch(url.host, ".i2p")) {
if (!i2p::client::context.GetAddressBook ().GetIdentHash (url.host, identHash)) {
RedirectToJumpService(url.host);
return true; /* request processed */
}
/* TODO: outproxy handler here */
} else {
std::string message = "Host " + url.host + " not inside i2p network, but outproxy support still missing";
HTTPRequestFailed(message.c_str());
LogPrint (eLogWarning, "HTTPProxy: ", message);
return true;
}
SanitizeHTTPRequest(req);
std::string dest_host = url.host;
uint16_t dest_port = url.port;
/* set proper 'Host' header in upstream request */
auto h = req.headers.find("Host");
if (dest_host != "") {
/* absolute url, replace 'Host' header */
std::string h = dest_host;
if (dest_port != 0 && dest_port != 80)
h += ":" + std::to_string(dest_port);
req.add_header("Host", h, true);
} else if (h != req.headers.end()) {
/* relative url and 'Host' header provided. transparent proxy mode? */
i2p::http::URL u;
std::string t = "http://" + h->second;
u.parse(t);
dest_host = u.host;
dest_port = u.port;
} else {
/* relative url and missing 'Host' header */
std::string message = "Can't detect destination host from request";
HTTPRequestFailed(message.c_str());
return true;
}
/* make relative url */
url.schema = "";
url.host = "";
req.uri = url.to_string();
/* drop original request from input buffer */
m_recv_buf.erase(m_recv_buf.begin(), m_recv_buf.begin() + req_len);
/* build new buffer from modified request and data from original request */
std::string request = req.to_string();
m_send_buf.assign(request.begin(), request.end());
m_send_buf.insert(m_send_buf.end(), m_recv_buf.begin(), m_recv_buf.end());
/* connect to destination */
GetOwner()->CreateStream (std::bind (&HTTPReqHandler::HandleStreamRequestComplete,
shared_from_this(), std::placeholders::_1), dest_host, dest_port);
return true;
}
void HTTPReqHandler::HandleSockRecv(const boost::system::error_code & ecode, std::size_t len)
{
LogPrint(eLogDebug, "HTTPProxy: sock recv: ", len, " bytes");
if(ecode)
{
LogPrint(eLogWarning, "HTTPProxy: sock recv got error: ", ecode);
Terminate();
return;
}
if (HandleRequest(len)) {
m_recv_buf.clear();
return; /* request processed */
}
AsyncSockRead();
}
void HTTPReqHandler::SentHTTPFailed(const boost::system::error_code & ecode)
{
if (ecode)
LogPrint (eLogError, "HTTPProxy: Closing socket after sending failure because: ", ecode.message ());
Terminate();
}
void HTTPReqHandler::HandleStreamRequestComplete (std::shared_ptr<i2p::stream::Stream> stream)
{
if (!stream) {
LogPrint (eLogError, "HTTPProxy: error when creating the stream, check the previous warnings for more info");
HTTPRequestFailed("error when creating the stream, check logs");
return;
}
if (Kill())
return;
LogPrint (eLogDebug, "HTTPProxy: New I2PTunnel connection");
auto connection = std::make_shared<i2p::client::I2PTunnelConnection>(GetOwner(), m_sock, stream);
GetOwner()->AddHandler (connection);
connection->I2PConnect (m_send_buf.data(), m_send_buf.size());
Done (shared_from_this());
}
HTTPProxy::HTTPProxy(const std::string& address, int port, std::shared_ptr<i2p::client::ClientDestination> localDestination):
TCPIPAcceptor(address, port, localDestination ? localDestination : i2p::client::context.GetSharedLocalDestination ())
{
}
std::shared_ptr<i2p::client::I2PServiceHandler> HTTPProxy::CreateHandler(std::shared_ptr<boost::asio::ip::tcp::socket> socket)
{
return std::make_shared<HTTPReqHandler> (this, socket);
}
} // http
} // i2p
<|endoftext|>
|
<commit_before>#include "HashTable.h"
HashTable::HashTable()
:method{LINEAR} {
if (method == PERFECT)
perfectTable = std::vector<std::vector<int>>(100);
else
openTable = std::vector<int>(100);
}
/* Param: METHOD m, int Size
* Desc: initializes hash table with size `size` and hashing algorithm `m`.
*/
HashTable::HashTable(METHOD m, int size)
:method{m} {
if (method == PERFECT)
perfectTable = std::vector<std::vector<int>>(size);
else
openTable = std::vector<int>(size);
}
HashTable::~HashTable()
{
}
/*---------------PUBLIC METHODS---------------*/
/* Param: int key, int value
* Desc: inserts `value` into table based on `key`
* Returns: void
*/
void HashTable::insert(int key, int value){
if (method == PERFECT) {
perfectTable[hashKey(key)][perfectHashKey(hashKey(key))] = value;
return;
}
openTable[hashKey(key)] = value;
}
/* Param: int key
* Desc: finds the value that corresponds to the given key
* Returns: returns the value or `<-1` if not found
*/
int HashTable::find(int key){
int pos = hashKey(key);
int val = -1;
if (method == PERFECT) {
val = perfectTable[pos][perfectHashKey(pos)];
} else {
val = openTable[pos];
}
return val;
}
/* Param: int key
* Desc: deletes the value in table that corresponds to the given key
* Returns: returns `true` if deleted or `false` if key not found
*/
bool HashTable::remove(int key){
int pos = hashKey(key);
int val = -5;
if (method == PERFECT) {
val = perfectTable[pos][perfectHashKey(pos)];
perfectTable[pos][perfectHashKey(pos)] = -2;
} else {
val = openTable[pos];
openTable[pos] = -2;
}
return (val != -5);
}
/*---------------PRIVATE METHODS---------------*/
/* Param: int key
* Desc: hashes `key` based on specified method
* Returns: returns its location in the table
*/
int HashTable::hashKey(int key){
int pos = 0;
//TODO: hash key, set pos
return pos;
}
int HashTable::perfectHashKey(int key){
return -1;
}
/* Param: int key
* Desc: hashes `key` linearly
* Returns: returns its location in the table
*/
int HashTable::linearHash(int key){
int retVal = -1;
//TODO: hash key
return retVal;
}
/* Param: int key
* Desc: hashes `key` quadtratically
* Returns: returns its location in the table
*/
int HashTable::quadraticHash(int key){
int retVal = -1;
//TODO: hash key
return retVal;
}
/* Param: int key
* Desc: hashes `key` perfectly
* Returns: returns its location in the table
*/
int HashTable::perfectHash(int key){
int retVal = -1;
//TODO: hash key
return retVal;
}<commit_msg>added doubleHash method. openTable vector now inits to -1<commit_after>#include "HashTable.h"
HashTable::HashTable()
:method{LINEAR} {
if (method == PERFECT)
perfectTable = std::vector<std::vector<int>>(100);
else
openTable = std::vector<int>(100, -1); // initialize all values to -1
}
/* Param: METHOD m, int Size
* Desc: initializes hash table with size `size` and hashing algorithm `m`.
*/
HashTable::HashTable(METHOD m, int size)
:method{m} {
if (method == PERFECT)
perfectTable = std::vector<std::vector<int>>(size);
else
openTable = std::vector<int>(size, -1); // initialize all values to -1
}
HashTable::~HashTable()
{
}
/*---------------PUBLIC METHODS---------------*/
/* Param: int key, int value
* Desc: inserts `value` into table based on `key`
* Returns: void
*/
void HashTable::insert(int key, int value){
if (method == PERFECT) {
perfectTable[hashKey(key)][perfectHashKey(hashKey(key))] = value;
return;
}
openTable[hashKey(key)] = value;
}
/* Param: int key
* Desc: finds the value that corresponds to the given key
* Returns: returns the value or `<-1` if not found
*/
int HashTable::find(int key){
int pos = hashKey(key);
int val = -1;
if (method == PERFECT) {
val = perfectTable[pos][perfectHashKey(pos)];
} else {
val = openTable[pos];
}
return val;
}
/* Param: int key
* Desc: deletes the value in table that corresponds to the given key
* Returns: returns `true` if deleted or `false` if key not found
*/
bool HashTable::remove(int key){
int pos = hashKey(key);
int val = -5;
if (method == PERFECT) {
val = perfectTable[pos][perfectHashKey(pos)];
perfectTable[pos][perfectHashKey(pos)] = -2;
} else {
val = openTable[pos];
openTable[pos] = -2;
}
return (val != -5);
}
/*---------------PRIVATE METHODS---------------*/
/* Param: int key
* Desc: hashes `key` based on specified method
* Returns: returns its location in the table
*/
int HashTable::hashKey(int key){
int pos = 0;
//TODO: hash key, set pos
return pos;
}
int HashTable::perfectHashKey(int key){
return -1;
}
/* Param: int key
* Desc: hashes `key` linearly
* Returns: returns its location in the table
*/
int HashTable::linearHash(int key){
int retVal = -1;
//TODO: hash key
return retVal;
}
/* Param: int key
* Desc: hashes `key` quadtratically
* Returns: returns its location in the table
*/
int HashTable::quadraticHash(int key){
int retVal = -1;
//TODO: hash key
return retVal;
}
/* Param: int key
* Desc: hashes `key` using double hash method
* Returns: returns its location in the table
*/
int HashTable::doubleHash(int key) {
int m = openTable.size(); // FIX THIS BETTER
int interval = 1 + (key % (m-1));
int idx = key % m;
// find empty spot. -1 if empty, -2 if deleted
while (openTable[idx] > -1) {
idx += interval;
}
return idx;
}
/* Param: int key
* Desc: hashes `key` perfectly
* Returns: returns its location in the table
*/
int HashTable::perfectHash(int key){
int retVal = -1;
//TODO: hash key
return retVal;
}<|endoftext|>
|
<commit_before>#include "iteration/updater/source_updater_gauss_seidel.h"
#include <memory>
#include <deal.II/base/mpi.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include "test_helpers/test_helper_functions.h"
#include "test_helpers/gmock_wrapper.h"
#include "system/moments/spherical_harmonic_types.h"
#include "system/system.h"
#include "system/system_types.h"
#include "formulation/tests/cfem_stamper_mock.h"
#include "formulation/cfem_stamper_i.h"
#include "test_helpers/test_assertions.h"
#include "system/terms/tests/linear_term_mock.h"
namespace {
using namespace bart;
using system::MPIVector;
using ::testing::An;
using ::testing::Ref;
using ::testing::DoDefault;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::WithArgs;
using ::testing::_;
/* This test class verifies the operation of the SourceUpdaterGaussSeidel class.
* It uses the template of it that uses a CFEMStamperI, a mock version of
* that object will be used. The required System object will be explicitly
* created, because it is just a struct, but some of the stored objects
* (the right hand side) will also use mocks.
*/
class IterationSourceUpdaterGaussSeidelTest : public ::testing::Test {
protected:
using CFEMSourceUpdater = iteration::updater::SourceUpdaterGaussSeidel<formulation::CFEMStamperI>;
using VariableTerms = system::terms::VariableLinearTerms;
// Required objects
// Test system
system::System test_system_;
// Vector returned by the mock RightHandSide object when the variable
// right hand side vector is requested. This is what should be stamped.
std::shared_ptr<MPIVector> source_vector_ptr_;
MPIVector expected_vector_;
// Required mocks
std::unique_ptr<formulation::CFEM_StamperMock> mock_stamper_ptr_;
std::unique_ptr<system::terms::LinearTermMock> mock_rhs_ptr_;
void SetUp() override;
};
/* Sets up the tests. This function first creates the mock objects to be used
* by the testing, then establishes any default behaviors for NiceMocks. The
* right hand side vector can be handed off to the System object, but the
* stamper needs to be given to the test updater _in_ the tests because, as a
* required dependency, it is passed in the constructor.
*/
void IterationSourceUpdaterGaussSeidelTest::SetUp() {
mock_stamper_ptr_ = std::make_unique<NiceMock<formulation::CFEM_StamperMock>>();
mock_rhs_ptr_ = std::make_unique<NiceMock<system::terms::LinearTermMock>>();
/* Create and populate moment maps. The inserted MomentVectors can be empty
* because we will check that the correct ones are passed by reference not
* entries.
*/
system::moments::MomentsMap current_iteration, previous_iteration;
int l_max = 2;
for (system::GroupNumber group = 0; group < 5; ++group) {
for (system::moments::HarmonicL l = 0; l < l_max; ++l) {
for (system::moments::HarmonicM m = -l_max; m <= l_max; ++m) {
system::moments::MomentVector current_moment, previous_moment;
current_iteration[{group, l, m}] = current_moment;
previous_iteration[{group, l, m}] = previous_moment;
}
}
}
test_system_.current_iteration_moments = current_iteration;
test_system_.previous_iteration_moments = previous_iteration;
/* Initialize MPI Vectors */
source_vector_ptr_ = std::make_shared<MPIVector>();
auto n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
source_vector_ptr_->reinit(MPI_COMM_WORLD,
n_processes*5,
5);
expected_vector_.reinit(*source_vector_ptr_);
ON_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::Index>(),_))
.WillByDefault(Return(source_vector_ptr_));
ON_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::GroupNumber>(),_))
.WillByDefault(Return(source_vector_ptr_));
}
// Fills an MPI vector with value
void StampMPIVector(MPIVector &to_fill, double value = 2) {
auto [local_begin, local_end] = to_fill.local_range();
for (unsigned int i = local_begin; i < local_end; ++i)
to_fill(i) += value;
to_fill.compress(dealii::VectorOperation::add);
}
// Verifies that the Updater takes ownership of the stamper.
TEST_F(IterationSourceUpdaterGaussSeidelTest, Constructor) {
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
EXPECT_EQ(mock_stamper_ptr_, nullptr);
}
/*
* ======== UpdateScatteringSource Tests =======================================
*/
// Verifies UpdateScatteringSource throws if RHS returns a null vector.
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateScatteringSourceBadRHS) {
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::Index>(),_))
.WillOnce(Return(nullptr));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateScatteringSource(test_system_, 0, 0));
}
// Verify trying to update a group that has no moment returns an error
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateScatteringSourceBadMoment) {
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateScatteringSource(test_system_, 10, 0));
}
// Verifies operation of the UpdateScatteringSource function
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateScatteringSourceTestMPI) {
system::GroupNumber group = btest::RandomDouble(1, 3);
system::AngleIndex angle = btest::RandomDouble(0, 10);
system::Index index = {group, angle};
// Fill source vector with the value 2
StampMPIVector(*source_vector_ptr_, 3);
StampMPIVector(expected_vector_, group);
/* Call expectations, expect to retrieve the scattering term vector from RHS
* and then stamp it. We invoke the StampMPIVector function, which STAMPS a
* vector. We make sure that the original value of 3, filled above, was zerod
* out and replaced by the random group number.
*/
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(index,
VariableTerms::kScatteringSource))
.WillOnce(DoDefault());
EXPECT_CALL(*mock_stamper_ptr_,
StampScatteringSource(Ref(*source_vector_ptr_),
group,
Ref(test_system_.current_iteration_moments[{group, 0, 0}]),
Ref(test_system_.current_iteration_moments)))
.WillOnce(WithArgs<0,1>(Invoke(StampMPIVector)));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
// Tested call
test_updater.UpdateScatteringSource(test_system_, group, angle);
EXPECT_TRUE(bart::testing::CompareMPIVectors(*source_vector_ptr_,
expected_vector_));
}
/*
* ======== UpdateFissionSource Tests ==========================================
*/
// Verifies UpdateFissionSource throws if RHS returns a null vector.
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceBadRHS) {
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::Index>(),_))
.WillOnce(Return(nullptr));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
test_system_.k_effective = 1.0;
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
}
// Verify trying to update a group that has no moment returns an error
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceBadMoment) {
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 10, 0));
}
// Verify a bad keffective value (0, negative, or nullopt) returns an error
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceBadKeff) {
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
// k_effective is still nullopt
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
test_system_.k_effective = 0;
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
test_system_.k_effective = -1;
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
}
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceTestMPI) {
system::GroupNumber group = btest::RandomDouble(1, 3);
system::AngleIndex angle = btest::RandomDouble(0, 10);
system::Index index = {group, angle};
// Fill source vector with the value 3
StampMPIVector(*source_vector_ptr_, 3);
// Expected value identical to the group, which is [1, 3)
StampMPIVector(expected_vector_, group);
double k_effective = 1.05;
test_system_.k_effective = k_effective;
/* Call expectations, expect to retrieve the fission term vector from RHS
* and then stamp it. We invoke the StampMPIVector function, which STAMPS a
* vector. We make sure that the original value of 3, filled above, was zerod
* out and replaced by the random group number.
*/
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(index,
VariableTerms::kFissionSource))
.WillOnce(DoDefault());
EXPECT_CALL(*mock_stamper_ptr_,
StampFissionSource(Ref(*source_vector_ptr_),
group,
k_effective,
Ref(test_system_.current_iteration_moments[{group, 0, 0}]),
Ref(test_system_.current_iteration_moments)))
.WillOnce(WithArgs<0,1>(Invoke(StampMPIVector)));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
// Tested call
test_updater.UpdateFissionSource(test_system_, group, angle);
EXPECT_TRUE(bart::testing::CompareMPIVectors(*source_vector_ptr_,
expected_vector_));
}
} // namespace<commit_msg>updated tests to use SphericalHarmonicI object instead of system.current_iteration_moments<commit_after>#include "iteration/updater/source_updater_gauss_seidel.h"
#include <memory>
#include <deal.II/base/mpi.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include "test_helpers/test_helper_functions.h"
#include "test_helpers/gmock_wrapper.h"
#include "system/moments/spherical_harmonic_types.h"
#include "system/system.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "system/system_types.h"
#include "formulation/tests/cfem_stamper_mock.h"
#include "formulation/cfem_stamper_i.h"
#include "test_helpers/test_assertions.h"
#include "system/terms/tests/linear_term_mock.h"
namespace {
using namespace bart;
using system::MPIVector;
using ::testing::An;
using ::testing::Ref;
using ::testing::DoDefault;
using ::testing::Invoke;
using ::testing::NiceMock;
using ::testing::Return, ::testing::ReturnRef;
using ::testing::WithArgs;
using ::testing::_;
/* This test class verifies the operation of the SourceUpdaterGaussSeidel class.
* It uses the template of it that uses a CFEMStamperI, a mock version of
* that object will be used. The required System object will be explicitly
* created, because it is just a struct, but some of the stored objects
* (the right hand side) will also use mocks.
*/
class IterationSourceUpdaterGaussSeidelTest : public ::testing::Test {
protected:
using CFEMSourceUpdater = iteration::updater::SourceUpdaterGaussSeidel<formulation::CFEMStamperI>;
using VariableTerms = system::terms::VariableLinearTerms;
// Required objects
// Test system
system::System test_system_;
// Vector returned by the mock RightHandSide object when the variable
// right hand side vector is requested. This is what should be stamped.
std::shared_ptr<MPIVector> source_vector_ptr_;
MPIVector expected_vector_;
// Required mocks and supporting objects
std::unique_ptr<formulation::CFEM_StamperMock> mock_stamper_ptr_;
std::unique_ptr<system::terms::LinearTermMock> mock_rhs_ptr_;
std::unique_ptr<system::moments::SphericalHarmonicMock> moments_ptr_;
system::moments::SphericalHarmonicMock* moments_obs_ptr_;
system::moments::MomentsMap current_iteration_moments_,
previous_iteration_moments_;
void SetUp() override;
};
/* Sets up the tests. This function first creates the mock objects to be used
* by the testing, then establishes any default behaviors for NiceMocks. The
* right hand side vector can be handed off to the System object, but the
* stamper needs to be given to the test updater _in_ the tests because, as a
* required dependency, it is passed in the constructor.
*/
void IterationSourceUpdaterGaussSeidelTest::SetUp() {
mock_stamper_ptr_ = std::make_unique<NiceMock<formulation::CFEM_StamperMock>>();
mock_rhs_ptr_ = std::make_unique<NiceMock<system::terms::LinearTermMock>>();
moments_ptr_ = std::make_unique<system::moments::SphericalHarmonicMock>();
/* Create and populate moment maps. The inserted MomentVectors can be empty
* because we will check that the correct ones are passed by reference not
* entries.
*/
int l_max = 2;
for (system::GroupNumber group = 0; group < 5; ++group) {
for (system::moments::HarmonicL l = 0; l < l_max; ++l) {
for (system::moments::HarmonicM m = -l_max; m <= l_max; ++m) {
system::moments::MomentVector current_moment, previous_moment;
current_iteration_moments_[{group, l, m}] = current_moment;
previous_iteration_moments_[{group, l, m}] = previous_moment;
}
}
}
moments_obs_ptr_ = moments_ptr_.get();
test_system_.current_moments = std::move(moments_ptr_);
/* Initialize MPI Vectors */
source_vector_ptr_ = std::make_shared<MPIVector>();
auto n_processes = dealii::Utilities::MPI::n_mpi_processes(MPI_COMM_WORLD);
source_vector_ptr_->reinit(MPI_COMM_WORLD,
n_processes*5,
5);
expected_vector_.reinit(*source_vector_ptr_);
ON_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::Index>(),_))
.WillByDefault(Return(source_vector_ptr_));
ON_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::GroupNumber>(),_))
.WillByDefault(Return(source_vector_ptr_));
}
// Fills an MPI vector with value
void StampMPIVector(MPIVector &to_fill, double value = 2) {
auto [local_begin, local_end] = to_fill.local_range();
for (unsigned int i = local_begin; i < local_end; ++i)
to_fill(i) += value;
to_fill.compress(dealii::VectorOperation::add);
}
// Verifies that the Updater takes ownership of the stamper.
TEST_F(IterationSourceUpdaterGaussSeidelTest, Constructor) {
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
EXPECT_EQ(mock_stamper_ptr_, nullptr);
}
/*
* ======== UpdateScatteringSource Tests =======================================
*/
// Verifies UpdateScatteringSource throws if RHS returns a null vector.
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateScatteringSourceBadRHS) {
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::Index>(),_))
.WillOnce(Return(nullptr));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateScatteringSource(test_system_, 0, 0));
}
// Verify trying to update a group that has no moment returns an error
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateScatteringSourceBadMoment) {
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateScatteringSource(test_system_, 10, 0));
}
// Verifies operation of the UpdateScatteringSource function
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateScatteringSourceTestMPI) {
system::GroupNumber group = btest::RandomDouble(1, 3);
system::AngleIndex angle = btest::RandomDouble(0, 10);
system::Index index = {group, angle};
// Fill source vector with the value 2
StampMPIVector(*source_vector_ptr_, 3);
StampMPIVector(expected_vector_, group);
/* Call expectations, expect to retrieve the scattering term vector from RHS
* and then stamp it. We invoke the StampMPIVector function, which STAMPS a
* vector. We make sure that the original value of 3, filled above, was zerod
* out and replaced by the random group number.
*/
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(index,
VariableTerms::kScatteringSource))
.WillOnce(DoDefault());
std::array<int, 3> moment_index{group, 0, 0};
EXPECT_CALL(*moments_obs_ptr_, GetMoment(moment_index))
.WillOnce(ReturnRef(current_iteration_moments_[{group, 0, 0}]));
EXPECT_CALL(*moments_obs_ptr_, moments())
.WillOnce(ReturnRef(current_iteration_moments_));
EXPECT_CALL(*mock_stamper_ptr_,
StampScatteringSource(Ref(*source_vector_ptr_),
group,
Ref(current_iteration_moments_[{group, 0, 0}]),
Ref(current_iteration_moments_)))
.WillOnce(WithArgs<0,1>(Invoke(StampMPIVector)));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
// Tested call
test_updater.UpdateScatteringSource(test_system_, group, angle);
EXPECT_TRUE(bart::testing::CompareMPIVectors(*source_vector_ptr_,
expected_vector_));
}
/*
* ======== UpdateFissionSource Tests ==========================================
*/
// Verifies UpdateFissionSource throws if RHS returns a null vector.
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceBadRHS) {
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(An<system::Index>(),_))
.WillOnce(Return(nullptr));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
test_system_.k_effective = 1.0;
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
}
// Verify trying to update a group that has no moment returns an error
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceBadMoment) {
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 10, 0));
}
// Verify a bad keffective value (0, negative, or nullopt) returns an error
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceBadKeff) {
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
// k_effective is still nullopt
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
test_system_.k_effective = 0;
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
test_system_.k_effective = -1;
EXPECT_ANY_THROW(test_updater.UpdateFissionSource(test_system_, 0, 0));
}
TEST_F(IterationSourceUpdaterGaussSeidelTest, UpdateFissionSourceTestMPI) {
system::GroupNumber group = btest::RandomDouble(1, 3);
system::AngleIndex angle = btest::RandomDouble(0, 10);
system::Index index = {group, angle};
// Fill source vector with the value 3
StampMPIVector(*source_vector_ptr_, 3);
// Expected value identical to the group, which is [1, 3)
StampMPIVector(expected_vector_, group);
double k_effective = 1.05;
test_system_.k_effective = k_effective;
/* Call expectations, expect to retrieve the fission term vector from RHS
* and then stamp it. We invoke the StampMPIVector function, which STAMPS a
* vector. We make sure that the original value of 3, filled above, was zerod
* out and replaced by the random group number.
*/
EXPECT_CALL(*mock_rhs_ptr_, GetVariableTermPtr(index,
VariableTerms::kFissionSource))
.WillOnce(DoDefault());
std::array<int, 3> moment_index{group, 0, 0};
EXPECT_CALL(*moments_obs_ptr_, GetMoment(moment_index))
.WillOnce(ReturnRef(current_iteration_moments_[{group, 0, 0}]));
EXPECT_CALL(*moments_obs_ptr_, moments())
.WillOnce(ReturnRef(current_iteration_moments_));
EXPECT_CALL(*mock_stamper_ptr_,
StampFissionSource(Ref(*source_vector_ptr_),
group,
k_effective,
Ref(current_iteration_moments_[{group, 0, 0}]),
Ref(current_iteration_moments_)))
.WillOnce(WithArgs<0,1>(Invoke(StampMPIVector)));
// Final Set up
test_system_.right_hand_side_ptr_ = std::move(mock_rhs_ptr_);
CFEMSourceUpdater test_updater(std::move(mock_stamper_ptr_));
// Tested call
test_updater.UpdateFissionSource(test_system_, group, angle);
EXPECT_TRUE(bart::testing::CompareMPIVectors(*source_vector_ptr_,
expected_vector_));
}
} // namespace<|endoftext|>
|
<commit_before><commit_msg>handle abstract origin attributes when accessing die names<commit_after><|endoftext|>
|
<commit_before>#include "ConfigServer.h"
static ConfigServer * confServer;
void ConfigServer::returnOK()
{
sendHeader("Connection", "close");
sendHeader("Access-Control-Allow-Origin", "*");
send(200, "text/plain", "Configuration updated. Rebooting in 10 seconds...\r\n");
delay (10000);
ESP.restart();
}
void ConfigServer::returnFail(String msg)
{
sendHeader("Connection", "close");
sendHeader("Access-Control-Allow-Origin", "*");
send(500, "text/plain", msg + "\r\n");
}
void ConfigServer::writeConfigField(int index, String str){
eepromConfig.stageWriteField(index, str);
}
void ConfigServer::handleRoot()
{
if (confServer->args() > 1){
Serial.println("Field update requested");
String sensorName = confServer->arg("SENSOR_NAME");
String wifiName = confServer->arg("WIFI_NAME");
String wifiPwd = confServer->arg("WIFI_PWD");
String mqttIp = confServer->arg("MQTT_IP");
String mqttPort = confServer->arg("MQTT_PORT");
Serial.print("sensorName :");
Serial.println(sensorName);
Serial.print("wifiName :");
Serial.println(wifiName);
Serial.print("wifiPwd :");
Serial.println(wifiPwd);
Serial.print("mqttIp :");
Serial.println(mqttIp);
Serial.print("mqttPort :");
Serial.println(mqttPort);
confServer->writeConfigField(0, confServer->config.sensorName);
confServer->writeConfigField(1, confServer->config.wifiName);
confServer->writeConfigField(2, confServer->config.wifiPwd);
confServer->writeConfigField(3, confServer->config.mqttIp);
confServer->writeConfigField(4, confServer->config.mqttPort);
confServer->eepromConfig.commit();
confServer->returnOK();
}
else {
Serial.println("no arg");
confServer->send(200, "text/html", confServer->getHtmlPage().c_str());
}
}
String ConfigServer::getHtmlPage(){
String result =
"<!DOCTYPE HTML>"
"<html>"
"<head>"
"<meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0\">"
"<title>ESP8266 Web Form Demo</title>"
"<style>"
"\"body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }\""
"</style>"
"</head>"
"<body>"
"<h1>Device Config</h1>"
"<FORM action=\"/\" method=\"post\">"
"<P>"
"Sensor name : "
"<INPUT type=\"text\" name=\"SENSOR_NAME\" value=\"" + config.sensorName + "\"<BR>"
"WIFI access point :"
"<INPUT type=\"text\" name=\"WIFI_NAME\" value=\"" + config.wifiName + "\"<BR>"
"WIFI password :"
"<INPUT type=\"text\" name=\"WIFI_PWD\" value=\"" + config.wifiPwd + "\"<BR>"
"MQTT broker IP address : "
"<INPUT type=\"text\" name=\"MQTT_IP\" value=\"" + config.mqttIp + "\"<BR>"
"MQTT port : "
"<INPUT type=\"text\" name=\"MQTT_PORT\" value=\"" + config.mqttPort + "\"<BR>"
"<INPUT type=\"submit\" value=\"Send\"> <INPUT type=\"reset\">"
"</P>"
"</FORM>"
"</body>"
"</html>";
return result;
}
ConfigServer::ConfigServer(IPAddress ip) : ESP8266WebServer(DEFAULT_PORT){
serverIP = ip;
//Ugly but not other solution found...
//Would need to pass context to callback regitrations in ESP8266WebServer API
confServer = this;
eepromConfig.readAll();
config.sensorName = eepromConfig.readField(0);
config.wifiName = eepromConfig.readField(1);
config.wifiPwd = eepromConfig.readField(2);
config.mqttIp = eepromConfig.readField(3);
config.mqttPort = eepromConfig.readField(4);
}
MqttConfig ConfigServer::getMqttConfig(){
return config;
}
void ConfigServer::start(){
Serial.println("starting config server");
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(serverIP, serverIP, IPAddress(255, 255, 255, 0));
int result = WiFi.softAP("ESP_CONFIG");
if(result == true)
{
Serial.println("Config server ready");
}
else
{
Serial.println("Config server failed to start!");
}
on("/", &ConfigServer::handleRoot);
//on("/", fn_wrapper);
begin();
}
<commit_msg>Fix bug in values written to EEPROM. It was using the members of the config instead of the values coming from the form submission<commit_after>#include "ConfigServer.h"
static ConfigServer * confServer;
void ConfigServer::returnOK()
{
sendHeader("Connection", "close");
sendHeader("Access-Control-Allow-Origin", "*");
send(200, "text/plain", "Configuration updated. Rebooting in 10 seconds...\r\n");
delay (10000);
ESP.restart();
}
void ConfigServer::returnFail(String msg)
{
sendHeader("Connection", "close");
sendHeader("Access-Control-Allow-Origin", "*");
send(500, "text/plain", msg + "\r\n");
}
void ConfigServer::writeConfigField(int index, String str){
eepromConfig.stageWriteField(index, str);
}
void ConfigServer::handleRoot()
{
if (confServer->args() > 1){
Serial.println("Field update requested");
String sensorName = confServer->arg("SENSOR_NAME");
String wifiName = confServer->arg("WIFI_NAME");
String wifiPwd = confServer->arg("WIFI_PWD");
String mqttIp = confServer->arg("MQTT_IP");
String mqttPort = confServer->arg("MQTT_PORT");
Serial.print("sensorName :");
Serial.println(sensorName);
Serial.print("wifiName :");
Serial.println(wifiName);
Serial.print("wifiPwd :");
Serial.println(wifiPwd);
Serial.print("mqttIp :");
Serial.println(mqttIp);
Serial.print("mqttPort :");
Serial.println(mqttPort);
confServer->writeConfigField(0, sensorName);
confServer->writeConfigField(1, wifiName);
confServer->writeConfigField(2, wifiPwd);
confServer->writeConfigField(3, mqttIp);
confServer->writeConfigField(4, mqttPort);
confServer->eepromConfig.commit();
confServer->returnOK();
}
else {
Serial.println("no arg");
confServer->send(200, "text/html", confServer->getHtmlPage().c_str());
}
}
String ConfigServer::getHtmlPage(){
String result =
"<!DOCTYPE HTML>"
"<html>"
"<head>"
"<meta name = \"viewport\" content = \"width = device-width, initial-scale = 1.0, maximum-scale = 1.0, user-scalable=0\">"
"<title>ESP8266 Web Form Demo</title>"
"<style>"
"\"body { background-color: #808080; font-family: Arial, Helvetica, Sans-Serif; Color: #000000; }\""
"</style>"
"</head>"
"<body>"
"<h1>Device Config</h1>"
"<FORM action=\"/\" method=\"post\">"
"<P>"
"Sensor name : "
"<INPUT type=\"text\" name=\"SENSOR_NAME\" value=\"" + config.sensorName + "\"<BR>"
"WIFI access point :"
"<INPUT type=\"text\" name=\"WIFI_NAME\" value=\"" + config.wifiName + "\"<BR>"
"WIFI password :"
"<INPUT type=\"text\" name=\"WIFI_PWD\" value=\"" + config.wifiPwd + "\"<BR>"
"MQTT broker IP address : "
"<INPUT type=\"text\" name=\"MQTT_IP\" value=\"" + config.mqttIp + "\"<BR>"
"MQTT port : "
"<INPUT type=\"text\" name=\"MQTT_PORT\" value=\"" + config.mqttPort + "\"<BR>"
"<INPUT type=\"submit\" value=\"Send\"> <INPUT type=\"reset\">"
"</P>"
"</FORM>"
"</body>"
"</html>";
return result;
}
ConfigServer::ConfigServer(IPAddress ip) : ESP8266WebServer(DEFAULT_PORT){
serverIP = ip;
//Ugly but not other solution found...
//Would need to pass context to callback regitrations in ESP8266WebServer API
confServer = this;
eepromConfig.readAll();
config.sensorName = eepromConfig.readField(0);
config.wifiName = eepromConfig.readField(1);
config.wifiPwd = eepromConfig.readField(2);
config.mqttIp = eepromConfig.readField(3);
config.mqttPort = eepromConfig.readField(4);
}
MqttConfig ConfigServer::getMqttConfig(){
return config;
}
void ConfigServer::start(){
Serial.println("starting config server");
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(serverIP, serverIP, IPAddress(255, 255, 255, 0));
int result = WiFi.softAP("ESP_CONFIG");
if(result == true)
{
Serial.println("Config server ready");
}
else
{
Serial.println("Config server failed to start!");
}
on("/", &ConfigServer::handleRoot);
//on("/", fn_wrapper);
begin();
}
<|endoftext|>
|
<commit_before>// Config file test for MUON spectormeter
// Remember to define the directory and option
// gAlice->SetConfigFunction("Config('$HOME','box');");
void Config(char directory[100]="", char option[6]="param")
{
//
// Config file for MUON test
//
//=====================================================================
// Libraries required by geant321
gSystem->Load("libgeant321.so");
new TGeant3TGeo("C++ Interface to Geant3");
//=======================================================================
// Create the output file
Text_t filename[100];
sprintf(filename,"%sgalice.root",directory);
cout << ">>> Output file is " << filename << endl;
cout << ">>> Config.C: Creating Run Loader ..."<<endl;
AliRunLoader* rl=0x0;
rl = AliRunLoader::Open(
filename, AliConfig::GetDefaultEventFolderName(), "recreate");
if (rl == 0x0) {
gAlice->Fatal("Config.C","Can not instatiate the Run Loader");
return;
}
rl->SetCompressionLevel(2);
rl->SetNumberOfEventsPerFile(100);
gAlice->SetRunLoader(rl);
//=======================================================================
// Set External decayer
TVirtualMCDecayer *decayer = new AliDecayerPythia();
decayer->SetForceDecay(kAll);
decayer->Init();
gMC->SetExternalDecayer(decayer);
//
//=======================================================================
// ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
gMC->SetProcess("DCAY",1);
gMC->SetProcess("PAIR",1);
gMC->SetProcess("COMP",1);
gMC->SetProcess("PHOT",1);
gMC->SetProcess("PFIS",0);
gMC->SetProcess("DRAY",0);
gMC->SetProcess("ANNI",1);
gMC->SetProcess("BREM",1);
gMC->SetProcess("MUNU",1);
gMC->SetProcess("CKOV",1);
gMC->SetProcess("HADR",1);
gMC->SetProcess("LOSS",2);
gMC->SetProcess("MULS",1);
gMC->SetProcess("RAYL",1);
Float_t cut = 1.e-3; // 1MeV cut by default
Float_t tofmax = 1.e10;
gMC->SetCut("CUTGAM", cut);
gMC->SetCut("CUTELE", cut);
gMC->SetCut("CUTNEU", cut);
gMC->SetCut("CUTHAD", cut);
gMC->SetCut("CUTMUO", cut);
gMC->SetCut("BCUTE", cut);
gMC->SetCut("BCUTM", cut);
gMC->SetCut("DCUTE", cut);
gMC->SetCut("DCUTM", cut);
gMC->SetCut("PPCUTM", cut);
gMC->SetCut("TOFMAX", tofmax);
//
//=======================================================================
// ************* STEERING parameters FOR ALICE SIMULATION **************
// Chamber positions
// From AliMUONConstants class we get :
// Position Z (along beam) of the chambers (in cm)
// (from AliMUONConstants class):
// 533.5, 546.5, 678.5, 693.5, 964.0, 986.0, 1251.5, 1278.5,
// 1416.5, 1443.5, 1610, 1625., 1710., 1725.
// Internal Radius (in cm)
// 36.4, 46.2, 66.0, 80., 80., 100., 100.
// External Radius (in cm)
// 183., 245., 395., 560., 563., 850., 900.
//=======================================================================
if (!strcmp(option,"box")) {
AliGenBox * gener = new AliGenBox(1);
gener->SetMomentumRange(20.,20.1);
gener->SetPhiRange(0., 360.);
gener->SetThetaRange(171.000,178.001);
gener->SetPart(13); // Muons
gener->SetOrigin(0.,0., 0.); //vertex position
gener->SetSigma(0.0, 0.0, 0.0); //Sigma in (X,Y,Z) (cm) on IP position
}
if (!strcmp(option,"gun")) {
//*********************************************
// Example for Fixed Particle Gun *
//*********************************************
AliGenFixed *gener = new AliGenFixed(ntracks);
gener->SetMomentum(10);
gener->SetPhiRange(0.);
gener->SetThetaRange(0.);
gener->SetOrigin(30,30,1200);//vertex position
gener->SetPart(13); //GEANT particle type 13 is muons
}
if (!strcmp(option,"scan")) {
AliGenScan *gener = new AliGenScan(-1);
gener->SetMomentumRange(10,10);
gener->SetPhiRange(0, 0);
gener->SetThetaRange(-180, -180);
//vertex position
//gener->SetSigma(1,1,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetPart(kRootino);
gener->SetRange(100, -300., 300., 100, -300., 300., 1, 2000, 2000);
}
if (!strcmp(option,"param")) {
//*******************************************************
// Example for J/psi or Upsilon Production from Parameterisation *
//*******************************************************
AliGenParam *gener = new AliGenParam(1, AliGenMUONlib::kUpsilon);
gener->SetMomentumRange(0,999);
gener->SetPtRange(0,100.);
gener->SetPhiRange(0., 360.);
gener->SetCutOnChild(1);
gener->SetChildPhiRange(0.,360.);
gener->SetChildThetaRange(171.0,178.0);
gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetForceDecay(kDiMuon);
gener->SetTrackingFlag(1);
gener->Init();
}
//=============================================================
// Field (L3 0.4 T)
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k4kG);
gAlice->SetField(field);
//=================== Alice BODY parameters =============================
AliBODY *BODY = new AliBODY("BODY","Alice envelop");
//=================== ABSO parameters ============================
AliABSO *ABSO = new AliABSOv0("ABSO", "Muon Absorber");
//=================== DIPO parameters ============================
AliDIPO *DIPO = new AliDIPOv2("DIPO", "Dipole version 2");
//================== HALL parameters ============================
AliHALL *HALL = new AliHALL("HALL", "Alice Hall");
//=================== PIPE parameters ============================
AliPIPE *PIPE = new AliPIPEv0("PIPE", "Beam Pipe");
//=================== SHIL parameters ============================
AliSHIL *SHIL = new AliSHILv2("SHIL", "Shielding Version 2");
//=================== MUON Subsystem ===========================
cout << ">>> Config.C: Creating AliMUONv1 ..."<<endl;
// New MUONv1 version (geometry defined via builders)
AliMUON *MUON = new AliMUONv1("MUON", "default");
//AliMUON *MUON = new AliMUONv1("MUON", "AliMUONFactoryV3"); // New segmentation
// If align = true, the detection elements transformations
// are taken from the input files and not from the code
//MUON->SetAlign(true);
MUON->AddGeometryBuilder(new AliMUONSt1GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSt2GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSlatGeometryBuilder(MUON));
MUON->AddGeometryBuilder(new AliMUONTriggerGeometryBuilder(MUON));
}
Float_t EtaToTheta(Float_t arg){
return (180./TMath::Pi())*2.*atan(exp(-arg));
}
<commit_msg>Changed factory options (in commented lines only)<commit_after>// Config file test for MUON spectormeter
// Remember to define the directory and option
// gAlice->SetConfigFunction("Config('$HOME','box');");
void Config(char directory[100]="", char option[6]="param")
{
//
// Config file for MUON test
//
//=====================================================================
// Libraries required by geant321
gSystem->Load("libgeant321.so");
new TGeant3TGeo("C++ Interface to Geant3");
//=======================================================================
// Create the output file
Text_t filename[100];
sprintf(filename,"%sgalice.root",directory);
cout << ">>> Output file is " << filename << endl;
cout << ">>> Config.C: Creating Run Loader ..."<<endl;
AliRunLoader* rl=0x0;
rl = AliRunLoader::Open(
filename, AliConfig::GetDefaultEventFolderName(), "recreate");
if (rl == 0x0) {
gAlice->Fatal("Config.C","Can not instatiate the Run Loader");
return;
}
rl->SetCompressionLevel(2);
rl->SetNumberOfEventsPerFile(100);
gAlice->SetRunLoader(rl);
//AliLog::SetModuleDebugLevel("MUON", 1);
//=======================================================================
// Set External decayer
TVirtualMCDecayer *decayer = new AliDecayerPythia();
decayer->SetForceDecay(kAll);
decayer->Init();
gMC->SetExternalDecayer(decayer);
//
//=======================================================================
// ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
gMC->SetProcess("DCAY",1);
gMC->SetProcess("PAIR",1);
gMC->SetProcess("COMP",1);
gMC->SetProcess("PHOT",1);
gMC->SetProcess("PFIS",0);
gMC->SetProcess("DRAY",0);
gMC->SetProcess("ANNI",1);
gMC->SetProcess("BREM",1);
gMC->SetProcess("MUNU",1);
gMC->SetProcess("CKOV",1);
gMC->SetProcess("HADR",1);
gMC->SetProcess("LOSS",2);
gMC->SetProcess("MULS",1);
gMC->SetProcess("RAYL",1);
Float_t cut = 1.e-3; // 1MeV cut by default
Float_t tofmax = 1.e10;
gMC->SetCut("CUTGAM", cut);
gMC->SetCut("CUTELE", cut);
gMC->SetCut("CUTNEU", cut);
gMC->SetCut("CUTHAD", cut);
gMC->SetCut("CUTMUO", cut);
gMC->SetCut("BCUTE", cut);
gMC->SetCut("BCUTM", cut);
gMC->SetCut("DCUTE", cut);
gMC->SetCut("DCUTM", cut);
gMC->SetCut("PPCUTM", cut);
gMC->SetCut("TOFMAX", tofmax);
//
//=======================================================================
// ************* STEERING parameters FOR ALICE SIMULATION **************
// Chamber positions
// From AliMUONConstants class we get :
// Position Z (along beam) of the chambers (in cm)
// (from AliMUONConstants class):
// 533.5, 546.5, 678.5, 693.5, 964.0, 986.0, 1251.5, 1278.5,
// 1416.5, 1443.5, 1610, 1625., 1710., 1725.
// Internal Radius (in cm)
// 36.4, 46.2, 66.0, 80., 80., 100., 100.
// External Radius (in cm)
// 183., 245., 395., 560., 563., 850., 900.
//=======================================================================
if (!strcmp(option,"box")) {
AliGenBox * gener = new AliGenBox(1);
gener->SetMomentumRange(20.,20.1);
gener->SetPhiRange(0., 360.);
gener->SetThetaRange(171.000,178.001);
gener->SetPart(13); // Muons
gener->SetOrigin(0.,0., 0.); //vertex position
gener->SetSigma(0.0, 0.0, 0.0); //Sigma in (X,Y,Z) (cm) on IP position
}
if (!strcmp(option,"gun")) {
//*********************************************
// Example for Fixed Particle Gun *
//*********************************************
AliGenFixed *gener = new AliGenFixed(ntracks);
gener->SetMomentum(10);
gener->SetPhiRange(0.);
gener->SetThetaRange(0.);
gener->SetOrigin(30,30,1200);//vertex position
gener->SetPart(13); //GEANT particle type 13 is muons
}
if (!strcmp(option,"scan")) {
AliGenScan *gener = new AliGenScan(-1);
gener->SetMomentumRange(10,10);
gener->SetPhiRange(0, 0);
gener->SetThetaRange(-180, -180);
//vertex position
//gener->SetSigma(1,1,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetPart(kRootino);
gener->SetRange(100, -300., 300., 100, -300., 300., 1, 2000, 2000);
}
if (!strcmp(option,"param")) {
//*******************************************************
// Example for J/psi or Upsilon Production from Parameterisation *
//*******************************************************
AliGenParam *gener = new AliGenParam(1, AliGenMUONlib::kUpsilon);
gener->SetMomentumRange(0,999);
gener->SetPtRange(0,100.);
gener->SetPhiRange(0., 360.);
gener->SetCutOnChild(1);
gener->SetChildPhiRange(0.,360.);
gener->SetChildThetaRange(171.0,178.0);
gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetForceDecay(kDiMuon);
gener->SetTrackingFlag(1);
gener->Init();
}
//=============================================================
// Field (L3 0.4 T)
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k4kG);
gAlice->SetField(field);
//=================== Alice BODY parameters =============================
AliBODY *BODY = new AliBODY("BODY","Alice envelop");
//=================== ABSO parameters ============================
AliABSO *ABSO = new AliABSOv0("ABSO", "Muon Absorber");
//=================== DIPO parameters ============================
AliDIPO *DIPO = new AliDIPOv2("DIPO", "Dipole version 2");
//================== HALL parameters ============================
AliHALL *HALL = new AliHALL("HALL", "Alice Hall");
//=================== PIPE parameters ============================
AliPIPE *PIPE = new AliPIPEv0("PIPE", "Beam Pipe");
//=================== SHIL parameters ============================
AliSHIL *SHIL = new AliSHILv2("SHIL", "Shielding Version 2");
//=================== MUON Subsystem ===========================
cout << ">>> Config.C: Creating AliMUONv1 ..."<<endl;
// New MUONv1 version (geometry defined via builders)
AliMUON *MUON = new AliMUONv1("MUON", "default");
//AliMUON *MUON = new AliMUONv1("MUON", "FactoryV3"); // New segmentation slats
//AliMUON *MUON = new AliMUONv1("MUON", "FactoryV4"); // New segmentation trigger
// If align = true, the detection elements transformations
// are taken from the input files and not from the code
//MUON->SetAlign(true);
MUON->AddGeometryBuilder(new AliMUONSt1GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSt2GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSlatGeometryBuilder(MUON));
MUON->AddGeometryBuilder(new AliMUONTriggerGeometryBuilder(MUON));
}
Float_t EtaToTheta(Float_t arg){
return (180./TMath::Pi())*2.*atan(exp(-arg));
}
<|endoftext|>
|
<commit_before>// Config file test for MUON spectormeter
// Remember to define the directory and option
// gAlice->SetConfigFunction("Config('$HOME','box');");
void Config(char directory[100]="", char option[6]="param")
{
//
// Config file for MUON test
//
//=====================================================================
// Libraries required by geant321
gSystem->Load("libgeant321.so");
new TGeant3TGeo("C++ Interface to Geant3");
//=======================================================================
// Create the output file
Text_t filename[100];
sprintf(filename,"%sgalice.root",directory);
cout << ">>> Output file is " << filename << endl;
cout << ">>> Config.C: Creating Run Loader ..."<<endl;
AliRunLoader* rl=0x0;
rl = AliRunLoader::Open(
filename, AliConfig::GetDefaultEventFolderName(), "recreate");
if (rl == 0x0) {
gAlice->Fatal("Config.C","Can not instatiate the Run Loader");
return;
}
rl->SetCompressionLevel(2);
rl->SetNumberOfEventsPerFile(100);
gAlice->SetRunLoader(rl);
//AliLog::SetModuleDebugLevel("MUON", 1);
//=======================================================================
// Set External decayer
TVirtualMCDecayer *decayer = new AliDecayerPythia();
decayer->SetForceDecay(kAll);
decayer->Init();
gMC->SetExternalDecayer(decayer);
//
//=======================================================================
// ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
gMC->SetProcess("DCAY",1);
gMC->SetProcess("PAIR",1);
gMC->SetProcess("COMP",1);
gMC->SetProcess("PHOT",1);
gMC->SetProcess("PFIS",0);
gMC->SetProcess("DRAY",0);
gMC->SetProcess("ANNI",1);
gMC->SetProcess("BREM",1);
gMC->SetProcess("MUNU",1);
gMC->SetProcess("CKOV",1);
gMC->SetProcess("HADR",1);
gMC->SetProcess("LOSS",2);
gMC->SetProcess("MULS",1);
gMC->SetProcess("RAYL",1);
Float_t cut = 1.e-3; // 1MeV cut by default
Float_t tofmax = 1.e10;
gMC->SetCut("CUTGAM", cut);
gMC->SetCut("CUTELE", cut);
gMC->SetCut("CUTNEU", cut);
gMC->SetCut("CUTHAD", cut);
gMC->SetCut("CUTMUO", cut);
gMC->SetCut("BCUTE", cut);
gMC->SetCut("BCUTM", cut);
gMC->SetCut("DCUTE", cut);
gMC->SetCut("DCUTM", cut);
gMC->SetCut("PPCUTM", cut);
gMC->SetCut("TOFMAX", tofmax);
//
//=======================================================================
// ************* STEERING parameters FOR ALICE SIMULATION **************
// Chamber positions
// From AliMUONConstants class we get :
// Position Z (along beam) of the chambers (in cm)
// (from AliMUONConstants class):
// 533.5, 546.5, 678.5, 693.5, 964.0, 986.0, 1251.5, 1278.5,
// 1416.5, 1443.5, 1610, 1625., 1710., 1725.
// Internal Radius (in cm)
// 36.4, 46.2, 66.0, 80., 80., 100., 100.
// External Radius (in cm)
// 183., 245., 395., 560., 563., 850., 900.
//=======================================================================
if (!strcmp(option,"box")) {
AliGenBox * gener = new AliGenBox(1);
gener->SetMomentumRange(20.,20.1);
gener->SetPhiRange(0., 360.);
gener->SetThetaRange(171.000,178.001);
gener->SetPart(13); // Muons
gener->SetOrigin(0.,0., 0.); //vertex position
gener->SetSigma(0.0, 0.0, 0.0); //Sigma in (X,Y,Z) (cm) on IP position
}
if (!strcmp(option,"gun")) {
//*********************************************
// Example for Fixed Particle Gun *
//*********************************************
AliGenFixed *gener = new AliGenFixed(ntracks);
gener->SetMomentum(10);
gener->SetPhiRange(0.);
gener->SetThetaRange(0.);
gener->SetOrigin(30,30,1200);//vertex position
gener->SetPart(13); //GEANT particle type 13 is muons
}
if (!strcmp(option,"scan")) {
AliGenScan *gener = new AliGenScan(-1);
gener->SetMomentumRange(10,10);
gener->SetPhiRange(0, 0);
gener->SetThetaRange(-180, -180);
//vertex position
//gener->SetSigma(1,1,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetPart(kRootino);
gener->SetRange(100, -300., 300., 100, -300., 300., 1, 2000, 2000);
}
if (!strcmp(option,"param")) {
//*******************************************************
// Example for J/psi or Upsilon Production from Parameterisation *
//*******************************************************
AliGenParam *gener = new AliGenParam(1, AliGenMUONlib::kUpsilon);
gener->SetMomentumRange(0,999);
gener->SetPtRange(0,100.);
gener->SetPhiRange(0., 360.);
gener->SetCutOnChild(1);
gener->SetChildPhiRange(0.,360.);
gener->SetChildThetaRange(171.0,178.0);
gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetForceDecay(kDiMuon);
gener->SetTrackingFlag(1);
gener->Init();
}
//=============================================================
// Field (L3 0.4 T)
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k4kG);
gAlice->SetField(field);
//=================== Alice BODY parameters =============================
AliBODY *BODY = new AliBODY("BODY","Alice envelop");
//=================== ABSO parameters ============================
AliABSO *ABSO = new AliABSOv0("ABSO", "Muon Absorber");
//=================== DIPO parameters ============================
AliDIPO *DIPO = new AliDIPOv2("DIPO", "Dipole version 2");
//================== HALL parameters ============================
AliHALL *HALL = new AliHALL("HALL", "Alice Hall");
//=================== PIPE parameters ============================
AliPIPE *PIPE = new AliPIPEv0("PIPE", "Beam Pipe");
//=================== SHIL parameters ============================
AliSHIL *SHIL = new AliSHILv2("SHIL", "Shielding Version 2");
//=================== MUON Subsystem ===========================
cout << ">>> Config.C: Creating AliMUONv1 ..."<<endl;
// New MUONv1 version (geometry defined via builders)
//
//AliMUON *MUON = new AliMUONv1("MUON", "default");
//
AliMUON *MUON = new AliMUONv1("MUON", "FactoryV3"); // New segmentation slats
//
//AliMUON *MUON = new AliMUONv1("MUON", "FactoryV4"); // New segmentation trigger
//
//Version below to get digitizer making a decalibration.
//AliMUON *MUON = new AliMUONv1("MUON", "FactoryV4",
// "sdigitizer:AliMUONSDigitizerV2","digitizer:NewDigitizerOldTrigger");
// If SetAlign, the detection elements transformations
// are taken from the input file and not from the code
// MUON->SetAlign("transform.dat");
// To generate and read scaler trigger events in rawdata
// MUON->SetTriggerScalerEvent();
MUON->AddGeometryBuilder(new AliMUONSt1GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSt2GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSlatGeometryBuilder(MUON));
MUON->AddGeometryBuilder(new AliMUONTriggerGeometryBuilder(MUON));
}
Float_t EtaToTheta(Float_t arg){
return (180./TMath::Pi())*2.*atan(exp(-arg));
}
<commit_msg>Added a commented out version with new trigger code. (Rachid)<commit_after>// Config file test for MUON spectormeter
// Remember to define the directory and option
// gAlice->SetConfigFunction("Config('$HOME','box');");
void Config(char directory[100]="", char option[6]="param")
{
//
// Config file for MUON test
//
//=====================================================================
// Libraries required by geant321
gSystem->Load("libgeant321.so");
new TGeant3TGeo("C++ Interface to Geant3");
//=======================================================================
// Create the output file
Text_t filename[100];
sprintf(filename,"%sgalice.root",directory);
cout << ">>> Output file is " << filename << endl;
cout << ">>> Config.C: Creating Run Loader ..."<<endl;
AliRunLoader* rl=0x0;
rl = AliRunLoader::Open(
filename, AliConfig::GetDefaultEventFolderName(), "recreate");
if (rl == 0x0) {
gAlice->Fatal("Config.C","Can not instatiate the Run Loader");
return;
}
rl->SetCompressionLevel(2);
rl->SetNumberOfEventsPerFile(100);
gAlice->SetRunLoader(rl);
//AliLog::SetModuleDebugLevel("MUON", 1);
//=======================================================================
// Set External decayer
TVirtualMCDecayer *decayer = new AliDecayerPythia();
decayer->SetForceDecay(kAll);
decayer->Init();
gMC->SetExternalDecayer(decayer);
//
//=======================================================================
// ******* GEANT STEERING parameters FOR ALICE SIMULATION *******
gMC->SetProcess("DCAY",1);
gMC->SetProcess("PAIR",1);
gMC->SetProcess("COMP",1);
gMC->SetProcess("PHOT",1);
gMC->SetProcess("PFIS",0);
gMC->SetProcess("DRAY",0);
gMC->SetProcess("ANNI",1);
gMC->SetProcess("BREM",1);
gMC->SetProcess("MUNU",1);
gMC->SetProcess("CKOV",1);
gMC->SetProcess("HADR",1);
gMC->SetProcess("LOSS",2);
gMC->SetProcess("MULS",1);
gMC->SetProcess("RAYL",1);
Float_t cut = 1.e-3; // 1MeV cut by default
Float_t tofmax = 1.e10;
gMC->SetCut("CUTGAM", cut);
gMC->SetCut("CUTELE", cut);
gMC->SetCut("CUTNEU", cut);
gMC->SetCut("CUTHAD", cut);
gMC->SetCut("CUTMUO", cut);
gMC->SetCut("BCUTE", cut);
gMC->SetCut("BCUTM", cut);
gMC->SetCut("DCUTE", cut);
gMC->SetCut("DCUTM", cut);
gMC->SetCut("PPCUTM", cut);
gMC->SetCut("TOFMAX", tofmax);
//
//=======================================================================
// ************* STEERING parameters FOR ALICE SIMULATION **************
// Chamber positions
// From AliMUONConstants class we get :
// Position Z (along beam) of the chambers (in cm)
// (from AliMUONConstants class):
// 533.5, 546.5, 678.5, 693.5, 964.0, 986.0, 1251.5, 1278.5,
// 1416.5, 1443.5, 1610, 1625., 1710., 1725.
// Internal Radius (in cm)
// 36.4, 46.2, 66.0, 80., 80., 100., 100.
// External Radius (in cm)
// 183., 245., 395., 560., 563., 850., 900.
//=======================================================================
if (!strcmp(option,"box")) {
AliGenBox * gener = new AliGenBox(1);
gener->SetMomentumRange(20.,20.1);
gener->SetPhiRange(0., 360.);
gener->SetThetaRange(171.000,178.001);
gener->SetPart(13); // Muons
gener->SetOrigin(0.,0., 0.); //vertex position
gener->SetSigma(0.0, 0.0, 0.0); //Sigma in (X,Y,Z) (cm) on IP position
}
if (!strcmp(option,"gun")) {
//*********************************************
// Example for Fixed Particle Gun *
//*********************************************
AliGenFixed *gener = new AliGenFixed(ntracks);
gener->SetMomentum(10);
gener->SetPhiRange(0.);
gener->SetThetaRange(0.);
gener->SetOrigin(30,30,1200);//vertex position
gener->SetPart(13); //GEANT particle type 13 is muons
}
if (!strcmp(option,"scan")) {
AliGenScan *gener = new AliGenScan(-1);
gener->SetMomentumRange(10,10);
gener->SetPhiRange(0, 0);
gener->SetThetaRange(-180, -180);
//vertex position
//gener->SetSigma(1,1,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetPart(kRootino);
gener->SetRange(100, -300., 300., 100, -300., 300., 1, 2000, 2000);
}
if (!strcmp(option,"param")) {
//*******************************************************
// Example for J/psi or Upsilon Production from Parameterisation *
//*******************************************************
AliGenParam *gener = new AliGenParam(1, AliGenMUONlib::kUpsilon);
gener->SetMomentumRange(0,999);
gener->SetPtRange(0,100.);
gener->SetPhiRange(0., 360.);
gener->SetCutOnChild(1);
gener->SetChildPhiRange(0.,360.);
gener->SetChildThetaRange(171.0,178.0);
gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position
gener->SetForceDecay(kDiMuon);
gener->SetTrackingFlag(1);
gener->Init();
}
//=============================================================
// Field (L3 0.4 T)
AliMagFMaps* field = new AliMagFMaps("Maps","Maps", 1, 1., 10., AliMagFMaps::k4kG);
gAlice->SetField(field);
//=================== Alice BODY parameters =============================
AliBODY *BODY = new AliBODY("BODY","Alice envelop");
//=================== ABSO parameters ============================
AliABSO *ABSO = new AliABSOv0("ABSO", "Muon Absorber");
//=================== DIPO parameters ============================
AliDIPO *DIPO = new AliDIPOv2("DIPO", "Dipole version 2");
//================== HALL parameters ============================
AliHALL *HALL = new AliHALL("HALL", "Alice Hall");
//=================== PIPE parameters ============================
AliPIPE *PIPE = new AliPIPEv0("PIPE", "Beam Pipe");
//=================== SHIL parameters ============================
AliSHIL *SHIL = new AliSHILv2("SHIL", "Shielding Version 2");
//=================== MUON Subsystem ===========================
cout << ">>> Config.C: Creating AliMUONv1 ..."<<endl;
// New MUONv1 version (geometry defined via builders)
//
//AliMUON *MUON = new AliMUONv1("MUON", "default");
//
AliMUON *MUON = new AliMUONv1("MUON", "FactoryV3"); // New segmentation slats
//
//AliMUON *MUON = new AliMUONv1("MUON", "FactoryV4"); // New segmentation trigger
//
//Version below to get digitizer making a decalibration.
//The 4-th parameter should be put to digitizer:NewDigitizerNewTrigger
//to test latest and greatest trigger code (from Rachid) as well.
//
//AliMUON *MUON = new AliMUONv1("MUON", "FactoryV4",
// "sdigitizer:AliMUONSDigitizerV2",
// "digitizer:NewDigitizerOldTrigger");
//AliMUON *MUON = new AliMUONv1("MUON", "FactoryV4",
// "sdigitizer:AliMUONSDigitizerV2",
// "digitizer:NewDigitizerNewTrigger");
// If SetAlign, the detection elements transformations
// are taken from the input file and not from the code
// MUON->SetAlign("transform.dat");
// To generate and read scaler trigger events in rawdata
// MUON->SetTriggerScalerEvent();
MUON->AddGeometryBuilder(new AliMUONSt1GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSt2GeometryBuilderV2(MUON));
MUON->AddGeometryBuilder(new AliMUONSlatGeometryBuilder(MUON));
MUON->AddGeometryBuilder(new AliMUONTriggerGeometryBuilder(MUON));
}
Float_t EtaToTheta(Float_t arg){
return (180./TMath::Pi())*2.*atan(exp(-arg));
}
<|endoftext|>
|
<commit_before>/*
* Copyright © 2011 Stéphane Raimbault <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* This library implements the Modbus protocol.
* http://libmodbus.org/
*
*/
#include <inttypes.h>
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#include <pins_arduino.h>
#endif
#include "Modbusino.h"
#define _MODBUS_RTU_SLAVE 0
#define _MODBUS_RTU_FUNCTION 1
#define _MODBUS_RTU_PRESET_REQ_LENGTH 6
#define _MODBUS_RTU_PRESET_RSP_LENGTH 2
#define _MODBUS_RTU_CHECKSUM_LENGTH 2
#define _MODBUSINO_RTU_MAX_ADU_LENGTH 128
/* Supported function codes */
#define _FC_READ_HOLDING_REGISTERS 0x03
#define _FC_WRITE_MULTIPLE_REGISTERS 0x10
enum {
_STEP_FUNCTION = 0x01,
_STEP_META,
_STEP_DATA
};
static uint16_t crc16(uint8_t *req, uint8_t req_length)
{
uint8_t j;
uint16_t crc;
crc = 0xFFFF;
while (req_length--) {
crc = crc ^ *req++;
for (j=0; j < 8; j++) {
if (crc & 0x0001)
crc = (crc >> 1) ^ 0xA001;
else
crc = crc >> 1;
}
}
return (crc << 8 | crc >> 8);
}
ModbusinoSlave::ModbusinoSlave(uint8_t slave) {
if (slave >= 0 & slave <= 247) {
_slave = slave;
}
}
void ModbusinoSlave::setup(long baud) {
Serial.begin(baud);
}
static int check_integrity(uint8_t *msg, uint8_t msg_length)
{
uint16_t crc_calculated;
uint16_t crc_received;
if (msg_length < 2)
return -1;
crc_calculated = crc16(msg, msg_length - 2);
crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];
/* Check CRC of msg */
if (crc_calculated == crc_received) {
return msg_length;
} else {
return -1;
}
}
static int build_response_basis(uint8_t slave, uint8_t function,
uint8_t* rsp)
{
rsp[0] = slave;
rsp[1] = function;
return _MODBUS_RTU_PRESET_RSP_LENGTH;
}
static void send_msg(uint8_t *msg, uint8_t msg_length)
{
uint16_t crc = crc16(msg, msg_length);
msg[msg_length++] = crc >> 8;
msg[msg_length++] = crc & 0x00FF;
Serial.write(msg, msg_length);
}
static uint8_t response_exception(uint8_t slave, uint8_t function,
uint8_t exception_code,
uint8_t *rsp)
{
uint8_t rsp_length;
rsp_length = build_response_basis(slave, function + 0x80, rsp);
/* Positive exception code */
rsp[rsp_length++] = exception_code;
return rsp_length;
}
static void flush(void)
{
uint8_t i = 0;
/* Wait a moment to receive the remaining garbage but avoid getting stuck
* because the line is saturated */
while (Serial.available() && i++ < 10) {
Serial.flush();
delay(3);
}
}
static int receive(uint8_t *req, uint8_t _slave)
{
uint8_t i;
uint8_t length_to_read;
uint8_t req_index;
uint8_t step;
uint8_t function;
/* We need to analyse the message step by step. At the first step, we want
* to reach the function code because all packets contain this
* information. */
step = _STEP_FUNCTION;
length_to_read = _MODBUS_RTU_FUNCTION + 1;
req_index = 0;
while (length_to_read != 0) {
/* The timeout is defined to ~10 ms between each bytes. Precision is
not that important so I rather to avoid millis() to apply the KISS
principle (millis overflows after 50 days, etc) */
if (!Serial.available()) {
i = 0;
while (!Serial.available()) {
delay(1);
if (++i == 10) {
/* Too late, bye */
return -1;
}
}
}
req[req_index] = Serial.read();
/* Moves the pointer to receive other data */
req_index++;
/* Computes remaining bytes */
length_to_read--;
if (length_to_read == 0) {
switch (step) {
case _STEP_FUNCTION:
/* Function code position */
function = req[_MODBUS_RTU_FUNCTION];
if (function == _FC_READ_HOLDING_REGISTERS) {
length_to_read = 4;
} else if (function == _FC_WRITE_MULTIPLE_REGISTERS) {
length_to_read = 5;
} else {
/* Wait a moment to receive the remaining garbage */
flush();
if (req[_MODBUS_RTU_SLAVE] == _slave ||
req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) {
/* It's for me so send an exception (reuse req) */
uint8_t rsp_length = response_exception(
_slave, function,
MODBUS_EXCEPTION_ILLEGAL_FUNCTION,
req);
send_msg(req, rsp_length);
return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;
}
return -1;
}
step = _STEP_META;
break;
case _STEP_META:
length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH;
if (function == _FC_WRITE_MULTIPLE_REGISTERS)
length_to_read += req[_MODBUS_RTU_FUNCTION + 5];
if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) {
flush();
if (req[_MODBUS_RTU_SLAVE] == _slave ||
req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) {
/* It's for me so send an exception (reuse req) */
uint8_t rsp_length = response_exception(
_slave, function,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
req);
send_msg(req, rsp_length);
return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;
}
return -1;
}
step = _STEP_DATA;
break;
default:
break;
}
}
}
return check_integrity(req, req_index);
}
static void reply(uint16_t *tab_reg, uint16_t nb_reg,
uint8_t *req, uint8_t req_length, uint8_t _slave)
{
uint8_t slave = req[_MODBUS_RTU_SLAVE];
uint8_t function = req[_MODBUS_RTU_FUNCTION];
uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) +
req[_MODBUS_RTU_FUNCTION + 2];
uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) +
req[_MODBUS_RTU_FUNCTION + 4];
uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH];
uint8_t rsp_length = 0;
if (slave != _slave &&
slave != MODBUS_BROADCAST_ADDRESS) {
return;
}
if (address + nb > nb_reg) {
rsp_length = response_exception(
slave, function,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
} else {
req_length -= _MODBUS_RTU_CHECKSUM_LENGTH;
if (function == _FC_READ_HOLDING_REGISTERS) {
uint16_t i; //needs to be 16-bit
rsp_length = build_response_basis(slave, function, rsp);
rsp[rsp_length++] = nb << 1;
for (i = address; i < address + nb; i++) {
rsp[rsp_length++] = tab_reg[i] >> 8;
rsp[rsp_length++] = tab_reg[i] & 0xFF;
}
} else {
int i, j;
for (i = address, j = 6; i < address + nb; i++, j += 2) {
/* 6 and 7 = first value */
tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) +
req[_MODBUS_RTU_FUNCTION + j + 1];
}
rsp_length = build_response_basis(slave, function, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
send_msg(rsp, rsp_length);
}
int ModbusinoSlave::loop(uint16_t* tab_reg, uint16_t nb_reg)
{
int rc = 0;
uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH];
if (Serial.available()) {
rc = receive(req, _slave);
if (rc > 0) {
reply(tab_reg, nb_reg, req, rc, _slave);
}
}
/* Returns a positive value if successful,
0 if a slave filtering has occured,
-1 if an undefined error has occured,
-2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION
etc */
return rc;
}
<commit_msg>Reindent code after new else introduced by previous commit<commit_after>/*
* Copyright © 2011 Stéphane Raimbault <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* This library implements the Modbus protocol.
* http://libmodbus.org/
*
*/
#include <inttypes.h>
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#include <pins_arduino.h>
#endif
#include "Modbusino.h"
#define _MODBUS_RTU_SLAVE 0
#define _MODBUS_RTU_FUNCTION 1
#define _MODBUS_RTU_PRESET_REQ_LENGTH 6
#define _MODBUS_RTU_PRESET_RSP_LENGTH 2
#define _MODBUS_RTU_CHECKSUM_LENGTH 2
#define _MODBUSINO_RTU_MAX_ADU_LENGTH 128
/* Supported function codes */
#define _FC_READ_HOLDING_REGISTERS 0x03
#define _FC_WRITE_MULTIPLE_REGISTERS 0x10
enum {
_STEP_FUNCTION = 0x01,
_STEP_META,
_STEP_DATA
};
static uint16_t crc16(uint8_t *req, uint8_t req_length)
{
uint8_t j;
uint16_t crc;
crc = 0xFFFF;
while (req_length--) {
crc = crc ^ *req++;
for (j=0; j < 8; j++) {
if (crc & 0x0001)
crc = (crc >> 1) ^ 0xA001;
else
crc = crc >> 1;
}
}
return (crc << 8 | crc >> 8);
}
ModbusinoSlave::ModbusinoSlave(uint8_t slave) {
if (slave >= 0 & slave <= 247) {
_slave = slave;
}
}
void ModbusinoSlave::setup(long baud) {
Serial.begin(baud);
}
static int check_integrity(uint8_t *msg, uint8_t msg_length)
{
uint16_t crc_calculated;
uint16_t crc_received;
if (msg_length < 2)
return -1;
crc_calculated = crc16(msg, msg_length - 2);
crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1];
/* Check CRC of msg */
if (crc_calculated == crc_received) {
return msg_length;
} else {
return -1;
}
}
static int build_response_basis(uint8_t slave, uint8_t function,
uint8_t* rsp)
{
rsp[0] = slave;
rsp[1] = function;
return _MODBUS_RTU_PRESET_RSP_LENGTH;
}
static void send_msg(uint8_t *msg, uint8_t msg_length)
{
uint16_t crc = crc16(msg, msg_length);
msg[msg_length++] = crc >> 8;
msg[msg_length++] = crc & 0x00FF;
Serial.write(msg, msg_length);
}
static uint8_t response_exception(uint8_t slave, uint8_t function,
uint8_t exception_code,
uint8_t *rsp)
{
uint8_t rsp_length;
rsp_length = build_response_basis(slave, function + 0x80, rsp);
/* Positive exception code */
rsp[rsp_length++] = exception_code;
return rsp_length;
}
static void flush(void)
{
uint8_t i = 0;
/* Wait a moment to receive the remaining garbage but avoid getting stuck
* because the line is saturated */
while (Serial.available() && i++ < 10) {
Serial.flush();
delay(3);
}
}
static int receive(uint8_t *req, uint8_t _slave)
{
uint8_t i;
uint8_t length_to_read;
uint8_t req_index;
uint8_t step;
uint8_t function;
/* We need to analyse the message step by step. At the first step, we want
* to reach the function code because all packets contain this
* information. */
step = _STEP_FUNCTION;
length_to_read = _MODBUS_RTU_FUNCTION + 1;
req_index = 0;
while (length_to_read != 0) {
/* The timeout is defined to ~10 ms between each bytes. Precision is
not that important so I rather to avoid millis() to apply the KISS
principle (millis overflows after 50 days, etc) */
if (!Serial.available()) {
i = 0;
while (!Serial.available()) {
delay(1);
if (++i == 10) {
/* Too late, bye */
return -1;
}
}
}
req[req_index] = Serial.read();
/* Moves the pointer to receive other data */
req_index++;
/* Computes remaining bytes */
length_to_read--;
if (length_to_read == 0) {
switch (step) {
case _STEP_FUNCTION:
/* Function code position */
function = req[_MODBUS_RTU_FUNCTION];
if (function == _FC_READ_HOLDING_REGISTERS) {
length_to_read = 4;
} else if (function == _FC_WRITE_MULTIPLE_REGISTERS) {
length_to_read = 5;
} else {
/* Wait a moment to receive the remaining garbage */
flush();
if (req[_MODBUS_RTU_SLAVE] == _slave ||
req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) {
/* It's for me so send an exception (reuse req) */
uint8_t rsp_length = response_exception(
_slave, function,
MODBUS_EXCEPTION_ILLEGAL_FUNCTION,
req);
send_msg(req, rsp_length);
return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;
}
return -1;
}
step = _STEP_META;
break;
case _STEP_META:
length_to_read = _MODBUS_RTU_CHECKSUM_LENGTH;
if (function == _FC_WRITE_MULTIPLE_REGISTERS)
length_to_read += req[_MODBUS_RTU_FUNCTION + 5];
if ((req_index + length_to_read) > _MODBUSINO_RTU_MAX_ADU_LENGTH) {
flush();
if (req[_MODBUS_RTU_SLAVE] == _slave ||
req[_MODBUS_RTU_SLAVE] == MODBUS_BROADCAST_ADDRESS) {
/* It's for me so send an exception (reuse req) */
uint8_t rsp_length = response_exception(
_slave, function,
MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE,
req);
send_msg(req, rsp_length);
return - 1 - MODBUS_EXCEPTION_ILLEGAL_FUNCTION;
}
return -1;
}
step = _STEP_DATA;
break;
default:
break;
}
}
}
return check_integrity(req, req_index);
}
static void reply(uint16_t *tab_reg, uint16_t nb_reg,
uint8_t *req, uint8_t req_length, uint8_t _slave)
{
uint8_t slave = req[_MODBUS_RTU_SLAVE];
uint8_t function = req[_MODBUS_RTU_FUNCTION];
uint16_t address = (req[_MODBUS_RTU_FUNCTION + 1] << 8) +
req[_MODBUS_RTU_FUNCTION + 2];
uint16_t nb = (req[_MODBUS_RTU_FUNCTION + 3] << 8) +
req[_MODBUS_RTU_FUNCTION + 4];
uint8_t rsp[_MODBUSINO_RTU_MAX_ADU_LENGTH];
uint8_t rsp_length = 0;
if (slave != _slave &&
slave != MODBUS_BROADCAST_ADDRESS) {
return;
}
if (address + nb > nb_reg) {
rsp_length = response_exception(
slave, function,
MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp);
} else {
req_length -= _MODBUS_RTU_CHECKSUM_LENGTH;
if (function == _FC_READ_HOLDING_REGISTERS) {
uint16_t i; //needs to be 16-bit
rsp_length = build_response_basis(slave, function, rsp);
rsp[rsp_length++] = nb << 1;
for (i = address; i < address + nb; i++) {
rsp[rsp_length++] = tab_reg[i] >> 8;
rsp[rsp_length++] = tab_reg[i] & 0xFF;
}
} else {
int i, j;
for (i = address, j = 6; i < address + nb; i++, j += 2) {
/* 6 and 7 = first value */
tab_reg[i] = (req[_MODBUS_RTU_FUNCTION + j] << 8) +
req[_MODBUS_RTU_FUNCTION + j + 1];
}
rsp_length = build_response_basis(slave, function, rsp);
/* 4 to copy the address (2) and the no. of registers */
memcpy(rsp + rsp_length, req + rsp_length, 4);
rsp_length += 4;
}
}
send_msg(rsp, rsp_length);
}
int ModbusinoSlave::loop(uint16_t* tab_reg, uint16_t nb_reg)
{
int rc = 0;
uint8_t req[_MODBUSINO_RTU_MAX_ADU_LENGTH];
if (Serial.available()) {
rc = receive(req, _slave);
if (rc > 0) {
reply(tab_reg, nb_reg, req, rc, _slave);
}
}
/* Returns a positive value if successful,
0 if a slave filtering has occured,
-1 if an undefined error has occured,
-2 for MODBUS_EXCEPTION_ILLEGAL_FUNCTION
etc */
return rc;
}
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* quick_open.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 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 "quick_open.h"
#include "core/os/keyboard.h"
void EditorQuickOpen::popup_dialog(const StringName &p_base, bool p_enable_multi, bool p_add_dirs, bool p_dontclear) {
add_directories = p_add_dirs;
popup_centered_ratio(0.6);
if (p_dontclear)
search_box->select_all();
else
search_box->clear();
if (p_enable_multi)
search_options->set_select_mode(Tree::SELECT_MULTI);
else
search_options->set_select_mode(Tree::SELECT_SINGLE);
search_box->grab_focus();
base_type = p_base;
_update_search();
}
String EditorQuickOpen::get_selected() const {
TreeItem *ti = search_options->get_selected();
if (!ti)
return String();
return "res://" + ti->get_text(0);
}
Vector<String> EditorQuickOpen::get_selected_files() const {
Vector<String> files;
TreeItem *item = search_options->get_next_selected(search_options->get_root());
while (item) {
files.push_back("res://" + item->get_text(0));
item = search_options->get_next_selected(item);
}
return files;
}
void EditorQuickOpen::_text_changed(const String &p_newtext) {
_update_search();
}
void EditorQuickOpen::_sbox_input(const Ref<InputEvent> &p_ie) {
Ref<InputEventKey> k = p_ie;
if (k.is_valid()) {
switch (k->get_keycode()) {
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
case KEY_PAGEDOWN: {
search_options->call("_gui_input", k);
search_box->accept_event();
TreeItem *root = search_options->get_root();
if (!root->get_children())
break;
TreeItem *current = search_options->get_selected();
TreeItem *item = search_options->get_next_selected(root);
while (item) {
item->deselect(0);
item = search_options->get_next_selected(item);
}
current->select(0);
} break;
}
}
}
float EditorQuickOpen::_path_cmp(String search, String path) const {
if (search == path) {
return 1.2f;
}
if (path.findn(search) != -1) {
return 1.1f;
}
return path.to_lower().similarity(search.to_lower());
}
void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector<Pair<String, Ref<Texture2D>>> &list) {
if (!add_directories) {
for (int i = 0; i < efsd->get_subdir_count(); i++) {
_parse_fs(efsd->get_subdir(i), list);
}
}
String search_text = search_box->get_text();
if (add_directories) {
String path = efsd->get_path();
if (!path.ends_with("/"))
path += "/";
if (path != "res://") {
path = path.substr(6, path.length());
if (search_text.is_subsequence_ofi(path)) {
Pair<String, Ref<Texture2D>> pair;
pair.first = path;
pair.second = search_options->get_theme_icon("folder", "FileDialog");
if (search_text != String() && list.size() > 0) {
float this_sim = _path_cmp(search_text, path);
float other_sim = _path_cmp(list[0].first, path);
int pos = 1;
while (pos < list.size() && this_sim <= other_sim) {
other_sim = _path_cmp(list[pos++].first, path);
}
pos = this_sim >= other_sim ? pos - 1 : pos;
list.insert(pos, pair);
} else {
list.push_back(pair);
}
}
}
}
for (int i = 0; i < efsd->get_file_count(); i++) {
String file = efsd->get_file_path(i);
file = file.substr(6, file.length());
if (ClassDB::is_parent_class(efsd->get_file_type(i), base_type) && (search_text.is_subsequence_ofi(file))) {
Pair<String, Ref<Texture2D>> pair;
pair.first = file;
pair.second = search_options->get_theme_icon((search_options->has_theme_icon(efsd->get_file_type(i), ei) ? efsd->get_file_type(i) : ot), ei);
list.push_back(pair);
}
}
if (add_directories) {
for (int i = 0; i < efsd->get_subdir_count(); i++) {
_parse_fs(efsd->get_subdir(i), list);
}
}
}
Vector<Pair<String, Ref<Texture2D>>> EditorQuickOpen::_sort_fs(Vector<Pair<String, Ref<Texture2D>>> &list) {
String search_text = search_box->get_text();
Vector<Pair<String, Ref<Texture2D>>> sorted_list;
if (search_text == String() || list.size() == 0)
return list;
Vector<float> scores;
scores.resize(list.size());
for (int i = 0; i < list.size(); i++)
scores.write[i] = _path_cmp(search_text, list[i].first);
while (list.size() > 0) {
float best_score = 0.0f;
int best_idx = 0;
for (int i = 0; i < list.size(); i++) {
float current_score = scores[i];
if (current_score > best_score) {
best_score = current_score;
best_idx = i;
}
}
sorted_list.push_back(list[best_idx]);
list.remove(best_idx);
scores.remove(best_idx);
}
return sorted_list;
}
void EditorQuickOpen::_update_search() {
search_options->clear();
TreeItem *root = search_options->create_item();
EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem();
Vector<Pair<String, Ref<Texture2D>>> list;
_parse_fs(efsd, list);
list = _sort_fs(list);
for (int i = 0; i < list.size(); i++) {
TreeItem *ti = search_options->create_item(root);
ti->set_text(0, list[i].first);
ti->set_icon(0, list[i].second);
}
if (root->get_children()) {
TreeItem *ti = root->get_children();
ti->select(0);
ti->set_as_cursor(0);
}
get_ok()->set_disabled(root->get_children() == nullptr);
}
void EditorQuickOpen::_confirmed() {
TreeItem *ti = search_options->get_selected();
if (!ti)
return;
emit_signal("quick_open");
hide();
}
void EditorQuickOpen::_theme_changed() {
search_box->set_right_icon(search_options->get_theme_icon("Search", "EditorIcons"));
}
void EditorQuickOpen::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
connect("confirmed", callable_mp(this, &EditorQuickOpen::_confirmed));
search_box->set_clear_button_enabled(true);
[[fallthrough]];
}
case NOTIFICATION_EXIT_TREE: {
disconnect("confirmed", callable_mp(this, &EditorQuickOpen::_confirmed));
} break;
}
}
StringName EditorQuickOpen::get_base_type() const {
return base_type;
}
void EditorQuickOpen::_bind_methods() {
ADD_SIGNAL(MethodInfo("quick_open"));
}
EditorQuickOpen::EditorQuickOpen() {
VBoxContainer *vbc = memnew(VBoxContainer);
vbc->connect("theme_changed", callable_mp(this, &EditorQuickOpen::_theme_changed));
add_child(vbc);
search_box = memnew(LineEdit);
vbc->add_margin_child(TTR("Search:"), search_box);
search_box->connect("text_changed", callable_mp(this, &EditorQuickOpen::_text_changed));
search_box->connect("gui_input", callable_mp(this, &EditorQuickOpen::_sbox_input));
search_options = memnew(Tree);
vbc->add_margin_child(TTR("Matches:"), search_options, true);
get_ok()->set_text(TTR("Open"));
get_ok()->set_disabled(true);
register_text_enter(search_box);
set_hide_on_ok(false);
search_options->connect("item_activated", callable_mp(this, &EditorQuickOpen::_confirmed));
search_options->set_hide_root(true);
search_options->set_hide_folding(true);
search_options->add_theme_constant_override("draw_guides", 1);
ei = "EditorIcons";
ot = "Object";
add_directories = false;
}
<commit_msg>Fix signal disconnection soon after connection in EditorQuickOpen<commit_after>/*************************************************************************/
/* quick_open.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 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 "quick_open.h"
#include "core/os/keyboard.h"
void EditorQuickOpen::popup_dialog(const StringName &p_base, bool p_enable_multi, bool p_add_dirs, bool p_dontclear) {
add_directories = p_add_dirs;
popup_centered_ratio(0.6);
if (p_dontclear)
search_box->select_all();
else
search_box->clear();
if (p_enable_multi)
search_options->set_select_mode(Tree::SELECT_MULTI);
else
search_options->set_select_mode(Tree::SELECT_SINGLE);
search_box->grab_focus();
base_type = p_base;
_update_search();
}
String EditorQuickOpen::get_selected() const {
TreeItem *ti = search_options->get_selected();
if (!ti)
return String();
return "res://" + ti->get_text(0);
}
Vector<String> EditorQuickOpen::get_selected_files() const {
Vector<String> files;
TreeItem *item = search_options->get_next_selected(search_options->get_root());
while (item) {
files.push_back("res://" + item->get_text(0));
item = search_options->get_next_selected(item);
}
return files;
}
void EditorQuickOpen::_text_changed(const String &p_newtext) {
_update_search();
}
void EditorQuickOpen::_sbox_input(const Ref<InputEvent> &p_ie) {
Ref<InputEventKey> k = p_ie;
if (k.is_valid()) {
switch (k->get_keycode()) {
case KEY_UP:
case KEY_DOWN:
case KEY_PAGEUP:
case KEY_PAGEDOWN: {
search_options->call("_gui_input", k);
search_box->accept_event();
TreeItem *root = search_options->get_root();
if (!root->get_children())
break;
TreeItem *current = search_options->get_selected();
TreeItem *item = search_options->get_next_selected(root);
while (item) {
item->deselect(0);
item = search_options->get_next_selected(item);
}
current->select(0);
} break;
}
}
}
float EditorQuickOpen::_path_cmp(String search, String path) const {
if (search == path) {
return 1.2f;
}
if (path.findn(search) != -1) {
return 1.1f;
}
return path.to_lower().similarity(search.to_lower());
}
void EditorQuickOpen::_parse_fs(EditorFileSystemDirectory *efsd, Vector<Pair<String, Ref<Texture2D>>> &list) {
if (!add_directories) {
for (int i = 0; i < efsd->get_subdir_count(); i++) {
_parse_fs(efsd->get_subdir(i), list);
}
}
String search_text = search_box->get_text();
if (add_directories) {
String path = efsd->get_path();
if (!path.ends_with("/"))
path += "/";
if (path != "res://") {
path = path.substr(6, path.length());
if (search_text.is_subsequence_ofi(path)) {
Pair<String, Ref<Texture2D>> pair;
pair.first = path;
pair.second = search_options->get_theme_icon("folder", "FileDialog");
if (search_text != String() && list.size() > 0) {
float this_sim = _path_cmp(search_text, path);
float other_sim = _path_cmp(list[0].first, path);
int pos = 1;
while (pos < list.size() && this_sim <= other_sim) {
other_sim = _path_cmp(list[pos++].first, path);
}
pos = this_sim >= other_sim ? pos - 1 : pos;
list.insert(pos, pair);
} else {
list.push_back(pair);
}
}
}
}
for (int i = 0; i < efsd->get_file_count(); i++) {
String file = efsd->get_file_path(i);
file = file.substr(6, file.length());
if (ClassDB::is_parent_class(efsd->get_file_type(i), base_type) && (search_text.is_subsequence_ofi(file))) {
Pair<String, Ref<Texture2D>> pair;
pair.first = file;
pair.second = search_options->get_theme_icon((search_options->has_theme_icon(efsd->get_file_type(i), ei) ? efsd->get_file_type(i) : ot), ei);
list.push_back(pair);
}
}
if (add_directories) {
for (int i = 0; i < efsd->get_subdir_count(); i++) {
_parse_fs(efsd->get_subdir(i), list);
}
}
}
Vector<Pair<String, Ref<Texture2D>>> EditorQuickOpen::_sort_fs(Vector<Pair<String, Ref<Texture2D>>> &list) {
String search_text = search_box->get_text();
Vector<Pair<String, Ref<Texture2D>>> sorted_list;
if (search_text == String() || list.size() == 0)
return list;
Vector<float> scores;
scores.resize(list.size());
for (int i = 0; i < list.size(); i++)
scores.write[i] = _path_cmp(search_text, list[i].first);
while (list.size() > 0) {
float best_score = 0.0f;
int best_idx = 0;
for (int i = 0; i < list.size(); i++) {
float current_score = scores[i];
if (current_score > best_score) {
best_score = current_score;
best_idx = i;
}
}
sorted_list.push_back(list[best_idx]);
list.remove(best_idx);
scores.remove(best_idx);
}
return sorted_list;
}
void EditorQuickOpen::_update_search() {
search_options->clear();
TreeItem *root = search_options->create_item();
EditorFileSystemDirectory *efsd = EditorFileSystem::get_singleton()->get_filesystem();
Vector<Pair<String, Ref<Texture2D>>> list;
_parse_fs(efsd, list);
list = _sort_fs(list);
for (int i = 0; i < list.size(); i++) {
TreeItem *ti = search_options->create_item(root);
ti->set_text(0, list[i].first);
ti->set_icon(0, list[i].second);
}
if (root->get_children()) {
TreeItem *ti = root->get_children();
ti->select(0);
ti->set_as_cursor(0);
}
get_ok()->set_disabled(root->get_children() == nullptr);
}
void EditorQuickOpen::_confirmed() {
TreeItem *ti = search_options->get_selected();
if (!ti)
return;
emit_signal("quick_open");
hide();
}
void EditorQuickOpen::_theme_changed() {
search_box->set_right_icon(search_options->get_theme_icon("Search", "EditorIcons"));
}
void EditorQuickOpen::_notification(int p_what) {
switch (p_what) {
case NOTIFICATION_ENTER_TREE: {
connect("confirmed", callable_mp(this, &EditorQuickOpen::_confirmed));
search_box->set_clear_button_enabled(true);
} break;
case NOTIFICATION_EXIT_TREE: {
disconnect("confirmed", callable_mp(this, &EditorQuickOpen::_confirmed));
} break;
}
}
StringName EditorQuickOpen::get_base_type() const {
return base_type;
}
void EditorQuickOpen::_bind_methods() {
ADD_SIGNAL(MethodInfo("quick_open"));
}
EditorQuickOpen::EditorQuickOpen() {
VBoxContainer *vbc = memnew(VBoxContainer);
vbc->connect("theme_changed", callable_mp(this, &EditorQuickOpen::_theme_changed));
add_child(vbc);
search_box = memnew(LineEdit);
vbc->add_margin_child(TTR("Search:"), search_box);
search_box->connect("text_changed", callable_mp(this, &EditorQuickOpen::_text_changed));
search_box->connect("gui_input", callable_mp(this, &EditorQuickOpen::_sbox_input));
search_options = memnew(Tree);
vbc->add_margin_child(TTR("Matches:"), search_options, true);
get_ok()->set_text(TTR("Open"));
get_ok()->set_disabled(true);
register_text_enter(search_box);
set_hide_on_ok(false);
search_options->connect("item_activated", callable_mp(this, &EditorQuickOpen::_confirmed));
search_options->set_hide_root(true);
search_options->set_hide_folding(true);
search_options->add_theme_constant_override("draw_guides", 1);
ei = "EditorIcons";
ot = "Object";
add_directories = false;
}
<|endoftext|>
|
<commit_before>#include "EM_Classes.h"
Model::Model(const int &N_, const int &lagsY_,
const bool &sigma_, const bool &beta_,
const bool &meanCorrected):
N(N_), lagsY(lagsY_), sigma(sigma_), beta(beta_),
meanCorrected(meanCorrected){
Nm = std::pow(N, lagsY + 1);
}
Data::Data(const MatrixXd & y,const MatrixXd & x):
Y(y){
if (y.rows() < y.cols())
Y.transposeInPlace();
T = Y.rows();
M = Y.cols(); // if M = 1, Univariate model
// T can't be different from x.rows()
if (x.rows() > x.cols()){
mX = x.cols();
X.setZero(T, mX+1);
X.col(0) = MatrixXd::Ones(T, 1);
X.rightCols(mX) = x;
} else {
mX = x.rows();
X.setZero(T, mX+1);
X.col(0) = MatrixXd::Ones(T, 1);
X.rightCols(mX) = x.transpose();
}
}
Data::Data(const MatrixXd & y):
Y(y){
if(y.cols() > y.rows())
Y.transposeInPlace();
T = Y.rows();
M = Y.cols();
X.setOnes(T, 1);
mX = 1;
}
<commit_msg>Add state dependence to exogenous variables<commit_after>#include "EM_Classes.h"
Model::Model(const int &N_, const int &lagsY_,
const bool &sigma_, const bool &betaY_,
const bool &betaX_, const bool &meanCorrected):
N(N_), lagsY(lagsY_), sigma(sigma_), betaY(betaY_),
betaX(betaX_), meanCorrected(meanCorrected){
Nm = (meanCorrected == true) ? std::pow(N, lagsY + 1):N;
}
Data::Data(const MatrixXd & y,const MatrixXd & x):
Y(y){
if (y.rows() < y.cols())
Y.transposeInPlace();
T = Y.rows();
M = Y.cols(); // if M = 1, Univariate model
// T can't be different from x.rows()
if (x.rows() > x.cols()){
k = x.cols();
X.setZero(T, k+1);
X.rightCols(k) = x;
} else {
k = x.rows();
X.setZero(T, k+1);
X.rightCols(k) = x.transpose();
}
}
Data::Data(const MatrixXd & y):
Y(y){
if(y.cols() > y.rows())
Y.transposeInPlace();
T = Y.rows();
M = Y.cols();
X.setOnes(T, 1);
k = 1;
}
void Data::embed(MatrixXd *Result, const MatrixXd &Y,
int m){
m+=1;
MatrixXd ytm(Y.rows()-m, Y.cols());
Result->resize(Y.rows()-m, Y.cols()*m);
for (int i = 0; i<m; i++){
ytm = Y.block(i, 0, Y.rows() - m, Y.cols());
Result->block(0, (m-1-i)*Y.cols(), Y.rows() - m, Y.cols()) = ytm;
}
}
<|endoftext|>
|
<commit_before>#include "NeuralNet.h"
//---------------------------------------------------------------Neuron---------------------------------------------------------------
Neuron::Neuron(unsigned numInputs)
{
for(unsigned i=0; i<numInputs+1; i++)
{
m_weights.push_back(randomValue());
}
}
double Neuron::randomValue()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dist(-1, 1);
return dist(gen);
}
double Neuron::operator* (const std::vector<double> & inputs)
{
double result = 0;
auto weight = m_weights.cbegin();
for(auto i = inputs.cbegin(); i != inputs.cend(); i++)
{
result += (*i) * (*weight);
weight++;
}
result += *weight;
result = sigmoid(result);
m_output = result;
return result;
}
double Neuron::sigmoid(double x) const
{
return 1.0 / (1.0 + std::exp(-x));
}
std::ostream& operator<< (std::ostream & out, const Neuron & neuron)
{
out << "[";
for(auto i = neuron.m_weights.cbegin(); i != neuron.m_weights.cend(); i++)
out << " " << *i;
out << " ]";
return out;
}
//----------------------------------------------------------------NeuralNet---------------------------------------------------------------
NeuralNet::NeuralNet(const std::vector<unsigned>& topology)
{
for(auto i = topology.cbegin()+1; i != topology.cend(); i++)
{
m_layers.push_back(Layer());
for(unsigned j=0; j < *i; j++)
{
m_layers.back().push_back(Neuron(*(i-1)));
}
}
}
std::vector<double> NeuralNet::propagate(const std::vector<double>& inputs)
{
if(inputs.size() != m_layers[0][0].m_weights.size()-1) throw std::invalid_argument("Wrong number of inputs!");
return *this * inputs;
}
std::vector<double> NeuralNet::operator* (const std::vector<double> & inputs)
{
std::vector<double> outputs = std::move(inputs);
std::vector<double> neuronOutput;
for(auto i = m_layers.begin(); i != m_layers.end(); i++)
{
for(auto j = (*i).begin(); j != (*i).end(); j++)
{
neuronOutput.push_back(*j * outputs);
}
outputs = std::move(neuronOutput);
}
return outputs;
}
void NeuralNet::backProp(const std::vector<TrainingExample> & examples, double tol, double alpha)
{
std::vector<double> Error;
do
{
Error.clear();
//calculate error for all examples
for(auto ex = examples.cbegin(); ex != examples.cend(); ex++)
{
std::vector<double> inputs = (*ex).m_inputs;
std::vector<double> outputs = propagate(inputs);
double error = 0;
auto target = (*ex).m_outputs.cbegin();
for(auto actual = outputs.cbegin(); actual != outputs.cend(); actual++)
{
error += 0.5 * std::pow((*target - *actual), 2);
target++;
}
Error.push_back(error);
//calculate deltas
std::vector<double> deltaWeight;
std::vector<double> delta;
target = (*ex).m_outputs.cbegin();
//for all layers
for(int layer = m_layers.size() - 1; layer >= 0; --layer)
{
double sum = std::accumulate(delta.cbegin(), delta.cend(), 0.0);
delta.clear();
//for all neurons in current layer
for(unsigned neuron = 0; neuron < m_layers[layer].size(); neuron++)
{
//for output layer
if(layer == (int)m_layers.size()-1)
{
double d = (m_layers[layer][neuron].m_output - *target) * m_layers[layer][neuron].m_output * (1 - m_layers[layer][neuron].m_output);
target++;
delta.push_back(d);
}
else //for hidden layer
{
double d = sum;
d *= m_layers[layer][neuron].m_output * m_layers[layer][neuron].m_output * (1 - m_layers[layer][neuron].m_output);
delta.push_back(d);
}
//for every weight in current neuron
unsigned n = m_layers[layer][neuron].m_weights.size();
for(unsigned weight = 0; weight < n; weight++)
{
if(layer > 0)//not first hidden
{
double w = delta.back() * (weight < n-1 ? m_layers[layer - 1][weight].m_output : 1);
deltaWeight.push_back(w);
}
else //first hidden
{
double w = delta.back() * (weight < n-1 ? (*ex).m_inputs[weight] : 1);
deltaWeight.push_back(w);
}
}
}
}
//update weight
auto iter = deltaWeight.cbegin();
for(int layer = m_layers.size() - 1; layer >= 0; layer--)
for(unsigned neuron = 0; neuron < m_layers[layer].size(); neuron++)
for(unsigned weight = 0; weight < m_layers[layer][neuron].m_weights.size(); weight++)
m_layers[layer][neuron].m_weights[weight] -= alpha * *iter++;
}
}
while(std::accumulate(Error.cbegin(), Error.cend(), 0.0) / examples.size() > tol);
}
void NeuralNet::updateNNWeights(const std::vector<double> & new_weights)
{
if(new_weights.size() != size()) throw std::invalid_argument("Too few of weights!");
unsigned count = 0;
for(unsigned i = 0; i < m_layers.size(); i++)
{
for(auto j = m_layers[i].begin(); j != m_layers[i].end(); j++)
{
for(unsigned k=0; k < (*j).m_weights.size(); k++)
(*j).m_weights[k] = new_weights[count++];
}
}
}
unsigned NeuralNet::size() const
{
unsigned count = 0;
for(unsigned i = 0; i < m_layers.size(); i++)
{
for(auto j = m_layers[i].cbegin(); j != m_layers[i].cend(); j++)
{
count += (*j).m_weights.size();
}
}
return count;
}
std::ostream& operator<< (std::ostream& out, const NeuralNet & net)
{
for(unsigned i=0; i < net.m_layers.size(); i++)
{
out << "########################Layer" << i << "########################" << std::endl;
for(auto j = net.m_layers[i].cbegin(); j != net.m_layers[i].cend(); j++)
out << *j << std::endl;
out << "######################################################" << std::endl;
}
return out;
}
//---------------------------------------------------------------TrainingExample---------------------------------------------------------------
TrainingExample::TrainingExample(std::vector<double> && inputs, std::vector<double> && outputs)
:m_inputs(inputs),
m_outputs(outputs)
{}<commit_msg>Fixed bug in back propagation alg<commit_after>#include "NeuralNet.h"
//---------------------------------------------------------------Neuron---------------------------------------------------------------
Neuron::Neuron(unsigned numInputs)
{
for(unsigned i=0; i<numInputs+1; i++)
{
m_weights.push_back(randomValue());
}
}
double Neuron::randomValue()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dist(-1, 1);
return dist(gen);
}
double Neuron::operator* (const std::vector<double> & inputs)
{
double result = 0;
auto weight = m_weights.cbegin();
for(auto i = inputs.cbegin(); i != inputs.cend(); i++)
{
result += (*i) * (*weight);
weight++;
}
result += *weight;
result = sigmoid(result);
m_output = result;
return result;
}
double Neuron::sigmoid(double x) const
{
return 1.0 / (1.0 + std::exp(-x));
}
std::ostream& operator<< (std::ostream & out, const Neuron & neuron)
{
out << "[";
for(auto i = neuron.m_weights.cbegin(); i != neuron.m_weights.cend(); i++)
out << " " << *i;
out << " ]";
return out;
}
//----------------------------------------------------------------NeuralNet---------------------------------------------------------------
NeuralNet::NeuralNet(const std::vector<unsigned>& topology)
{
for(auto i = topology.cbegin()+1; i != topology.cend(); i++)
{
m_layers.push_back(Layer());
for(unsigned j=0; j < *i; j++)
{
m_layers.back().push_back(Neuron(*(i-1)));
}
}
}
std::vector<double> NeuralNet::propagate(const std::vector<double>& inputs)
{
if(inputs.size() != m_layers[0][0].m_weights.size()-1) throw std::invalid_argument("Wrong number of inputs!");
return *this * inputs;
}
std::vector<double> NeuralNet::operator* (const std::vector<double> & inputs)
{
std::vector<double> outputs = std::move(inputs);
std::vector<double> neuronOutput;
for(auto i = m_layers.begin(); i != m_layers.end(); i++)
{
for(auto j = (*i).begin(); j != (*i).end(); j++)
{
neuronOutput.push_back(*j * outputs);
}
outputs = std::move(neuronOutput);
}
return outputs;
}
void NeuralNet::backProp(const std::vector<TrainingExample> & examples, double tol, double alpha)
{
std::vector<double> Error;
do
{
Error.clear();
//calculate error for all examples
for(auto ex = examples.cbegin(); ex != examples.cend(); ex++)
{
std::vector<double> inputs = (*ex).m_inputs;
std::vector<double> outputs = propagate(inputs);
double error = 0;
auto target = (*ex).m_outputs.cbegin();
for(auto actual = outputs.cbegin(); actual != outputs.cend(); actual++)
{
error += 0.5 * std::pow((*target - *actual), 2);
target++;
}
Error.push_back(error);
//calculate deltas
std::vector<double> deltaWeight;
std::vector<double> delta;
std::vector<double> prevDelta;
target = (*ex).m_outputs.cbegin();
//for all layers
for(int layer = m_layers.size() - 1; layer >= 0; --layer)
{
prevDelta = std::move(delta);
//for all neurons in current layer
for(unsigned neuron = 0; neuron < m_layers[layer].size(); neuron++)
{
//for output layer
if(layer == (int)m_layers.size()-1)
{
double d = (m_layers[layer][neuron].m_output - *target) * m_layers[layer][neuron].m_output * (1 - m_layers[layer][neuron].m_output);
target++;
delta.push_back(d);
}
else //for hidden layer
{
double sum = 0.0;
int count = 0;
for(auto deltaIter = prevDelta.cbegin(); deltaIter != prevDelta.cend(); deltaIter++)
{
sum += *deltaIter * m_layers[layer+1][count].m_weights[neuron];
count++;
}
double d = sum * m_layers[layer][neuron].m_output * (1 - m_layers[layer][neuron].m_output);
delta.push_back(d);
}
//for every weight in current neuron
unsigned n = m_layers[layer][neuron].m_weights.size();
for(unsigned weight = 0; weight < n; weight++)
{
if(layer > 0)//not first hidden
{
double w = delta.back() * (weight < n-1 ? m_layers[layer - 1][weight].m_output : 1);
deltaWeight.push_back(w);
}
else //first hidden
{
double w = delta.back() * (weight < n-1 ? (*ex).m_inputs[weight] : 1);
deltaWeight.push_back(w);
}
}
}
}
//update weights
auto iter = deltaWeight.cbegin();
for(int layer = m_layers.size() - 1; layer >= 0; layer--)
for(unsigned neuron = 0; neuron < m_layers[layer].size(); neuron++)
for(unsigned weight = 0; weight < m_layers[layer][neuron].m_weights.size(); weight++)
m_layers[layer][neuron].m_weights[weight] -= alpha * *iter++;
}
}
while(std::accumulate(Error.cbegin(), Error.cend(), 0.0) / examples.size() > tol);
}
void NeuralNet::updateNNWeights(const std::vector<double> & new_weights)
{
if(new_weights.size() != size()) throw std::invalid_argument("Too few of weights!");
unsigned count = 0;
for(unsigned i = 0; i < m_layers.size(); i++)
{
for(auto j = m_layers[i].begin(); j != m_layers[i].end(); j++)
{
for(unsigned k=0; k < (*j).m_weights.size(); k++)
(*j).m_weights[k] = new_weights[count++];
}
}
}
unsigned NeuralNet::size() const
{
unsigned count = 0;
for(unsigned i = 0; i < m_layers.size(); i++)
{
for(auto j = m_layers[i].cbegin(); j != m_layers[i].cend(); j++)
{
count += (*j).m_weights.size();
}
}
return count;
}
std::ostream& operator<< (std::ostream& out, const NeuralNet & net)
{
for(unsigned i=0; i < net.m_layers.size(); i++)
{
out << "########################Layer" << i << "########################" << std::endl;
for(auto j = net.m_layers[i].cbegin(); j != net.m_layers[i].cend(); j++)
out << *j << std::endl;
out << "######################################################" << std::endl;
}
return out;
}
//---------------------------------------------------------------TrainingExample---------------------------------------------------------------
TrainingExample::TrainingExample(std::vector<double> && inputs, std::vector<double> && outputs)
:m_inputs(inputs),
m_outputs(outputs)
{}<|endoftext|>
|
<commit_before>#include "OSGWidget.h"
#include <osg/Camera>
#include <osg/DisplaySettings>
#include <osg/Geode>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgGA/EventQueue>
#include <osgGA/TrackballManipulator>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/PolytopeIntersector>
#include <osgViewer/View>
#include <osgViewer/ViewerEventHandlers>
#include <cassert>
#include <stdexcept>
#include <vector>
#include <QDebug>
#include <QKeyEvent>
#include <QWheelEvent>
namespace
{
QRect makeRectangle( const QPoint& first, const QPoint& second )
{
// Relative to the first point, the second point may be in either one of the
// four quadrants of an Euclidean coordinate system.
//
// We enumerate them in counter-clockwise order, starting from the lower-right
// quadrant that corresponds to the default case:
//
// |
// (3) | (4)
// |
// -------|-------
// |
// (2) | (1)
// |
if( second.x() >= first.x() && second.y() >= first.y() )
return QRect( first, second );
else if( second.x() < first.x() && second.y() >= first.y() )
return QRect( QPoint( second.x(), first.y() ), QPoint( first.x(), second.y() ) );
else if( second.x() < first.x() && second.y() < first.y() )
return QRect( second, first );
else if( second.x() >= first.x() && second.y() < first.y() )
return QRect( QPoint( first.x(), second.y() ), QPoint( second.x(), first.y() ) );
// Should never reach that point...
return QRect();
}
}
OSGWidget::OSGWidget( QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags f )
: QGLWidget( parent,
shareWidget,
f )
, viewer_( new osgViewer::CompositeViewer )
, selectionActive_( false )
, selectionFinished_( true )
{
osg::Sphere* sphere = new osg::Sphere( osg::Vec3( 0.f, 0.f, 0.f ), 0.25f );
osg::ShapeDrawable* sd = new osg::ShapeDrawable( sphere );
sd->setColor( osg::Vec4( 1.f, 0.f, 0.f, 1.f ) );
sd->setName( "A nice sphere" );
osg::Geode* geode = new osg::Geode;
geode->addDrawable( sd );
float aspectRatio = static_cast<float>( this->width() / 2 ) / static_cast<float>( this->height() );
osg::Camera* camera = new osg::Camera;
camera->setViewport( 0, 0, this->width() / 2, this->height() );
camera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) );
camera->setProjectionMatrixAsPerspective( 30.f, aspectRatio, 1.f, 1000.f );
camera->setGraphicsContext( graphicsWindow_ );
osgViewer::View* view = new osgViewer::View;
view->setCamera( camera );
view->setSceneData( geode );
view->addEventHandler( new osgViewer::StatsHandler );
view->setCameraManipulator( new osgGA::TrackballManipulator );
osg::Camera* sideCamera = new osg::Camera;
sideCamera->setViewport( this->width() /2, 0,
this->width() /2, this->height() );
sideCamera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) );
sideCamera->setProjectionMatrixAsPerspective( 30.f, aspectRatio, 1.f, 1000.f );
sideCamera->setGraphicsContext( graphicsWindow_ );
osgViewer::View* sideView = new osgViewer::View;
sideView->setCamera( sideCamera );
sideView->setSceneData( geode );
sideView->addEventHandler( new osgViewer::StatsHandler );
sideView->setCameraManipulator( new osgGA::TrackballManipulator );
viewer_->addView( view );
viewer_->addView( sideView );
viewer_->setThreadingModel( osgViewer::CompositeViewer::SingleThreaded );
// This ensures that the widget will receive keyboard events. This focus
// policy is not set by default. The default, Qt::NoFocus, will result in
// keyboard events that are ignored.
this->setFocusPolicy( Qt::StrongFocus );
this->setMinimumSize( 100, 100 );
// Ensures that the widget receives mouse move events even though no
// mouse button has been pressed. We require this in order to let the
// graphics window switch viewports properly.
this->setMouseTracking( true );
}
OSGWidget::~OSGWidget()
{
}
void OSGWidget::paintEvent( QPaintEvent* /* paintEvent */ )
{
QPainter painter( this );
painter.setRenderHint( QPainter::Antialiasing );
this->paintGL();
if( selectionActive_ && !selectionFinished_ )
{
painter.setPen( Qt::black );
painter.setBrush( Qt::transparent );
painter.drawRect( makeRectangle( selectionStart_, selectionEnd_ ) );
}
painter.end();
this->swapBuffers();
}
void OSGWidget::paintGL()
{
viewer_->frame();
}
void OSGWidget::resizeGL( int width, int height )
{
this->getEventQueue()->windowResize( this->x(), this->y(), width, height );
graphicsWindow_->resized( this->x(), this->y(), width, height );
this->onResize( width, height );
}
void OSGWidget::keyPressEvent( QKeyEvent* event )
{
QString keyString = event->text();
const char* keyData = keyString.toAscii().data();
if( event->key() == Qt::Key_S )
selectionActive_ = !selectionActive_;
else if( event->key() == Qt::Key_H )
this->onHome();
else
this->getEventQueue()->keyPress( osgGA::GUIEventAdapter::KeySymbol( *keyData ) );
}
void OSGWidget::keyReleaseEvent( QKeyEvent* event )
{
QString keyString = event->text();
const char* keyData = keyString.toAscii().data();
this->getEventQueue()->keyRelease( osgGA::GUIEventAdapter::KeySymbol( *keyData ) );
}
void OSGWidget::mouseMoveEvent( QMouseEvent* event )
{
// Note that we have to check the buttons mask in order to see whether the
// left button has been pressed. A call to `button()` will only result in
// `Qt::NoButton` for mouse move events.
if( selectionActive_ && event->buttons() & Qt::LeftButton )
{
selectionEnd_ = event->pos();
// Ensures that new paint events are created while the user moves the
// mouse.
this->update();
}
else
{
this->getEventQueue()->mouseMotion( static_cast<float>( event->x() ),
static_cast<float>( event->y() ) );
}
}
void OSGWidget::mousePressEvent( QMouseEvent* event )
{
// Selection processing
if( selectionActive_ && event->button() == Qt::LeftButton )
{
selectionStart_ = event->pos();
selectionEnd_ = selectionStart_; // Deletes the old selection
selectionFinished_ = false; // As long as this is set, the rectangle will be drawn
}
// Normal processing
else
{
// 1 = left mouse button
// 2 = middle mouse button
// 3 = right mouse button
unsigned int button = 0;
switch( event->button() )
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
this->getEventQueue()->mouseButtonPress( static_cast<float>( event->x() ),
static_cast<float>( event->y() ),
button );
}
}
void OSGWidget::mouseReleaseEvent(QMouseEvent* event)
{
// Selection processing: Store end position and obtain selected objects
// through polytope intersection.
if( selectionActive_ && event->button() == Qt::LeftButton )
{
selectionEnd_ = event->pos();
selectionFinished_ = true; // Will force the painter to stop drawing the
// selection rectangle
this->processSelection();
}
// Normal processing
else
{
// 1 = left mouse button
// 2 = middle mouse button
// 3 = right mouse button
unsigned int button = 0;
switch( event->button() )
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
this->getEventQueue()->mouseButtonRelease( static_cast<float>( event->x() ),
static_cast<float>( event->y() ),
button );
}
}
void OSGWidget::wheelEvent( QWheelEvent* event )
{
// Ignore wheel events as long as the selection is active.
if( selectionActive_ )
return;
event->accept();
int delta = event->delta();
osgGA::GUIEventAdapter::ScrollingMotion motion = delta > 0 ? osgGA::GUIEventAdapter::SCROLL_UP
: osgGA::GUIEventAdapter::SCROLL_DOWN;
this->getEventQueue()->mouseScroll( motion );
}
bool OSGWidget::event( QEvent* event )
{
bool handled = QGLWidget::event( event );
// This ensures that the OSG widget is always going to be repainted after the
// user performed some interaction. Doing this in the event handler ensures
// that we don't forget about some event and prevents duplicate code.
switch( event->type() )
{
case QEvent::KeyPress:
case QEvent::KeyRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove:
case QEvent::Wheel:
this->update();
break;
default:
break;
}
return( handled );
}
void OSGWidget::onHome()
{
osgViewer::ViewerBase::Views views;
viewer_->getViews( views );
for( std::size_t i = 0; i < views.size(); i++ )
{
osgViewer::View* view = views.at(i);
view->home();
}
}
void OSGWidget::onResize( int width, int height )
{
std::vector<osg::Camera*> cameras;
viewer_->getCameras( cameras );
assert( cameras.size() == 2 );
cameras[0]->setViewport( 0, 0, this->width() / 2, this->height() );
cameras[1]->setViewport( this->width() / 2, 0, this->width() / 2, this->height() );
}
osgGA::EventQueue* OSGWidget::getEventQueue() const
{
osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue();
if( eventQueue )
return( eventQueue );
else
throw( std::runtime_error( "Unable to obtain valid event queue") );
}
void OSGWidget::processSelection()
{
QRect selectionRectangle = makeRectangle( selectionStart_, selectionEnd_ );
int widgetHeight = this->height();
double xMin = selectionRectangle.left();
double xMax = selectionRectangle.right();
double yMin = widgetHeight - selectionRectangle.bottom();
double yMax = widgetHeight - selectionRectangle.top();
osgUtil::PolytopeIntersector* polytopeIntersector
= new osgUtil::PolytopeIntersector( osgUtil::PolytopeIntersector::WINDOW,
xMin, yMin,
xMax, yMax );
// This limits the amount of intersections that are reported by the
// polytope intersector. Using this setting, a single drawable will
// appear at most once while calculating intersections. This is the
// preferred and expected behaviour.
polytopeIntersector->setIntersectionLimit( osgUtil::Intersector::LIMIT_ONE_PER_DRAWABLE );
osgUtil::IntersectionVisitor iv( polytopeIntersector );
for( unsigned int viewIndex = 0; viewIndex < viewer_->getNumViews(); viewIndex++ )
{
osgViewer::View* view = viewer_->getView( viewIndex );
if( !view )
throw std::runtime_error( "Unable to obtain valid view for selection processing" );
osg::Camera* camera = view->getCamera();
if( !camera )
throw std::runtime_error( "Unable to obtain valid camera for selection processing" );
camera->accept( iv );
if( !polytopeIntersector->containsIntersections() )
continue;
auto intersections = polytopeIntersector->getIntersections();
for( auto&& intersection : intersections )
qDebug() << "Selected a drawable:" << QString::fromStdString( intersection.drawable->getName() );
}
}
<commit_msg>Fixed missing graphics window initialization<commit_after>#include "OSGWidget.h"
#include <osg/Camera>
#include <osg/DisplaySettings>
#include <osg/Geode>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgGA/EventQueue>
#include <osgGA/TrackballManipulator>
#include <osgUtil/IntersectionVisitor>
#include <osgUtil/PolytopeIntersector>
#include <osgViewer/View>
#include <osgViewer/ViewerEventHandlers>
#include <cassert>
#include <stdexcept>
#include <vector>
#include <QDebug>
#include <QKeyEvent>
#include <QWheelEvent>
namespace
{
QRect makeRectangle( const QPoint& first, const QPoint& second )
{
// Relative to the first point, the second point may be in either one of the
// four quadrants of an Euclidean coordinate system.
//
// We enumerate them in counter-clockwise order, starting from the lower-right
// quadrant that corresponds to the default case:
//
// |
// (3) | (4)
// |
// -------|-------
// |
// (2) | (1)
// |
if( second.x() >= first.x() && second.y() >= first.y() )
return QRect( first, second );
else if( second.x() < first.x() && second.y() >= first.y() )
return QRect( QPoint( second.x(), first.y() ), QPoint( first.x(), second.y() ) );
else if( second.x() < first.x() && second.y() < first.y() )
return QRect( second, first );
else if( second.x() >= first.x() && second.y() < first.y() )
return QRect( QPoint( first.x(), second.y() ), QPoint( second.x(), first.y() ) );
// Should never reach that point...
return QRect();
}
}
OSGWidget::OSGWidget( QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags f )
: QGLWidget( parent,
shareWidget,
f )
, graphicsWindow_( new osgViewer::GraphicsWindowEmbedded( this->x(),
this->y(),
this->width(),
this->height() ) )
, viewer_( new osgViewer::CompositeViewer )
, selectionActive_( false )
, selectionFinished_( true )
{
osg::Sphere* sphere = new osg::Sphere( osg::Vec3( 0.f, 0.f, 0.f ), 0.25f );
osg::ShapeDrawable* sd = new osg::ShapeDrawable( sphere );
sd->setColor( osg::Vec4( 1.f, 0.f, 0.f, 1.f ) );
sd->setName( "A nice sphere" );
osg::Geode* geode = new osg::Geode;
geode->addDrawable( sd );
float aspectRatio = static_cast<float>( this->width() / 2 ) / static_cast<float>( this->height() );
osg::Camera* camera = new osg::Camera;
camera->setViewport( 0, 0, this->width() / 2, this->height() );
camera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) );
camera->setProjectionMatrixAsPerspective( 30.f, aspectRatio, 1.f, 1000.f );
camera->setGraphicsContext( graphicsWindow_ );
osgViewer::View* view = new osgViewer::View;
view->setCamera( camera );
view->setSceneData( geode );
view->addEventHandler( new osgViewer::StatsHandler );
view->setCameraManipulator( new osgGA::TrackballManipulator );
osg::Camera* sideCamera = new osg::Camera;
sideCamera->setViewport( this->width() /2, 0,
this->width() /2, this->height() );
sideCamera->setClearColor( osg::Vec4( 0.f, 0.f, 1.f, 1.f ) );
sideCamera->setProjectionMatrixAsPerspective( 30.f, aspectRatio, 1.f, 1000.f );
sideCamera->setGraphicsContext( graphicsWindow_ );
osgViewer::View* sideView = new osgViewer::View;
sideView->setCamera( sideCamera );
sideView->setSceneData( geode );
sideView->addEventHandler( new osgViewer::StatsHandler );
sideView->setCameraManipulator( new osgGA::TrackballManipulator );
viewer_->addView( view );
viewer_->addView( sideView );
viewer_->setThreadingModel( osgViewer::CompositeViewer::SingleThreaded );
// This ensures that the widget will receive keyboard events. This focus
// policy is not set by default. The default, Qt::NoFocus, will result in
// keyboard events that are ignored.
this->setFocusPolicy( Qt::StrongFocus );
this->setMinimumSize( 100, 100 );
// Ensures that the widget receives mouse move events even though no
// mouse button has been pressed. We require this in order to let the
// graphics window switch viewports properly.
this->setMouseTracking( true );
}
OSGWidget::~OSGWidget()
{
}
void OSGWidget::paintEvent( QPaintEvent* /* paintEvent */ )
{
QPainter painter( this );
painter.setRenderHint( QPainter::Antialiasing );
this->paintGL();
if( selectionActive_ && !selectionFinished_ )
{
painter.setPen( Qt::black );
painter.setBrush( Qt::transparent );
painter.drawRect( makeRectangle( selectionStart_, selectionEnd_ ) );
}
painter.end();
this->swapBuffers();
}
void OSGWidget::paintGL()
{
viewer_->frame();
}
void OSGWidget::resizeGL( int width, int height )
{
this->getEventQueue()->windowResize( this->x(), this->y(), width, height );
graphicsWindow_->resized( this->x(), this->y(), width, height );
this->onResize( width, height );
}
void OSGWidget::keyPressEvent( QKeyEvent* event )
{
QString keyString = event->text();
const char* keyData = keyString.toAscii().data();
if( event->key() == Qt::Key_S )
selectionActive_ = !selectionActive_;
else if( event->key() == Qt::Key_H )
this->onHome();
else
this->getEventQueue()->keyPress( osgGA::GUIEventAdapter::KeySymbol( *keyData ) );
}
void OSGWidget::keyReleaseEvent( QKeyEvent* event )
{
QString keyString = event->text();
const char* keyData = keyString.toAscii().data();
this->getEventQueue()->keyRelease( osgGA::GUIEventAdapter::KeySymbol( *keyData ) );
}
void OSGWidget::mouseMoveEvent( QMouseEvent* event )
{
// Note that we have to check the buttons mask in order to see whether the
// left button has been pressed. A call to `button()` will only result in
// `Qt::NoButton` for mouse move events.
if( selectionActive_ && event->buttons() & Qt::LeftButton )
{
selectionEnd_ = event->pos();
// Ensures that new paint events are created while the user moves the
// mouse.
this->update();
}
else
{
this->getEventQueue()->mouseMotion( static_cast<float>( event->x() ),
static_cast<float>( event->y() ) );
}
}
void OSGWidget::mousePressEvent( QMouseEvent* event )
{
// Selection processing
if( selectionActive_ && event->button() == Qt::LeftButton )
{
selectionStart_ = event->pos();
selectionEnd_ = selectionStart_; // Deletes the old selection
selectionFinished_ = false; // As long as this is set, the rectangle will be drawn
}
// Normal processing
else
{
// 1 = left mouse button
// 2 = middle mouse button
// 3 = right mouse button
unsigned int button = 0;
switch( event->button() )
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
this->getEventQueue()->mouseButtonPress( static_cast<float>( event->x() ),
static_cast<float>( event->y() ),
button );
}
}
void OSGWidget::mouseReleaseEvent(QMouseEvent* event)
{
// Selection processing: Store end position and obtain selected objects
// through polytope intersection.
if( selectionActive_ && event->button() == Qt::LeftButton )
{
selectionEnd_ = event->pos();
selectionFinished_ = true; // Will force the painter to stop drawing the
// selection rectangle
this->processSelection();
}
// Normal processing
else
{
// 1 = left mouse button
// 2 = middle mouse button
// 3 = right mouse button
unsigned int button = 0;
switch( event->button() )
{
case Qt::LeftButton:
button = 1;
break;
case Qt::MiddleButton:
button = 2;
break;
case Qt::RightButton:
button = 3;
break;
default:
break;
}
this->getEventQueue()->mouseButtonRelease( static_cast<float>( event->x() ),
static_cast<float>( event->y() ),
button );
}
}
void OSGWidget::wheelEvent( QWheelEvent* event )
{
// Ignore wheel events as long as the selection is active.
if( selectionActive_ )
return;
event->accept();
int delta = event->delta();
osgGA::GUIEventAdapter::ScrollingMotion motion = delta > 0 ? osgGA::GUIEventAdapter::SCROLL_UP
: osgGA::GUIEventAdapter::SCROLL_DOWN;
this->getEventQueue()->mouseScroll( motion );
}
bool OSGWidget::event( QEvent* event )
{
bool handled = QGLWidget::event( event );
// This ensures that the OSG widget is always going to be repainted after the
// user performed some interaction. Doing this in the event handler ensures
// that we don't forget about some event and prevents duplicate code.
switch( event->type() )
{
case QEvent::KeyPress:
case QEvent::KeyRelease:
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove:
case QEvent::Wheel:
this->update();
break;
default:
break;
}
return( handled );
}
void OSGWidget::onHome()
{
osgViewer::ViewerBase::Views views;
viewer_->getViews( views );
for( std::size_t i = 0; i < views.size(); i++ )
{
osgViewer::View* view = views.at(i);
view->home();
}
}
void OSGWidget::onResize( int width, int height )
{
std::vector<osg::Camera*> cameras;
viewer_->getCameras( cameras );
assert( cameras.size() == 2 );
cameras[0]->setViewport( 0, 0, this->width() / 2, this->height() );
cameras[1]->setViewport( this->width() / 2, 0, this->width() / 2, this->height() );
}
osgGA::EventQueue* OSGWidget::getEventQueue() const
{
osgGA::EventQueue* eventQueue = graphicsWindow_->getEventQueue();
if( eventQueue )
return( eventQueue );
else
throw( std::runtime_error( "Unable to obtain valid event queue") );
}
void OSGWidget::processSelection()
{
QRect selectionRectangle = makeRectangle( selectionStart_, selectionEnd_ );
int widgetHeight = this->height();
double xMin = selectionRectangle.left();
double xMax = selectionRectangle.right();
double yMin = widgetHeight - selectionRectangle.bottom();
double yMax = widgetHeight - selectionRectangle.top();
osgUtil::PolytopeIntersector* polytopeIntersector
= new osgUtil::PolytopeIntersector( osgUtil::PolytopeIntersector::WINDOW,
xMin, yMin,
xMax, yMax );
// This limits the amount of intersections that are reported by the
// polytope intersector. Using this setting, a single drawable will
// appear at most once while calculating intersections. This is the
// preferred and expected behaviour.
polytopeIntersector->setIntersectionLimit( osgUtil::Intersector::LIMIT_ONE_PER_DRAWABLE );
osgUtil::IntersectionVisitor iv( polytopeIntersector );
for( unsigned int viewIndex = 0; viewIndex < viewer_->getNumViews(); viewIndex++ )
{
osgViewer::View* view = viewer_->getView( viewIndex );
if( !view )
throw std::runtime_error( "Unable to obtain valid view for selection processing" );
osg::Camera* camera = view->getCamera();
if( !camera )
throw std::runtime_error( "Unable to obtain valid camera for selection processing" );
camera->accept( iv );
if( !polytopeIntersector->containsIntersections() )
continue;
auto intersections = polytopeIntersector->getIntersections();
for( auto&& intersection : intersections )
qDebug() << "Selected a drawable:" << QString::fromStdString( intersection.drawable->getName() );
}
}
<|endoftext|>
|
<commit_before>#include "FboQuickView.h"
#include <QScopedPointer>
#include <QQuickItem>
FboQuickView::FboQuickView( QOpenGLContext* context /*= 0*/ )
: FboQuickWindow( context ), m_qmlComponent( 0 ), m_rootItem( 0 )
{
}
FboQuickView::~FboQuickView()
{
}
void FboQuickView::setSource( const QUrl& source )
{
if( m_rootItem ) {
delete m_rootItem;
m_rootItem = 0;
}
if( m_qmlComponent ) {
delete m_qmlComponent;
m_qmlComponent = 0;
}
if( !source.isEmpty() ) {
m_qmlComponent = new QQmlComponent( &m_qmlEngine, source );
if( m_qmlComponent->isLoading() ) {
connect( m_qmlComponent, &QQmlComponent::statusChanged,
this, &FboQuickView::componentStatusChanged );
} else {
componentStatusChanged( m_qmlComponent->status() );
}
QResizeEvent event( size(), size() );
resizeEvent( &event );
}
}
void FboQuickView::componentStatusChanged( QQmlComponent::Status status )
{
Q_ASSERT( !m_rootItem );
if( QQmlComponent::Ready != status )
return;
QScopedPointer<QObject> rootObject( m_qmlComponent->create() );
m_rootItem = qobject_cast<QQuickItem*>( rootObject.data() );
if( !m_rootItem )
return;
m_rootItem->setParentItem( contentItem() );
rootObject.take();
}
void FboQuickView::resizeEvent( QResizeEvent* event )
{
FboQuickWindow::resizeEvent( event );
if( m_rootItem )
m_rootItem->setSize( QSizeF( width(), height() ) );
}
<commit_msg>fix memory leak<commit_after>#include "FboQuickView.h"
#include <QScopedPointer>
#include <QQuickItem>
FboQuickView::FboQuickView( QOpenGLContext* context /*= 0*/ )
: FboQuickWindow( context ), m_qmlComponent( 0 ), m_rootItem( 0 )
{
}
FboQuickView::~FboQuickView()
{
}
void FboQuickView::setSource( const QUrl& source )
{
if( m_rootItem ) {
delete m_rootItem;
m_rootItem = 0;
}
if( m_qmlComponent ) {
delete m_qmlComponent;
m_qmlComponent = 0;
}
if( !source.isEmpty() ) {
m_qmlComponent = new QQmlComponent( &m_qmlEngine, source, &m_qmlEngine );
if( m_qmlComponent->isLoading() ) {
connect( m_qmlComponent, &QQmlComponent::statusChanged,
this, &FboQuickView::componentStatusChanged );
} else {
componentStatusChanged( m_qmlComponent->status() );
}
QResizeEvent event( size(), size() );
resizeEvent( &event );
}
}
void FboQuickView::componentStatusChanged( QQmlComponent::Status status )
{
Q_ASSERT( !m_rootItem );
if( QQmlComponent::Ready != status )
return;
QScopedPointer<QObject> rootObject( m_qmlComponent->create() );
m_rootItem = qobject_cast<QQuickItem*>( rootObject.data() );
if( !m_rootItem )
return;
rootObject.take()->setParent( contentItem() );
m_rootItem->setParentItem( contentItem() );
}
void FboQuickView::resizeEvent( QResizeEvent* event )
{
FboQuickWindow::resizeEvent( event );
if( m_rootItem )
m_rootItem->setSize( QSizeF( width(), height() ) );
}
<|endoftext|>
|
<commit_before>#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
int main() {
sf::RenderWindow drawingBoard(sf::VideoMode(1300, 1300), "Drawing Board"),
textWindow(sf::VideoMode(1100, 800), "Shell");
drawingBoard.setPosition(sf::Vector2i{1100, 0});
textWindow.setPosition(sf::Vector2i{0, 0});
drawingBoard.setVerticalSyncEnabled(true);
textWindow.setVerticalSyncEnabled(true);
std::string s;
sf::Font font;
font.loadFromFile("monaco.ttf");
sf::Text text;
text.setFont(font);
text.setCharacterSize(27);
text.setFillColor(sf::Color::Black);
text.setStyle(sf::Text::Bold | sf::Text::Underlined);
while (textWindow.isOpen() && drawingBoard.isOpen()) {
sf::Event event;
textWindow.clear(sf::Color::White);
drawingBoard.clear(sf::Color::White);
while (textWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
textWindow.close();
} else if (event.type == sf::Event::TextEntered) {
if (isprint(event.text.unicode)) {
s.push_back(static_cast<char>(event.text.unicode));
} else if (event.text.unicode == 8) {
// BackSpace
s.pop_back();
} else if (event.text.unicode == 10) {
// Line feed
}
text.setString(s);
}
}
while (drawingBoard.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
textWindow.close();
}
}
textWindow.draw(text);
textWindow.display();
drawingBoard.display();
}
return 0;
}
<commit_msg>增加文本框的历史记录功能<commit_after>#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
using namespace std;
namespace {
sf::Font font;
};
sf::Text getText(const std::string &res, sf::Color c = sf::Color::Black) {
sf::Text text;
text.setString(res);
text.setFont(font);
text.setCharacterSize(27);
text.setFillColor(c);
return std::move(text);
}
int main() {
sf::RenderWindow drawingBoard(sf::VideoMode(1300, 1300), "Drawing Board"),
textWindow(sf::VideoMode(1100, 800), "Shell");
drawingBoard.setPosition(sf::Vector2i{1100, 0});
textWindow.setPosition(sf::Vector2i{0, 0});
drawingBoard.setVerticalSyncEnabled(true);
textWindow.setVerticalSyncEnabled(true);
font.loadFromFile("monaco.ttf");
vector<sf::Text> history;
std::string s;
sf::Text currentText{getText(s)};
while (textWindow.isOpen() && drawingBoard.isOpen()) {
sf::Event event;
textWindow.clear(sf::Color::White);
drawingBoard.clear(sf::Color::White);
while (textWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
textWindow.close();
} else if (event.type == sf::Event::TextEntered) {
if (isprint(event.text.unicode)) {
s.push_back(static_cast<char>(event.text.unicode));
} else if (event.text.unicode == 8 && !s.empty()) { // BackSpace
s.pop_back();
} else if (event.text.unicode == 10) { // LineFeed
s += "\n\t";
long openBrace = std::count(begin(s), end(s), ')');
long closeBrace = std::count(begin(s), end(s), '(');
if (openBrace > 0 && openBrace == closeBrace) {
history.push_back(currentText);
history.back().setFillColor(sf::Color::Red);
float delta = 10 + currentText.getLocalBounds().height;
for_each(begin(history), end(history),
[delta](sf::Text &text) { text.move(0, -delta); });
s.clear();
}
}
} else if (event.type == sf::Event::MouseWheelScrolled) {
auto delta = event.mouseWheelScroll.delta * 5;
currentText.move(0, delta);
for_each(begin(history), end(history),
[delta](sf::Text &text) { text.move(0, delta); });
}
}
while (drawingBoard.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
textWindow.close();
}
}
currentText.setString(s);
textWindow.draw(currentText);
for_each(begin(history), end(history),
[&textWindow](const sf::Text &text) { textWindow.draw(text); });
textWindow.display();
drawingBoard.display();
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Restructuring Shogun's statistical hypothesis testing framework.
* Copyright (C) 2016 Soumyajit De
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 <shogun/lib/SGMatrix.h>
#include <shogun/statistical_testing/internals/ComputationManager.h>
#include <shogun/statistical_testing/internals/mmd/UnbiasedFull.h>
using namespace shogun;
using namespace internal;
ComputationManager::ComputationManager()
{
}
ComputationManager::~ComputationManager()
{
}
void ComputationManager::num_data(index_t n)
{
data_array.resize(n);
}
SGMatrix<float64_t>& ComputationManager::data(index_t i)
{
return data_array[i];
}
void ComputationManager::enqueue_job(std::function<float64_t(SGMatrix<float64_t>)> job)
{
job_array.push_back(job);
}
void ComputationManager::compute_data_parallel_jobs()
{
result_array.resize(job_array.size());
for(size_t j=0; j<job_array.size(); ++j)
{
const auto& compute_job=job_array[j];
std::vector<float64_t> current_job_results(data_array.size());
if (gpu)
{
// TODO current_job_results = compute_job.compute_using_gpu(data_array);
}
else
{
#pragma omp parallel for
for (size_t i=0; i<data_array.size(); ++i)
current_job_results[i]=compute_job(data_array[i]);
}
result_array[j]=current_job_results;
}
}
void ComputationManager::compute_task_parallel_jobs()
{
result_array.resize(job_array.size());
#pragma omp parallel for
for(size_t j=0; j<job_array.size(); ++j)
{
const auto& compute_job=job_array[j];
std::vector<float64_t> current_job_results(data_array.size());
if (gpu)
{
// TODO current_job_results = compute_job.compute_using_gpu(data_array);
}
else
{
for (size_t i=0; i<data_array.size(); ++i)
current_job_results[i]=compute_job(data_array[i]);
}
result_array[j]=current_job_results;
}
}
void ComputationManager::done()
{
job_array.resize(0);
result_array.resize(0);
}
std::vector<float64_t>& ComputationManager::result(index_t i)
{
return result_array[i];
}
ComputationManager& ComputationManager::use_gpu()
{
gpu=true;
return *this;
}
ComputationManager& ComputationManager::use_cpu()
{
gpu=false;
return *this;
}
<commit_msg>added data parallel job computation cache friendly<commit_after>/*
* Restructuring Shogun's statistical hypothesis testing framework.
* Copyright (C) 2016 Soumyajit De
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 <shogun/lib/SGMatrix.h>
#include <shogun/statistical_testing/internals/ComputationManager.h>
#include <shogun/statistical_testing/internals/mmd/UnbiasedFull.h>
using namespace shogun;
using namespace internal;
ComputationManager::ComputationManager()
{
}
ComputationManager::~ComputationManager()
{
}
void ComputationManager::num_data(index_t n)
{
data_array.resize(n);
}
SGMatrix<float64_t>& ComputationManager::data(index_t i)
{
return data_array[i];
}
void ComputationManager::enqueue_job(std::function<float64_t(SGMatrix<float64_t>)> job)
{
job_array.push_back(job);
}
void ComputationManager::compute_data_parallel_jobs()
{
// this is used when there are more number of data blocks to be processed
// than there are jobs
result_array.resize(job_array.size());
for (size_t j=0; j<job_array.size(); ++j)
result_array[j].resize(data_array.size());
if (gpu)
{
// TODO current_job_results = compute_job.compute_using_gpu(data_array);
}
else
{
#pragma omp parallel for
for (size_t i=0; i<data_array.size(); ++i)
{
// using a temporary vector to hold the result, because it is
// cache friendly, since the original result matrix would lead
// to several cache misses, specially because the data is also
// being used here
std::vector<float64_t> current_data_results(job_array.size());
for (size_t j=0; j<job_array.size(); ++j)
{
const auto& compute_job=job_array[j];
current_data_results[j]=compute_job(data_array[i]);
}
// data is no more required, less cache miss when we just have to
// store the results
for (size_t j=0; j<current_data_results.size(); ++j)
result_array[j][i]=current_data_results[j];
}
}
}
void ComputationManager::compute_task_parallel_jobs()
{
// this is used when there are more number of jobs to be processed
// than there are data blocks
result_array.resize(job_array.size());
for (size_t j=0; j<job_array.size(); ++j)
result_array[j].resize(data_array.size());
if (gpu)
{
// TODO current_job_results = compute_job.compute_using_gpu(data_array);
}
else
{
#pragma omp parallel for
for (size_t j=0; j<job_array.size(); ++j)
{
const auto& compute_job=job_array[j];
// result_array[j][i] is contiguous, cache miss is minimized
for (size_t i=0; i<data_array.size(); ++i)
result_array[j][i]=compute_job(data_array[i]);
}
}
}
void ComputationManager::done()
{
job_array.resize(0);
result_array.resize(0);
}
std::vector<float64_t>& ComputationManager::result(index_t i)
{
return result_array[i];
}
ComputationManager& ComputationManager::use_gpu()
{
gpu=true;
return *this;
}
ComputationManager& ComputationManager::use_cpu()
{
gpu=false;
return *this;
}
<|endoftext|>
|
<commit_before>#include <msgpack.hpp>
#include <msgpack/fbuffer.hpp>
#include <msgpack/fbuffer.h>
#include <msgpack/zbuffer.hpp>
#include <gtest/gtest.h>
#include <string.h>
TEST(buffer, sbuffer)
{
msgpack::sbuffer sbuf;
sbuf.write("a", 1);
sbuf.write("a", 1);
sbuf.write("a", 1);
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
sbuf.clear();
sbuf.write("a", 1);
sbuf.write("a", 1);
sbuf.write("a", 1);
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
}
TEST(buffer, vrefbuffer)
{
msgpack::vrefbuffer vbuf;
vbuf.write("a", 1);
vbuf.write("a", 1);
vbuf.write("a", 1);
const struct iovec* vec = vbuf.vector();
size_t veclen = vbuf.vector_size();
msgpack::sbuffer sbuf;
for(size_t i=0; i < veclen; ++i) {
sbuf.write((const char*)vec[i].iov_base, vec[i].iov_len);
}
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
vbuf.clear();
vbuf.write("a", 1);
vbuf.write("a", 1);
vbuf.write("a", 1);
vec = vbuf.vector();
veclen = vbuf.vector_size();
sbuf.clear();
for(size_t i=0; i < veclen; ++i) {
sbuf.write((const char*)vec[i].iov_base, vec[i].iov_len);
}
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
}
TEST(buffer, zbuffer)
{
msgpack::zbuffer zbuf;
zbuf.write("a", 1);
zbuf.write("a", 1);
zbuf.write("a", 1);
zbuf.flush();
}
TEST(buffer, fbuffer)
{
FILE* file = tmpfile();
EXPECT_TRUE( file != NULL );
msgpack::fbuffer fbuf(file);
EXPECT_EQ(file, fbuf.file());
fbuf.write("a", 1);
fbuf.write("a", 1);
fbuf.write("a", 1);
fflush(file);
rewind(file);
for (size_t i=0; i < 3; ++i) {
int ch = fgetc(file);
EXPECT_TRUE(ch != EOF);
EXPECT_EQ('a', static_cast<char>(ch));
}
EXPECT_EQ(EOF, fgetc(file));
}
TEST(buffer, fbuffer_c)
{
FILE* file = tmpfile();
void* fbuf = (void*)file;
EXPECT_TRUE( file != NULL );
EXPECT_EQ(0, msgpack_fbuffer_write(fbuf, "a", 1));
EXPECT_EQ(0, msgpack_fbuffer_write(fbuf, "a", 1));
EXPECT_EQ(0, msgpack_fbuffer_write(fbuf, "a", 1));
fflush(file);
rewind(file);
for (size_t i=0; i < 3; ++i) {
int ch = fgetc(file);
EXPECT_TRUE(ch != EOF);
EXPECT_EQ('a', (char) ch);
}
EXPECT_EQ(EOF, fgetc(file));
}
<commit_msg>Add fclose to fbuffer's tests<commit_after>#include <msgpack.hpp>
#include <msgpack/fbuffer.hpp>
#include <msgpack/fbuffer.h>
#include <msgpack/zbuffer.hpp>
#include <gtest/gtest.h>
#include <string.h>
TEST(buffer, sbuffer)
{
msgpack::sbuffer sbuf;
sbuf.write("a", 1);
sbuf.write("a", 1);
sbuf.write("a", 1);
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
sbuf.clear();
sbuf.write("a", 1);
sbuf.write("a", 1);
sbuf.write("a", 1);
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
}
TEST(buffer, vrefbuffer)
{
msgpack::vrefbuffer vbuf;
vbuf.write("a", 1);
vbuf.write("a", 1);
vbuf.write("a", 1);
const struct iovec* vec = vbuf.vector();
size_t veclen = vbuf.vector_size();
msgpack::sbuffer sbuf;
for(size_t i=0; i < veclen; ++i) {
sbuf.write((const char*)vec[i].iov_base, vec[i].iov_len);
}
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
vbuf.clear();
vbuf.write("a", 1);
vbuf.write("a", 1);
vbuf.write("a", 1);
vec = vbuf.vector();
veclen = vbuf.vector_size();
sbuf.clear();
for(size_t i=0; i < veclen; ++i) {
sbuf.write((const char*)vec[i].iov_base, vec[i].iov_len);
}
EXPECT_EQ(3, sbuf.size());
EXPECT_TRUE( memcmp(sbuf.data(), "aaa", 3) == 0 );
}
TEST(buffer, zbuffer)
{
msgpack::zbuffer zbuf;
zbuf.write("a", 1);
zbuf.write("a", 1);
zbuf.write("a", 1);
zbuf.flush();
}
TEST(buffer, fbuffer)
{
FILE* file = tmpfile();
EXPECT_TRUE( file != NULL );
msgpack::fbuffer fbuf(file);
EXPECT_EQ(file, fbuf.file());
fbuf.write("a", 1);
fbuf.write("a", 1);
fbuf.write("a", 1);
fflush(file);
rewind(file);
for (size_t i=0; i < 3; ++i) {
int ch = fgetc(file);
EXPECT_TRUE(ch != EOF);
EXPECT_EQ('a', static_cast<char>(ch));
}
EXPECT_EQ(EOF, fgetc(file));
fclose(file);
}
TEST(buffer, fbuffer_c)
{
FILE* file = tmpfile();
void* fbuf = (void*)file;
EXPECT_TRUE( file != NULL );
EXPECT_EQ(0, msgpack_fbuffer_write(fbuf, "a", 1));
EXPECT_EQ(0, msgpack_fbuffer_write(fbuf, "a", 1));
EXPECT_EQ(0, msgpack_fbuffer_write(fbuf, "a", 1));
fflush(file);
rewind(file);
for (size_t i=0; i < 3; ++i) {
int ch = fgetc(file);
EXPECT_TRUE(ch != EOF);
EXPECT_EQ('a', (char) ch);
}
EXPECT_EQ(EOF, fgetc(file));
fclose(file);
}
<|endoftext|>
|
<commit_before><commit_msg>Added missing include<commit_after><|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.