text
stringlengths 54
60.6k
|
---|
<commit_before>#ifndef MP_INTRUSIVEPTR_HPP
#define MP_INTRUSIVEPTR_HPP
#include <boost/atomic.hpp>
// boost::intrusive_ptr but safe/atomic
template<typename T>
struct IntrusivePtr {
boost::atomic<T*> ptr;
IntrusivePtr(T* _p = NULL) : ptr(NULL) {
if(_p) {
intrusive_ptr_add_ref(_p);
ptr = _p;
}
}
IntrusivePtr(const IntrusivePtr& other) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
}
~IntrusivePtr() {
T* _p = ptr.exchange(NULL);
if(_p)
intrusive_ptr_release(_p);
}
IntrusivePtr& operator=(const IntrusivePtr& other) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
return *this;
}
T& operator*() const { return *ptr; }
T* operator->() const { return ptr; }
operator bool() const { return ptr; }
void swap(IntrusivePtr&& other) {
T* old = ptr.exchange(other.ptr);
other.ptr = old;
}
void reset(T* _p = NULL) {
swap(IntrusivePtr(_p));
}
};
#endif // INTRUSIVEPTR_HPP
<commit_msg>very stupid fix<commit_after>#ifndef MP_INTRUSIVEPTR_HPP
#define MP_INTRUSIVEPTR_HPP
#include <boost/atomic.hpp>
// boost::intrusive_ptr but safe/atomic
template<typename T>
struct IntrusivePtr {
boost::atomic<T*> ptr;
IntrusivePtr(T* _p = NULL) : ptr(NULL) {
if(_p) {
intrusive_ptr_add_ref(_p);
ptr = _p;
}
}
IntrusivePtr(const IntrusivePtr& other) : ptr(NULL) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
}
~IntrusivePtr() {
T* _p = ptr.exchange(NULL);
if(_p)
intrusive_ptr_release(_p);
}
IntrusivePtr& operator=(const IntrusivePtr& other) {
T* p = other.ptr.load();
swap(IntrusivePtr(p));
return *this;
}
T& operator*() const { return *ptr; }
T* operator->() const { return ptr; }
operator bool() const { return ptr; }
void swap(IntrusivePtr&& other) {
T* old = ptr.exchange(other.ptr);
other.ptr = old;
}
void reset(T* _p = NULL) {
swap(IntrusivePtr(_p));
}
};
#endif // INTRUSIVEPTR_HPP
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <gtest/gtest.h>
#include <autocheck/check.hpp>
#include <autocheck/sequence.hpp>
namespace ac = autocheck;
struct reverse_prop_t {
template <typename T>
bool operator() (const std::vector<T>& xs) const {
std::vector<T> ys(xs);
std::reverse(ys.begin(), ys.end());
std::reverse(ys.begin(), ys.end());
return xs == ys;
}
};
template <typename T>
void insert_sorted(const T& x, std::vector<T>& xs) {
xs.push_back(x);
if (xs.size() == 1) return;
for (std::vector<int>::reverse_iterator
b = xs.rbegin(), a = b++, e = xs.rend(); (b != e) && (*a < *b); ++b, ++a)
{
std::iter_swap(a, b);
}
}
template <typename T>
T copy(const T& t) { return t; }
TEST(Check, Compiles) {
ac::gtest_reporter rep;
ac::check<bool>(100, [] (bool x) { return true; },
ac::make_arbitrary<bool>(), copy(rep));
ac::check<int>(100, [] (int x) { return x >= 0; },
ac::make_arbitrary<int>(), copy(rep));
//ac::check<bool>(100, [] (bool x) { return true; }); // ICEs Clang
reverse_prop_t reverse_prop;
ac::check<std::vector<int>>(100, reverse_prop,
ac::make_arbitrary(ac::list_of<int>()), copy(rep));
ac::check<std::vector<int>>(100, reverse_prop,
ac::make_arbitrary(ac::cons<std::vector<int>, unsigned int, int>()),
copy(rep));
ac::check<std::vector<char>>(100, reverse_prop,
ac::make_arbitrary(ac::list_of<char>()), copy(rep));
ac::check<std::vector<std::string>>(100, reverse_prop,
ac::make_arbitrary(ac::list_of<std::string>()), copy(rep));
//std::function<bool (const std::string&)> print_prop =
//[] (const std::string& x) { return !!(std::clog << x << std::endl); };
//ac::check<std::string>(100, print_prop,
//ac::make_arbitrary<std::string>(), copy(rep));
//ac::check<std::string>(100, print_prop,
//ac::make_arbitrary(ac::make_string_generator<ac::ccPrintable>()),
//copy(rep));
/* Chaining... */
//auto arb = ac::make_arbitrary(ac::generator<int>(), ac::ordered_list<int>())
//.only_if([] (int, const std::vector<int>& xs) -> bool { return std::is_sorted(xs.begin(), xs.end()); })
//.at_most(100);
/* ..., or combinators. */
auto arb =
ac::at_most(100,
ac::only_if([] (int, const std::vector<int>& xs) -> bool { return std::is_sorted(xs.begin(), xs.end()); },
ac::make_arbitrary(ac::generator<int>(), ac::ordered_list<int>())));
//ac::make_arbitrary(ac::generator<int>(), ac::list_of<int>())));
ac::classifier<int, std::vector<int>> cls;
cls.trivial([] (int, const std::vector<int>& xs) { return xs.empty(); });
cls.classify(
[] (int x, const std::vector<int>& xs) -> std::string {
std::ostringstream out;
out << xs.size();
return out.str();
});
cls.classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (x < xs.front()); }, "at-head");
cls.classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (xs.front() < x); }, "at-tail");
/* Can't use combinators here because it breaks template deduction (?). */
//auto cls =
//ac::trivial([] (int, const std::vector<int>& xs) { return xs.empty(); },
//ac::classify(
//[] (int x, const std::vector<int>& xs) -> std::string {
//std::ostringstream out;
//out << xs.size();
//return out.str();
//},
//ac::classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (x < xs.front()); }, "at-head",
//ac::classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (xs.back() < x); }, "at-tail",
//ac::classifier<int, const std::vector<int>>()))));
ac::check<int, std::vector<int>>(100,
[] (int x, const std::vector<int>& xs) -> bool {
std::vector<int> ys(xs);
insert_sorted(x, ys);
return std::is_sorted(ys.begin(), ys.end());
},
copy(arb), copy(rep), copy(cls));
}
<commit_msg>better examples<commit_after>#include <algorithm>
#include <gtest/gtest.h>
#include <autocheck/check.hpp>
#include <autocheck/sequence.hpp>
namespace ac = autocheck;
struct reverse_prop_t {
template <typename T>
bool operator() (const std::vector<T>& xs) const {
std::vector<T> ys(xs);
std::reverse(ys.begin(), ys.end());
std::reverse(ys.begin(), ys.end());
return xs == ys;
}
};
template <typename T>
void insert_sorted(const T& x, std::vector<T>& xs) {
xs.push_back(x);
if (xs.size() == 1) return;
for (std::vector<int>::reverse_iterator
b = xs.rbegin(), a = b++, e = xs.rend(); (b != e) && (*a < *b); ++b, ++a)
{
std::iter_swap(a, b);
}
}
template <typename T>
T copy(const T& t) { return t; }
TEST(Check, Compiles) {
ac::gtest_reporter rep;
ac::check<bool>(100, [] (bool x) { return true; },
ac::make_arbitrary<bool>(), copy(rep));
ac::check<int>(100, [] (int x) { return x >= 0; },
ac::make_arbitrary<int>(), copy(rep));
//ac::check<bool>(100, [] (bool x) { return true; }); // ICEs Clang
reverse_prop_t reverse_prop;
ac::check<std::vector<int>>(100, reverse_prop,
ac::make_arbitrary(ac::list_of<int>()), copy(rep));
ac::check<std::vector<int>>(100, reverse_prop,
ac::make_arbitrary(ac::cons<std::vector<int>, unsigned int, int>()),
copy(rep));
ac::check<std::vector<char>>(100, reverse_prop,
ac::make_arbitrary(ac::list_of<char>()), copy(rep));
ac::check<std::vector<std::string>>(100, reverse_prop,
ac::make_arbitrary(ac::list_of<std::string>()), copy(rep));
//std::function<bool (const std::string&)> print_prop =
//[] (const std::string& x) { return !!(std::clog << x << std::endl); };
//ac::check<std::string>(100, print_prop,
//ac::make_arbitrary<std::string>(), copy(rep));
//ac::check<std::string>(100, print_prop,
//ac::make_arbitrary(ac::make_string_generator<ac::ccPrintable>()),
//copy(rep));
/* Chaining, ... */
//auto arb = ac::make_arbitrary(ac::generator<int>(), ac::ordered_list<int>())
//.only_if([] (int, const std::vector<int>& xs) -> bool { return std::is_sorted(xs.begin(), xs.end()); })
//.at_most(100);
/* ... or combinators. */
auto arb =
ac::at_most(100,
ac::only_if([] (int, const std::vector<int>& xs) -> bool { return std::is_sorted(xs.begin(), xs.end()); },
//ac::make_arbitrary(ac::generator<int>(), ac::ordered_list<int>())));
ac::make_arbitrary(ac::generator<int>(), ac::list_of<int>())));
ac::classifier<int, std::vector<int>> cls;
cls.trivial([] (int, const std::vector<int>& xs) { return xs.empty(); });
cls.classify(
[] (int x, const std::vector<int>& xs) -> std::string {
std::ostringstream out;
out << xs.size();
return out.str();
});
cls.classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (x < xs.front()); }, "at-head");
cls.classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (xs.front() < x); }, "at-tail");
/* Can't use combinators here because it breaks template deduction (?). */
//auto cls =
//ac::trivial([] (int, const std::vector<int>& xs) { return xs.empty(); },
//ac::classify(
//[] (int x, const std::vector<int>& xs) -> std::string {
//std::ostringstream out;
//out << xs.size();
//return out.str();
//},
//ac::classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (x < xs.front()); }, "at-head",
//ac::classify([] (int x, const std::vector<int>& xs) { return xs.empty() || (xs.back() < x); }, "at-tail",
//ac::classifier<int, const std::vector<int>>()))));
ac::check<int, std::vector<int>>(100,
[] (int x, const std::vector<int>& xs) -> bool {
std::vector<int> ys(xs);
insert_sorted(x, ys);
return std::is_sorted(ys.begin(), ys.end());
},
copy(arb), copy(rep), copy(cls));
}
<|endoftext|>
|
<commit_before>#include <Kernel/Scheduler.hh>
#include <Kernel/Thread.hh>
#include <X86/ThreadContext.hh>
#include <Parameters.hh>
#include <Debug.hh>
#include <spinlock.h>
#include <list>
#include <cstdio>
using namespace Kernel;
namespace
{
spinlock_softirq_t threadLock = SPINLOCK_SOFTIRQ_STATIC_INITIALIZER;
std::list<Thread*>&
getThreadList()
{
static std::list<Thread*> threadList;
return threadList;
}
};
unsigned long Thread::nextThreadId = 1;
Thread::Thread(Thread::Type type)
: idM(-1ul),
userStackM(0),
kernelStackM(0),
stateM(New),
typeM(type),
processM(0),
nextM(0),
onCpuM(0)
{
if (type == Thread::Type::UserThread)
{
Debug::verbose("Creating user thread...\n");
}
else
{
Debug::verbose("Creating thread...\n");
}
}
Thread::~Thread()
{
// XXX free stack space!
printf("Deleteing thread: %p...\n", this);
Scheduler::remove(this);
}
// used when creating thread 0
bool
Thread::init0(uintptr_t stack)
{
idM = 0;
kernelStackM = stack;
processM = Scheduler::getKernelProcess();
Debug::verbose("Initializing idle thread (thread0): %p...\n", (void*)stack);
getThreadList().push_back(this);
nameM = "idle";
return true;
}
bool
Thread::init()
{
if (typeM == Thread::Type::UserThread)
{
Debug::verbose("Initializing user thread %p...\n", this);
}
else
{
Debug::verbose("Initializing kernel thread %p...\n", this);
}
spinlock_softirq_enter(&threadLock);
KASSERT(nextThreadId != 0);
idM = nextThreadId++;
bool success = Memory::createKernelStack(kernelStackM);
if (!success)
{
spinlock_softirq_exit(&threadLock);
return false;
}
if (typeM == UserThread)
{
userStackM = UserStackStart;
kernelStackM = ThreadContext::initUserStack(kernelStackM,
CodeStart,
0xdeadbabe);
// memcpy((void*)CodeStart, "\xb8\xfa\x00\x00\x10\x00\xe0\xff", 8);
}
else
{
kernelStackM = ThreadContext::initKernelStack(kernelStackM,
reinterpret_cast<uintptr_t>(&Thread::main),
reinterpret_cast<uintptr_t>(this));
}
spinlock_softirq_exit(&threadLock);
Debug::verbose("Thread's new kernel stack is %p\n", (void*)kernelStackM);
Scheduler::insert(this);
getThreadList().push_back(this);
return success;
}
bool
Thread::addJob(const std::function<void()>& task)
{
Debug::verbose("Thread::addJob\n");
jobsM.emplace(task);
return true;
}
const char* threadType[] =
{
"User",
"Kernel",
"Interrupt"
};
const char* threadState[] =
{
"New",
"Idle",
"Ready",
"Running",
"Agony",
"Dead"
};
void
Thread::dump()
{
printf(" %lu\t%p\t%p\t%s\t%s\t%lu\t%s\n", idM, (void *)kernelStackM,
(void*)userStackM, threadState[stateM], threadType[typeM],
onCpuM, nameM.c_str());
}
void
Thread::printAll()
{
printf(" id\tkstack\t\tustack\t\tstate\ttype\toncpu\tname\n");
for (auto& t : getThreadList())
{
t->dump();
}
}
void
Thread::main(Thread* thread)
{
printf("Thread main called on %p (%p)!\n", thread, &thread);
thread->stateM = Ready;
for (;;)
{
if (thread->stateM == Ready)
{
thread->stateM = Running;
while (!thread->jobsM.empty())
{
printf("Running job\n");
Job job = thread->jobsM.back();
thread->jobsM.pop();
job.execute();
}
}
else if (thread->stateM == Agony)
{
printf("Thread %p is exiting...\n", thread);
thread->stateM = Dead;
for (;;)
{
// wait for destruction
asm volatile("pause");
}
}
thread->stateM = Idle;
}
}
Thread*
Thread::createKernelThread(const char* name)
{
Thread* thread = new Thread(Type::KernelThread);
thread->processM = Scheduler::getKernelProcess();
thread->setName(name);
thread->init();
printf("Kernel thread created: %s\n", name);
return thread;
}
Thread*
Thread::createKernelThread()
{
char threadName[32];
Thread* thread = new Thread(Type::KernelThread);
thread->processM = Scheduler::getKernelProcess();
thread->init();
// XXX should be done before init, but init gaves a thread an id
int len = snprintf(threadName, sizeof(threadName), "KernelThread-%lu", thread->getId());
KASSERT(len < (int)sizeof(threadName));
thread->setName(threadName);
printf("Kernel thread created: %s\n", threadName);
return thread;
}
Thread*
Thread::createUserThread(Process* process)
{
Thread* thread = new Thread(Type::UserThread);
thread->processM = process;
thread->init();
return thread;
}
unsigned long
Thread::getId() const
{
return idM;
}
void
Thread::setName(const char* name)
{
nameM = std::string(name);
}
std::string
Thread::getName() const
{
return nameM;
}
uintptr_t
Thread::getKernelStack() const
{
return kernelStackM;
}
void
Thread::setKernelStack(uintptr_t stack)
{
kernelStackM = stack;
}
uintptr_t
Thread::getUserStack() const
{
return userStackM;
}
void
Thread::setUserStack(uintptr_t stack)
{
userStackM = stack;
}
Thread::Type
Thread::getType() const
{
return typeM;
}
Process*
Thread::getProcess() const
{
return processM;
}
void
Thread::setRunning()
{
stateM = Running;
onCpuM++;
}
void
Thread::setReady()
{
stateM = Ready;
}
<commit_msg>Add missing locks<commit_after>#include <Kernel/Scheduler.hh>
#include <Kernel/Thread.hh>
#include <X86/ThreadContext.hh>
#include <Parameters.hh>
#include <Debug.hh>
#include <spinlock.h>
#include <list>
#include <cstdio>
using namespace Kernel;
namespace
{
spinlock_softirq_t threadLock = SPINLOCK_SOFTIRQ_STATIC_INITIALIZER;
std::list<Thread*>&
getThreadList()
{
static std::list<Thread*> threadList;
return threadList;
}
};
unsigned long Thread::nextThreadId = 1;
Thread::Thread(Thread::Type type)
: idM(-1ul),
userStackM(0),
kernelStackM(0),
stateM(New),
typeM(type),
processM(0),
nextM(0),
onCpuM(0)
{
if (type == Thread::Type::UserThread)
{
Debug::verbose("Creating user thread...\n");
}
else
{
Debug::verbose("Creating thread...\n");
}
}
Thread::~Thread()
{
// XXX free stack space!
printf("Deleteing thread: %p...\n", this);
Scheduler::remove(this);
}
// used when creating thread 0
bool
Thread::init0(uintptr_t stack)
{
idM = 0;
kernelStackM = stack;
processM = Scheduler::getKernelProcess();
Debug::verbose("Initializing idle thread (thread0): %p...\n", (void*)stack);
spinlock_softirq_enter(&threadLock);
getThreadList().push_back(this);
spinlock_softirq_exit(&threadLock);
nameM = "idle";
return true;
}
bool
Thread::init()
{
if (typeM == Thread::Type::UserThread)
{
Debug::verbose("Initializing user thread %p...\n", this);
}
else
{
Debug::verbose("Initializing kernel thread %p...\n", this);
}
spinlock_softirq_enter(&threadLock);
KASSERT(nextThreadId != 0);
idM = nextThreadId++;
bool success = Memory::createKernelStack(kernelStackM);
if (!success)
{
spinlock_softirq_exit(&threadLock);
return false;
}
if (typeM == UserThread)
{
userStackM = UserStackStart;
kernelStackM = ThreadContext::initUserStack(kernelStackM,
CodeStart,
0xdeadbabe);
// memcpy((void*)CodeStart, "\xb8\xfa\x00\x00\x10\x00\xe0\xff", 8);
}
else
{
kernelStackM = ThreadContext::initKernelStack(kernelStackM,
reinterpret_cast<uintptr_t>(&Thread::main),
reinterpret_cast<uintptr_t>(this));
}
spinlock_softirq_exit(&threadLock);
Debug::verbose("Thread's new kernel stack is %p\n", (void*)kernelStackM);
Scheduler::insert(this);
spinlock_softirq_enter(&threadLock);
getThreadList().push_back(this);
spinlock_softirq_exit(&threadLock);
return success;
}
bool
Thread::addJob(const std::function<void()>& task)
{
Debug::verbose("Thread::addJob\n");
lockM.enter();
jobsM.emplace(task);
lockM.exit();
return true;
}
const char* threadType[] =
{
"User",
"Kernel",
"Interrupt"
};
const char* threadState[] =
{
"New",
"Idle",
"Ready",
"Running",
"Agony",
"Dead"
};
void
Thread::dump()
{
printf(" %lu\t%p\t%p\t%s\t%s\t%lu\t%s\n", idM, (void *)kernelStackM,
(void*)userStackM, threadState[stateM], threadType[typeM],
onCpuM, nameM.c_str());
}
void
Thread::printAll()
{
printf(" id\tkstack\t\tustack\t\tstate\ttype\toncpu\tname\n");
spinlock_softirq_enter(&threadLock);
for (auto& t : getThreadList())
{
t->dump();
}
spinlock_softirq_exit(&threadLock);
}
void
Thread::main(Thread* thread)
{
printf("Thread main called on %p (%p)!\n", thread, &thread);
thread->stateM = Ready;
for (;;)
{
if (thread->stateM == Ready)
{
thread->stateM = Running;
thread->lockM.enter();
while (!thread->jobsM.empty())
{
printf("Running job\n");
Job job = thread->jobsM.back();
thread->jobsM.pop();
thread->lockM.exit();
job.execute();
thread->lockM.enter();
}
thread->lockM.exit();
}
else if (thread->stateM == Agony)
{
printf("Thread %p is exiting...\n", thread);
thread->stateM = Dead;
for (;;)
{
// wait for destruction
asm volatile("pause");
}
}
thread->stateM = Idle;
}
}
Thread*
Thread::createKernelThread(const char* name)
{
Thread* thread = new Thread(Type::KernelThread);
thread->processM = Scheduler::getKernelProcess();
thread->setName(name);
thread->init();
printf("Kernel thread created: %s\n", name);
return thread;
}
Thread*
Thread::createKernelThread()
{
char threadName[32];
Thread* thread = new Thread(Type::KernelThread);
thread->processM = Scheduler::getKernelProcess();
thread->init();
// XXX should be done before init, but init gaves a thread an id
int len = snprintf(threadName, sizeof(threadName), "KernelThread-%lu", thread->getId());
KASSERT(len < (int)sizeof(threadName));
thread->setName(threadName);
printf("Kernel thread created: %s\n", threadName);
return thread;
}
Thread*
Thread::createUserThread(Process* process)
{
Thread* thread = new Thread(Type::UserThread);
thread->processM = process;
thread->init();
return thread;
}
unsigned long
Thread::getId() const
{
return idM;
}
void
Thread::setName(const char* name)
{
nameM = std::string(name);
}
std::string
Thread::getName() const
{
return nameM;
}
uintptr_t
Thread::getKernelStack() const
{
return kernelStackM;
}
void
Thread::setKernelStack(uintptr_t stack)
{
kernelStackM = stack;
}
uintptr_t
Thread::getUserStack() const
{
return userStackM;
}
void
Thread::setUserStack(uintptr_t stack)
{
userStackM = stack;
}
Thread::Type
Thread::getType() const
{
return typeM;
}
Process*
Thread::getProcess() const
{
return processM;
}
void
Thread::setRunning()
{
stateM = Running;
onCpuM++;
}
void
Thread::setReady()
{
stateM = Ready;
}
<|endoftext|>
|
<commit_before>#include "Pong.h"
#include "ConsoleGaming.h"
#include "Vector2D.h"
#include "Paddle.h"
using namespace std;
HANDLE consoleHandle;
typedef vector<GameObject>::iterator randomAccess_iterator;
typedef vector<GameObject>::const_iterator const_iterator;
// Window constants
const int WindowWidth = 70;
const int WindowHeight = 30;
const int CharWidth = 9;
const int CharHeight = 15;
Vector2D ballSpeed = Vector2D(1, 1);
int playerScore = 0;
int enemyScore = 0;
// Paddle variables
const int PaddleLength = 5;
//const float deflectionCoefficient;
int paddleSpeed = 1;
int player2PaddleSpeed = 1;
// Game variables
unsigned long sleepDuration = 70;
GameState gameState;
map<ControlNames, char> controls;
//AI
bool Smart = false;
bool Multiplayer = false;
bool EpilepsyMode = false;
vector<Paddle> paddles;
GameObject ball(WindowWidth / 2, WindowHeight / 2, '#');
void HandleInput(COORD &player1Direction, COORD &player2Direction)
{
if (_kbhit())
{
char key = _getch();
//make sure controls work with shift/CAPS LOCK
if(key >= 'A' && key <= 'Z')
key -= 'A' - 'a';
switch (gameState)
{
case Menu:
if(key == controls[MenuSingleplayer])
{
Multiplayer = false;
gameState = Playing;
} else if(key == controls[MenuMultiplayer]) {
Multiplayer = true;
gameState = Playing;
} else if(key == controls[MenuSettings]) {
gameState = Settings;
} else if(key == controls[MenuHighscore]) {
//TODO
} else if(key == controls[MenuAbout]) {
//TODO
} else if(key == controls[MenuExit]) {
exit(0);
}
break;
case Playing:
case Paused:
if(key == controls[PaddleUp1])
{
player1Direction.Y = -paddleSpeed;
} else if(key == controls[PaddleDown1]) {
player1Direction.Y = paddleSpeed;
} else if(key == controls[PaddleUp2]) {
player2Direction.Y = -player2PaddleSpeed;
} else if(key == controls[PaddleDown2]) {
player2Direction.Y = player2PaddleSpeed;
} else if(key == controls[Pause]) {
if(gameState == Playing)
gameState = Paused;
else if(gameState == Paused)
gameState = Playing;
}
break;
case Settings:
if(key == controls[SettingsSmart])
{
Smart = true;
} else if(key == controls[SettingsStupid]) {
Smart = false;
} else if(key == controls[SettingsToMainMenu]) {
gameState = Menu;
} else if(key == controls[SettingsSinglePlayer]) {
Multiplayer = false;
} else if(key == controls[SettingsMultiplayer]) {
Multiplayer = true;
} else if(key == controls[SettingsStart]) {
gameState = Playing;
} else if(key == controls[SettingsEpilepsy]) {
if(!EpilepsyMode)
EpilepsyMode = true;
else
EpilepsyMode = false;
}
break;
}
}
}
void HandleAI(COORD &enemyDirection, int paddleIndex)
{
if(Smart)
{
enemyDirection.Y = ball.Coordinates.Y > paddles[paddleIndex].position.Y ? paddleSpeed : -paddleSpeed;
} else {
enemyDirection.Y = rand()%100 > 50 ? paddleSpeed : -paddleSpeed;
}
}
void HandleCollision()
{
typedef vector<Paddle>::iterator vector_iterator;
for (vector_iterator paddle = paddles.begin(); paddle != paddles.end(); ++paddle)
{
for (randomAccess_iterator paddlePart = paddle->elements.begin(); paddlePart != paddle->elements.end(); ++paddlePart)
{
if(((ball.Coordinates.X == paddlePart->Coordinates.X + 1)||(ball.Coordinates.X == paddlePart->Coordinates.X - 1)))
{
if(ball.Coordinates.Y == paddlePart->Coordinates.Y)
{
ballSpeed.x = -ballSpeed.x;
}
}
}
}
}
void Update()
{
vector<COORD> directions;
directions.resize(paddles.size());
HandleInput(directions[0], directions[1]);
if(gameState == Playing)
{
if(!Multiplayer)
for(int i = 1;i < paddles.size();i++)
HandleAI(directions[i], i);
HandleCollision();
typedef vector<vector<GameObject>>::iterator vector_iterator;
//Handle any and all paddles
for(int i = 0;i < paddles.size();i++)
{
for (randomAccess_iterator paddleElement = paddles[i].elements.begin(); paddleElement != paddles[i].elements.end(); ++paddleElement)//check if paddle can move
{
if((paddleElement->Coordinates.Y >= WindowHeight && directions[i].Y > 0) || (paddleElement->Coordinates.Y <= 1) && directions[i].Y < 0)
{
directions[i].Y = 0;
}
}
paddles[i].position.X += directions[i].X;
paddles[i].position.Y += directions[i].Y;
for (randomAccess_iterator paddleElement = paddles[i].elements.begin(); paddleElement != paddles[i].elements.end(); ++paddleElement)//actually move it
{
paddleElement->Coordinates.X += directions[i].X;
paddleElement->Coordinates.Y += directions[i].Y;
}
}
//Ball movement
ball.Coordinates.X += (SHORT)ballSpeed.x;
if (ball.Coordinates.X >= WindowWidth - 1 || ball.Coordinates.X <= 0)
{
ballSpeed.x = -ballSpeed.x;
}
ball.Coordinates.Y += (SHORT)ballSpeed.y;
if (ball.Coordinates.Y >= WindowHeight || ball.Coordinates.Y <= 1)
{
ballSpeed.y = -ballSpeed.y;
}
}
if(EpilepsyMode)
{
int randomizer = 0;
randomizer = rand() % 10 + 1;
switch (randomizer)
{
case 1:
system("Color 01");
case 2:
system("Color A2");
case 3:
system("Color B3");
case 4:
system("Color 24");
case 5:
system("Color 75");
case 6:
system("Color E6");
case 7:
system("Color 07");
case 8:
system("Color 0A");
case 9:
system("Color 0B");
case 10:
system("Color 0C");
default:
system("Color 0F");
}
}
if(ball.Coordinates.X == 0)
{
enemyScore += 1;
ball.Coordinates.X = WindowWidth / 2;
ball.Coordinates.Y = WindowHeight / 2;
}
else if(ball.Coordinates.X == WindowWidth - 1)
{
playerScore += 1;
ball.Coordinates.X = WindowWidth / 2;
ball.Coordinates.Y = WindowHeight / 2;
}
}
void DrawPaddles()
{
typedef vector<Paddle>::iterator vector_iterator;
for (vector_iterator paddle = paddles.begin(); paddle != paddles.end(); ++paddle)
{
for (randomAccess_iterator paddlePart = paddle->elements.begin(); paddlePart != paddle->elements.end(); ++paddlePart)
{
paddlePart->Draw(consoleHandle);
}
}
}
void DrawMenu()
{
cout << MenuString << endl;
}
void DrawScore()
{
cout << Boundaries << endl;
cout << "Score: " << playerScore << "|" << enemyScore << endl;
}
void DrawSettings()
{
cout << SettingsString << endl;
}
void Draw()
{
ball.Color = ConsoleColors::Yellow;
ClearScreen(consoleHandle);
switch (gameState)
{
case Menu:
DrawMenu();
break;
case Settings:
DrawSettings();
break;
case Paused:
case Playing:
DrawScore();
DrawPaddles();
ball.Draw(consoleHandle);
break;
default:
break;
}
}
void SetupControls()
{
controls[PaddleDown1] = 's';
controls[PaddleUp1] = 'w';
controls[PaddleDown2] = 'k';
controls[PaddleUp2] = 'i';
controls[Pause] = 'p';
controls[MenuSingleplayer] = 's';
controls[MenuMultiplayer] = 'm';
controls[MenuSettings] = 't';
controls[MenuHighscore] = 'h';
controls[MenuAbout] = 'a';
controls[MenuExit] = 'e';
controls[SettingsSmart] = 's';
controls[SettingsStupid] = 't';
controls[SettingsToMainMenu] = 'q';
controls[SettingsSinglePlayer] = 'p';
controls[SettingsMultiplayer] = 'm';
controls[SettingsStart] = 'n';
controls[SettingsEpilepsy] = 'e';
};
int main()
{
PlaySound(TEXT("pong_OST.wav"), NULL, SND_ASYNC|SND_FILENAME|SND_LOOP);
InitScreen(WindowWidth*CharWidth, WindowHeight*CharHeight);
consoleHandle = GetStdHandle( STD_OUTPUT_HANDLE );
SetupControls();
gameState = Menu;
srand((unsigned int)time(NULL));
Paddle leftPaddle, rightPaddle;
int paddleStartingPos = WindowHeight / 2 - PaddleLength / 2;
leftPaddle.position.X = 0;
leftPaddle.position.Y = paddleStartingPos;
rightPaddle.position.X = WindowWidth - 1;
rightPaddle.position.Y = paddleStartingPos;
for (int i = 0; i < PaddleLength; ++i)
{
leftPaddle.elements.push_back(GameObject(leftPaddle.position.X, paddleStartingPos + i, '$'));
rightPaddle.elements.push_back(GameObject(rightPaddle.position.X, paddleStartingPos + i, '*'));
}
paddles.push_back(leftPaddle);
paddles.push_back(rightPaddle);
while (true)
{
Update();
Draw();
Sleep(sleepDuration);
}
return 0;
}<commit_msg>Added hyper-realistic HD ball movement using advanced kinematic analysis<commit_after>#include "Pong.h"
#include "ConsoleGaming.h"
#include "Vector2D.h"
#include "Paddle.h"
using namespace std;
HANDLE consoleHandle;
typedef vector<GameObject>::iterator randomAccess_iterator;
typedef vector<GameObject>::const_iterator const_iterator;
// Window constants
const int WindowWidth = 70;
const int WindowHeight = 30;
const int CharWidth = 9;
const int CharHeight = 15;
Vector2D ballSpeed = Vector2D(1, 1);
Vector2D ballPosition = Vector2D(WindowWidth / 2, WindowHeight / 2);
int playerScore = 0;
int enemyScore = 0;
// Paddle variables
const int PaddleLength = 5;
int paddleSpeed = 2;
int player2PaddleSpeed = 2;
// Game variables
unsigned long sleepDuration = 70;
GameState gameState;
map<ControlNames, char> controls;
const float DeflectionAmount = 0.3f;
const float BallSpeedIncrease = 0.2f;
//AI
bool Smart = false;
bool Multiplayer = false;
bool EpilepsyMode = false;
bool MultiplayerArrowKeys = true;
vector<Paddle> paddles;
GameObject ball(WindowWidth / 2, WindowHeight / 2, '#');
void HandleInput(COORD &player1Direction, COORD &player2Direction)
{
if (_kbhit())
{
char key = _getch();
//cout << (int)key << " ";
//make sure controls work with shift/CAPS LOCK
if(key >= 'A' && key <= 'Z')
key -= 'A' - 'a';
switch (gameState)
{
case Menu:
if(key == controls[MenuSingleplayer])
{
Multiplayer = false;
gameState = Playing;
} else if(key == controls[MenuMultiplayer]) {
Multiplayer = true;
gameState = Playing;
} else if(key == controls[MenuSettings]) {
gameState = Settings;
} else if(key == controls[MenuHighscore]) {
//TODO
} else if(key == controls[MenuAbout]) {
//TODO
} else if(key == controls[MenuExit]) {
exit(0);
}
break;
case Playing:
case Paused:
if(key == controls[PaddleUp1])
{
player1Direction.Y = -paddleSpeed;
} else if(key == controls[PaddleDown1]) {
player1Direction.Y = paddleSpeed;
} else if(key == controls[PaddleUp2]) {
player2Direction.Y = -player2PaddleSpeed;
} else if(key == controls[PaddleDown2]) {
player2Direction.Y = player2PaddleSpeed;
} else if(key == controls[Pause]) {
if(gameState == Playing)
gameState = Paused;
else if(gameState == Paused)
gameState = Playing;
} else if((key == 0 || key == 224) && MultiplayerArrowKeys) {//0x00 and 0xE0, first half of arrow keys code
key = _getch();
if(key == 72)//up
{
player2Direction.Y = -player2PaddleSpeed;
} else if(key == 80) {//down
player2Direction.Y = player2PaddleSpeed;
}
}
break;
case Settings:
if(key == controls[SettingsSmart])
{
Smart = true;
} else if(key == controls[SettingsStupid]) {
Smart = false;
} else if(key == controls[SettingsToMainMenu]) {
gameState = Menu;
} else if(key == controls[SettingsSinglePlayer]) {
Multiplayer = false;
} else if(key == controls[SettingsMultiplayer]) {
Multiplayer = true;
} else if(key == controls[SettingsStart]) {
gameState = Playing;
} else if(key == controls[SettingsEpilepsy]) {
EpilepsyMode = !EpilepsyMode;
}
break;
}
}
}
void HandleAI(COORD &enemyDirection, int paddleIndex)
{
if(Smart)
{
enemyDirection.Y = ballPosition.y > paddles[paddleIndex].position.Y ? paddleSpeed : -paddleSpeed;
} else {
enemyDirection.Y = rand()%100 > 50 ? paddleSpeed : -paddleSpeed;
}
}
void HandleCollision()
{
typedef vector<Paddle>::iterator vector_iterator;
for (vector_iterator paddle = paddles.begin(); paddle != paddles.end(); ++paddle)
{
if((((SHORT)(ballPosition.x + ballSpeed.x) == paddle->position.X)||((SHORT)(ballPosition.x + ballSpeed.x) == paddle->position.X)))
{
for (randomAccess_iterator paddlePart = paddle->elements.begin(); paddlePart != paddle->elements.end(); ++paddlePart)
{
if((SHORT)ballPosition.y == paddlePart->Coordinates.Y + paddle->position.Y)
{
float oldLen = ballSpeed.Length();
oldLen += BallSpeedIncrease;
ballSpeed.x = -ballSpeed.x;
ballSpeed.y += paddlePart->Coordinates.Y *DeflectionAmount;
ballSpeed = ballSpeed.Normalize()*oldLen;
}
}
}
}
}
void Update()
{
vector<COORD> directions;
directions.resize(paddles.size());
HandleInput(directions[0], directions[1]);
if(gameState == Playing)
{
if(!Multiplayer)
for(int i = 1;i < paddles.size();i++)
HandleAI(directions[i], i);
HandleCollision();
typedef vector<vector<GameObject>>::iterator vector_iterator;
//Handle any and all paddles
for(int i = 0;i < paddles.size();i++)
{
for (randomAccess_iterator paddleElement = paddles[i].elements.begin(); paddleElement != paddles[i].elements.end(); ++paddleElement)//check if paddle can move
{
if((paddleElement->Coordinates.Y + paddles[i].position.Y >= WindowHeight && directions[i].Y > 0) || (paddleElement->Coordinates.Y + paddles[i].position.Y <= 1) && directions[i].Y < 0)
{
directions[i].Y = 0;
}
}
paddles[i].position.X += directions[i].X;
paddles[i].position.Y += directions[i].Y;
}
//Ball movement
ballPosition.x += ballSpeed.x;
if (ballPosition.x >= WindowWidth - 1 || ballPosition.x <= 0)
{
ballSpeed.x = -ballSpeed.x;
}
ballPosition.y += ballSpeed.y;
if (ballPosition.y >= WindowHeight || ballPosition.y <= 1)
{
ballSpeed.y = -ballSpeed.y;
}
}
if(EpilepsyMode)
{
int randomizer = 0;
randomizer = rand() % 10 + 1;
switch (randomizer)
{
case 1:
system("Color 01");
case 2:
system("Color A2");
case 3:
system("Color B3");
case 4:
system("Color 24");
case 5:
system("Color 75");
case 6:
system("Color E6");
case 7:
system("Color 07");
case 8:
system("Color 0A");
case 9:
system("Color 0B");
case 10:
system("Color 0C");
default:
system("Color 0F");
}
}
if(ball.Coordinates.X <= 0)
{
enemyScore += 1;
ballPosition.x = WindowWidth / 2;
ballPosition.y = WindowHeight / 2;
ballSpeed = Vector2D(1, 1);
}
else if(ball.Coordinates.X >= WindowWidth - 1)
{
playerScore += 1;
ballPosition.x = WindowWidth / 2;
ballPosition.y = WindowHeight / 2;
ballSpeed = Vector2D(1, 1);
}
}
void DrawPaddles()
{
typedef vector<Paddle>::iterator vector_iterator;
for (vector_iterator paddle = paddles.begin(); paddle != paddles.end(); ++paddle)
{
for (randomAccess_iterator paddlePart = paddle->elements.begin(); paddlePart != paddle->elements.end(); ++paddlePart)
{
paddlePart->Coordinates.Y += paddle->position.Y;
paddlePart->Draw(consoleHandle);
paddlePart->Coordinates.Y -= paddle->position.Y;
}
}
}
void DrawMenu()
{
cout << MenuString << endl;
}
void DrawScore()
{
cout << Boundaries << endl;
cout << "Score: " << playerScore << "|" << enemyScore << endl;
}
void DrawSettings()
{
cout << SettingsString << endl;
}
void Draw()
{
ball.Color = ConsoleColors::Yellow;
ClearScreen(consoleHandle);
switch (gameState)
{
case Menu:
DrawMenu();
break;
case Settings:
DrawSettings();
break;
case Paused:
case Playing:
DrawScore();
DrawPaddles();
ball.Coordinates.X = (SHORT)ballPosition.x;
ball.Coordinates.Y = (SHORT)ballPosition.y;
ball.Draw(consoleHandle);
break;
default:
break;
}
}
void SetupControls()
{
controls[PaddleDown1] = 's';
controls[PaddleUp1] = 'w';
controls[PaddleDown2] = 'k';
controls[PaddleUp2] = 'i';
controls[Pause] = 'p';
controls[MenuSingleplayer] = 's';
controls[MenuMultiplayer] = 'm';
controls[MenuSettings] = 't';
controls[MenuHighscore] = 'h';
controls[MenuAbout] = 'a';
controls[MenuExit] = 'e';
controls[SettingsSmart] = 's';
controls[SettingsStupid] = 't';
controls[SettingsToMainMenu] = 'q';
controls[SettingsSinglePlayer] = 'p';
controls[SettingsMultiplayer] = 'm';
controls[SettingsStart] = 'n';
controls[SettingsEpilepsy] = 'e';
};
int main()
{
PlaySound(TEXT("pong_OST.wav"), NULL, SND_ASYNC|SND_FILENAME|SND_LOOP);
InitScreen(WindowWidth*CharWidth, WindowHeight*CharHeight);
consoleHandle = GetStdHandle( STD_OUTPUT_HANDLE );
SetupControls();
gameState = Menu;
srand((unsigned int)time(NULL));
Paddle leftPaddle, rightPaddle;
int paddleStartingPos = WindowHeight / 2;
leftPaddle.position.X = 0;
leftPaddle.position.Y = paddleStartingPos;
rightPaddle.position.X = WindowWidth - 1;
rightPaddle.position.Y = paddleStartingPos;
for (int i = -PaddleLength/2; i <= PaddleLength/2; ++i)
{
leftPaddle.elements.push_back(GameObject(leftPaddle.position.X, i, '$'));
rightPaddle.elements.push_back(GameObject(rightPaddle.position.X, i, '*'));
}
paddles.push_back(leftPaddle);
paddles.push_back(rightPaddle);
while (true)
{
Update();
Draw();
Sleep(sleepDuration);
}
return 0;
}<|endoftext|>
|
<commit_before>#include<cstdlib>
class Solution {
public:
int compareVersion(string version1, string version2) {
int pos1 = 0, pos2 = 0;
int val1 = 0, val2 = 0;
while(!version1.empty() || !version2.empty())
{
val1 = val2 = 0;
pos1 = version1.find(".");
pos2 = version2.find(".");
if(pos1 != version1.npos)
{
val1 = atoi(version1.substr(0,pos1).c_str() );
version1 = version1.substr(pos1+1);
}
else
{
val1 = atoi(version1.c_str());
version1.clear();
}
if(pos2 != version2.npos)
{
val2 = atoi(version2.substr(0,pos2).c_str());
version2 = version2.substr(pos2+1);
}
else
{
val2 = atoi(version2.c_str());
version2.clear();
}
if(val1 > val2)
return 1;
else if(val1 < val2)
return -1;
}
return 0;
}
};
<commit_msg>Update 165.cpp<commit_after>#include<cstdlib>
class Solution {
public:
int compareVersion(string version1, string version2) {
int pos1 = 0, pos2 = 0;
int val1 = 0, val2 = 0;
while(!version1.empty() || !version2.empty())
{
val1 = val2 = 0;
pos1 = version1.find(".");
pos2 = version2.find(".");
if(pos1 != version1.npos)
{
val1 = atoi(version1.substr(0,pos1).c_str() );
version1 = version1.substr(pos1+1);
}
else
{
val1 = atoi(version1.c_str());
version1.clear();
}
if(pos2 != version2.npos)
{
val2 = atoi(version2.substr(0,pos2).c_str());
version2 = version2.substr(pos2+1);
}
else
{
val2 = atoi(version2.c_str());
version2.clear();
}
if(val1 > val2)
return 1;
else if(val1 < val2)
return -1;
}
return 0;
}
};
<|endoftext|>
|
<commit_before>/*
open source routing machine
Copyright (C) Dennis Luxen, 2010
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include "OSRM.h"
OSRM::OSRM(const char * server_ini_path) {
if( !testDataFile(server_ini_path) ){
throw OSRMException("server.ini not found");
}
IniFile serverConfig(server_ini_path);
boost::filesystem::path base_path =
boost::filesystem::absolute(server_ini_path).parent_path();
boost::filesystem::path hsgr_path = boost::filesystem::absolute(
serverConfig.GetParameter("hsgrData"),
base_path
);
boost::filesystem::path ram_index_path = boost::filesystem::absolute(
serverConfig.GetParameter("ramIndex"),
base_path
);
boost::filesystem::path file_index_path = boost::filesystem::absolute(
serverConfig.GetParameter("fileIndex"),
base_path
);
boost::filesystem::path node_data_path = boost::filesystem::absolute(
serverConfig.GetParameter("nodesData"),
base_path
);
boost::filesystem::path edge_data_path = boost::filesystem::absolute(
serverConfig.GetParameter("edgesData"),
base_path
);
boost::filesystem::path name_data_path = boost::filesystem::absolute(
serverConfig.GetParameter("namesData"),
base_path
);
boost::filesystem::path timestamp_path = boost::filesystem::absolute(
serverConfig.GetParameter("timestamp"),
base_path
);
objects = new QueryObjectsStorage(
hsgr_path.string(),
ram_index_path.string(),
file_index_path.string(),
node_data_path.string(),
edge_data_path.string(),
name_data_path.string(),
timestamp_path.string()
);
RegisterPlugin(new HelloWorldPlugin());
RegisterPlugin(new LocatePlugin(objects));
RegisterPlugin(new NearestPlugin(objects));
RegisterPlugin(new TimestampPlugin(objects));
RegisterPlugin(new ViaRoutePlugin(objects));
}
OSRM::~OSRM() {
BOOST_FOREACH(PluginMap::value_type & plugin_pointer, pluginMap) {
delete plugin_pointer.second;
}
delete objects;
}
void OSRM::RegisterPlugin(BasePlugin * plugin) {
SimpleLogger().Write() << "[plugin] " << plugin->GetDescriptor() << std::endl;
pluginMap[plugin->GetDescriptor()] = plugin;
}
void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) {
const PluginMap::const_iterator & iter = pluginMap.find(route_parameters.service);
if(pluginMap.end() != iter) {
reply.status = http::Reply::ok;
iter->second->HandleRequest(route_parameters, reply );
} else {
reply = http::Reply::stockReply(http::Reply::badRequest);
}
}
<commit_msg>Remove superflous output of endline<commit_after>/*
open source routing machine
Copyright (C) Dennis Luxen, 2010
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
or see http://www.gnu.org/licenses/agpl.txt.
*/
#include "OSRM.h"
OSRM::OSRM(const char * server_ini_path) {
if( !testDataFile(server_ini_path) ){
throw OSRMException("server.ini not found");
}
IniFile serverConfig(server_ini_path);
boost::filesystem::path base_path =
boost::filesystem::absolute(server_ini_path).parent_path();
boost::filesystem::path hsgr_path = boost::filesystem::absolute(
serverConfig.GetParameter("hsgrData"),
base_path
);
boost::filesystem::path ram_index_path = boost::filesystem::absolute(
serverConfig.GetParameter("ramIndex"),
base_path
);
boost::filesystem::path file_index_path = boost::filesystem::absolute(
serverConfig.GetParameter("fileIndex"),
base_path
);
boost::filesystem::path node_data_path = boost::filesystem::absolute(
serverConfig.GetParameter("nodesData"),
base_path
);
boost::filesystem::path edge_data_path = boost::filesystem::absolute(
serverConfig.GetParameter("edgesData"),
base_path
);
boost::filesystem::path name_data_path = boost::filesystem::absolute(
serverConfig.GetParameter("namesData"),
base_path
);
boost::filesystem::path timestamp_path = boost::filesystem::absolute(
serverConfig.GetParameter("timestamp"),
base_path
);
objects = new QueryObjectsStorage(
hsgr_path.string(),
ram_index_path.string(),
file_index_path.string(),
node_data_path.string(),
edge_data_path.string(),
name_data_path.string(),
timestamp_path.string()
);
RegisterPlugin(new HelloWorldPlugin());
RegisterPlugin(new LocatePlugin(objects));
RegisterPlugin(new NearestPlugin(objects));
RegisterPlugin(new TimestampPlugin(objects));
RegisterPlugin(new ViaRoutePlugin(objects));
}
OSRM::~OSRM() {
BOOST_FOREACH(PluginMap::value_type & plugin_pointer, pluginMap) {
delete plugin_pointer.second;
}
delete objects;
}
void OSRM::RegisterPlugin(BasePlugin * plugin) {
SimpleLogger().Write() << "loaded plugin: " << plugin->GetDescriptor();
pluginMap[plugin->GetDescriptor()] = plugin;
}
void OSRM::RunQuery(RouteParameters & route_parameters, http::Reply & reply) {
const PluginMap::const_iterator & iter = pluginMap.find(route_parameters.service);
if(pluginMap.end() != iter) {
reply.status = http::Reply::ok;
iter->second->HandleRequest(route_parameters, reply );
} else {
reply = http::Reply::stockReply(http::Reply::badRequest);
}
}
<|endoftext|>
|
<commit_before>/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
/* $Id$ */
/// \ingroup macros
/// \file rootlogon.C
/// \brief Macro which is run when starting Root in MUON
///
/// It loads the MUON libraries needed for simulation and reconstruction
/// and sets the include path.
///
/// \author Laurent Aphecetche
{
cout << "Loading MUON libraries ..." << endl;
gROOT->LoadMacro("${ALICE_ROOT}/MUON/loadlibs.C");
gInterpreter->ProcessLine("loadlibs()");
cout << "Setting include path ..." << endl;
TString includePath = "-I${ALICE_ROOT}/STEER ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/FASTSIM ";
includePath += "-I${ALICE_ROOT}/EVGEN ";
includePath += "-I${ALICE_ROOT}/SHUTTLE/TestShuttle ";
includePath += "-I${ALICE_ROOT}/ITS ";
includePath += "-I${ALICE_ROOT}/MUON ";
includePath += "-I${ALICE_ROOT}/MUON/mapping ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/include ";
gSystem->SetIncludePath(includePath.Data());
}
<commit_msg>In rootlogon.C: Updated includes from STEER (now in subdirectories).<commit_after>/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
/* $Id$ */
/// \ingroup macros
/// \file rootlogon.C
/// \brief Macro which is run when starting Root in MUON
///
/// It loads the MUON libraries needed for simulation and reconstruction
/// and sets the include path.
///
/// \author Laurent Aphecetche
{
cout << "Loading MUON libraries ..." << endl;
gROOT->LoadMacro("${ALICE_ROOT}/MUON/loadlibs.C");
gInterpreter->ProcessLine("loadlibs()");
cout << "Setting include path ..." << endl;
TString includePath = "-I${ALICE_ROOT}/STEER ";
includePath += "-I${ALICE_ROOT}/STEER/STEER ";
includePath += "-I${ALICE_ROOT}/STEER/STEERBase ";
includePath += "-I${ALICE_ROOT}/STEER/CDB ";
includePath += "-I${ALICE_ROOT}/STEER/ESD ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/FASTSIM ";
includePath += "-I${ALICE_ROOT}/EVGEN ";
includePath += "-I${ALICE_ROOT}/SHUTTLE/TestShuttle ";
includePath += "-I${ALICE_ROOT}/ITS ";
includePath += "-I${ALICE_ROOT}/MUON ";
includePath += "-I${ALICE_ROOT}/MUON/mapping ";
includePath += "-I${ALICE_ROOT}/RAW ";
includePath += "-I${ALICE_ROOT}/include ";
gSystem->SetIncludePath(includePath.Data());
}
<|endoftext|>
|
<commit_before><commit_msg>Q_FOREACH to support no_keywords<commit_after><|endoftext|>
|
<commit_before>// Best-first Utility-Guided Search Yes! From:
// "Best-first Utility-Guided Search," Wheeler Ruml and Minh B. Do,
// Proceedings of the Twentieth International Joint Conference on
// Artificial Intelligence (IJCAI-07), 2007
#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
template <class D> struct Bugsy_slim : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
typedef typename D::Edge Edge;
struct Node {
ClosedEntry<Node, D> closedent;
int openind;
Node *parent;
PackedState state;
Oper op, pop;
Cost g, h, d;
double u, t;
// The expansion count when this node was
// generated.
unsigned long expct;
Node() : openind(-1) {
}
static ClosedEntry<Node, D> &closedentry(Node *n) {
return n->closedent;
}
static PackedState &key(Node *n) {
return n->state;
}
static void setind(Node *n, int i) {
n->openind = i;
}
static int getind(const Node *n) {
return n->openind;
}
static bool pred(Node *a, Node *b) {
if (a->u != b->u)
return a->u > b->u;
if (a->t != b->t)
return a->t < b->t;
Cost af = a->g + a->h;
Cost bf = b->g + b->h;
if (af != bf)
return af < bf;
return a->g > b->g;
}
};
enum {
// Resort1 is the number of expansions to perform
// before the 1st open list resort.
Resort1 = 128,
};
Bugsy_slim(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), avgdelay(0), delaysum(0),
timeper(0.0), lastexpd(0), nextresort(Resort1), nresort(0),
closed(30000001) {
wf = wt = -1;
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
wf = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
wt = strtod(argv[++i], NULL);
}
if (wf < 0)
fatal("Must specify non-negative f-weight using -wf");
if (wt < 0)
fatal("Must specify non-negative t-weight using -wt");
}
~Bugsy_slim() {
}
void search(D &d, typename D::State &s0) {
this->start();
lasttime = walltime();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
Node* n = *open.pop();
State buf, &state = d.unpack(buf, n->state);
if (d.isgoal(state)) {
solpath<D, Node>(d, n, this->res);
break;
}
expand(d, n, state);
updateopen();
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
nodes.releaseall();
timeper = 0.0;
lastexpd = 0;
delaysum = 0;
avgdelay = 0;
nresort = 0;
nextresort = Resort1;
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "%s", "binary heap");
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "wf", "%g", wf);
dfpair(stdout, "wt", "%g", wt);
dfpair(stdout, "final time per expand", "%g", timeper);
dfpair(stdout, "number of resorts", "%lu", nresort);
dfpair(stdout, "mean expansion delay", "%g", avgdelay);
}
private:
// expand expands the node, adding its children to the
// open and closed lists as appropriate.
void expand(D &d, Node *n, State &state) {
this->res.expd++;
delaysum += this->res.expd - n->expct;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
this->res.gend++;
Edge e(d, state, ops[i]);
Node *kid = nodes.construct();
d.pack(kid->state, e.state);
unsigned long hash = kid->state.hash(&d);
if (closed.find(kid->state, hash)) {
this->res.dups++;
nodes.destruct(kid);
continue;
}
kid->expct = this->res.expd;
kid->g = n->g + e.cost;
kid->d = std::max(d.d(e.state), n->d - Cost(1));
kid->h = std::max(d.h(e.state), n->h - e.cost);
kid->parent = n;
kid->op = ops[i];
kid->pop = e.revop;
computeutil(kid);
closed.add(kid, hash);
open.push(kid);
}
}
Node *init(D &d, State &s0) {
Node *n0 = nodes.construct();
d.pack(n0->state, s0);
n0->g = Cost(0);
n0->h = d.h(s0);
n0->d = d.d(s0);
computeutil(n0);
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
n0->expct = 0;
return n0;
}
// compututil computes the utility value of the given node
// using corrected estimates of d and h.
void computeutil(Node *n) {
n->t = timeper * (avgdelay <= 0 ? 1 : avgdelay) * n->d;
n->u = -(wf * (n->h + n->g) + wt * n->t);
}
// updateopen updates the utilities of all nodes on open and
// reinitializes the heap every 2^i expansions.
void updateopen() {
if (this->res.expd < nextresort)
return;
double nexpd = this->res.expd - lastexpd;
lastexpd = this->res.expd;
double t = walltime();
timeper = (t - lasttime) / nexpd;
lasttime = t;
avgdelay = delaysum/nexpd;
delaysum = 0;
nextresort *= 2;
nresort++;
reinitheap();
}
// Reinitheap reinitialize the heap property in O(n)
// time while also updating the utilities.
void reinitheap() {
if (open.size() <= 0)
return;
for (long i = open.size()-1; i > (long) open.size()/2; i--)
computeutil(open.at(i));
for (long i = (long) open.size()/2; i >= 0; i--) {
computeutil(open.at(i));
open.pushdown(i);
}
}
// wf and wt are the cost and time weight respectively.
double wf, wt;
// expansion delay
double avgdelay;
unsigned long delaysum;
// for nodes-per-second estimation
double timeper, lasttime;
long lastexpd;
// for resorting the open list
unsigned long nextresort;
unsigned int nresort;
BinHeap<Node, Node*> open;
ClosedList<Node, Node, D> closed;
Pool<Node> nodes;
};
<commit_msg>bugsy-slim: remove the old paper citation.<commit_after>// Best-first Utility-Guided Search Yes!
#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
template <class D> struct Bugsy_slim : public SearchAlgorithm<D> {
typedef typename D::State State;
typedef typename D::PackedState PackedState;
typedef typename D::Cost Cost;
typedef typename D::Oper Oper;
typedef typename D::Edge Edge;
struct Node {
ClosedEntry<Node, D> closedent;
int openind;
Node *parent;
PackedState state;
Oper op, pop;
Cost g, h, d;
double u, t;
// The expansion count when this node was
// generated.
unsigned long expct;
Node() : openind(-1) {
}
static ClosedEntry<Node, D> &closedentry(Node *n) {
return n->closedent;
}
static PackedState &key(Node *n) {
return n->state;
}
static void setind(Node *n, int i) {
n->openind = i;
}
static int getind(const Node *n) {
return n->openind;
}
static bool pred(Node *a, Node *b) {
if (a->u != b->u)
return a->u > b->u;
if (a->t != b->t)
return a->t < b->t;
Cost af = a->g + a->h;
Cost bf = b->g + b->h;
if (af != bf)
return af < bf;
return a->g > b->g;
}
};
enum {
// Resort1 is the number of expansions to perform
// before the 1st open list resort.
Resort1 = 128,
};
Bugsy_slim(int argc, const char *argv[]) :
SearchAlgorithm<D>(argc, argv), avgdelay(0), delaysum(0),
timeper(0.0), lastexpd(0), nextresort(Resort1), nresort(0),
closed(30000001) {
wf = wt = -1;
for (int i = 0; i < argc; i++) {
if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
wf = strtod(argv[++i], NULL);
else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
wt = strtod(argv[++i], NULL);
}
if (wf < 0)
fatal("Must specify non-negative f-weight using -wf");
if (wt < 0)
fatal("Must specify non-negative t-weight using -wt");
}
~Bugsy_slim() {
}
void search(D &d, typename D::State &s0) {
this->start();
lasttime = walltime();
closed.init(d);
Node *n0 = init(d, s0);
closed.add(n0);
open.push(n0);
while (!open.empty() && !SearchAlgorithm<D>::limit()) {
Node* n = *open.pop();
State buf, &state = d.unpack(buf, n->state);
if (d.isgoal(state)) {
solpath<D, Node>(d, n, this->res);
break;
}
expand(d, n, state);
updateopen();
}
this->finish();
}
virtual void reset() {
SearchAlgorithm<D>::reset();
open.clear();
closed.clear();
nodes.releaseall();
timeper = 0.0;
lastexpd = 0;
delaysum = 0;
avgdelay = 0;
nresort = 0;
nextresort = Resort1;
}
virtual void output(FILE *out) {
SearchAlgorithm<D>::output(out);
closed.prstats(stdout, "closed ");
dfpair(stdout, "open list type", "%s", "binary heap");
dfpair(stdout, "node size", "%u", sizeof(Node));
dfpair(stdout, "wf", "%g", wf);
dfpair(stdout, "wt", "%g", wt);
dfpair(stdout, "final time per expand", "%g", timeper);
dfpair(stdout, "number of resorts", "%lu", nresort);
dfpair(stdout, "mean expansion delay", "%g", avgdelay);
}
private:
// expand expands the node, adding its children to the
// open and closed lists as appropriate.
void expand(D &d, Node *n, State &state) {
this->res.expd++;
delaysum += this->res.expd - n->expct;
typename D::Operators ops(d, state);
for (unsigned int i = 0; i < ops.size(); i++) {
if (ops[i] == n->pop)
continue;
this->res.gend++;
Edge e(d, state, ops[i]);
Node *kid = nodes.construct();
d.pack(kid->state, e.state);
unsigned long hash = kid->state.hash(&d);
if (closed.find(kid->state, hash)) {
this->res.dups++;
nodes.destruct(kid);
continue;
}
kid->expct = this->res.expd;
kid->g = n->g + e.cost;
kid->d = std::max(d.d(e.state), n->d - Cost(1));
kid->h = std::max(d.h(e.state), n->h - e.cost);
kid->parent = n;
kid->op = ops[i];
kid->pop = e.revop;
computeutil(kid);
closed.add(kid, hash);
open.push(kid);
}
}
Node *init(D &d, State &s0) {
Node *n0 = nodes.construct();
d.pack(n0->state, s0);
n0->g = Cost(0);
n0->h = d.h(s0);
n0->d = d.d(s0);
computeutil(n0);
n0->op = n0->pop = D::Nop;
n0->parent = NULL;
n0->expct = 0;
return n0;
}
// compututil computes the utility value of the given node
// using corrected estimates of d and h.
void computeutil(Node *n) {
n->t = timeper * (avgdelay <= 0 ? 1 : avgdelay) * n->d;
n->u = -(wf * (n->h + n->g) + wt * n->t);
}
// updateopen updates the utilities of all nodes on open and
// reinitializes the heap every 2^i expansions.
void updateopen() {
if (this->res.expd < nextresort)
return;
double nexpd = this->res.expd - lastexpd;
lastexpd = this->res.expd;
double t = walltime();
timeper = (t - lasttime) / nexpd;
lasttime = t;
avgdelay = delaysum/nexpd;
delaysum = 0;
nextresort *= 2;
nresort++;
reinitheap();
}
// Reinitheap reinitialize the heap property in O(n)
// time while also updating the utilities.
void reinitheap() {
if (open.size() <= 0)
return;
for (long i = open.size()-1; i > (long) open.size()/2; i--)
computeutil(open.at(i));
for (long i = (long) open.size()/2; i >= 0; i--) {
computeutil(open.at(i));
open.pushdown(i);
}
}
// wf and wt are the cost and time weight respectively.
double wf, wt;
// expansion delay
double avgdelay;
unsigned long delaysum;
// for nodes-per-second estimation
double timeper, lasttime;
long lastexpd;
// for resorting the open list
unsigned long nextresort;
unsigned int nresort;
BinHeap<Node, Node*> open;
ClosedList<Node, Node, D> closed;
Pool<Node> nodes;
};
<|endoftext|>
|
<commit_before>// 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/.
/** @file
* Estimate the best AR(p) model given data on standard input.
*/
#include "burg.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
int main(int argc, char *argv[])
{
using namespace std;
// Process a possible --subtract-mean flag, shifting arguments if needed
bool subtract_mean = false;
if (argc > 1 && 0 == strcmp("--subtract-mean", argv[1])) {
subtract_mean = true;
argv[1] = argv[0];
++argv;
--argc;
}
// Use burg_method to estimate a hierarchy of AR models from input data
double mean;
size_t order = 512;
vector<double> params, sigma2e, gain, autocor;
params .reserve(order*(order + 1)/2);
sigma2e.reserve(order + 1);
gain .reserve(order + 1);
autocor.reserve(order + 1);
const size_t N = burg_method(istream_iterator<double>(cin),
istream_iterator<double>(),
mean,
order,
back_inserter(params),
back_inserter(sigma2e),
back_inserter(gain),
back_inserter(autocor),
subtract_mean,
/* output hierarchy? */ true);
// Keep only best model according to CIC accounting for subtract_mean.
if (subtract_mean) {
best_model<CIC<Burg<mean_subtracted> > >(
N, params, sigma2e, gain, autocor);
} else {
best_model<CIC<Burg<mean_retained> > >(
N, params, sigma2e, gain, autocor);
}
// Compute decorrelation time from the estimated autocorrelation model
const double T0 = decorrelation_time(N, autocorrelation(
params.begin(), params.end(), gain[0], autocor.begin()));
// Output details about the best model and derived information
cout.precision(numeric_limits<double>::digits10 + 2);
cout << showpos
<< "# N " << N
<< "\n# AR(p) " << params.size()
<< "\n# Mean " << mean
<< "\n# \\sigma^2_\\epsilon " << sigma2e[0]
<< "\n# Gain " << gain[0]
<< "\n# \\sigma^2_x " << gain[0]*sigma2e[0]
<< "\n# t_decorrelation " << T0
<< "\n# N_effective " << N / T0
<< "\n# Variance_effective " << (N*gain[0]*sigma2e[0]) / (N - T0)
<< '\n';
copy(params.begin(), params.end(), ostream_iterator<double>(cout,"\n"));
cout.flush();
return 0;
}
<commit_msg>always take absolute value of rho<commit_after>// 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/.
/** @file
* Estimate the best AR(p) model given data on standard input.
*/
#include "burg.hpp"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
int main(int argc, char *argv[])
{
using namespace std;
// Process a possible --subtract-mean flag, shifting arguments if needed
bool subtract_mean = false;
if (argc > 1 && 0 == strcmp("--subtract-mean", argv[1])) {
subtract_mean = true;
argv[1] = argv[0];
++argv;
--argc;
}
// Use burg_method to estimate a hierarchy of AR models from input data
double mean;
size_t order = 512;
vector<double> params, sigma2e, gain, autocor;
params .reserve(order*(order + 1)/2);
sigma2e.reserve(order + 1);
gain .reserve(order + 1);
autocor.reserve(order + 1);
const size_t N = burg_method(istream_iterator<double>(cin),
istream_iterator<double>(),
mean,
order,
back_inserter(params),
back_inserter(sigma2e),
back_inserter(gain),
back_inserter(autocor),
subtract_mean,
/* output hierarchy? */ true);
// Keep only best model according to CIC accounting for subtract_mean.
if (subtract_mean) {
best_model<CIC<Burg<mean_subtracted> > >(
N, params, sigma2e, gain, autocor);
} else {
best_model<CIC<Burg<mean_retained> > >(
N, params, sigma2e, gain, autocor);
}
// Compute decorrelation time from the estimated autocorrelation model
const double T0 = decorrelation_time(N, autocorrelation(params.begin(),
params.end(), gain[0], autocor.begin()), /* abs(rho) */ true);
// Output details about the best model and derived information
cout.precision(numeric_limits<double>::digits10 + 2);
cout << showpos
<< "# N " << N
<< "\n# AR(p) " << params.size()
<< "\n# Mean " << mean
<< "\n# \\sigma^2_\\epsilon " << sigma2e[0]
<< "\n# Gain " << gain[0]
<< "\n# \\sigma^2_x " << gain[0]*sigma2e[0]
<< "\n# t_decorrelation " << T0
<< "\n# N_effective " << N / T0
<< "\n# Variance_effective " << (N*gain[0]*sigma2e[0]) / (N - T0)
<< '\n';
copy(params.begin(), params.end(), ostream_iterator<double>(cout,"\n"));
cout.flush();
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
using namespace std;
int dp(vector<vector<int> > mat, int n)
{
for(int i = 2; i <= n; i++)
{
for(int j = 1; j <= i; j++)
{
if( 1 == j)//左边界线上的元素
mat[i][j] = mat[i-1][j] + mat[i][j];
if( i == j)//右边界线上的元素
mat[i][j] = mat[i-1][j-1] + mat[i][j];
else
{
mat[i][j] = (mat[i-1][j-1] < mat[i-1][j] ? mat[i-1][j-1] : mat[i-1][j]) + mat[i][j];//该节点和 = [左父亲和 + 右父亲和]min + 该节点值
}
}
}
int min;
min = mat[n][1];
for(int j = 2; j <= n; j++)
{
min = (min < mat[n][j]? min : mat[n][j]);
}
return min;
}
int main()
{
int n;
while(cin >> n)
{
int tmp;
vector<vector<int> > mat;
mat.resize(n+1);
for(int i = 0; i < n+1; i++)
{
mat[i].resize(n+1);
}
for(int i =1; i <= n; i++)
{
for(int j = 1; j <= i; j++)
{
cin >> tmp;
mat[i][j] = tmp;
}
}
cout << dp(mat, n)<< endl;
}
}
<commit_msg>update<commit_after>#include <iostream>
#include <vector>
using namespace std;
int dp(vector<vector<int> > mat, int n)
{
for(int i = 2; i <= n; i++)
{
for(int j = 1; j <= i; j++)
{
if( 1 == j)//左边界线上的元素
mat[i][j] = mat[i-1][j] + mat[i][j];
if( i == j)//右边界线上的元素
mat[i][j] = mat[i-1][j-1] + mat[i][j];
else
{
//到该节点的最小路径和 = [左父亲和 , 右父亲和]min + 该节点值
mat[i][j] = (mat[i-1][j-1] < mat[i-1][j] ? mat[i-1][j-1] : mat[i-1][j]) + mat[i][j];
}
}
}
int min;
//到达底层节点,找最小路径
min = mat[n][1];
for(int j = 2; j <= n; j++)
{
min = (min < mat[n][j]? min : mat[n][j]);
}
return min;
}
int main()
{
int n;
while(cin >> n)
{
int tmp;
vector<vector<int> > mat;
mat.resize(n+1);
for(int i = 0; i < n+1; i++)
{
mat[i].resize(n+1);
}
//输入数据
for(int i =1; i <= n; i++)
{
for(int j = 1; j <= i; j++)
{
cin >> tmp;
mat[i][j] = tmp;
}
}
cout << dp(mat, n)<< endl;
}
}
<|endoftext|>
|
<commit_before>/* util.cpp
Copyright (c) 2014, tuxuser. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include <QtEndian>
#include <QDirIterator>
#include <QDateTime>
#include <QUuid>
#include <qtplist/PListParser.h>
#include <qtplist/PListSerializer.h>
#include "dsdt2bios/Dsdt2Bios.h"
#include "../ffs.h"
#include "util.h"
/* General stuff */
UINT8 fileOpen(QString path, QByteArray & buf)
{
QFileInfo fileInfo(path);
if (!fileInfo.exists())
return ERR_FILE_NOT_FOUND;
QFile inputFile;
inputFile.setFileName(path);
if (!inputFile.open(QFile::ReadOnly))
return ERR_FILE_OPEN;
buf.clear();
buf.append(inputFile.readAll());
inputFile.close();
return ERR_SUCCESS;
}
UINT8 fileWrite(QString path, QByteArray & buf)
{
QFileInfo fileInfo(path);
if (fileInfo.exists())
printf("Warning: File already exists! Overwriting it...\n");
QFile writeFile;
writeFile.setFileName(path);
if (!writeFile.open(QFile::WriteOnly))
return ERR_FILE_OPEN;
if(writeFile.write(buf) != buf.size())
return ERR_FILE_WRITE;
writeFile.close();
return ERR_SUCCESS;
}
BOOLEAN fileExists(QString path)
{
QFileInfo fileInfo = QFileInfo(path);
return fileInfo.exists();
}
UINT8 dirCreate(QString path)
{
QDir dir;
if (dir.cd(path))
return ERR_DIR_ALREADY_EXIST;
if (!dir.mkpath(path))
return ERR_DIR_CREATE;
return ERR_SUCCESS;
}
BOOLEAN dirExists(QString path)
{
QDir dir(path);
return dir.exists();
}
QString pathConcatenate(QString path, QString filename)
{
return QDir(path).filePath(filename);
}
UINT32 getDateTime()
{
QDateTime dateTime = QDateTime::currentDateTime();
return dateTime.toTime_t();
}
UINT16 getUInt16(QByteArray & buf, UINT32 start, bool fromBE)
{
UINT16 tmp = 0;
tmp = (tmp << 8) + buf.at(start+0);
tmp = (tmp << 8) + buf.at(start+1);
if(fromBE)
return qFromBigEndian(tmp);
else
return tmp;
}
UINT32 getUInt32(QByteArray & buf, UINT32 start, bool fromBE)
{
UINT32 tmp = 0;
tmp = (tmp << 8) + buf.at(start+0);
tmp = (tmp << 8) + buf.at(start+1);
tmp = (tmp << 8) + buf.at(start+2);
tmp = (tmp << 8) + buf.at(start+3);
if(fromBE)
return qFromBigEndian(tmp);
else
return tmp;
}
/* Specific stuff */
UINT8 getGUIDfromFile(QByteArray object, QString & name)
{
QByteArray header;
EFI_GUID* guid;
header = object.left(sizeof(EFI_GUID));
guid = (EFI_GUID*)(header.constData());
// Get info
name = guidToQString(*guid);
return ERR_SUCCESS;
}
UINT8 plistReadExecName(QByteArray plist, QString & name)
{
static const QString execIdentifier = "CFBundleExecutable";
QString plistExec;
QVariantMap parsed = PListParser::parsePList(plist).toMap();
if (parsed.contains(execIdentifier))
plistExec = parsed.value(execIdentifier).toString();
if(plistExec.isEmpty()) {
printf("ERROR: '%s'' in plist is blank. Aborting!\n", qPrintable(execIdentifier));
return ERR_ERROR;
}
name = plistExec;
return ERR_SUCCESS;
}
UINT8 plistReadBundlenameAndVersion(QByteArray plist, QString & name, QString & version)
{
static const QString nameIdentifier = "CFBundleName";
static const QString versionIdentifier = "CFBundleShortVersionString";
QString plistName;
QString plistVersion;
QVariantMap parsed = PListParser::parsePList(plist).toMap();
if (parsed.contains(nameIdentifier))
plistName = parsed.value(nameIdentifier).toString();
if (parsed.contains(versionIdentifier))
plistVersion = parsed.value(versionIdentifier).toString();
if(plistName.isEmpty()) {
printf("ERROR: '%s' in plist is blank. Aborting!\n", qPrintable(nameIdentifier));
return ERR_ERROR;
}
name = plistName;
version = plistVersion;
return ERR_SUCCESS;
}
UINT8 plistWriteNewBasename(QByteArray plist, QString newName, QByteArray & out)
{
static const QString nameIdentifier = "CFBundleName";
QString plistName;
QVariantMap parsed = PListParser::parsePList(plist).toMap();
if (parsed.contains(nameIdentifier))
plistName = parsed.value(nameIdentifier).toString();
if(plistName.isEmpty()) {
printf("ERROR: '%s' in plist is blank. Aborting!\n", qPrintable(nameIdentifier));
return ERR_ERROR;
}
// Assign new value for CFBundleName
parsed.insert(nameIdentifier, newName);
QVariant qv(parsed);
QByteArray plistByteArray = PListSerializer::toPList(qv);
out.clear();
out.append(plistByteArray);
return ERR_SUCCESS;
}
UINT8 checkAggressivityLevel(int aggressivity) {
QString level;
switch(aggressivity) {
case RUN_AS_IS:
level = "Do nothing - Inject as-is";
break;
case RUN_COMPRESS:
level = "Compress CORE_DXE";
break;
case RUN_DELETE:
level = "Delete network stuff from BIOS";
break;
case RUN_DEL_OZM_NREQ:
level = "Delete non-required Ozmosis files";
break;
default:
printf("Warning: Invalid aggressivity level set!\n");
return ERR_ERROR;
}
printf("Info: Aggressivity level set to '%s'...\n", qPrintable(level));
return ERR_SUCCESS;
}
UINT8 convertOzmPlist(QString input, QByteArray & out)
{
UINT8 ret;
QByteArray plist;
ret = fileOpen(input, plist);
if(ret) {
printf("ERROR: Open failed: %s\n", qPrintable(input));
return ERR_ERROR;
}
ret = ffsCreate(plist, ozmPlistGUID, ozmSectionName, out);
if(ret) {
printf("ERROR: KEXT2FFS failed on '%s'\n", qPrintable(ozmDefaultsFilename));
return ERR_ERROR;
}
return ERR_SUCCESS;
}
UINT8 convertKext(QString input, int kextIndex, QByteArray & out)
{
UINT8 ret;
UINT8 nullterminator = 0;
QString sectionName, guid;
QString bundleName, bundleVersion, execName;
QDir dir;
QFileInfo binaryPath;
QFileInfo plistPath;
QByteArray plistbuf, newPlist;
QByteArray binarybuf;
QByteArray toConvertBinary;
// Check all folders in input-dir
if(kextIndex > 0xF) {
printf("ERROR: Invalid kextIndex '%i' supplied!\n", kextIndex);
return ERR_ERROR;
}
dir.setPath(input);
dir = dir.filePath("Contents");
plistPath.setFile(dir,"Info.plist");
dir = dir.filePath("MacOS");
if (!dir.exists()) {
printf("ERROR: Kext-dir invalid: */Contents/MacOS/ missing!\n");
return ERR_ERROR;
}
if (!plistPath.exists()) {
printf("ERROR: Kext-dir invalid: */Contents/Info.plist missing!\n");
return ERR_ERROR;
}
ret = fileOpen(plistPath.filePath(), plistbuf);
if(ret) {
printf("ERROR: Opening '%s' failed!\n", qPrintable(plistPath.filePath()));
return ret;
}
ret = plistReadExecName(plistbuf, execName);
if(ret) {
printf("ERROR: Failed to get executableName Info.plist\n");
return ret;
}
binaryPath.setFile(dir, execName);
if (!binaryPath.exists()) {
printf("ERROR: Kext-dir invalid: */Contents/MacOS/%s missing!\n",
qPrintable(execName));
return ERR_ERROR;
}
ret = plistReadBundlenameAndVersion(plistbuf, bundleName, bundleVersion);
if (ret) {
printf("ERROR: Failed to get bundleName and/or version from Info.plist\n");
return ret;
}
ret = fileOpen(binaryPath.filePath(), binarybuf);
if (ret) {
printf("ERROR: Opening '%s' failed!\n", qPrintable(binaryPath.filePath()));
return ERR_ERROR;
}
if(bundleVersion.isEmpty())
bundleVersion = "?";
sectionName.sprintf("%s-%s",qPrintable(bundleName), qPrintable(bundleVersion));
plistWriteNewBasename(plistbuf, sectionName, newPlist);
guid = kextGUID.arg(kextIndex, 0, 16);
toConvertBinary.append(newPlist);
toConvertBinary.append(nullterminator);
toConvertBinary.append(binarybuf);
ret = ffsCreate(toConvertBinary, guid, sectionName, out);
if(ret) {
printf("ERROR: KEXT2FFS failed on '%s'\n", qPrintable(sectionName));
return ERR_ERROR;
}
return ERR_SUCCESS;
}
UINT8 ffsCreate(QByteArray body, QString guid, QString sectionName, QByteArray & out)
{
QByteArray bufSectionName;
QByteArray fileBody, header;
/* FFS PE32 Section */
header.fill(0, sizeof(EFI_COMMON_SECTION_HEADER));
EFI_COMMON_SECTION_HEADER* PE32SectionHeader = (EFI_COMMON_SECTION_HEADER*)header.data();
uint32ToUint24(sizeof(EFI_COMMON_SECTION_HEADER)+body.size(), PE32SectionHeader->Size);
PE32SectionHeader->Type = EFI_SECTION_PE32;
fileBody.append(header, sizeof(EFI_COMMON_SECTION_HEADER));
fileBody.append(body);
/* FFS User Interface */
header.clear();
header.fill(0, sizeof(EFI_USER_INTERFACE_SECTION));
EFI_USER_INTERFACE_SECTION* UserInterfaceSection = (EFI_USER_INTERFACE_SECTION*)header.data();
/* Convert sectionName to unicode data */
bufSectionName.append((const char*) (sectionName.utf16()), sectionName.size() * 2);
uint32ToUint24(sizeof(EFI_USER_INTERFACE_SECTION)+bufSectionName.size(), UserInterfaceSection->Size);
UserInterfaceSection->Type = EFI_SECTION_USER_INTERFACE;
/* Align for next section */
UINT8 alignment = fileBody.size() % 4;
if (alignment) {
alignment = 4 - alignment;
fileBody.append(QByteArray(alignment, '\x00'));
}
fileBody.append(header, sizeof(EFI_USER_INTERFACE_SECTION));
fileBody.append(bufSectionName);
/* FFS File */
const static UINT8 revision = 0;
const static UINT8 erasePolarity = 1;
const static UINT32 size = fileBody.size();
QUuid uuid = QUuid(guid);
header.clear();
header.fill(0, sizeof(EFI_FFS_FILE_HEADER));
EFI_FFS_FILE_HEADER* fileHeader = (EFI_FFS_FILE_HEADER*)header.data();
uint32ToUint24(sizeof(EFI_FFS_FILE_HEADER)+size, fileHeader->Size);
fileHeader->Attributes = 0x00;
fileHeader->Attributes |= (erasePolarity == ERASE_POLARITY_TRUE) ? '\xFF' : '\x00';
fileHeader->Type = EFI_FV_FILETYPE_FREEFORM;
fileHeader->State = EFI_FILE_HEADER_CONSTRUCTION | EFI_FILE_HEADER_VALID | EFI_FILE_DATA_VALID;
// Invert state bits if erase polarity is true
if (erasePolarity == ERASE_POLARITY_TRUE)
fileHeader->State = ~fileHeader->State;
memcpy(&fileHeader->Name, &uuid.data1, sizeof(EFI_GUID));
// Calculate header checksum
fileHeader->IntegrityCheck.Checksum.Header = 0;
fileHeader->IntegrityCheck.Checksum.File = 0;
fileHeader->IntegrityCheck.Checksum.Header = calculateChecksum8((UINT8*)fileHeader, sizeof(EFI_FFS_FILE_HEADER)-1);
// Set data checksum
if (fileHeader->Attributes & FFS_ATTRIB_CHECKSUM)
fileHeader->IntegrityCheck.Checksum.File = calculateChecksum8((UINT8*)fileBody.constData(), fileBody.size());
else if (revision == 1)
fileHeader->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
else
fileHeader->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM2;
out.clear();
out.append(header, sizeof(EFI_FFS_FILE_HEADER));
out.append(fileBody);
return ERR_SUCCESS;
}
<commit_msg>Use sectionName '<Name>.Rev-<Version>' instead of '<Name>-<Version>'<commit_after>/* util.cpp
Copyright (c) 2014, tuxuser. All rights reserved.
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
*/
#include <QtEndian>
#include <QDirIterator>
#include <QDateTime>
#include <QUuid>
#include <qtplist/PListParser.h>
#include <qtplist/PListSerializer.h>
#include "dsdt2bios/Dsdt2Bios.h"
#include "../ffs.h"
#include "util.h"
/* General stuff */
UINT8 fileOpen(QString path, QByteArray & buf)
{
QFileInfo fileInfo(path);
if (!fileInfo.exists())
return ERR_FILE_NOT_FOUND;
QFile inputFile;
inputFile.setFileName(path);
if (!inputFile.open(QFile::ReadOnly))
return ERR_FILE_OPEN;
buf.clear();
buf.append(inputFile.readAll());
inputFile.close();
return ERR_SUCCESS;
}
UINT8 fileWrite(QString path, QByteArray & buf)
{
QFileInfo fileInfo(path);
if (fileInfo.exists())
printf("Warning: File already exists! Overwriting it...\n");
QFile writeFile;
writeFile.setFileName(path);
if (!writeFile.open(QFile::WriteOnly))
return ERR_FILE_OPEN;
if(writeFile.write(buf) != buf.size())
return ERR_FILE_WRITE;
writeFile.close();
return ERR_SUCCESS;
}
BOOLEAN fileExists(QString path)
{
QFileInfo fileInfo = QFileInfo(path);
return fileInfo.exists();
}
UINT8 dirCreate(QString path)
{
QDir dir;
if (dir.cd(path))
return ERR_DIR_ALREADY_EXIST;
if (!dir.mkpath(path))
return ERR_DIR_CREATE;
return ERR_SUCCESS;
}
BOOLEAN dirExists(QString path)
{
QDir dir(path);
return dir.exists();
}
QString pathConcatenate(QString path, QString filename)
{
return QDir(path).filePath(filename);
}
UINT32 getDateTime()
{
QDateTime dateTime = QDateTime::currentDateTime();
return dateTime.toTime_t();
}
UINT16 getUInt16(QByteArray & buf, UINT32 start, bool fromBE)
{
UINT16 tmp = 0;
tmp = (tmp << 8) + buf.at(start+0);
tmp = (tmp << 8) + buf.at(start+1);
if(fromBE)
return qFromBigEndian(tmp);
else
return tmp;
}
UINT32 getUInt32(QByteArray & buf, UINT32 start, bool fromBE)
{
UINT32 tmp = 0;
tmp = (tmp << 8) + buf.at(start+0);
tmp = (tmp << 8) + buf.at(start+1);
tmp = (tmp << 8) + buf.at(start+2);
tmp = (tmp << 8) + buf.at(start+3);
if(fromBE)
return qFromBigEndian(tmp);
else
return tmp;
}
/* Specific stuff */
UINT8 getGUIDfromFile(QByteArray object, QString & name)
{
QByteArray header;
EFI_GUID* guid;
header = object.left(sizeof(EFI_GUID));
guid = (EFI_GUID*)(header.constData());
// Get info
name = guidToQString(*guid);
return ERR_SUCCESS;
}
UINT8 plistReadExecName(QByteArray plist, QString & name)
{
static const QString execIdentifier = "CFBundleExecutable";
QString plistExec;
QVariantMap parsed = PListParser::parsePList(plist).toMap();
if (parsed.contains(execIdentifier))
plistExec = parsed.value(execIdentifier).toString();
if(plistExec.isEmpty()) {
printf("ERROR: '%s'' in plist is blank. Aborting!\n", qPrintable(execIdentifier));
return ERR_ERROR;
}
name = plistExec;
return ERR_SUCCESS;
}
UINT8 plistReadBundlenameAndVersion(QByteArray plist, QString & name, QString & version)
{
static const QString nameIdentifier = "CFBundleName";
static const QString versionIdentifier = "CFBundleShortVersionString";
QString plistName;
QString plistVersion;
QVariantMap parsed = PListParser::parsePList(plist).toMap();
if (parsed.contains(nameIdentifier))
plistName = parsed.value(nameIdentifier).toString();
if (parsed.contains(versionIdentifier))
plistVersion = parsed.value(versionIdentifier).toString();
if(plistName.isEmpty()) {
printf("ERROR: '%s' in plist is blank. Aborting!\n", qPrintable(nameIdentifier));
return ERR_ERROR;
}
name = plistName;
version = plistVersion;
return ERR_SUCCESS;
}
UINT8 plistWriteNewBasename(QByteArray plist, QString newName, QByteArray & out)
{
static const QString nameIdentifier = "CFBundleName";
QString plistName;
QVariantMap parsed = PListParser::parsePList(plist).toMap();
if (parsed.contains(nameIdentifier))
plistName = parsed.value(nameIdentifier).toString();
if(plistName.isEmpty()) {
printf("ERROR: '%s' in plist is blank. Aborting!\n", qPrintable(nameIdentifier));
return ERR_ERROR;
}
// Assign new value for CFBundleName
parsed.insert(nameIdentifier, newName);
QVariant qv(parsed);
QByteArray plistByteArray = PListSerializer::toPList(qv);
out.clear();
out.append(plistByteArray);
return ERR_SUCCESS;
}
UINT8 checkAggressivityLevel(int aggressivity) {
QString level;
switch(aggressivity) {
case RUN_AS_IS:
level = "Do nothing - Inject as-is";
break;
case RUN_COMPRESS:
level = "Compress CORE_DXE";
break;
case RUN_DELETE:
level = "Delete network stuff from BIOS";
break;
case RUN_DEL_OZM_NREQ:
level = "Delete non-required Ozmosis files";
break;
default:
printf("Warning: Invalid aggressivity level set!\n");
return ERR_ERROR;
}
printf("Info: Aggressivity level set to '%s'...\n", qPrintable(level));
return ERR_SUCCESS;
}
UINT8 convertOzmPlist(QString input, QByteArray & out)
{
UINT8 ret;
QByteArray plist;
ret = fileOpen(input, plist);
if(ret) {
printf("ERROR: Open failed: %s\n", qPrintable(input));
return ERR_ERROR;
}
ret = ffsCreate(plist, ozmPlistGUID, ozmSectionName, out);
if(ret) {
printf("ERROR: KEXT2FFS failed on '%s'\n", qPrintable(ozmDefaultsFilename));
return ERR_ERROR;
}
return ERR_SUCCESS;
}
UINT8 convertKext(QString input, int kextIndex, QByteArray & out)
{
UINT8 ret;
UINT8 nullterminator = 0;
QString sectionName, guid;
QString bundleName, bundleVersion, execName;
QDir dir;
QFileInfo binaryPath;
QFileInfo plistPath;
QByteArray plistbuf, newPlist;
QByteArray binarybuf;
QByteArray toConvertBinary;
// Check all folders in input-dir
if(kextIndex > 0xF) {
printf("ERROR: Invalid kextIndex '%i' supplied!\n", kextIndex);
return ERR_ERROR;
}
dir.setPath(input);
dir = dir.filePath("Contents");
plistPath.setFile(dir,"Info.plist");
dir = dir.filePath("MacOS");
if (!dir.exists()) {
printf("ERROR: Kext-dir invalid: */Contents/MacOS/ missing!\n");
return ERR_ERROR;
}
if (!plistPath.exists()) {
printf("ERROR: Kext-dir invalid: */Contents/Info.plist missing!\n");
return ERR_ERROR;
}
ret = fileOpen(plistPath.filePath(), plistbuf);
if(ret) {
printf("ERROR: Opening '%s' failed!\n", qPrintable(plistPath.filePath()));
return ret;
}
ret = plistReadExecName(plistbuf, execName);
if(ret) {
printf("ERROR: Failed to get executableName Info.plist\n");
return ret;
}
binaryPath.setFile(dir, execName);
if (!binaryPath.exists()) {
printf("ERROR: Kext-dir invalid: */Contents/MacOS/%s missing!\n",
qPrintable(execName));
return ERR_ERROR;
}
ret = plistReadBundlenameAndVersion(plistbuf, bundleName, bundleVersion);
if (ret) {
printf("ERROR: Failed to get bundleName and/or version from Info.plist\n");
return ret;
}
ret = fileOpen(binaryPath.filePath(), binarybuf);
if (ret) {
printf("ERROR: Opening '%s' failed!\n", qPrintable(binaryPath.filePath()));
return ERR_ERROR;
}
if(bundleVersion.isEmpty())
bundleVersion = "?";
sectionName.sprintf("%s.Rev-%s",qPrintable(bundleName), qPrintable(bundleVersion));
plistWriteNewBasename(plistbuf, sectionName, newPlist);
guid = kextGUID.arg(kextIndex, 0, 16);
toConvertBinary.append(newPlist);
toConvertBinary.append(nullterminator);
toConvertBinary.append(binarybuf);
ret = ffsCreate(toConvertBinary, guid, sectionName, out);
if(ret) {
printf("ERROR: KEXT2FFS failed on '%s'\n", qPrintable(sectionName));
return ERR_ERROR;
}
return ERR_SUCCESS;
}
UINT8 ffsCreate(QByteArray body, QString guid, QString sectionName, QByteArray & out)
{
QByteArray bufSectionName;
QByteArray fileBody, header;
/* FFS PE32 Section */
header.fill(0, sizeof(EFI_COMMON_SECTION_HEADER));
EFI_COMMON_SECTION_HEADER* PE32SectionHeader = (EFI_COMMON_SECTION_HEADER*)header.data();
uint32ToUint24(sizeof(EFI_COMMON_SECTION_HEADER)+body.size(), PE32SectionHeader->Size);
PE32SectionHeader->Type = EFI_SECTION_PE32;
fileBody.append(header, sizeof(EFI_COMMON_SECTION_HEADER));
fileBody.append(body);
/* FFS User Interface */
header.clear();
header.fill(0, sizeof(EFI_USER_INTERFACE_SECTION));
EFI_USER_INTERFACE_SECTION* UserInterfaceSection = (EFI_USER_INTERFACE_SECTION*)header.data();
/* Convert sectionName to unicode data */
bufSectionName.append((const char*) (sectionName.utf16()), sectionName.size() * 2);
uint32ToUint24(sizeof(EFI_USER_INTERFACE_SECTION)+bufSectionName.size(), UserInterfaceSection->Size);
UserInterfaceSection->Type = EFI_SECTION_USER_INTERFACE;
/* Align for next section */
UINT8 alignment = fileBody.size() % 4;
if (alignment) {
alignment = 4 - alignment;
fileBody.append(QByteArray(alignment, '\x00'));
}
fileBody.append(header, sizeof(EFI_USER_INTERFACE_SECTION));
fileBody.append(bufSectionName);
/* FFS File */
const static UINT8 revision = 0;
const static UINT8 erasePolarity = 1;
const static UINT32 size = fileBody.size();
QUuid uuid = QUuid(guid);
header.clear();
header.fill(0, sizeof(EFI_FFS_FILE_HEADER));
EFI_FFS_FILE_HEADER* fileHeader = (EFI_FFS_FILE_HEADER*)header.data();
uint32ToUint24(sizeof(EFI_FFS_FILE_HEADER)+size, fileHeader->Size);
fileHeader->Attributes = 0x00;
fileHeader->Attributes |= (erasePolarity == ERASE_POLARITY_TRUE) ? '\xFF' : '\x00';
fileHeader->Type = EFI_FV_FILETYPE_FREEFORM;
fileHeader->State = EFI_FILE_HEADER_CONSTRUCTION | EFI_FILE_HEADER_VALID | EFI_FILE_DATA_VALID;
// Invert state bits if erase polarity is true
if (erasePolarity == ERASE_POLARITY_TRUE)
fileHeader->State = ~fileHeader->State;
memcpy(&fileHeader->Name, &uuid.data1, sizeof(EFI_GUID));
// Calculate header checksum
fileHeader->IntegrityCheck.Checksum.Header = 0;
fileHeader->IntegrityCheck.Checksum.File = 0;
fileHeader->IntegrityCheck.Checksum.Header = calculateChecksum8((UINT8*)fileHeader, sizeof(EFI_FFS_FILE_HEADER)-1);
// Set data checksum
if (fileHeader->Attributes & FFS_ATTRIB_CHECKSUM)
fileHeader->IntegrityCheck.Checksum.File = calculateChecksum8((UINT8*)fileBody.constData(), fileBody.size());
else if (revision == 1)
fileHeader->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM;
else
fileHeader->IntegrityCheck.Checksum.File = FFS_FIXED_CHECKSUM2;
out.clear();
out.append(header, sizeof(EFI_FFS_FILE_HEADER));
out.append(fileBody);
return ERR_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <absl/flags/usage.h>
#include <absl/flags/usage_config.h>
#include <QApplication>
#include <QDir>
#include <QFontDatabase>
#include <QMessageBox>
#include <QProcessEnvironment>
#include <QProgressDialog>
#include <QStyleFactory>
#ifdef _WIN32
#include <process.h>
#else
#include <unistd.h>
#endif
#include "App.h"
#include "ApplicationOptions.h"
#include "Error.h"
#include "MainThreadExecutorImpl.h"
#include "OrbitBase/Logging.h"
#include "OrbitGgp/Error.h"
#include "OrbitSsh/Context.h"
#include "OrbitSsh/Credentials.h"
#include "OrbitSshQt/Session.h"
#include "OrbitStartupWindow.h"
#include "OrbitVersion/OrbitVersion.h"
#include "Path.h"
#include "deploymentconfigurations.h"
#include "opengldetect.h"
#include "orbitmainwindow.h"
#include "servicedeploymanager.h"
#ifdef ORBIT_CRASH_HANDLING
#include "CrashHandler.h"
#include "CrashOptions.h"
#endif
ABSL_FLAG(bool, enable_stale_features, false,
"Enable obsolete features that are not working or are not "
"implemented in the client's UI");
ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI");
ABSL_FLAG(uint16_t, grpc_port, 44765,
"The service's GRPC server port (use default value if unsure)");
ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService");
// TODO(b/160549506): Remove this flag once it can be specified in the ui.
ABSL_FLAG(uint16_t, sampling_rate, 1000, "Frequency of callstack sampling in samples per second");
// TODO(b/160549506): Remove this flag once it can be specified in the ui.
ABSL_FLAG(bool, frame_pointer_unwinding, false, "Use frame pointers for unwinding");
using ServiceDeployManager = OrbitQt::ServiceDeployManager;
using DeploymentConfiguration = OrbitQt::DeploymentConfiguration;
using OrbitStartupWindow = OrbitQt::OrbitStartupWindow;
using Error = OrbitQt::Error;
using ScopedConnection = OrbitSshQt::ScopedConnection;
using GrpcPort = ServiceDeployManager::GrpcPort;
using SshCredentials = OrbitSsh::Credentials;
using Context = OrbitSsh::Context;
static outcome::result<GrpcPort> DeployOrbitService(
std::optional<ServiceDeployManager>& service_deploy_manager,
const DeploymentConfiguration& deployment_configuration, Context* context,
const SshCredentials& ssh_credentials, const GrpcPort& remote_ports) {
QProgressDialog progress_dialog{};
service_deploy_manager.emplace(deployment_configuration, context, ssh_credentials, remote_ports);
QObject::connect(&progress_dialog, &QProgressDialog::canceled, &service_deploy_manager.value(),
&ServiceDeployManager::Cancel);
QObject::connect(&service_deploy_manager.value(), &ServiceDeployManager::statusMessage,
&progress_dialog, &QProgressDialog::setLabelText);
QObject::connect(&service_deploy_manager.value(), &ServiceDeployManager::statusMessage,
[](const QString& msg) { LOG("Status message: %s", msg.toStdString()); });
return service_deploy_manager->Exec();
}
static outcome::result<void> RunUiInstance(
QApplication* app, std::optional<DeploymentConfiguration> deployment_configuration,
Context* context) {
std::optional<OrbitQt::ServiceDeployManager> service_deploy_manager;
OUTCOME_TRY(result, [&]() -> outcome::result<std::tuple<GrpcPort, QString>> {
const GrpcPort remote_ports{/*.grpc_port =*/absl::GetFlag(FLAGS_grpc_port)};
if (!deployment_configuration) {
// When the local flag is present
return std::make_tuple(remote_ports, QString{});
}
OrbitStartupWindow sw{};
OUTCOME_TRY(result, sw.Run<OrbitSsh::Credentials>());
if (!std::holds_alternative<OrbitSsh::Credentials>(result)) {
// The user chose to open a capture.
return std::make_tuple(remote_ports, std::get<QString>(result));
}
// The user chose a remote profiling target.
OUTCOME_TRY(tunnel_ports,
DeployOrbitService(service_deploy_manager, deployment_configuration.value(),
context, std::get<SshCredentials>(result), remote_ports));
return std::make_tuple(tunnel_ports, QString{});
}());
const auto& [ports, capture_path] = result;
ApplicationOptions options;
options.grpc_server_address = absl::StrFormat("127.0.0.1:%d", ports.grpc_port);
ServiceDeployManager* service_deploy_manager_ptr = nullptr;
if (service_deploy_manager) {
service_deploy_manager_ptr = &service_deploy_manager.value();
}
std::optional<std::error_code> error;
OrbitApp::Init(std::move(options), CreateMainThreadExecutor());
{ // Scoping of QT UI Resources
OrbitMainWindow w(app, service_deploy_manager_ptr);
Orbit_ImGui_Init();
// "resize" is required to make "showMaximized" work properly.
w.resize(1280, 720);
w.showMaximized();
auto error_handler = [&]() -> ScopedConnection {
if (!service_deploy_manager) {
return ScopedConnection();
}
return OrbitSshQt::ScopedConnection{QObject::connect(
&service_deploy_manager.value(), &ServiceDeployManager::socketErrorOccurred,
&service_deploy_manager.value(), [&](std::error_code e) {
error = e;
w.close();
QApplication::quit();
})};
}();
if (!capture_path.isEmpty()) {
w.OpenCapture(capture_path.toStdString());
}
QApplication::exec();
Orbit_ImGui_Shutdown();
}
GOrbitApp->OnExit();
if (error) {
return outcome::failure(error.value());
} else {
return outcome::success();
}
}
static void StyleOrbit(QApplication& app) {
QApplication::setStyle(QStyleFactory::create("Fusion"));
QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::HighlightedText, Qt::black);
QColor light_gray{160, 160, 160};
QColor dark_gray{90, 90, 90};
QColor darker_gray{80, 80, 80};
darkPalette.setColor(QPalette::Disabled, QPalette::Window, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Base, darker_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::AlternateBase, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipBase, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Text, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Button, darker_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::BrightText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Link, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, dark_gray);
QApplication::setPalette(darkPalette);
app.setStyleSheet(
"QToolTip { color: #ffffff; background-color: #2a82da; border: 1px "
"solid white; }");
}
static std::optional<OrbitQt::DeploymentConfiguration> FigureOutDeploymentConfiguration() {
if (absl::GetFlag(FLAGS_local)) {
return std::nullopt;
}
auto env = QProcessEnvironment::systemEnvironment();
const char* const kEnvExecutablePath = "ORBIT_COLLECTOR_EXECUTABLE_PATH";
const char* const kEnvRootPassword = "ORBIT_COLLECTOR_ROOT_PASSWORD";
const char* const kEnvPackagePath = "ORBIT_COLLECTOR_PACKAGE_PATH";
const char* const kEnvSignaturePath = "ORBIT_COLLECTOR_SIGNATURE_PATH";
const char* const kEnvNoDeployment = "ORBIT_COLLECTOR_NO_DEPLOYMENT";
if (env.contains(kEnvExecutablePath) && env.contains(kEnvRootPassword)) {
return OrbitQt::BareExecutableAndRootPasswordDeployment{
env.value(kEnvExecutablePath).toStdString(), env.value(kEnvRootPassword).toStdString()};
} else if (env.contains(kEnvPackagePath) && env.contains(kEnvSignaturePath)) {
return OrbitQt::SignedDebianPackageDeployment{env.value(kEnvPackagePath).toStdString(),
env.value(kEnvSignaturePath).toStdString()};
} else if (env.contains(kEnvNoDeployment)) {
return OrbitQt::NoDeployment{};
} else {
return OrbitQt::SignedDebianPackageDeployment{};
}
}
static void DisplayErrorToUser(const QString& message) {
QMessageBox::critical(nullptr, QApplication::applicationName(), message);
}
int main(int argc, char* argv[]) {
// Will be filled by QApplication once instantiated.
QString path_to_executable;
// argv might be changed, so we make a copy here!
auto original_argv = new char*[argc + 1];
for (int i = 0; i < argc; ++i) {
const auto size = std::strlen(argv[i]);
auto dest = new char[size];
std::strncpy(dest, argv[i], size);
original_argv[i] = dest;
}
original_argv[argc] = nullptr;
{
absl::SetProgramUsageMessage("CPU Profiler");
absl::SetFlagsUsageConfig(absl::FlagsUsageConfig{{}, {}, {}, &OrbitCore::GetBuildReport, {}});
absl::ParseCommandLine(argc, argv);
const std::string log_file_path = Path::GetLogFilePathAndCreateDir();
InitLogFile(log_file_path);
LOG("You are running Orbit Profiler version %s", OrbitCore::GetVersion());
#if __linux__
QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
#endif
QApplication app(argc, argv);
QApplication::setApplicationName("orbitprofiler");
// The application display name is automatically appended to all window titles when shown in the
// title bar: <specific window title> - <application display name>
const auto version_string = QString::fromStdString(OrbitCore::GetVersion());
QApplication::setApplicationDisplayName(
QString{"Orbit Profiler %1 [BETA]"}.arg(version_string));
QApplication::setApplicationVersion(version_string);
path_to_executable = QCoreApplication::applicationFilePath();
#ifdef ORBIT_CRASH_HANDLING
const std::string dump_path = Path::CreateOrGetDumpDir();
#ifdef _WIN32
const char* handler_name = "crashpad_handler.exe";
#else
const char* handler_name = "crashpad_handler";
#endif
const std::string handler_path =
QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(handler_name).toStdString();
const std::string crash_server_url = CrashServerOptions::GetUrl();
const std::vector<std::string> attachments = {Path::GetLogFilePathAndCreateDir()};
CrashHandler crash_handler(dump_path, handler_path, crash_server_url, attachments);
#endif // ORBIT_CRASH_HANDLING
StyleOrbit(app);
const auto deployment_configuration = FigureOutDeploymentConfiguration();
const auto open_gl_version = OrbitQt::DetectOpenGlVersion();
if (!open_gl_version) {
DisplayErrorToUser(
"OpenGL support was not found. Please make sure you're not trying to "
"start Orbit in a remote session and make sure you have a recent "
"graphics driver installed. Then try again!");
return -1;
}
LOG("Detected OpenGL version: %i.%i", open_gl_version->major, open_gl_version->minor);
if (open_gl_version->major < 2) {
DisplayErrorToUser(QString("The minimum required version of OpenGL is 2.0. But this machine "
"only supports up to version %1.%2. Please make sure you're not "
"trying to start Orbit in a remote session and make sure you "
"have a recent graphics driver installed. Then try again!")
.arg(open_gl_version->major)
.arg(open_gl_version->minor));
return -1;
}
auto context = Context::Create();
if (!context) {
DisplayErrorToUser(QString("An error occurred while initializing ssh: %1")
.arg(QString::fromStdString(context.error().message())));
return -1;
}
while (true) {
const auto result = RunUiInstance(&app, deployment_configuration, &(context.value()));
if (result || result.error() == make_error_code(Error::kUserClosedStartUpWindow) ||
!deployment_configuration) {
// It was either a clean shutdown or the deliberately closed the
// dialog, or we started with the --local flag.
return 0;
} else if (result.error() == make_error_code(OrbitGgp::Error::kCouldNotUseGgpCli)) {
DisplayErrorToUser(QString::fromStdString(result.error().message()));
return 1;
} else if (result.error() != make_error_code(Error::kUserCanceledServiceDeployment)) {
DisplayErrorToUser(
QString("An error occurred: %1").arg(QString::fromStdString(result.error().message())));
break;
}
}
}
execv(path_to_executable.toLocal8Bit().constData(), original_argv);
UNREACHABLE();
}
<commit_msg>Enable dev-mode via env variable<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <absl/flags/usage.h>
#include <absl/flags/usage_config.h>
#include <QApplication>
#include <QDir>
#include <QFontDatabase>
#include <QMessageBox>
#include <QProcessEnvironment>
#include <QProgressDialog>
#include <QStyleFactory>
#ifdef _WIN32
#include <process.h>
#else
#include <unistd.h>
#endif
#include "App.h"
#include "ApplicationOptions.h"
#include "Error.h"
#include "MainThreadExecutorImpl.h"
#include "OrbitBase/Logging.h"
#include "OrbitGgp/Error.h"
#include "OrbitSsh/Context.h"
#include "OrbitSsh/Credentials.h"
#include "OrbitSshQt/Session.h"
#include "OrbitStartupWindow.h"
#include "OrbitVersion/OrbitVersion.h"
#include "Path.h"
#include "deploymentconfigurations.h"
#include "opengldetect.h"
#include "orbitmainwindow.h"
#include "servicedeploymanager.h"
#ifdef ORBIT_CRASH_HANDLING
#include "CrashHandler.h"
#include "CrashOptions.h"
#endif
ABSL_FLAG(bool, enable_stale_features, false,
"Enable obsolete features that are not working or are not "
"implemented in the client's UI");
ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI");
ABSL_FLAG(uint16_t, grpc_port, 44765,
"The service's GRPC server port (use default value if unsure)");
ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService");
// TODO(b/160549506): Remove this flag once it can be specified in the ui.
ABSL_FLAG(uint16_t, sampling_rate, 1000, "Frequency of callstack sampling in samples per second");
// TODO(b/160549506): Remove this flag once it can be specified in the ui.
ABSL_FLAG(bool, frame_pointer_unwinding, false, "Use frame pointers for unwinding");
using ServiceDeployManager = OrbitQt::ServiceDeployManager;
using DeploymentConfiguration = OrbitQt::DeploymentConfiguration;
using OrbitStartupWindow = OrbitQt::OrbitStartupWindow;
using Error = OrbitQt::Error;
using ScopedConnection = OrbitSshQt::ScopedConnection;
using GrpcPort = ServiceDeployManager::GrpcPort;
using SshCredentials = OrbitSsh::Credentials;
using Context = OrbitSsh::Context;
static outcome::result<GrpcPort> DeployOrbitService(
std::optional<ServiceDeployManager>& service_deploy_manager,
const DeploymentConfiguration& deployment_configuration, Context* context,
const SshCredentials& ssh_credentials, const GrpcPort& remote_ports) {
QProgressDialog progress_dialog{};
service_deploy_manager.emplace(deployment_configuration, context, ssh_credentials, remote_ports);
QObject::connect(&progress_dialog, &QProgressDialog::canceled, &service_deploy_manager.value(),
&ServiceDeployManager::Cancel);
QObject::connect(&service_deploy_manager.value(), &ServiceDeployManager::statusMessage,
&progress_dialog, &QProgressDialog::setLabelText);
QObject::connect(&service_deploy_manager.value(), &ServiceDeployManager::statusMessage,
[](const QString& msg) { LOG("Status message: %s", msg.toStdString()); });
return service_deploy_manager->Exec();
}
static outcome::result<void> RunUiInstance(
QApplication* app, std::optional<DeploymentConfiguration> deployment_configuration,
Context* context) {
std::optional<OrbitQt::ServiceDeployManager> service_deploy_manager;
OUTCOME_TRY(result, [&]() -> outcome::result<std::tuple<GrpcPort, QString>> {
const GrpcPort remote_ports{/*.grpc_port =*/absl::GetFlag(FLAGS_grpc_port)};
if (!deployment_configuration) {
// When the local flag is present
return std::make_tuple(remote_ports, QString{});
}
OrbitStartupWindow sw{};
OUTCOME_TRY(result, sw.Run<OrbitSsh::Credentials>());
if (!std::holds_alternative<OrbitSsh::Credentials>(result)) {
// The user chose to open a capture.
return std::make_tuple(remote_ports, std::get<QString>(result));
}
// The user chose a remote profiling target.
OUTCOME_TRY(tunnel_ports,
DeployOrbitService(service_deploy_manager, deployment_configuration.value(),
context, std::get<SshCredentials>(result), remote_ports));
return std::make_tuple(tunnel_ports, QString{});
}());
const auto& [ports, capture_path] = result;
ApplicationOptions options;
options.grpc_server_address = absl::StrFormat("127.0.0.1:%d", ports.grpc_port);
ServiceDeployManager* service_deploy_manager_ptr = nullptr;
if (service_deploy_manager) {
service_deploy_manager_ptr = &service_deploy_manager.value();
}
std::optional<std::error_code> error;
OrbitApp::Init(std::move(options), CreateMainThreadExecutor());
{ // Scoping of QT UI Resources
OrbitMainWindow w(app, service_deploy_manager_ptr);
Orbit_ImGui_Init();
// "resize" is required to make "showMaximized" work properly.
w.resize(1280, 720);
w.showMaximized();
auto error_handler = [&]() -> ScopedConnection {
if (!service_deploy_manager) {
return ScopedConnection();
}
return OrbitSshQt::ScopedConnection{QObject::connect(
&service_deploy_manager.value(), &ServiceDeployManager::socketErrorOccurred,
&service_deploy_manager.value(), [&](std::error_code e) {
error = e;
w.close();
QApplication::quit();
})};
}();
if (!capture_path.isEmpty()) {
w.OpenCapture(capture_path.toStdString());
}
QApplication::exec();
Orbit_ImGui_Shutdown();
}
GOrbitApp->OnExit();
if (error) {
return outcome::failure(error.value());
} else {
return outcome::success();
}
}
static void StyleOrbit(QApplication& app) {
QApplication::setStyle(QStyleFactory::create("Fusion"));
QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::HighlightedText, Qt::black);
QColor light_gray{160, 160, 160};
QColor dark_gray{90, 90, 90};
QColor darker_gray{80, 80, 80};
darkPalette.setColor(QPalette::Disabled, QPalette::Window, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Base, darker_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::AlternateBase, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipBase, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Text, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Button, darker_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::BrightText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Link, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, dark_gray);
QApplication::setPalette(darkPalette);
app.setStyleSheet(
"QToolTip { color: #ffffff; background-color: #2a82da; border: 1px "
"solid white; }");
}
static std::optional<OrbitQt::DeploymentConfiguration> FigureOutDeploymentConfiguration() {
if (absl::GetFlag(FLAGS_local)) {
return std::nullopt;
}
auto env = QProcessEnvironment::systemEnvironment();
const char* const kEnvExecutablePath = "ORBIT_COLLECTOR_EXECUTABLE_PATH";
const char* const kEnvRootPassword = "ORBIT_COLLECTOR_ROOT_PASSWORD";
const char* const kEnvPackagePath = "ORBIT_COLLECTOR_PACKAGE_PATH";
const char* const kEnvSignaturePath = "ORBIT_COLLECTOR_SIGNATURE_PATH";
const char* const kEnvNoDeployment = "ORBIT_COLLECTOR_NO_DEPLOYMENT";
if (env.contains(kEnvExecutablePath) && env.contains(kEnvRootPassword)) {
return OrbitQt::BareExecutableAndRootPasswordDeployment{
env.value(kEnvExecutablePath).toStdString(), env.value(kEnvRootPassword).toStdString()};
} else if (env.contains(kEnvPackagePath) && env.contains(kEnvSignaturePath)) {
return OrbitQt::SignedDebianPackageDeployment{env.value(kEnvPackagePath).toStdString(),
env.value(kEnvSignaturePath).toStdString()};
} else if (env.contains(kEnvNoDeployment)) {
return OrbitQt::NoDeployment{};
} else {
return OrbitQt::SignedDebianPackageDeployment{};
}
}
static void DisplayErrorToUser(const QString& message) {
QMessageBox::critical(nullptr, QApplication::applicationName(), message);
}
static bool DevModeEnabledViaEnvironmentVariable() {
const auto env = QProcessEnvironment::systemEnvironment();
return env.contains("ORBIT_DEV_MODE") || env.contains("ORBIT_DEVELOPER_MODE");
}
int main(int argc, char* argv[]) {
// Will be filled by QApplication once instantiated.
QString path_to_executable;
// argv might be changed, so we make a copy here!
auto original_argv = new char*[argc + 1];
for (int i = 0; i < argc; ++i) {
const auto size = std::strlen(argv[i]);
auto dest = new char[size];
std::strncpy(dest, argv[i], size);
original_argv[i] = dest;
}
original_argv[argc] = nullptr;
{
absl::SetProgramUsageMessage("CPU Profiler");
absl::SetFlagsUsageConfig(absl::FlagsUsageConfig{{}, {}, {}, &OrbitCore::GetBuildReport, {}});
absl::ParseCommandLine(argc, argv);
const std::string log_file_path = Path::GetLogFilePathAndCreateDir();
InitLogFile(log_file_path);
LOG("You are running Orbit Profiler version %s", OrbitCore::GetVersion());
#if __linux__
QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
#endif
QApplication app(argc, argv);
QApplication::setApplicationName("orbitprofiler");
if (DevModeEnabledViaEnvironmentVariable()) {
absl::SetFlag(&FLAGS_devmode, true);
}
// The application display name is automatically appended to all window titles when shown in the
// title bar: <specific window title> - <application display name>
const auto version_string = QString::fromStdString(OrbitCore::GetVersion());
QApplication::setApplicationDisplayName(
QString{"Orbit Profiler %1 [BETA]"}.arg(version_string));
QApplication::setApplicationVersion(version_string);
path_to_executable = QCoreApplication::applicationFilePath();
#ifdef ORBIT_CRASH_HANDLING
const std::string dump_path = Path::CreateOrGetDumpDir();
#ifdef _WIN32
const char* handler_name = "crashpad_handler.exe";
#else
const char* handler_name = "crashpad_handler";
#endif
const std::string handler_path =
QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(handler_name).toStdString();
const std::string crash_server_url = CrashServerOptions::GetUrl();
const std::vector<std::string> attachments = {Path::GetLogFilePathAndCreateDir()};
CrashHandler crash_handler(dump_path, handler_path, crash_server_url, attachments);
#endif // ORBIT_CRASH_HANDLING
StyleOrbit(app);
const auto deployment_configuration = FigureOutDeploymentConfiguration();
const auto open_gl_version = OrbitQt::DetectOpenGlVersion();
if (!open_gl_version) {
DisplayErrorToUser(
"OpenGL support was not found. Please make sure you're not trying to "
"start Orbit in a remote session and make sure you have a recent "
"graphics driver installed. Then try again!");
return -1;
}
LOG("Detected OpenGL version: %i.%i", open_gl_version->major, open_gl_version->minor);
if (open_gl_version->major < 2) {
DisplayErrorToUser(QString("The minimum required version of OpenGL is 2.0. But this machine "
"only supports up to version %1.%2. Please make sure you're not "
"trying to start Orbit in a remote session and make sure you "
"have a recent graphics driver installed. Then try again!")
.arg(open_gl_version->major)
.arg(open_gl_version->minor));
return -1;
}
auto context = Context::Create();
if (!context) {
DisplayErrorToUser(QString("An error occurred while initializing ssh: %1")
.arg(QString::fromStdString(context.error().message())));
return -1;
}
while (true) {
const auto result = RunUiInstance(&app, deployment_configuration, &(context.value()));
if (result || result.error() == make_error_code(Error::kUserClosedStartUpWindow) ||
!deployment_configuration) {
// It was either a clean shutdown or the deliberately closed the
// dialog, or we started with the --local flag.
return 0;
} else if (result.error() == make_error_code(OrbitGgp::Error::kCouldNotUseGgpCli)) {
DisplayErrorToUser(QString::fromStdString(result.error().message()));
return 1;
} else if (result.error() != make_error_code(Error::kUserCanceledServiceDeployment)) {
DisplayErrorToUser(
QString("An error occurred: %1").arg(QString::fromStdString(result.error().message())));
break;
}
}
}
execv(path_to_executable.toLocal8Bit().constData(), original_argv);
UNREACHABLE();
}
<|endoftext|>
|
<commit_before>#include <atomic>
#include <chrono>
#include <list>
#include <mutex>
#include <thread>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <mpi.h>
#include "rma-buffer/rma_buff.hpp"
#include "async.hpp"
#define REQUIRE_CB_MUTEX
#define ASYNC_ARGS_SIZE 512
typedef unsigned char byte;
// task representation for messaging and internal queues
struct task
{
int origin, target;
fptr task_func;
byte task_runner_args[ASYNC_ARGS_SIZE];
task() {}
task(int o, int t, fptr tf, byte *ta, size_t sz) :
origin(o), target(t), task_func(tf)
{
assert(sz <= ASYNC_ARGS_SIZE);
memcpy(task_runner_args, ta, sz);
}
} __attribute__ ((packed));
#define ASYNC_MSG_SIZE sizeof(struct task)
#define ASYNC_MSG_BUFFLEN 128
#ifndef mpi_assert
#define mpi_assert(X) assert(X == MPI_SUCCESS);
#endif
// message buffer object: handles incoming / outgoing task messages; managed
// by the mover thread
static rma_buff<task> *task_buff;
// progress threads: message mover and task executor
static std::thread *th_mover;
static std::thread *th_executor;
// exit flag for progress threads
static std::atomic<bool> done(false);
// mutual exclusion for task queues and (maybe) local updates to cb_count
static std::mutex task_queue_mtx;
static std::mutex outgoing_task_queue_mtx;
#ifdef REQUIRE_CB_MUTEX
static std::mutex cb_mutex;
#endif
// task queues
static std::list<task *> task_queue;
static std::list<task *> outgoing_task_queue;
// general mpi
static int my_rank;
static MPI_Comm my_comm;
// callback counter: tracks the number of outstanding tasks
static int *cb_count;
static MPI_Win cb_win;
/*
* Decrement the callback counter on the specified rank
*/
static void cb_dec(int target)
{
int dec = -1;
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.lock();
#endif
mpi_assert(MPI_Win_lock(MPI_LOCK_EXCLUSIVE, target, 0, cb_win));
mpi_assert(MPI_Accumulate(&dec,
1, MPI_INT, target, 0,
1, MPI_INT, MPI_SUM, cb_win));
mpi_assert(MPI_Win_unlock(target, cb_win));
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.unlock();
#endif
}
/*
* Increment the callback counter on the specified rank
*/
static void cb_inc(int target)
{
int inc = 1;
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.lock();
#endif
mpi_assert(MPI_Win_lock(MPI_LOCK_EXCLUSIVE, target, 0, cb_win));
mpi_assert(MPI_Accumulate(&inc,
1, MPI_INT, target, 0,
1, MPI_INT, MPI_SUM, cb_win));
mpi_assert(MPI_Win_unlock(target, cb_win));
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.unlock();
#endif
}
/*
* Get the callback counter on the specified rank
*/
static int cb_get(int target)
{
int val;
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.lock();
#endif
mpi_assert(MPI_Win_lock(MPI_LOCK_EXCLUSIVE, target, 0, cb_win));
mpi_assert(MPI_Get(&val,
1, MPI_INT, target, 0,
1, MPI_INT, cb_win));
mpi_assert(MPI_Win_unlock(target, cb_win));
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.unlock();
#endif
return val;
}
/*
* Action performed by the mover progress thread: moves async tasks in and out
* of the rma_buff object to / from their respective queues.
*/
static void mover()
{
task task_msg_in[ASYNC_MSG_BUFFLEN];
while (! done) {
int nmsg;
// service incoming tasks (enqueue them for execution)
if ((nmsg = task_buff->get(task_msg_in, 1)) > 0) {
for (int i = 0; i < nmsg; i++) {
task *t = new task();
memcpy(t, (void *)&task_msg_in[i], ASYNC_MSG_SIZE);
task_queue_mtx.lock();
task_queue.push_back((task *) t);
task_queue_mtx.unlock();
}
}
// place outgoing tasks on their respective targets
task *msg = NULL;
outgoing_task_queue_mtx.lock();
if (! outgoing_task_queue.empty()) {
msg = outgoing_task_queue.front();
outgoing_task_queue.pop_front();
}
outgoing_task_queue_mtx.unlock();
if (msg != NULL) {
// try to place task on the target (non-blocking)
if (task_buff->put(msg->target, msg)) {
// success: clean up
delete msg;
} else {
// failure: the target buffer must be full; put the message back in
// the queue and retry later
outgoing_task_queue_mtx.lock();
outgoing_task_queue.push_back(msg);
outgoing_task_queue_mtx.unlock();
}
}
// possibly sleep if there was no work to do
if (nmsg == 0 && msg == NULL)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
/*
* Action performed by the executor thread: remove tasks from the queue and run
* them (remembering to decrement the origin callback counter thereafter)
*/
static void executor()
{
while (! done) {
task *msg = NULL;
task_queue_mtx.lock();
if (! task_queue.empty()) {
msg = task_queue.front();
task_queue.pop_front();
}
task_queue_mtx.unlock();
if (msg != NULL) {
msg->task_func(msg->task_runner_args);
cb_dec(msg->origin);
delete msg;
} else
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
/**
* Route a task to the correct queue for exection on the target
*
* This routine will fast-path to our own local execution queue if we are in
* fact the target. While it is not a user-facing function per se, it is called
* by the \c async() task invocation launch functions (and thus cannot have
* static linkage).
*
* \param target target rank for task execution
* \param rp pointer to the appropriate runner function
* \param tp pointer to the packed task data (function pointer and args)
* \param sz size (bytes) of the packed task data
*/
void _enqueue(int target, fptr rp, void *tp, size_t sz)
{
task *t = new task(my_rank, target, rp, (byte *)tp, sz);
if (target == my_rank) {
task_queue_mtx.lock();
task_queue.push_back(t);
task_queue_mtx.unlock();
} else {
outgoing_task_queue_mtx.lock();
outgoing_task_queue.push_back(t);
outgoing_task_queue_mtx.unlock();
}
cb_inc(my_rank);
}
/**
* Enable asynchronous task execution among ranks on the supplied communicator
*
* This call is collective.
*
* \param comm MPI communicator over participating ranks
*/
void async_enable(MPI_Comm comm)
{
int mpi_init, mpi_thread;
// sanity check on mpi threading support
mpi_assert(MPI_Initialized(&mpi_init));
assert(mpi_init);
mpi_assert(MPI_Query_thread(&mpi_thread));
assert(mpi_thread == MPI_THREAD_MULTIPLE);
my_comm = comm;
mpi_assert(MPI_Comm_rank(my_comm, &my_rank));
mpi_assert(MPI_Alloc_mem(sizeof(int), MPI_INFO_NULL, &cb_count));
*cb_count = 0;
mpi_assert(MPI_Win_create(cb_count, sizeof(int), sizeof(int),
MPI_INFO_NULL,
comm, &cb_win));
task_buff = new rma_buff<task>(1, ASYNC_MSG_BUFFLEN, comm);
th_mover = new std::thread(mover);
th_executor = new std::thread(executor);
mpi_assert(MPI_Barrier(my_comm));
}
/**
* Stop invocation of asynchronous tasks and block until all outstanding
* tasks have been executed
*
* This call is collective.
*/
void async_disable()
{
while (cb_get(my_rank))
std::this_thread::sleep_for(std::chrono::milliseconds(10));
mpi_assert(MPI_Barrier(my_comm));
done = true;
th_mover->join();
th_executor->join();
mpi_assert(MPI_Win_free(&cb_win));
mpi_assert(MPI_Free_mem(cb_count));
delete th_mover;
delete th_executor;
delete task_buff;
}
<commit_msg>Minor cleanup in async.cpp<commit_after>#include <atomic>
#include <chrono>
#include <list>
#include <mutex>
#include <thread>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <mpi.h>
#include "rma-buffer/rma_buff.hpp"
#include "async.hpp"
typedef unsigned char byte;
// do concurrent (across progress threads) RMA calls for updating callback
// counters need to be protected with a mutex
#define REQUIRE_CB_MUTEX
// default max size for the packed async runner argument buffer
#define ASYNC_ARGS_SIZE 512
// task representation for messaging and internal queues
struct task
{
int origin, target;
fptr task_func;
byte task_runner_args[ASYNC_ARGS_SIZE];
task() {}
task(int o, int t, fptr tf, byte *ta, size_t sz) :
origin(o), target(t), task_func(tf)
{
assert(sz <= ASYNC_ARGS_SIZE);
memcpy(task_runner_args, ta, sz);
}
} __attribute__ ((packed));
// inferred async task message size
#define ASYNC_MSG_SIZE sizeof(struct task)
// length of the async message buffer
#define ASYNC_MSG_BUFFLEN 2048
#ifndef mpi_assert
#define mpi_assert(X) assert(X == MPI_SUCCESS);
#endif
// message buffer object: handles incoming / outgoing task messages; managed
// by the mover thread
static rma_buff<task> *task_buff;
// progress threads: message mover and task executor
static std::thread *th_mover;
static std::thread *th_executor;
// exit flag for progress threads
static std::atomic<bool> done(false);
// mutual exclusion for task queues and (maybe) local updates to cb_count
static std::mutex task_queue_mtx;
static std::mutex outgoing_task_queue_mtx;
#ifdef REQUIRE_CB_MUTEX
static std::mutex cb_mutex;
#endif
// task queues
static std::list<task *> task_queue;
static std::list<task *> outgoing_task_queue;
// general mpi
static int my_rank;
static MPI_Comm my_comm;
// callback counter: tracks the number of outstanding tasks
static int *cb_count;
static MPI_Win cb_win;
/*
* Decrement the callback counter on the specified rank
*/
static void cb_dec(int target)
{
int dec = -1;
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.lock();
#endif
mpi_assert(MPI_Win_lock(MPI_LOCK_EXCLUSIVE, target, 0, cb_win));
mpi_assert(MPI_Accumulate(&dec,
1, MPI_INT, target, 0,
1, MPI_INT, MPI_SUM, cb_win));
mpi_assert(MPI_Win_unlock(target, cb_win));
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.unlock();
#endif
}
/*
* Increment the callback counter on the specified rank
*/
static void cb_inc(int target)
{
int inc = 1;
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.lock();
#endif
mpi_assert(MPI_Win_lock(MPI_LOCK_EXCLUSIVE, target, 0, cb_win));
mpi_assert(MPI_Accumulate(&inc,
1, MPI_INT, target, 0,
1, MPI_INT, MPI_SUM, cb_win));
mpi_assert(MPI_Win_unlock(target, cb_win));
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.unlock();
#endif
}
/*
* Get the callback counter on the specified rank
*/
static int cb_get(int target)
{
int val;
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.lock();
#endif
mpi_assert(MPI_Win_lock(MPI_LOCK_EXCLUSIVE, target, 0, cb_win));
mpi_assert(MPI_Get(&val,
1, MPI_INT, target, 0,
1, MPI_INT, cb_win));
mpi_assert(MPI_Win_unlock(target, cb_win));
#ifdef REQUIRE_CB_MUTEX
if (target == my_rank)
cb_mutex.unlock();
#endif
return val;
}
/*
* Action performed by the mover progress thread: moves async tasks in and out
* of the rma_buff object to / from their respective queues.
*/
static void mover()
{
task task_msg_in[ASYNC_MSG_BUFFLEN];
while (! done) {
int nmsg;
// service incoming tasks (enqueue them for execution)
if ((nmsg = task_buff->get(task_msg_in, 1)) > 0) {
for (int i = 0; i < nmsg; i++) {
task *t = new task();
memcpy(t, (void *)&task_msg_in[i], ASYNC_MSG_SIZE);
task_queue_mtx.lock();
task_queue.push_back((task *) t);
task_queue_mtx.unlock();
}
}
// place outgoing tasks on their respective targets
task *msg = NULL;
outgoing_task_queue_mtx.lock();
if (! outgoing_task_queue.empty()) {
msg = outgoing_task_queue.front();
outgoing_task_queue.pop_front();
}
outgoing_task_queue_mtx.unlock();
if (msg != NULL) {
// try to place task on the target (non-blocking)
if (task_buff->put(msg->target, msg)) {
// success: clean up
delete msg;
} else {
// failure: the target buffer must be full; put the message back in
// the queue and retry later
outgoing_task_queue_mtx.lock();
outgoing_task_queue.push_back(msg);
outgoing_task_queue_mtx.unlock();
}
}
// possibly sleep if there was no work to do
if (nmsg == 0 && msg == NULL)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
} /* static void mover() */
/*
* Action performed by the executor thread: remove tasks from the queue and run
* them (remembering to decrement the origin callback counter thereafter)
*/
static void executor()
{
while (! done) {
task *msg = NULL;
task_queue_mtx.lock();
if (! task_queue.empty()) {
msg = task_queue.front();
task_queue.pop_front();
}
task_queue_mtx.unlock();
if (msg != NULL) {
msg->task_func(msg->task_runner_args);
cb_dec(msg->origin);
delete msg;
} else
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
} /* static void executor() */
/**
* Route a task to the correct queue for exection on the target
*
* This routine will fast-path to our own local execution queue if we are in
* fact the target. While it is not a user-facing function per se, it is called
* by the \c async() task invocation launch functions (and thus cannot have
* static linkage).
*
* \param target target rank for task execution
* \param rp pointer to the appropriate runner function
* \param tp pointer to the packed task data (function pointer and args)
* \param sz size (bytes) of the packed task data
*/
void _enqueue(int target, fptr rp, void *tp, size_t sz)
{
task *t = new task(my_rank, target, rp, (byte *)tp, sz);
if (target == my_rank) {
task_queue_mtx.lock();
task_queue.push_back(t);
task_queue_mtx.unlock();
} else {
outgoing_task_queue_mtx.lock();
outgoing_task_queue.push_back(t);
outgoing_task_queue_mtx.unlock();
}
cb_inc(my_rank);
}
/**
* Enable asynchronous task execution among ranks on the supplied communicator
*
* This call is collective.
*
* \param comm MPI communicator over participating ranks
*/
void async_enable(MPI_Comm comm)
{
int mpi_init, mpi_thread;
// sanity check on mpi threading support
mpi_assert(MPI_Initialized(&mpi_init));
assert(mpi_init);
mpi_assert(MPI_Query_thread(&mpi_thread));
assert(mpi_thread == MPI_THREAD_MULTIPLE);
// set communicator and rank
my_comm = comm;
mpi_assert(MPI_Comm_rank(my_comm, &my_rank));
// setup callback counter
mpi_assert(MPI_Alloc_mem(sizeof(int), MPI_INFO_NULL, &cb_count));
*cb_count = 0;
mpi_assert(MPI_Win_create(cb_count, sizeof(int), sizeof(int),
MPI_INFO_NULL,
comm, &cb_win));
// setup the task buffer
task_buff = new rma_buff<task>(1, ASYNC_MSG_BUFFLEN, comm);
// setup the progress threads
th_mover = new std::thread(mover);
th_executor = new std::thread(executor);
// synchronize and return
mpi_assert(MPI_Barrier(my_comm));
}
/**
* Stop invocation of asynchronous tasks and block until all outstanding
* tasks have been executed
*
* This call is collective.
*/
void async_disable()
{
// wait for all outstanding tasks to complete
while (cb_get(my_rank))
std::this_thread::sleep_for(std::chrono::milliseconds(10));
// synchronize
mpi_assert(MPI_Barrier(my_comm));
// no more work to do; shut down the progress threads
done = true;
th_mover->join();
th_executor->join();
// clean up
mpi_assert(MPI_Win_free(&cb_win));
mpi_assert(MPI_Free_mem(cb_count));
delete th_mover;
delete th_executor;
delete task_buff;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 Adam Chyła, [email protected]
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "send_command.h"
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "slas_parser.hpp"
extern "C"
{
void SendCommand(const char *command) {
static const slas::Options *options = nullptr;
if (options == nullptr) {
slas::Parser p;
p.SetConfigFilePath(BASH_SLAS_CONF_PATH);
options = new slas::Options(p.Parse());
}
int fd, res;
struct sockaddr_un saddr;
fd = socket(PF_UNIX, SOCK_STREAM, 0);
saddr.sun_family = AF_UNIX;
strcpy(saddr.sun_path, options->GetBashSocketPath().c_str());
res = connect(fd, (struct sockaddr *) &saddr, sizeof (struct sockaddr_un));
if (res == 0) {
send(fd, command, strlen(command) + 1, 0);
close(fd);
}
else {
fprintf(stderr, "Can't connect to log server.");
}
}
}
<commit_msg>Configure logger in bash<commit_after>/*
* Copyright 2016 Adam Chyła, [email protected]
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "send_command.h"
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <patlms/util/configure_logger.h>
#include "slas_parser.hpp"
extern "C"
{
void SendCommand(const char *command) {
static const slas::Options *options = nullptr;
if (options == nullptr) {
slas::Parser p;
p.SetConfigFilePath(BASH_SLAS_CONF_PATH);
options = new slas::Options(p.Parse());
}
util::ConfigureLogger(options->GetLogfilePath(), options->IsDebug());
int fd, res;
struct sockaddr_un saddr;
fd = socket(PF_UNIX, SOCK_STREAM, 0);
saddr.sun_family = AF_UNIX;
strcpy(saddr.sun_path, options->GetBashSocketPath().c_str());
res = connect(fd, (struct sockaddr *) &saddr, sizeof (struct sockaddr_un));
if (res == 0) {
send(fd, command, strlen(command) + 1, 0);
close(fd);
}
else {
fprintf(stderr, "Can't connect to log server.");
}
}
}
<|endoftext|>
|
<commit_before>/** \file
*
* \brief Implementation of \a QBrowseButton
*
* This file provides the implementation of the \a QBrowseButton class.
*
* \author Peter 'png' Hille <[email protected]>
*
* \version 1.0
*/
#include <QHBoxLayout>
#include <QDebug>
#include "nullptr.h"
#include "QBrowseButton.h"
/** \brief Create new QBrowseButton instance
*
* Initializes a new QBrowseButton widget that can be used to browse for a
* file.
*
* \param parent Parent QWidget that owns the newly created QBrowseButton
*/
QBrowseButton::QBrowseButton(QWidget *parent) :
QFrame(parent), m_mode(QFileDialog::AnyFile), m_caption(tr("Browse for file")),
m_selectedItem("")
{
setupUi();
}
/** \brief Create new QBrowseButton for directories
*
* Initializes a QBrowseButton widget that can be used to browse for a
* directory.
*
* \param dir Directory where the browser shall start
* \param parent Parent QWidget that owns the newly created QBrowseButton
*/
QBrowseButton::QBrowseButton(QDir dir, QWidget *parent) :
QFrame(parent), m_mode(QFileDialog::DirectoryOnly), m_caption(tr("Browse for directory")),
m_selectedItem(dir.absolutePath())
{
setupUi();
setSelectedItem(m_selectedItem);
}
/** \brief Initialize sub-widgets
*
* Initializes the sub-widgets that belong to the QBrowseButton instance.
*
* \internal This helper method is called from the class constructors to reduce code
* redundancy for initializing all the child widgets of our button.
*/
void QBrowseButton::setupUi() {
QHBoxLayout* hbox = nullptr;
try {
hbox = new QHBoxLayout(this);
}
catch (std::bad_alloc& ex) {
qCritical() << "Caught exception when trying to allocate new QVBoxLayout in" << Q_FUNC_INFO << ":" << ex.what();
throw;
}
try {
ui_leSelectedItem = new QLineEdit(m_selectedItem, this);
ui_leSelectedItem->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
hbox->addWidget(ui_leSelectedItem);
}
catch (std::bad_alloc& ex) {
qCritical() << "Caught exception when trying to allocate new QLineEdit in" << Q_FUNC_INFO << ":" << ex.what();
throw;
}
try {
ui_btnBrowse = new QPushButton(tr("..."), this);
if (m_mode == QFileDialog::AnyFile)
ui_btnBrowse->setIcon(QIcon::fromTheme("folder-open"));
else
ui_btnBrowse->setIcon(QIcon::fromTheme("folder-open"));
ui_btnBrowse->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
connect(ui_btnBrowse, SIGNAL(clicked()), this, SLOT(btnBrowse_clicked()));
hbox->addWidget(ui_btnBrowse);
}
catch (std::bad_alloc& ex) {
qCritical() << "Caught exception when trying to allocate new QPushButton in" << Q_FUNC_INFO << ":" << ex.what();
throw;
}
QFrame::setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
QFrame::setLineWidth(1);
QFrame::setLayout(hbox);
}
/** \brief Set open mode
*
* This can be used to specify wether the dialog that gets opened when the user clicks the 'browse'
* button shall be a file or directory selection dialog by using either \a QFileDialog::AnyFile or
* \a QFileDialog::DirectoryOnly as value for the \a mode parameter.
*
* \note Other values for \a mode are ignored and generate a \a qWarning message!
*
* \param mode New selection mode for this button
*/
void QBrowseButton::setMode(QFileDialog::FileMode mode) {
if (!(mode == QFileDialog::AnyFile || QFileDialog::DirectoryOnly)) {
qWarning() << "Unsupported open mode" << mode << "in" << Q_FUNC_INFO;
return;
}
m_mode = mode;
}
/** \brief Set selection dialog caption
*
* Sets the caption for the selection dialog that is shown when the user clicks the 'browse' button.
*
* \param title New selection dialog caption
*/
void QBrowseButton::setCaption(QString title) {
m_caption = title;
}
/** \brief Set selected item
*
* Sets the 'selected item' box of this button to a new value.
*
* \param path New path that shall be shown in the 'selected item' box
*/
void QBrowseButton::setSelectedItem(QString path) {
m_selectedItem = path;
ui_leSelectedItem->setText(path);
}
/** \brief Set icon for 'browse' button
*
* Sets the icon for the 'browse' button to a new QIcon.
*
* \param icon New icon for 'browse' button
*/
void QBrowseButton::setIcon(QIcon icon) {
ui_btnBrowse->setIcon(icon);
}
/** \brief Set 'browse' button caption
*
* Sets the caption of the 'browse' button to a new value.
*
* \param text New caption for 'browse' button
*/
void QBrowseButton::setButtonText(QString text) {
ui_btnBrowse->setText(text);
}
/** \brief Slot for \a clicked signal of 'browse' button
*
* \internal This slot is connected to the \a clicked() signal of \a ui_btnBrowse and shows
* a file or directory selection dialog depending on the settings that have been
* specified for this \a QBrowseButton instance.
*/
void QBrowseButton::btnBrowse_clicked() {
QString selection;
switch (m_mode) {
default:
case QFileDialog::AnyFile:
selection = QFileDialog::getOpenFileName(this, m_caption, m_selectedItem, "*");
break;
case QFileDialog::DirectoryOnly:
selection = QFileDialog::getExistingDirectory(this, m_caption, m_selectedItem);
break;
}
if (selection.isNull())
return;
m_selectedItem = selection;
emit newSelection(selection);
}
<commit_msg>properly update QLineEdit after new selection...<commit_after>/** \file
*
* \brief Implementation of \a QBrowseButton
*
* This file provides the implementation of the \a QBrowseButton class.
*
* \author Peter 'png' Hille <[email protected]>
*
* \version 1.0
*/
#include <QHBoxLayout>
#include <QDebug>
#include "nullptr.h"
#include "QBrowseButton.h"
/** \brief Create new QBrowseButton instance
*
* Initializes a new QBrowseButton widget that can be used to browse for a
* file.
*
* \param parent Parent QWidget that owns the newly created QBrowseButton
*/
QBrowseButton::QBrowseButton(QWidget *parent) :
QFrame(parent), m_mode(QFileDialog::AnyFile), m_caption(tr("Browse for file")),
m_selectedItem("")
{
setupUi();
}
/** \brief Create new QBrowseButton for directories
*
* Initializes a QBrowseButton widget that can be used to browse for a
* directory.
*
* \param dir Directory where the browser shall start
* \param parent Parent QWidget that owns the newly created QBrowseButton
*/
QBrowseButton::QBrowseButton(QDir dir, QWidget *parent) :
QFrame(parent), m_mode(QFileDialog::DirectoryOnly), m_caption(tr("Browse for directory")),
m_selectedItem(dir.absolutePath())
{
setupUi();
setSelectedItem(m_selectedItem);
}
/** \brief Initialize sub-widgets
*
* Initializes the sub-widgets that belong to the QBrowseButton instance.
*
* \internal This helper method is called from the class constructors to reduce code
* redundancy for initializing all the child widgets of our button.
*/
void QBrowseButton::setupUi() {
QHBoxLayout* hbox = nullptr;
try {
hbox = new QHBoxLayout(this);
}
catch (std::bad_alloc& ex) {
qCritical() << "Caught exception when trying to allocate new QVBoxLayout in" << Q_FUNC_INFO << ":" << ex.what();
throw;
}
try {
ui_leSelectedItem = new QLineEdit(m_selectedItem, this);
ui_leSelectedItem->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum);
hbox->addWidget(ui_leSelectedItem);
}
catch (std::bad_alloc& ex) {
qCritical() << "Caught exception when trying to allocate new QLineEdit in" << Q_FUNC_INFO << ":" << ex.what();
throw;
}
try {
ui_btnBrowse = new QPushButton(tr("..."), this);
if (m_mode == QFileDialog::AnyFile)
ui_btnBrowse->setIcon(QIcon::fromTheme("folder-open"));
else
ui_btnBrowse->setIcon(QIcon::fromTheme("folder-open"));
ui_btnBrowse->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
connect(ui_btnBrowse, SIGNAL(clicked()), this, SLOT(btnBrowse_clicked()));
hbox->addWidget(ui_btnBrowse);
}
catch (std::bad_alloc& ex) {
qCritical() << "Caught exception when trying to allocate new QPushButton in" << Q_FUNC_INFO << ":" << ex.what();
throw;
}
QFrame::setFrameStyle(QFrame::StyledPanel | QFrame::Raised);
QFrame::setLineWidth(1);
QFrame::setLayout(hbox);
}
/** \brief Set open mode
*
* This can be used to specify wether the dialog that gets opened when the user clicks the 'browse'
* button shall be a file or directory selection dialog by using either \a QFileDialog::AnyFile or
* \a QFileDialog::DirectoryOnly as value for the \a mode parameter.
*
* \note Other values for \a mode are ignored and generate a \a qWarning message!
*
* \param mode New selection mode for this button
*/
void QBrowseButton::setMode(QFileDialog::FileMode mode) {
if (!(mode == QFileDialog::AnyFile || QFileDialog::DirectoryOnly)) {
qWarning() << "Unsupported open mode" << mode << "in" << Q_FUNC_INFO;
return;
}
m_mode = mode;
}
/** \brief Set selection dialog caption
*
* Sets the caption for the selection dialog that is shown when the user clicks the 'browse' button.
*
* \param title New selection dialog caption
*/
void QBrowseButton::setCaption(QString title) {
m_caption = title;
}
/** \brief Set selected item
*
* Sets the 'selected item' box of this button to a new value.
*
* \param path New path that shall be shown in the 'selected item' box
*/
void QBrowseButton::setSelectedItem(QString path) {
m_selectedItem = path;
ui_leSelectedItem->setText(path);
}
/** \brief Set icon for 'browse' button
*
* Sets the icon for the 'browse' button to a new QIcon.
*
* \param icon New icon for 'browse' button
*/
void QBrowseButton::setIcon(QIcon icon) {
ui_btnBrowse->setIcon(icon);
}
/** \brief Set 'browse' button caption
*
* Sets the caption of the 'browse' button to a new value.
*
* \param text New caption for 'browse' button
*/
void QBrowseButton::setButtonText(QString text) {
ui_btnBrowse->setText(text);
}
/** \brief Slot for \a clicked signal of 'browse' button
*
* \internal This slot is connected to the \a clicked() signal of \a ui_btnBrowse and shows
* a file or directory selection dialog depending on the settings that have been
* specified for this \a QBrowseButton instance.
*/
void QBrowseButton::btnBrowse_clicked() {
QString selection;
switch (m_mode) {
case QFileDialog::DirectoryOnly:
selection = QFileDialog::getExistingDirectory(this, m_caption, m_selectedItem);
break;
case QFileDialog::AnyFile:
default:
selection = QFileDialog::getOpenFileName(this, m_caption, m_selectedItem, "*");
break;
}
if (selection.isNull())
return;
m_selectedItem = selection;
ui_leSelectedItem->setText(selection);
emit newSelection(selection);
}
<|endoftext|>
|
<commit_before>#include "URIBeacon.h"
#ifdef defined(NRF51) || defined(__RFduino__)
#define MAX_SERVICE_DATA_SIZE 18
#else
#define MAX_SERVICE_DATA_SIZE 15 // only 15 bytes (instead of 18), because flags (3 bytes) are in advertisement data
#endif
static const char* URI_BEACON_PREFIX_SUBSTITUTIONS[] = {
"http://www.",
"https://www.",
"http://",
"https://",
"urn:uuid:"
};
static const char* URI_BEACON_SUFFIX_SUBSTITUTIONS[] = {
".com/",
".org/",
".edu/",
".net/",
".info/",
".biz/",
".gov/",
".com",
".org",
".edu",
".net",
".info",
".biz",
".gov"
};
URIBeacon::URIBeacon(unsigned char req, unsigned char rdy, unsigned char rst) :
_blePeripheral(req, rdy, rst),
_bleService("fed8"),
_bleCharacteristic("fed9", BLERead | BLEBroadcast, MAX_SERVICE_DATA_SIZE)
{
// this->_blePeripheral.setLocalName(uri);
// this->_blePeripheral.setLocalName("uri-beacon");
this->_blePeripheral.setAdvertisedServiceUuid(this->_bleService.uuid());
this->_blePeripheral.setConnectable(false);
this->_blePeripheral.addAttribute(this->_bleService);
this->_blePeripheral.addAttribute(this->_bleCharacteristic);
}
void URIBeacon::begin(unsigned char flags, unsigned char power, const char* uri) {
unsigned char serviceData[MAX_SERVICE_DATA_SIZE];
serviceData[0] = flags;
serviceData[1] = power;
unsigned char compressedURIlength = this->compressURI(uri, (char *)&serviceData[2], sizeof(serviceData) - 2);
this->_bleCharacteristic.setValue(serviceData, 2 + compressedURIlength);
this->_blePeripheral.begin();
this->_bleCharacteristic.broadcast();
}
unsigned char URIBeacon::compressURI(const char* uri, char *compressedUri, unsigned char compressedUriSize) {
String uriString = uri;
// replace prefixes
for (int i = 0; i < (sizeof(URI_BEACON_PREFIX_SUBSTITUTIONS) / sizeof(char *)); i++) {
String replacement = " ";
replacement[0] = (char)(i | 0x80); // set high bit, String.replace does not like '\0' replacement
uriString.replace(URI_BEACON_PREFIX_SUBSTITUTIONS[i], replacement);
}
// replace suffixes
for (int i = 0; i < (sizeof(URI_BEACON_SUFFIX_SUBSTITUTIONS) / sizeof(char *)); i++) {
String replacement = " ";
replacement[0] = (char)(i | 0x80); // set high bit, String.replace does not like '\0' replacement
uriString.replace(URI_BEACON_SUFFIX_SUBSTITUTIONS[i], replacement);
}
unsigned char i = 0;
for (i = 0; i < uriString.length() && i < compressedUriSize; i++) {
compressedUri[i] = (uriString[i] & 0x7f); // assign byte after clearing hight bit
}
return i;
}
void URIBeacon::loop() {
this->_blePeripheral.poll();
}
<commit_msg>- fix some warnings<commit_after>#include "URIBeacon.h"
#if defined(NRF51) || defined(__RFduino__)
#define MAX_SERVICE_DATA_SIZE 18
#else
#define MAX_SERVICE_DATA_SIZE 15 // only 15 bytes (instead of 18), because flags (3 bytes) are in advertisement data
#endif
static const char* URI_BEACON_PREFIX_SUBSTITUTIONS[] = {
"http://www.",
"https://www.",
"http://",
"https://",
"urn:uuid:"
};
static const char* URI_BEACON_SUFFIX_SUBSTITUTIONS[] = {
".com/",
".org/",
".edu/",
".net/",
".info/",
".biz/",
".gov/",
".com",
".org",
".edu",
".net",
".info",
".biz",
".gov"
};
URIBeacon::URIBeacon(unsigned char req, unsigned char rdy, unsigned char rst) :
_blePeripheral(req, rdy, rst),
_bleService("fed8"),
_bleCharacteristic("fed9", BLERead | BLEBroadcast, MAX_SERVICE_DATA_SIZE)
{
// this->_blePeripheral.setLocalName(uri);
// this->_blePeripheral.setLocalName("uri-beacon");
this->_blePeripheral.setAdvertisedServiceUuid(this->_bleService.uuid());
this->_blePeripheral.setConnectable(false);
this->_blePeripheral.addAttribute(this->_bleService);
this->_blePeripheral.addAttribute(this->_bleCharacteristic);
}
void URIBeacon::begin(unsigned char flags, unsigned char power, const char* uri) {
unsigned char serviceData[MAX_SERVICE_DATA_SIZE];
serviceData[0] = flags;
serviceData[1] = power;
unsigned char compressedURIlength = this->compressURI(uri, (char *)&serviceData[2], sizeof(serviceData) - 2);
this->_bleCharacteristic.setValue(serviceData, 2 + compressedURIlength);
this->_blePeripheral.begin();
this->_bleCharacteristic.broadcast();
}
unsigned char URIBeacon::compressURI(const char* uri, char *compressedUri, unsigned char compressedUriSize) {
String uriString = uri;
// replace prefixes
for (unsigned int i = 0; i < (sizeof(URI_BEACON_PREFIX_SUBSTITUTIONS) / sizeof(char *)); i++) {
String replacement = " ";
replacement[0] = (char)(i | 0x80); // set high bit, String.replace does not like '\0' replacement
uriString.replace(URI_BEACON_PREFIX_SUBSTITUTIONS[i], replacement);
}
// replace suffixes
for (unsigned int i = 0; i < (sizeof(URI_BEACON_SUFFIX_SUBSTITUTIONS) / sizeof(char *)); i++) {
String replacement = " ";
replacement[0] = (char)(i | 0x80); // set high bit, String.replace does not like '\0' replacement
uriString.replace(URI_BEACON_SUFFIX_SUBSTITUTIONS[i], replacement);
}
unsigned char i = 0;
for (i = 0; i < uriString.length() && i < compressedUriSize; i++) {
compressedUri[i] = (uriString[i] & 0x7f); // assign byte after clearing hight bit
}
return i;
}
void URIBeacon::loop() {
this->_blePeripheral.poll();
}
<|endoftext|>
|
<commit_before>/*8921005 303677512 maxim vainshtein*/
#include <iostream>
#include <stdlib.h>
#include "Client.h"
#include "Player.h"
#define NAME_INPUT "TreeBots"
#define NAME_INPUT_OPPONENT "Opponent"
int main(int argc, const char * argv[]) {
//First create a client for all the players
Client *udpClient = Client::createClient(ProtocolTypeUDP, 6000);
Player *goalie = Player::createPlayer(PlayerTypeGoalKeeper, udpClient->connection(), NAME_INPUT);
goalie->start();
Player *striker1 = Player::createPlayer(PlayerTypeStrikerBottom, udpClient->connection(), NAME_INPUT);
striker1->start();
Player *striker2 = Player::createPlayer(PlayerTypeStriker, udpClient->connection(), NAME_INPUT);
striker2->start();
Player *striker3 = Player::createPlayer(PlayerTypeStrikerTop, udpClient->connection(), NAME_INPUT);
striker3->start();
Player *striker4 = Player::createPlayer(PlayerTypeStrikerCenter, udpClient->connection(), NAME_INPUT);
striker4->start();
Player *striker5 = Player::createPlayer(PlayerTypeStrikerAux, udpClient->connection(), NAME_INPUT);
striker5->start();
Player *defender1 = Player::createPlayer(PlayerTypeDefender, udpClient->connection(), NAME_INPUT);
defender1->start();
Player *defender2 = Player::createPlayer(PlayerTypeDefenderTop, udpClient->connection(), NAME_INPUT);
defender2->start();
Player *midfield1 = Player::createPlayer(PlayerTypeMidFielder, udpClient->connection(), NAME_INPUT);
midfield1->start();
Player *midfield2 = Player::createPlayer(PlayerTypeMidFielderTop, udpClient->connection(), NAME_INPUT);
midfield2->start();
Player *midfield3 = Player::createPlayer(PlayerTypeMidFielderBottom, udpClient->connection(), NAME_INPUT);
midfield3->start();
//Waits for the player to finish playing
goalie->waitCompletion();
striker1->waitCompletion();
striker2->waitCompletion();
striker3->waitCompletion();
striker4->waitCompletion();
striker5->waitCompletion();
defender1->waitCompletion();
defender2->waitCompletion();
midfield1->waitCompletion();
midfield2->waitCompletion();
midfield3->waitCompletion();
return 0;
}
<commit_msg>Final<commit_after>/*8921005 303677512 maxim vainshtein*/
#include <iostream>
#include <stdlib.h>
#include "Client.h"
#include "Player.h"
#define NAME_INPUT "TreeBots"
int main(int argc, const char * argv[]) {
//First create a client for all the players
Client *udpClient = Client::createClient(ProtocolTypeUDP, 6000);
Player *goalie = Player::createPlayer(PlayerTypeGoalKeeper, udpClient->connection(), NAME_INPUT);
goalie->start();
Player *striker1 = Player::createPlayer(PlayerTypeStrikerBottom, udpClient->connection(), NAME_INPUT);
striker1->start();
Player *striker2 = Player::createPlayer(PlayerTypeStriker, udpClient->connection(), NAME_INPUT);
striker2->start();
Player *striker3 = Player::createPlayer(PlayerTypeStrikerTop, udpClient->connection(), NAME_INPUT);
striker3->start();
Player *striker4 = Player::createPlayer(PlayerTypeStrikerCenter, udpClient->connection(), NAME_INPUT);
striker4->start();
Player *striker5 = Player::createPlayer(PlayerTypeStrikerAux, udpClient->connection(), NAME_INPUT);
striker5->start();
Player *defender1 = Player::createPlayer(PlayerTypeDefender, udpClient->connection(), NAME_INPUT);
defender1->start();
Player *defender2 = Player::createPlayer(PlayerTypeDefenderTop, udpClient->connection(), NAME_INPUT);
defender2->start();
Player *midfield1 = Player::createPlayer(PlayerTypeMidFielder, udpClient->connection(), NAME_INPUT);
midfield1->start();
Player *midfield2 = Player::createPlayer(PlayerTypeMidFielderTop, udpClient->connection(), NAME_INPUT);
midfield2->start();
Player *midfield3 = Player::createPlayer(PlayerTypeMidFielderBottom, udpClient->connection(), NAME_INPUT);
midfield3->start();
//Waits for the player to finish playing
goalie->waitCompletion();
striker1->waitCompletion();
striker2->waitCompletion();
striker3->waitCompletion();
striker4->waitCompletion();
striker5->waitCompletion();
defender1->waitCompletion();
defender2->waitCompletion();
midfield1->waitCompletion();
midfield2->waitCompletion();
midfield3->waitCompletion();
return 0;
}
<|endoftext|>
|
<commit_before>/*
SevenSegment.h - Arduino Library for SM41056 7 Segment Led Display
Copyright (c) 2014 Salvatore Gentile
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 "SevenSegment.h"
// DIGIT A B C D E F G
const byte ZERO[SEGMENTS] = { ON, ON, ON, ON, ON, ON, OFF };
const byte ONE[SEGMENTS] = { OFF, ON, ON, OFF, OFF, OFF, OFF };
const byte TWO[SEGMENTS] = { ON, ON, OFF, ON, ON, OFF, ON };
const byte THREE[SEGMENTS] = { ON, ON, ON, ON, OFF, OFF, ON };
const byte FOUR[SEGMENTS] = { OFF, ON, ON, OFF, OFF, ON, ON };
const byte FIVE[SEGMENTS] = { ON, OFF, ON, ON, OFF, ON, ON };
const byte SIX[SEGMENTS] = { ON, OFF, ON, ON, ON, ON, ON };
const byte SEVEN[SEGMENTS] = { ON, ON, ON, OFF, OFF, OFF, OFF };
const byte EIGHT[SEGMENTS] = { ON, ON, ON, ON, ON, ON, ON };
const byte NINE[SEGMENTS] = { ON, ON, ON, ON, OFF, ON, ON };
const byte LOW_A[SEGMENTS] = { ON, ON, ON, OFF, ON, ON, ON };
const byte LOW_B[SEGMENTS] = { OFF, OFF, ON, ON, ON, ON, ON };
const byte LOW_C[SEGMENTS] = { ON, OFF, OFF, ON, ON, ON, OFF };
const byte LOW_D[SEGMENTS] = { OFF, ON, ON, ON, ON, OFF, ON };
const byte LOW_E[SEGMENTS] = { ON, OFF, OFF, ON, ON, ON, ON };
const byte LOW_F[SEGMENTS] = { ON, OFF, OFF, OFF, ON, ON, ON };
const byte DASH[SEGMENTS] = { OFF, OFF, OFF, OFF, OFF, OFF, ON };
SevenSegment::SevenSegment(int pins[], int dotPin)
{
_pins = pins;
for (int pin = 0; pin < SEGMENTS; pin++)
{
pinMode(_pins[pin], OUTPUT);
}
_dotPin = dotPin;
pinMode(dotPin, OUTPUT);
}
void SevenSegment::display(int digit)
{
display(digit, false);
}
void SevenSegment::display(int digit, bool dot)
{
const byte *selectedDigit = select(digit);
for (int segment = 0; segment < SEGMENTS; segment++)
{
digitalWrite(_pins[segment], selectedDigit[segment]);
}
if (dot)
{
setDot(ON);
}
else
{
setDot(OFF);
}
}
const byte* SevenSegment::select(int digit)
{
switch (digit)
{
case (0):
return ZERO;
break;
case (1):
return ONE;
break;
case (2):
return TWO;
break;
case (3):
return THREE;
break;
case (4):
return FOUR;
break;
case (5):
return FIVE;
break;
case (6):
return SIX;
break;
case (7):
return SEVEN;
break;
case (8):
return EIGHT;
break;
case (9):
return NINE;
break;
case (10):
return LOW_A;
break;
case (11):
return LOW_B;
break;
case (12):
return LOW_C;
break;
case (13):
return LOW_D;
break;
case (14):
return LOW_E;
break;
case (15):
return LOW_F;
break;
default:
return DASH;
}
}
void SevenSegment::setDot(byte status)
{
digitalWrite(_dotPin, status);
}
<commit_msg>Minor fixes<commit_after>/*
SevenSegment.h - Arduino Library for SM41056 7 Segment Led Display
Copyright (c) 2014 Salvatore Gentile
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 "SevenSegment.h"
// DIGIT A B C D E F G
const byte ZERO[SEGMENTS] = { ON, ON, ON, ON, ON, ON, OFF };
const byte ONE[SEGMENTS] = { OFF, ON, ON, OFF, OFF, OFF, OFF };
const byte TWO[SEGMENTS] = { ON, ON, OFF, ON, ON, OFF, ON };
const byte THREE[SEGMENTS] = { ON, ON, ON, ON, OFF, OFF, ON };
const byte FOUR[SEGMENTS] = { OFF, ON, ON, OFF, OFF, ON, ON };
const byte FIVE[SEGMENTS] = { ON, OFF, ON, ON, OFF, ON, ON };
const byte SIX[SEGMENTS] = { ON, OFF, ON, ON, ON, ON, ON };
const byte SEVEN[SEGMENTS] = { ON, ON, ON, OFF, OFF, OFF, OFF };
const byte EIGHT[SEGMENTS] = { ON, ON, ON, ON, ON, ON, ON };
const byte NINE[SEGMENTS] = { ON, ON, ON, ON, OFF, ON, ON };
const byte A[SEGMENTS] = { ON, ON, ON, OFF, ON, ON, ON };
const byte B[SEGMENTS] = { OFF, OFF, ON, ON, ON, ON, ON };
const byte C[SEGMENTS] = { ON, OFF, OFF, ON, ON, ON, OFF };
const byte D[SEGMENTS] = { OFF, ON, ON, ON, ON, OFF, ON };
const byte E[SEGMENTS] = { ON, OFF, OFF, ON, ON, ON, ON };
const byte F[SEGMENTS] = { ON, OFF, OFF, OFF, ON, ON, ON };
const byte DASH[SEGMENTS] = { OFF, OFF, OFF, OFF, OFF, OFF, ON };
SevenSegment::SevenSegment(int pins[], int dotPin)
{
_pins = pins;
for (int pin = 0; pin < SEGMENTS; pin++)
{
pinMode(_pins[pin], OUTPUT);
}
_dotPin = dotPin;
pinMode(dotPin, OUTPUT);
}
void SevenSegment::display(int digit)
{
display(digit, false);
}
void SevenSegment::display(int digit, bool dot)
{
const byte *selectedDigit = select(digit);
for (int segment = 0; segment < SEGMENTS; segment++)
{
digitalWrite(_pins[segment], selectedDigit[segment]);
}
if (dot)
{
setDot(ON);
}
else
{
setDot(OFF);
}
}
const byte* SevenSegment::select(int digit)
{
switch (digit)
{
case (0):
return ZERO;
break;
case (1):
return ONE;
break;
case (2):
return TWO;
break;
case (3):
return THREE;
break;
case (4):
return FOUR;
break;
case (5):
return FIVE;
break;
case (6):
return SIX;
break;
case (7):
return SEVEN;
break;
case (8):
return EIGHT;
break;
case (9):
return NINE;
break;
case (10):
return A;
break;
case (11):
return B;
break;
case (12):
return C;
break;
case (13):
return D;
break;
case (14):
return E;
break;
case (15):
return F;
break;
default:
return DASH;
}
}
void SevenSegment::setDot(byte status)
{
digitalWrite(_dotPin, status);
}
<|endoftext|>
|
<commit_before>#include "ride/project.h"
#include <wx/utils.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
Project::Project(wxTextCtrl* output, const wxString& root_folder) : output_(output), root_folder_(root_folder) {
}
const wxString& Project::root_folder() const {
return root_folder_;
}
void Project::Settings() {
// todo: implement me
}
void Project::Build(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo build");
}
void Project::Clean(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo clean");
}
void Project::Rebuild(bool clean_output) {
if (clean_output) {
CleanOutput();
}
Clean(false);
Build(false);
}
void Project::Doc(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo doc");
}
void Project::Run(bool clean_output) {
if (clean_output) {
CleanOutput();
}
Build(false);
}
void Project::Test(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo test");
}
void Project::Bench(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo bench");
}
void Project::Update(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo update");
}
//////////////////////////////////////////////////////////////////////////
class MyProcess : public wxProcess
{
public:
MyProcess(Project* parent, const wxString& cmd)
: wxProcess(), m_cmd(cmd)
{
m_parent = parent;
}
// instead of overriding this virtual function we might as well process the
// event from it in the frame class - this might be more convenient in some
// cases
virtual void OnTerminate(int pid, int status) {
m_parent->Append(wxString::Format(wxT("Process %u ('%s') terminated with exit code %d."),
pid, m_cmd.c_str(), status));
m_parent->OnAsyncTermination(this);
}
protected:
Project *m_parent;
wxString m_cmd;
};
// A specialization of MyProcess for redirecting the output
class MyPipedProcess : public MyProcess
{
public:
MyPipedProcess(Project *parent, const wxString& cmd)
: MyProcess(parent, cmd)
{
Redirect();
}
virtual void OnTerminate(int pid, int status) {
// show the rest of the output
while (HasInput())
;
m_parent->OnProcessTerminated(this);
MyProcess::OnTerminate(pid, status);
}
virtual bool HasInput() {
bool hasInput = false;
if (IsInputAvailable())
{
wxTextInputStream tis(*GetInputStream());
// this assumes that the output is always line buffered
wxString msg;
msg << m_cmd << wxT(" (stdout): ") << tis.ReadLine();
m_parent->Append(msg);
hasInput = true;
}
if (IsErrorAvailable())
{
wxTextInputStream tis(*GetErrorStream());
// this assumes that the output is always line buffered
wxString msg;
msg << m_cmd << wxT(" (stderr): ") << tis.ReadLine();
m_parent->Append(msg);
hasInput = true;
}
return hasInput;
}
};
void Project::CleanOutput() {
output_->Clear();
}
void Project::Append(const wxString str) {
output_->AppendText(str);
output_->AppendText("\n");
}
void Project::RunCmd(const wxString& cmd) {
MyPipedProcess* process = new MyPipedProcess(this, cmd);
if (root_folder_.IsEmpty()) {
wxMessageBox("No project open, you need to open a cargo project first!", "No project open!", wxICON_INFORMATION);
return;
}
wxExecuteEnv env;
env.cwd = root_folder_;
if (!wxExecute(cmd, wxEXEC_ASYNC | wxEXEC_HIDE_CONSOLE, process, &env)) {
Append(wxString::Format(wxT("Execution of '%s' failed."), cmd.c_str()));
delete process;
}
else {
AddPipedProcess(process);
}
}
void Project::AddPipedProcess(MyPipedProcess *process)
{
m_running.Add(process);
m_allAsync.Add(process);
}
void Project::OnProcessTerminated(MyPipedProcess *process)
{
m_running.Remove(process);
}
void Project::OnAsyncTermination(MyProcess *process)
{
m_allAsync.Remove(process);
delete process;
}
<commit_msg>Less verbose build output<commit_after>#include "ride/project.h"
#include <wx/utils.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
Project::Project(wxTextCtrl* output, const wxString& root_folder) : output_(output), root_folder_(root_folder) {
}
const wxString& Project::root_folder() const {
return root_folder_;
}
void Project::Settings() {
// todo: implement me
}
void Project::Build(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo build");
}
void Project::Clean(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo clean");
}
void Project::Rebuild(bool clean_output) {
if (clean_output) {
CleanOutput();
}
Clean(false);
Build(false);
}
void Project::Doc(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo doc");
}
void Project::Run(bool clean_output) {
if (clean_output) {
CleanOutput();
}
Build(false);
}
void Project::Test(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo test");
}
void Project::Bench(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo bench");
}
void Project::Update(bool clean_output) {
if (clean_output) {
CleanOutput();
}
RunCmd("cargo update");
}
//////////////////////////////////////////////////////////////////////////
class MyProcess : public wxProcess
{
public:
MyProcess(Project* parent, const wxString& cmd)
: wxProcess(), m_cmd(cmd)
{
m_parent = parent;
}
// instead of overriding this virtual function we might as well process the
// event from it in the frame class - this might be more convenient in some
// cases
virtual void OnTerminate(int pid, int status) {
m_parent->Append(wxString::Format(wxT("Process %u ('%s') terminated with exit code %d."),
pid, m_cmd.c_str(), status));
m_parent->Append("");
m_parent->OnAsyncTermination(this);
}
protected:
Project *m_parent;
wxString m_cmd;
};
// A specialization of MyProcess for redirecting the output
class MyPipedProcess : public MyProcess
{
public:
MyPipedProcess(Project *parent, const wxString& cmd)
: MyProcess(parent, cmd)
{
Redirect();
}
virtual void OnTerminate(int pid, int status) {
// show the rest of the output
while (HasInput())
;
m_parent->OnProcessTerminated(this);
MyProcess::OnTerminate(pid, status);
}
virtual bool HasInput() {
bool hasInput = false;
if (IsInputAvailable())
{
wxTextInputStream tis(*GetInputStream());
// this assumes that the output is always line buffered
wxString msg = tis.ReadLine();
m_parent->Append(msg);
hasInput = true;
}
if (IsErrorAvailable())
{
wxTextInputStream tis(*GetErrorStream());
// this assumes that the output is always line buffered
wxString msg = tis.ReadLine();
m_parent->Append(msg);
hasInput = true;
}
return hasInput;
}
};
void Project::CleanOutput() {
output_->Clear();
}
void Project::Append(const wxString str) {
output_->AppendText(str);
output_->AppendText("\n");
}
void Project::RunCmd(const wxString& cmd) {
if (root_folder_.IsEmpty()) {
wxMessageBox("No project open, you need to open a cargo project first!", "No project open!", wxICON_INFORMATION);
return;
}
MyPipedProcess* process = new MyPipedProcess(this, cmd);
Append("> " + cmd);
wxExecuteEnv env;
env.cwd = root_folder_;
if (!wxExecute(cmd, wxEXEC_ASYNC | wxEXEC_HIDE_CONSOLE, process, &env)) {
Append(wxString::Format(wxT("Execution of '%s' failed."), cmd.c_str()));
delete process;
}
else {
AddPipedProcess(process);
}
}
void Project::AddPipedProcess(MyPipedProcess *process)
{
m_running.Add(process);
m_allAsync.Add(process);
}
void Project::OnProcessTerminated(MyPipedProcess *process)
{
m_running.Remove(process);
}
void Project::OnAsyncTermination(MyProcess *process)
{
m_allAsync.Remove(process);
delete process;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbdocutl.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:18:30 $
*
* 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
*
************************************************************************/
#ifdef PCH
#include "core_pch.hxx"
#endif
#pragma hdrstop
// INCLUDE ---------------------------------------------------------------
#include <com/sun/star/sdbc/DataType.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <svtools/zforlist.hxx>
#include "dbdocutl.hxx"
#include "document.hxx"
#include "cell.hxx"
#include "errorcodes.hxx"
using namespace ::com::sun::star;
#define D_TIMEFACTOR 86400.0
// -----------------------------------------------------------------------
// static
void ScDatabaseDocUtil::PutData( ScDocument* pDoc, SCCOL nCol, SCROW nRow, SCTAB nTab,
const uno::Reference<sdbc::XRow>& xRow, long nRowPos,
long nType, BOOL bCurrency, BOOL* pSimpleFlag )
{
String aString;
double nVal = 0.0;
BOOL bValue = FALSE;
BOOL bEmptyFlag = FALSE;
BOOL bError = FALSE;
ULONG nFormatIndex = 0;
//! wasNull calls only if null value was found?
try
{
switch ( nType )
{
case sdbc::DataType::BIT:
case sdbc::DataType::BOOLEAN:
//! use language from doc (here, date/time and currency)?
nFormatIndex = pDoc->GetFormatTable()->GetStandardFormat(
NUMBERFORMAT_LOGICAL, ScGlobal::eLnge );
nVal = (xRow->getBoolean(nRowPos) ? 1 : 0);
bEmptyFlag = ( nVal == 0.0 ) && xRow->wasNull();
bValue = TRUE;
break;
case sdbc::DataType::TINYINT:
case sdbc::DataType::SMALLINT:
case sdbc::DataType::INTEGER:
case sdbc::DataType::BIGINT:
case sdbc::DataType::FLOAT:
case sdbc::DataType::REAL:
case sdbc::DataType::DOUBLE:
case sdbc::DataType::NUMERIC:
case sdbc::DataType::DECIMAL:
//! do the conversion here?
nVal = xRow->getDouble(nRowPos);
bEmptyFlag = ( nVal == 0.0 ) && xRow->wasNull();
bValue = TRUE;
break;
case sdbc::DataType::CHAR:
case sdbc::DataType::VARCHAR:
case sdbc::DataType::LONGVARCHAR:
aString = xRow->getString(nRowPos);
bEmptyFlag = ( aString.Len() == 0 ) && xRow->wasNull();
break;
case sdbc::DataType::DATE:
{
SvNumberFormatter* pFormTable = pDoc->GetFormatTable();
nFormatIndex = pFormTable->GetStandardFormat(
NUMBERFORMAT_DATE, ScGlobal::eLnge );
util::Date aDate = xRow->getDate(nRowPos);
nVal = Date( aDate.Day, aDate.Month, aDate.Year ) -
*pFormTable->GetNullDate();
bEmptyFlag = xRow->wasNull();
bValue = TRUE;
}
break;
case sdbc::DataType::TIME:
{
SvNumberFormatter* pFormTable = pDoc->GetFormatTable();
nFormatIndex = pFormTable->GetStandardFormat(
NUMBERFORMAT_TIME, ScGlobal::eLnge );
util::Time aTime = xRow->getTime(nRowPos);
nVal = ( aTime.Hours * 3600 + aTime.Minutes * 60 +
aTime.Seconds + aTime.HundredthSeconds / 100.0 ) / D_TIMEFACTOR;
bEmptyFlag = xRow->wasNull();
bValue = TRUE;
}
break;
case sdbc::DataType::TIMESTAMP:
{
SvNumberFormatter* pFormTable = pDoc->GetFormatTable();
nFormatIndex = pFormTable->GetStandardFormat(
NUMBERFORMAT_DATETIME, ScGlobal::eLnge );
util::DateTime aStamp = xRow->getTimestamp(nRowPos);
nVal = ( Date( aStamp.Day, aStamp.Month, aStamp.Year ) -
*pFormTable->GetNullDate() ) +
( aStamp.Hours * 3600 + aStamp.Minutes * 60 +
aStamp.Seconds + aStamp.HundredthSeconds / 100.0 ) / D_TIMEFACTOR;
bEmptyFlag = xRow->wasNull();
bValue = TRUE;
}
break;
case sdbc::DataType::SQLNULL:
bEmptyFlag = TRUE;
break;
case sdbc::DataType::BINARY:
case sdbc::DataType::VARBINARY:
case sdbc::DataType::LONGVARBINARY:
default:
bError = TRUE; // unknown type
}
}
catch ( uno::Exception& )
{
bError = TRUE;
}
if ( bValue && bCurrency )
nFormatIndex = pDoc->GetFormatTable()->GetStandardFormat(
NUMBERFORMAT_CURRENCY, ScGlobal::eLnge );
ScBaseCell* pCell;
if (bEmptyFlag)
{
pCell = NULL;
pDoc->PutCell( nCol, nRow, nTab, pCell );
}
else if (bError)
{
pDoc->SetError( nCol, nRow, nTab, NOVALUE );
}
else if (bValue)
{
pCell = new ScValueCell( nVal );
if (nFormatIndex == 0)
pDoc->PutCell( nCol, nRow, nTab, pCell );
else
pDoc->PutCell( nCol, nRow, nTab, pCell, nFormatIndex );
}
else
{
if (aString.Len())
{
pCell = ScBaseCell::CreateTextCell( aString, pDoc );
if ( pSimpleFlag && pCell->GetCellType() == CELLTYPE_EDIT )
*pSimpleFlag = FALSE;
}
else
pCell = NULL;
pDoc->PutCell( nCol, nRow, nTab, pCell );
}
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.6.216); FILE MERGED 2006/07/12 10:01:30 kaib 1.6.216.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbdocutl.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-07-21 10:50:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
// INCLUDE ---------------------------------------------------------------
#include <com/sun/star/sdbc/DataType.hpp>
#include <com/sun/star/sdbc/XRow.hpp>
#include <svtools/zforlist.hxx>
#include "dbdocutl.hxx"
#include "document.hxx"
#include "cell.hxx"
#include "errorcodes.hxx"
using namespace ::com::sun::star;
#define D_TIMEFACTOR 86400.0
// -----------------------------------------------------------------------
// static
void ScDatabaseDocUtil::PutData( ScDocument* pDoc, SCCOL nCol, SCROW nRow, SCTAB nTab,
const uno::Reference<sdbc::XRow>& xRow, long nRowPos,
long nType, BOOL bCurrency, BOOL* pSimpleFlag )
{
String aString;
double nVal = 0.0;
BOOL bValue = FALSE;
BOOL bEmptyFlag = FALSE;
BOOL bError = FALSE;
ULONG nFormatIndex = 0;
//! wasNull calls only if null value was found?
try
{
switch ( nType )
{
case sdbc::DataType::BIT:
case sdbc::DataType::BOOLEAN:
//! use language from doc (here, date/time and currency)?
nFormatIndex = pDoc->GetFormatTable()->GetStandardFormat(
NUMBERFORMAT_LOGICAL, ScGlobal::eLnge );
nVal = (xRow->getBoolean(nRowPos) ? 1 : 0);
bEmptyFlag = ( nVal == 0.0 ) && xRow->wasNull();
bValue = TRUE;
break;
case sdbc::DataType::TINYINT:
case sdbc::DataType::SMALLINT:
case sdbc::DataType::INTEGER:
case sdbc::DataType::BIGINT:
case sdbc::DataType::FLOAT:
case sdbc::DataType::REAL:
case sdbc::DataType::DOUBLE:
case sdbc::DataType::NUMERIC:
case sdbc::DataType::DECIMAL:
//! do the conversion here?
nVal = xRow->getDouble(nRowPos);
bEmptyFlag = ( nVal == 0.0 ) && xRow->wasNull();
bValue = TRUE;
break;
case sdbc::DataType::CHAR:
case sdbc::DataType::VARCHAR:
case sdbc::DataType::LONGVARCHAR:
aString = xRow->getString(nRowPos);
bEmptyFlag = ( aString.Len() == 0 ) && xRow->wasNull();
break;
case sdbc::DataType::DATE:
{
SvNumberFormatter* pFormTable = pDoc->GetFormatTable();
nFormatIndex = pFormTable->GetStandardFormat(
NUMBERFORMAT_DATE, ScGlobal::eLnge );
util::Date aDate = xRow->getDate(nRowPos);
nVal = Date( aDate.Day, aDate.Month, aDate.Year ) -
*pFormTable->GetNullDate();
bEmptyFlag = xRow->wasNull();
bValue = TRUE;
}
break;
case sdbc::DataType::TIME:
{
SvNumberFormatter* pFormTable = pDoc->GetFormatTable();
nFormatIndex = pFormTable->GetStandardFormat(
NUMBERFORMAT_TIME, ScGlobal::eLnge );
util::Time aTime = xRow->getTime(nRowPos);
nVal = ( aTime.Hours * 3600 + aTime.Minutes * 60 +
aTime.Seconds + aTime.HundredthSeconds / 100.0 ) / D_TIMEFACTOR;
bEmptyFlag = xRow->wasNull();
bValue = TRUE;
}
break;
case sdbc::DataType::TIMESTAMP:
{
SvNumberFormatter* pFormTable = pDoc->GetFormatTable();
nFormatIndex = pFormTable->GetStandardFormat(
NUMBERFORMAT_DATETIME, ScGlobal::eLnge );
util::DateTime aStamp = xRow->getTimestamp(nRowPos);
nVal = ( Date( aStamp.Day, aStamp.Month, aStamp.Year ) -
*pFormTable->GetNullDate() ) +
( aStamp.Hours * 3600 + aStamp.Minutes * 60 +
aStamp.Seconds + aStamp.HundredthSeconds / 100.0 ) / D_TIMEFACTOR;
bEmptyFlag = xRow->wasNull();
bValue = TRUE;
}
break;
case sdbc::DataType::SQLNULL:
bEmptyFlag = TRUE;
break;
case sdbc::DataType::BINARY:
case sdbc::DataType::VARBINARY:
case sdbc::DataType::LONGVARBINARY:
default:
bError = TRUE; // unknown type
}
}
catch ( uno::Exception& )
{
bError = TRUE;
}
if ( bValue && bCurrency )
nFormatIndex = pDoc->GetFormatTable()->GetStandardFormat(
NUMBERFORMAT_CURRENCY, ScGlobal::eLnge );
ScBaseCell* pCell;
if (bEmptyFlag)
{
pCell = NULL;
pDoc->PutCell( nCol, nRow, nTab, pCell );
}
else if (bError)
{
pDoc->SetError( nCol, nRow, nTab, NOVALUE );
}
else if (bValue)
{
pCell = new ScValueCell( nVal );
if (nFormatIndex == 0)
pDoc->PutCell( nCol, nRow, nTab, pCell );
else
pDoc->PutCell( nCol, nRow, nTab, pCell, nFormatIndex );
}
else
{
if (aString.Len())
{
pCell = ScBaseCell::CreateTextCell( aString, pDoc );
if ( pSimpleFlag && pCell->GetCellType() == CELLTYPE_EDIT )
*pSimpleFlag = FALSE;
}
else
pCell = NULL;
pDoc->PutCell( nCol, nRow, nTab, pCell );
}
}
<|endoftext|>
|
<commit_before><commit_msg>Related: #i91494# same for CTL as CJK<commit_after><|endoftext|>
|
<commit_before>#ifndef PB_FAST_RAND
#define PB_FAST_RAND
#include <chrono>
#include <cstdint>
#include <cmath>
/* 16 Random 64-bit unsigned ints from Random.org
* https://xkcd.com/221/ */
#define RAND_SEED \
0x3defc96632ef02b9, \
0x8e90363c0e17b94f, \
0xa475bebf725d5637, \
0x0a730a049bf3226e, \
0xf4ae35c08c925568, \
0xef7ad28ad649d06f, \
0xae7bad73c3749a5c, \
0x58e7ab85e6bc90c8, \
0x2b9ffce661908871, \
0xb6f9013a41f3483c, \
0x59cdd885b0a75528, \
0x7ba6bac4b645578c, \
0x70d174668607356f, \
0x1f9bf4c0ac86d9d8, \
0x6edb83c3ed843533
class pbfastrand
{
private:
//State infomation
uint64_t state[16]{RAND_SEED};
unsigned p = 0;
//For generating normal
double z0 = 0;
double z1 = 0;
bool do_gen_unif = false;
//For generating 32bit
uint64_t rand_64 = 0;
bool do_gen_32 = false;
//Constants
static constexpr double epsilon = std::numeric_limits<double>::min();
static constexpr double two_pi = 2.0 * 3.14159265358979323846L;
public:
pbfastrand() { }
~pbfastrand() { }
//No copying
pbfastrand(const pbfastrand&) = delete;
pbfastrand(const pbfastrand&&) = delete;
pbfastrand& operator=(const pbfastrand&) = delete;
pbfastrand& operator=(const pbfastrand&&) = delete;
//Seed using small xorshift with current time
void seed()
{
uint64_t s =
std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::system_clock::now().time_since_epoch()).count();
for(auto i = 0; i < 16; i++)
{
s ^= s >> 12;
s ^= s << 25;
s ^= s >> 27;
state[i] = s * 2685821657736338717ull;
}
}
//Seed using an array of 64 bit unsigned ints
//If n > 16, we just take the first 16
void seed(uint64_t* seed_arr, size_t n)
{
size_t len = (n < 16) ? n : 16;
for(unsigned i = 0; i < len; i++)
state[i] = seed_arr[i];
}
//Standard generate
uint64_t gen()
{
uint64_t s0 = state[p];
uint64_t s1 = state[p = (p+1) & 15];
s1 ^= s1 << 31;
s1 ^= s1 >> 11;
s0 ^= s0 >> 30;
return (state[p] = s0 ^ s1) * 1181783497276652981ull;
}
//Generates a signed 32 bit integer
int32_t gen_int32()
{
uint32_t rnd = gen_uint32();
return *(int32_t*)(&rnd);
}
//Generates an unsigned 32 bit integer
//Just takes half the bits from a 64 bit
uint32_t gen_uint32()
{
uint32_t rnd;
do_gen_32 = !do_gen_32;
if(!do_gen_32)
return rand_64 & UINT32_MAX;
rand_64 = gen();
rnd = rand_64 & UINT32_MAX;
rand_64 >>= 32;
return rnd;
}
//Generates a signed 64 bit integer
int64_t gen_int64()
{
uint64_t rnd = gen();
return *(int64_t*)(&rnd);
}
//Generates an unsigned 64 bit integer
inline uint64_t gen_uint64()
{
return gen();
}
//Generate a uniformly distributed random double in [0,1]
double gen_unif()
{
uint64_t rand64 = gen_uint64();
return (double)rand64 * (1.0L / UINT64_MAX);
}
//Generate a normally distributed random double
double gen_norm(double mu = 0.0L, double sigma = 1.0L)
{
do_gen_unif = !do_gen_unif;
if(!do_gen_unif)
return z1 * sigma + mu;
double u1, u2;
do
{
u1 = gen_unif();
u2 = gen_unif();
} while(u1 <= epsilon);
z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2);
z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2);
return z0 * sigma + mu;
}
//Generates a chi-squared random double
//Sum of k squared standard normal random variables
double gen_chisq(unsigned k)
{
double res = 0.0L;
for(unsigned i = 0; i < k; i++)
{
double x = gen_norm();
res += (x * x);
}
return res;
}
//Beta
double gen_beta(double alpha, double beta)
{
double gamm = tgamma(alpha + beta) / (tgamma(alpha) * tgamma(beta));
double max_x = (alpha - 1.0L) / (alpha + beta - 2.0L);
double max_y = gamm * pow(max_x, alpha - 1.0L) * pow(1.0L - max_x, beta - 1.0L);
double res, u, y;
do
{
u = gen_unif();
y = gen_unif();
res = gamm * pow(y, alpha - 1.0L) * pow(1.0L - y, beta - 1.0L);
} while(u > (res / max_y));
return y;
}
//Generates an exponential random double
//Amount of time between events in a Poisson process
//with const avg time between events lambda
double gen_exp(double lambda)
{
double u1 = gen_unif();
while(u1 <= epsilon)
u1 = gen_unif();
return (-1.0L / lambda) * log(1.0L - u1);
}
//Erlang
//Sum of n independent exponentials with mean 1/lambda
template <typename IntType=unsigned>
double gen_erlang(IntType n, double lambda)
{
double mult = 1.0L;
for(auto i = 0; i < n; i++)
mult *= gen_unif();
return (-1.0L / lambda) * log(mult);
}
//Generates a random Poisson variable
//Number of events occuring in a const time interval with rate lambda
template <typename IntType=unsigned>
IntType gen_poisson(double lambda)
{
IntType res(0);
double mult = 1.0L;
while((mult *= gen_unif()) > exp(-1.0L * lambda))
res++;
return res;
}
//Generates a bernoulli random trial with success p
//1 if success, 0 if failure, probability p
template <typename IntType=int>
inline IntType gen_bernoulli(double p)
{
return (gen_unif() < p) ? IntType(1) : IntType(0);
}
//Generates a binomial random variable with success p and n trials
//Number of successes in n indpendent trials each with probability p
template <typename IntType=unsigned>
IntType gen_binomial(double p, IntType n)
{
IntType res(0);
for(auto i = 0; i < n; i++)
res += gen_bernoulli(p);
return res;
}
//
template <typename IntType=unsigned>
inline IntType gen_geometric(double p)
{
return floor(log(gen_unif()) / log(1.0L - p));
}
//Number of failures before the nth success of bernoulli trials
//with probablity of success p
template <typename IntType=unsigned>
IntType gen_negbinomial(double p, IntType n)
{
IntType res(0);
for(auto i = 0; i < n; i++)
res += gen_geometric<IntType>(p);
return res;
}
}; //end class pbfastrand
#undef RAND_SEED
#endif //PB_FAST_RAND
<commit_msg>Updates to pbfastrand<commit_after>#ifndef PB_FAST_RAND
#define PB_FAST_RAND
#include <chrono>
#include <cstdint>
#include <cmath>
//Check for uint64_t, work with 32 bit if not
#ifdef UINT64_MAX
#define STATE_SIZE 16
/* 16 Random 64-bit unsigned ints from Random.org
* https://xkcd.com/221/ */
#define RAND_SEED \
0x3defc96632ef02b9, \
0x8e90363c0e17b94f, \
0xa475bebf725d5637, \
0x0a730a049bf3226e, \
0xf4ae35c08c925568, \
0xef7ad28ad649d06f, \
0xae7bad73c3749a5c, \
0x58e7ab85e6bc90c8, \
0x2b9ffce661908871, \
0xb6f9013a41f3483c, \
0x59cdd885b0a75528, \
0x7ba6bac4b645578c, \
0x70d174668607356f, \
0x1f9bf4c0ac86d9d8, \
0x6edb83c3ed843533
#else
//TODO: what to do if no 64 bit
#endif
class pbfastrand
{
private:
//State infomation
uint64_t state[STATE_SIZE]{RAND_SEED};
unsigned p = 0;
//For generating normal
double z0 = 0;
double z1 = 0;
bool do_gen_unif = false;
//For generating 32bit
uint64_t rand_64 = 0;
bool do_gen_32 = false;
//Constants
static constexpr double epsilon = std::numeric_limits<double>::min();
static constexpr double two_pi = 2.0 * 3.14159265358979323846L;
public:
pbfastrand() { }
~pbfastrand() { }
//No copying
pbfastrand(const pbfastrand&) = delete;
pbfastrand(const pbfastrand&&) = delete;
pbfastrand& operator=(const pbfastrand&) = delete;
pbfastrand& operator=(const pbfastrand&&) = delete;
//Seed using small xorshift with current time
void seed()
{
uint64_t s =
std::chrono::duration_cast<std::chrono::milliseconds>
(std::chrono::system_clock::now().time_since_epoch()).count();
for(auto i = 0; i < STATE_SIZE; i++)
{
s ^= s >> 12;
s ^= s << 25;
s ^= s >> 27;
state[i] = s * 2685821657736338717ull;
}
}
//Seed using an array of 64 bit unsigned ints
//If n > STATE_SIZE, we just take the first STATE_SIZE
void seed(uint64_t* seed_arr, size_t n)
{
size_t len = (n < STATE_SIZE) ? n : STATE_SIZE;
for(unsigned i = 0; i < len; i++)
state[i] = seed_arr[i];
}
//Standard generate
uint64_t gen()
{
uint64_t s0 = state[p];
uint64_t s1 = state[p = (p+1) & 15];
s1 ^= s1 << 31;
s1 ^= s1 >> 11;
s0 ^= s0 >> 30;
return (state[p] = s0 ^ s1) * 1181783497276652981ull;
}
//Generates a signed 32 bit integer
int32_t gen_int32()
{
uint32_t rnd = gen_uint32();
return *(int32_t*)(&rnd);
}
//Generates an unsigned 32 bit integer
//Just takes half the bits from a 64 bit
uint32_t gen_uint32()
{
uint32_t rnd;
do_gen_32 = !do_gen_32;
if(!do_gen_32)
return rand_64 & UINT32_MAX;
rand_64 = gen();
rnd = rand_64 & UINT32_MAX;
rand_64 >>= 32;
return rnd;
}
//Generates a signed 64 bit integer
int64_t gen_int64()
{
uint64_t rnd = gen();
return *(int64_t*)(&rnd);
}
//Generates an unsigned 64 bit integer
inline uint64_t gen_uint64()
{
return gen();
}
//Generate a uniformly distributed random double in [0,1]
inline double gen_unif()
{
return (double)gen() * (1.0L / (double)UINT64_MAX);
}
//Generate a uniformly distributed random double in [min,max]
//NOTE: don't combine with default, save some instructions for [0,1]
double gen_unif(double min, double max)
{
return ((max-min) * gen_unif()) + min;
}
//Generate a normally distributed random double
double gen_norm(double mu = 0.0L, double sigma = 1.0L)
{
do_gen_unif = !do_gen_unif;
if(!do_gen_unif)
return z1 * sigma + mu;
double u1, u2;
do
{
u1 = gen_unif();
u2 = gen_unif();
} while(u1 <= epsilon);
z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2);
z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2);
return z0 * sigma + mu;
}
//Generates a chi-squared random double
//Sum of k squared standard normal random variables
double gen_chisq(unsigned k)
{
double res = 0.0L;
for(unsigned i = 0; i < k; i++)
{
double x = gen_norm();
res += (x * x);
}
return res;
}
//Beta
double gen_beta(double alpha, double beta)
{
double gamm = tgamma(alpha + beta) / (tgamma(alpha) * tgamma(beta));
double max_x = (alpha - 1.0L) / (alpha + beta - 2.0L);
double max_y = gamm * pow(max_x, alpha - 1.0L) * pow(1.0L - max_x, beta - 1.0L);
double res, u, y;
do
{
u = gen_unif();
y = gen_unif();
res = gamm * pow(y, alpha - 1.0L) * pow(1.0L - y, beta - 1.0L);
} while(u > (res / max_y));
return y;
}
//Generates an exponential random double
//Amount of time between events in a Poisson process
//with const avg time between events lambda
double gen_exp(double lambda)
{
double u1 = gen_unif();
while(u1 <= epsilon)
u1 = gen_unif();
return (-1.0L / lambda) * log(1.0L - u1);
}
//Erlang
//Sum of n independent exponentials with mean 1/lambda
template <typename IntType=unsigned>
double gen_erlang(IntType n, double lambda)
{
double mult = 1.0L;
for(auto i = 0; i < n; i++)
mult *= gen_unif();
return (-1.0L / lambda) * log(mult);
}
//Generates a random Poisson variable
//Number of events occuring in a const time interval with rate lambda
template <typename IntType=unsigned>
IntType gen_poisson(double lambda)
{
IntType res(0);
double mult = 1.0L;
while((mult *= gen_unif()) > exp(-1.0L * lambda))
res++;
return res;
}
//Generates a bernoulli random trial with success p
//1 if success, 0 if failure, probability p
template <typename IntType=int>
inline IntType gen_bernoulli(double p)
{
return (gen_unif() < p) ? IntType(1) : IntType(0);
}
//Generates a binomial random variable with success p and n trials
//Number of successes in n indpendent trials each with probability p
template <typename IntType=unsigned>
IntType gen_binomial(double p, IntType n)
{
IntType res(0);
for(auto i = 0; i < n; i++)
res += gen_bernoulli(p);
return res;
}
//
template <typename IntType=unsigned>
inline IntType gen_geometric(double p)
{
return floor(log(gen_unif()) / log(1.0L - p));
}
//Number of failures before the nth success of bernoulli trials
//with probablity of success p
template <typename IntType=unsigned>
IntType gen_negbinomial(double p, IntType n)
{
IntType res(0);
for(auto i = 0; i < n; i++)
res += gen_geometric<IntType>(p);
return res;
}
}; //end class pbfastrand
#undef RAND_SEED
#endif //PB_FAST_RAND
<|endoftext|>
|
<commit_before>#include "breedSFC.h"
#include "TApplication.h"
#include "TCanvas.h"
#include "TPaveText.h"
#include "TPolyLine3D.h"
#include "TPad.h"
#include "TView.h"
#include "TPolyMarker3D.h"
int main(int argc, char **argv) {
int N = 3;
SFCCube c = SFCCube(N);
c.print();
TApplication theApp("App", &argc, argv);
TCanvas * c1 = new TCanvas("c1","PolyLine3D & PolyMarker3D Window",200,10,700,500);
TPad * p1 = new TPad("p1","p1",0.05,0.02,0.95,0.82,46,3,1);
p1->Draw();
p1->cd();
TView * view = TView::CreateView(1);
view->SetRange(-N,-N,-N,N,N,N);
view->ShowAxis();
view->SetPerspective();
TPolyMarker3D * centers = new TPolyMarker3D(N * N * 6, 2);
int i = 0;
for (auto tile : c.getTiles()) {
auto center = tile->getCenter();
centers->SetPoint(i++, center.x(), center.y(), center.z());
int j = 0;
TPolyLine3D * outline = new TPolyLine3D(4);
for (auto point : tile->getPoints()) {
outline->SetPoint(j++, center.x(), center.y(), center.z());
}
outline->Draw();
}
centers->Draw();
// theApp.Run(kTRUE);
// cout << "hello" << endl;
theApp.Run();
return 0;
// TApplication theApp("App", &argc, argv);
// // auto f = [=](double x){ return x * x; };
// // cout << f(4) << endl;
// TCanvas * c1 = new TCanvas("c1","PolyLine3D & PolyMarker3D Window",200,10,700,500);
// // create a pad
// // auto p1 = new TPad("p1","p1",0.05,0.02,0.95,0.82,46,3,1);
// TPad * p1 = new TPad("p1","p1",0.05,0.02,0.95,0.82,46,3,1);
// p1->Draw();
// p1->cd();
// // creating a view
// TView * view = TView::CreateView(1);
// view->SetRange(5,5,5,25,25,25);
// // create a first PolyLine3D
// TPolyLine3D *pl3d1 = new TPolyLine3D(5);
// // set points
// pl3d1->SetPoint(0, 10, 10, 10);
// pl3d1->SetPoint(1, 15, 15, 10);
// pl3d1->SetPoint(2, 20, 15, 15);
// pl3d1->SetPoint(3, 20, 20, 20);
// pl3d1->SetPoint(4, 10, 10, 20);
// // set attributes
// pl3d1->SetLineWidth(3);
// pl3d1->SetLineColor(5);
// // create a second PolyLine3D
// TPolyLine3D *pl3d2 = new TPolyLine3D(4);
// // set points
// pl3d2->SetPoint(0, 5, 10, 5);
// pl3d2->SetPoint(1, 10, 15, 8);
// pl3d2->SetPoint(2, 15, 15, 18);
// pl3d2->SetPoint(3, 5, 20, 20);
// pl3d2->SetPoint(4, 10, 10, 5);
// // set attributes
// pl3d2->SetLineWidth(5);
// pl3d2->SetLineColor(2);
// // create a first PolyMarker3D
// TPolyMarker3D *pm3d1 = new TPolyMarker3D(12);
// // set points
// pm3d1->SetPoint(0, 10, 10, 10);
// pm3d1->SetPoint(1, 11, 15, 11);
// pm3d1->SetPoint(2, 12, 15, 9);
// pm3d1->SetPoint(3, 13, 17, 20);
// pm3d1->SetPoint(4, 14, 16, 15);
// pm3d1->SetPoint(5, 15, 20, 15);
// pm3d1->SetPoint(6, 16, 18, 10);
// pm3d1->SetPoint(7, 17, 15, 10);
// pm3d1->SetPoint(8, 18, 22, 15);
// pm3d1->SetPoint(9, 19, 28, 25);
// pm3d1->SetPoint(10, 20, 12, 15);
// pm3d1->SetPoint(11, 21, 12, 15);
// // set marker size, color & style
// pm3d1->SetMarkerSize(2);
// pm3d1->SetMarkerColor(4);
// pm3d1->SetMarkerStyle(2);
// // create a second PolyMarker3D
// TPolyMarker3D *pm3d2 = new TPolyMarker3D(8);
// pm3d2->SetPoint(0, 22, 15, 15);
// pm3d2->SetPoint(1, 23, 18, 21);
// pm3d2->SetPoint(2, 24, 26, 13);
// pm3d2->SetPoint(3, 25, 17, 15);
// pm3d2->SetPoint(4, 26, 20, 15);
// pm3d2->SetPoint(5, 27, 15, 18);
// pm3d2->SetPoint(6, 28, 20, 10);
// pm3d2->SetPoint(7, 29, 20, 20);
// // set marker size, color & style
// pm3d2->SetMarkerSize(2);
// pm3d2->SetMarkerColor(1);
// pm3d2->SetMarkerStyle(8);
// // draw
// pl3d1->Draw();
// pl3d2->Draw();
// pm3d1->Draw();
// pm3d2->Draw();
// //
// // draw a title/explanation in the canvas pad
// c1->cd();
// TPaveText *title = new TPaveText(0.1,0.85,0.9,0.97);
// title->SetFillColor(24);
// title->AddText("Examples of 3-D primitives");
// TText *click=title->AddText("Click anywhere on the picture to rotate");
// click->SetTextColor(4);
// title->Draw();
// theApp.Run(kTRUE);
// cout << "hello" << endl;
// theApp.Run();
// return 0;
}
<commit_msg>Fix drawing in the playground.<commit_after>#include "breedSFC.h"
#include "TApplication.h"
#include "TCanvas.h"
#include "TPaveText.h"
#include "TPolyLine3D.h"
#include "TPad.h"
#include "TView.h"
#include "TPolyMarker3D.h"
int main(int argc, char **argv) {
int N = 3;
SFCCube c = SFCCube(N);
c.print();
TApplication theApp("App", &argc, argv);
TCanvas * c1 = new TCanvas("c1","PolyLine3D & PolyMarker3D Window",200,10,700,500);
TPad * p1 = new TPad("p1","p1",0.05,0.02,0.95,0.82,46,3,1);
p1->Draw();
p1->cd();
TView * view = TView::CreateView(1);
view->SetRange(-1,-1,-1,1,1,1);
view->ShowAxis();
view->SetPerspective();
TPolyMarker3D * centers = new TPolyMarker3D(N * N * 6, 2);
int i = 0;
for (auto tile : c.getTiles()) {
auto center = tile->getCenter();
centers->SetPoint(i++, center.x(), center.y(), center.z());
int j = 0;
TPolyLine3D * outline = new TPolyLine3D(4);
for (auto point : tile->getPoints()) {
outline->SetPoint(j++, point.x(), point.y(), point.z());
}
outline->Draw();
}
centers->Draw();
// theApp.Run(kTRUE);
// cout << "hello" << endl;
theApp.Run();
return 0;
// TApplication theApp("App", &argc, argv);
// // auto f = [=](double x){ return x * x; };
// // cout << f(4) << endl;
// TCanvas * c1 = new TCanvas("c1","PolyLine3D & PolyMarker3D Window",200,10,700,500);
// // create a pad
// // auto p1 = new TPad("p1","p1",0.05,0.02,0.95,0.82,46,3,1);
// TPad * p1 = new TPad("p1","p1",0.05,0.02,0.95,0.82,46,3,1);
// p1->Draw();
// p1->cd();
// // creating a view
// TView * view = TView::CreateView(1);
// view->SetRange(5,5,5,25,25,25);
// // create a first PolyLine3D
// TPolyLine3D *pl3d1 = new TPolyLine3D(5);
// // set points
// pl3d1->SetPoint(0, 10, 10, 10);
// pl3d1->SetPoint(1, 15, 15, 10);
// pl3d1->SetPoint(2, 20, 15, 15);
// pl3d1->SetPoint(3, 20, 20, 20);
// pl3d1->SetPoint(4, 10, 10, 20);
// // set attributes
// pl3d1->SetLineWidth(3);
// pl3d1->SetLineColor(5);
// // create a second PolyLine3D
// TPolyLine3D *pl3d2 = new TPolyLine3D(4);
// // set points
// pl3d2->SetPoint(0, 5, 10, 5);
// pl3d2->SetPoint(1, 10, 15, 8);
// pl3d2->SetPoint(2, 15, 15, 18);
// pl3d2->SetPoint(3, 5, 20, 20);
// pl3d2->SetPoint(4, 10, 10, 5);
// // set attributes
// pl3d2->SetLineWidth(5);
// pl3d2->SetLineColor(2);
// // create a first PolyMarker3D
// TPolyMarker3D *pm3d1 = new TPolyMarker3D(12);
// // set points
// pm3d1->SetPoint(0, 10, 10, 10);
// pm3d1->SetPoint(1, 11, 15, 11);
// pm3d1->SetPoint(2, 12, 15, 9);
// pm3d1->SetPoint(3, 13, 17, 20);
// pm3d1->SetPoint(4, 14, 16, 15);
// pm3d1->SetPoint(5, 15, 20, 15);
// pm3d1->SetPoint(6, 16, 18, 10);
// pm3d1->SetPoint(7, 17, 15, 10);
// pm3d1->SetPoint(8, 18, 22, 15);
// pm3d1->SetPoint(9, 19, 28, 25);
// pm3d1->SetPoint(10, 20, 12, 15);
// pm3d1->SetPoint(11, 21, 12, 15);
// // set marker size, color & style
// pm3d1->SetMarkerSize(2);
// pm3d1->SetMarkerColor(4);
// pm3d1->SetMarkerStyle(2);
// // create a second PolyMarker3D
// TPolyMarker3D *pm3d2 = new TPolyMarker3D(8);
// pm3d2->SetPoint(0, 22, 15, 15);
// pm3d2->SetPoint(1, 23, 18, 21);
// pm3d2->SetPoint(2, 24, 26, 13);
// pm3d2->SetPoint(3, 25, 17, 15);
// pm3d2->SetPoint(4, 26, 20, 15);
// pm3d2->SetPoint(5, 27, 15, 18);
// pm3d2->SetPoint(6, 28, 20, 10);
// pm3d2->SetPoint(7, 29, 20, 20);
// // set marker size, color & style
// pm3d2->SetMarkerSize(2);
// pm3d2->SetMarkerColor(1);
// pm3d2->SetMarkerStyle(8);
// // draw
// pl3d1->Draw();
// pl3d2->Draw();
// pm3d1->Draw();
// pm3d2->Draw();
// //
// // draw a title/explanation in the canvas pad
// c1->cd();
// TPaveText *title = new TPaveText(0.1,0.85,0.9,0.97);
// title->SetFillColor(24);
// title->AddText("Examples of 3-D primitives");
// TText *click=title->AddText("Click anywhere on the picture to rotate");
// click->SetTextColor(4);
// title->Draw();
// theApp.Run(kTRUE);
// cout << "hello" << endl;
// theApp.Run();
// return 0;
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* 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 "utility/TemplateUtil.hpp"
#include <memory>
#include <string>
#include <sstream>
#include "utility/Macros.hpp"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace quickstep {
class SomeArgType {
public:
explicit SomeArgType(std::string value) : value_(value) {
}
SomeArgType(SomeArgType &&arg) {
value_ = std::move(arg.value_);
}
std::string toString() const {
return value_;
}
private:
std::string value_;
DISALLOW_COPY_AND_ASSIGN(SomeArgType);
};
class BaseClass {
public:
virtual std::string toString() const = 0;
};
template <bool c1, bool c2, bool c3, bool c4, bool c5, bool c6>
class SomeClass : public BaseClass {
public:
SomeClass(int a1, SomeArgType &&a2)
: a1_(a1), a2_(std::forward<SomeArgType>(a2)) {
}
std::string toString() const override {
std::ostringstream oss;
oss << "{ ";
if (c1) {
oss << "c1 ";
}
if (c2) {
oss << "c2 ";
}
if (c3) {
oss << "c3 ";
}
if (c4) {
oss << "c4 ";
}
if (c5) {
oss << "c5 ";
}
if (c6) {
oss << "c6 ";
}
oss << "} " << a1_ << " " << a2_.toString();
return oss.str();
}
private:
int a1_;
SomeArgType a2_;
};
//void RunTest(bool c1, bool c2, bool c3, bool c4, bool c5, bool c6, std::string expected) {
// // arg should be perfectly forwarded.
// SomeArgType arg("xyz");
//
// std::unique_ptr<BaseClass> base(
// CreateBoolInstantiatedInstance<SomeClass, BaseClass>(std::forward_as_tuple(10, std::move(arg)),
// c1, c2, c3, c4, c5, c6));
// EXPECT_TRUE(base->toString() == expected);
//}
TEST(TemplateUtilTest, TemplateUtilTest) {
// RunTest(true, false, true, false, true, false, "{ c1 c3 c5 } 10 xyz");
// RunTest(true, true, true, true, true, true, "{ c1 c2 c3 c4 c5 c6 } 10 xyz");
// RunTest(false, false, true, true, false, false, "{ c3 c4 } 10 xyz");
// RunTest(false, false, false, false, false, false, "{ } 10 xyz");
std::tuple<int, float, std::string> value(1, 2.5, "abc");
EXPECT_TRUE(std::get<0>(value) == 1);
EXPECT_TRUE(std::get<1>(value) == 2.5);
EXPECT_TRUE(std::get<2>(value) == std::string("abc"));
}
} // namespace quickstep
<commit_msg>test_forward_get_tuple_on_travis_ci<commit_after>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* 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 "utility/TemplateUtil.hpp"
#include <memory>
#include <string>
#include <sstream>
#include "utility/Macros.hpp"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace quickstep {
class SomeArgType {
public:
explicit SomeArgType(std::string value) : value_(value) {
}
SomeArgType(SomeArgType &&arg) {
value_ = std::move(arg.value_);
}
std::string toString() const {
return value_;
}
private:
std::string value_;
DISALLOW_COPY_AND_ASSIGN(SomeArgType);
};
class BaseClass {
public:
virtual std::string toString() const = 0;
};
template <bool c1, bool c2, bool c3, bool c4, bool c5, bool c6>
class SomeClass : public BaseClass {
public:
SomeClass(int a1, SomeArgType &&a2)
: a1_(a1), a2_(std::forward<SomeArgType>(a2)) {
}
std::string toString() const override {
std::ostringstream oss;
oss << "{ ";
if (c1) {
oss << "c1 ";
}
if (c2) {
oss << "c2 ";
}
if (c3) {
oss << "c3 ";
}
if (c4) {
oss << "c4 ";
}
if (c5) {
oss << "c5 ";
}
if (c6) {
oss << "c6 ";
}
oss << "} " << a1_ << " " << a2_.toString();
return oss.str();
}
private:
int a1_;
SomeArgType a2_;
};
//void RunTest(bool c1, bool c2, bool c3, bool c4, bool c5, bool c6, std::string expected) {
// // arg should be perfectly forwarded.
// SomeArgType arg("xyz");
//
// std::unique_ptr<BaseClass> base(
// CreateBoolInstantiatedInstance<SomeClass, BaseClass>(std::forward_as_tuple(10, std::move(arg)),
// c1, c2, c3, c4, c5, c6));
// EXPECT_TRUE(base->toString() == expected);
//}
std::string concat(int x, float y, SomeArgType &&z) {
std::ostringstream oss;
oss << x << " " << y << " " << z.toString();
return oss.str();
}
template <typename ...Args, size_t ...i>
std::string concat(std::tuple<Args...> &&args, Seq<i...> &&indices) {
return concat(std::forward<Args>(std::get<i>(args))...);
}
TEST(TemplateUtilTest, TemplateUtilTest) {
// RunTest(true, false, true, false, true, false, "{ c1 c3 c5 } 10 xyz");
// RunTest(true, true, true, true, true, true, "{ c1 c2 c3 c4 c5 c6 } 10 xyz");
// RunTest(false, false, true, true, false, false, "{ c3 c4 } 10 xyz");
// RunTest(false, false, false, false, false, false, "{ } 10 xyz");
SomeArgType arg("abc");
std::string result = concat(std::forward_as_tuple(1, 2.5, std::move(arg)), GenSeq<3>::type());
EXPECT_TRUE(result == "1 2.5 abc");
}
} // namespace quickstep
<|endoftext|>
|
<commit_before><commit_msg>restore original comment<commit_after><|endoftext|>
|
<commit_before>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* 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 "utility/TemplateUtil.hpp"
#include <memory>
#include <string>
#include <sstream>
#include "utility/Macros.hpp"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace quickstep {
class SomeArgType {
public:
explicit SomeArgType(std::string value) : value_(value) {
}
SomeArgType(SomeArgType &&arg) {
value_ = std::move(arg.value_);
}
std::string toString() const {
return value_;
}
private:
std::string value_;
DISALLOW_COPY_AND_ASSIGN(SomeArgType);
};
class BaseClass {
public:
virtual std::string toString() const = 0;
};
template <bool c1, bool c2, bool c3, bool c4, bool c5, bool c6>
class SomeClass : public BaseClass {
public:
SomeClass(int a1, SomeArgType &&a2)
: a1_(a1), a2_(std::forward<SomeArgType>(a2)) {
}
std::string toString() const override {
std::ostringstream oss;
oss << "{ ";
if (c1) {
oss << "c1 ";
}
if (c2) {
oss << "c2 ";
}
if (c3) {
oss << "c3 ";
}
if (c4) {
oss << "c4 ";
}
if (c5) {
oss << "c5 ";
}
if (c6) {
oss << "c6 ";
}
oss << "} " << a1_ << " " << a2_.toString();
return oss.str();
}
private:
int a1_;
SomeArgType a2_;
};
//void RunTest(bool c1, bool c2, bool c3, bool c4, bool c5, bool c6, std::string expected) {
// // arg should be perfectly forwarded.
// SomeArgType arg("xyz");
//
// std::unique_ptr<BaseClass> base(
// CreateBoolInstantiatedInstance<SomeClass, BaseClass>(std::forward_as_tuple(10, std::move(arg)),
// c1, c2, c3, c4, c5, c6));
// EXPECT_TRUE(base->toString() == expected);
//}
std::string concat(int x, float y, SomeArgType &&z) {
std::ostringstream oss;
oss << x << " " << y << " " << z.toString();
return oss.str();
}
template <typename ...Args, size_t ...i>
std::string concat(std::tuple<Args...> &&args, Seq<i...> &&indices) {
return concat(std::forward<Args>(std::get<i>(args))...);
}
TEST(TemplateUtilTest, TemplateUtilTest) {
// RunTest(true, false, true, false, true, false, "{ c1 c3 c5 } 10 xyz");
// RunTest(true, true, true, true, true, true, "{ c1 c2 c3 c4 c5 c6 } 10 xyz");
// RunTest(false, false, true, true, false, false, "{ c3 c4 } 10 xyz");
// RunTest(false, false, false, false, false, false, "{ } 10 xyz");
SomeArgType arg("abc");
std::string result = concat(std::forward_as_tuple(1, 2.5, std::move(arg)), GenSeq<3>::type());
EXPECT_TRUE(result == "1 2.5 abc");
}
} // namespace quickstep
<commit_msg>test_get_forward_tuple_on_travis_ci<commit_after>/**
* Copyright 2016, Quickstep Research Group, Computer Sciences Department,
* University of Wisconsin—Madison.
*
* 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 "utility/TemplateUtil.hpp"
#include <memory>
#include <string>
#include <sstream>
#include "utility/Macros.hpp"
#include "glog/logging.h"
#include "gtest/gtest.h"
namespace quickstep {
class SomeArgType {
public:
explicit SomeArgType(std::string value) : value_(value) {
}
SomeArgType(SomeArgType &&arg) {
value_ = std::move(arg.value_);
}
std::string toString() const {
return value_;
}
private:
std::string value_;
DISALLOW_COPY_AND_ASSIGN(SomeArgType);
};
class BaseClass {
public:
virtual std::string toString() const = 0;
};
template <bool c1, bool c2, bool c3, bool c4, bool c5, bool c6>
class SomeClass : public BaseClass {
public:
SomeClass(int a1, SomeArgType &&a2)
: a1_(a1), a2_(std::forward<SomeArgType>(a2)) {
}
std::string toString() const override {
std::ostringstream oss;
oss << "{ ";
if (c1) {
oss << "c1 ";
}
if (c2) {
oss << "c2 ";
}
if (c3) {
oss << "c3 ";
}
if (c4) {
oss << "c4 ";
}
if (c5) {
oss << "c5 ";
}
if (c6) {
oss << "c6 ";
}
oss << "} " << a1_ << " " << a2_.toString();
return oss.str();
}
private:
int a1_;
SomeArgType a2_;
};
//void RunTest(bool c1, bool c2, bool c3, bool c4, bool c5, bool c6, std::string expected) {
// // arg should be perfectly forwarded.
// SomeArgType arg("xyz");
//
// std::unique_ptr<BaseClass> base(
// CreateBoolInstantiatedInstance<SomeClass, BaseClass>(std::forward_as_tuple(10, std::move(arg)),
// c1, c2, c3, c4, c5, c6));
// EXPECT_TRUE(base->toString() == expected);
//}
std::string concat(int x, float y, SomeArgType &&z) {
std::ostringstream oss;
oss << x << " " << y << " " << z.toString();
return oss.str();
}
template <typename Tuple, size_t ...i>
std::string concat(Tuple &&args, Seq<i...> &&indices) {
return concat(std::get<i>(std::forward<Tuple>(args))...);
}
TEST(TemplateUtilTest, TemplateUtilTest) {
// RunTest(true, false, true, false, true, false, "{ c1 c3 c5 } 10 xyz");
// RunTest(true, true, true, true, true, true, "{ c1 c2 c3 c4 c5 c6 } 10 xyz");
// RunTest(false, false, true, true, false, false, "{ c3 c4 } 10 xyz");
// RunTest(false, false, false, false, false, false, "{ } 10 xyz");
SomeArgType arg("abc");
std::string result = concat(std::forward_as_tuple(1, 2.5, std::move(arg)), GenSeq<3>::type());
EXPECT_TRUE(result == "1 2.5 abc");
}
} // namespace quickstep
<|endoftext|>
|
<commit_before>#ifndef ITER_ZIP_LONGEST_HPP_
#define ITER_ZIP_LONGEST_HPP_
#include "internal/iterbase.hpp"
#include <boost/optional.hpp>
#include <iterator>
#include <tuple>
#include <utility>
namespace iter {
namespace impl {
template <typename... RestContainers>
class ZippedLongest;
template <typename Container, typename... RestContainers>
class ZippedLongest<Container, RestContainers...>;
template <>
class ZippedLongest<>;
}
template <typename... Containers>
impl::ZippedLongest<Containers...> zip_longest(Containers&&...);
}
template <typename Container, typename... RestContainers>
class iter::impl::ZippedLongest<Container, RestContainers...> {
static_assert(!std::is_rvalue_reference<Container>::value,
"Itertools cannot be templated with rvalue references");
friend ZippedLongest zip_longest<Container, RestContainers...>(
Container&&, RestContainers&&...);
template <typename...>
friend class ZippedLongest;
private:
template <typename C>
using OptIterDeref = boost::optional<iterator_deref<C>>;
using OptType = OptIterDeref<Container>;
using ZipIterDeref = std::tuple<OptType, OptIterDeref<RestContainers>...>;
Container container;
ZippedLongest<RestContainers...> rest_zipped;
ZippedLongest(Container&& in_container, RestContainers&&... rest)
: container(std::forward<Container>(in_container)),
rest_zipped{std::forward<RestContainers>(rest)...} {}
public:
class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref> {
private:
using RestIter = typename ZippedLongest<RestContainers...>::Iterator;
iterator_type<Container> iter;
iterator_type<Container> end;
RestIter rest_iter;
public:
Iterator(iterator_type<Container>&& it, iterator_type<Container>&& in_end,
RestIter&& rest)
: iter{std::move(it)},
end{std::move(in_end)},
rest_iter{std::move(rest)} {}
Iterator& operator++() {
if (this->iter != this->end) {
++this->iter;
}
++this->rest_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->iter != other.iter || this->rest_iter != other.rest_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
ZipIterDeref operator*() {
if (this->iter != this->end) {
return std::tuple_cat(
std::tuple<OptType>{{*this->iter}}, *this->rest_iter);
} else {
return std::tuple_cat(std::tuple<OptType>{{}}, *this->rest_iter);
}
}
ArrowProxy<ZipIterDeref> operator->() {
return {**this};
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container),
std::begin(this->rest_zipped)};
}
Iterator end() {
return {std::end(this->container), std::end(this->container),
std::end(this->rest_zipped)};
}
};
template <>
class iter::impl::ZippedLongest<> {
public:
class Iterator : public std::iterator<std::input_iterator_tag, std::tuple<>> {
public:
Iterator& operator++() {
return *this;
}
constexpr Iterator operator++(int) const {
return *this;
}
constexpr bool operator!=(const Iterator&) const {
return false;
}
constexpr bool operator==(const Iterator&) const {
return true;
}
constexpr std::tuple<> operator*() const {
return {};
}
constexpr ArrowProxy<std::tuple<>> operator->() const {
return {{}};
}
};
constexpr Iterator begin() const {
return {};
}
constexpr Iterator end() const {
return {};
}
};
template <typename... Containers>
iter::impl::ZippedLongest<Containers...> iter::zip_longest(
Containers&&... containers) {
return {std::forward<Containers>(containers)...};
}
#endif
<commit_msg>makes zip_longest impl class move-only<commit_after>#ifndef ITER_ZIP_LONGEST_HPP_
#define ITER_ZIP_LONGEST_HPP_
#include "internal/iterbase.hpp"
#include <boost/optional.hpp>
#include <iterator>
#include <tuple>
#include <utility>
namespace iter {
namespace impl {
template <typename... RestContainers>
class ZippedLongest;
template <typename Container, typename... RestContainers>
class ZippedLongest<Container, RestContainers...>;
template <>
class ZippedLongest<>;
}
template <typename... Containers>
impl::ZippedLongest<Containers...> zip_longest(Containers&&...);
}
template <typename Container, typename... RestContainers>
class iter::impl::ZippedLongest<Container, RestContainers...> {
friend ZippedLongest zip_longest<Container, RestContainers...>(
Container&&, RestContainers&&...);
template <typename...>
friend class ZippedLongest;
private:
template <typename C>
using OptIterDeref = boost::optional<iterator_deref<C>>;
using OptType = OptIterDeref<Container>;
using ZipIterDeref = std::tuple<OptType, OptIterDeref<RestContainers>...>;
Container container;
ZippedLongest<RestContainers...> rest_zipped;
ZippedLongest(Container&& in_container, RestContainers&&... rest)
: container(std::forward<Container>(in_container)),
rest_zipped{std::forward<RestContainers>(rest)...} {}
public:
ZippedLongest(ZippedLongest&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, ZipIterDeref> {
private:
using RestIter = typename ZippedLongest<RestContainers...>::Iterator;
iterator_type<Container> iter;
iterator_type<Container> end;
RestIter rest_iter;
public:
Iterator(iterator_type<Container>&& it, iterator_type<Container>&& in_end,
RestIter&& rest)
: iter{std::move(it)},
end{std::move(in_end)},
rest_iter{std::move(rest)} {}
Iterator& operator++() {
if (this->iter != this->end) {
++this->iter;
}
++this->rest_iter;
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator& other) const {
return this->iter != other.iter || this->rest_iter != other.rest_iter;
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
ZipIterDeref operator*() {
if (this->iter != this->end) {
return std::tuple_cat(
std::tuple<OptType>{{*this->iter}}, *this->rest_iter);
} else {
return std::tuple_cat(std::tuple<OptType>{{}}, *this->rest_iter);
}
}
ArrowProxy<ZipIterDeref> operator->() {
return {**this};
}
};
Iterator begin() {
return {std::begin(this->container), std::end(this->container),
std::begin(this->rest_zipped)};
}
Iterator end() {
return {std::end(this->container), std::end(this->container),
std::end(this->rest_zipped)};
}
};
template <>
class iter::impl::ZippedLongest<> {
public:
ZippedLongest(ZippedLongest&&) = default;
class Iterator : public std::iterator<std::input_iterator_tag, std::tuple<>> {
public:
Iterator& operator++() {
return *this;
}
constexpr Iterator operator++(int) const {
return *this;
}
constexpr bool operator!=(const Iterator&) const {
return false;
}
constexpr bool operator==(const Iterator&) const {
return true;
}
constexpr std::tuple<> operator*() const {
return {};
}
constexpr ArrowProxy<std::tuple<>> operator->() const {
return {{}};
}
};
constexpr Iterator begin() const {
return {};
}
constexpr Iterator end() const {
return {};
}
};
template <typename... Containers>
iter::impl::ZippedLongest<Containers...> iter::zip_longest(
Containers&&... containers) {
return {std::forward<Containers>(containers)...};
}
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xlconst.hxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: obo $ $Date: 2004-06-04 11:00:38 $
*
* 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 SC_XLCONST_HXX
#define SC_XLCONST_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _SOLAR_H_
#include <tools/solar.h>
#endif
// Common =====================================================================
// Excel sheet dimensions -----------------------------------------------------
const sal_uInt16 EXC_MAXCOL2 = 255;
const sal_uInt16 EXC_MAXROW2 = 16383;
const sal_uInt16 EXC_MAXTAB2 = 0;
const sal_uInt16 EXC_MAXCOL3 = EXC_MAXCOL2;
const sal_uInt16 EXC_MAXROW3 = EXC_MAXROW2;
const sal_uInt16 EXC_MAXTAB3 = EXC_MAXTAB2;
const sal_uInt16 EXC_MAXCOL4 = EXC_MAXCOL3;
const sal_uInt16 EXC_MAXROW4 = EXC_MAXROW3;
const sal_uInt16 EXC_MAXTAB4 = 32767;
const sal_uInt16 EXC_MAXCOL5 = EXC_MAXCOL4;
const sal_uInt16 EXC_MAXROW5 = EXC_MAXROW4;
const sal_uInt16 EXC_MAXTAB5 = EXC_MAXTAB4;
const sal_uInt16 EXC_MAXCOL8 = EXC_MAXCOL5;
const sal_uInt16 EXC_MAXROW8 = 65535;
const sal_uInt16 EXC_MAXTAB8 = EXC_MAXTAB5;
const SCTAB SCNOTAB = SCTAB_MAX; /// An invalid Calc sheet index, for common use.
const sal_uInt16 EXC_NOTAB = 0xFFFF; /// An invalid Excel sheet index, for common use.
// In/out stream --------------------------------------------------------------
const sal_uInt32 RECORD_SEEK_TO_BEGIN = 0;
const sal_uInt32 RECORD_SEEK_TO_END = ~RECORD_SEEK_TO_BEGIN;
const sal_uInt16 EXC_MAXRECSIZE_BIFF5 = 2080;
const sal_uInt16 EXC_MAXRECSIZE_BIFF8 = 8224;
const sal_uInt16 EXC_ID_UNKNOWN = 0xFFFF;
const sal_uInt16 EXC_ID_CONT = 0x003C;
// String import/export -------------------------------------------------------
/** Flags used to specify import/export mode of strings. */
typedef sal_uInt16 XclStrFlags;
const XclStrFlags EXC_STR_DEFAULT = 0x0000; /// Default string settings.
const XclStrFlags EXC_STR_FORCEUNICODE = 0x0001; /// Always use UCS-2 characters (default: try to compress). BIFF8 only.
const XclStrFlags EXC_STR_8BITLENGTH = 0x0002; /// 8-bit string length field (default: 16-bit).
const XclStrFlags EXC_STR_SMARTFLAGS = 0x0004; /// Omit flags on empty string (default: read/write always). BIFF8 only.
const sal_uInt8 EXC_STRF_16BIT = 0x01;
const sal_uInt8 EXC_STRF_FAREAST = 0x04;
const sal_uInt8 EXC_STRF_RICH = 0x08;
const sal_uInt8 EXC_STRF_UNKNOWN = 0xF2;
// Fixed-size characters
const sal_uInt8 EXC_LF_C = '\x0A'; /// LF character (used for line break).
const sal_uInt16 EXC_LF = EXC_LF_C; /// LF character (unicode).
const sal_uInt8 EXC_NUL_C = '\x00'; /// NUL chararcter.
const sal_uInt16 EXC_NUL = EXC_NUL_C; /// NUL chararcter (unicode).
// Encoded URLs ---------------------------------------------------------------
const sal_Unicode EXC_URLSTART_ENCODED = '\x01'; /// Encoded URL.
const sal_Unicode EXC_URLSTART_SELF = '\x02'; /// Reference to own workbook.
const sal_Unicode EXC_URLSTART_SELFENCODED = '\x03'; /// Encoded self reference.
const sal_Unicode EXC_URL_DOSDRIVE = '\x01'; /// DOS drive letter or UNC server name.
const sal_Unicode EXC_URL_DRIVEROOT = '\x02'; /// Root directory of current drive.
const sal_Unicode EXC_URL_SUBDIR = '\x03'; /// Directory name delimiter.
const sal_Unicode EXC_URL_PARENTDIR = '\x04'; /// Parent directory.
const sal_Unicode EXC_URL_RAW = '\x05'; /// Unencoded URL.
const sal_Unicode EXC_URL_SHEETNAME = '\x09'; /// Sheet name starts here (BIFF4).
const sal_Unicode EXC_DDE_DELIM = '\x03'; /// DDE application-topic delimiter
// Error codes ----------------------------------------------------------------
const sal_uInt8 EXC_ERR_NULL = 0x00;
const sal_uInt8 EXC_ERR_DIV0 = 0x07;
const sal_uInt8 EXC_ERR_VALUE = 0x0F;
const sal_uInt8 EXC_ERR_REF = 0x17;
const sal_uInt8 EXC_ERR_NAME = 0x1D;
const sal_uInt8 EXC_ERR_NUM = 0x24;
const sal_uInt8 EXC_ERR_NA = 0x2A;
// Cached values list (EXTERNNAME, ptgArray, ...) -----------------------------
const sal_uInt8 EXC_CACHEDVAL_EMPTY = 0x00;
const sal_uInt8 EXC_CACHEDVAL_DOUBLE = 0x01;
const sal_uInt8 EXC_CACHEDVAL_STRING = 0x02;
const sal_uInt8 EXC_CACHEDVAL_BOOL = 0x04;
const sal_uInt8 EXC_CACHEDVAL_ERROR = 0x10;
// Measures -------------------------------------------------------------------
const sal_Int32 EXC_POINTS_PER_INCH = 72;
const sal_Int32 EXC_TWIPS_PER_INCH = EXC_POINTS_PER_INCH * 20;
// Records (ordered by lowest record ID) ======================================
// (0x0007, 0x0207) STRING ----------------------------------------------------
const sal_uInt16 EXC_ID_STRING = 0x0207;
// (0x001C) NOTE --------------------------------------------------------------
const sal_uInt16 EXC_ID_NOTE = 0x001C;
const sal_uInt16 EXC_NOTE_VISIBLE = 0x0002;
// (0x0012, 0x0019) PROTECT and WINDOWPROTECT --------------------
const sal_uInt16 EXC_ID_PROTECT = 0x0012;
const sal_uInt16 EXC_ID_WINDOWPROTECT = 0x0019;
// (0x003D) WINDOW1 -----------------------------------------------------------
const sal_uInt16 EXC_ID_WINDOW1 = 0x003D;
const sal_uInt16 EXC_WIN1_DEFAULTFLAGS = 0x0038; /// Default flags for export.
const sal_uInt16 EXC_WIN1_TABBARRATIO = 600; /// Sheet tab bar takes 60% of window width.
// (0x0055) DEFCOLWIDTH -------------------------------------------------------
const sal_uInt16 EXC_ID_DEFCOLWIDTH = 0x0055;
// (0x007D) COLINFO -----------------------------------------------------------
const sal_uInt16 EXC_ID_COLINFO = 0x007D;
const sal_uInt16 EXC_COLINFO_HIDDEN = 0x0001;
const sal_uInt16 EXC_COLINFO_COLLAPSED = 0x1000;
// (0x007E) RK ----------------------------------------------------------------
const sal_Int32 EXC_RK_100FLAG = 0x00000001;
const sal_Int32 EXC_RK_INTFLAG = 0x00000002;
const sal_Int32 EXC_RK_VALUEMASK = 0xFFFFFFFC;
const sal_Int32 EXC_RK_DBL = 0x00000000;
const sal_Int32 EXC_RK_DBL100 = EXC_RK_100FLAG;
const sal_Int32 EXC_RK_INT = EXC_RK_INTFLAG;
const sal_Int32 EXC_RK_INT100 = EXC_RK_100FLAG | EXC_RK_INTFLAG;
// (0x0081) WSBOOL ------------------------------------------------------------
const sal_uInt16 EXC_ID_WSBOOL = 0x0081;
const sal_uInt16 EXC_WSBOOL_ROWBELOW = 0x0040;
const sal_uInt16 EXC_WSBOOL_COLBELOW = 0x0080;
const sal_uInt16 EXC_WSBOOL_FITTOPAGE = 0x0100;
const sal_uInt16 EXC_WSBOOL_DEFAULTFLAGS = 0x04C1;
// (0x008C) COUNTRY -----------------------------------------------------------
const sal_uInt16 EXC_ID_COUNTRY = 0x008C;
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS fieldoptions (1.13.18); FILE MERGED 2004/05/12 11:42:03 dr 1.13.18.1: #i23447# reimpl of pivot table import completed<commit_after>/*************************************************************************
*
* $RCSfile: xlconst.hxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: obo $ $Date: 2004-06-04 14:06:49 $
*
* 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 SC_XLCONST_HXX
#define SC_XLCONST_HXX
#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _SOLAR_H_
#include <tools/solar.h>
#endif
// Common =====================================================================
// Excel sheet dimensions -----------------------------------------------------
const sal_uInt16 EXC_MAXCOL2 = 255;
const sal_uInt16 EXC_MAXROW2 = 16383;
const sal_uInt16 EXC_MAXTAB2 = 0;
const sal_uInt16 EXC_MAXCOL3 = EXC_MAXCOL2;
const sal_uInt16 EXC_MAXROW3 = EXC_MAXROW2;
const sal_uInt16 EXC_MAXTAB3 = EXC_MAXTAB2;
const sal_uInt16 EXC_MAXCOL4 = EXC_MAXCOL3;
const sal_uInt16 EXC_MAXROW4 = EXC_MAXROW3;
const sal_uInt16 EXC_MAXTAB4 = 32767;
const sal_uInt16 EXC_MAXCOL5 = EXC_MAXCOL4;
const sal_uInt16 EXC_MAXROW5 = EXC_MAXROW4;
const sal_uInt16 EXC_MAXTAB5 = EXC_MAXTAB4;
const sal_uInt16 EXC_MAXCOL8 = EXC_MAXCOL5;
const sal_uInt16 EXC_MAXROW8 = 65535;
const sal_uInt16 EXC_MAXTAB8 = EXC_MAXTAB5;
const SCTAB SCNOTAB = SCTAB_MAX; /// An invalid Calc sheet index, for common use.
const sal_uInt16 EXC_NOTAB = 0xFFFF; /// An invalid Excel sheet index, for common use.
// In/out stream --------------------------------------------------------------
const sal_uInt32 RECORD_SEEK_TO_BEGIN = 0;
const sal_uInt32 RECORD_SEEK_TO_END = ~RECORD_SEEK_TO_BEGIN;
const sal_uInt16 EXC_MAXRECSIZE_BIFF5 = 2080;
const sal_uInt16 EXC_MAXRECSIZE_BIFF8 = 8224;
// String import/export -------------------------------------------------------
/** Flags used to specify import/export mode of strings. */
typedef sal_uInt16 XclStrFlags;
const XclStrFlags EXC_STR_DEFAULT = 0x0000; /// Default string settings.
const XclStrFlags EXC_STR_FORCEUNICODE = 0x0001; /// Always use UCS-2 characters (default: try to compress). BIFF8 only.
const XclStrFlags EXC_STR_8BITLENGTH = 0x0002; /// 8-bit string length field (default: 16-bit).
const XclStrFlags EXC_STR_SMARTFLAGS = 0x0004; /// Omit flags on empty string (default: read/write always). BIFF8 only.
const sal_uInt8 EXC_STRF_16BIT = 0x01;
const sal_uInt8 EXC_STRF_FAREAST = 0x04;
const sal_uInt8 EXC_STRF_RICH = 0x08;
const sal_uInt8 EXC_STRF_UNKNOWN = 0xF2;
// Fixed-size characters
const sal_uInt8 EXC_LF_C = '\x0A'; /// LF character (used for line break).
const sal_uInt16 EXC_LF = EXC_LF_C; /// LF character (unicode).
const sal_uInt8 EXC_NUL_C = '\x00'; /// NUL chararcter.
const sal_uInt16 EXC_NUL = EXC_NUL_C; /// NUL chararcter (unicode).
// Encoded URLs ---------------------------------------------------------------
const sal_Unicode EXC_URLSTART_ENCODED = '\x01'; /// Encoded URL.
const sal_Unicode EXC_URLSTART_SELF = '\x02'; /// Reference to own workbook.
const sal_Unicode EXC_URLSTART_SELFENCODED = '\x03'; /// Encoded self reference.
const sal_Unicode EXC_URL_DOSDRIVE = '\x01'; /// DOS drive letter or UNC server name.
const sal_Unicode EXC_URL_DRIVEROOT = '\x02'; /// Root directory of current drive.
const sal_Unicode EXC_URL_SUBDIR = '\x03'; /// Directory name delimiter.
const sal_Unicode EXC_URL_PARENTDIR = '\x04'; /// Parent directory.
const sal_Unicode EXC_URL_RAW = '\x05'; /// Unencoded URL.
const sal_Unicode EXC_URL_SHEETNAME = '\x09'; /// Sheet name starts here (BIFF4).
const sal_Unicode EXC_DDE_DELIM = '\x03'; /// DDE application-topic delimiter
// Error codes ----------------------------------------------------------------
const sal_uInt8 EXC_ERR_NULL = 0x00;
const sal_uInt8 EXC_ERR_DIV0 = 0x07;
const sal_uInt8 EXC_ERR_VALUE = 0x0F;
const sal_uInt8 EXC_ERR_REF = 0x17;
const sal_uInt8 EXC_ERR_NAME = 0x1D;
const sal_uInt8 EXC_ERR_NUM = 0x24;
const sal_uInt8 EXC_ERR_NA = 0x2A;
// Cached values list (EXTERNNAME, ptgArray, ...) -----------------------------
const sal_uInt8 EXC_CACHEDVAL_EMPTY = 0x00;
const sal_uInt8 EXC_CACHEDVAL_DOUBLE = 0x01;
const sal_uInt8 EXC_CACHEDVAL_STRING = 0x02;
const sal_uInt8 EXC_CACHEDVAL_BOOL = 0x04;
const sal_uInt8 EXC_CACHEDVAL_ERROR = 0x10;
// Measures -------------------------------------------------------------------
const sal_Int32 EXC_POINTS_PER_INCH = 72;
const sal_Int32 EXC_TWIPS_PER_INCH = EXC_POINTS_PER_INCH * 20;
// Records (ordered by lowest record ID) ======================================
// (0x0007, 0x0207) STRING ----------------------------------------------------
const sal_uInt16 EXC_ID_STRING = 0x0207;
// (0x000A) EOF ---------------------------------------------------------------
const sal_uInt16 EXC_ID_EOF = 0x000A;
// (0x001C) NOTE --------------------------------------------------------------
const sal_uInt16 EXC_ID_NOTE = 0x001C;
const sal_uInt16 EXC_NOTE_VISIBLE = 0x0002;
// (0x0012, 0x0019) PROTECT and WINDOWPROTECT --------------------
const sal_uInt16 EXC_ID_PROTECT = 0x0012;
const sal_uInt16 EXC_ID_WINDOWPROTECT = 0x0019;
// (0x003C) CONTINUE ----------------------------------------------------------
const sal_uInt16 EXC_ID_CONT = 0x003C;
// (0x003D) WINDOW1 -----------------------------------------------------------
const sal_uInt16 EXC_ID_WINDOW1 = 0x003D;
const sal_uInt16 EXC_WIN1_DEFAULTFLAGS = 0x0038; /// Default flags for export.
const sal_uInt16 EXC_WIN1_TABBARRATIO = 600; /// Sheet tab bar takes 60% of window width.
// (0x0055) DEFCOLWIDTH -------------------------------------------------------
const sal_uInt16 EXC_ID_DEFCOLWIDTH = 0x0055;
// (0x007D) COLINFO -----------------------------------------------------------
const sal_uInt16 EXC_ID_COLINFO = 0x007D;
const sal_uInt16 EXC_COLINFO_HIDDEN = 0x0001;
const sal_uInt16 EXC_COLINFO_COLLAPSED = 0x1000;
// (0x007E) RK ----------------------------------------------------------------
const sal_Int32 EXC_RK_100FLAG = 0x00000001;
const sal_Int32 EXC_RK_INTFLAG = 0x00000002;
const sal_Int32 EXC_RK_VALUEMASK = 0xFFFFFFFC;
const sal_Int32 EXC_RK_DBL = 0x00000000;
const sal_Int32 EXC_RK_DBL100 = EXC_RK_100FLAG;
const sal_Int32 EXC_RK_INT = EXC_RK_INTFLAG;
const sal_Int32 EXC_RK_INT100 = EXC_RK_100FLAG | EXC_RK_INTFLAG;
// (0x0081) WSBOOL ------------------------------------------------------------
const sal_uInt16 EXC_ID_WSBOOL = 0x0081;
const sal_uInt16 EXC_WSBOOL_ROWBELOW = 0x0040;
const sal_uInt16 EXC_WSBOOL_COLBELOW = 0x0080;
const sal_uInt16 EXC_WSBOOL_FITTOPAGE = 0x0100;
const sal_uInt16 EXC_WSBOOL_DEFAULTFLAGS = 0x04C1;
// (0x008C) COUNTRY -----------------------------------------------------------
const sal_uInt16 EXC_ID_COUNTRY = 0x008C;
// (0xFFFF) unknown record - special ID ---------------------------------------
const sal_uInt16 EXC_ID_UNKNOWN = 0xFFFF;
// ============================================================================
#endif
<|endoftext|>
|
<commit_before>#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<bitset>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAXN=100010;
const int MAXM=200010;
int mp[MAXN];
struct graph{
int head[MAXN];
struct Node{
int val,nxt,v;
}Edge[MAXM];
int cnte=0;
int in[MAXN];
void clear()
{
memset(Edge,0,sizeof(Edge));
memset(in,0,sizeof(in));
memset(head,0,sizeof(head));
cnte=0;
}
inline void add(const int &u,const int &v,const int &val)
{
++in[v];
Edge[++cnte].nxt=head[u];
Edge[cnte].v=v;
Edge[cnte].val=val;
head[u]=cnte;
}
}G,G0,Gr;
struct NODE{
int dis,lvl,disn;
int num;
bool operator <(NODE a)
{
if(dis!=a.dis)
return dis<a.dis;
else return lvl<a.lvl;
}
}pnt[MAXN];
int ans[MAXN][60];
int n,m,u,v,val,P,K;
bool inq[MAXN];
void spfa()
{
memset(inq,0,sizeof(inq));
queue<int> q;
q.push(1);inq[1]=1;
pnt[1].dis=0;
while(!q.empty())
{
int x=q.front();q.pop();
inq[x]=0;
for(int i=G.head[x];i;i=G.Edge[i].nxt)
{
int v=G.Edge[i].v;
if(pnt[v].dis>pnt[x].dis+G.Edge[i].val)
{
pnt[v].dis=pnt[x].dis+G.Edge[i].val;
if(!inq[v])
q.push(v);
}
}
}
}
void spfa_2()
{
memset(inq,0,sizeof(inq));
queue<int> q;
q.push(n);inq[n]=1;
pnt[n].disn=0;
while(!q.empty())
{
int x=q.front();q.pop();
inq[x]=0;
for(int i=Gr.head[x];i;i=Gr.Edge[i].nxt)
{
int v=Gr.Edge[i].v;
if(pnt[v].disn>pnt[x].disn+Gr.Edge[i].val)
{
pnt[v].disn=pnt[x].disn+Gr.Edge[i].val;
if(!inq[v])
q.push(v);
}
}
}
}
bool tsort()
{
queue<int> q;
for(int i=1;i<=n;i++)
if(!G0.in[i])
q.push(i);
while(!q.empty())
{
int x=q.front();q.pop();
for(int i=G0.head[x];i;i=G0.Edge[i].nxt)
{
int v=G0.Edge[i].v;
pnt[v].lvl=pnt[x].lvl+1;
--G0.in[v];
if(!G0.in[v])
q.push(v);
}
}
for(int i=1;i<=n;i++)
if(G0.in[i]&&pnt[i].dis+pnt[i].disn<=pnt[n].dis+K)
return false;
return true;
}
int T;
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%d",&n,&m,&K,&P);
G.clear();G0.clear();Gr.clear();
memset(pnt,0,sizeof(pnt));
memset(ans,0,sizeof(ans));
for(int i=1;i<=n;i++)
pnt[i].dis=pnt[i].disn=0x3f3f3f3f,pnt[i].num=i;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&val);
G.add(u,v,val);
Gr.add(v,u,val);
if(!val)
G0.add(u,v,val);
}
spfa();
spfa_2();
if(!tsort())
puts("-1");
else
{
ans[1][0]=1;
sort(pnt+1,pnt+1+n);
for(int i=1;i<=n;i++)
mp[pnt[i].num]=i;
for(int u=1;u<=n;u++)
{
for(int i=G.head[pnt[u].num];i;i=G.Edge[i].nxt)
{
int v=G.Edge[i].v;
for(int j=0;j<=K;j++)
if(pnt[u].dis+j+G.Edge[i].val<=pnt[mp[v]].dis+K)
(ans[v][pnt[u].dis+j+G.Edge[i].val-pnt[mp[v]].dis]+=ans[pnt[u].num][j])%=P;
}
}
ll ansi=0;
for(int i=0;i<=K;i++)
(ansi+=ans[n][i])%=P;
printf("%lld\n",ansi);
}
}
}
<commit_msg>洛谷 3953<commit_after>#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<cassert>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MAXN=1E5+10;
const int MAXK=51;
int d1[MAXN],dn[MAXN],f[MAXN][MAXK],d[MAXN],n,m,K,P,tps[MAXN],Tms,pnt[MAXN];
bool vis[MAXN];
vector<int> G0[MAXN];
vector<pair<int,int> > G[MAXN],Gr[MAXN];
priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > > pq;
queue<int> q;
void dijkstra(int s,int* dis,vector<pair<int,int> >* g)
{
memset(dis,0x3f,sizeof d1);
memset(vis,0,sizeof vis);
dis[s]=0;pq.push(make_pair(0,s));
while(!pq.empty())
{
pair<int,int> t=pq.top();pq.pop();
if(vis[t.second]) continue;
vis[t.second]=1;
for(auto v:g[t.second])
{
if(dis[v.first]>t.first+v.second)
{
dis[v.first]=t.first+v.second;
pq.push(make_pair(dis[v.first],v.first));
}
}
}
}
void topo()
{
for(int i=1;i<=n;i++) if(!d[i]) q.push(i);
while(!q.empty())
{
int x=q.front();q.pop();
tps[x]=++Tms;
for(auto v:G0[x])
if(!(--d[v])) q.push(v);
}
}
void Solve()
{
scanf("%d%d%d%d",&n,&m,&K,&P);Tms=0;
for(int i=1;i<=n;i++) pnt[i]=i,G[i].clear(),Gr[i].clear(),G0[i].clear();
memset(d,0,sizeof d);memset(tps,0,sizeof tps);memset(f,0,sizeof f);
for(int i=1,u,v,w;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
G[u].push_back(make_pair(v,w));
Gr[v].push_back(make_pair(u,w));
if(w==0) G0[u].push_back(v),++d[v];
}
dijkstra(1,d1,G);dijkstra(n,dn,Gr);topo();
sort(pnt+1,pnt+1+n,[](int a,int b)->bool{return d1[a]<d1[b]||(d1[a]==d1[b]&&tps[a]<tps[b]);});
f[1][0]=1;
for(int k=0;k<=K;k++)
{
for(int i=1;i<=n;i++)
{
int x=pnt[i];
for(auto v:G[x])
if(d1[x]+v.second+k-d1[v.first]<=K)
(f[v.first][d1[x]+v.second+k-d1[v.first]]+=f[x][k])%=P;
}
}
bool fl=0;
for(int i=1;i<=n;i++)
if(d1[i]+dn[i]<=d1[n]+K&&d[i]) {fl=1;break;}
if(fl) puts("-1");
else
{
ll Ans=0;
for(int i=0;i<=K;i++) (Ans+=f[n][i])%=P;
printf("%lld\n",Ans);
}
}
int main()
{
int T;
for(scanf("%d",&T);T--;Solve());
}<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2012 Michael Meeks <[email protected]> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "sal/config.h"
#include <vector>
#include "contacts.hrc"
#include "sendfunc.hxx"
#include "docsh.hxx"
#include "scresid.hxx"
#include <svtools/filter.hxx>
#include <tubes/manager.hxx>
#include <vcl/fixed.hxx>
#include <vcl/dialog.hxx>
#include <svx/simptabl.hxx>
#define CONTACTS_DLG
#ifdef CONTACTS_DLG
namespace {
class TubeContacts : public ModelessDialog
{
FixedLine maLabel;
PushButton maBtnConnect;
PushButton maBtnListen;
SvxSimpleTableContainer maListContainer;
SvxSimpleTable maList;
DECL_LINK( BtnConnectHdl, void * );
DECL_LINK( BtnListenHdl, void * );
struct AccountContact
{
TpAccount* mpAccount;
TpContact* mpContact;
AccountContact( TpAccount* pAccount, TpContact* pContact ):
mpAccount(pAccount), mpContact(pContact) {}
};
boost::ptr_vector<AccountContact> maACs;
void Listen()
{
ScDocShell *pScDocShell = reinterpret_cast<ScDocShell*> (SfxObjectShell::Current());
ScDocFunc *pDocFunc = pScDocShell ? &pScDocShell->GetDocFunc() : NULL;
ScDocFuncSend *pSender = reinterpret_cast<ScDocFuncSend*> (pDocFunc);
if (!pSender)
{
delete pDocFunc;
boost::shared_ptr<ScDocFuncDirect> pDirect( new ScDocFuncDirect( *pScDocShell ) );
boost::shared_ptr<ScDocFuncRecv> pReceiver( new ScDocFuncRecv( pDirect ) );
pSender = new ScDocFuncSend( *pScDocShell, pReceiver );
pDocFunc = pSender;
}
pSender->InitTeleManager( false );
}
void StartBuddySession()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = reinterpret_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
TpAccount* pAccount = pAC->mpAccount;
TpContact* pContact = pAC->mpContact;
fprintf( stderr, "picked %s\n", tp_contact_get_identifier( pContact ) );
// TeleManager has to exist already, false will be ignored:
TeleManager *pManager = TeleManager::get( false );
if (!pManager->startBuddySession( pAccount, pContact ))
fprintf( stderr, "could not start session with %s\n",
tp_contact_get_identifier( pContact ) );
pManager->unref();
}
}
public:
TubeContacts() :
ModelessDialog( NULL, ScResId( RID_SCDLG_CONTACTS ) ),
maLabel( this, ScResId( FL_LABEL ) ),
maBtnConnect( this, ScResId( BTN_CONNECT ) ),
maBtnListen( this, ScResId( BTN_LISTEN ) ),
maListContainer( this, ScResId( CTL_LIST ) ),
maList( maListContainer )
{
maBtnConnect.SetClickHdl( LINK( this, TubeContacts, BtnConnectHdl ) );
maBtnListen.SetClickHdl( LINK( this, TubeContacts, BtnListenHdl ) );
static long aStaticTabs[]=
{
3 /* count */, 0, 20, 100, 150, 200
};
maList.SvxSimpleTable::SetTabs( aStaticTabs );
String sHeader( '\t' );
sHeader += String( ScResId( STR_HEADER_ALIAS ) );
sHeader += '\t';
sHeader += String( ScResId( STR_HEADER_NAME ) );
sHeader += '\t';
maList.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT );
Show();
}
virtual ~TubeContacts() {}
static rtl::OUString fromUTF8( const char *pStr )
{
return rtl::OStringToOUString( rtl::OString( pStr, strlen( pStr ) ),
RTL_TEXTENCODING_UTF8 );
}
void Populate( const TeleManager &rManager )
{
ContactList *pContacts = rManager.getContactList();
if ( pContacts )
{
fprintf( stderr, "contacts !\n" );
AccountContactPairV aPairs = pContacts->getContacts();
AccountContactPairV::iterator it;
for( it = aPairs.begin(); it != aPairs.end(); it++ )
{
Image aImage;
GFile *pAvatarFile = tp_contact_get_avatar_file( it->second );
if( pAvatarFile )
{
const rtl::OUString sAvatarFileUrl = fromUTF8( g_file_get_path ( pAvatarFile ) );
Graphic aGraphic;
if( GRFILTER_OK == GraphicFilter::LoadGraphic( sAvatarFileUrl, rtl::OUString(""), aGraphic ) )
{
BitmapEx aBitmap = aGraphic.GetBitmapEx();
double fScale = 30.0 / aBitmap.GetSizePixel().Height();
aBitmap.Scale( fScale, fScale );
aImage = Image( aBitmap );
}
}
fprintf( stderr, "'%s' => '%s' '%s'\n",
tp_account_get_display_name( it->first ),
tp_contact_get_alias( it->second ),
tp_contact_get_identifier( it->second ) );
rtl::OUStringBuffer aEntry( 128 );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_alias( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_identifier( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
SvLBoxEntry* pEntry = maList.InsertEntry( aEntry.makeStringAndClear(), aImage, aImage );
// FIXME: ref the TpAccount, TpContact ...
maACs.push_back( new AccountContact( it->first, it->second ) );
pEntry->SetUserData( &maACs.back() );
}
}
}
};
IMPL_LINK_NOARG( TubeContacts, BtnConnectHdl )
{
StartBuddySession();
Close();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnListenHdl )
{
Listen();
Close();
return 0;
}
} // anonymous namespace
#endif
namespace tubes {
void createContacts( const TeleManager &rManager )
{
#ifdef CONTACTS_DLG
TubeContacts *pContacts = new TubeContacts();
pContacts->Populate( rManager );
#endif
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>tubes: use correct casts<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* Version: MPL 1.1 / GPLv3+ / LGPLv3+
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License or as specified alternatively below. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Major Contributor(s):
* Copyright (C) 2012 Michael Meeks <[email protected]> (initial developer)
*
* All Rights Reserved.
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 3 or later (the "GPLv3+"), or
* the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"),
* in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable
* instead of those above.
*/
#include "sal/config.h"
#include <vector>
#include "contacts.hrc"
#include "sendfunc.hxx"
#include "docsh.hxx"
#include "scresid.hxx"
#include <svtools/filter.hxx>
#include <tubes/manager.hxx>
#include <vcl/fixed.hxx>
#include <vcl/dialog.hxx>
#include <svx/simptabl.hxx>
#define CONTACTS_DLG
#ifdef CONTACTS_DLG
namespace {
class TubeContacts : public ModelessDialog
{
FixedLine maLabel;
PushButton maBtnConnect;
PushButton maBtnListen;
SvxSimpleTableContainer maListContainer;
SvxSimpleTable maList;
DECL_LINK( BtnConnectHdl, void * );
DECL_LINK( BtnListenHdl, void * );
struct AccountContact
{
TpAccount* mpAccount;
TpContact* mpContact;
AccountContact( TpAccount* pAccount, TpContact* pContact ):
mpAccount(pAccount), mpContact(pContact) {}
};
boost::ptr_vector<AccountContact> maACs;
void Listen()
{
ScDocShell *pScDocShell = dynamic_cast<ScDocShell*> (SfxObjectShell::Current());
ScDocFunc *pDocFunc = pScDocShell ? &pScDocShell->GetDocFunc() : NULL;
ScDocFuncSend *pSender = dynamic_cast<ScDocFuncSend*> (pDocFunc);
if (!pSender)
{
delete pDocFunc;
boost::shared_ptr<ScDocFuncDirect> pDirect( new ScDocFuncDirect( *pScDocShell ) );
boost::shared_ptr<ScDocFuncRecv> pReceiver( new ScDocFuncRecv( pDirect ) );
pSender = new ScDocFuncSend( *pScDocShell, pReceiver );
pDocFunc = pSender;
}
pSender->InitTeleManager( false );
}
void StartBuddySession()
{
AccountContact *pAC = NULL;
if (maList.FirstSelected())
pAC = static_cast<AccountContact*> (maList.FirstSelected()->GetUserData());
if (pAC)
{
TpAccount* pAccount = pAC->mpAccount;
TpContact* pContact = pAC->mpContact;
fprintf( stderr, "picked %s\n", tp_contact_get_identifier( pContact ) );
// TeleManager has to exist already, false will be ignored:
TeleManager *pManager = TeleManager::get( false );
if (!pManager->startBuddySession( pAccount, pContact ))
fprintf( stderr, "could not start session with %s\n",
tp_contact_get_identifier( pContact ) );
pManager->unref();
}
}
public:
TubeContacts() :
ModelessDialog( NULL, ScResId( RID_SCDLG_CONTACTS ) ),
maLabel( this, ScResId( FL_LABEL ) ),
maBtnConnect( this, ScResId( BTN_CONNECT ) ),
maBtnListen( this, ScResId( BTN_LISTEN ) ),
maListContainer( this, ScResId( CTL_LIST ) ),
maList( maListContainer )
{
maBtnConnect.SetClickHdl( LINK( this, TubeContacts, BtnConnectHdl ) );
maBtnListen.SetClickHdl( LINK( this, TubeContacts, BtnListenHdl ) );
static long aStaticTabs[]=
{
3 /* count */, 0, 20, 100, 150, 200
};
maList.SvxSimpleTable::SetTabs( aStaticTabs );
String sHeader( '\t' );
sHeader += String( ScResId( STR_HEADER_ALIAS ) );
sHeader += '\t';
sHeader += String( ScResId( STR_HEADER_NAME ) );
sHeader += '\t';
maList.InsertHeaderEntry( sHeader, HEADERBAR_APPEND, HIB_LEFT );
Show();
}
virtual ~TubeContacts() {}
static rtl::OUString fromUTF8( const char *pStr )
{
return rtl::OStringToOUString( rtl::OString( pStr, strlen( pStr ) ),
RTL_TEXTENCODING_UTF8 );
}
void Populate( const TeleManager &rManager )
{
ContactList *pContacts = rManager.getContactList();
if ( pContacts )
{
fprintf( stderr, "contacts !\n" );
AccountContactPairV aPairs = pContacts->getContacts();
AccountContactPairV::iterator it;
for( it = aPairs.begin(); it != aPairs.end(); it++ )
{
Image aImage;
GFile *pAvatarFile = tp_contact_get_avatar_file( it->second );
if( pAvatarFile )
{
const rtl::OUString sAvatarFileUrl = fromUTF8( g_file_get_path ( pAvatarFile ) );
Graphic aGraphic;
if( GRFILTER_OK == GraphicFilter::LoadGraphic( sAvatarFileUrl, rtl::OUString(""), aGraphic ) )
{
BitmapEx aBitmap = aGraphic.GetBitmapEx();
double fScale = 30.0 / aBitmap.GetSizePixel().Height();
aBitmap.Scale( fScale, fScale );
aImage = Image( aBitmap );
}
}
fprintf( stderr, "'%s' => '%s' '%s'\n",
tp_account_get_display_name( it->first ),
tp_contact_get_alias( it->second ),
tp_contact_get_identifier( it->second ) );
rtl::OUStringBuffer aEntry( 128 );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_alias( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
aEntry.append( fromUTF8 ( tp_contact_get_identifier( it->second ) ) );
aEntry.append( sal_Unicode( '\t' ) );
SvLBoxEntry* pEntry = maList.InsertEntry( aEntry.makeStringAndClear(), aImage, aImage );
// FIXME: ref the TpAccount, TpContact ...
maACs.push_back( new AccountContact( it->first, it->second ) );
pEntry->SetUserData( &maACs.back() );
}
}
}
};
IMPL_LINK_NOARG( TubeContacts, BtnConnectHdl )
{
StartBuddySession();
Close();
return 0;
}
IMPL_LINK_NOARG( TubeContacts, BtnListenHdl )
{
Listen();
Close();
return 0;
}
} // anonymous namespace
#endif
namespace tubes {
void createContacts( const TeleManager &rManager )
{
#ifdef CONTACTS_DLG
TubeContacts *pContacts = new TubeContacts();
pContacts->Populate( rManager );
#endif
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: masterpasscrtdlg.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-09 10:22:50 $
*
* 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 _SVT_FILEDLG_HXX
#include <svtools/filedlg.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef UUI_IDS_HRC
#include <ids.hrc>
#endif
#ifndef UUI_MASTERPASSCRTDLG_HRC
#include <masterpasscrtdlg.hrc>
#endif
#ifndef UUI_MASTERPASSCRTDLG_HXX
#include <masterpasscrtdlg.hxx>
#endif
// MasterPasswordCreateDialog---------------------------------------------------
// -----------------------------------------------------------------------
IMPL_LINK( MasterPasswordCreateDialog, EditHdl_Impl, Edit *, EMPTYARG )
{
aOKBtn.Enable( aEDMasterPasswordCrt.GetText().Len() >= nMinLen );
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( MasterPasswordCreateDialog, OKHdl_Impl, OKButton *, EMPTYARG )
{
// compare both passwords and show message box if there are not equal!!
if( aEDMasterPasswordCrt.GetText() == aEDMasterPasswordRepeat.GetText() )
EndDialog( RET_OK );
else
{
String aErrorMsg( ResId( STR_ERROR_PASSWORDS_NOT_IDENTICAL, pResourceMgr ));
ErrorBox aErrorBox( this, WB_OK, aErrorMsg );
aErrorBox.Execute();
aEDMasterPasswordCrt.SetText( String() );
aEDMasterPasswordRepeat.SetText( String() );
aEDMasterPasswordCrt.GrabFocus();
}
return 1;
}
// -----------------------------------------------------------------------
MasterPasswordCreateDialog::MasterPasswordCreateDialog
(
Window* pParent,
ResMgr* pResMgr
) :
ModalDialog( pParent, ResId( DLG_UUI_MASTERPASSWORD_CRT, pResMgr ) ),
aFTMasterPasswordCrt ( this, ResId( FT_MASTERPASSWORD_CRT ) ),
aEDMasterPasswordCrt ( this, ResId( ED_MASTERPASSWORD_CRT ) ),
aFTMasterPasswordRepeat ( this, ResId( FT_MASTERPASSWORD_REPEAT ) ),
aEDMasterPasswordRepeat ( this, ResId( ED_MASTERPASSWORD_REPEAT ) ),
aOKBtn ( this, ResId( BTN_MASTERPASSCRT_OK ) ),
aCancelBtn ( this, ResId( BTN_MASTERPASSCRT_CANCEL ) ),
aHelpBtn ( this, ResId( BTN_MASTERPASSCRT_HELP ) ),
pResourceMgr ( pResMgr ),
nMinLen(5)
{
FreeResource();
aOKBtn.Enable( sal_False );
aOKBtn.SetClickHdl( LINK( this, MasterPasswordCreateDialog, OKHdl_Impl ) );
aEDMasterPasswordCrt.SetModifyHdl( LINK( this, MasterPasswordCreateDialog, EditHdl_Impl ) );
};
<commit_msg>INTEGRATION: CWS residcleanup (1.2.96); FILE MERGED 2007/02/24 19:15:40 pl 1.2.96.1: #i74635# residcleanup<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: masterpasscrtdlg.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2007-04-26 08:19:27 $
*
* 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 _SVT_FILEDLG_HXX
#include <svtools/filedlg.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef UUI_IDS_HRC
#include <ids.hrc>
#endif
#ifndef UUI_MASTERPASSCRTDLG_HRC
#include <masterpasscrtdlg.hrc>
#endif
#ifndef UUI_MASTERPASSCRTDLG_HXX
#include <masterpasscrtdlg.hxx>
#endif
// MasterPasswordCreateDialog---------------------------------------------------
// -----------------------------------------------------------------------
IMPL_LINK( MasterPasswordCreateDialog, EditHdl_Impl, Edit *, EMPTYARG )
{
aOKBtn.Enable( aEDMasterPasswordCrt.GetText().Len() >= nMinLen );
return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( MasterPasswordCreateDialog, OKHdl_Impl, OKButton *, EMPTYARG )
{
// compare both passwords and show message box if there are not equal!!
if( aEDMasterPasswordCrt.GetText() == aEDMasterPasswordRepeat.GetText() )
EndDialog( RET_OK );
else
{
String aErrorMsg( ResId( STR_ERROR_PASSWORDS_NOT_IDENTICAL, *pResourceMgr ));
ErrorBox aErrorBox( this, WB_OK, aErrorMsg );
aErrorBox.Execute();
aEDMasterPasswordCrt.SetText( String() );
aEDMasterPasswordRepeat.SetText( String() );
aEDMasterPasswordCrt.GrabFocus();
}
return 1;
}
// -----------------------------------------------------------------------
MasterPasswordCreateDialog::MasterPasswordCreateDialog
(
Window* pParent,
ResMgr* pResMgr
) :
ModalDialog( pParent, ResId( DLG_UUI_MASTERPASSWORD_CRT, *pResMgr ) ),
aFTMasterPasswordCrt ( this, ResId( FT_MASTERPASSWORD_CRT, *pResMgr ) ),
aEDMasterPasswordCrt ( this, ResId( ED_MASTERPASSWORD_CRT, *pResMgr ) ),
aFTMasterPasswordRepeat ( this, ResId( FT_MASTERPASSWORD_REPEAT, *pResMgr ) ),
aEDMasterPasswordRepeat ( this, ResId( ED_MASTERPASSWORD_REPEAT, *pResMgr ) ),
aOKBtn ( this, ResId( BTN_MASTERPASSCRT_OK, *pResMgr ) ),
aCancelBtn ( this, ResId( BTN_MASTERPASSCRT_CANCEL, *pResMgr ) ),
aHelpBtn ( this, ResId( BTN_MASTERPASSCRT_HELP, *pResMgr ) ),
pResourceMgr ( pResMgr ),
nMinLen(5)
{
FreeResource();
aOKBtn.Enable( sal_False );
aOKBtn.SetClickHdl( LINK( this, MasterPasswordCreateDialog, OKHdl_Impl ) );
aEDMasterPasswordCrt.SetModifyHdl( LINK( this, MasterPasswordCreateDialog, EditHdl_Impl ) );
};
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: mutex.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2003-04-04 17:10: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 _OSL_MUTEX_HXX_
#define _OSL_MUTEX_HXX_
#ifdef __cplusplus
#include <osl/mutex.h>
namespace osl
{
/** A mutual exclusion synchronization object
*/
class Mutex {
oslMutex mutex;
// these make no sense
Mutex( oslMutex );
Mutex( const Mutex & );
Mutex& operator= ( oslMutex );
Mutex& operator= ( const Mutex& );
public:
/** Create a thread-local mutex.
@return 0 if the mutex could not be created, otherwise a handle to the mutex.
@seealso ::osl_createMutex()
*/
Mutex()
{
mutex = osl_createMutex();
}
/** Release the OS-structures and free mutex data-structure.
@seealso ::osl_destroyMutex()
*/
~Mutex()
{
osl_destroyMutex(mutex);
}
/** Acquire the mutex, block if already acquired by another thread.
@return sal_False if system-call fails.
@seealso ::osl_acquireMutex()
*/
sal_Bool acquire()
{
return osl_acquireMutex(mutex);
}
/** Try to acquire the mutex without blocking.
@return sal_False if it could not be acquired.
@seealso ::osl_tryToAcquireMutex()
*/
sal_Bool tryToAcquire()
{
return osl_tryToAcquireMutex(mutex);
}
/** Release the mutex.
@return sal_False if system-call fails.
@seealso ::osl_releaseMutex()
*/
sal_Bool release()
{
return osl_releaseMutex(mutex);
}
/** Returns a global static mutex object.
The global and static mutex object can be used to initialize other
static objects in a thread safe manner.
@return the global mutex object
@seealso ::osl_getGlobalMutex()
*/
static Mutex * getGlobalMutex()
{
return (Mutex *)osl_getGlobalMutex();
}
};
/** A helper class for mutex objects and interfaces.
*/
template<class T>
class Guard
{
private:
Guard( const Guard& );
const Guard& operator = ( const Guard& );
protected:
T * pT;
public:
/** Acquires the object specified as parameter.
*/
Guard(T * pT_) : pT(pT_)
{
pT->acquire();
}
/** Acquires the object specified as parameter.
*/
Guard(T & t) : pT(&t)
{
pT->acquire();
}
/** Releases the mutex or interface. */
~Guard()
{
pT->release();
}
};
/** A helper class for mutex objects and interfaces.
*/
template<class T>
class ClearableGuard
{
private:
ClearableGuard( const ClearableGuard& );
const ClearableGuard& operator = ( const ClearableGuard& );
protected:
T * pT;
public:
/** Acquires the object specified as parameter.
*/
ClearableGuard(T * pT_) : pT(pT_)
{
pT->acquire();
}
/** Acquires the object specified as parameter.
*/
ClearableGuard(T & t) : pT(&t)
{
pT->acquire();
}
/** Releases the mutex or interface if not already released by clear().
*/
~ClearableGuard()
{
if (pT)
pT->release();
}
/** Releases the mutex or interface.
*/
void clear()
{
if(pT)
{
pT->release();
pT = NULL;
}
}
};
/** A helper class for mutex objects and interfaces.
*/
template< class T >
class ResettableGuard : public ClearableGuard< T >
{
protected:
T* pResetT;
public:
/** Acquires the object specified as parameter.
*/
ResettableGuard( T* pT ) :
ClearableGuard<T>( pT ),
pResetT( pT )
{}
/** Acquires the object specified as parameter.
*/
ResettableGuard( T& rT ) :
ClearableGuard<T>( rT ),
pResetT( &rT )
{}
/** Re-aquires the mutex or interface.
*/
void reset()
{
if( pResetT )
{
pT = pResetT;
pT->acquire();
}
}
};
typedef Guard<Mutex> MutexGuard;
typedef ClearableGuard<Mutex> ClearableMutexGuard;
typedef ResettableGuard< Mutex > ResettableMutexGuard;
}
#endif /* __cplusplus */
#endif /* _OSL_MUTEX_HXX_ */
<commit_msg>INTEGRATION: CWS qdiet01 (1.9.70); FILE MERGED 2003/09/23 10:29:34 hro 1.9.70.2: #110999# Typo: Member mutex must not have the same name as the class Mutex 2003/09/17 09:45:36 obr 1.9.70.1: #110999# made synchrnoization objects non copy constructable / assignable and updated documentation.<commit_after>/*************************************************************************
*
* $RCSfile: mutex.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2003-10-20 16:10:59 $
*
* 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 _OSL_MUTEX_HXX_
#define _OSL_MUTEX_HXX_
#ifdef __cplusplus
#include <osl/mutex.h>
namespace osl
{
/** A mutual exclusion synchronization object
*/
class Mutex {
public:
/** Create a thread-local mutex.
@return 0 if the mutex could not be created, otherwise a handle to the mutex.
@seealso ::osl_createMutex()
*/
Mutex()
{
mutex = osl_createMutex();
}
/** Release the OS-structures and free mutex data-structure.
@seealso ::osl_destroyMutex()
*/
~Mutex()
{
osl_destroyMutex(mutex);
}
/** Acquire the mutex, block if already acquired by another thread.
@return sal_False if system-call fails.
@seealso ::osl_acquireMutex()
*/
sal_Bool acquire()
{
return osl_acquireMutex(mutex);
}
/** Try to acquire the mutex without blocking.
@return sal_False if it could not be acquired.
@seealso ::osl_tryToAcquireMutex()
*/
sal_Bool tryToAcquire()
{
return osl_tryToAcquireMutex(mutex);
}
/** Release the mutex.
@return sal_False if system-call fails.
@seealso ::osl_releaseMutex()
*/
sal_Bool release()
{
return osl_releaseMutex(mutex);
}
/** Returns a global static mutex object.
The global and static mutex object can be used to initialize other
static objects in a thread safe manner.
@return the global mutex object
@seealso ::osl_getGlobalMutex()
*/
static Mutex * getGlobalMutex()
{
return (Mutex *)osl_getGlobalMutex();
}
private:
oslMutex mutex;
/** The underlying oslMutex has no reference count.
Since the underlying oslMutex is not a reference counted object, copy
constructed Mutex may work on an already destructed oslMutex object.
*/
Mutex(const Mutex&);
/** The underlying oslMutex has no reference count.
When destructed, the Mutex object destroys the undelying oslMutex,
which might cause severe problems in case it's a temporary object.
*/
Mutex(oslMutex Mutex);
/** This assignment operator is private for the same reason as
the copy constructor.
*/
Mutex& operator= (const Mutex&);
/** This assignment operator is private for the same reason as
the constructor taking a oslMutex argument.
*/
Mutex& operator= (oslMutex);
};
/** A helper class for mutex objects and interfaces.
*/
template<class T>
class Guard
{
private:
Guard( const Guard& );
const Guard& operator = ( const Guard& );
protected:
T * pT;
public:
/** Acquires the object specified as parameter.
*/
Guard(T * pT_) : pT(pT_)
{
pT->acquire();
}
/** Acquires the object specified as parameter.
*/
Guard(T & t) : pT(&t)
{
pT->acquire();
}
/** Releases the mutex or interface. */
~Guard()
{
pT->release();
}
};
/** A helper class for mutex objects and interfaces.
*/
template<class T>
class ClearableGuard
{
private:
ClearableGuard( const ClearableGuard& );
const ClearableGuard& operator = ( const ClearableGuard& );
protected:
T * pT;
public:
/** Acquires the object specified as parameter.
*/
ClearableGuard(T * pT_) : pT(pT_)
{
pT->acquire();
}
/** Acquires the object specified as parameter.
*/
ClearableGuard(T & t) : pT(&t)
{
pT->acquire();
}
/** Releases the mutex or interface if not already released by clear().
*/
~ClearableGuard()
{
if (pT)
pT->release();
}
/** Releases the mutex or interface.
*/
void clear()
{
if(pT)
{
pT->release();
pT = NULL;
}
}
};
/** A helper class for mutex objects and interfaces.
*/
template< class T >
class ResettableGuard : public ClearableGuard< T >
{
protected:
T* pResetT;
public:
/** Acquires the object specified as parameter.
*/
ResettableGuard( T* pT ) :
ClearableGuard<T>( pT ),
pResetT( pT )
{}
/** Acquires the object specified as parameter.
*/
ResettableGuard( T& rT ) :
ClearableGuard<T>( rT ),
pResetT( &rT )
{}
/** Re-aquires the mutex or interface.
*/
void reset()
{
if( pResetT )
{
pT = pResetT;
pT->acquire();
}
}
};
typedef Guard<Mutex> MutexGuard;
typedef ClearableGuard<Mutex> ClearableMutexGuard;
typedef ResettableGuard< Mutex > ResettableMutexGuard;
}
#endif /* __cplusplus */
#endif /* _OSL_MUTEX_HXX_ */
<|endoftext|>
|
<commit_before>#ifndef VIENNAGRID_DOMAIN_HPP
#define VIENNAGRID_DOMAIN_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/domain/domain.hpp"
#include "viennagrid/domain/element_creation.hpp"
namespace viennagrid
{
template<typename src_domain_type, typename src_segment_container_type, typename dst_domain_type, typename dst_segment_container_type>
void copy_domain(
src_domain_type const & src_domain, src_segment_container_type const & src_segments,
dst_domain_type & dst_domain, dst_segment_container_type & dst_segments )
{
typedef typename src_segment_container_type::value_type src_segment_type;
typedef typename dst_segment_container_type::value_type dst_segment_type;
typedef typename viennagrid::result_of::cell_tag<src_domain_type>::type src_cell_tag;
typedef typename viennagrid::result_of::cell_type<src_domain_type>::type src_cell_type;
typedef typename viennagrid::result_of::const_vertex_range<src_domain_type>::type src_vertex_range_type;
typedef typename viennagrid::result_of::iterator<src_vertex_range_type>::type src_vertex_range_iterator;
typedef typename viennagrid::result_of::const_cell_range<src_segment_type>::type src_cell_range_type;
typedef typename viennagrid::result_of::iterator<src_cell_range_type>::type src_cell_range_itertor;
typedef typename viennagrid::result_of::const_vertex_handle<src_domain_type>::type src_const_vertex_handle;
typedef typename viennagrid::result_of::vertex_handle<dst_domain_type>::type dst_vertex_handle;
if (&src_domain == &dst_domain)
return;
viennagrid::clear_domain(dst_domain);
dst_segments.clear();
std::map<src_const_vertex_handle, dst_vertex_handle> vertex_handle_map;
src_vertex_range_type vertices = viennagrid::elements( src_domain );
// std::cout << "Copy: vertex count = " << vertices.size() << std::endl;
for (src_vertex_range_iterator it = vertices.begin(); it != vertices.end(); ++it)
vertex_handle_map[it.handle()] = viennagrid::create_vertex( dst_domain, viennagrid::point(src_domain, *it) );
for (typename src_segment_container_type::const_iterator seg_it = src_segments.begin(); seg_it != src_segments.end(); ++seg_it)
{
dst_segments.push_back( viennagrid::create_view<dst_segment_type>(dst_domain) );
dst_segment_type & dst_segment = dst_segments.back();
src_cell_range_type cells = viennagrid::elements( *seg_it );
// std::cout << "Copy: cell count = " << cells.size() << std::endl;
for (src_cell_range_itertor it = cells.begin(); it != cells.end(); ++it)
{
src_cell_type const & cell = *it;
std::deque<dst_vertex_handle> vertex_handles;
typedef typename viennagrid::result_of::const_vertex_range<src_cell_type>::type src_vertex_on_src_cell_range_type;
typedef typename viennagrid::result_of::iterator<src_vertex_on_src_cell_range_type>::type src_vertex_on_src_cell_range_iterator;
src_vertex_on_src_cell_range_type cell_vertices = viennagrid::elements(cell);
for (src_vertex_on_src_cell_range_iterator jt = cell_vertices.begin(); jt != cell_vertices.end(); ++jt)
vertex_handles.push_back( vertex_handle_map[jt.handle()] );
typedef typename viennagrid::result_of::cell_type<dst_domain_type>::type dst_cell_type;
viennagrid::create_element<dst_cell_type>( dst_segment, vertex_handles.begin(), vertex_handles.end() );
}
}
}
}
#endif
<commit_msg>fixed include guard<commit_after>#ifndef VIENNAGRID_DOMAIN_OPERATIONS_HPP
#define VIENNAGRID_DOMAIN_OPERATIONS_HPP
/* =======================================================================
Copyright (c) 2011-2012, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
Authors: Karl Rupp [email protected]
Josef Weinbub [email protected]
(A list of additional contributors can be found in the PDF manual)
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include "viennagrid/domain/domain.hpp"
#include "viennagrid/domain/element_creation.hpp"
namespace viennagrid
{
template<typename src_domain_type, typename src_segment_container_type, typename dst_domain_type, typename dst_segment_container_type>
void copy_domain(
src_domain_type const & src_domain, src_segment_container_type const & src_segments,
dst_domain_type & dst_domain, dst_segment_container_type & dst_segments )
{
typedef typename src_segment_container_type::value_type src_segment_type;
typedef typename dst_segment_container_type::value_type dst_segment_type;
typedef typename viennagrid::result_of::cell_tag<src_domain_type>::type src_cell_tag;
typedef typename viennagrid::result_of::cell_type<src_domain_type>::type src_cell_type;
typedef typename viennagrid::result_of::const_vertex_range<src_domain_type>::type src_vertex_range_type;
typedef typename viennagrid::result_of::iterator<src_vertex_range_type>::type src_vertex_range_iterator;
typedef typename viennagrid::result_of::const_cell_range<src_segment_type>::type src_cell_range_type;
typedef typename viennagrid::result_of::iterator<src_cell_range_type>::type src_cell_range_itertor;
typedef typename viennagrid::result_of::const_vertex_handle<src_domain_type>::type src_const_vertex_handle;
typedef typename viennagrid::result_of::vertex_handle<dst_domain_type>::type dst_vertex_handle;
if (&src_domain == &dst_domain)
return;
viennagrid::clear_domain(dst_domain);
dst_segments.clear();
std::map<src_const_vertex_handle, dst_vertex_handle> vertex_handle_map;
src_vertex_range_type vertices = viennagrid::elements( src_domain );
// std::cout << "Copy: vertex count = " << vertices.size() << std::endl;
for (src_vertex_range_iterator it = vertices.begin(); it != vertices.end(); ++it)
vertex_handle_map[it.handle()] = viennagrid::create_vertex( dst_domain, viennagrid::point(src_domain, *it) );
for (typename src_segment_container_type::const_iterator seg_it = src_segments.begin(); seg_it != src_segments.end(); ++seg_it)
{
dst_segments.push_back( viennagrid::create_view<dst_segment_type>(dst_domain) );
dst_segment_type & dst_segment = dst_segments.back();
src_cell_range_type cells = viennagrid::elements( *seg_it );
// std::cout << "Copy: cell count = " << cells.size() << std::endl;
for (src_cell_range_itertor it = cells.begin(); it != cells.end(); ++it)
{
src_cell_type const & cell = *it;
std::deque<dst_vertex_handle> vertex_handles;
typedef typename viennagrid::result_of::const_vertex_range<src_cell_type>::type src_vertex_on_src_cell_range_type;
typedef typename viennagrid::result_of::iterator<src_vertex_on_src_cell_range_type>::type src_vertex_on_src_cell_range_iterator;
src_vertex_on_src_cell_range_type cell_vertices = viennagrid::elements(cell);
for (src_vertex_on_src_cell_range_iterator jt = cell_vertices.begin(); jt != cell_vertices.end(); ++jt)
vertex_handles.push_back( vertex_handle_map[jt.handle()] );
typedef typename viennagrid::result_of::cell_type<dst_domain_type>::type dst_cell_type;
viennagrid::create_element<dst_cell_type>( dst_segment, vertex_handles.begin(), vertex_handles.end() );
}
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <folly/File.h>
#include <folly/FileUtil.h>
#include <folly/Singleton.h>
#include <folly/experimental/TestUtil.h>
#include <folly/portability/GTest.h>
#include <folly/portability/SysStat.h>
#include <folly/synchronization/Baton.h>
#include <wangle/portability/Filesystem.h>
#include <wangle/util/FilePoller.h>
#if !defined(_WIN32) || defined(WANGLE_USE_STD_FILESYSTEM)
using namespace testing;
using namespace folly;
using namespace wangle;
using namespace folly::test;
using namespace std::chrono;
using FileTime = FilePoller::FileTime;
class FilePollerTest : public testing::Test {
public:
void createFile() { File(tmpFile, O_CREAT); }
TemporaryDirectory tmpDir;
fs::path tmpFilePath{tmpDir.path() / "file-poller"};
std::string tmpFile{tmpFilePath.string()};
};
void updateModifiedTime(
const std::string& path,
bool forward = true,
nanoseconds timeDiffNano = seconds(10)) {
#if WANGLE_USE_STD_FILESYSTEM
auto filesystemPath = std::filesystem::path{path};
auto lastWriteTime = std::filesystem::last_write_time(filesystemPath);
auto timeDiff =
std::chrono::duration_cast<std::filesystem::file_time_type::duration>(
timeDiffNano);
auto newLastWriteTime =
forward ? lastWriteTime + timeDiff : lastWriteTime - timeDiff;
std::filesystem::last_write_time(filesystemPath, newLastWriteTime);
#else
struct stat currentFileStat;
std::array<struct timespec, 2> newTimes;
if (stat(path.c_str(), ¤tFileStat) < 0) {
throw std::runtime_error("Failed to stat file: " + path);
}
#ifdef _WIN32
throw std::runtime_error("don't know how to set mtime on win32");
#elif defined(__APPLE__) || defined(__FreeBSD__) \
|| (defined(__NetBSD__) && (__NetBSD_Version__ < 6099000000))
newTimes[0] = currentFileStat.st_atimespec;
newTimes[1] = currentFileStat.st_mtimespec;
#else
newTimes[0] = currentFileStat.st_atim;
newTimes[1] = currentFileStat.st_mtim;
#endif
auto secVal = duration_cast<seconds>(timeDiffNano).count();
auto nsecVal = timeDiffNano.count();
if (forward) {
newTimes[1].tv_sec += secVal;
newTimes[1].tv_nsec += nsecVal;
} else {
newTimes[1].tv_sec -= secVal;
newTimes[1].tv_nsec -= nsecVal;
}
// 0 <= tv_nsec < 1e9
newTimes[1].tv_nsec %= (long)1e9;
if (newTimes[1].tv_nsec < 0) {
newTimes[1].tv_nsec *= -1;
}
if (utimensat(AT_FDCWD, path.c_str(), newTimes.data(), 0) < 0) {
throw std::runtime_error("Failed to set time for file: " + path);
}
#endif
}
TEST_F(FilePollerTest, TestUpdateFile) {
createFile();
Baton<> baton;
bool updated = false;
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
updateModifiedTime(tmpFile);
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestUpdateFileSubSecond) {
createFile();
Baton<> baton;
bool updated = false;
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
updateModifiedTime(tmpFile, true, milliseconds(10));
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestUpdateFileBackwards) {
createFile();
Baton<> baton;
bool updated = false;
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
updateModifiedTime(tmpFile, false);
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestCreateFile) {
Baton<> baton;
bool updated = false;
createFile();
remove(tmpFile.c_str());
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
File(creat(tmpFile.c_str(), O_RDONLY));
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestDeleteFile) {
Baton<> baton;
bool updated = false;
createFile();
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
remove(tmpFile.c_str());
ASSERT_FALSE(baton.try_wait_for(seconds(1)));
ASSERT_FALSE(updated);
}
struct UpdateSyncState {
std::mutex m;
std::condition_variable cv;
bool updated{false};
void updateTriggered() {
std::unique_lock<std::mutex> lk(m);
updated = true;
cv.notify_one();
}
void waitForUpdate(bool expect = true) {
std::unique_lock<std::mutex> lk(m);
cv.wait_for(lk, seconds(1), [&] { return updated; });
ASSERT_EQ(updated, expect);
updated = false;
}
};
class TestFile {
public:
TestFile(bool exists, FileTime modTime)
: exists_(exists), modTime_(modTime) {}
void update(bool e, FileTime t) {
std::unique_lock<std::mutex> lk(m);
exists_ = e;
modTime_ = t;
}
FilePoller::FileModificationData toFileModData() {
std::unique_lock<std::mutex> lk(m);
return FilePoller::FileModificationData(exists_, modTime_);
}
const std::string name{"fakeFile"};
private:
bool exists_{false};
FileTime modTime_;
std::mutex m;
};
class NoDiskPoller : public FilePoller {
public:
explicit NoDiskPoller(TestFile& testFile)
: FilePoller(milliseconds(10)), testFile_(testFile) {}
protected:
FilePoller::FileModificationData
getFileModData(const std::string& path) noexcept override {
EXPECT_EQ(path, testFile_.name);
return testFile_.toFileModData();
}
private:
TestFile& testFile_;
};
struct PollerWithState {
explicit PollerWithState(TestFile& testFile) {
poller = std::make_unique<NoDiskPoller>(testFile);
poller->addFileToTrack(testFile.name, [&] {
state.updateTriggered();
});
}
void waitForUpdate(bool expect = true) {
ASSERT_NO_FATAL_FAILURE(state.waitForUpdate(expect));
}
std::unique_ptr<FilePoller> poller;
UpdateSyncState state;
};
TEST_F(FilePollerTest, TestTwoUpdatesAndDelete) {
TestFile testFile(true, FileTime(seconds(1)));
PollerWithState poller(testFile);
testFile.update(true, FileTime(seconds(2)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());
testFile.update(true, FileTime(seconds(3)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());
testFile.update(false, FileTime(seconds(0)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));
}
TEST_F(FilePollerTest, TestFileCreatedLate) {
TestFile testFile(false,
FileTime(seconds(0))); // not created yet
PollerWithState poller(testFile);
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));
testFile.update(true, FileTime(seconds(1)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());
}
TEST_F(FilePollerTest, TestMultiplePollers) {
TestFile testFile(true, FileTime(seconds(1)));
PollerWithState p1(testFile);
PollerWithState p2(testFile);
testFile.update(true, FileTime(seconds(2)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());
testFile.update(true, FileTime(seconds(1)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());
// clear one of the pollers and make sure the other is still
// getting them
p2.poller.reset();
testFile.update(true, FileTime(seconds(3)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate(false));
}
TEST(FilePoller, TestFork) {
TestFile testFile(true, FileTime(seconds(1)));
PollerWithState p1(testFile);
testFile.update(true, FileTime(seconds(2)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
// nuke singleton
folly::SingletonVault::singleton()->destroyInstances();
testFile.update(true, FileTime(seconds(3)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
}
#endif
<commit_msg>Improve error handling in FilePollerTest<commit_after>/*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <folly/File.h>
#include <folly/FileUtil.h>
#include <folly/Singleton.h>
#include <folly/experimental/TestUtil.h>
#include <folly/portability/GTest.h>
#include <folly/portability/SysStat.h>
#include <folly/synchronization/Baton.h>
#include <glog/logging.h>
#include <wangle/portability/Filesystem.h>
#include <wangle/util/FilePoller.h>
#if !defined(_WIN32) || defined(WANGLE_USE_STD_FILESYSTEM)
using namespace testing;
using namespace folly;
using namespace wangle;
using namespace folly::test;
using namespace std::chrono;
using FileTime = FilePoller::FileTime;
class FilePollerTest : public testing::Test {
public:
void createFile() { File(tmpFile, O_CREAT); }
TemporaryDirectory tmpDir;
fs::path tmpFilePath{tmpDir.path() / "file-poller"};
std::string tmpFile{tmpFilePath.string()};
};
void updateModifiedTime(
const std::string& path,
bool forward = true,
nanoseconds timeDiffNano = seconds(10)) {
#if WANGLE_USE_STD_FILESYSTEM
auto filesystemPath = std::filesystem::path{path};
auto lastWriteTime = std::filesystem::last_write_time(filesystemPath);
auto timeDiff =
std::chrono::duration_cast<std::filesystem::file_time_type::duration>(
timeDiffNano);
auto newLastWriteTime =
forward ? lastWriteTime + timeDiff : lastWriteTime - timeDiff;
std::filesystem::last_write_time(filesystemPath, newLastWriteTime);
#else
struct stat currentFileStat;
std::array<struct timespec, 2> newTimes;
if (stat(path.c_str(), ¤tFileStat) < 0) {
throw std::runtime_error("Failed to stat file: " + path);
}
#ifdef _WIN32
throw std::runtime_error("don't know how to set mtime on win32");
#elif defined(__APPLE__) || defined(__FreeBSD__) \
|| (defined(__NetBSD__) && (__NetBSD_Version__ < 6099000000))
newTimes[0] = currentFileStat.st_atimespec;
newTimes[1] = currentFileStat.st_mtimespec;
#else
newTimes[0] = currentFileStat.st_atim;
newTimes[1] = currentFileStat.st_mtim;
#endif
auto secVal = duration_cast<seconds>(timeDiffNano).count();
auto nsecVal = timeDiffNano.count();
if (forward) {
newTimes[1].tv_sec += secVal;
newTimes[1].tv_nsec += nsecVal;
} else {
newTimes[1].tv_sec -= secVal;
newTimes[1].tv_nsec -= nsecVal;
}
// 0 <= tv_nsec < 1e9
newTimes[1].tv_nsec %= (long)1e9;
if (newTimes[1].tv_nsec < 0) {
newTimes[1].tv_nsec *= -1;
}
if (utimensat(AT_FDCWD, path.c_str(), newTimes.data(), 0) < 0) {
throw std::runtime_error("Failed to set time for file: " + path);
}
#endif
}
TEST_F(FilePollerTest, TestUpdateFile) {
createFile();
Baton<> baton;
bool updated = false;
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
updateModifiedTime(tmpFile);
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestUpdateFileSubSecond) {
createFile();
Baton<> baton;
bool updated = false;
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
updateModifiedTime(tmpFile, true, milliseconds(10));
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestUpdateFileBackwards) {
createFile();
Baton<> baton;
bool updated = false;
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
updateModifiedTime(tmpFile, false);
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestCreateFile) {
Baton<> baton;
bool updated = false;
createFile();
PCHECK(remove(tmpFile.c_str()) == 0);
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
File(creat(tmpFile.c_str(), O_RDONLY));
ASSERT_TRUE(baton.try_wait_for(seconds(5)));
ASSERT_TRUE(updated);
}
TEST_F(FilePollerTest, TestDeleteFile) {
Baton<> baton;
bool updated = false;
createFile();
FilePoller poller(milliseconds(1));
poller.addFileToTrack(tmpFile, [&]() {
updated = true;
baton.post();
});
PCHECK(remove(tmpFile.c_str()) == 0);
ASSERT_FALSE(baton.try_wait_for(seconds(1)));
ASSERT_FALSE(updated);
}
struct UpdateSyncState {
std::mutex m;
std::condition_variable cv;
bool updated{false};
void updateTriggered() {
std::unique_lock<std::mutex> lk(m);
updated = true;
cv.notify_one();
}
void waitForUpdate(bool expect = true) {
std::unique_lock<std::mutex> lk(m);
cv.wait_for(lk, seconds(1), [&] { return updated; });
ASSERT_EQ(updated, expect);
updated = false;
}
};
class TestFile {
public:
TestFile(bool exists, FileTime modTime)
: exists_(exists), modTime_(modTime) {}
void update(bool e, FileTime t) {
std::unique_lock<std::mutex> lk(m);
exists_ = e;
modTime_ = t;
}
FilePoller::FileModificationData toFileModData() {
std::unique_lock<std::mutex> lk(m);
return FilePoller::FileModificationData(exists_, modTime_);
}
const std::string name{"fakeFile"};
private:
bool exists_{false};
FileTime modTime_;
std::mutex m;
};
class NoDiskPoller : public FilePoller {
public:
explicit NoDiskPoller(TestFile& testFile)
: FilePoller(milliseconds(10)), testFile_(testFile) {}
protected:
FilePoller::FileModificationData
getFileModData(const std::string& path) noexcept override {
EXPECT_EQ(path, testFile_.name);
return testFile_.toFileModData();
}
private:
TestFile& testFile_;
};
struct PollerWithState {
explicit PollerWithState(TestFile& testFile) {
poller = std::make_unique<NoDiskPoller>(testFile);
poller->addFileToTrack(testFile.name, [&] {
state.updateTriggered();
});
}
void waitForUpdate(bool expect = true) {
ASSERT_NO_FATAL_FAILURE(state.waitForUpdate(expect));
}
std::unique_ptr<FilePoller> poller;
UpdateSyncState state;
};
TEST_F(FilePollerTest, TestTwoUpdatesAndDelete) {
TestFile testFile(true, FileTime(seconds(1)));
PollerWithState poller(testFile);
testFile.update(true, FileTime(seconds(2)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());
testFile.update(true, FileTime(seconds(3)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());
testFile.update(false, FileTime(seconds(0)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));
}
TEST_F(FilePollerTest, TestFileCreatedLate) {
TestFile testFile(false,
FileTime(seconds(0))); // not created yet
PollerWithState poller(testFile);
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate(false));
testFile.update(true, FileTime(seconds(1)));
ASSERT_NO_FATAL_FAILURE(poller.waitForUpdate());
}
TEST_F(FilePollerTest, TestMultiplePollers) {
TestFile testFile(true, FileTime(seconds(1)));
PollerWithState p1(testFile);
PollerWithState p2(testFile);
testFile.update(true, FileTime(seconds(2)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());
testFile.update(true, FileTime(seconds(1)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate());
// clear one of the pollers and make sure the other is still
// getting them
p2.poller.reset();
testFile.update(true, FileTime(seconds(3)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
ASSERT_NO_FATAL_FAILURE(p2.waitForUpdate(false));
}
TEST(FilePoller, TestFork) {
TestFile testFile(true, FileTime(seconds(1)));
PollerWithState p1(testFile);
testFile.update(true, FileTime(seconds(2)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
// nuke singleton
folly::SingletonVault::singleton()->destroyInstances();
testFile.update(true, FileTime(seconds(3)));
ASSERT_NO_FATAL_FAILURE(p1.waitForUpdate());
}
#endif
<|endoftext|>
|
<commit_before>/*
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
consideration of your agreement to the following terms, and your use, installation,
modification or redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject to these
terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
this original Apple software (the "Apple Software"), to use, reproduce, modify and
redistribute the Apple Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the Apple Software in its entirety and without
modifications, you must retain this notice and the following text and disclaimers in all
such redistributions of the Apple Software. Neither the name, trademarks, service marks
or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
the Apple Software without specific prior written permission from Apple. Except as expressly
stated in this notice, no other rights or licenses, express or implied, are granted by Apple
herein, including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES,
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <stdio.h>
#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/tools/pepper_test_plugin/plugin_object.h"
#ifdef WIN32
#define NPAPI WINAPI
#else
#define NPAPI
#endif
namespace {
void Log(NPP instance, const char* format, ...) {
va_list args;
va_start(args, format);
std::string message("PLUGIN: ");
StringAppendV(&message, format, args);
va_end(args);
NPObject* window_object = 0;
NPError error = browser->getvalue(instance, NPNVWindowNPObject,
&window_object);
if (error != NPERR_NO_ERROR) {
LOG(ERROR) << "Failed to retrieve window object while logging: "
<< message;
return;
}
NPVariant console_variant;
if (!browser->getproperty(instance, window_object,
browser->getstringidentifier("console"),
&console_variant)) {
LOG(ERROR) << "Failed to retrieve console object while logging: "
<< message;
browser->releaseobject(window_object);
return;
}
NPObject* console_object = NPVARIANT_TO_OBJECT(console_variant);
NPVariant message_variant;
STRINGZ_TO_NPVARIANT(message.c_str(), message_variant);
NPVariant result;
if (!browser->invoke(instance, console_object,
browser->getstringidentifier("log"),
&message_variant, 1, &result)) {
fprintf(stderr, "Failed to invoke console.log while logging: %s\n",
message);
browser->releaseobject(console_object);
browser->releaseobject(window_object);
return;
}
browser->releasevariantvalue(&result);
browser->releaseobject(console_object);
browser->releaseobject(window_object);
}
} // namespace
// Plugin entry points
extern "C" {
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
, NPPluginFuncs* plugin_funcs
#endif
);
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs);
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
void NPAPI NP_Shutdown() {
}
#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value);
const char* NP_GetMIMEDescription();
#endif
} // extern "C"
// Plugin entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
, NPPluginFuncs* plugin_funcs
#endif
) {
browser = browser_funcs;
#if defined(OS_LINUX)
return NP_GetEntryPoints(plugin_funcs);
#else
return NPERR_NO_ERROR;
#endif
}
// Entrypoints -----------------------------------------------------------------
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) {
plugin_funcs->version = 11;
plugin_funcs->size = sizeof(plugin_funcs);
plugin_funcs->newp = NPP_New;
plugin_funcs->destroy = NPP_Destroy;
plugin_funcs->setwindow = NPP_SetWindow;
plugin_funcs->newstream = NPP_NewStream;
plugin_funcs->destroystream = NPP_DestroyStream;
plugin_funcs->asfile = NPP_StreamAsFile;
plugin_funcs->writeready = NPP_WriteReady;
plugin_funcs->write = (NPP_WriteProcPtr)NPP_Write;
plugin_funcs->print = NPP_Print;
plugin_funcs->event = NPP_HandleEvent;
plugin_funcs->urlnotify = NPP_URLNotify;
plugin_funcs->getvalue = NPP_GetValue;
plugin_funcs->setvalue = NPP_SetValue;
return NPERR_NO_ERROR;
}
NPError NPP_New(NPMIMEType pluginType,
NPP instance,
uint16 mode,
int16 argc, char* argn[], char* argv[],
NPSavedData* saved) {
if (browser->version >= 14) {
PluginObject* obj = reinterpret_cast<PluginObject*>(
browser->createobject(instance, PluginObject::GetPluginClass()));
instance->pdata = obj;
}
return NPERR_NO_ERROR;
}
NPError NPP_Destroy(NPP instance, NPSavedData** save) {
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj)
browser->releaseobject(obj->header());
fflush(stdout);
return NPERR_NO_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow* window) {
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj)
obj->SetWindow(*window);
return NPERR_NO_ERROR;
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream* stream,
NPBool seekable,
uint16* stype) {
*stype = NP_ASFILEONLY;
return NPERR_NO_ERROR;
}
NPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason) {
return NPERR_NO_ERROR;
}
void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {
}
int32 NPP_Write(NPP instance,
NPStream* stream,
int32 offset,
int32 len,
void* buffer) {
return 0;
}
int32 NPP_WriteReady(NPP instance, NPStream* stream) {
return 0;
}
void NPP_Print(NPP instance, NPPrint* platformPrint) {
}
int16 NPP_HandleEvent(NPP instance, void* event) {
return 0;
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason,
void* notify_data) {
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) {
NPError err = NPERR_NO_ERROR;
switch (variable) {
#if defined(OS_LINUX)
case NPPVpluginNameString:
*((const char**)value) = "Pepper Test PlugIn";
break;
case NPPVpluginDescriptionString:
*((const char**)value) = "Simple Pepper plug-in for manual testing.";
break;
case NPPVpluginNeedsXEmbed:
*((NPBool*)value) = TRUE;
break;
#endif
case NPPVpluginScriptableNPObject: {
void** v = (void**)value;
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
// Return value is expected to be retained
browser->retainobject((NPObject*)obj);
*v = obj;
break;
}
default:
fprintf(stderr, "Unhandled variable to NPP_GetValue\n");
err = NPERR_GENERIC_ERROR;
break;
}
return err;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) {
return NPERR_GENERIC_ERROR;
}
#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value) {
return NPP_GetValue(instance, variable, value);
}
const char* NP_GetMIMEDescription() {
return "pepper-application/x-pepper-test-plugin pepper test;";
}
#endif
<commit_msg>Fix a compilation failure on Linux. It still doesn't link correctly yet on Linux.<commit_after>/*
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
consideration of your agreement to the following terms, and your use, installation,
modification or redistribution of this Apple software constitutes acceptance of these
terms. If you do not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject to these
terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
this original Apple software (the "Apple Software"), to use, reproduce, modify and
redistribute the Apple Software, with or without modifications, in source and/or binary
forms; provided that if you redistribute the Apple Software in its entirety and without
modifications, you must retain this notice and the following text and disclaimers in all
such redistributions of the Apple Software. Neither the name, trademarks, service marks
or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
the Apple Software without specific prior written permission from Apple. Except as expressly
stated in this notice, no other rights or licenses, express or implied, are granted by Apple
herein, including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES,
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <stdio.h>
#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/tools/pepper_test_plugin/plugin_object.h"
#ifdef WIN32
#define NPAPI WINAPI
#else
#define NPAPI
#endif
namespace {
void Log(NPP instance, const char* format, ...) {
va_list args;
va_start(args, format);
std::string message("PLUGIN: ");
StringAppendV(&message, format, args);
va_end(args);
NPObject* window_object = 0;
NPError error = browser->getvalue(instance, NPNVWindowNPObject,
&window_object);
if (error != NPERR_NO_ERROR) {
LOG(ERROR) << "Failed to retrieve window object while logging: "
<< message;
return;
}
NPVariant console_variant;
if (!browser->getproperty(instance, window_object,
browser->getstringidentifier("console"),
&console_variant)) {
LOG(ERROR) << "Failed to retrieve console object while logging: "
<< message;
browser->releaseobject(window_object);
return;
}
NPObject* console_object = NPVARIANT_TO_OBJECT(console_variant);
NPVariant message_variant;
STRINGZ_TO_NPVARIANT(message.c_str(), message_variant);
NPVariant result;
if (!browser->invoke(instance, console_object,
browser->getstringidentifier("log"),
&message_variant, 1, &result)) {
fprintf(stderr, "Failed to invoke console.log while logging: %s\n",
message.c_str());
browser->releaseobject(console_object);
browser->releaseobject(window_object);
return;
}
browser->releasevariantvalue(&result);
browser->releaseobject(console_object);
browser->releaseobject(window_object);
}
} // namespace
// Plugin entry points
extern "C" {
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
, NPPluginFuncs* plugin_funcs
#endif
);
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs);
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
void NPAPI NP_Shutdown() {
}
#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value);
const char* NP_GetMIMEDescription();
#endif
} // extern "C"
// Plugin entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
, NPPluginFuncs* plugin_funcs
#endif
) {
browser = browser_funcs;
#if defined(OS_LINUX)
return NP_GetEntryPoints(plugin_funcs);
#else
return NPERR_NO_ERROR;
#endif
}
// Entrypoints -----------------------------------------------------------------
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) {
plugin_funcs->version = 11;
plugin_funcs->size = sizeof(plugin_funcs);
plugin_funcs->newp = NPP_New;
plugin_funcs->destroy = NPP_Destroy;
plugin_funcs->setwindow = NPP_SetWindow;
plugin_funcs->newstream = NPP_NewStream;
plugin_funcs->destroystream = NPP_DestroyStream;
plugin_funcs->asfile = NPP_StreamAsFile;
plugin_funcs->writeready = NPP_WriteReady;
plugin_funcs->write = (NPP_WriteProcPtr)NPP_Write;
plugin_funcs->print = NPP_Print;
plugin_funcs->event = NPP_HandleEvent;
plugin_funcs->urlnotify = NPP_URLNotify;
plugin_funcs->getvalue = NPP_GetValue;
plugin_funcs->setvalue = NPP_SetValue;
return NPERR_NO_ERROR;
}
NPError NPP_New(NPMIMEType pluginType,
NPP instance,
uint16 mode,
int16 argc, char* argn[], char* argv[],
NPSavedData* saved) {
if (browser->version >= 14) {
PluginObject* obj = reinterpret_cast<PluginObject*>(
browser->createobject(instance, PluginObject::GetPluginClass()));
instance->pdata = obj;
}
return NPERR_NO_ERROR;
}
NPError NPP_Destroy(NPP instance, NPSavedData** save) {
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj)
browser->releaseobject(obj->header());
fflush(stdout);
return NPERR_NO_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow* window) {
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
if (obj)
obj->SetWindow(*window);
return NPERR_NO_ERROR;
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream* stream,
NPBool seekable,
uint16* stype) {
*stype = NP_ASFILEONLY;
return NPERR_NO_ERROR;
}
NPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason) {
return NPERR_NO_ERROR;
}
void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {
}
int32 NPP_Write(NPP instance,
NPStream* stream,
int32 offset,
int32 len,
void* buffer) {
return 0;
}
int32 NPP_WriteReady(NPP instance, NPStream* stream) {
return 0;
}
void NPP_Print(NPP instance, NPPrint* platformPrint) {
}
int16 NPP_HandleEvent(NPP instance, void* event) {
return 0;
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason,
void* notify_data) {
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) {
NPError err = NPERR_NO_ERROR;
switch (variable) {
#if defined(OS_LINUX)
case NPPVpluginNameString:
*((const char**)value) = "Pepper Test PlugIn";
break;
case NPPVpluginDescriptionString:
*((const char**)value) = "Simple Pepper plug-in for manual testing.";
break;
case NPPVpluginNeedsXEmbed:
*((NPBool*)value) = TRUE;
break;
#endif
case NPPVpluginScriptableNPObject: {
void** v = (void**)value;
PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
// Return value is expected to be retained
browser->retainobject((NPObject*)obj);
*v = obj;
break;
}
default:
fprintf(stderr, "Unhandled variable to NPP_GetValue\n");
err = NPERR_GENERIC_ERROR;
break;
}
return err;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) {
return NPERR_GENERIC_ERROR;
}
#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value) {
return NPP_GetValue(instance, variable, value);
}
const char* NP_GetMIMEDescription() {
return "pepper-application/x-pepper-test-plugin pepper test;";
}
#endif
<|endoftext|>
|
<commit_before>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the software's owners nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// (This is the BSD 3-clause license)
#include "pointarray.h"
#include <QtGui/QMessageBox>
#include <QtOpenGL/QGLShaderProgram>
#include <unordered_map>
#include <fstream>
#include "tinyformat.h"
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4996)
# pragma warning(disable : 4267)
#elif __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-aliasing"
# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
// Note... laslib generates a small horde of warnings
#include <lasreader.hpp>
#ifdef _MSC_VER
# pragma warning(push)
#elif __GNUC__
# pragma GCC diagnostic pop
#if LAS_TOOLS_VERSION <= 120124
// Hack: kill gcc unused variable warning
class MonkeyChops { MonkeyChops() { (void)LAS_TOOLS_FORMAT_NAMES; } };
#endif
#endif
//------------------------------------------------------------------------------
// Hashing of std::pair, copied from stack overflow
template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
namespace std
{
template<typename S, typename T> struct hash<pair<S, T>>
{
inline size_t operator()(const pair<S, T> & v) const
{
size_t seed = 0;
::hash_combine(seed, v.first);
::hash_combine(seed, v.second);
return seed;
}
};
}
//------------------------------------------------------------------------------
// PointArray implementation
PointArray::PointArray()
: m_fileName(),
m_npoints(0),
m_bucketWidth(100),
m_offset(0),
m_bbox(),
m_centroid(0),
m_buckets()
{ }
PointArray::~PointArray()
{ }
struct PointArray::Bucket
{
V3f centroid;
size_t beginIndex;
size_t endIndex;
Bucket(V3f centroid, size_t beginIndex, size_t endIndex)
: centroid(centroid),
beginIndex(beginIndex),
endIndex(endIndex)
{ }
};
template<typename T>
void reorderArray(std::unique_ptr<T[]>& data, const size_t* inds, size_t size)
{
if (!data)
return;
std::unique_ptr<T[]> tmpData(new T[size]);
for (size_t i = 0; i < size; ++i)
tmpData[i] = data[inds[i]];
data.swap(tmpData);
}
bool PointArray::loadPointFile(QString fileName, size_t maxPointCount)
{
m_fileName = fileName;
size_t totPoints = 0;
V3d Psum(0);
if (fileName.endsWith(".las") || fileName.endsWith(".laz"))
{
LASreadOpener lasReadOpener;
#ifdef _WIN32
// Hack: liblas doesn't like forward slashes as path separators on windows
fileName = fileName.replace('/', '\\');
#endif
lasReadOpener.set_file_name(fileName.toAscii().constData());
std::unique_ptr<LASreader> lasReader(lasReadOpener.open());
if(!lasReader)
{
QMessageBox::critical(0, tr("Error"),
tr("Couldn't open file \"%1\"").arg(fileName));
return false;
}
emit loadStepStarted("Reading file");
// Figure out how much to decimate the point cloud.
totPoints = lasReader->header.number_of_point_records;
size_t decimate = (totPoints + maxPointCount - 1) / maxPointCount;
if(decimate > 1)
tfm::printf("Decimating \"%s\" by factor of %d\n", fileName.toStdString(), decimate);
m_npoints = (totPoints + decimate - 1) / decimate;
m_offset = V3d(lasReader->header.min_x, lasReader->header.min_y, 0);
// Attempt to place all data on the same vertical scale, but allow other
// offsets if the magnitude of z is too large (and we would therefore loose
// noticable precision by storing the data as floats)
if (fabs(lasReader->header.min_z) > 10000)
m_offset.z = lasReader->header.min_z;
m_P.reset(new V3f[m_npoints]);
m_intensity.reset(new float[m_npoints]);
m_returnIndex.reset(new unsigned char[m_npoints]);
m_numberOfReturns.reset(new unsigned char[m_npoints]);
m_pointSourceId.reset(new unsigned char[m_npoints]);
m_bbox.makeEmpty();
// Iterate over all points & pull in the data.
V3f* outP = m_P.get();
float* outIntens = m_intensity.get();
unsigned char* returnIndex = m_returnIndex.get();
unsigned char* numReturns = m_numberOfReturns.get();
unsigned char* pointSourceId = m_pointSourceId.get();
size_t readCount = 0;
size_t nextBlock = 1;
size_t nextStore = 1;
if (!lasReader->read_point())
return false;
const LASpoint& point = lasReader->point;
if (point.have_rgb)
m_color.reset(new C3f[m_npoints]);
V3f* outCol = m_color.get();
do
{
// Read a point from the las file
++readCount;
if(readCount % 10000 == 0)
emit pointsLoaded(100*readCount/totPoints);
V3d P = V3d(point.get_x(), point.get_y(), point.get_z());
m_bbox.extendBy(P);
Psum += P;
if(readCount < nextStore)
continue;
// Store the point
*outP++ = P - m_offset;
// float intens = float(point.scan_angle_rank) / 40;
*outIntens++ = point.intensity;
*returnIndex++ = point.return_number;
*numReturns++ = point.number_of_returns_of_given_pulse;
*pointSourceId++ = point.point_source_ID;
// Extract point RGB
if (outCol)
*outCol++ = (1.0f/USHRT_MAX) * C3f(point.rgb[0], point.rgb[1], point.rgb[2]);
// Figure out which point will be the next stored point.
nextBlock += decimate;
nextStore = nextBlock;
if(decimate > 1)
{
// Randomize selected point within block to avoid repeated patterns
nextStore += (qrand() % decimate);
if(nextBlock <= totPoints && nextStore > totPoints)
nextStore = totPoints;
}
}
while(lasReader->read_point());
lasReader->close();
}
else
{
// Assume text, xyz format
// TODO: Make this less braindead!
std::ifstream inFile(fileName.toStdString());
std::vector<Imath::V3d> points;
Imath::V3d p;
m_bbox.makeEmpty();
while (inFile >> p.x >> p.y >> p.z)
{
points.push_back(p);
m_bbox.extendBy(p);
}
m_npoints = points.size();
totPoints = points.size();
m_offset = points[0];
m_P.reset(new V3f[m_npoints]);
m_intensity.reset(new float[m_npoints]);
m_returnIndex.reset(new unsigned char[m_npoints]);
m_numberOfReturns.reset(new unsigned char[m_npoints]);
m_pointSourceId.reset(new unsigned char[m_npoints]);
for (size_t i = 0; i < m_npoints; ++i)
{
m_P[i] = points[i] - m_offset;
Psum += points[i];
m_intensity[i] = 0;
}
}
emit pointsLoaded(100);
m_centroid = (1.0/totPoints) * Psum;
tfm::printf("Displaying %d of %d points from file %s\n", m_npoints,
totPoints, fileName.toStdString());
emit loadStepStarted("Bucketing points");
typedef std::unordered_map<std::pair<int,int>, std::vector<size_t> > IndexMap;
float invBucketSize = 1/m_bucketWidth;
IndexMap buckets;
for (size_t i = 0; i < m_npoints; ++i)
{
int x = (int)floor(m_P[i].x*invBucketSize);
int y = (int)floor(m_P[i].y*invBucketSize);
buckets[std::make_pair(x,y)].push_back(i);
if(i % 100000 == 0)
emit pointsLoaded(100*i/m_npoints);
}
//emit loadStepStarted("Shuffling buckets");
std::unique_ptr<size_t[]> inds(new size_t[m_npoints]);
size_t idx = 0;
m_buckets.clear();
m_buckets.reserve(buckets.size() + 1);
for (IndexMap::iterator b = buckets.begin(); b != buckets.end(); ++b)
{
size_t startIdx = idx;
std::vector<size_t>& bucketInds = b->second;
V3f centroid(0);
// Random shuffle so that choosing an initial sequence will correspond
// to a stochastic simplification of the bucket. TODO: Use a
// quasirandom shuffling method for better visual properties.
std::random_shuffle(bucketInds.begin(), bucketInds.end());
for (size_t i = 0, iend = bucketInds.size(); i < iend; ++i, ++idx)
{
inds[idx] = bucketInds[i];
centroid += m_P[inds[idx]];
}
centroid *= 1.0f/(idx - startIdx);
m_buckets.push_back(Bucket(centroid, startIdx, idx));
}
reorderArray(m_P, inds.get(), m_npoints);
reorderArray(m_color, inds.get(), m_npoints);
reorderArray(m_intensity, inds.get(), m_npoints);
reorderArray(m_returnIndex, inds.get(), m_npoints);
reorderArray(m_numberOfReturns, inds.get(), m_npoints);
reorderArray(m_pointSourceId, inds.get(), m_npoints);
return true;
}
size_t PointArray::closestPoint(V3d pos, V3f N,
double normalDirectionScale,
double* distance) const
{
pos -= m_offset;
N.normalize();
const V3f* P = m_P.get();
size_t nearestIdx = -1;
double nearestDist2 = DBL_MAX;
double f = normalDirectionScale*normalDirectionScale;
for(size_t i = 0; i < m_npoints; ++i, ++P)
{
V3f v = pos - *P;
float distN = N.dot(v);
float distNperp = (v - distN*N).length2();
float d = f*distN*distN + distNperp;
//float d = (pos - *P).length2();
if(d < nearestDist2)
{
nearestDist2 = d;
nearestIdx = i;
}
}
if(distance)
*distance = sqrt(nearestDist2);
return nearestIdx;
}
void PointArray::draw(QGLShaderProgram& prog, const V3d& cameraPos,
double quality) const
{
prog.enableAttributeArray("position");
prog.enableAttributeArray("intensity");
prog.enableAttributeArray("returnIndex");
prog.enableAttributeArray("numberOfReturns");
prog.enableAttributeArray("pointSourceId");
if (m_color)
prog.enableAttributeArray("color");
else
{
prog.disableAttributeArray("color");
prog.setAttributeValue("color", 0.0f, 0.0f, 0.0f);
}
// Draw points in each bucket, with total number drawn depending on how far
// away the bucket is. Since the points are shuffled, this corresponds to
// a stochastic simplification of the full point cloud.
size_t totDraw = 0;
for (size_t bucketIdx = 0; bucketIdx < m_buckets.size(); ++bucketIdx)
{
const Bucket& bucket = m_buckets[bucketIdx];
size_t b = bucket.beginIndex;
prog.setAttributeArray("position", (const GLfloat*)(m_P.get() + b), 3);
prog.setAttributeArray("intensity", m_intensity.get() + b, 1);
prog.setAttributeArray("returnIndex", GL_UNSIGNED_BYTE, m_returnIndex.get() + b, 1);
prog.setAttributeArray("numberOfReturns", GL_UNSIGNED_BYTE, m_numberOfReturns.get() + b, 1);
prog.setAttributeArray("pointSourceId", GL_UNSIGNED_BYTE, m_pointSourceId.get() + b, 1);
if (m_color)
prog.setAttributeArray("color", (const GLfloat*)(m_color.get() + b), 3);
// Compute the desired fraction of points for this bucket.
//
// The desired fraction is chosen such that the density of points per
// solid angle is constant; when removing points, the point radii are
// scaled up to keep the total area covered by the points constant.
float dist = (bucket.centroid + m_offset - cameraPos).length();
double desiredFraction = quality <= 0 ? 1 : quality * pow(m_bucketWidth/dist, 2);
size_t ndraw = bucket.endIndex - bucket.beginIndex;
float lodMultiplier = 1;
if (desiredFraction < 1)
{
ndraw = std::max((size_t) 1, (size_t) (ndraw*desiredFraction));
lodMultiplier = (float)sqrt(1/desiredFraction);
}
prog.setUniformValue("pointSizeLodMultiplier", lodMultiplier);
glDrawArrays(GL_POINTS, 0, ndraw);
totDraw += ndraw;
}
//tfm::printf("Drew %.2f%% of total points\n", 100.0*totDraw/m_npoints);
}
<commit_msg>Fix crash when point cloud has zero points<commit_after>// Copyright (C) 2012, Chris J. Foster and the other authors and contributors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the software's owners nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// (This is the BSD 3-clause license)
#include "pointarray.h"
#include <QtGui/QMessageBox>
#include <QtOpenGL/QGLShaderProgram>
#include <unordered_map>
#include <fstream>
#include "tinyformat.h"
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable : 4996)
# pragma warning(disable : 4267)
#elif __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-aliasing"
# pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
// Note... laslib generates a small horde of warnings
#include <lasreader.hpp>
#ifdef _MSC_VER
# pragma warning(push)
#elif __GNUC__
# pragma GCC diagnostic pop
#if LAS_TOOLS_VERSION <= 120124
// Hack: kill gcc unused variable warning
class MonkeyChops { MonkeyChops() { (void)LAS_TOOLS_FORMAT_NAMES; } };
#endif
#endif
//------------------------------------------------------------------------------
// Hashing of std::pair, copied from stack overflow
template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
namespace std
{
template<typename S, typename T> struct hash<pair<S, T>>
{
inline size_t operator()(const pair<S, T> & v) const
{
size_t seed = 0;
::hash_combine(seed, v.first);
::hash_combine(seed, v.second);
return seed;
}
};
}
//------------------------------------------------------------------------------
// PointArray implementation
PointArray::PointArray()
: m_fileName(),
m_npoints(0),
m_bucketWidth(100),
m_offset(0),
m_bbox(),
m_centroid(0),
m_buckets()
{ }
PointArray::~PointArray()
{ }
struct PointArray::Bucket
{
V3f centroid;
size_t beginIndex;
size_t endIndex;
Bucket(V3f centroid, size_t beginIndex, size_t endIndex)
: centroid(centroid),
beginIndex(beginIndex),
endIndex(endIndex)
{ }
};
template<typename T>
void reorderArray(std::unique_ptr<T[]>& data, const size_t* inds, size_t size)
{
if (!data)
return;
std::unique_ptr<T[]> tmpData(new T[size]);
for (size_t i = 0; i < size; ++i)
tmpData[i] = data[inds[i]];
data.swap(tmpData);
}
bool PointArray::loadPointFile(QString fileName, size_t maxPointCount)
{
m_fileName = fileName;
size_t totPoints = 0;
V3d Psum(0);
if (fileName.endsWith(".las") || fileName.endsWith(".laz"))
{
LASreadOpener lasReadOpener;
#ifdef _WIN32
// Hack: liblas doesn't like forward slashes as path separators on windows
fileName = fileName.replace('/', '\\');
#endif
lasReadOpener.set_file_name(fileName.toAscii().constData());
std::unique_ptr<LASreader> lasReader(lasReadOpener.open());
if(!lasReader)
{
QMessageBox::critical(0, tr("Error"),
tr("Couldn't open file \"%1\"").arg(fileName));
return false;
}
emit loadStepStarted("Reading file");
// Figure out how much to decimate the point cloud.
totPoints = lasReader->header.number_of_point_records;
size_t decimate = totPoints == 0 ? 1 : 1 + (totPoints - 1) / maxPointCount;
if(decimate > 1)
tfm::printf("Decimating \"%s\" by factor of %d\n", fileName.toStdString(), decimate);
m_npoints = (totPoints + decimate - 1) / decimate;
m_offset = V3d(lasReader->header.min_x, lasReader->header.min_y, 0);
// Attempt to place all data on the same vertical scale, but allow other
// offsets if the magnitude of z is too large (and we would therefore loose
// noticable precision by storing the data as floats)
if (fabs(lasReader->header.min_z) > 10000)
m_offset.z = lasReader->header.min_z;
m_P.reset(new V3f[m_npoints]);
m_intensity.reset(new float[m_npoints]);
m_returnIndex.reset(new unsigned char[m_npoints]);
m_numberOfReturns.reset(new unsigned char[m_npoints]);
m_pointSourceId.reset(new unsigned char[m_npoints]);
m_bbox.makeEmpty();
// Iterate over all points & pull in the data.
V3f* outP = m_P.get();
float* outIntens = m_intensity.get();
unsigned char* returnIndex = m_returnIndex.get();
unsigned char* numReturns = m_numberOfReturns.get();
unsigned char* pointSourceId = m_pointSourceId.get();
size_t readCount = 0;
size_t nextBlock = 1;
size_t nextStore = 1;
if (!lasReader->read_point())
return false;
const LASpoint& point = lasReader->point;
if (point.have_rgb)
m_color.reset(new C3f[m_npoints]);
V3f* outCol = m_color.get();
do
{
// Read a point from the las file
++readCount;
if(readCount % 10000 == 0)
emit pointsLoaded(100*readCount/totPoints);
V3d P = V3d(point.get_x(), point.get_y(), point.get_z());
m_bbox.extendBy(P);
Psum += P;
if(readCount < nextStore)
continue;
// Store the point
*outP++ = P - m_offset;
// float intens = float(point.scan_angle_rank) / 40;
*outIntens++ = point.intensity;
*returnIndex++ = point.return_number;
*numReturns++ = point.number_of_returns_of_given_pulse;
*pointSourceId++ = point.point_source_ID;
// Extract point RGB
if (outCol)
*outCol++ = (1.0f/USHRT_MAX) * C3f(point.rgb[0], point.rgb[1], point.rgb[2]);
// Figure out which point will be the next stored point.
nextBlock += decimate;
nextStore = nextBlock;
if(decimate > 1)
{
// Randomize selected point within block to avoid repeated patterns
nextStore += (qrand() % decimate);
if(nextBlock <= totPoints && nextStore > totPoints)
nextStore = totPoints;
}
}
while(lasReader->read_point());
lasReader->close();
}
else
{
// Assume text, xyz format
// TODO: Make this less braindead!
std::ifstream inFile(fileName.toStdString());
std::vector<Imath::V3d> points;
Imath::V3d p;
m_bbox.makeEmpty();
while (inFile >> p.x >> p.y >> p.z)
{
points.push_back(p);
m_bbox.extendBy(p);
}
m_npoints = points.size();
totPoints = points.size();
m_offset = points[0];
m_P.reset(new V3f[m_npoints]);
m_intensity.reset(new float[m_npoints]);
m_returnIndex.reset(new unsigned char[m_npoints]);
m_numberOfReturns.reset(new unsigned char[m_npoints]);
m_pointSourceId.reset(new unsigned char[m_npoints]);
for (size_t i = 0; i < m_npoints; ++i)
{
m_P[i] = points[i] - m_offset;
Psum += points[i];
m_intensity[i] = 0;
}
}
emit pointsLoaded(100);
m_centroid = (1.0/totPoints) * Psum;
tfm::printf("Displaying %d of %d points from file %s\n", m_npoints,
totPoints, fileName.toStdString());
emit loadStepStarted("Bucketing points");
typedef std::unordered_map<std::pair<int,int>, std::vector<size_t> > IndexMap;
float invBucketSize = 1/m_bucketWidth;
IndexMap buckets;
for (size_t i = 0; i < m_npoints; ++i)
{
int x = (int)floor(m_P[i].x*invBucketSize);
int y = (int)floor(m_P[i].y*invBucketSize);
buckets[std::make_pair(x,y)].push_back(i);
if(i % 100000 == 0)
emit pointsLoaded(100*i/m_npoints);
}
//emit loadStepStarted("Shuffling buckets");
std::unique_ptr<size_t[]> inds(new size_t[m_npoints]);
size_t idx = 0;
m_buckets.clear();
m_buckets.reserve(buckets.size() + 1);
for (IndexMap::iterator b = buckets.begin(); b != buckets.end(); ++b)
{
size_t startIdx = idx;
std::vector<size_t>& bucketInds = b->second;
V3f centroid(0);
// Random shuffle so that choosing an initial sequence will correspond
// to a stochastic simplification of the bucket. TODO: Use a
// quasirandom shuffling method for better visual properties.
std::random_shuffle(bucketInds.begin(), bucketInds.end());
for (size_t i = 0, iend = bucketInds.size(); i < iend; ++i, ++idx)
{
inds[idx] = bucketInds[i];
centroid += m_P[inds[idx]];
}
centroid *= 1.0f/(idx - startIdx);
m_buckets.push_back(Bucket(centroid, startIdx, idx));
}
reorderArray(m_P, inds.get(), m_npoints);
reorderArray(m_color, inds.get(), m_npoints);
reorderArray(m_intensity, inds.get(), m_npoints);
reorderArray(m_returnIndex, inds.get(), m_npoints);
reorderArray(m_numberOfReturns, inds.get(), m_npoints);
reorderArray(m_pointSourceId, inds.get(), m_npoints);
return true;
}
size_t PointArray::closestPoint(V3d pos, V3f N,
double normalDirectionScale,
double* distance) const
{
pos -= m_offset;
N.normalize();
const V3f* P = m_P.get();
size_t nearestIdx = -1;
double nearestDist2 = DBL_MAX;
double f = normalDirectionScale*normalDirectionScale;
for(size_t i = 0; i < m_npoints; ++i, ++P)
{
V3f v = pos - *P;
float distN = N.dot(v);
float distNperp = (v - distN*N).length2();
float d = f*distN*distN + distNperp;
//float d = (pos - *P).length2();
if(d < nearestDist2)
{
nearestDist2 = d;
nearestIdx = i;
}
}
if(distance)
*distance = sqrt(nearestDist2);
return nearestIdx;
}
void PointArray::draw(QGLShaderProgram& prog, const V3d& cameraPos,
double quality) const
{
prog.enableAttributeArray("position");
prog.enableAttributeArray("intensity");
prog.enableAttributeArray("returnIndex");
prog.enableAttributeArray("numberOfReturns");
prog.enableAttributeArray("pointSourceId");
if (m_color)
prog.enableAttributeArray("color");
else
{
prog.disableAttributeArray("color");
prog.setAttributeValue("color", 0.0f, 0.0f, 0.0f);
}
// Draw points in each bucket, with total number drawn depending on how far
// away the bucket is. Since the points are shuffled, this corresponds to
// a stochastic simplification of the full point cloud.
size_t totDraw = 0;
for (size_t bucketIdx = 0; bucketIdx < m_buckets.size(); ++bucketIdx)
{
const Bucket& bucket = m_buckets[bucketIdx];
size_t b = bucket.beginIndex;
prog.setAttributeArray("position", (const GLfloat*)(m_P.get() + b), 3);
prog.setAttributeArray("intensity", m_intensity.get() + b, 1);
prog.setAttributeArray("returnIndex", GL_UNSIGNED_BYTE, m_returnIndex.get() + b, 1);
prog.setAttributeArray("numberOfReturns", GL_UNSIGNED_BYTE, m_numberOfReturns.get() + b, 1);
prog.setAttributeArray("pointSourceId", GL_UNSIGNED_BYTE, m_pointSourceId.get() + b, 1);
if (m_color)
prog.setAttributeArray("color", (const GLfloat*)(m_color.get() + b), 3);
// Compute the desired fraction of points for this bucket.
//
// The desired fraction is chosen such that the density of points per
// solid angle is constant; when removing points, the point radii are
// scaled up to keep the total area covered by the points constant.
float dist = (bucket.centroid + m_offset - cameraPos).length();
double desiredFraction = quality <= 0 ? 1 : quality * pow(m_bucketWidth/dist, 2);
size_t ndraw = bucket.endIndex - bucket.beginIndex;
float lodMultiplier = 1;
if (desiredFraction < 1)
{
ndraw = std::max((size_t) 1, (size_t) (ndraw*desiredFraction));
lodMultiplier = (float)sqrt(1/desiredFraction);
}
prog.setUniformValue("pointSizeLodMultiplier", lodMultiplier);
glDrawArrays(GL_POINTS, 0, ndraw);
totDraw += ndraw;
}
//tfm::printf("Drew %.2f%% of total points\n", 100.0*totDraw/m_npoints);
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2013, 2014 JCube001
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 <math.h>
#include "quaternion.h"
Quaternion::Quaternion() :
w(1.0f),
x(0.0f),
y(0.0f),
z(0.0f)
{
}
Quaternion::Quaternion(const Quaternion &q) :
w(q.w),
x(q.x),
y(q.y),
z(q.z)
{
}
Quaternion::Quaternion(float w, float x, float y, float z) :
w(w),
x(x),
y(y),
z(z)
{
}
Quaternion Quaternion::conjugate() const
{
return Quaternion(w, -x, -y, -z);
}
void Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle) const
{
ax = x;
ay = y;
az = z;
angle = 2.0f * acos(w);
}
void Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw) const
{
roll = atan2((y * z) + (w * x), 0.5f - ((x * x) + (y * y)));
pitch = asin(-2.0f * ((x * z) + (w * y)));
yaw = atan2((x * y) + (w * z), 0.5f - ((y * y) + (z * z)));
}
float Quaternion::dot(const Quaternion &q) const
{
return (w * q.w) + (x * q.x) + (y * q.y) + (z * q.z);
}
Quaternion Quaternion::inverse() const
{
const float n = norm();
if (n == 0.0f)
{
return Quaternion();
}
return conjugate() / (n * n);
}
float Quaternion::norm() const
{
return sqrt((w * w) + (x * x) + (y * y) + (z * z));
}
void Quaternion::normalize()
{
*this /= norm();
}
Quaternion Quaternion::normalized() const
{
return *this / norm();
}
Quaternion &Quaternion::operator=(const Quaternion &q)
{
w = q.w;
x = q.x;
y = q.y;
z = q.z;
return *this;
}
Quaternion &Quaternion::operator+=(const Quaternion &q)
{
w += q.w;
x += q.x;
y += q.y;
z += q.z;
return *this;
}
Quaternion &Quaternion::operator-=(const Quaternion &q)
{
w -= q.w;
x -= q.x;
y -= q.y;
z -= q.z;
return *this;
}
Quaternion &Quaternion::operator*=(float factor)
{
w *= factor;
x *= factor;
y *= factor;
z *= factor;
return *this;
}
Quaternion &Quaternion::operator*=(const Quaternion &q)
{
w = (w * q.w) - (x * q.x) - (y * q.y) - (z * q.z);
x = (w * q.x) + (x * q.w) + (y * q.z) - (z * q.y);
y = (w * q.y) - (x * q.z) + (y * q.w) + (z * q.x);
z = (w * q.z) + (x * q.y) - (y * q.x) + (z * q.w);
return *this;
}
Quaternion &Quaternion::operator/=(float divisor)
{
w /= divisor;
x /= divisor;
y /= divisor;
z /= divisor;
return *this;
}
<commit_msg>Fixed variables being overwritten during multiplication<commit_after>/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2013, 2014 JCube001
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 <math.h>
#include "quaternion.h"
Quaternion::Quaternion() :
w(1.0f),
x(0.0f),
y(0.0f),
z(0.0f)
{
}
Quaternion::Quaternion(const Quaternion &q) :
w(q.w),
x(q.x),
y(q.y),
z(q.z)
{
}
Quaternion::Quaternion(float w, float x, float y, float z) :
w(w),
x(x),
y(y),
z(z)
{
}
Quaternion Quaternion::conjugate() const
{
return Quaternion(w, -x, -y, -z);
}
void Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle) const
{
ax = x;
ay = y;
az = z;
angle = 2.0f * acos(w);
}
void Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw) const
{
roll = atan2((y * z) + (w * x), 0.5f - ((x * x) + (y * y)));
pitch = asin(-2.0f * ((x * z) + (w * y)));
yaw = atan2((x * y) + (w * z), 0.5f - ((y * y) + (z * z)));
}
float Quaternion::dot(const Quaternion &q) const
{
return (w * q.w) + (x * q.x) + (y * q.y) + (z * q.z);
}
Quaternion Quaternion::inverse() const
{
const float n = norm();
if (n == 0.0f)
{
return Quaternion();
}
return conjugate() / (n * n);
}
float Quaternion::norm() const
{
return sqrt((w * w) + (x * x) + (y * y) + (z * z));
}
void Quaternion::normalize()
{
*this /= norm();
}
Quaternion Quaternion::normalized() const
{
return *this / norm();
}
Quaternion &Quaternion::operator=(const Quaternion &q)
{
w = q.w;
x = q.x;
y = q.y;
z = q.z;
return *this;
}
Quaternion &Quaternion::operator+=(const Quaternion &q)
{
w += q.w;
x += q.x;
y += q.y;
z += q.z;
return *this;
}
Quaternion &Quaternion::operator-=(const Quaternion &q)
{
w -= q.w;
x -= q.x;
y -= q.y;
z -= q.z;
return *this;
}
Quaternion &Quaternion::operator*=(float factor)
{
w *= factor;
x *= factor;
y *= factor;
z *= factor;
return *this;
}
Quaternion &Quaternion::operator*=(const Quaternion &q)
{
Quaternion t = *this;
w = (t.w * q.w) - (t.x * q.x) - (t.y * q.y) - (t.z * q.z);
x = (t.w * q.x) + (t.x * q.w) + (t.y * q.z) - (t.z * q.y);
y = (t.w * q.y) - (t.x * q.z) + (t.y * q.w) + (t.z * q.x);
z = (t.w * q.z) + (t.x * q.y) - (t.y * q.x) + (t.z * q.w);
return *this;
}
Quaternion &Quaternion::operator/=(float divisor)
{
w /= divisor;
x /= divisor;
y /= divisor;
z /= divisor;
return *this;
}
<|endoftext|>
|
<commit_before>#pragma once
#include <bts/blockchain/asset.hpp>
#include <bts/blockchain/config.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/exception/exception.hpp>
#include <fc/io/enum_type.hpp>
#include <fc/time.hpp>
#include <tuple>
namespace bts { namespace blockchain {
struct market_index_key
{
market_index_key( const price& price_arg = price(),
const address& owner_arg = address() )
:order_price(price_arg),owner(owner_arg){}
price order_price;
address owner;
friend bool operator == ( const market_index_key& a, const market_index_key& b )
{
return a.order_price == b.order_price && a.owner == b.owner;
}
friend bool operator < ( const market_index_key& a, const market_index_key& b )
{
return std::tie(a.order_price, a.owner) < std::tie(b.order_price, b.owner);
}
};
struct market_history_key
{
enum time_granularity_enum {
each_block,
each_hour,
each_day
};
market_history_key( asset_id_type quote_id = 0,
asset_id_type base_id = 1,
time_granularity_enum granularity = each_block,
fc::time_point_sec timestamp = fc::time_point_sec())
: quote_id(quote_id),
base_id(base_id),
granularity(granularity),
timestamp(timestamp)
{}
asset_id_type quote_id;
asset_id_type base_id;
time_granularity_enum granularity;
fc::time_point_sec timestamp;
bool operator < ( const market_history_key& other ) const
{
return std::tie(base_id, quote_id, granularity, timestamp) < std::tie(other.base_id, other.quote_id, other.granularity, other.timestamp);
}
bool operator == ( const market_history_key& other ) const
{
return quote_id == other.quote_id
&& base_id == other.base_id
&& granularity == other.granularity
&& timestamp == other.timestamp;
}
};
struct market_history_record
{
market_history_record(price highest_bid = price(),
price lowest_ask = price(),
price opening_price = price(),
price closing_price = price(),
share_type volume = 0,
fc::optional<price> recent_average_price = fc::optional<price>())
: highest_bid(highest_bid),
lowest_ask(lowest_ask),
opening_price(opening_price),
closing_price(closing_price),
volume(volume),
recent_average_price(recent_average_price)
{}
price highest_bid;
price lowest_ask;
price opening_price;
price closing_price;
share_type volume;
fc::optional<price> recent_average_price;
bool operator == ( const market_history_record& other ) const
{
return highest_bid == other.highest_bid
&& lowest_ask == other.lowest_ask
&& volume == other.volume;
}
};
typedef fc::optional<market_history_record> omarket_history_record;
struct market_history_point
{
fc::time_point_sec timestamp;
double highest_bid;
double lowest_ask;
double opening_price;
double closing_price;
share_type volume;
fc::optional<double> recent_average_price;
};
typedef vector<market_history_point> market_history_points;
struct order_record
{
order_record():balance(0){}
order_record( share_type b )
:balance(b){}
bool is_null() const { return balance == 0; }
share_type balance;
optional<price> short_price_limit;
fc::time_point last_update;
};
typedef fc::optional<order_record> oorder_record;
enum order_type_enum
{
null_order,
bid_order,
ask_order,
short_order,
cover_order
};
struct market_order
{
market_order( order_type_enum t, market_index_key k, order_record s )
:type(t),market_index(k),state(s){}
market_order( order_type_enum t, market_index_key k, order_record s, share_type c )
:type(t),market_index(k),state(s),collateral(c){}
market_order():type(null_order){}
order_id_type get_id()const;
string get_small_id()const;
asset get_balance()const; // funds available for this order
price get_price()const;
price get_highest_cover_price()const; // the price that consumes all collateral
asset get_quantity()const;
asset get_quote_quantity()const;
address get_owner()const { return market_index.owner; }
fc::enum_type<uint8_t, order_type_enum> type = null_order;
market_index_key market_index;
order_record state;
optional<share_type> collateral;
};
struct market_transaction
{
address bid_owner;
address ask_owner;
price bid_price;
price ask_price;
asset bid_paid;
asset bid_received;
/** if bid_type == short, then collateral will be paid from short to cover positon */
optional<asset> bid_collateral;
asset ask_paid;
asset ask_received;
fc::enum_type<uint8_t, order_type_enum> bid_type = null_order;
fc::enum_type<uint8_t, order_type_enum> ask_type = null_order;
asset fees_collected;
};
typedef optional<market_order> omarket_order;
struct order_history_record : public market_transaction
{
order_history_record(const market_transaction& market_trans = market_transaction(), fc::time_point_sec timestamp = fc::time_point_sec())
: market_transaction(market_trans),
timestamp(timestamp)
{}
fc::time_point_sec timestamp;
};
struct collateral_record
{
collateral_record(share_type c = 0, share_type p = 0):collateral_balance(c),payoff_balance(p){}
bool is_null() const { return 0 == payoff_balance && 0 == collateral_balance; }
share_type collateral_balance;
share_type payoff_balance;
};
typedef fc::optional<collateral_record> ocollateral_record;
struct market_status
{
market_status():bid_depth(-BTS_BLOCKCHAIN_MAX_SHARES),ask_depth(-BTS_BLOCKCHAIN_MAX_SHARES){}
market_status( asset_id_type quote, asset_id_type base, share_type biddepth, share_type askdepth )
:quote_id(quote),base_id(base),bid_depth(biddepth),ask_depth(askdepth){}
bool is_null()const { return bid_depth == ask_depth && bid_depth == -BTS_BLOCKCHAIN_MAX_SHARES; }
asset_id_type quote_id;
asset_id_type base_id;
price minimum_ask()const
{
auto avg = center_price;
avg.ratio *= 9;
avg.ratio /= 10;
return avg;
}
price maximum_bid()const
{
auto avg = center_price;
avg.ratio *= 10;
avg.ratio /= 9;
return avg;
}
share_type bid_depth;
share_type ask_depth;
/**
* Calculated as the average of the highest bid and lowest ask
* every time the market executes. The new is weighted against
* the old value with a factor of 1:BLOCKS_PER_DAY. In a very
* active market this will be a 24 hour moving average, in
* less active markets this will be a longer window.
*
* No shorts or covers will execute at prices more 30% +/- this
* number which serves as a natural rate limitor on price movement
* and thus limits the potential manipulation.
*/
price center_price;
optional<fc::exception> last_error;
};
typedef optional<market_status> omarket_status;
struct api_market_status : public market_status {
api_market_status(const market_status& market_stat = market_status())
: market_status(market_stat)
{}
double center_price;
};
} } // bts::blockchain
FC_REFLECT_ENUM( bts::blockchain::order_type_enum, (null_order)(bid_order)(ask_order)(short_order)(cover_order) )
FC_REFLECT_ENUM( bts::blockchain::market_history_key::time_granularity_enum, (each_block)(each_hour)(each_day) )
FC_REFLECT( bts::blockchain::market_status, (quote_id)(base_id)(bid_depth)(ask_depth)(center_price)(last_error) )
FC_REFLECT_DERIVED( bts::blockchain::api_market_status, (bts::blockchain::market_status), (center_price) )
FC_REFLECT( bts::blockchain::market_index_key, (order_price)(owner) )
FC_REFLECT( bts::blockchain::market_history_record, (highest_bid)(lowest_ask)(opening_price)(closing_price)(volume)(recent_average_price) )
FC_REFLECT( bts::blockchain::market_history_key, (quote_id)(base_id)(granularity)(timestamp) )
FC_REFLECT( bts::blockchain::market_history_point, (timestamp)(highest_bid)(lowest_ask)(opening_price)(closing_price)(volume)(recent_average_price) )
FC_REFLECT( bts::blockchain::order_record, (balance)(short_price_limit)(last_update) )
FC_REFLECT( bts::blockchain::collateral_record, (collateral_balance)(payoff_balance) )
FC_REFLECT( bts::blockchain::market_order, (type)(market_index)(state)(collateral) )
FC_REFLECT_TYPENAME( std::vector<bts::blockchain::market_transaction> )
FC_REFLECT_TYPENAME( bts::blockchain::market_history_key::time_granularity_enum ) // http://en.wikipedia.org/wiki/Voodoo_programminqg
FC_REFLECT( bts::blockchain::market_transaction,
(bid_owner)
(ask_owner)
(bid_price)
(ask_price)
(bid_paid)
(bid_received)
(bid_collateral)
(ask_paid)
(ask_received)
(bid_type)
(ask_type)
(fees_collected)
)
FC_REFLECT_DERIVED( bts::blockchain::order_history_record, (bts::blockchain::market_transaction), (timestamp) )
<commit_msg>Use time_point_sec instead of time_point<commit_after>#pragma once
#include <bts/blockchain/asset.hpp>
#include <bts/blockchain/config.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/exception/exception.hpp>
#include <fc/io/enum_type.hpp>
#include <fc/time.hpp>
#include <tuple>
namespace bts { namespace blockchain {
struct market_index_key
{
market_index_key( const price& price_arg = price(),
const address& owner_arg = address() )
:order_price(price_arg),owner(owner_arg){}
price order_price;
address owner;
friend bool operator == ( const market_index_key& a, const market_index_key& b )
{
return a.order_price == b.order_price && a.owner == b.owner;
}
friend bool operator < ( const market_index_key& a, const market_index_key& b )
{
return std::tie(a.order_price, a.owner) < std::tie(b.order_price, b.owner);
}
};
struct market_history_key
{
enum time_granularity_enum {
each_block,
each_hour,
each_day
};
market_history_key( asset_id_type quote_id = 0,
asset_id_type base_id = 1,
time_granularity_enum granularity = each_block,
fc::time_point_sec timestamp = fc::time_point_sec())
: quote_id(quote_id),
base_id(base_id),
granularity(granularity),
timestamp(timestamp)
{}
asset_id_type quote_id;
asset_id_type base_id;
time_granularity_enum granularity;
fc::time_point_sec timestamp;
bool operator < ( const market_history_key& other ) const
{
return std::tie(base_id, quote_id, granularity, timestamp) < std::tie(other.base_id, other.quote_id, other.granularity, other.timestamp);
}
bool operator == ( const market_history_key& other ) const
{
return quote_id == other.quote_id
&& base_id == other.base_id
&& granularity == other.granularity
&& timestamp == other.timestamp;
}
};
struct market_history_record
{
market_history_record(price highest_bid = price(),
price lowest_ask = price(),
price opening_price = price(),
price closing_price = price(),
share_type volume = 0,
fc::optional<price> recent_average_price = fc::optional<price>())
: highest_bid(highest_bid),
lowest_ask(lowest_ask),
opening_price(opening_price),
closing_price(closing_price),
volume(volume),
recent_average_price(recent_average_price)
{}
price highest_bid;
price lowest_ask;
price opening_price;
price closing_price;
share_type volume;
fc::optional<price> recent_average_price;
bool operator == ( const market_history_record& other ) const
{
return highest_bid == other.highest_bid
&& lowest_ask == other.lowest_ask
&& volume == other.volume;
}
};
typedef fc::optional<market_history_record> omarket_history_record;
struct market_history_point
{
fc::time_point_sec timestamp;
double highest_bid;
double lowest_ask;
double opening_price;
double closing_price;
share_type volume;
fc::optional<double> recent_average_price;
};
typedef vector<market_history_point> market_history_points;
struct order_record
{
order_record():balance(0){}
order_record( share_type b )
:balance(b){}
bool is_null() const { return balance == 0; }
share_type balance;
optional<price> short_price_limit;
fc::time_point_sec last_update;
};
typedef fc::optional<order_record> oorder_record;
enum order_type_enum
{
null_order,
bid_order,
ask_order,
short_order,
cover_order
};
struct market_order
{
market_order( order_type_enum t, market_index_key k, order_record s )
:type(t),market_index(k),state(s){}
market_order( order_type_enum t, market_index_key k, order_record s, share_type c )
:type(t),market_index(k),state(s),collateral(c){}
market_order():type(null_order){}
order_id_type get_id()const;
string get_small_id()const;
asset get_balance()const; // funds available for this order
price get_price()const;
price get_highest_cover_price()const; // the price that consumes all collateral
asset get_quantity()const;
asset get_quote_quantity()const;
address get_owner()const { return market_index.owner; }
fc::enum_type<uint8_t, order_type_enum> type = null_order;
market_index_key market_index;
order_record state;
optional<share_type> collateral;
};
struct market_transaction
{
address bid_owner;
address ask_owner;
price bid_price;
price ask_price;
asset bid_paid;
asset bid_received;
/** if bid_type == short, then collateral will be paid from short to cover positon */
optional<asset> bid_collateral;
asset ask_paid;
asset ask_received;
fc::enum_type<uint8_t, order_type_enum> bid_type = null_order;
fc::enum_type<uint8_t, order_type_enum> ask_type = null_order;
asset fees_collected;
};
typedef optional<market_order> omarket_order;
struct order_history_record : public market_transaction
{
order_history_record(const market_transaction& market_trans = market_transaction(), fc::time_point_sec timestamp = fc::time_point_sec())
: market_transaction(market_trans),
timestamp(timestamp)
{}
fc::time_point_sec timestamp;
};
struct collateral_record
{
collateral_record(share_type c = 0, share_type p = 0):collateral_balance(c),payoff_balance(p){}
bool is_null() const { return 0 == payoff_balance && 0 == collateral_balance; }
share_type collateral_balance;
share_type payoff_balance;
};
typedef fc::optional<collateral_record> ocollateral_record;
struct market_status
{
market_status():bid_depth(-BTS_BLOCKCHAIN_MAX_SHARES),ask_depth(-BTS_BLOCKCHAIN_MAX_SHARES){}
market_status( asset_id_type quote, asset_id_type base, share_type biddepth, share_type askdepth )
:quote_id(quote),base_id(base),bid_depth(biddepth),ask_depth(askdepth){}
bool is_null()const { return bid_depth == ask_depth && bid_depth == -BTS_BLOCKCHAIN_MAX_SHARES; }
asset_id_type quote_id;
asset_id_type base_id;
price minimum_ask()const
{
auto avg = center_price;
avg.ratio *= 9;
avg.ratio /= 10;
return avg;
}
price maximum_bid()const
{
auto avg = center_price;
avg.ratio *= 10;
avg.ratio /= 9;
return avg;
}
share_type bid_depth;
share_type ask_depth;
/**
* Calculated as the average of the highest bid and lowest ask
* every time the market executes. The new is weighted against
* the old value with a factor of 1:BLOCKS_PER_DAY. In a very
* active market this will be a 24 hour moving average, in
* less active markets this will be a longer window.
*
* No shorts or covers will execute at prices more 30% +/- this
* number which serves as a natural rate limitor on price movement
* and thus limits the potential manipulation.
*/
price center_price;
optional<fc::exception> last_error;
};
typedef optional<market_status> omarket_status;
struct api_market_status : public market_status {
api_market_status(const market_status& market_stat = market_status())
: market_status(market_stat)
{}
double center_price;
};
} } // bts::blockchain
FC_REFLECT_ENUM( bts::blockchain::order_type_enum, (null_order)(bid_order)(ask_order)(short_order)(cover_order) )
FC_REFLECT_ENUM( bts::blockchain::market_history_key::time_granularity_enum, (each_block)(each_hour)(each_day) )
FC_REFLECT( bts::blockchain::market_status, (quote_id)(base_id)(bid_depth)(ask_depth)(center_price)(last_error) )
FC_REFLECT_DERIVED( bts::blockchain::api_market_status, (bts::blockchain::market_status), (center_price) )
FC_REFLECT( bts::blockchain::market_index_key, (order_price)(owner) )
FC_REFLECT( bts::blockchain::market_history_record, (highest_bid)(lowest_ask)(opening_price)(closing_price)(volume)(recent_average_price) )
FC_REFLECT( bts::blockchain::market_history_key, (quote_id)(base_id)(granularity)(timestamp) )
FC_REFLECT( bts::blockchain::market_history_point, (timestamp)(highest_bid)(lowest_ask)(opening_price)(closing_price)(volume)(recent_average_price) )
FC_REFLECT( bts::blockchain::order_record, (balance)(short_price_limit)(last_update) )
FC_REFLECT( bts::blockchain::collateral_record, (collateral_balance)(payoff_balance) )
FC_REFLECT( bts::blockchain::market_order, (type)(market_index)(state)(collateral) )
FC_REFLECT_TYPENAME( std::vector<bts::blockchain::market_transaction> )
FC_REFLECT_TYPENAME( bts::blockchain::market_history_key::time_granularity_enum ) // http://en.wikipedia.org/wiki/Voodoo_programminqg
FC_REFLECT( bts::blockchain::market_transaction,
(bid_owner)
(ask_owner)
(bid_price)
(ask_price)
(bid_paid)
(bid_received)
(bid_collateral)
(ask_paid)
(ask_received)
(bid_type)
(ask_type)
(fees_collected)
)
FC_REFLECT_DERIVED( bts::blockchain::order_history_record, (bts::blockchain::market_transaction), (timestamp) )
<|endoftext|>
|
<commit_before>#pragma once
#include <bts/blockchain/asset.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/time.hpp>
namespace bts { namespace blockchain {
struct market_index_key
{
market_index_key( const price& price_arg = price(),
const address& owner_arg = address() )
:order_price(price_arg),owner(owner_arg){}
price order_price;
address owner;
friend bool operator == ( const market_index_key& a, const market_index_key& b )
{
return a.order_price == b.order_price && a.owner == b.owner;
}
friend bool operator < ( const market_index_key& a, const market_index_key& b )
{
if( a.order_price < b.order_price ) return true;
if( a.order_price > b.order_price ) return false;
return a.owner < b.owner;
}
};
struct market_history_key
{
enum time_granularity_enum {
each_block,
each_hour,
each_day
};
market_history_key( asset_id_type quote_id = 0,
asset_id_type base_id = 1,
time_granularity_enum granularity = each_block,
fc::time_point_sec timestamp = fc::time_point_sec())
: quote_id(quote_id),
base_id(base_id),
granularity(granularity),
timestamp(timestamp)
{}
asset_id_type quote_id;
asset_id_type base_id;
time_granularity_enum granularity;
fc::time_point_sec timestamp;
bool operator < ( const market_history_key& other ) const
{
if( base_id < other.base_id ) return true;
if( base_id > other.base_id ) return false;
if( quote_id < other.quote_id ) return true;
if( quote_id > other.quote_id ) return false;
if( granularity < other.granularity ) return true;
if( granularity > other.granularity ) return false;
return timestamp < other.timestamp;
}
bool operator == ( const market_history_key& other ) const
{
return quote_id == other.quote_id
&& base_id == other.base_id
&& granularity == other.granularity
&& timestamp == other.timestamp;
}
};
struct market_history_record
{
market_history_record(price highest_bid = price(),
price lowest_ask = price(),
share_type volume = 0)
: highest_bid(highest_bid),
lowest_ask(lowest_ask),
volume(volume)
{}
price highest_bid;
price lowest_ask;
share_type volume;
bool operator == ( const market_history_record& other ) const
{
return highest_bid == other.highest_bid
&& lowest_ask == other.lowest_ask
&& volume == other.volume;
}
};
typedef fc::optional<market_history_record> omarket_history_record;
typedef std::vector<std::pair<time_point_sec, market_history_record>> market_history_points;
struct order_record
{
order_record():balance(0){}
order_record( share_type b )
:balance(b){}
bool is_null() const { return 0 == balance; }
share_type balance;
};
typedef fc::optional<order_record> oorder_record;
enum order_type_enum
{
null_order,
bid_order,
ask_order,
short_order,
cover_order
};
struct market_order
{
market_order( order_type_enum t, market_index_key k, order_record s )
:type(t),market_index(k),state(s){}
market_order( order_type_enum t, market_index_key k, order_record s, share_type c )
:type(t),market_index(k),state(s),collateral(c){}
market_order():type(null_order){}
string get_id()const;
asset get_balance()const; // funds available for this order
price get_price()const;
price get_highest_cover_price()const; // the price that consumes all collateral
asset get_quantity()const;
asset get_quote_quantity()const;
address get_owner()const { return market_index.owner; }
order_type_enum type;
market_index_key market_index;
order_record state;
optional<share_type> collateral;
};
struct market_transaction
{
market_transaction(){}
address bid_owner;
address ask_owner;
price bid_price;
price ask_price;
asset bid_paid;
asset bid_received;
asset ask_paid;
asset ask_received;
asset fees_collected;
};
typedef optional<market_order> omarket_order;
struct collateral_record
{
collateral_record(share_type c = 0, share_type p = 0):collateral_balance(c),payoff_balance(p){}
bool is_null() const { return 0 == payoff_balance && 0 == collateral_balance; }
share_type collateral_balance;
share_type payoff_balance;
};
typedef fc::optional<collateral_record> ocollateral_record;
} } // bts::blockchain
FC_REFLECT_ENUM( bts::blockchain::order_type_enum, (null_order)(bid_order)(ask_order)(short_order)(cover_order) )
FC_REFLECT_ENUM( bts::blockchain::market_history_key::time_granularity_enum, (each_block)(each_hour)(each_day) )
FC_REFLECT( bts::blockchain::market_index_key, (order_price)(owner) )
FC_REFLECT( bts::blockchain::market_history_record, (highest_bid)(lowest_ask)(volume) )
FC_REFLECT( bts::blockchain::market_history_key, (quote_id)(base_id)(granularity)(timestamp) )
FC_REFLECT( bts::blockchain::order_record, (balance) )
FC_REFLECT( bts::blockchain::collateral_record, (collateral_balance)(payoff_balance) )
FC_REFLECT( bts::blockchain::market_order, (type)(market_index)(state)(collateral) )
FC_REFLECT_TYPENAME( std::vector<bts::blockchain::market_transaction> )
FC_REFLECT_TYPENAME( bts::blockchain::market_history_key::time_granularity_enum ) // http://en.wikipedia.org/wiki/Voodoo_programminqg
FC_REFLECT( bts::blockchain::market_transaction,
(bid_owner)
(ask_owner)
(bid_price)
(ask_price)
(bid_paid)
(bid_received)
(ask_paid)
(ask_received)
(fees_collected)
)
<commit_msg>Fix market_history_key::operator<<commit_after>#pragma once
#include <bts/blockchain/asset.hpp>
#include <bts/blockchain/types.hpp>
#include <fc/time.hpp>
#include <tuple>
namespace bts { namespace blockchain {
struct market_index_key
{
market_index_key( const price& price_arg = price(),
const address& owner_arg = address() )
:order_price(price_arg),owner(owner_arg){}
price order_price;
address owner;
friend bool operator == ( const market_index_key& a, const market_index_key& b )
{
return a.order_price == b.order_price && a.owner == b.owner;
}
friend bool operator < ( const market_index_key& a, const market_index_key& b )
{
return std::tie(a.order_price, a.owner) < std::tie(b.order_price, b.owner);
}
};
struct market_history_key
{
enum time_granularity_enum {
each_block,
each_hour,
each_day
};
market_history_key( asset_id_type quote_id = 0,
asset_id_type base_id = 1,
time_granularity_enum granularity = each_block,
fc::time_point_sec timestamp = fc::time_point_sec())
: quote_id(quote_id),
base_id(base_id),
granularity(granularity),
timestamp(timestamp)
{}
asset_id_type quote_id;
asset_id_type base_id;
time_granularity_enum granularity;
fc::time_point_sec timestamp;
bool operator < ( const market_history_key& other ) const
{
return std::tie(base_id, quote_id, granularity, timestamp) < std::tie(other.base_id, other.quote_id, other.granularity, other.timestamp);
}
bool operator == ( const market_history_key& other ) const
{
return quote_id == other.quote_id
&& base_id == other.base_id
&& granularity == other.granularity
&& timestamp == other.timestamp;
}
};
struct market_history_record
{
market_history_record(price highest_bid = price(),
price lowest_ask = price(),
share_type volume = 0)
: highest_bid(highest_bid),
lowest_ask(lowest_ask),
volume(volume)
{}
price highest_bid;
price lowest_ask;
share_type volume;
bool operator == ( const market_history_record& other ) const
{
return highest_bid == other.highest_bid
&& lowest_ask == other.lowest_ask
&& volume == other.volume;
}
};
typedef fc::optional<market_history_record> omarket_history_record;
typedef std::vector<std::pair<time_point_sec, market_history_record>> market_history_points;
struct order_record
{
order_record():balance(0){}
order_record( share_type b )
:balance(b){}
bool is_null() const { return 0 == balance; }
share_type balance;
};
typedef fc::optional<order_record> oorder_record;
enum order_type_enum
{
null_order,
bid_order,
ask_order,
short_order,
cover_order
};
struct market_order
{
market_order( order_type_enum t, market_index_key k, order_record s )
:type(t),market_index(k),state(s){}
market_order( order_type_enum t, market_index_key k, order_record s, share_type c )
:type(t),market_index(k),state(s),collateral(c){}
market_order():type(null_order){}
string get_id()const;
asset get_balance()const; // funds available for this order
price get_price()const;
price get_highest_cover_price()const; // the price that consumes all collateral
asset get_quantity()const;
asset get_quote_quantity()const;
address get_owner()const { return market_index.owner; }
order_type_enum type;
market_index_key market_index;
order_record state;
optional<share_type> collateral;
};
struct market_transaction
{
market_transaction(){}
address bid_owner;
address ask_owner;
price bid_price;
price ask_price;
asset bid_paid;
asset bid_received;
asset ask_paid;
asset ask_received;
asset fees_collected;
};
typedef optional<market_order> omarket_order;
struct collateral_record
{
collateral_record(share_type c = 0, share_type p = 0):collateral_balance(c),payoff_balance(p){}
bool is_null() const { return 0 == payoff_balance && 0 == collateral_balance; }
share_type collateral_balance;
share_type payoff_balance;
};
typedef fc::optional<collateral_record> ocollateral_record;
} } // bts::blockchain
FC_REFLECT_ENUM( bts::blockchain::order_type_enum, (null_order)(bid_order)(ask_order)(short_order)(cover_order) )
FC_REFLECT_ENUM( bts::blockchain::market_history_key::time_granularity_enum, (each_block)(each_hour)(each_day) )
FC_REFLECT( bts::blockchain::market_index_key, (order_price)(owner) )
FC_REFLECT( bts::blockchain::market_history_record, (highest_bid)(lowest_ask)(volume) )
FC_REFLECT( bts::blockchain::market_history_key, (quote_id)(base_id)(granularity)(timestamp) )
FC_REFLECT( bts::blockchain::order_record, (balance) )
FC_REFLECT( bts::blockchain::collateral_record, (collateral_balance)(payoff_balance) )
FC_REFLECT( bts::blockchain::market_order, (type)(market_index)(state)(collateral) )
FC_REFLECT_TYPENAME( std::vector<bts::blockchain::market_transaction> )
FC_REFLECT_TYPENAME( bts::blockchain::market_history_key::time_granularity_enum ) // http://en.wikipedia.org/wiki/Voodoo_programminqg
FC_REFLECT( bts::blockchain::market_transaction,
(bid_owner)
(ask_owner)
(bid_price)
(ask_price)
(bid_paid)
(bid_received)
(ask_paid)
(ask_received)
(fees_collected)
)
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: SlsBitmapCompressor.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-10-24 07:39:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER 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 SD_SLIDESORTER_BITMAP_COMPRESSOR_HXX
#define SD_SLIDESORTER_BITMAP_COMPRESSOR_HXX
#include <sal/types.h>
#include <tools/gen.hxx>
#include <boost/shared_ptr.hpp>
class BitmapEx;
namespace sd { namespace slidesorter { namespace cache {
class BitmapReplacement;
/** This interface class provides the minimal method set for classes that
implement the compression and decompression of preview bitmaps.
*/
class BitmapCompressor
{
public:
/** Compress the given bitmap into a replacement format that is specific
to the compressor class.
*/
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const = 0;
/** Decompress the given replacement data into a preview bitmap.
Depending on the compression technique the returned bitmap may
differ from the original bitmap given to the Compress() method. It
may even of the wrong size or empty or the NULL pointer. It is the
task of the caller to create a new preview bitmap if the returned
one is not as desired.
*/
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData)const=0;
/** Return whether the compression and decompression is lossless. This
value is used by the caller of Decompress() to decide whether to use
the returned bitmap as is or if a new preview has to be created.
*/
virtual bool IsLossless (void) const = 0;
};
/** Interface for preview bitmap replacements. Each bitmap
compressor/decompressor has to provide an implementation that is
suitable to store the compressed bitmaps.
*/
class BitmapReplacement
{
public:
virtual sal_Int32 GetMemorySize (void) const { return 0; }
};
/** This is one trivial bitmap compressor. It stores bitmaps unmodified
instead of compressing them.
This compressor is lossless.
*/
class NoBitmapCompression
: public BitmapCompressor
{
class DummyReplacement;
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
/** This is another trivial bitmap compressor. Instead of compressing a
bitmap, it throws the bitmap away. Its Decompress() method returns a
NULL pointer. The caller has to create a new preview bitmap instead.
This compressor clearly is not lossless.
*/
class CompressionByDeletion
: public BitmapCompressor
{
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
/** Compress a preview bitmap by reducing its resolution. While the aspect
ratio is maintained the horizontal resolution is scaled down to 100
pixels.
This compressor is not lossless.
*/
class ResolutionReduction
: public BitmapCompressor
{
class ResolutionReducedReplacement;
static const sal_Int32 mnWidth = 100;
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
/** Scale the replacement bitmap up to the original size.
*/
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
/** Compress preview bitmaps using the PNG format.
This compressor is lossless.
*/
class PngCompression
: public BitmapCompressor
{
class PngReplacement;
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
} } } // end of namespace ::sd::slidesorter::cache
#endif
<commit_msg>INTEGRATION: CWS pj42 (1.2.20); FILE MERGED 2005/11/10 21:59:07 pjanik 1.2.20.1: #i57567#: Remove SISSL license.<commit_after>/*************************************************************************
*
* $RCSfile: SlsBitmapCompressor.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-11-11 10:47:44 $
*
* 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 SD_SLIDESORTER_BITMAP_COMPRESSOR_HXX
#define SD_SLIDESORTER_BITMAP_COMPRESSOR_HXX
#include <sal/types.h>
#include <tools/gen.hxx>
#include <boost/shared_ptr.hpp>
class BitmapEx;
namespace sd { namespace slidesorter { namespace cache {
class BitmapReplacement;
/** This interface class provides the minimal method set for classes that
implement the compression and decompression of preview bitmaps.
*/
class BitmapCompressor
{
public:
/** Compress the given bitmap into a replacement format that is specific
to the compressor class.
*/
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const = 0;
/** Decompress the given replacement data into a preview bitmap.
Depending on the compression technique the returned bitmap may
differ from the original bitmap given to the Compress() method. It
may even of the wrong size or empty or the NULL pointer. It is the
task of the caller to create a new preview bitmap if the returned
one is not as desired.
*/
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData)const=0;
/** Return whether the compression and decompression is lossless. This
value is used by the caller of Decompress() to decide whether to use
the returned bitmap as is or if a new preview has to be created.
*/
virtual bool IsLossless (void) const = 0;
};
/** Interface for preview bitmap replacements. Each bitmap
compressor/decompressor has to provide an implementation that is
suitable to store the compressed bitmaps.
*/
class BitmapReplacement
{
public:
virtual sal_Int32 GetMemorySize (void) const { return 0; }
};
/** This is one trivial bitmap compressor. It stores bitmaps unmodified
instead of compressing them.
This compressor is lossless.
*/
class NoBitmapCompression
: public BitmapCompressor
{
class DummyReplacement;
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
/** This is another trivial bitmap compressor. Instead of compressing a
bitmap, it throws the bitmap away. Its Decompress() method returns a
NULL pointer. The caller has to create a new preview bitmap instead.
This compressor clearly is not lossless.
*/
class CompressionByDeletion
: public BitmapCompressor
{
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
/** Compress a preview bitmap by reducing its resolution. While the aspect
ratio is maintained the horizontal resolution is scaled down to 100
pixels.
This compressor is not lossless.
*/
class ResolutionReduction
: public BitmapCompressor
{
class ResolutionReducedReplacement;
static const sal_Int32 mnWidth = 100;
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
/** Scale the replacement bitmap up to the original size.
*/
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
/** Compress preview bitmaps using the PNG format.
This compressor is lossless.
*/
class PngCompression
: public BitmapCompressor
{
class PngReplacement;
public:
virtual ::boost::shared_ptr<BitmapReplacement> Compress (
const ::boost::shared_ptr<BitmapEx>& rpBitmap) const;
virtual ::boost::shared_ptr<BitmapEx> Decompress (const BitmapReplacement& rBitmapData) const;
virtual bool IsLossless (void) const;
};
} } } // end of namespace ::sd::slidesorter::cache
#endif
<|endoftext|>
|
<commit_before>// $Id$
//
// Copyright (C) 2008 Greg Landrum
// All Rights Reserved
//
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <RDGeneral/RDLog.h>
#include <vector>
#include <algorithm>
using namespace RDKit;
void BuildSimpleMolecule(){
// build the molecule: C/C=C\C
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addBond(0,1,Bond::SINGLE); // bond 0
mol->addBond(1,2,Bond::DOUBLE); // bond 1
mol->addBond(2,3,Bond::SINGLE); // bond 2
// setup the stereochem:
mol->getBondWithIdx(0)->setBondDir(Bond::ENDUPRIGHT);
mol->getBondWithIdx(2)->setBondDir(Bond::ENDDOWNRIGHT);
// do the chemistry perception:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" sample 1 SMILES: " <<smiles<<std::endl;
}
void WorkWithRingInfo(){
// use a more complicated molecule to demonstrate querying about
// ring information
ROMol *mol=SmilesToMol("OC1CCC2C1CCCC2");
// the molecule from SmilesToMol is already sanitized, so we don't
// need to worry about that.
// work with ring information
RingInfo *ringInfo = mol->getRingInfo();
TEST_ASSERT(ringInfo->numRings()==2);
// can ask how many rings an atom is in:
TEST_ASSERT(ringInfo->numAtomRings(0)==0);
TEST_ASSERT(ringInfo->numAtomRings(1)==1);
TEST_ASSERT(ringInfo->numAtomRings(4)==2);
// same with bonds:
TEST_ASSERT(ringInfo->numBondRings(0)==0);
TEST_ASSERT(ringInfo->numBondRings(1)==1);
// can check if an atom is in a ring of a particular size:
TEST_ASSERT(!ringInfo->isAtomInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(1,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,6));
// same with bonds:
TEST_ASSERT(!ringInfo->isBondInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isBondInRingOfSize(1,5));
// can also get the full list of rings as atom indices:
VECT_INT_VECT atomRings; // VECT_INT_VECT is vector< vector<int> >
atomRings=ringInfo->atomRings();
TEST_ASSERT(atomRings.size()==2);
TEST_ASSERT(atomRings[0].size()==5);
TEST_ASSERT(atomRings[1].size()==6);
// this sort is just here for test/demo purposes:
std::sort(atomRings[0].begin(),atomRings[0].end());
TEST_ASSERT(atomRings[0][0]==1);
TEST_ASSERT(atomRings[0][1]==2);
TEST_ASSERT(atomRings[0][2]==3);
TEST_ASSERT(atomRings[0][3]==4);
TEST_ASSERT(atomRings[0][4]==5);
// same with bonds:
VECT_INT_VECT bondRings; // VECT_INT_VECT is vector< vector<int> >
bondRings=ringInfo->bondRings();
TEST_ASSERT(bondRings.size()==2);
TEST_ASSERT(bondRings[0].size()==5);
TEST_ASSERT(bondRings[1].size()==6);
// the same trick played above with the contents of each ring
// can be played, but we won't
// count the number of rings of size 5:
unsigned int nRingsSize5=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()==5) nRingsSize5++;
}
TEST_ASSERT(nRingsSize5==1);
delete mol;
// count the number of atoms in 5-rings where all the atoms
// are aromatic:
mol=SmilesToMol("C1CC2=C(C1)C1=C(NC3=C1C=CC=C3)C=C2");
ringInfo = mol->getRingInfo();
atomRings=ringInfo->atomRings();
unsigned int nMatchingAtoms=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()!=5){
continue;
}
bool isAromatic=true;
for(INT_VECT_CI atomIt=ringIt->begin();
atomIt!=ringIt->end();++atomIt){
if(!mol->getAtomWithIdx(*atomIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic){
nMatchingAtoms+=5;
}
}
TEST_ASSERT(nMatchingAtoms==5);
delete mol;
// count the number of rings where all the bonds
// are aromatic.
mol=SmilesToMol("c1cccc2c1CCCC2");
ringInfo = mol->getRingInfo();
bondRings=ringInfo->bondRings();
unsigned int nAromaticRings=0;
for(VECT_INT_VECT_CI ringIt=bondRings.begin();
ringIt!=bondRings.end();++ringIt){
bool isAromatic=true;
for(INT_VECT_CI bondIt=ringIt->begin();
bondIt!=ringIt->end();++bondIt){
if(!mol->getBondWithIdx(*bondIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic) nAromaticRings++;
}
TEST_ASSERT(nAromaticRings==1);
delete mol;
}
void WorkWithSmarts(){
// demonstrate the use of substructure searching
ROMol *mol=SmilesToMol("ClCC=CCC");
// a simple SMARTS pattern for rotatable bonds:
ROMol *pattern=SmartsToMol("[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]");
std::vector<MatchVectType> matches;
unsigned int nMatches;
nMatches=SubstructMatch(*mol,*pattern,matches);
TEST_ASSERT(nMatches==2);
TEST_ASSERT(matches.size()==2); // <- there are two rotatable bonds
// a MatchVect is a vector of std::pairs with (patternIdx, molIdx):
TEST_ASSERT(matches[0].size()==2);
TEST_ASSERT(matches[0][0].first==0);
TEST_ASSERT(matches[0][0].second==1);
TEST_ASSERT(matches[0][1].first==1);
TEST_ASSERT(matches[0][1].second==2);
delete pattern;
delete mol;
}
void DepictDemo(){
// demonstrate the use of the depiction-generation code2D coordinates:
ROMol *mol=SmilesToMol("ClCC=CCC");
// generate the 2D coordinates:
RDDepict::compute2DCoords(*mol);
// generate a mol block (could also go to a file):
std::string molBlock=MolToMolBlock(*mol);
BOOST_LOG(rdInfoLog)<<molBlock;
delete mol;
}
void CleanupMolecule(){
// build: C1CC1C(:O):O
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addAtom(new Atom(8)); // atom 4
mol->addAtom(new Atom(8)); // atom 5
mol->addBond(3,4,Bond::AROMATIC); // bond 0
mol->addBond(3,5,Bond::AROMATIC); // bond 1
mol->addBond(3,2,Bond::SINGLE); // bond 2
mol->addBond(2,1,Bond::SINGLE); // bond 3
mol->addBond(1,0,Bond::SINGLE); // bond 4
mol->addBond(0,2,Bond::SINGLE); // bond 5
// instead of calling sanitize mol, which would generate an error,
// we'll perceive the rings, then take care of aromatic bonds
// that aren't in a ring, then sanitize:
MolOps::findSSSR(*mol);
for(ROMol::BondIterator bondIt=mol->beginBonds();
bondIt!=mol->endBonds();++bondIt){
if( ((*bondIt)->getIsAromatic() ||
(*bondIt)->getBondType()==Bond::AROMATIC)
&& !mol->getRingInfo()->numBondRings((*bondIt)->getIdx()) ){
(*bondIt)->setIsAromatic(false);
// NOTE: this isn't really reasonable:
(*bondIt)->setBondType(Bond::SINGLE);
}
}
// now it's safe to sanitize:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" fixed SMILES: " <<smiles<<std::endl;
}
int
main(int argc, char *argv[])
{
RDLog::InitLogs();
CleanupMolecule();
BuildSimpleMolecule();
WorkWithRingInfo();
WorkWithSmarts();
DepictDemo();
}
<commit_msg>update this<commit_after>// $Id$
//
// Copyright (C) 2008-2010 Greg Landrum
// All Rights Reserved
//
// Can be built with:
// g++ -o sample.exe sample.cpp -I$RDBASE/Code -I$RDBASE/Extern \
// -L$RDBASE/lib -L$RDBASE/bin -lFileParsers -lSmilesParse -lDepictor \
// -lSubstructMatch -lGraphMol -lDataStructs -lRDGeometryLib -lRDGeneral
//
#include <RDGeneral/Invariant.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <GraphMol/SmilesParse/SmilesWrite.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/Depictor/RDDepictor.h>
#include <GraphMol/FileParsers/FileParsers.h>
#include <RDGeneral/RDLog.h>
#include <vector>
#include <algorithm>
using namespace RDKit;
void BuildSimpleMolecule(){
// build the molecule: C/C=C\C
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addBond(0,1,Bond::SINGLE); // bond 0
mol->addBond(1,2,Bond::DOUBLE); // bond 1
mol->addBond(2,3,Bond::SINGLE); // bond 2
// setup the stereochem:
mol->getBondWithIdx(0)->setBondDir(Bond::ENDUPRIGHT);
mol->getBondWithIdx(2)->setBondDir(Bond::ENDDOWNRIGHT);
// do the chemistry perception:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" sample 1 SMILES: " <<smiles<<std::endl;
}
void WorkWithRingInfo(){
// use a more complicated molecule to demonstrate querying about
// ring information
ROMol *mol=SmilesToMol("OC1CCC2C1CCCC2");
// the molecule from SmilesToMol is already sanitized, so we don't
// need to worry about that.
// work with ring information
RingInfo *ringInfo = mol->getRingInfo();
TEST_ASSERT(ringInfo->numRings()==2);
// can ask how many rings an atom is in:
TEST_ASSERT(ringInfo->numAtomRings(0)==0);
TEST_ASSERT(ringInfo->numAtomRings(1)==1);
TEST_ASSERT(ringInfo->numAtomRings(4)==2);
// same with bonds:
TEST_ASSERT(ringInfo->numBondRings(0)==0);
TEST_ASSERT(ringInfo->numBondRings(1)==1);
// can check if an atom is in a ring of a particular size:
TEST_ASSERT(!ringInfo->isAtomInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(1,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,5));
TEST_ASSERT(ringInfo->isAtomInRingOfSize(4,6));
// same with bonds:
TEST_ASSERT(!ringInfo->isBondInRingOfSize(0,5));
TEST_ASSERT(ringInfo->isBondInRingOfSize(1,5));
// can also get the full list of rings as atom indices:
VECT_INT_VECT atomRings; // VECT_INT_VECT is vector< vector<int> >
atomRings=ringInfo->atomRings();
TEST_ASSERT(atomRings.size()==2);
TEST_ASSERT(atomRings[0].size()==5);
TEST_ASSERT(atomRings[1].size()==6);
// this sort is just here for test/demo purposes:
std::sort(atomRings[0].begin(),atomRings[0].end());
TEST_ASSERT(atomRings[0][0]==1);
TEST_ASSERT(atomRings[0][1]==2);
TEST_ASSERT(atomRings[0][2]==3);
TEST_ASSERT(atomRings[0][3]==4);
TEST_ASSERT(atomRings[0][4]==5);
// same with bonds:
VECT_INT_VECT bondRings; // VECT_INT_VECT is vector< vector<int> >
bondRings=ringInfo->bondRings();
TEST_ASSERT(bondRings.size()==2);
TEST_ASSERT(bondRings[0].size()==5);
TEST_ASSERT(bondRings[1].size()==6);
// the same trick played above with the contents of each ring
// can be played, but we won't
// count the number of rings of size 5:
unsigned int nRingsSize5=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()==5) nRingsSize5++;
}
TEST_ASSERT(nRingsSize5==1);
delete mol;
// count the number of atoms in 5-rings where all the atoms
// are aromatic:
mol=SmilesToMol("C1CC2=C(C1)C1=C(NC3=C1C=CC=C3)C=C2");
ringInfo = mol->getRingInfo();
atomRings=ringInfo->atomRings();
unsigned int nMatchingAtoms=0;
for(VECT_INT_VECT_CI ringIt=atomRings.begin();
ringIt!=atomRings.end();++ringIt){
if(ringIt->size()!=5){
continue;
}
bool isAromatic=true;
for(INT_VECT_CI atomIt=ringIt->begin();
atomIt!=ringIt->end();++atomIt){
if(!mol->getAtomWithIdx(*atomIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic){
nMatchingAtoms+=5;
}
}
TEST_ASSERT(nMatchingAtoms==5);
delete mol;
// count the number of rings where all the bonds
// are aromatic.
mol=SmilesToMol("c1cccc2c1CCCC2");
ringInfo = mol->getRingInfo();
bondRings=ringInfo->bondRings();
unsigned int nAromaticRings=0;
for(VECT_INT_VECT_CI ringIt=bondRings.begin();
ringIt!=bondRings.end();++ringIt){
bool isAromatic=true;
for(INT_VECT_CI bondIt=ringIt->begin();
bondIt!=ringIt->end();++bondIt){
if(!mol->getBondWithIdx(*bondIt)->getIsAromatic()){
isAromatic=false;
break;
}
}
if(isAromatic) nAromaticRings++;
}
TEST_ASSERT(nAromaticRings==1);
delete mol;
}
void WorkWithSmarts(){
// demonstrate the use of substructure searching
ROMol *mol=SmilesToMol("ClCC=CCC");
// a simple SMARTS pattern for rotatable bonds:
ROMol *pattern=SmartsToMol("[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]");
std::vector<MatchVectType> matches;
unsigned int nMatches;
nMatches=SubstructMatch(*mol,*pattern,matches);
TEST_ASSERT(nMatches==2);
TEST_ASSERT(matches.size()==2); // <- there are two rotatable bonds
// a MatchVect is a vector of std::pairs with (patternIdx, molIdx):
TEST_ASSERT(matches[0].size()==2);
TEST_ASSERT(matches[0][0].first==0);
TEST_ASSERT(matches[0][0].second==1);
TEST_ASSERT(matches[0][1].first==1);
TEST_ASSERT(matches[0][1].second==2);
delete pattern;
delete mol;
}
void DepictDemo(){
// demonstrate the use of the depiction-generation code2D coordinates:
ROMol *mol=SmilesToMol("ClCC=CCC");
// generate the 2D coordinates:
RDDepict::compute2DCoords(*mol);
// generate a mol block (could also go to a file):
std::string molBlock=MolToMolBlock(*mol);
BOOST_LOG(rdInfoLog)<<molBlock;
delete mol;
}
void CleanupMolecule(){
// an example of doing some cleaning up of a molecule before
// calling the sanitizeMol function()
// build: C1CC1C(:O):O
RWMol *mol=new RWMol();
// add atoms and bonds:
mol->addAtom(new Atom(6)); // atom 0
mol->addAtom(new Atom(6)); // atom 1
mol->addAtom(new Atom(6)); // atom 2
mol->addAtom(new Atom(6)); // atom 3
mol->addAtom(new Atom(8)); // atom 4
mol->addAtom(new Atom(8)); // atom 5
mol->addBond(3,4,Bond::AROMATIC); // bond 0
mol->addBond(3,5,Bond::AROMATIC); // bond 1
mol->addBond(3,2,Bond::SINGLE); // bond 2
mol->addBond(2,1,Bond::SINGLE); // bond 3
mol->addBond(1,0,Bond::SINGLE); // bond 4
mol->addBond(0,2,Bond::SINGLE); // bond 5
// instead of calling sanitize mol, which would generate an error,
// we'll perceive the rings, then take care of aromatic bonds
// that aren't in a ring, then sanitize:
MolOps::findSSSR(*mol);
for(ROMol::BondIterator bondIt=mol->beginBonds();
bondIt!=mol->endBonds();++bondIt){
if( ((*bondIt)->getIsAromatic() ||
(*bondIt)->getBondType()==Bond::AROMATIC)
&& !mol->getRingInfo()->numBondRings((*bondIt)->getIdx()) ){
// remove the aromatic flag on the bond:
(*bondIt)->setIsAromatic(false);
// and cleanup its attached atoms as well (they were
// also marked aromatic when the bond was added)
(*bondIt)->getBeginAtom()->setIsAromatic(false);
(*bondIt)->getEndAtom()->setIsAromatic(false);
// NOTE: this isn't really reasonable:
(*bondIt)->setBondType(Bond::SINGLE);
}
}
// now it's safe to sanitize:
RDKit::MolOps::sanitizeMol(*mol);
// Get the canonical SMILES, include stereochemistry:
std::string smiles;
smiles = MolToSmiles(*(static_cast<ROMol *>(mol)),true);
BOOST_LOG(rdInfoLog)<<" fixed SMILES: " <<smiles<<std::endl;
}
int
main(int argc, char *argv[])
{
RDLog::InitLogs();
BuildSimpleMolecule();
WorkWithRingInfo();
WorkWithSmarts();
DepictDemo();
CleanupMolecule();
}
<|endoftext|>
|
<commit_before>#include "common.h"
#include <Audiopolicy.h>
#include <Mmdeviceapi.h>
#include <Appmodel.h>
#include <ShlObj.h>
#include <propkey.h>
#include <PathCch.h>
#include "AudioSessionService.h"
#include "ShellProperties.h"
#include "MrtResourceManager.h"
using namespace std;
using namespace std::tr1;
using namespace EarTrumpet::Interop;
AudioSessionService* AudioSessionService::__instance = nullptr;
struct PackageInfoReferenceDeleter
{
void operator()(PACKAGE_INFO_REFERENCE* reference)
{
ClosePackageInfo(*reference);
}
};
typedef unique_ptr<PACKAGE_INFO_REFERENCE, PackageInfoReferenceDeleter> PackageInfoReference;
void AudioSessionService::CleanUpAudioSessions()
{
for (auto session = _sessions.begin(); session != _sessions.end(); session++)
{
CoTaskMemFree(session->DisplayName);
CoTaskMemFree(session->IconPath);
}
_sessions.clear();
_sessionMap.clear();
}
int AudioSessionService::GetAudioSessionCount()
{
return _sessions.size();
}
HRESULT AudioSessionService::RefreshAudioSessions()
{
CleanUpAudioSessions();
CComPtr<IMMDeviceEnumerator> deviceEnumerator;
FAST_FAIL(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&deviceEnumerator)));
CComPtr<IMMDevice> device;
FAST_FAIL(deviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &device));
CComPtr<IAudioSessionManager2> audioSessionManager;
FAST_FAIL(device->Activate(__uuidof(IAudioSessionManager2), CLSCTX_INPROC, nullptr, (void**)&audioSessionManager));
CComPtr<IAudioSessionEnumerator> audioSessionEnumerator;
FAST_FAIL(audioSessionManager->GetSessionEnumerator(&audioSessionEnumerator));
int sessionCount;
FAST_FAIL(audioSessionEnumerator->GetCount(&sessionCount));
for (int i = 0; i < sessionCount; i++)
{
EarTrumpetAudioSession audioSession;
if (SUCCEEDED(CreateEtAudioSessionFromAudioSession(audioSessionEnumerator, i, &audioSession)))
{
_sessions.push_back(audioSession);
}
}
return S_OK;
}
HRESULT AudioSessionService::CreateEtAudioSessionFromAudioSession(CComPtr<IAudioSessionEnumerator> audioSessionEnumerator, int sessionCount, EarTrumpetAudioSession* etAudioSession)
{
CComPtr<IAudioSessionControl> audioSessionControl;
FAST_FAIL(audioSessionEnumerator->GetSession(sessionCount, &audioSessionControl));
CComPtr<IAudioSessionControl2> audioSessionControl2;
FAST_FAIL(audioSessionControl->QueryInterface(IID_PPV_ARGS(&audioSessionControl2)));
DWORD pid;
FAST_FAIL(audioSessionControl2->GetProcessId(&pid));
etAudioSession->ProcessId = pid;
FAST_FAIL(audioSessionControl2->GetGroupingParam(&etAudioSession->GroupingId));
CComHeapPtr<wchar_t> sessionIdString;
FAST_FAIL(audioSessionControl2->GetSessionInstanceIdentifier(&sessionIdString));
hash<wstring> stringHash;
etAudioSession->SessionId = stringHash(static_cast<PWSTR>(sessionIdString));
_sessionMap[etAudioSession->SessionId] = audioSessionControl2;
CComPtr<ISimpleAudioVolume> simpleAudioVolume;
FAST_FAIL(audioSessionControl->QueryInterface(IID_PPV_ARGS(&simpleAudioVolume)));
FAST_FAIL(simpleAudioVolume->GetMasterVolume(&etAudioSession->Volume));
BOOL isMuted;
FAST_FAIL(simpleAudioVolume->GetMute(&isMuted));
etAudioSession->IsMuted = !!isMuted;
HRESULT hr = IsImmersiveProcess(pid);
if (hr == S_OK)
{
PWSTR appUserModelId;
FAST_FAIL(GetAppUserModelIdFromPid(pid, &appUserModelId));
FAST_FAIL(GetAppProperties(appUserModelId, &etAudioSession->DisplayName, &etAudioSession->IconPath, &etAudioSession->BackgroundColor));
etAudioSession->IsDesktopApp = false;
}
else if (hr == S_FALSE)
{
bool isSystemSoundsSession = (S_OK == audioSessionControl2->IsSystemSoundsSession());
AudioSessionState state;
FAST_FAIL(audioSessionControl2->GetState(&state));
if (!isSystemSoundsSession && (state == AudioSessionState::AudioSessionStateExpired))
{
return E_NOT_VALID_STATE;
}
if (isSystemSoundsSession)
{
PCWSTR pszDllPath;
BOOL isWow64Process;
if (!IsWow64Process(GetCurrentProcess(), &isWow64Process) || isWow64Process)
{
pszDllPath = L"%windir%\\sysnative\\audiosrv.dll";
}
else
{
pszDllPath = L"%windir%\\system32\\audiosrv.dll";
}
wchar_t szPath[MAX_PATH] = {};
if (0 == ExpandEnvironmentStrings(pszDllPath, szPath, ARRAYSIZE(szPath)))
{
return E_FAIL;
}
FAST_FAIL(SHStrDup(pszDllPath, &etAudioSession->IconPath));
FAST_FAIL(SHStrDup(L"System Sounds", &etAudioSession->DisplayName));
}
else
{
shared_ptr<void> processHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid), CloseHandle);
FAST_FAIL_HANDLE(processHandle.get());
wchar_t imagePath[MAX_PATH] = {};
DWORD dwCch = ARRAYSIZE(imagePath);
FAST_FAIL(QueryFullProcessImageName(processHandle.get(), 0, imagePath, &dwCch) == 0 ? E_FAIL : S_OK);
FAST_FAIL(SHStrDup(imagePath, &etAudioSession->IconPath));
FAST_FAIL(SHStrDup(PathFindFileName(imagePath), &etAudioSession->DisplayName));
}
etAudioSession->IsDesktopApp = true;
etAudioSession->BackgroundColor = 0x00000000;
}
return S_OK;
}
HRESULT AudioSessionService::GetAudioSessions(void** audioSessions)
{
if (_sessions.size() == 0)
{
return HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS);
}
*audioSessions = &_sessions[0];
return S_OK;
}
HRESULT AudioSessionService::IsImmersiveProcess(DWORD pid)
{
shared_ptr<void> processHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid), CloseHandle);
FAST_FAIL_HANDLE(processHandle.get());
return (::IsImmersiveProcess(processHandle.get()) ? S_OK : S_FALSE);
}
HRESULT AudioSessionService::CanResolveAppByApplicationUserModelId(LPCWSTR applicationUserModelId)
{
CComPtr<IShellItem2> item;
return SUCCEEDED(SHCreateItemInKnownFolder(FOLDERID_AppsFolder, KF_FLAG_DONT_VERIFY, applicationUserModelId, IID_PPV_ARGS(&item)));
}
HRESULT AudioSessionService::GetAppUserModelIdFromPid(DWORD pid, LPWSTR* applicationUserModelId)
{
shared_ptr<void> processHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid), CloseHandle);
FAST_FAIL_HANDLE(processHandle.get());
unsigned int appUserModelIdLength = 0;
long returnCode = GetApplicationUserModelId(processHandle.get(), &appUserModelIdLength, nullptr);
if (returnCode != ERROR_INSUFFICIENT_BUFFER)
{
return HRESULT_FROM_WIN32(returnCode);
}
unique_ptr<wchar_t[]> appUserModelId(new wchar_t[appUserModelIdLength]);
returnCode = GetApplicationUserModelId(processHandle.get(), &appUserModelIdLength, appUserModelId.get());
if (returnCode != ERROR_SUCCESS)
{
return HRESULT_FROM_WIN32(returnCode);
}
if (CanResolveAppByApplicationUserModelId(appUserModelId.get()))
{
FAST_FAIL(SHStrDup(appUserModelId.get(), applicationUserModelId));
}
else
{
wchar_t packageFamilyName[PACKAGE_FAMILY_NAME_MAX_LENGTH];
UINT32 packageFamilyNameLength = ARRAYSIZE(packageFamilyName);
wchar_t packageRelativeAppId[PACKAGE_RELATIVE_APPLICATION_ID_MAX_LENGTH];
UINT32 packageRelativeAppIdLength = ARRAYSIZE(packageRelativeAppId);
FAST_FAIL_WIN32(ParseApplicationUserModelId(appUserModelId.get(), &packageFamilyNameLength, packageFamilyName, &packageRelativeAppIdLength, packageRelativeAppId));
UINT32 packageCount = 0;
UINT32 packageNamesBufferLength = 0;
FAST_FAIL_BUFFER(FindPackagesByPackageFamily(packageFamilyName, PACKAGE_FILTER_HEAD | PACKAGE_INFORMATION_BASIC, &packageCount, nullptr, &packageNamesBufferLength, nullptr, nullptr));
if (packageCount <= 0)
{
return E_NOTFOUND;
}
unique_ptr<PWSTR[]> packageNames(new PWSTR[packageCount]);
unique_ptr<wchar_t[]> buffer(new wchar_t[packageNamesBufferLength]);
FAST_FAIL_WIN32(FindPackagesByPackageFamily(packageFamilyName, PACKAGE_FILTER_HEAD | PACKAGE_INFORMATION_BASIC, &packageCount, packageNames.get(), &packageNamesBufferLength, buffer.get(), nullptr));
PackageInfoReference packageInfoRef;
PACKAGE_INFO_REFERENCE rawPackageInfoRef;
FAST_FAIL_WIN32(OpenPackageInfoByFullName(packageNames[0], 0, &rawPackageInfoRef));
packageInfoRef.reset(&rawPackageInfoRef);
UINT32 packageIdsLength = 0;
UINT32 packageIdCount = 0;
FAST_FAIL_BUFFER(GetPackageApplicationIds(*packageInfoRef.get(), &packageIdsLength, nullptr, &packageIdCount));
if (packageIdCount <= 0)
{
return E_NOTFOUND;
}
unique_ptr<BYTE[]> packageIdsRaw(new BYTE[packageIdsLength]);
FAST_FAIL_WIN32(GetPackageApplicationIds(*packageInfoRef.get(), &packageIdsLength, packageIdsRaw.get(), &packageIdCount));
PCWSTR* packageIds = reinterpret_cast<PCWSTR*>(packageIdsRaw.get());
FAST_FAIL(SHStrDup(packageIds[0], applicationUserModelId));
}
return S_OK;
}
HRESULT AudioSessionService::SetAudioSessionVolume(unsigned long sessionId, float volume)
{
if (!_sessionMap[sessionId])
{
return E_INVALIDARG;
}
CComPtr<ISimpleAudioVolume> simpleAudioVolume;
FAST_FAIL(_sessionMap[sessionId]->QueryInterface(IID_PPV_ARGS(&simpleAudioVolume)));
FAST_FAIL(simpleAudioVolume->SetMasterVolume(volume, nullptr));
return S_OK;
}
HRESULT AudioSessionService::SetAudioSessionMute(unsigned long sessionId, bool isMuted)
{
if (!_sessionMap[sessionId])
{
return E_INVALIDARG;
}
CComPtr<ISimpleAudioVolume> simpleAudioVolume;
FAST_FAIL(_sessionMap[sessionId]->QueryInterface(IID_PPV_ARGS(&simpleAudioVolume)));
FAST_FAIL(simpleAudioVolume->SetMute(isMuted, nullptr));
return S_OK;
}
HRESULT AudioSessionService::GetAppProperties(PCWSTR pszAppId, PWSTR* ppszName, PWSTR* ppszIcon, ULONG *background)
{
*ppszIcon = nullptr;
*ppszName = nullptr;
*background = 0;
CComPtr<IShellItem2> item;
FAST_FAIL(SHCreateItemInKnownFolder(FOLDERID_AppsFolder, KF_FLAG_DONT_VERIFY, pszAppId, IID_PPV_ARGS(&item)));
CComHeapPtr<wchar_t> itemName;
FAST_FAIL(item->GetString(PKEY_ItemNameDisplay, &itemName));
FAST_FAIL(item->GetUInt32(PKEY_AppUserModel_Background, background));
CComHeapPtr<wchar_t> installPath;
FAST_FAIL(item->GetString(PKEY_AppUserModel_PackageInstallPath, &installPath));
CComHeapPtr<wchar_t> iconPath;
FAST_FAIL(item->GetString(PKEY_AppUserModel_Icon, &iconPath));
CComHeapPtr<wchar_t> fullPackagePath;
FAST_FAIL(item->GetString(PKEY_AppUserModel_PackageFullName, &fullPackagePath));
CComPtr<IMrtResourceManager> mrtResMgr;
FAST_FAIL(CoCreateInstance(__uuidof(MrtResourceManager), nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&mrtResMgr)));
FAST_FAIL(mrtResMgr->InitializeForPackage(fullPackagePath));
CComPtr<IResourceMap> resourceMap;
FAST_FAIL(mrtResMgr->GetMainResourceMap(IID_PPV_ARGS(&resourceMap)));
CComHeapPtr<wchar_t> resolvedIconPath;
FAST_FAIL(resourceMap->GetFilePath(iconPath, &resolvedIconPath));
*ppszIcon = resolvedIconPath.Detach();
*ppszName = itemName.Detach();
return S_OK;
}<commit_msg>Handle PKEY_AppUserModel_Icon having URLs in it (fixes #79)<commit_after>#include "common.h"
#include <Audiopolicy.h>
#include <Mmdeviceapi.h>
#include <Appmodel.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <propkey.h>
#include <PathCch.h>
#include "AudioSessionService.h"
#include "ShellProperties.h"
#include "MrtResourceManager.h"
using namespace std;
using namespace std::tr1;
using namespace EarTrumpet::Interop;
AudioSessionService* AudioSessionService::__instance = nullptr;
struct PackageInfoReferenceDeleter
{
void operator()(PACKAGE_INFO_REFERENCE* reference)
{
ClosePackageInfo(*reference);
}
};
typedef unique_ptr<PACKAGE_INFO_REFERENCE, PackageInfoReferenceDeleter> PackageInfoReference;
void AudioSessionService::CleanUpAudioSessions()
{
for (auto session = _sessions.begin(); session != _sessions.end(); session++)
{
CoTaskMemFree(session->DisplayName);
CoTaskMemFree(session->IconPath);
}
_sessions.clear();
_sessionMap.clear();
}
int AudioSessionService::GetAudioSessionCount()
{
return _sessions.size();
}
HRESULT AudioSessionService::RefreshAudioSessions()
{
CleanUpAudioSessions();
CComPtr<IMMDeviceEnumerator> deviceEnumerator;
FAST_FAIL(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&deviceEnumerator)));
CComPtr<IMMDevice> device;
FAST_FAIL(deviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &device));
CComPtr<IAudioSessionManager2> audioSessionManager;
FAST_FAIL(device->Activate(__uuidof(IAudioSessionManager2), CLSCTX_INPROC, nullptr, (void**)&audioSessionManager));
CComPtr<IAudioSessionEnumerator> audioSessionEnumerator;
FAST_FAIL(audioSessionManager->GetSessionEnumerator(&audioSessionEnumerator));
int sessionCount;
FAST_FAIL(audioSessionEnumerator->GetCount(&sessionCount));
for (int i = 0; i < sessionCount; i++)
{
EarTrumpetAudioSession audioSession;
if (SUCCEEDED(CreateEtAudioSessionFromAudioSession(audioSessionEnumerator, i, &audioSession)))
{
_sessions.push_back(audioSession);
}
}
return S_OK;
}
HRESULT AudioSessionService::CreateEtAudioSessionFromAudioSession(CComPtr<IAudioSessionEnumerator> audioSessionEnumerator, int sessionCount, EarTrumpetAudioSession* etAudioSession)
{
CComPtr<IAudioSessionControl> audioSessionControl;
FAST_FAIL(audioSessionEnumerator->GetSession(sessionCount, &audioSessionControl));
CComPtr<IAudioSessionControl2> audioSessionControl2;
FAST_FAIL(audioSessionControl->QueryInterface(IID_PPV_ARGS(&audioSessionControl2)));
DWORD pid;
FAST_FAIL(audioSessionControl2->GetProcessId(&pid));
etAudioSession->ProcessId = pid;
FAST_FAIL(audioSessionControl2->GetGroupingParam(&etAudioSession->GroupingId));
CComHeapPtr<wchar_t> sessionIdString;
FAST_FAIL(audioSessionControl2->GetSessionInstanceIdentifier(&sessionIdString));
hash<wstring> stringHash;
etAudioSession->SessionId = stringHash(static_cast<PWSTR>(sessionIdString));
_sessionMap[etAudioSession->SessionId] = audioSessionControl2;
CComPtr<ISimpleAudioVolume> simpleAudioVolume;
FAST_FAIL(audioSessionControl->QueryInterface(IID_PPV_ARGS(&simpleAudioVolume)));
FAST_FAIL(simpleAudioVolume->GetMasterVolume(&etAudioSession->Volume));
BOOL isMuted;
FAST_FAIL(simpleAudioVolume->GetMute(&isMuted));
etAudioSession->IsMuted = !!isMuted;
HRESULT hr = IsImmersiveProcess(pid);
if (hr == S_OK)
{
PWSTR appUserModelId;
FAST_FAIL(GetAppUserModelIdFromPid(pid, &appUserModelId));
FAST_FAIL(GetAppProperties(appUserModelId, &etAudioSession->DisplayName, &etAudioSession->IconPath, &etAudioSession->BackgroundColor));
etAudioSession->IsDesktopApp = false;
}
else if (hr == S_FALSE)
{
bool isSystemSoundsSession = (S_OK == audioSessionControl2->IsSystemSoundsSession());
AudioSessionState state;
FAST_FAIL(audioSessionControl2->GetState(&state));
if (!isSystemSoundsSession && (state == AudioSessionState::AudioSessionStateExpired))
{
return E_NOT_VALID_STATE;
}
if (isSystemSoundsSession)
{
PCWSTR pszDllPath;
BOOL isWow64Process;
if (!IsWow64Process(GetCurrentProcess(), &isWow64Process) || isWow64Process)
{
pszDllPath = L"%windir%\\sysnative\\audiosrv.dll";
}
else
{
pszDllPath = L"%windir%\\system32\\audiosrv.dll";
}
wchar_t szPath[MAX_PATH] = {};
if (0 == ExpandEnvironmentStrings(pszDllPath, szPath, ARRAYSIZE(szPath)))
{
return E_FAIL;
}
FAST_FAIL(SHStrDup(pszDllPath, &etAudioSession->IconPath));
FAST_FAIL(SHStrDup(L"System Sounds", &etAudioSession->DisplayName));
}
else
{
shared_ptr<void> processHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid), CloseHandle);
FAST_FAIL_HANDLE(processHandle.get());
wchar_t imagePath[MAX_PATH] = {};
DWORD dwCch = ARRAYSIZE(imagePath);
FAST_FAIL(QueryFullProcessImageName(processHandle.get(), 0, imagePath, &dwCch) == 0 ? E_FAIL : S_OK);
FAST_FAIL(SHStrDup(imagePath, &etAudioSession->IconPath));
FAST_FAIL(SHStrDup(PathFindFileName(imagePath), &etAudioSession->DisplayName));
}
etAudioSession->IsDesktopApp = true;
etAudioSession->BackgroundColor = 0x00000000;
}
return S_OK;
}
HRESULT AudioSessionService::GetAudioSessions(void** audioSessions)
{
if (_sessions.size() == 0)
{
return HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS);
}
*audioSessions = &_sessions[0];
return S_OK;
}
HRESULT AudioSessionService::IsImmersiveProcess(DWORD pid)
{
shared_ptr<void> processHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid), CloseHandle);
FAST_FAIL_HANDLE(processHandle.get());
return (::IsImmersiveProcess(processHandle.get()) ? S_OK : S_FALSE);
}
HRESULT AudioSessionService::CanResolveAppByApplicationUserModelId(LPCWSTR applicationUserModelId)
{
CComPtr<IShellItem2> item;
return SUCCEEDED(SHCreateItemInKnownFolder(FOLDERID_AppsFolder, KF_FLAG_DONT_VERIFY, applicationUserModelId, IID_PPV_ARGS(&item)));
}
HRESULT AudioSessionService::GetAppUserModelIdFromPid(DWORD pid, LPWSTR* applicationUserModelId)
{
shared_ptr<void> processHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid), CloseHandle);
FAST_FAIL_HANDLE(processHandle.get());
unsigned int appUserModelIdLength = 0;
long returnCode = GetApplicationUserModelId(processHandle.get(), &appUserModelIdLength, nullptr);
if (returnCode != ERROR_INSUFFICIENT_BUFFER)
{
return HRESULT_FROM_WIN32(returnCode);
}
unique_ptr<wchar_t[]> appUserModelId(new wchar_t[appUserModelIdLength]);
returnCode = GetApplicationUserModelId(processHandle.get(), &appUserModelIdLength, appUserModelId.get());
if (returnCode != ERROR_SUCCESS)
{
return HRESULT_FROM_WIN32(returnCode);
}
if (CanResolveAppByApplicationUserModelId(appUserModelId.get()))
{
FAST_FAIL(SHStrDup(appUserModelId.get(), applicationUserModelId));
}
else
{
wchar_t packageFamilyName[PACKAGE_FAMILY_NAME_MAX_LENGTH];
UINT32 packageFamilyNameLength = ARRAYSIZE(packageFamilyName);
wchar_t packageRelativeAppId[PACKAGE_RELATIVE_APPLICATION_ID_MAX_LENGTH];
UINT32 packageRelativeAppIdLength = ARRAYSIZE(packageRelativeAppId);
FAST_FAIL_WIN32(ParseApplicationUserModelId(appUserModelId.get(), &packageFamilyNameLength, packageFamilyName, &packageRelativeAppIdLength, packageRelativeAppId));
UINT32 packageCount = 0;
UINT32 packageNamesBufferLength = 0;
FAST_FAIL_BUFFER(FindPackagesByPackageFamily(packageFamilyName, PACKAGE_FILTER_HEAD | PACKAGE_INFORMATION_BASIC, &packageCount, nullptr, &packageNamesBufferLength, nullptr, nullptr));
if (packageCount <= 0)
{
return E_NOTFOUND;
}
unique_ptr<PWSTR[]> packageNames(new PWSTR[packageCount]);
unique_ptr<wchar_t[]> buffer(new wchar_t[packageNamesBufferLength]);
FAST_FAIL_WIN32(FindPackagesByPackageFamily(packageFamilyName, PACKAGE_FILTER_HEAD | PACKAGE_INFORMATION_BASIC, &packageCount, packageNames.get(), &packageNamesBufferLength, buffer.get(), nullptr));
PackageInfoReference packageInfoRef;
PACKAGE_INFO_REFERENCE rawPackageInfoRef;
FAST_FAIL_WIN32(OpenPackageInfoByFullName(packageNames[0], 0, &rawPackageInfoRef));
packageInfoRef.reset(&rawPackageInfoRef);
UINT32 packageIdsLength = 0;
UINT32 packageIdCount = 0;
FAST_FAIL_BUFFER(GetPackageApplicationIds(*packageInfoRef.get(), &packageIdsLength, nullptr, &packageIdCount));
if (packageIdCount <= 0)
{
return E_NOTFOUND;
}
unique_ptr<BYTE[]> packageIdsRaw(new BYTE[packageIdsLength]);
FAST_FAIL_WIN32(GetPackageApplicationIds(*packageInfoRef.get(), &packageIdsLength, packageIdsRaw.get(), &packageIdCount));
PCWSTR* packageIds = reinterpret_cast<PCWSTR*>(packageIdsRaw.get());
FAST_FAIL(SHStrDup(packageIds[0], applicationUserModelId));
}
return S_OK;
}
HRESULT AudioSessionService::SetAudioSessionVolume(unsigned long sessionId, float volume)
{
if (!_sessionMap[sessionId])
{
return E_INVALIDARG;
}
CComPtr<ISimpleAudioVolume> simpleAudioVolume;
FAST_FAIL(_sessionMap[sessionId]->QueryInterface(IID_PPV_ARGS(&simpleAudioVolume)));
FAST_FAIL(simpleAudioVolume->SetMasterVolume(volume, nullptr));
return S_OK;
}
HRESULT AudioSessionService::SetAudioSessionMute(unsigned long sessionId, bool isMuted)
{
if (!_sessionMap[sessionId])
{
return E_INVALIDARG;
}
CComPtr<ISimpleAudioVolume> simpleAudioVolume;
FAST_FAIL(_sessionMap[sessionId]->QueryInterface(IID_PPV_ARGS(&simpleAudioVolume)));
FAST_FAIL(simpleAudioVolume->SetMute(isMuted, nullptr));
return S_OK;
}
HRESULT AudioSessionService::GetAppProperties(PCWSTR pszAppId, PWSTR* ppszName, PWSTR* ppszIcon, ULONG *background)
{
*ppszIcon = nullptr;
*ppszName = nullptr;
*background = 0;
CComPtr<IShellItem2> item;
FAST_FAIL(SHCreateItemInKnownFolder(FOLDERID_AppsFolder, KF_FLAG_DONT_VERIFY, pszAppId, IID_PPV_ARGS(&item)));
CComHeapPtr<wchar_t> itemName;
FAST_FAIL(item->GetString(PKEY_ItemNameDisplay, &itemName));
FAST_FAIL(item->GetUInt32(PKEY_AppUserModel_Background, background));
CComHeapPtr<wchar_t> installPath;
FAST_FAIL(item->GetString(PKEY_AppUserModel_PackageInstallPath, &installPath));
CComHeapPtr<wchar_t> iconPath;
FAST_FAIL(item->GetString(PKEY_AppUserModel_Icon, &iconPath));
LPWSTR resolvedIconPath;
if (UrlIsFileUrl(iconPath))
{
FAST_FAIL(PathCreateFromUrlAlloc(iconPath, &resolvedIconPath, 0));
}
else
{
CComHeapPtr<wchar_t> fullPackagePath;
FAST_FAIL(item->GetString(PKEY_AppUserModel_PackageFullName, &fullPackagePath));
CComPtr<IMrtResourceManager> mrtResMgr;
FAST_FAIL(CoCreateInstance(__uuidof(MrtResourceManager), nullptr, CLSCTX_INPROC, IID_PPV_ARGS(&mrtResMgr)));
FAST_FAIL(mrtResMgr->InitializeForPackage(fullPackagePath));
CComPtr<IResourceMap> resourceMap;
FAST_FAIL(mrtResMgr->GetMainResourceMap(IID_PPV_ARGS(&resourceMap)));
FAST_FAIL(resourceMap->GetFilePath(iconPath, &resolvedIconPath));
}
*ppszIcon = resolvedIconPath;
*ppszName = itemName.Detach();
return S_OK;
}<|endoftext|>
|
<commit_before>#include <assert.h>
#include "ScheduleActualizer.h"
#include "Extensions/ScheduleActualizationAlgorithm.h"
namespace Scheduler
{
ScheduleActualizer::ScheduleActualizer(Schedule *schedule):
schedule(schedule),
algorithms_factory(nullptr),
is_actualizing(false)
{
}
void ScheduleActualizer::onOperationAdded(const Stop *stop, const Operation *operation) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationAdded(stop, operation);
}
void ScheduleActualizer::onOperationRemoved(const Stop *stop) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationRemoved(stop);
}
void ScheduleActualizer::onStopAdded(const Run *run, const Stop *stop, size_t index) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopAdded(run, stop, index);
}
void ScheduleActualizer::onStopRemoved(const Run *run) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopRemoved(run);
}
void ScheduleActualizer::onStopReplaced(const Run * run, const Stop * new_stop, size_t index)
{
}
void ScheduleActualizer::onRunVehicleChanged(const Run *run, const Vehicle *vehicle) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunVehicleChanged(run, vehicle);
}
void ScheduleActualizer::onRunAdded(const Run *run, size_t index) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunAdded(run, index);
}
void ScheduleActualizer::onRunRemoved() {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunRemoved();
}
void ScheduleActualizer::actualize() {
if(is_actualizing) return;
is_actualizing = true;
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->actualize();
is_actualizing = false;
}
ScheduleActualizer::~ScheduleActualizer() {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithms_factory->destroyObject(algorithm);
}
void ScheduleActualizer::onStopNextRouteChanged(const Stop *stop) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopNextRouteChanged(stop);
}
void ScheduleActualizer::setScheduleActualizationAlgorithmsFactory(
Factory<ScheduleActualizationAlgorithm> *factory) {
this->algorithms_factory = factory;
}
}<commit_msg>[#37] Fixed mixed event processing in schedule actualizer<commit_after>#include <assert.h>
#include "ScheduleActualizer.h"
#include "Extensions/ScheduleActualizationAlgorithm.h"
namespace Scheduler
{
ScheduleActualizer::ScheduleActualizer(Schedule *schedule):
schedule(schedule),
algorithms_factory(nullptr),
is_actualizing(false)
{
}
void ScheduleActualizer::onOperationAdded(const Stop *stop, const Operation *operation) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationAdded(stop, operation);
}
void ScheduleActualizer::onOperationRemoved(const Stop *stop) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onOperationRemoved(stop);
}
void ScheduleActualizer::onStopAdded(const Run *run, const Stop *stop, size_t index) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopAdded(run, stop, index);
}
void ScheduleActualizer::onStopRemoved(const Run *run) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopRemoved(run);
}
void ScheduleActualizer::onStopReplaced(const Run * run, const Stop * new_stop, size_t index)
{
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopReplaced(run, new_stop, index);
}
void ScheduleActualizer::onRunVehicleChanged(const Run *run, const Vehicle *vehicle) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunVehicleChanged(run, vehicle);
}
void ScheduleActualizer::onRunAdded(const Run *run, size_t index) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunAdded(run, index);
}
void ScheduleActualizer::onRunRemoved() {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onRunRemoved();
}
void ScheduleActualizer::actualize() {
if(is_actualizing) return;
is_actualizing = true;
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->actualize();
is_actualizing = false;
}
ScheduleActualizer::~ScheduleActualizer() {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithms_factory->destroyObject(algorithm);
}
void ScheduleActualizer::onStopNextRouteChanged(const Stop *stop) {
for(ScheduleActualizationAlgorithm* algorithm : algorithms) algorithm->onStopNextRouteChanged(stop);
}
void ScheduleActualizer::setScheduleActualizationAlgorithmsFactory(
Factory<ScheduleActualizationAlgorithm> *factory) {
this->algorithms_factory = factory;
}
}<|endoftext|>
|
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "pluginManagerImplementation.h"
#include <QtCore/QCoreApplication>
#include <qrkernel/logging.h>
using namespace qReal::details;
PluginManagerImplementation::PluginManagerImplementation(const QString &applicationDirPath
, const QString &additionalPart)
: mPluginsDir(QDir(applicationDirPath))
, mApplicationDirectoryPath(applicationDirPath)
, mAdditionalPart(additionalPart)
{
}
PluginManagerImplementation::~PluginManagerImplementation()
{
}
QList<QObject *> PluginManagerImplementation::loadAllPlugins()
{
while (!mPluginsDir.isRoot() && !mPluginsDir.entryList(QDir::Dirs).contains("plugins")) {
mPluginsDir.cdUp();
}
QList<QString> splittedDir = mAdditionalPart.split('/');
for (const QString &partOfDirectory : splittedDir) {
mPluginsDir.cd(partOfDirectory);
}
QList<QObject *> listOfPlugins;
for (const QString &fileName : mPluginsDir.entryList(QDir::Files)) {
QPair<QObject *, QString> const pluginAndError = pluginLoadedByName(fileName);
QObject * const pluginByName = pluginAndError.first;
if (pluginByName) {
listOfPlugins.append(pluginByName);
mFileNameAndPlugin.insert(fileName, pluginByName);
} else {
QLOG_ERROR() << "Plugin loading failed:" << pluginAndError.second;
qDebug() << "Plugin loading failed:" << pluginAndError.second;
}
}
return listOfPlugins;
}
QPair<QObject *, QString> PluginManagerImplementation::pluginLoadedByName(const QString &pluginName)
{
QPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName), qApp);
loader->load();
QObject *plugin = loader->instance();
QPair<QString, QPluginLoader*> pairOfLoader = qMakePair(pluginName, loader);
mNewLoaders.append(pairOfLoader);
if (plugin) {
mFileNameAndPlugin.insert(loader->metaData()["IID"].toString(), plugin);
return qMakePair(plugin, QString());
}
const QString loaderError = loader->errorString();
// Unloading of plugins is currently (Qt 5.3) broken due to a bug in metatype system: calling Q_DECLARE_METATYPE
// from plugin registers some data from plugin address space in Qt metatype system, which is not being updated
// when plugin is unloaded and loaded again. Any subsequent calls to QVariant or other template classes/methods
// which use metainformation will result in a crash. It is likely (but not verified) that qRegisterMetaType leads
// to the same issue. Since we can not guarantee that plugin does not use Q_DECLARE_METATYPE or qRegisterMetaType
// we shall not unload plugin at all, to be safe rather than sorry.
//
// But it seems also that metainformation gets deleted BEFORE plugins are unloaded on application exit, so we can
// not call any metainformation-using code in destructors that get called on unloading. Since Qt classes themselves
// are using such calls (QGraphicsViewScene, for example), random crashes on exit may be a symptom of this problem.
//
// EditorManager is an exception, because it really needs to unload editor plugins, to be able to load new versions
// compiled by metaeditor. Editor plugins are generated, so we can guarantee to some extent that there will be no
// metatype registrations.
//
// See:
// http://stackoverflow.com/questions/19234703/using-q-declare-metatype-with-a-dll-that-may-be-loaded-multiple-times
// (and http://qt-project.org/forums/viewthread/35587)
// https://bugreports.qt-project.org/browse/QTBUG-32442
delete loader;
return qMakePair(nullptr, loaderError);
}
QString PluginManagerImplementation::unloadPlugin(const QString &pluginName)
{
int count = 0;
bool stateUnload = true;
for (auto currentPair : mNewLoaders) {
if (currentPair.first == pluginName) {
stateUnload = currentPair.second->unload();
}
++count;
}
for (int j = 0; j < count; ++j) {
mNewLoaders.removeFirst();
}
if (stateUnload) {
return QString();
}
return QString("Plugin was not found");
}
QList<QString> PluginManagerImplementation::namesOfPlugins()
{
QList<QString> listOfNames;
for (auto currentPair : mNewLoaders) {
listOfNames.append(currentPair.first);
}
return listOfNames;
}
QString PluginManagerImplementation::fileName(QObject *plugin) const
{
return mFileNameAndPlugin.key(plugin);
}
QObject *PluginManagerImplementation::pluginByName(const QString &pluginName) const
{
return mFileNameAndPlugin[pluginName];
}
<commit_msg>styleguide fix<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "pluginManagerImplementation.h"
#include <QtCore/QCoreApplication>
#include <qrkernel/logging.h>
using namespace qReal::details;
PluginManagerImplementation::PluginManagerImplementation(const QString &applicationDirPath
, const QString &additionalPart)
: mPluginsDir(QDir(applicationDirPath))
, mApplicationDirectoryPath(applicationDirPath)
, mAdditionalPart(additionalPart)
{
}
PluginManagerImplementation::~PluginManagerImplementation()
{
}
QList<QObject *> PluginManagerImplementation::loadAllPlugins()
{
while (!mPluginsDir.isRoot() && !mPluginsDir.entryList(QDir::Dirs).contains("plugins")) {
mPluginsDir.cdUp();
}
QList<QString> splittedDir = mAdditionalPart.split('/');
for (const QString &partOfDirectory : splittedDir) {
mPluginsDir.cd(partOfDirectory);
}
QList<QObject *> listOfPlugins;
for (const QString &fileName : mPluginsDir.entryList(QDir::Files)) {
QPair<QObject *, QString> const pluginAndError = pluginLoadedByName(fileName);
QObject * const pluginByName = pluginAndError.first;
if (pluginByName) {
listOfPlugins.append(pluginByName);
mFileNameAndPlugin.insert(fileName, pluginByName);
} else {
QLOG_ERROR() << "Plugin loading failed:" << pluginAndError.second;
qDebug() << "Plugin loading failed:" << pluginAndError.second;
}
}
return listOfPlugins;
}
QPair<QObject *, QString> PluginManagerImplementation::pluginLoadedByName(const QString &pluginName)
{
QPluginLoader *loader = new QPluginLoader(mPluginsDir.absoluteFilePath(pluginName), qApp);
loader->load();
QObject *plugin = loader->instance();
QPair<QString, QPluginLoader*> pairOfLoader = qMakePair(pluginName, loader);
mNewLoaders.append(pairOfLoader);
if (plugin) {
mFileNameAndPlugin.insert(loader->metaData()["IID"].toString(), plugin);
return qMakePair(plugin, QString());
}
const QString loaderError = loader->errorString();
// Unloading of plugins is currently (Qt 5.3) broken due to a bug in metatype system: calling Q_DECLARE_METATYPE
// from plugin registers some data from plugin address space in Qt metatype system, which is not being updated
// when plugin is unloaded and loaded again. Any subsequent calls to QVariant or other template classes/methods
// which use metainformation will result in a crash. It is likely (but not verified) that qRegisterMetaType leads
// to the same issue. Since we can not guarantee that plugin does not use Q_DECLARE_METATYPE or qRegisterMetaType
// we shall not unload plugin at all, to be safe rather than sorry.
//
// But it seems also that metainformation gets deleted BEFORE plugins are unloaded on application exit, so we can
// not call any metainformation-using code in destructors that get called on unloading. Since Qt classes themselves
// are using such calls (QGraphicsViewScene, for example), random crashes on exit may be a symptom of this problem.
//
// EditorManager is an exception, because it really needs to unload editor plugins, to be able to load new versions
// compiled by metaeditor. Editor plugins are generated, so we can guarantee to some extent that there will be no
// metatype registrations.
//
// See:
// http://stackoverflow.com/questions/19234703/using-q-declare-metatype-with-a-dll-that-may-be-loaded-multiple-times
// (and http://qt-project.org/forums/viewthread/35587)
// https://bugreports.qt-project.org/browse/QTBUG-32442
delete loader;
return qMakePair(nullptr, loaderError);
}
QString PluginManagerImplementation::unloadPlugin(const QString &pluginName)
{
int count = 0;
bool stateUnload = true;
for (auto currentPair : mNewLoaders) {
if (currentPair.first == pluginName) {
stateUnload = currentPair.second->unload();
}
++count;
}
for (int j = 0; j < count; ++j) {
mNewLoaders.removeFirst();
}
if (stateUnload) {
return QString();
}
return QString("Plugin was not found");
}
QList<QString> PluginManagerImplementation::namesOfPlugins()
{
QList<QString> listOfNames;
for (auto currentPair : mNewLoaders) {
listOfNames.append(currentPair.first);
}
return listOfNames;
}
QString PluginManagerImplementation::fileName(QObject *plugin) const
{
return mFileNameAndPlugin.key(plugin);
}
QObject *PluginManagerImplementation::pluginByName(const QString &pluginName) const
{
return mFileNameAndPlugin[pluginName];
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015-2016 Alex Spataru <alex_spataru@outlook>
*
* 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 "EventLogger.h"
#include <stdio.h>
#include <QDir>
#include <QFile>
#include <QDebug>
#include <QTimer>
#include <QSysInfo>
#include <QDateTime>
#include <QJsonArray>
#include <QJsonObject>
#include <QApplication>
#include <QJsonDocument>
#include <QDesktopServices>
#define LOG qDebug() << "DS Events:"
/* Used for the custom message handler */
#define PRINT_FMT "%-14s %-13s %-12s\n"
#define PRINT(string) QString(string).toLocal8Bit().constData()
#define GET_DATE_TIME(format) QDateTime::currentDateTime().toString(format)
/**
* Repeats the \a input string \a n times and returns the obtained string
*/
static QString REPEAT (QString input, int n)
{
QString string;
for (int i = 0; i < n; ++i)
string.append (input);
return string;
}
/**
* Connects the signals/slots between the \c DriverStation and the logger
*/
DSEventLogger::DSEventLogger()
{
m_init = 0;
m_dump = NULL;
m_currentLog = "";
init();
saveDataLoop();
connectSlots();
}
/**
* Closes the log file
*/
DSEventLogger::~DSEventLogger()
{
saveData();
}
/**
* Returns a pointer to the only instance of this class
*/
DSEventLogger* DSEventLogger::getInstance()
{
static DSEventLogger instance;
return &instance;
}
/**
* Returns the path in which the log files are saved
*/
QString DSEventLogger::logsPath() const
{
return QString ("%1/.%2/%3/Logs/")
.arg (QDir::homePath(),
qApp->applicationName().toLower(),
qApp->applicationVersion().toLower());
}
/**
* Calls the appropiate functions to display the \a data on the console
* and write it on the log file
*/
void DSEventLogger::messageHandler (QtMsgType type,
const QMessageLogContext& context,
const QString& data)
{
(void) type;
(void) context;
getInstance()->handleMessage (type, data);
}
/**
* Writes the message output to the console and to the dump file (which is
* dumped on the DS log file when the application exits).
*/
void DSEventLogger::handleMessage (const QtMsgType type, const QString& data)
{
/* Data is empty */
if (data.isEmpty())
return;
/* Logger not initialized */
if (!m_init)
init();
/* Get warning level */
QString level;
switch (type) {
case QtDebugMsg:
level = "DEBUG";
break;
case QtWarningMsg:
level = "WARNING";
break;
case QtCriticalMsg:
level = "CRITICAL";
break;
case QtFatalMsg:
level = "FATAL";
break;
default:
level = "SYSTEM";
break;
}
/* Get elapsed time */
qint64 msec = m_timer.elapsed();
qint64 secs = (msec / 1000);
qint64 mins = (secs / 60) % 60;
/* Get the remaining seconds and milliseconds */
secs = secs % 60;
msec = msec % 1000;
/* Get current time */
QString time = (QString ("%1:%2.%3")
.arg (mins, 2, 10, QLatin1Char ('0'))
.arg (secs, 2, 10, QLatin1Char ('0'))
.arg (QString::number (msec).at (0)));
/* Write logs to dump file and console */
fprintf (m_dump, PRINT_FMT, PRINT (time), PRINT (level), PRINT (data));
fprintf (stderr, PRINT_FMT, PRINT (time), PRINT (level), PRINT (data));
/* Flush to write "instantly" */
fflush (m_dump);
}
/**
* Prepares the log file for writting
*/
void DSEventLogger::init()
{
if (!m_init) {
/* Initialize the timer */
m_init = true;
m_timer.restart();
/* Get app info */
QString appN = qApp->applicationName();
QString appV = qApp->applicationVersion();
QString ldsV = DriverStation::libDSVersion();
QString time = GET_DATE_TIME ("MMM dd yyyy - HH:mm:ss AP");
/* Get dump directoru */
QString path = QString ("%1/%2/%3/%4/")
.arg (logsPath())
.arg (GET_DATE_TIME ("yyyy"))
.arg (GET_DATE_TIME ("MMMM"))
.arg (GET_DATE_TIME ("ddd dd"));
/* Create logs directory (if necessesary) */
QDir dir (path);
if (!dir.exists())
dir.mkpath (".");
/* Get dump file path */
m_currentLog = QString ("%1/%2.log")
.arg (path)
.arg (GET_DATE_TIME ("HH_mm_ss AP"));
/* Open dump file */
m_dump = fopen (m_currentLog.toStdString().c_str(), "w");
m_dump = !m_dump ? stderr : m_dump;
/* Get OS information */
QString sysV;
#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0)
sysV = QSysInfo::prettyProductName();
#else
#if defined Q_OS_WIN
sysV = "Windows";
#elif defined Q_OS_MAC
sysV = "Mac OSX";
#elif defined Q_OS_LINUX
sysV = "GNU/Linux";
#else
sysV = "Unknown";
#endif
#endif
/* Format app info */
time.prepend ("Log created on: ");
ldsV.prepend ("LibDS version: ");
sysV.prepend ("Operating System: ");
appN.prepend ("Application name: ");
appV.prepend ("Application version: ");
/* Append app info */
fprintf (m_dump, "%s\n", PRINT (time));
fprintf (m_dump, "%s\n", PRINT (ldsV));
fprintf (m_dump, "%s\n", PRINT (sysV));
fprintf (m_dump, "%s\n", PRINT (appN));
fprintf (m_dump, "%s\n\n", PRINT (appV));
/* Start the table header */
fprintf (m_dump, "%s\n", PRINT (REPEAT ("-", 72)));
fprintf (m_dump, PRINT_FMT, "ELAPSED TIME", "ERROR LEVEL", "MESSAGE");
fprintf (m_dump, "%s\n", PRINT (REPEAT ("-", 72)));
}
}
/**
* Opens the application logs directory with a file explorer
*/
void DSEventLogger::openLogsPath()
{
if (!QDir (logsPath()).exists())
QDir (logsPath()).mkpath (".");
QDesktopServices::openUrl (QUrl::fromLocalFile (logsPath()));
}
/**
* Opens the current log file using a system process
*/
void DSEventLogger::openCurrentLog()
{
if (!m_currentLog.isEmpty())
QDesktopServices::openUrl (QUrl::fromLocalFile (m_currentLog));
}
/**
* Saves the log data to the disk and schedules another call in the future
*/
void DSEventLogger::saveDataLoop()
{
saveData();
QTimer::singleShot (500, Qt::PreciseTimer, this, SLOT (saveDataLoop()));
}
/**
* Called when the DS reports a change of the robot's CAN utilization
*/
void DSEventLogger::onCANUsageChanged (int usage)
{
Q_UNUSED (usage);
m_canUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a change of the robot's CPU usage
*/
void DSEventLogger::onCPUUsageChanged (int usage)
{
Q_UNUSED (usage);
m_cpuUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a change of the robot's RAM usage
*/
void DSEventLogger::onRAMUsageChanged (int usage)
{
Q_UNUSED (usage);
m_ramUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a new NetConsole message
*/
void DSEventLogger::onNewMessage (QString message)
{
Q_UNUSED (message);
m_messagesLog.append (qMakePair<qint64, QString> (currentTime(), message));
}
/**
* Called when the DS reports a change of the robot's disk usage
*/
void DSEventLogger::onDiskUsageChanged (int usage)
{
Q_UNUSED (usage);
m_diskUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a change of the enabled status
*/
void DSEventLogger::onEnabledChanged (bool enabled)
{
LOG << "Robot enabled state set to" << enabled;
m_enabledLog.append (qMakePair<qint64, bool> (currentTime(), enabled));
}
/**
* Called when the DS reports a change of the team number
*/
void DSEventLogger::onTeamNumberChanged (int number)
{
LOG << "Team number set to" << number;
}
/**
* Called when the DS reports a change in the robot voltage
*/
void DSEventLogger::onVoltageChanged (float voltage)
{
Q_UNUSED (voltage);
m_voltageLog.append (qMakePair<qint64, float> (currentTime(), voltage));
}
/**
* Called when the DS reports a change in the robot code status
*/
void DSEventLogger::onRobotCodeChanged (bool robotCode)
{
LOG << "Robot code status set to" << robotCode;
m_robotCodeLog.append (qMakePair<qint64, bool> (currentTime(), robotCode));
}
/**
* Called when the DS reports a change in the FMS communications status
*/
void DSEventLogger::onFMSCommunicationsChanged (bool connected)
{
LOG << "FMS communications set to" << connected;
m_fmsCommsLog.append (qMakePair<qint64, bool> (currentTime(), connected));
}
/**
* Called when the DS reports a change in the radio communications status
*/
void DSEventLogger::onRadioCommunicationsChanged (bool connected)
{
LOG << "Radio communications set to" << connected;
m_radioCommsLog.append (qMakePair<qint64, bool> (currentTime(), connected));
}
/**
* Called when the DS reports a change in the robot communications status
*/
void DSEventLogger::onRobotCommunicationsChanged (bool connected)
{
LOG << "Robot communications set to" << connected;
m_robotCommsLog.append (qMakePair<qint64, bool> (currentTime(), connected));
}
/**
* Called when the DS reports a change in the emergency stop status
*/
void DSEventLogger::onEmergencyStoppedChanged (bool emergencyStopped)
{
LOG << "ESTOP set to" << emergencyStopped;
m_emergencyStopLog.append (qMakePair<qint64, bool> (currentTime(),
emergencyStopped));
}
/**
* Called when the DS reports a change in the robot control mode
*/
void DSEventLogger::onControlModeChanged (DriverStation::Control mode)
{
LOG << "Robot control mode set to" << mode;
m_controlModeLog.append (qMakePair<qint64, int> (currentTime(),
(int) mode));
}
/**
* Called when the DS reports a change in the team alliance
*/
void DSEventLogger::onAllianceChanged (DriverStation::Alliance alliance)
{
LOG << "Team alliance set to" << alliance;
}
/**
* Called when the DS reports a change in the team position
*/
void DSEventLogger::onPositionChanged (DriverStation::Position position)
{
LOG << "Team position set to" << position;
}
/**
* Saves the current log information to a local file using the JSON format
*/
void DSEventLogger::saveData()
{
}
/**
* Allows the logger class to react when the DriverStation receives a
* new event from the LibDS library
*/
void DSEventLogger::connectSlots()
{
DriverStation* ds = DriverStation::getInstance();
connect (ds, &DriverStation::canUsageChanged,
this, &DSEventLogger::onCANUsageChanged);
connect (ds, &DriverStation::cpuUsageChanged,
this, &DSEventLogger::onCPUUsageChanged);
connect (ds, &DriverStation::ramUsageChanged,
this, &DSEventLogger::onRAMUsageChanged);
connect (ds, &DriverStation::newMessage,
this, &DSEventLogger::onNewMessage);
connect (ds, &DriverStation::diskUsageChanged,
this, &DSEventLogger::onDiskUsageChanged);
connect (ds, &DriverStation::enabledChanged,
this, &DSEventLogger::onEnabledChanged);
connect (ds, &DriverStation::teamNumberChanged,
this, &DSEventLogger::onTeamNumberChanged);
connect (ds, &DriverStation::voltageChanged,
this, &DSEventLogger::onVoltageChanged);
connect (ds, &DriverStation::robotCodeChanged,
this, &DSEventLogger::onRobotCodeChanged);
connect (ds, &DriverStation::fmsCommunicationsChanged,
this, &DSEventLogger::onFMSCommunicationsChanged);
connect (ds, &DriverStation::radioCommunicationsChanged,
this, &DSEventLogger::onRadioCommunicationsChanged);
connect (ds, &DriverStation::robotCommunicationsChanged,
this, &DSEventLogger::onRobotCommunicationsChanged);
connect (ds, &DriverStation::emergencyStoppedChanged,
this, &DSEventLogger::onEmergencyStoppedChanged);
connect (ds, &DriverStation::controlModeChanged,
this, &DSEventLogger::onControlModeChanged);
connect (ds, &DriverStation::allianceChanged,
this, &DSEventLogger::onAllianceChanged);
connect (ds, &DriverStation::positionChanged,
this, &DSEventLogger::onPositionChanged);
}
/**
* Returns the current time signature
*/
qint64 DSEventLogger::currentTime()
{
QDateTime time = QDateTime::currentDateTime();
return time.toMSecsSinceEpoch();
}
<commit_msg>Update EventLogger.cpp<commit_after>/*
* Copyright (C) 2015-2016 Alex Spataru <alex_spataru@outlook>
*
* 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 "EventLogger.h"
#include <stdio.h>
#include <QUrl>
#include <QDir>
#include <QFile>
#include <QDebug>
#include <QTimer>
#include <QSysInfo>
#include <QDateTime>
#include <QJsonArray>
#include <QJsonObject>
#include <QApplication>
#include <QJsonDocument>
#include <QDesktopServices>
#define LOG qDebug() << "DS Events:"
/* Used for the custom message handler */
#define PRINT_FMT "%-14s %-13s %-12s\n"
#define PRINT(string) QString(string).toLocal8Bit().constData()
#define GET_DATE_TIME(format) QDateTime::currentDateTime().toString(format)
/**
* Repeats the \a input string \a n times and returns the obtained string
*/
static QString REPEAT (QString input, int n)
{
QString string;
for (int i = 0; i < n; ++i)
string.append (input);
return string;
}
/**
* Connects the signals/slots between the \c DriverStation and the logger
*/
DSEventLogger::DSEventLogger()
{
m_init = 0;
m_dump = NULL;
m_currentLog = "";
init();
saveDataLoop();
connectSlots();
}
/**
* Closes the log file
*/
DSEventLogger::~DSEventLogger()
{
saveData();
}
/**
* Returns a pointer to the only instance of this class
*/
DSEventLogger* DSEventLogger::getInstance()
{
static DSEventLogger instance;
return &instance;
}
/**
* Returns the path in which the log files are saved
*/
QString DSEventLogger::logsPath() const
{
return QString ("%1/.%2/%3/Logs/")
.arg (QDir::homePath(),
qApp->applicationName().toLower(),
qApp->applicationVersion().toLower());
}
/**
* Calls the appropiate functions to display the \a data on the console
* and write it on the log file
*/
void DSEventLogger::messageHandler (QtMsgType type,
const QMessageLogContext& context,
const QString& data)
{
(void) type;
(void) context;
getInstance()->handleMessage (type, data);
}
/**
* Writes the message output to the console and to the dump file (which is
* dumped on the DS log file when the application exits).
*/
void DSEventLogger::handleMessage (const QtMsgType type, const QString& data)
{
/* Data is empty */
if (data.isEmpty())
return;
/* Logger not initialized */
if (!m_init)
init();
/* Get warning level */
QString level;
switch (type) {
case QtDebugMsg:
level = "DEBUG";
break;
case QtWarningMsg:
level = "WARNING";
break;
case QtCriticalMsg:
level = "CRITICAL";
break;
case QtFatalMsg:
level = "FATAL";
break;
default:
level = "SYSTEM";
break;
}
/* Get elapsed time */
qint64 msec = m_timer.elapsed();
qint64 secs = (msec / 1000);
qint64 mins = (secs / 60) % 60;
/* Get the remaining seconds and milliseconds */
secs = secs % 60;
msec = msec % 1000;
/* Get current time */
QString time = (QString ("%1:%2.%3")
.arg (mins, 2, 10, QLatin1Char ('0'))
.arg (secs, 2, 10, QLatin1Char ('0'))
.arg (QString::number (msec).at (0)));
/* Write logs to dump file and console */
fprintf (m_dump, PRINT_FMT, PRINT (time), PRINT (level), PRINT (data));
fprintf (stderr, PRINT_FMT, PRINT (time), PRINT (level), PRINT (data));
/* Flush to write "instantly" */
fflush (m_dump);
}
/**
* Prepares the log file for writting
*/
void DSEventLogger::init()
{
if (!m_init) {
/* Initialize the timer */
m_init = true;
m_timer.restart();
/* Get app info */
QString appN = qApp->applicationName();
QString appV = qApp->applicationVersion();
QString ldsV = DriverStation::libDSVersion();
QString time = GET_DATE_TIME ("MMM dd yyyy - HH:mm:ss AP");
/* Get dump directoru */
QString path = QString ("%1/%2/%3/%4/")
.arg (logsPath())
.arg (GET_DATE_TIME ("yyyy"))
.arg (GET_DATE_TIME ("MMMM"))
.arg (GET_DATE_TIME ("ddd dd"));
/* Create logs directory (if necessesary) */
QDir dir (path);
if (!dir.exists())
dir.mkpath (".");
/* Get dump file path */
m_currentLog = QString ("%1/%2.log")
.arg (path)
.arg (GET_DATE_TIME ("HH_mm_ss AP"));
/* Open dump file */
m_dump = fopen (m_currentLog.toStdString().c_str(), "w");
m_dump = !m_dump ? stderr : m_dump;
/* Get OS information */
QString sysV;
#if QT_VERSION >= QT_VERSION_CHECK (5, 4, 0)
sysV = QSysInfo::prettyProductName();
#else
#if defined Q_OS_WIN
sysV = "Windows";
#elif defined Q_OS_MAC
sysV = "Mac OSX";
#elif defined Q_OS_LINUX
sysV = "GNU/Linux";
#else
sysV = "Unknown";
#endif
#endif
/* Format app info */
time.prepend ("Log created on: ");
ldsV.prepend ("LibDS version: ");
sysV.prepend ("Operating System: ");
appN.prepend ("Application name: ");
appV.prepend ("Application version: ");
/* Append app info */
fprintf (m_dump, "%s\n", PRINT (time));
fprintf (m_dump, "%s\n", PRINT (ldsV));
fprintf (m_dump, "%s\n", PRINT (sysV));
fprintf (m_dump, "%s\n", PRINT (appN));
fprintf (m_dump, "%s\n\n", PRINT (appV));
/* Start the table header */
fprintf (m_dump, "%s\n", PRINT (REPEAT ("-", 72)));
fprintf (m_dump, PRINT_FMT, "ELAPSED TIME", "ERROR LEVEL", "MESSAGE");
fprintf (m_dump, "%s\n", PRINT (REPEAT ("-", 72)));
}
}
/**
* Opens the application logs directory with a file explorer
*/
void DSEventLogger::openLogsPath()
{
if (!QDir (logsPath()).exists())
QDir (logsPath()).mkpath (".");
QDesktopServices::openUrl (QUrl::fromLocalFile (logsPath()));
}
/**
* Opens the current log file using a system process
*/
void DSEventLogger::openCurrentLog()
{
if (!m_currentLog.isEmpty())
QDesktopServices::openUrl (QUrl::fromLocalFile (m_currentLog));
}
/**
* Saves the log data to the disk and schedules another call in the future
*/
void DSEventLogger::saveDataLoop()
{
saveData();
QTimer::singleShot (500, Qt::PreciseTimer, this, SLOT (saveDataLoop()));
}
/**
* Called when the DS reports a change of the robot's CAN utilization
*/
void DSEventLogger::onCANUsageChanged (int usage)
{
Q_UNUSED (usage);
m_canUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a change of the robot's CPU usage
*/
void DSEventLogger::onCPUUsageChanged (int usage)
{
Q_UNUSED (usage);
m_cpuUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a change of the robot's RAM usage
*/
void DSEventLogger::onRAMUsageChanged (int usage)
{
Q_UNUSED (usage);
m_ramUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a new NetConsole message
*/
void DSEventLogger::onNewMessage (QString message)
{
Q_UNUSED (message);
m_messagesLog.append (qMakePair<qint64, QString> (currentTime(), message));
}
/**
* Called when the DS reports a change of the robot's disk usage
*/
void DSEventLogger::onDiskUsageChanged (int usage)
{
Q_UNUSED (usage);
m_diskUsageLog.append (qMakePair<qint64, int> (currentTime(), usage));
}
/**
* Called when the DS reports a change of the enabled status
*/
void DSEventLogger::onEnabledChanged (bool enabled)
{
LOG << "Robot enabled state set to" << enabled;
m_enabledLog.append (qMakePair<qint64, bool> (currentTime(), enabled));
}
/**
* Called when the DS reports a change of the team number
*/
void DSEventLogger::onTeamNumberChanged (int number)
{
LOG << "Team number set to" << number;
}
/**
* Called when the DS reports a change in the robot voltage
*/
void DSEventLogger::onVoltageChanged (float voltage)
{
Q_UNUSED (voltage);
m_voltageLog.append (qMakePair<qint64, float> (currentTime(), voltage));
}
/**
* Called when the DS reports a change in the robot code status
*/
void DSEventLogger::onRobotCodeChanged (bool robotCode)
{
LOG << "Robot code status set to" << robotCode;
m_robotCodeLog.append (qMakePair<qint64, bool> (currentTime(), robotCode));
}
/**
* Called when the DS reports a change in the FMS communications status
*/
void DSEventLogger::onFMSCommunicationsChanged (bool connected)
{
LOG << "FMS communications set to" << connected;
m_fmsCommsLog.append (qMakePair<qint64, bool> (currentTime(), connected));
}
/**
* Called when the DS reports a change in the radio communications status
*/
void DSEventLogger::onRadioCommunicationsChanged (bool connected)
{
LOG << "Radio communications set to" << connected;
m_radioCommsLog.append (qMakePair<qint64, bool> (currentTime(), connected));
}
/**
* Called when the DS reports a change in the robot communications status
*/
void DSEventLogger::onRobotCommunicationsChanged (bool connected)
{
LOG << "Robot communications set to" << connected;
m_robotCommsLog.append (qMakePair<qint64, bool> (currentTime(), connected));
}
/**
* Called when the DS reports a change in the emergency stop status
*/
void DSEventLogger::onEmergencyStoppedChanged (bool emergencyStopped)
{
LOG << "ESTOP set to" << emergencyStopped;
m_emergencyStopLog.append (qMakePair<qint64, bool> (currentTime(),
emergencyStopped));
}
/**
* Called when the DS reports a change in the robot control mode
*/
void DSEventLogger::onControlModeChanged (DriverStation::Control mode)
{
LOG << "Robot control mode set to" << mode;
m_controlModeLog.append (qMakePair<qint64, int> (currentTime(),
(int) mode));
}
/**
* Called when the DS reports a change in the team alliance
*/
void DSEventLogger::onAllianceChanged (DriverStation::Alliance alliance)
{
LOG << "Team alliance set to" << alliance;
}
/**
* Called when the DS reports a change in the team position
*/
void DSEventLogger::onPositionChanged (DriverStation::Position position)
{
LOG << "Team position set to" << position;
}
/**
* Saves the current log information to a local file using the JSON format
*/
void DSEventLogger::saveData()
{
}
/**
* Allows the logger class to react when the DriverStation receives a
* new event from the LibDS library
*/
void DSEventLogger::connectSlots()
{
DriverStation* ds = DriverStation::getInstance();
connect (ds, &DriverStation::canUsageChanged,
this, &DSEventLogger::onCANUsageChanged);
connect (ds, &DriverStation::cpuUsageChanged,
this, &DSEventLogger::onCPUUsageChanged);
connect (ds, &DriverStation::ramUsageChanged,
this, &DSEventLogger::onRAMUsageChanged);
connect (ds, &DriverStation::newMessage,
this, &DSEventLogger::onNewMessage);
connect (ds, &DriverStation::diskUsageChanged,
this, &DSEventLogger::onDiskUsageChanged);
connect (ds, &DriverStation::enabledChanged,
this, &DSEventLogger::onEnabledChanged);
connect (ds, &DriverStation::teamNumberChanged,
this, &DSEventLogger::onTeamNumberChanged);
connect (ds, &DriverStation::voltageChanged,
this, &DSEventLogger::onVoltageChanged);
connect (ds, &DriverStation::robotCodeChanged,
this, &DSEventLogger::onRobotCodeChanged);
connect (ds, &DriverStation::fmsCommunicationsChanged,
this, &DSEventLogger::onFMSCommunicationsChanged);
connect (ds, &DriverStation::radioCommunicationsChanged,
this, &DSEventLogger::onRadioCommunicationsChanged);
connect (ds, &DriverStation::robotCommunicationsChanged,
this, &DSEventLogger::onRobotCommunicationsChanged);
connect (ds, &DriverStation::emergencyStoppedChanged,
this, &DSEventLogger::onEmergencyStoppedChanged);
connect (ds, &DriverStation::controlModeChanged,
this, &DSEventLogger::onControlModeChanged);
connect (ds, &DriverStation::allianceChanged,
this, &DSEventLogger::onAllianceChanged);
connect (ds, &DriverStation::positionChanged,
this, &DSEventLogger::onPositionChanged);
}
/**
* Returns the current time signature
*/
qint64 DSEventLogger::currentTime()
{
QDateTime time = QDateTime::currentDateTime();
return time.toMSecsSinceEpoch();
}
<|endoftext|>
|
<commit_before>#include "xchainer/array_repr.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
#include "xchainer/device_id.h"
#include "xchainer/native_backend.h"
namespace xchainer {
namespace {
template <typename T>
void CheckArrayRepr(const std::string& expected, const std::vector<T>& data_vec, Shape shape, const DeviceId& device_id,
const std::vector<GraphId> graph_ids = {}) {
// Copy to a contiguous memory block because std::vector<bool> is not packed as a sequence of bool's.
std::shared_ptr<T> data_ptr = std::make_unique<T[]>(data_vec.size());
std::copy(data_vec.begin(), data_vec.end(), data_ptr.get());
Array array = Array::FromBuffer(shape, TypeToDtype<T>, static_cast<std::shared_ptr<void>>(data_ptr), device_id);
for (const GraphId& graph_id : graph_ids) {
array.RequireGrad(graph_id);
}
// std::string version
EXPECT_EQ(expected, ArrayRepr(array));
// std::ostream version
std::ostringstream os;
os << array;
EXPECT_EQ(expected, os.str());
}
TEST(ArrayReprTest, AllDtypesOnNativeBackend) {
NativeBackend backend;
// bool
CheckArrayRepr<bool>("array([False], dtype=bool, device_id=('native', 0))", {false}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<bool>("array([ True], dtype=bool, device_id=('native', 0))", {true}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<bool>(
"array([[False, True, True],\n"
" [ True, False, True]], dtype=bool, device_id=('native', 0))",
{false, true, true, true, false, true}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<bool>("array([[[[ True]]]], dtype=bool, device_id=('native', 0))", {true}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// int8
CheckArrayRepr<int8_t>("array([0], dtype=int8, device_id=('native', 0))", {0}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int8_t>("array([-2], dtype=int8, device_id=('native', 0))", {-2}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int8_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int8, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int8_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int8, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int8_t>("array([[[[3]]]], dtype=int8, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// int16
CheckArrayRepr<int16_t>("array([0], dtype=int16, device_id=('native', 0))", {0}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int16_t>("array([-2], dtype=int16, device_id=('native', 0))", {-2}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int16_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int16, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int16_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int16, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int16_t>("array([[[[3]]]], dtype=int16, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// int32
CheckArrayRepr<int32_t>("array([0], dtype=int32, device_id=('native', 0))", {0}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int32_t>("array([-2], dtype=int32, device_id=('native', 0))", {-2}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int32_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int32, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int32_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int32, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int32_t>("array([[[[3]]]], dtype=int32, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// int64
CheckArrayRepr<int64_t>("array([0], dtype=int64, device_id=('native', 0))", {0}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int64_t>("array([-2], dtype=int64, device_id=('native', 0))", {-2}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<int64_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int64, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int64_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int64, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<int64_t>("array([[[[3]]]], dtype=int64, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// uint8
CheckArrayRepr<uint8_t>("array([0], dtype=uint8, device_id=('native', 0))", {0}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<uint8_t>("array([2], dtype=uint8, device_id=('native', 0))", {2}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<uint8_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=uint8, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<uint8_t>("array([[[[3]]]], dtype=uint8, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// float32
CheckArrayRepr<float>("array([0.], dtype=float32, device_id=('native', 0))", {0}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<float>("array([3.25], dtype=float32, device_id=('native', 0))", {3.25}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<float>("array([-3.25], dtype=float32, device_id=('native', 0))", {-3.25}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<float>("array([ inf], dtype=float32, device_id=('native', 0))", {std::numeric_limits<float>::infinity()}, Shape({1}),
DeviceId{&backend});
CheckArrayRepr<float>("array([ -inf], dtype=float32, device_id=('native', 0))", {-std::numeric_limits<float>::infinity()}, Shape({1}),
DeviceId{&backend});
CheckArrayRepr<float>("array([ nan], dtype=float32, device_id=('native', 0))", {std::nanf("")}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<float>(
"array([[0., 1., 2.],\n"
" [3., 4., 5.]], dtype=float32, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<float>(
"array([[0. , 1. , 2. ],\n"
" [3.25, 4. , 5. ]], dtype=float32, device_id=('native', 0))",
{0, 1, 2, 3.25, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<float>(
"array([[ 0. , 1. , 2. ],\n"
" [-3.25, 4. , 5. ]], dtype=float32, device_id=('native', 0))",
{0, 1, 2, -3.25, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<float>("array([[[[3.25]]]], dtype=float32, device_id=('native', 0))", {3.25}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// float64
CheckArrayRepr<double>("array([0.], dtype=float64, device_id=('native', 0))", {0}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<double>("array([3.25], dtype=float64, device_id=('native', 0))", {3.25}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<double>("array([-3.25], dtype=float64, device_id=('native', 0))", {-3.25}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<double>("array([ inf], dtype=float64, device_id=('native', 0))", {std::numeric_limits<double>::infinity()}, Shape({1}),
DeviceId{&backend});
CheckArrayRepr<double>("array([ -inf], dtype=float64, device_id=('native', 0))", {-std::numeric_limits<double>::infinity()}, Shape({1}),
DeviceId{&backend});
CheckArrayRepr<double>("array([ nan], dtype=float64, device_id=('native', 0))", {std::nan("")}, Shape({1}), DeviceId{&backend});
CheckArrayRepr<double>(
"array([[0., 1., 2.],\n"
" [3., 4., 5.]], dtype=float64, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<double>(
"array([[0. , 1. , 2. ],\n"
" [3.25, 4. , 5. ]], dtype=float64, device_id=('native', 0))",
{0, 1, 2, 3.25, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<double>(
"array([[ 0. , 1. , 2. ],\n"
" [-3.25, 4. , 5. ]], dtype=float64, device_id=('native', 0))",
{0, 1, 2, -3.25, 4, 5}, Shape({2, 3}), DeviceId{&backend});
CheckArrayRepr<double>("array([[[[3.25]]]], dtype=float64, device_id=('native', 0))", {3.25}, Shape({1, 1, 1, 1}), DeviceId{&backend});
// Single graph
CheckArrayRepr<int32_t>("array([-2], dtype=int32, device_id=('native', 0), graph_ids=['graph_1'])", {-2}, Shape({1}),
DeviceId{&backend}, {"graph_1"});
// Two graphs
CheckArrayRepr<int32_t>("array([1], dtype=int32, device_id=('native', 0), graph_ids=['graph_1', 'graph_2'])", {1}, Shape({1}),
DeviceId{&backend}, {"graph_1", "graph_2"});
// Multiple graphs
CheckArrayRepr<int32_t>(
"array([-9], dtype=int32, device_id=('native', 0), graph_ids=['graph_1', 'graph_2', 'graph_3', 'graph_4', 'graph_5'])", {-9},
Shape({1}), DeviceId{&backend}, {"graph_1", "graph_2", "graph_3", "graph_4", "graph_5"});
}
} // namespace
} // namespace xchainer
<commit_msg>Replace DeviceId with Device<commit_after>#include "xchainer/array_repr.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <vector>
#include "xchainer/device.h"
#include "xchainer/native_backend.h"
#include "xchainer/native_device.h"
namespace xchainer {
namespace {
template <typename T>
void CheckArrayRepr(const std::string& expected, const std::vector<T>& data_vec, Shape shape, Device& device,
const std::vector<GraphId> graph_ids = {}) {
// Copy to a contiguous memory block because std::vector<bool> is not packed as a sequence of bool's.
std::shared_ptr<T> data_ptr = std::make_unique<T[]>(data_vec.size());
std::copy(data_vec.begin(), data_vec.end(), data_ptr.get());
Array array = Array::FromBuffer(shape, TypeToDtype<T>, static_cast<std::shared_ptr<void>>(data_ptr), device);
for (const GraphId& graph_id : graph_ids) {
array.RequireGrad(graph_id);
}
// std::string version
EXPECT_EQ(expected, ArrayRepr(array));
// std::ostream version
std::ostringstream os;
os << array;
EXPECT_EQ(expected, os.str());
}
TEST(ArrayReprTest, AllDtypesOnNativeBackend) {
NativeBackend backend;
NativeDevice device{backend, 0};
// bool
CheckArrayRepr<bool>("array([False], dtype=bool, device_id=('native', 0))", {false}, Shape({1}), device);
CheckArrayRepr<bool>("array([ True], dtype=bool, device_id=('native', 0))", {true}, Shape({1}), device);
CheckArrayRepr<bool>(
"array([[False, True, True],\n"
" [ True, False, True]], dtype=bool, device_id=('native', 0))",
{false, true, true, true, false, true}, Shape({2, 3}), device);
CheckArrayRepr<bool>("array([[[[ True]]]], dtype=bool, device_id=('native', 0))", {true}, Shape({1, 1, 1, 1}), device);
// int8
CheckArrayRepr<int8_t>("array([0], dtype=int8, device_id=('native', 0))", {0}, Shape({1}), device);
CheckArrayRepr<int8_t>("array([-2], dtype=int8, device_id=('native', 0))", {-2}, Shape({1}), device);
CheckArrayRepr<int8_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int8, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int8_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int8, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int8_t>("array([[[[3]]]], dtype=int8, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), device);
// int16
CheckArrayRepr<int16_t>("array([0], dtype=int16, device_id=('native', 0))", {0}, Shape({1}), device);
CheckArrayRepr<int16_t>("array([-2], dtype=int16, device_id=('native', 0))", {-2}, Shape({1}), device);
CheckArrayRepr<int16_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int16, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int16_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int16, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int16_t>("array([[[[3]]]], dtype=int16, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), device);
// int32
CheckArrayRepr<int32_t>("array([0], dtype=int32, device_id=('native', 0))", {0}, Shape({1}), device);
CheckArrayRepr<int32_t>("array([-2], dtype=int32, device_id=('native', 0))", {-2}, Shape({1}), device);
CheckArrayRepr<int32_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int32, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int32_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int32, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int32_t>("array([[[[3]]]], dtype=int32, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), device);
// int64
CheckArrayRepr<int64_t>("array([0], dtype=int64, device_id=('native', 0))", {0}, Shape({1}), device);
CheckArrayRepr<int64_t>("array([-2], dtype=int64, device_id=('native', 0))", {-2}, Shape({1}), device);
CheckArrayRepr<int64_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=int64, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int64_t>(
"array([[ 0, 1, 2],\n"
" [-3, 4, 5]], dtype=int64, device_id=('native', 0))",
{0, 1, 2, -3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<int64_t>("array([[[[3]]]], dtype=int64, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), device);
// uint8
CheckArrayRepr<uint8_t>("array([0], dtype=uint8, device_id=('native', 0))", {0}, Shape({1}), device);
CheckArrayRepr<uint8_t>("array([2], dtype=uint8, device_id=('native', 0))", {2}, Shape({1}), device);
CheckArrayRepr<uint8_t>(
"array([[0, 1, 2],\n"
" [3, 4, 5]], dtype=uint8, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<uint8_t>("array([[[[3]]]], dtype=uint8, device_id=('native', 0))", {3}, Shape({1, 1, 1, 1}), device);
// float32
CheckArrayRepr<float>("array([0.], dtype=float32, device_id=('native', 0))", {0}, Shape({1}), device);
CheckArrayRepr<float>("array([3.25], dtype=float32, device_id=('native', 0))", {3.25}, Shape({1}), device);
CheckArrayRepr<float>("array([-3.25], dtype=float32, device_id=('native', 0))", {-3.25}, Shape({1}), device);
CheckArrayRepr<float>("array([ inf], dtype=float32, device_id=('native', 0))", {std::numeric_limits<float>::infinity()}, Shape({1}),
device);
CheckArrayRepr<float>("array([ -inf], dtype=float32, device_id=('native', 0))", {-std::numeric_limits<float>::infinity()}, Shape({1}),
device);
CheckArrayRepr<float>("array([ nan], dtype=float32, device_id=('native', 0))", {std::nanf("")}, Shape({1}), device);
CheckArrayRepr<float>(
"array([[0., 1., 2.],\n"
" [3., 4., 5.]], dtype=float32, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<float>(
"array([[0. , 1. , 2. ],\n"
" [3.25, 4. , 5. ]], dtype=float32, device_id=('native', 0))",
{0, 1, 2, 3.25, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<float>(
"array([[ 0. , 1. , 2. ],\n"
" [-3.25, 4. , 5. ]], dtype=float32, device_id=('native', 0))",
{0, 1, 2, -3.25, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<float>("array([[[[3.25]]]], dtype=float32, device_id=('native', 0))", {3.25}, Shape({1, 1, 1, 1}), device);
// float64
CheckArrayRepr<double>("array([0.], dtype=float64, device_id=('native', 0))", {0}, Shape({1}), device);
CheckArrayRepr<double>("array([3.25], dtype=float64, device_id=('native', 0))", {3.25}, Shape({1}), device);
CheckArrayRepr<double>("array([-3.25], dtype=float64, device_id=('native', 0))", {-3.25}, Shape({1}), device);
CheckArrayRepr<double>("array([ inf], dtype=float64, device_id=('native', 0))", {std::numeric_limits<double>::infinity()}, Shape({1}),
device);
CheckArrayRepr<double>("array([ -inf], dtype=float64, device_id=('native', 0))", {-std::numeric_limits<double>::infinity()}, Shape({1}),
device);
CheckArrayRepr<double>("array([ nan], dtype=float64, device_id=('native', 0))", {std::nan("")}, Shape({1}), device);
CheckArrayRepr<double>(
"array([[0., 1., 2.],\n"
" [3., 4., 5.]], dtype=float64, device_id=('native', 0))",
{0, 1, 2, 3, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<double>(
"array([[0. , 1. , 2. ],\n"
" [3.25, 4. , 5. ]], dtype=float64, device_id=('native', 0))",
{0, 1, 2, 3.25, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<double>(
"array([[ 0. , 1. , 2. ],\n"
" [-3.25, 4. , 5. ]], dtype=float64, device_id=('native', 0))",
{0, 1, 2, -3.25, 4, 5}, Shape({2, 3}), device);
CheckArrayRepr<double>("array([[[[3.25]]]], dtype=float64, device_id=('native', 0))", {3.25}, Shape({1, 1, 1, 1}), device);
// Single graph
CheckArrayRepr<int32_t>("array([-2], dtype=int32, device_id=('native', 0), graph_ids=['graph_1'])", {-2}, Shape({1}),
device, {"graph_1"});
// Two graphs
CheckArrayRepr<int32_t>("array([1], dtype=int32, device_id=('native', 0), graph_ids=['graph_1', 'graph_2'])", {1}, Shape({1}),
device, {"graph_1", "graph_2"});
// Multiple graphs
CheckArrayRepr<int32_t>(
"array([-9], dtype=int32, device_id=('native', 0), graph_ids=['graph_1', 'graph_2', 'graph_3', 'graph_4', 'graph_5'])", {-9},
Shape({1}), device, {"graph_1", "graph_2", "graph_3", "graph_4", "graph_5"});
}
} // namespace
} // namespace xchainer
<|endoftext|>
|
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/searchlib/queryeval/dot_product_search.h>
#include <vespa/searchlib/fef/fef.h>
#include <vespa/searchlib/query/tree/simplequery.h>
#include <vespa/searchlib/queryeval/field_spec.h>
#include <vespa/searchlib/queryeval/blueprint.h>
#include <vespa/searchlib/queryeval/emptysearch.h>
#include <vespa/searchlib/queryeval/fake_result.h>
#include <vespa/searchlib/queryeval/fake_searchable.h>
#include <vespa/searchlib/queryeval/fake_requestcontext.h>
#include <vespa/searchlib/test/weightedchildrenverifiers.h>
using namespace search;
using namespace search::query;
using namespace search::fef;
using namespace search::queryeval;
using search::test::SearchIteratorVerifier;
using search::test::DocumentWeightAttributeHelper;
namespace {
void setupFakeSearchable(FakeSearchable &fake) {
for (size_t docid = 1; docid < 10; ++docid) {
std::string token1 = vespalib::make_string("%zu", docid);
std::string token2 = vespalib::make_string("1%zu", docid);
std::string token3 = vespalib::make_string("2%zu", docid);
fake.addResult("field", token1, FakeResult().doc(docid).weight(docid).pos(0));
fake.addResult("multi-field", token1, FakeResult().doc(docid).weight(docid).pos(0));
fake.addResult("multi-field", token2, FakeResult().doc(docid).weight(2 * docid).pos(0));
fake.addResult("multi-field", token3, FakeResult().doc(docid).weight(3 * docid).pos(0));
}
}
struct DP {
static const uint32_t fieldId = 0;
static const TermFieldHandle handle = 0;
std::vector<std::pair<std::string, uint32_t> > tokens;
DP &add(const std::string &token, uint32_t weight) {
tokens.push_back(std::make_pair(token, weight));
return *this;
}
Node::UP createNode() const {
SimpleDotProduct *node = new SimpleDotProduct("view", 0, Weight(0));
for (size_t i = 0; i < tokens.size(); ++i) {
node->append(Node::UP(new SimpleStringTerm(tokens[i].first, "view", 0, Weight(tokens[i].second))));
}
return Node::UP(node);
}
FakeResult search(Searchable &searchable, const std::string &field, bool strict) const {
MatchData::UP md(MatchData::makeTestInstance(1, 1));
FakeRequestContext requestContext;
Node::UP node = createNode();
FieldSpecList fields = FieldSpecList().add(FieldSpec(field, fieldId, handle));
queryeval::Blueprint::UP bp = searchable.createBlueprint(requestContext, fields, *node);
bp->fetchPostings(strict);
SearchIterator::UP sb = bp->createSearch(*md, strict);
EXPECT_TRUE(dynamic_cast<DotProductSearch*>(sb.get()) != 0);
sb->initFullRange();
FakeResult result;
for (uint32_t docId = 1; docId < 10; ++docId) {
if (sb->seek(docId)) {
sb->unpack(docId);
result.doc(docId);
double score = md->resolveTermField(handle)->getRawScore();
EXPECT_EQUAL((int)score, score);
result.score(score);
}
}
return result;
}
};
struct MockSearch : public SearchIterator {
int seekCnt;
uint32_t _initial;
MockSearch(uint32_t initial) : SearchIterator(), seekCnt(0), _initial(initial) { }
void initRange(uint32_t begin, uint32_t end) override {
SearchIterator::initRange(begin, end);
setDocId(_initial);
}
virtual void doSeek(uint32_t) {
++seekCnt;
setAtEnd();
}
virtual void doUnpack(uint32_t) {}
};
struct MockFixture {
MockSearch *mock;
TermFieldMatchData tfmd;
std::unique_ptr<SearchIterator> search;
MockFixture(uint32_t initial) :
MockFixture(initial, {new EmptySearch()})
{ }
MockFixture(uint32_t initial, std::vector<SearchIterator *> children) : mock(0), tfmd(), search() {
std::vector<TermFieldMatchData*> childMatch;
std::vector<int32_t> weights;
const size_t numChildren(children.size()+1);
MatchData::UP md(MatchData::makeTestInstance(numChildren, numChildren));
for (size_t i(0); i < children.size(); i++) {
childMatch.push_back(md->resolveTermField(i));
weights.push_back(1);
}
mock = new MockSearch(initial);
childMatch.push_back(md->resolveTermField(children.size()));
children.push_back(mock);
weights.push_back(1);
search = DotProductSearch::create(children, tfmd, childMatch, weights, std::move(md));
}
};
} // namespace <unnamed>
TEST("test Simple") {
FakeSearchable index;
setupFakeSearchable(index);
FakeResult expect = FakeResult()
.doc(3).score(30 * 3)
.doc(5).score(50 * 5)
.doc(7).score(70 * 7);
DP ws = DP().add("7", 70).add("5", 50).add("3", 30).add("100", 1000);
EXPECT_EQUAL(expect, ws.search(index, "field", true));
EXPECT_EQUAL(expect, ws.search(index, "field", false));
EXPECT_EQUAL(expect, ws.search(index, "multi-field", true));
EXPECT_EQUAL(expect, ws.search(index, "multi-field", false));
}
TEST("test Multi") {
FakeSearchable index;
setupFakeSearchable(index);
FakeResult expect = FakeResult()
.doc(3).score(30 * 3 + 130 * 2 * 3 + 230 * 3 * 3)
.doc(5).score(50 * 5 + 150 * 2 * 5)
.doc(7).score(70 * 7);
DP ws = DP().add("7", 70).add("5", 50).add("3", 30)
.add("15", 150).add("13", 130)
.add("23", 230).add("100", 1000);
EXPECT_EQUAL(expect, ws.search(index, "multi-field", true));
EXPECT_EQUAL(expect, ws.search(index, "multi-field", false));
}
TEST_F("test Eager Single Empty Child", MockFixture(search::endDocId, {})) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_TRUE(search.isAtEnd());
EXPECT_EQUAL(0, mock->seekCnt);
}
TEST_F("test Multiple Eager Empty Children", MockFixture(search::endDocId)) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_EQUAL(search.beginId(), search.getDocId());
EXPECT_TRUE(!search.seek(1));
EXPECT_TRUE(search.isAtEnd());
EXPECT_EQUAL(0, mock->seekCnt);
}
void verifyEagerMatching(SearchIterator & search, MockSearch * mock) {
EXPECT_TRUE(!search.seek(3));
EXPECT_EQUAL(5u, search.getDocId());
EXPECT_EQUAL(0, mock->seekCnt);
EXPECT_TRUE(search.seek(5));
EXPECT_EQUAL(5u, search.getDocId());
EXPECT_EQUAL(0, mock->seekCnt);
EXPECT_TRUE(!search.seek(7));
EXPECT_TRUE(search.isAtEnd());
EXPECT_EQUAL(1, mock->seekCnt);
}
TEST_F("test Eager Single Matching Child", MockFixture(5, {})) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_EQUAL(5u, search.getDocId());
verifyEagerMatching(search, mock);
}
TEST_F("test Eager Matching Children", MockFixture(5)) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_EQUAL(search.beginId(), search.getDocId());
verifyEagerMatching(search, mock);
}
class IteratorChildrenVerifier : public search::test::IteratorChildrenVerifier {
private:
SearchIterator::UP create(const std::vector<SearchIterator*> &children) const override {
std::vector<fef::TermFieldMatchData*> no_child_match;
MatchData::UP no_match_data;
return DotProductSearch::create(children, _tfmd, no_child_match, _weights, std::move(no_match_data));
}
};
class WeightIteratorChildrenVerifier : public search::test::DwaIteratorChildrenVerifier {
private:
SearchIterator::UP create(std::vector<DocumentWeightIterator> && children) const override {
return SearchIterator::UP(DotProductSearch::create(_tfmd, _weights, std::move(children)));
}
};
TEST("verify search iterator conformance with search iterator children") {
IteratorChildrenVerifier verifier;
verifier.verify();
}
TEST("verify search iterator conformance with document weight iterator children") {
WeightIteratorChildrenVerifier verifier;
verifier.verify();
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Unify naming<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/testapp.h>
#include <vespa/searchlib/queryeval/dot_product_search.h>
#include <vespa/searchlib/fef/fef.h>
#include <vespa/searchlib/query/tree/simplequery.h>
#include <vespa/searchlib/queryeval/field_spec.h>
#include <vespa/searchlib/queryeval/blueprint.h>
#include <vespa/searchlib/queryeval/emptysearch.h>
#include <vespa/searchlib/queryeval/fake_result.h>
#include <vespa/searchlib/queryeval/fake_searchable.h>
#include <vespa/searchlib/queryeval/fake_requestcontext.h>
#include <vespa/searchlib/test/weightedchildrenverifiers.h>
using namespace search;
using namespace search::query;
using namespace search::fef;
using namespace search::queryeval;
using search::test::SearchIteratorVerifier;
using search::test::DocumentWeightAttributeHelper;
namespace {
void setupFakeSearchable(FakeSearchable &fake) {
for (size_t docid = 1; docid < 10; ++docid) {
std::string token1 = vespalib::make_string("%zu", docid);
std::string token2 = vespalib::make_string("1%zu", docid);
std::string token3 = vespalib::make_string("2%zu", docid);
fake.addResult("field", token1, FakeResult().doc(docid).weight(docid).pos(0));
fake.addResult("multi-field", token1, FakeResult().doc(docid).weight(docid).pos(0));
fake.addResult("multi-field", token2, FakeResult().doc(docid).weight(2 * docid).pos(0));
fake.addResult("multi-field", token3, FakeResult().doc(docid).weight(3 * docid).pos(0));
}
}
struct DP {
static const uint32_t fieldId = 0;
static const TermFieldHandle handle = 0;
std::vector<std::pair<std::string, uint32_t> > tokens;
DP &add(const std::string &token, uint32_t weight) {
tokens.push_back(std::make_pair(token, weight));
return *this;
}
Node::UP createNode() const {
SimpleDotProduct *node = new SimpleDotProduct("view", 0, Weight(0));
for (size_t i = 0; i < tokens.size(); ++i) {
node->append(Node::UP(new SimpleStringTerm(tokens[i].first, "view", 0, Weight(tokens[i].second))));
}
return Node::UP(node);
}
FakeResult search(Searchable &searchable, const std::string &field, bool strict) const {
MatchData::UP md(MatchData::makeTestInstance(1, 1));
FakeRequestContext requestContext;
Node::UP node = createNode();
FieldSpecList fields = FieldSpecList().add(FieldSpec(field, fieldId, handle));
queryeval::Blueprint::UP bp = searchable.createBlueprint(requestContext, fields, *node);
bp->fetchPostings(strict);
SearchIterator::UP sb = bp->createSearch(*md, strict);
EXPECT_TRUE(dynamic_cast<DotProductSearch*>(sb.get()) != 0);
sb->initFullRange();
FakeResult result;
for (uint32_t docId = 1; docId < 10; ++docId) {
if (sb->seek(docId)) {
sb->unpack(docId);
result.doc(docId);
double score = md->resolveTermField(handle)->getRawScore();
EXPECT_EQUAL((int)score, score);
result.score(score);
}
}
return result;
}
};
struct MockSearch : public SearchIterator {
int seekCnt;
uint32_t _initial;
MockSearch(uint32_t initial) : SearchIterator(), seekCnt(0), _initial(initial) { }
void initRange(uint32_t begin, uint32_t end) override {
SearchIterator::initRange(begin, end);
setDocId(_initial);
}
virtual void doSeek(uint32_t) {
++seekCnt;
setAtEnd();
}
virtual void doUnpack(uint32_t) {}
};
struct MockFixture {
MockSearch *mock;
TermFieldMatchData tfmd;
std::unique_ptr<SearchIterator> search;
MockFixture(uint32_t initial) :
MockFixture(initial, {new EmptySearch()})
{ }
MockFixture(uint32_t initial, std::vector<SearchIterator *> children) : mock(0), tfmd(), search() {
std::vector<TermFieldMatchData*> childMatch;
std::vector<int32_t> weights;
const size_t numChildren(children.size()+1);
MatchData::UP md(MatchData::makeTestInstance(numChildren, numChildren));
for (size_t i(0); i < children.size(); i++) {
childMatch.push_back(md->resolveTermField(i));
weights.push_back(1);
}
mock = new MockSearch(initial);
childMatch.push_back(md->resolveTermField(children.size()));
children.push_back(mock);
weights.push_back(1);
search = DotProductSearch::create(children, tfmd, childMatch, weights, std::move(md));
}
};
} // namespace <unnamed>
TEST("test Simple") {
FakeSearchable index;
setupFakeSearchable(index);
FakeResult expect = FakeResult()
.doc(3).score(30 * 3)
.doc(5).score(50 * 5)
.doc(7).score(70 * 7);
DP ws = DP().add("7", 70).add("5", 50).add("3", 30).add("100", 1000);
EXPECT_EQUAL(expect, ws.search(index, "field", true));
EXPECT_EQUAL(expect, ws.search(index, "field", false));
EXPECT_EQUAL(expect, ws.search(index, "multi-field", true));
EXPECT_EQUAL(expect, ws.search(index, "multi-field", false));
}
TEST("test Multi") {
FakeSearchable index;
setupFakeSearchable(index);
FakeResult expect = FakeResult()
.doc(3).score(30 * 3 + 130 * 2 * 3 + 230 * 3 * 3)
.doc(5).score(50 * 5 + 150 * 2 * 5)
.doc(7).score(70 * 7);
DP ws = DP().add("7", 70).add("5", 50).add("3", 30)
.add("15", 150).add("13", 130)
.add("23", 230).add("100", 1000);
EXPECT_EQUAL(expect, ws.search(index, "multi-field", true));
EXPECT_EQUAL(expect, ws.search(index, "multi-field", false));
}
TEST_F("test Eager Empty Child", MockFixture(search::endDocId, {})) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_TRUE(search.isAtEnd());
EXPECT_EQUAL(0, mock->seekCnt);
}
TEST_F("test Eager Empty Children", MockFixture(search::endDocId)) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_EQUAL(search.beginId(), search.getDocId());
EXPECT_TRUE(!search.seek(1));
EXPECT_TRUE(search.isAtEnd());
EXPECT_EQUAL(0, mock->seekCnt);
}
void verifyEagerMatching(SearchIterator & search, MockSearch * mock) {
EXPECT_TRUE(!search.seek(3));
EXPECT_EQUAL(5u, search.getDocId());
EXPECT_EQUAL(0, mock->seekCnt);
EXPECT_TRUE(search.seek(5));
EXPECT_EQUAL(5u, search.getDocId());
EXPECT_EQUAL(0, mock->seekCnt);
EXPECT_TRUE(!search.seek(7));
EXPECT_TRUE(search.isAtEnd());
EXPECT_EQUAL(1, mock->seekCnt);
}
TEST_F("test Eager Matching Child", MockFixture(5, {})) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_EQUAL(5u, search.getDocId());
verifyEagerMatching(search, mock);
}
TEST_F("test Eager Matching Children", MockFixture(5)) {
MockSearch *mock = f1.mock;
SearchIterator &search = *f1.search;
search.initFullRange();
EXPECT_EQUAL(search.beginId(), search.getDocId());
verifyEagerMatching(search, mock);
}
class IteratorChildrenVerifier : public search::test::IteratorChildrenVerifier {
private:
SearchIterator::UP create(const std::vector<SearchIterator*> &children) const override {
std::vector<fef::TermFieldMatchData*> no_child_match;
MatchData::UP no_match_data;
return DotProductSearch::create(children, _tfmd, no_child_match, _weights, std::move(no_match_data));
}
};
class WeightIteratorChildrenVerifier : public search::test::DwaIteratorChildrenVerifier {
private:
SearchIterator::UP create(std::vector<DocumentWeightIterator> && children) const override {
return SearchIterator::UP(DotProductSearch::create(_tfmd, _weights, std::move(children)));
}
};
TEST("verify search iterator conformance with search iterator children") {
IteratorChildrenVerifier verifier;
verifier.verify();
}
TEST("verify search iterator conformance with document weight iterator children") {
WeightIteratorChildrenVerifier verifier;
verifier.verify();
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>
|
<commit_before>// FRAGMENT(includes)
#include <iostream>
#include <seqan/store.h>
#include <seqan/misc/misc_svg.h>
using namespace seqan;
int main ()
{
FragmentStore<> store;
loadContigs(store, "ex1.fa");
std::ifstream file("ex1.sam");
read(file, store, Sam());
// FRAGMENT(ascii)
AlignedReadLayout layout;
layoutAlignment(layout, store);
printAlignment(std::cout, Raw(), layout, store, 1, 0, 150, 0, 36);
// FRAGMENT(svg)
SVGFile svg("layout.svg");
printAlignment(svg, Raw(), layout, store, 1, 0, 150, 0, 36);
return 0;
}
<commit_msg><commit_after>// FRAGMENT(includes)
#include <iostream>
#include <seqan/store.h>
#include <seqan/misc/misc_svg.h>
using namespace seqan;
int main ()
{
FragmentStore<> store;
loadContigs(store, "ex1.fa");
std::ifstream file("ex1.sam");
read(file, store, Sam());
// FRAGMENT(ascii)
AlignedReadLayout layout;
layoutAlignment(layout, store);
printAlignment(std::cout, Raw(), layout, store, 1, 0, 150, 0, 36);
// FRAGMENT(svg)
SVGFile svg("layout.svg");
printAlignment(svg, Raw(), layout, store, 1, 0, 150, 0, 36);
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
typedef tuple<int, int, int> state; // now, from, clr
typedef tuple<int, int> cond; // now, depth
ll N;
ll M;
vector<int> V[100010];
int main () {
cin >> N >> M;
for (auto i = 0; i < M; ++i) {
int a, b;
cin >> a >> b;
--a, --b;
V[a].push_back(b);
V[b].push_back(a);
}
for (auto i = 0; i < N; ++i) {
random_shuffle(V[i].begin(), V[i].end());
}
int visited[100010];
fill(visited, visited+100010, 0);
int color[100010];
fill(color, color+100010, 0);
int parent[100010];
stack<state> S;
S.push(state(0, -1, 1));
while (!S.empty()) {
int now = get<0>(S.top());
int from = get<1>(S.top());
int clr = get<2>(S.top());
// cerr << "now = " << now << ", from = " << from << endl;
S.pop();
if (visited[now] == 0) {
visited[now] = true;
parent[now] = from;
color[now] = clr;
// cerr << "parent[" << now << "] = " << from << endl;
S.push(state(now, now, 3-clr));
for (auto x : V[now]) {
if (x != parent[now]) {
S.push(state(x, now, 3-clr));
}
}
} else if (visited[now] == 1) {
if (from != now) {
if (color[now] == clr) continue;
color[now] = 3;
color[from] = 3;
int back = parent[from];
while (back != now) {
color[back] = 3;
back = parent[back];
}
} else {
visited[now] = 2;
}
}
}
for (auto i = 0; i < 100010; ++i) {
visited[i] = (color[i] == 3);
}
ll ans = 0;
for (auto i = 0; i < N; ++i) {
if (visited[i]) continue;
stack<cond> SS;
SS.push(cond(i, 0));
ll cnt[2] = {0, 0};
while (!SS.empty()) {
int now = get<0>(SS.top());
int depth = get<1>(SS.top());
SS.pop();
if (!visited[now]) {
visited[now] = true;
cnt[depth%2]++;
for (auto x : V[now]) {
if (!visited[x]) {
SS.push(cond(x, depth+1));
}
}
}
}
ans += cnt[0] * cnt[1];
}
ll L = 0;
for (auto i = 0; i < N; ++i) {
if (color[i] == 3) L++;
}
cerr << "L = " << L << endl;
ans += L * (L-1) / 2 + L * (N-L) - M;
cout << ans << endl;
}
<commit_msg>submit C.cpp to 'C - 3 Steps' (code-festival-2017-qualb) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
typedef tuple<int, int, int> state; // now, from, clr
typedef tuple<int, int> cond; // now, depth
ll N;
ll M;
vector<int> V[100010];
int main () {
cin >> N >> M;
for (auto i = 0; i < M; ++i) {
int a, b;
cin >> a >> b;
--a, --b;
V[a].push_back(b);
V[b].push_back(a);
}
for (auto i = 0; i < N; ++i) {
random_shuffle(V[i].begin(), V[i].end());
}
int visited[100010];
fill(visited, visited+100010, 0);
int color[100010];
fill(color, color+100010, 0);
int parent[100010];
stack<state> S;
S.push(state(0, -1, 1));
while (!S.empty()) {
int now = get<0>(S.top());
int from = get<1>(S.top());
int clr = get<2>(S.top());
// cerr << "now = " << now << ", from = " << from << endl;
S.pop();
if (visited[now] == 0) {
visited[now] = true;
parent[now] = from;
color[now] = clr;
// cerr << "parent[" << now << "] = " << from << endl;
S.push(state(now, now, 3-clr));
for (auto x : V[now]) {
if (x != parent[now]) {
S.push(state(x, now, 3-clr));
}
}
} else if (visited[now] == 1) {
if (from != now) {
if (color[now] == clr) continue;
color[now] = 3;
color[from] = 3;
int back = parent[from];
while (back != now) {
color[back] = 3;
back = parent[back];
}
} else {
visited[now] = 2;
}
}
}
for (auto i = 0; i < 100010; ++i) {
visited[i] = (color[i] == 3);
}
ll L = 0;
for (auto i = 0; i < N; ++i) {
if (color[i] == 3) L++;
}
ll ans = 0;
for (auto i = 0; i < N; ++i) {
if (visited[i]) continue;
stack<cond> SS;
SS.push(cond(i, 0));
ll cnt[2] = {0, 0};
while (!SS.empty()) {
int now = get<0>(SS.top());
int depth = get<1>(SS.top());
SS.pop();
if (!visited[now]) {
visited[now] = true;
cnt[depth%2]++;
for (auto x : V[now]) {
if (!visited[x]) {
SS.push(cond(x, depth+1));
}
}
}
}
ans += cnt[0] * cnt[1];
ll wa = cnt[0] + cnt[1];
ans += (N - wa) * wa;
}
cerr << "L = " << L << endl;
ans += L * (L-1) / 2 - M;
cout << ans << endl;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string S;
int main () {
cin >> S;
int N = S.size();
int cnt[26];
fill(cnt, cnt+26, 0);
for (auto x : S) {
cnt[x - 'a']++;
}
int ans = 0;
for (auto i = 0; i < 26; ++i) {
if (cnt[i] % 2 == 1) {
ans++;
}
}
bool has_edge = false;
if (cnt[S[0] - 'a'] % 2 == 1) {
has_edge = true;
}
if (cnt[S[N-1] - 'a'] % 2 == 1) {
has_edge = true;
}
for (auto i = 0; i < N-1; ++i) {
if (S[i] != S[i+1]
&& cnt[S[i] - 'a'] % 2 == 1
&& cnt[S[i+1] - 'a'] % 2 == 1) {
has_edge = true;
break;
}
}
if (has_edge) {
cout << ans << endl;
} else {
cout << ans + 1 << endl;
}
}
<commit_msg>tried D.cpp to 'D'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
string S;
int num[200010];
int main () {
cin >> S;
int N = S.size();
int cnt[26];
fill(cnt, cnt+26, 0);
for (auto x : S) {
cnt[x - 'a']++;
}
int ans = 0;
for (auto i = 0; i < 26; ++i) {
if (cnt[i] % 2 == 1) {
ans++;
}
}
for (auto i = 0; i < 26; ++i) {
char c = (char)('a' + i);
int l = 0;
for (auto j = 0; j < N; ++j) {
if (S[j] == c) num[j] = l;
l++;
}
}
bool has_edge = false;
if (cnt[S[0] - 'a'] % 2 == 1) {
has_edge = true;
}
if (cnt[S[N-1] - 'a'] % 2 == 1) {
has_edge = true;
}
for (auto i = 0; i < N-1; ++i) {
if (S[i] != S[i+1]
&& num[i] % 2 == 0
&& num[i+1] % 2 == 0
&& cnt[S[i] - 'a'] % 2 == 1
&& cnt[S[i+1] - 'a'] % 2 == 1) {
has_edge = true;
break;
}
}
if (has_edge) {
cout << ans << endl;
} else {
cout << ans + 1 << endl;
}
}
<|endoftext|>
|
<commit_before>// Time: O(max(m, n))
// Space: O(1)
class Solution { // TLE
public:
/**
* @param A: An integer matrix
* @return: The index of the peak
*/
vector<int> findPeakII(vector<vector<int> > A) {
int upper = 0;
int down = A.size() - 1;
int left = 0;
int right = A[0].size() - 1;
while (upper < down && left < right) {
int height = upper - down + 1;
int width = right - left + 1;
if (width > height) { // Vertical split.
int mid_j = left + (right - left) / 2;
int left_max = 0;
int central_max = 0;
int right_max = 0;
int max_i = 0;
int max_j = 0;
for (int i = upper + 1; i < down; ++i) {
if (A[i][mid_j] > central_max) {
max_i = i;
max_j = mid_j;
central_max = A[i][mid_j];
}
left_max = max(left_max, A[i][mid_j - 1]);
right_max = max(right_max, A[i][mid_j + 1]);
}
if (left_max > central_max && left_max > right_max) {
right = mid_j;
} else if (right_max > central_max && right_max > left_max) {
left = mid_j;
} else {
return {max_i, max_j};
}
} else { // Horizontal split.
int mid_i = upper + (down - upper) / 2;
int upper_max = 0;
int central_max = 0;
int down_max = 0;
int max_i = 0;
int max_j = 0;
for (int j = left + 1; j < right; ++j) {
if (A[mid_i][j] > central_max) {
max_i = mid_i;
max_j = j;
central_max = A[mid_i][j];
}
upper_max = max(upper_max, A[mid_i - 1][j]);
down_max = max(down_max, A[mid_i + 1][j]);
}
if (upper_max > central_max && upper_max > down_max) {
down = mid_i;
} else if (down_max > central_max && down_max > upper_max) {
upper = mid_i;
} else {
return {max_i, max_j};
}
}
}
return {-1, -1};
}
};
<commit_msg>Update find-peak-element-ii.cpp<commit_after>// Time: O(max(m, n))
// Space: O(1)
class Solution { // TLE
public:
/**
* @param A: An integer matrix
* @return: The index of the peak
*/
vector<int> findPeakII(vector<vector<int> > A) {
int upper = 0, down = A.size() - 1;
int left = 0, right = A[0].size() - 1;
while (upper < down && left < right) {
int height = upper - down + 1;
int width = right - left + 1;
if (width > height) { // Vertical split.
int mid_j = left + (right - left) / 2;
int left_max = 0, central_max = 0, right_max = 0;
int max_i = 0, max_j = 0;
for (int i = upper + 1; i < down; ++i) {
if (A[i][mid_j] > central_max) {
max_i = i;
max_j = mid_j;
central_max = A[i][mid_j];
}
left_max = max(left_max, A[i][mid_j - 1]);
right_max = max(right_max, A[i][mid_j + 1]);
}
if (left_max > central_max && left_max > right_max) {
right = mid_j;
} else if (right_max > central_max && right_max > left_max) {
left = mid_j;
} else {
return {max_i, max_j};
}
} else { // Horizontal split.
int mid_i = upper + (down - upper) / 2;
int upper_max = 0, central_max = 0, down_max = 0;
int max_i = 0, max_j = 0;
for (int j = left + 1; j < right; ++j) {
if (A[mid_i][j] > central_max) {
max_i = mid_i;
max_j = j;
central_max = A[mid_i][j];
}
upper_max = max(upper_max, A[mid_i - 1][j]);
down_max = max(down_max, A[mid_i + 1][j]);
}
if (upper_max > central_max && upper_max > down_max) {
down = mid_i;
} else if (down_max > central_max && down_max > upper_max) {
upper = mid_i;
} else {
return {max_i, max_j};
}
}
}
return {-1, -1};
}
};
<|endoftext|>
|
<commit_before>/*
To use .lib file, go to Project > References... > Configuration Properties > Linker >
> General > Additional Library directories | add the directory the .lib is in.
Then go to Project > References... > Configuration Properties > Linker > Input > Additional dependencies |
add the name of the .lib file ("<name>.lib")
*/
/*
Image taking proccess is currently under a second, compare efficiency of GUI verses our technique
*/
#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <windows.h>
#include <string>
#include <sstream>
#include <time.h>
#include "SXUSB.h"
#include "longnam.h"
#include "fitsio.h"
#define NUMBER_OF_CAMERAS 1
#define PIXEL_WIDTH 1392
#define PIXEL_HEIGHT 1040
#define OBJECT "allsky"
#define TELESCOP ""
#define ORIGIN ""
#define INSTRUME "Starlight Xpress Oculus"
#define OBSERVER "UMD Observatory"
#define TEMPLATE "!IMG%05d.fits"
int takeStandardImage(HANDLE handle, int camIndex, ULONG exposure, USHORT *pixelArray);
int writeImage(HANDLE handle, int camIndex, USHORT *pixelArray, std::string path, ULONG exposure);
int writeMultipleImages(HANDLE handle, int camIndex, USHORT *pixelArray, std::string path, ULONG exposure, int images);
int writeVariableExposureImages(HANDLE handle, int camIndex, USHORT *pixelArray, std::string path);
int numDigits(int number);
std::string getDate();
std::string getTime();
std::string NumberToString(int number);
/* declare these out here so that memory is stored in the heap */
USHORT pixels[PIXEL_WIDTH * PIXEL_HEIGHT];
/* constants */
short const BITPIX = USHORT_IMG;
short const NAXIS = 2;
short const NAXIS1 = PIXEL_HEIGHT;
short const NAXIS2 = PIXEL_WIDTH;
long NAXES[2] = {PIXEL_WIDTH, PIXEL_HEIGHT}; /* purposely missing const */
int main()
{
/* local variables */
HANDLE handles[NUMBER_OF_CAMERAS];
t_sxccd_params params[NUMBER_OF_CAMERAS];
long firmwareVersions[NUMBER_OF_CAMERAS];
int openVal, cameraModels[NUMBER_OF_CAMERAS];
/* open the connected cameras */
openVal = sxOpen(handles);
printf("Opened Cameras: %d\n", openVal);
/* error check the number of cameras */
if (openVal > NUMBER_OF_CAMERAS){
printf("MORE CAMERAS CONNECTED (%d) THAN SPECIFIED BY CODE (%d)\nTERMINATING PROGRAM\n", openVal, NUMBER_OF_CAMERAS);
return 0;
}
if (openVal < NUMBER_OF_CAMERAS){
printf("LESS CAMERAS CONNECTED (%d) THAN SPECIFIED BY CODE (%d)\nCODE WILL RUN, MEMEORY WILL BE WASTED\n", openVal, NUMBER_OF_CAMERAS);
}
/* Get and display camera information */
for (int i = 0; i < openVal; i++){
printf("Camera %d:\n", i);
printf("\tCamera Firmware Version: %d\n", (firmwareVersions[i] = sxGetFirmwareVersion(handles[i])));
printf("\tCamera Model: %d\n", (cameraModels[i] = sxGetCameraModel(handles[i])));
sxGetCameraParams(handles[i], i, params);
}
/* Taking an Image */
writeMultipleImages(handles[0], 0, pixels, "", 50, 5);
return 0;
}
/**
Takes an image with a connected camera. The camera exposes for the given time and then reads the image into pixels
@param exposure - this is measured in milliseconds
@return - 1 if the image was taken correctly, 0 if the image had an error. Will attempt to print error message.
*/
int takeStandardImage(HANDLE handle, int camIndex, ULONG exposure, USHORT *pixelArray){
try{
int bytesRead;
/* clear pixels on the camera and expose them to take the image */
sxClearPixels(handle, 0x00, camIndex);
sxExposePixels(handle, 0x8B, camIndex, 0, 0, PIXEL_WIDTH, PIXEL_HEIGHT, 1, 1, exposure);
/* read the pixels from the camera into an array */
if ((bytesRead = sxReadPixels(handle, pixelArray, PIXEL_WIDTH * PIXEL_HEIGHT)) <= 0){
printf("Error reading pixels\n");
return 0;
}
}
catch(int e){
printf("Error while taking image. Error number: %d\n", e);
return 0;
}
return 1;
}
/**
attempts to take multiple images with the camera stored in handle with an index of camIndex. This function will expose, read, and write the images
on its own.
@return - number of images successfully written.
*/
int writeMultipleImages(HANDLE handle, int camIndex, USHORT *pixelArray, std::string path, ULONG exposure, int images){
int imagesTaken = 0;
char newPath[20];
for (int i = 0; i < images; i++){
try{
/* IMGxxxxx.fits */
sprintf_s(newPath, 20, TEMPLATE, imagesTaken);
writeImage(handle, camIndex, pixelArray, newPath, exposure);
}
catch(int e){
printf("CAUGHT ERROR %d while taking multiple images, stopped after %d images\n", e, imagesTaken);
return imagesTaken;
}
imagesTaken++;
}
return imagesTaken;
}
/**
writes image to given pixelArray to path (NOTE: path does not include extension, that is added by the function).
@return - 0 if failed, 1 if successfully wrote image.
*/
int writeImage(HANDLE handle, int camIndex, USHORT *pixelArray, std::string path, ULONG exposure){
takeStandardImage(handle, 0, exposure, pixels);
/* set up a fits file with proper hdu to write to a file */
fitsfile *file;
int status = 0;
const char *newPath = path.c_str();
if (fits_create_file(&file, newPath, &status)){
/*fits_report_error(stdout, status);*/
printf("status: %d\n", status);
}
/* basic header information (BITPIX, NAXIS, NAXES, etc) is taken care of through this function as well) */
if (fits_create_img(file, BITPIX, NAXIS, NAXES, &status)){
fits_report_error(stdout, status);
}
/* extended header information */
if (fits_write_key(file, TSTRING, "OBJECT", OBJECT, "", &status)){
fits_report_error(stderr, status);
}
if (fits_write_key(file, TSTRING, "TELESCOP", TELESCOP, "", &status)){
fits_report_error(stderr, status);
}
if (fits_write_key(file, TSTRING, "ORIGIN", ORIGIN, "", &status)){
fits_report_error(stderr, status);
}
if (fits_write_key(file, TSTRING, "INSTRUME", INSTRUME, "", &status)){
fits_report_error(stderr, status);
}
if (fits_write_key(file, TSTRING, "OBSERVER", OBSERVER, "", &status)){
fits_report_error(stderr, status);
}
/* find the current time and write it to a keyword */
std::string date = getDate();
std::string time = getTime();
if (fits_write_key(file, TSTRING, "DATE-OBS", (void *) date.c_str(), "", &status)){
fits_report_error(stderr, status);
}
if (fits_write_key(file, TSTRING, "TIME-OBS", (void *) time.c_str(), "", &status)){
fits_report_error(stderr, status);
}
/* write the image data to the file */
if (fits_write_img(file, TUSHORT, 1, PIXEL_HEIGHT * PIXEL_WIDTH, pixels, &status)){
fits_report_error(stderr, status);
}
/* close the file */
if (fits_close_file(file, &status)){
fits_report_error(stdout, status);
}
return 1;
}
/**
returns number of digits in an int
*/
int numDigits(int number){
int length = 1;
while ( number /= 10 )
length++;
return length;
}
std::string getTime(){
time_t rawtime;
struct tm * ptm;
time(&rawtime);
/* pointer to time object with UTC time */
ptm = gmtime(&rawtime);
;
int hours = ptm->tm_hour;
int minutes = ptm->tm_min;
int seconds = ptm->tm_sec;
/* pad the hours, minutes, seconds with a zero if its only 1 digit long eg. 0-9) */
std::string h = std::string(2 - numDigits(hours), '0').append(NumberToString(hours));
std::string m = std::string(2 - numDigits(minutes), '0').append(NumberToString(minutes));
std::string s = std::string(2 - numDigits(seconds), '0').append(NumberToString(seconds));
std::string time = h + ":" + m + ":" + s;
//@TODO check if seconds could contain the fractional seconds as well
return time;
}
std::string getDate(){
time_t rawtime;
struct tm * ptm;
time(&rawtime);
/* pointer to time object with UTC time */
ptm = gmtime(&rawtime);
int year = ptm->tm_year + 1900; /* ptm->tm_year == years since 1900 */
int month = ptm->tm_mon + 1;
int day = ptm->tm_mday;
/* pad the months with a zero if its only 1 digit long eg. 0-9) */
std::string y = NumberToString(year);
std::string m = std::string(2 - numDigits(month), '0').append(NumberToString(month));
std::string d = NumberToString(day);
std::string date = y + "-" + m + "-" + d;
return date;
}
std::string NumberToString(int Number)
{
std::stringstream ss;
ss << Number;
return ss.str();
}<commit_msg>Struct implementation for parameters<commit_after>/*
To use .lib file, go to Project > References... > Configuration Properties > Linker >
> General > Additional Library directories | add the directory the .lib is in.
Then go to Project > References... > Configuration Properties > Linker > Input > Additional dependencies |
add the name of the .lib file ("<name>.lib")
*/
/*
Image taking proccess is currently under a second, compare efficiency of GUI verses our technique
*/
/* TODO:
- Allow users to input date format using strptime()
- Make a Makefile to make building project with other compilers
*/
#include "stdafx.h"
#include <cstdio>
#include <direct.h>
#include "fitsio.h"
#include "getopt.h"
#include <iostream>
#include "longnam.h"
#include <sstream>
#include "Shlwapi.h"
#include <string>
#include <time.h>
#include "SXUSB.h"
#include <Windows.h>
/* for camera */
#define NUMBER_OF_CAMERAS 1
#define PIXEL_WIDTH 1392
#define PIXEL_HEIGHT 1040
/* for hdus */
#define OBJECT "allsky"
#define ORIGIN ""
#define TELESCOP ""
#define INSTRUME "Starlight Xpress Oculus"
#define OBSERVER "UMD Observatory"
/* path info */
#ifdef MAX_PATH
#define MAX_FILE_LEN MAX_PATH
#else
#define MAX_FILE_LEN 1024
#endif
bool dirExists(const char *);
bool my_mkdir(char *);
bool unix_mkdir(const char *);
bool windows_mkdir(const char *);
int numDigits(int);
int takeStandardImage(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params * params);
int writeImage(HANDLE handle, int camIndex, USHORT *pixelArray, char *, struct Params * params);
int writeMultipleImages(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params * params);
std::string getDate();
std::string getTime();
std::string numberToString(int number);
void correctDir(char dir[]);
void printError(int, const char *);
void setDate(fitsfile *, int);
struct Params /* structure used to store parameter information */
{
bool overwrite; /* -f */
bool verbose; /* -v */
char dirName[MAX_PATH]; /* -d <string> */
char observatory[MAX_PATH]; /* -o <string> */
char templateName[MAX_PATH]; /* -t <string> */
float exposure; /* -e <float> NOTE: in seconds */
float sleepTime; /* -s <float> Sleep time in between taking images */
int dateOption; /* -u <int> */
int initialIndex; /* -i <int> */
int numImages; /* -n <int> */
Params():
overwrite(false),
verbose(false),
exposure(1.0),
sleepTime(0.0),
dateOption(0),
initialIndex(0),
numImages(1){}
};
/* declare these out here so that memory is stored in the heap */
USHORT pixels[PIXEL_WIDTH * PIXEL_HEIGHT];
/* constants */
short const BITPIX = USHORT_IMG;
short const NAXIS = 2;
short const NAXIS1 = PIXEL_HEIGHT;
short const NAXIS2 = PIXEL_WIDTH;
const long NAXES[2] = {PIXEL_WIDTH, PIXEL_HEIGHT};
int main(int argc, char **argv)
{
/* local variables */
HANDLE handles[NUMBER_OF_CAMERAS];
t_sxccd_params cam_params[NUMBER_OF_CAMERAS];
long firmwareVersions[NUMBER_OF_CAMERAS];
int openVal, cameraModels[NUMBER_OF_CAMERAS];
struct Params *params = new Params();
/* default values for strings in params */
strcpy(params->dirName, "test_data\\");
strcpy(params->templateName, "IMG%05d.fits");
strcpy(params->observatory, "defaultObs");
/* parse command line arguments */
int c;
while ((c = getopt(argc, argv, "o:e:n:d:t:s:i:ufv")) != -1)
switch (c){
case 'o':
strcpy(params->observatory, optarg);
break;
case 'e':
params->exposure = strtol(optarg, NULL, 10);
break;
case 'n':
params->numImages = strtol(optarg, NULL, 10);
break;
case 'd':
strcpy(params->dirName, optarg);
break;
case 't':
strcpy(params->templateName, optarg);
break;
case 's':
params->sleepTime = strtol(optarg, NULL, 10);
break;
case 'u':
params->dateOption = strtol(optarg, NULL, 10);
break;
case 'i':
params->initialIndex = strtol(optarg, NULL, 10);
break;
case 'f':
params->overwrite = true;
break;
case 'v':
params->verbose = true;
break;
default:
break;
}
/* open the connected cameras */
openVal = sxOpen(handles);
if (params->verbose){
printf("Opened Cameras: %d\n", openVal);
}
/* error check the number of cameras */
if (openVal > NUMBER_OF_CAMERAS){
printf("MORE CAMERAS CONNECTED (%d) THAN SPECIFIED BY CODE (%d)\nTERMINATING PROGRAM\n", openVal, NUMBER_OF_CAMERAS);
return 0;
}
if (openVal < NUMBER_OF_CAMERAS){
printf("LESS CAMERAS CONNECTED (%d) THAN SPECIFIED BY CODE (%d)\nCODE WILL RUN, MEMEORY WILL BE WASTED\n", openVal, NUMBER_OF_CAMERAS);
}
/* Get and display camera information */
for (int i = 0; i < openVal; i++){
if (params->verbose){
printf("Camera %d:\n", i);
printf("\tCamera Firmware Version: %d\n", (firmwareVersions[i] = sxGetFirmwareVersion(handles[i])));
printf("\tCamera Model: %d\n", (cameraModels[i] = sxGetCameraModel(handles[i])));
}
sxGetCameraParams(handles[i], i, cam_params);
}
/* Taking images */
writeMultipleImages(handles[0], 0, pixels, params);
return 0;
}
/**
Takes an image with a connected camera. The camera exposes for the given time and then reads the image into pixels
@param exposure - this is measured in milliseconds
@return - 1 if the image was taken correctly, 0 if the image had an error. Will attempt to print error message.
*/
int takeStandardImage(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params *params){
try{
int bytesRead;
/* clear pixels on the camera and expose them to take the image */
sxClearPixels(handle, 0x00, camIndex);
sxExposePixels(handle, 0x8B, camIndex, 0, 0, PIXEL_WIDTH, PIXEL_HEIGHT, 1, 1, (ULONG) (params->exposure * 1000));
/* read the pixels from the camera into an array */
if ((bytesRead = sxReadPixels(handle, pixelArray, PIXEL_WIDTH * PIXEL_HEIGHT)) <= 0){
printf("Error reading pixels\n");
return 0;
}
}
catch(int e){
printf("Error while taking image. Error number: %d\n", e);
return 0;
}
return 1;
}
/**
attempts to take multiple images with the camera stored in handle with an index of camIndex. This function will expose, read, and write the images
on its own.
@return - number of images successfully written.
*/
int writeMultipleImages(HANDLE handle, int camIndex, USHORT *pixelArray, struct Params * params){
int imagesTaken = 0;
char newPath[MAX_PATH];
if (params->verbose){
printf("Attempting to write %d images\n", params->numImages);
}
for (int i = 0; i < params->numImages; i++){
try{
/* <templateName>.fits */
sprintf_s(newPath, MAX_PATH - 1, params->templateName, imagesTaken + params->initialIndex);
writeImage(handle, camIndex, pixelArray, newPath, params);
}
catch(int e){
printf("CAUGHT ERROR %d while taking multiple images, stopped after %d images\n", e, imagesTaken);
return imagesTaken;
}
imagesTaken++;
Sleep(params->sleepTime);
}
if (params->verbose){
printf("Succeeded writing %d images\n", imagesTaken);
}
return imagesTaken;
}
/**
writes image to given pixelArray to path (NOTE: path does not include extension, that is added by the function).
@return - 0 if failed, 1 if successfully wrote image.
*/
int writeImage(HANDLE handle, int camIndex, USHORT *pixelArray, char * filename, struct Params * params){
takeStandardImage(handle, 0, pixels, params);
/* set up a fits file with proper hdu to write to a file */
fitsfile *file;
int status = 0;
char newPath[MAX_PATH], finalPath[MAX_PATH];
printf("*Before my_mkdir(): %s\n", params->dirName);
my_mkdir(params->dirName);
strcpy(newPath, params->dirName);
strcat(newPath, filename);
printf("*After strcat(): %s\n", params->dirName);
/* if overwrite flag is true add an '!' to the front so that fitsio overwrites files of
of the same name */
if (params->overwrite == true){
strcpy(finalPath, "!");
strcat(finalPath, newPath);
}
else{
strcpy(finalPath, newPath);
}
if (params->verbose){
printf("Writing %s\n", finalPath);
}
if (fits_create_file(&file, finalPath, &status)){
/*fits_report_error(stdout, status);*/
printError(status, "writeImage, while creating file");
}
/* basic header information (BITPIX, NAXIS, NAXES, etc) is taken care of through this function as well) */
if (fits_create_img(file, BITPIX, NAXIS, (long *) NAXES, &status)){
printError(status, "writeImage, while creating image");
}
/* extended header information */
if (fits_write_key(file, TSTRING, "OBJECT", OBJECT, "", &status)){
printError(status, "writeImage, while writing OBJECT");
}
if (fits_write_key(file, TSTRING, "TELESCOP", TELESCOP, "", &status)){
printError(status, "writeImage, while writing TELESCOP");
}
if (fits_write_key(file, TSTRING, "ORIGIN", ORIGIN, "", &status)){
printError(status, "writeImage, while writing ORIGIN");
}
if (fits_write_key(file, TSTRING, "INSTRUME", INSTRUME, "", &status)){
printError(status, "writeImage, while writing INSTRUME");
}
if (fits_write_key(file, TSTRING, "OBSERVER", (void *) params->observatory, "", &status)){
printError(status, "writeImage, while writing OBSERVER");
}
if (fits_write_key(file, TFLOAT, "EXPTIME", (void *) &(params->exposure), "", &status)){
printError(status, "writeImage, while writing EXPTIME");
}
/* find the current date and time and write it to a keyword(s) */
setDate(file, params->dateOption);
/* write the image data to the file */
if (fits_write_img(file, TUSHORT, 1, PIXEL_HEIGHT * PIXEL_WIDTH, pixels, &status)){
fits_report_error(stderr, status);
}
/* close the file */
if (fits_close_file(file, &status)){
fits_report_error(stdout, status);
}
return 1;
}
/**
returns number of digits in an int
*/
int numDigits(int number){
int length = 1;
while ( number /= 10 )
length++;
return length;
}
/**
returns the time in the format HH:MM:DD as a string in UTC time
*/
std::string getTime(){
time_t rawtime;
struct tm * ptm;
time(&rawtime);
/* pointer to time object with UTC time */
ptm = gmtime(&rawtime);
;
int hours = ptm->tm_hour;
int minutes = ptm->tm_min;
int seconds = ptm->tm_sec;
/* pad the hours, minutes, seconds with a zero if its only 1 digit long eg. 0-9) */
std::string h = std::string(2 - numDigits(hours), '0').append(numberToString(hours));
std::string m = std::string(2 - numDigits(minutes), '0').append(numberToString(minutes));
std::string s = std::string(2 - numDigits(seconds), '0').append(numberToString(seconds));
std::string time = h + ":" + m + ":" + s;
//@TODO check if seconds could contain the fractional seconds as well
return time;
}
/**
returns the data in the format YYYY-MM-DD as a string in UTC time
*/
std::string getDate(){
time_t rawtime;
struct tm * ptm;
time(&rawtime);
/* pointer to time object with UTC time */
ptm = gmtime(&rawtime);
int year = ptm->tm_year + 1900; /* ptm->tm_year == years since 1900 */
int month = ptm->tm_mon + 1;
int day = ptm->tm_mday;
/* pad the months with a zero if its only 1 digit long eg. 0-9) */
std::string y = numberToString(year);
std::string m = std::string(2 - numDigits(month), '0').append(numberToString(month));
std::string d = std::string(2 - numDigits(day), '0').append(numberToString(day));
std::string date = y + "-" + m + "-" + d;
return date;
}
/**
converts an int into a string
*/
std::string numberToString(int Number)
{
std::stringstream ss;
ss << Number;
return ss.str();
}
/**
Sets the date of the fits file in the HDU and the time (in universal time)
@param option 0: format is DATE-OBS: <YYYY>-<MM>-<DD>
TIME-OBS: <HH>:<MM>:<SS>
1: format is DATE-OBS: <YYYY>-<MM>-<DD>T<HH>:<MM>:<SS>
*/
void setDate(fitsfile *file, int option){
int status = 0;
std::string date = getDate();
std::string time = getTime();
if (option == 0){
if (fits_write_key(file, TSTRING, "DATE-OBS", (void *) date.c_str(), "", &status)){
printError(status, "setDate while writing keyword DATE-OBS");
}
if (fits_write_key(file, TSTRING, "TIME-OBS", (void *) time.c_str(), "", &status)){
printError(status, "setDate while writing keyword TIME-OBS");
}
}
else if (option == 1){
if (fits_write_key(file, TSTRING, "DATE-OBS", (void *) (date.append("T").append(time)).c_str(), "", &status)){
printError(status, "setDate while writing keyword DATE-OBS, option == 1");
}
}
else{
printf("INCORRECT USE OF setDate() INVALID PARAMETER OPTION (must be 0 or 1, your input: %d)", option);
}
}
/* Note: for proper output, include function name at beginning of message */
void printError(int status, const char * message){
printf("(FITSIO) ERROR OCCURED IN FUNCTION %s, STATUS NUMBER: %d\n", message, status);
}
/**
Checks if the directory exists, if it does not, creates it
NOTE: will add a \ to the end of dir if it does not end in one
@return true if it creates it or it already exists
false if it could not create the directory
*/
bool windows_mkdir(char * dir){
correctDir(dir); // correct the directory if it doesnt end in a slash
unsigned int i = 0;
/* the logic here is that _mkdir cannot create two new directories inside of each other at the same time
(first create \firstDir\ then /firstDir/secondDir/ rather than at the same time)
so we copy the original directory over to a temporary and everytime it meets a \ create that directory
then once at the end of the string, make that directory too even if it didn't end in a back slash
*/
char temp[MAX_PATH];
while (i < strlen(dir)){
/* copy the current character */
temp[i] = dir[i];
/* if its a backslash, create the directory if it doesn't already exist */
if (dir[i] == '\\'){
temp[i + 1] = 0;
if (!dirExists(temp)){
if (_mkdir(temp) == -1){
printf("Could not make directory %s :", *dir);
perror(""); //perror is an empty string since our error note is from the printf above
printf("\n");
return false;
}
}
}
i++;
}
return true;
}
bool unix_mkdir(const char * dir){
printf("unix_mkdir() NOT YET IMPLEMENTED!\n");
return false;
}
/**
Calling this function will simply call the corresponding mkdir function for Windows or Unix
*/
bool my_mkdir(char * dir){
#ifdef OS_WINDOWS
return windows_mkdir(dir);
#else
return unix_mkdir(dir);
#endif
}
/**
Checks whether a directory exists
@return true if it exists
false if it does not exists
*/
bool dirExists(const char * dirName_in)
{
DWORD ftyp = GetFileAttributesA(dirName_in);
if (ftyp == INVALID_FILE_ATTRIBUTES)
return false; //something is wrong with your path!
if (ftyp & FILE_ATTRIBUTE_DIRECTORY)
return true; // this is a directory!
return false; // this is not a directory!
}
/**
checks if the directory ends in a backslash for Windows or forward slash for other machines
if it does not, then it will add a backslash/forward slash so it can be created successfully.
*/
void correctDir(char dir[]){
#ifdef OS_WINDOWS
if (dir[strlen(dir) - 1] != '\\'){
/* must store strlen(dir) into an int here because once you make dir[len] = \, dir[len] is no longer
the terminating character and thus if the array had characters after the terminating character
the code will not work as intended */
int len = strlen(dir);
dir[len] = '\\';
dir[len + 1] = 0;
}
#else
if (dir[strlen(dir) - 1] != '/'){
dir[strlen(dir)] = '/';
dir[strlen(dir) + 1] = 0;
}
#endif
}<|endoftext|>
|
<commit_before>#include <pex/PexOptimizer.h>
#include <unordered_map>
#include <vector>
namespace caprica { namespace pex {
struct OptInstruction final
{
size_t id{ 0 };
size_t instructionNum{ 0 };
PexInstruction* instr{ nullptr };
std::vector<OptInstruction*> instructionsReferencingLabel{ };
OptInstruction* branchTarget{ nullptr };
uint16_t lineNumber{ 0 };
explicit OptInstruction(size_t id, PexInstruction* instr) : id(id), instr(instr) { }
~OptInstruction() = default;
bool isDead() const {
return instr == nullptr || instr->opCode == PexOpCode::Nop;
}
void killInstruction() {
#if 0
instr->opCode = PexOpCode::Nop;
instr->args.clear();
instr->variadicArgs.clear();
#else
delete instr;
instr = nullptr;
branchTarget = nullptr;
lineNumber = 0;
#endif
}
private:
explicit OptInstruction() = default;
};
static std::vector<OptInstruction*> buildOptInstructions(const PexDebugFunctionInfo* debInfo,
const PexInstructionList& instructions) {
std::unordered_map<size_t, OptInstruction*> labelMap;
for (auto cur = instructions.begin(), end = instructions.end(); cur != end; ++cur) {
if (cur->isBranch()) {
auto targI = cur->branchTarget() + cur.index;
if (!labelMap.count((size_t)(targI)))
labelMap.emplace((size_t)targI, new OptInstruction(0, nullptr));
}
}
std::vector<OptInstruction*> optimizedInstructions{ };
optimizedInstructions.reserve(instructions.size());
size_t id = 0;
for (auto cur = instructions.begin(), end = instructions.end(); cur != end; ++cur, id++) {
auto f = labelMap.find(cur.index);
if (f != labelMap.end()) {
f->second->id = id++;
optimizedInstructions.emplace_back(f->second);
}
auto o = new OptInstruction(id, *cur);
if (debInfo && cur.index < debInfo->instructionLineMap.size())
o->lineNumber = debInfo->instructionLineMap[cur.index];
if (o->instr->isBranch()) {
o->branchTarget = labelMap[(size_t)(o->instr->branchTarget() + cur.index)];
o->branchTarget->instructionsReferencingLabel.push_back(o);
}
optimizedInstructions.emplace_back(o);
}
auto f = labelMap.find(instructions.size());
if (f != labelMap.end()) {
f->second->id = optimizedInstructions.size();
optimizedInstructions.emplace_back(f->second);
}
return optimizedInstructions;
}
void PexOptimizer::optimize(PexFile* file,
PexObject* object,
PexState* state,
PexFunction* function,
const std::string& propertyName,
PexDebugFunctionType functionType) {
PexDebugFunctionInfo* debInfo = file->tryFindFunctionDebugInfo(object, state, function, propertyName, functionType);
auto optimizedInstructions = buildOptInstructions(debInfo, function->instructions);
const auto isDeadBetween = [&optimizedInstructions](size_t startID, size_t endID) -> bool {
for (size_t i = startID + 1; i <= endID; i++) {
assert(i < optimizedInstructions.size());
if (!optimizedInstructions[i]->isDead())
return false;
}
return true;
};
const auto nextNonDead = [&optimizedInstructions](size_t startID) -> OptInstruction* {
for (size_t i = startID + 1; i < optimizedInstructions.size(); i++) {
if (!optimizedInstructions[i]->isDead())
return optimizedInstructions[i];
}
return nullptr;
};
for (int i = (int)optimizedInstructions.size() - 1; i >= 0; i--) {
auto opt = optimizedInstructions[i];
if (opt->instr) {
switch (opt->instr->opCode) {
case PexOpCode::Assign:
if (opt->instr->args[0] == opt->instr->args[1])
opt->killInstruction();
break;
case PexOpCode::Jmp:
if (opt->id < opt->branchTarget->id && isDeadBetween(opt->id, opt->branchTarget->id))
opt->killInstruction();
break;
case PexOpCode::Not: {
if (i <= 1)
break;
auto n = nextNonDead(opt->id);
if (!n)
break;
if (n->instr->opCode != PexOpCode::JmpF && n->instr->opCode != PexOpCode::JmpT)
break;
// Ensure source of branch is dest of not.
if (opt->instr->args[0] != n->instr->args[0])
break;
if (n->instr->opCode == PexOpCode::JmpF)
n->instr->opCode = PexOpCode::JmpT;
else if (n->instr->opCode == PexOpCode::JmpT)
n->instr->opCode = PexOpCode::JmpF;
else
CapricaReportingContext::logicalFatal("Somehow got a weird op-code here.");
n->instr->args[0] = opt->instr->args[1];
opt->killInstruction();
break;
}
default:
break;
}
}
}
size_t curInstrNum = 0;
for (auto& i : optimizedInstructions) {
i->instructionNum = curInstrNum;
if (i->instr)
curInstrNum++;
}
PexInstructionList newInstructions{ };
newInstructions.reserve(curInstrNum);
std::vector<uint16_t> newLineInfo{ };
newLineInfo.reserve(curInstrNum);
for (auto& i : optimizedInstructions) {
if (i->instr) {
newLineInfo.push_back(i->lineNumber);
newInstructions.emplace_back(std::move(*i->instr));
if (i->instr->isBranch())
i->instr->setBranchTarget((int)i->branchTarget->instructionNum - (int)i->instructionNum);
}
}
function->instructions = std::move(newInstructions);
if (debInfo)
debInfo->instructionLineMap = std::move(newLineInfo);
for (auto& i : optimizedInstructions)
delete i;
}
}}
<commit_msg>Disable an optimization in the pex optimizer that was unsafe. Fixes #10.<commit_after>#include <pex/PexOptimizer.h>
#include <unordered_map>
#include <vector>
namespace caprica { namespace pex {
struct OptInstruction final
{
size_t id{ 0 };
size_t instructionNum{ 0 };
PexInstruction* instr{ nullptr };
std::vector<OptInstruction*> instructionsReferencingLabel{ };
OptInstruction* branchTarget{ nullptr };
uint16_t lineNumber{ 0 };
explicit OptInstruction(size_t id, PexInstruction* instr) : id(id), instr(instr) { }
~OptInstruction() = default;
bool isDead() const {
return instr == nullptr || instr->opCode == PexOpCode::Nop;
}
void killInstruction() {
#if 0
instr->opCode = PexOpCode::Nop;
instr->args.clear();
instr->variadicArgs.clear();
#else
delete instr;
instr = nullptr;
branchTarget = nullptr;
lineNumber = 0;
#endif
}
private:
explicit OptInstruction() = default;
};
static std::vector<OptInstruction*> buildOptInstructions(const PexDebugFunctionInfo* debInfo,
const PexInstructionList& instructions) {
std::unordered_map<size_t, OptInstruction*> labelMap;
for (auto cur = instructions.begin(), end = instructions.end(); cur != end; ++cur) {
if (cur->isBranch()) {
auto targI = cur->branchTarget() + cur.index;
if (!labelMap.count((size_t)(targI)))
labelMap.emplace((size_t)targI, new OptInstruction(0, nullptr));
}
}
std::vector<OptInstruction*> optimizedInstructions{ };
optimizedInstructions.reserve(instructions.size());
size_t id = 0;
for (auto cur = instructions.begin(), end = instructions.end(); cur != end; ++cur, id++) {
auto f = labelMap.find(cur.index);
if (f != labelMap.end()) {
f->second->id = id++;
optimizedInstructions.emplace_back(f->second);
}
auto o = new OptInstruction(id, *cur);
if (debInfo && cur.index < debInfo->instructionLineMap.size())
o->lineNumber = debInfo->instructionLineMap[cur.index];
if (o->instr->isBranch()) {
o->branchTarget = labelMap[(size_t)(o->instr->branchTarget() + cur.index)];
o->branchTarget->instructionsReferencingLabel.push_back(o);
}
optimizedInstructions.emplace_back(o);
}
auto f = labelMap.find(instructions.size());
if (f != labelMap.end()) {
f->second->id = optimizedInstructions.size();
optimizedInstructions.emplace_back(f->second);
}
return optimizedInstructions;
}
void PexOptimizer::optimize(PexFile* file,
PexObject* object,
PexState* state,
PexFunction* function,
const std::string& propertyName,
PexDebugFunctionType functionType) {
PexDebugFunctionInfo* debInfo = file->tryFindFunctionDebugInfo(object, state, function, propertyName, functionType);
auto optimizedInstructions = buildOptInstructions(debInfo, function->instructions);
const auto isDeadBetween = [&optimizedInstructions](size_t startID, size_t endID) -> bool {
for (size_t i = startID + 1; i <= endID; i++) {
assert(i < optimizedInstructions.size());
if (!optimizedInstructions[i]->isDead())
return false;
}
return true;
};
const auto nextNonDead = [&optimizedInstructions](size_t startID) -> OptInstruction* {
for (size_t i = startID + 1; i < optimizedInstructions.size(); i++) {
if (!optimizedInstructions[i]->isDead())
return optimizedInstructions[i];
}
return nullptr;
};
for (int i = (int)optimizedInstructions.size() - 1; i >= 0; i--) {
auto opt = optimizedInstructions[i];
if (opt->instr) {
switch (opt->instr->opCode) {
case PexOpCode::Assign:
if (opt->instr->args[0] == opt->instr->args[1])
opt->killInstruction();
break;
case PexOpCode::Jmp:
if (opt->id < opt->branchTarget->id && isDeadBetween(opt->id, opt->branchTarget->id))
opt->killInstruction();
break;
#if 0
case PexOpCode::Not: {
if (i <= 1)
break;
auto n = nextNonDead(opt->id);
if (!n)
break;
if (n->instr->opCode != PexOpCode::JmpF && n->instr->opCode != PexOpCode::JmpT)
break;
// Ensure source of branch is dest of not.
if (opt->instr->args[0] != n->instr->args[0])
break;
if (n->instr->opCode == PexOpCode::JmpF)
n->instr->opCode = PexOpCode::JmpT;
else if (n->instr->opCode == PexOpCode::JmpT)
n->instr->opCode = PexOpCode::JmpF;
else
CapricaReportingContext::logicalFatal("Somehow got a weird op-code here.");
n->instr->args[0] = opt->instr->args[1];
opt->killInstruction();
break;
}
#endif
default:
break;
}
}
}
size_t curInstrNum = 0;
for (auto& i : optimizedInstructions) {
i->instructionNum = curInstrNum;
if (i->instr)
curInstrNum++;
}
PexInstructionList newInstructions{ };
newInstructions.reserve(curInstrNum);
std::vector<uint16_t> newLineInfo{ };
newLineInfo.reserve(curInstrNum);
for (auto& i : optimizedInstructions) {
if (i->instr) {
newLineInfo.push_back(i->lineNumber);
newInstructions.emplace_back(std::move(*i->instr));
if (i->instr->isBranch())
i->instr->setBranchTarget((int)i->branchTarget->instructionNum - (int)i->instructionNum);
}
}
function->instructions = std::move(newInstructions);
if (debInfo)
debInfo->instructionLineMap = std::move(newLineInfo);
for (auto& i : optimizedInstructions)
delete i;
}
}}
<|endoftext|>
|
<commit_before>//===-- ClangUtilityFunction.cpp ---------------------------------*- C++-*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ClangUtilityFunction.h"
#include "ClangExpressionDeclMap.h"
#include "ClangExpressionParser.h"
// C Includes
#include <stdio.h>
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
// C++ Includes
#include "lldb/Core/Module.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Host/Host.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
using namespace lldb_private;
//------------------------------------------------------------------
/// Constructor
///
/// @param[in] text
/// The text of the function. Must be a full translation unit.
///
/// @param[in] name
/// The name of the function, as used in the text.
//------------------------------------------------------------------
ClangUtilityFunction::ClangUtilityFunction(ExecutionContextScope &exe_scope,
const char *text, const char *name)
: UtilityFunction(exe_scope, text, name) {}
ClangUtilityFunction::~ClangUtilityFunction() {}
//------------------------------------------------------------------
/// Install the utility function into a process
///
/// @param[in] diagnostic_manager
/// A diagnostic manager to report errors and warnings to.
///
/// @param[in] exe_ctx
/// The execution context to install the utility function to.
///
/// @return
/// True on success (no errors); false otherwise.
//------------------------------------------------------------------
bool ClangUtilityFunction::Install(DiagnosticManager &diagnostic_manager,
ExecutionContext &exe_ctx) {
if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
diagnostic_manager.PutString(eDiagnosticSeverityWarning,
"already installed");
return false;
}
////////////////////////////////////
// Set up the target and compiler
//
Target *target = exe_ctx.GetTargetPtr();
if (!target) {
diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
return false;
}
Process *process = exe_ctx.GetProcessPtr();
if (!process) {
diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid process");
return false;
}
//////////////////////////
// Parse the expression
//
bool keep_result_in_memory = false;
ResetDeclMap(exe_ctx, keep_result_in_memory);
if (!DeclMap()->WillParse(exe_ctx, NULL)) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"current process state is unsuitable for expression parsing");
return false;
}
const bool generate_debug_info = true;
ClangExpressionParser parser(exe_ctx.GetBestExecutionContextScope(), *this,
generate_debug_info);
unsigned num_errors = parser.Parse(diagnostic_manager);
if (num_errors) {
ResetDeclMap();
return false;
}
//////////////////////////////////
// JIT the output of the parser
//
bool can_interpret = false; // should stay that way
Status jit_error = parser.PrepareForExecution(
m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
can_interpret, eExecutionPolicyAlways);
if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
m_jit_process_wp = process->shared_from_this();
if (parser.GetGenerateDebugInfo()) {
lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
if (jit_module_sp) {
ConstString const_func_name(FunctionName());
FileSpec jit_file;
jit_file.GetFilename() = const_func_name;
jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
m_jit_module_wp = jit_module_sp;
target->GetImages().Append(jit_module_sp);
}
}
}
#if 0
// jingham: look here
StreamFile logfile ("/tmp/exprs.txt", "a");
logfile.Printf ("0x%16.16" PRIx64 ": func = %s, source =\n%s\n",
m_jit_start_addr,
m_function_name.c_str(),
m_function_text.c_str());
#endif
DeclMap()->DidParse();
ResetDeclMap();
if (jit_error.Success()) {
return true;
} else {
const char *error_cstr = jit_error.AsCString();
if (error_cstr && error_cstr[0]) {
diagnostic_manager.Printf(eDiagnosticSeverityError, "%s", error_cstr);
} else {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"expression can't be interpreted or run");
}
return false;
}
}
void ClangUtilityFunction::ClangUtilityFunctionHelper::ResetDeclMap(
ExecutionContext &exe_ctx, bool keep_result_in_memory) {
m_expr_decl_map_up.reset(
new ClangExpressionDeclMap(keep_result_in_memory, nullptr, exe_ctx));
}
<commit_msg>[ExpressionParser] Garbage-collect dead code. NFCI.<commit_after>//===-- ClangUtilityFunction.cpp ---------------------------------*- C++-*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ClangUtilityFunction.h"
#include "ClangExpressionDeclMap.h"
#include "ClangExpressionParser.h"
// C Includes
#include <stdio.h>
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
// C++ Includes
#include "lldb/Core/Module.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Host/Host.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
using namespace lldb_private;
//------------------------------------------------------------------
/// Constructor
///
/// @param[in] text
/// The text of the function. Must be a full translation unit.
///
/// @param[in] name
/// The name of the function, as used in the text.
//------------------------------------------------------------------
ClangUtilityFunction::ClangUtilityFunction(ExecutionContextScope &exe_scope,
const char *text, const char *name)
: UtilityFunction(exe_scope, text, name) {}
ClangUtilityFunction::~ClangUtilityFunction() {}
//------------------------------------------------------------------
/// Install the utility function into a process
///
/// @param[in] diagnostic_manager
/// A diagnostic manager to report errors and warnings to.
///
/// @param[in] exe_ctx
/// The execution context to install the utility function to.
///
/// @return
/// True on success (no errors); false otherwise.
//------------------------------------------------------------------
bool ClangUtilityFunction::Install(DiagnosticManager &diagnostic_manager,
ExecutionContext &exe_ctx) {
if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
diagnostic_manager.PutString(eDiagnosticSeverityWarning,
"already installed");
return false;
}
////////////////////////////////////
// Set up the target and compiler
//
Target *target = exe_ctx.GetTargetPtr();
if (!target) {
diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid target");
return false;
}
Process *process = exe_ctx.GetProcessPtr();
if (!process) {
diagnostic_manager.PutString(eDiagnosticSeverityError, "invalid process");
return false;
}
//////////////////////////
// Parse the expression
//
bool keep_result_in_memory = false;
ResetDeclMap(exe_ctx, keep_result_in_memory);
if (!DeclMap()->WillParse(exe_ctx, NULL)) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"current process state is unsuitable for expression parsing");
return false;
}
const bool generate_debug_info = true;
ClangExpressionParser parser(exe_ctx.GetBestExecutionContextScope(), *this,
generate_debug_info);
unsigned num_errors = parser.Parse(diagnostic_manager);
if (num_errors) {
ResetDeclMap();
return false;
}
//////////////////////////////////
// JIT the output of the parser
//
bool can_interpret = false; // should stay that way
Status jit_error = parser.PrepareForExecution(
m_jit_start_addr, m_jit_end_addr, m_execution_unit_sp, exe_ctx,
can_interpret, eExecutionPolicyAlways);
if (m_jit_start_addr != LLDB_INVALID_ADDRESS) {
m_jit_process_wp = process->shared_from_this();
if (parser.GetGenerateDebugInfo()) {
lldb::ModuleSP jit_module_sp(m_execution_unit_sp->GetJITModule());
if (jit_module_sp) {
ConstString const_func_name(FunctionName());
FileSpec jit_file;
jit_file.GetFilename() = const_func_name;
jit_module_sp->SetFileSpecAndObjectName(jit_file, ConstString());
m_jit_module_wp = jit_module_sp;
target->GetImages().Append(jit_module_sp);
}
}
}
DeclMap()->DidParse();
ResetDeclMap();
if (jit_error.Success()) {
return true;
} else {
const char *error_cstr = jit_error.AsCString();
if (error_cstr && error_cstr[0]) {
diagnostic_manager.Printf(eDiagnosticSeverityError, "%s", error_cstr);
} else {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"expression can't be interpreted or run");
}
return false;
}
}
void ClangUtilityFunction::ClangUtilityFunctionHelper::ResetDeclMap(
ExecutionContext &exe_ctx, bool keep_result_in_memory) {
m_expr_decl_map_up.reset(
new ClangExpressionDeclMap(keep_result_in_memory, nullptr, exe_ctx));
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012, Oscar Esteban - [email protected]
with Biomedical Image Technology, UPM (BIT-UPM)
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 names of the BIT-UPM and LTS5-EPFL, 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 Oscar Esteban ''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 OSCAR ESTEBAN 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 "regseg.h"
int main(int argc, char *argv[]) {
std::string outPrefix;
std::vector< std::string > fixedImageNames, movingSurfaceNames;
std::string logFileName = ".log";
bool outImages = false;
size_t verbosity = 1;
bpo::options_description desc("Usage");
desc.add_options()
("help,h", "show help message")
("fixed-images,F", bpo::value < std::vector<std::string> > (&fixedImageNames)->multitoken()->required(), "fixed image file")
("moving-surfaces,M", bpo::value < std::vector<std::string> > (&movingSurfaceNames)->multitoken()->required(), "moving image file")
("output-prefix,o", bpo::value < std::string > (&outPrefix), "prefix for output files")
("output-all", bpo::bool_switch(&outImages),"output intermediate images")
("alpha,a", bpo::value< float > (), "alpha value in regularization")
("beta,b", bpo::value< float > (), "beta value in regularization")
("step-size,s", bpo::value< float > (), "step-size value in optimization")
("iterations,i", bpo::value< int > (), "number of iterations")
("grid-size,g", bpo::value< int > (), "grid size")
("logfile,l", bpo::value<std::string>(&logFileName), "log filename")
("verbosity,V", bpo::value<size_t>(&verbosity), "verbosity level ( 0 = no output; 5 = verbose )");
bpo::positional_options_description pdesc;
bpo::variables_map vmap;
bpo::store(
bpo::command_line_parser(argc, argv).options(desc).positional(pdesc).run(),
vmap);
if (vmap.count("help")) {
std::cout << desc << std::endl;
return 1;
}
try {
bpo::notify(vmap);
} catch (boost::exception_detail::clone_impl
< boost::exception_detail::error_info_injector< boost::program_options::required_option> > &err) {
std::cout << "Error: " << err.what() << std::endl;
std::cout << desc << std::endl;
return EXIT_FAILURE;
}
// Create the JSON output object
Json::Value root;
root["description"] = "RSTK Summary File";
std::time_t time;
root["information"] = std::ctime( &time );
// Read fixed image(s) --------------------------------------------------------------
clock_t preProcessStart = clock();
// Initialize LevelSet function
FunctionalType::Pointer functional = FunctionalType::New();
// Connect Optimizer
OptimizerPointer opt = Optimizer::New();
opt->SetFunctional( functional );
//typename ObserverType::Pointer o = ObserverType::New();
//o->SetCallbackFunction( opt, & PrintIteration );
//o->AddObserver( itk::IterationEvent(), o );
// Read target feature(s) -----------------------------------------------------------
root["inputs"]["target"]["components"]["size"] = Json::Int (fixedImageNames.size());
root["inputs"]["target"]["components"]["type"] = std::string("feature");
Json::Value targetjson(Json::arrayValue);
InputToVectorFilterType::Pointer comb = InputToVectorFilterType::New();
for (size_t i = 0; i < fixedImageNames.size(); i++ ) {
ImageReader::Pointer r = ImageReader::New();
r->SetFileName( fixedImageNames[i] );
r->Update();
comb->SetInput(i,r->GetOutput());
targetjson.append( fixedImageNames[i]);
}
root["inputs"]["target"]["components"] = targetjson;
ChannelType::DirectionType dir; dir.SetIdentity();
comb->Update();
ImageType::Pointer im = comb->GetOutput();
im->SetDirection( dir );
functional->SetReferenceImage( im );
// Read moving surface(s) -----------------------------------------------------------
root["inputs"]["moving"]["components"]["size"] = Json::Int (movingSurfaceNames.size());
root["inputs"]["moving"]["components"]["type"] = std::string("surface");
Json::Value movingjson(Json::arrayValue);
for (size_t i = 0; i < movingSurfaceNames.size(); i++) {
ReaderType::Pointer polyDataReader = ReaderType::New();
polyDataReader->SetFileName( movingSurfaceNames[i] );
polyDataReader->Update();
functional->AddShapePrior( polyDataReader->GetOutput() );
movingjson.append( movingSurfaceNames[i] );
}
root["inputs"]["moving"]["components"] = movingjson;
// Set up registration ------------------------------------------------------------
if (vmap.count("grid-size")) {
opt->SetGridSize( vmap["grid-size"].as<int>() );
}
if (vmap.count("iterations")) {
opt->SetNumberOfIterations( vmap["iterations"].as<int>() );
}
if (vmap.count("step-size")) {
opt->SetStepSize( vmap["step-size"].as<float>() );
}
if (vmap.count("alpha")) {
opt->SetAlpha( vmap["alpha"].as<float>() );
}
clock_t preProcessStop = clock();
float pre_tot_t = (float) (((double) (preProcessStop - preProcessStart)) / CLOCKS_PER_SEC);
root["time"]["preprocessing"] = pre_tot_t;
// Start registration -------------------------------------------------------------
std::cout << " --------------------------------- Starting registration process." << std::endl;
clock_t initTime = clock();
opt->Start();
clock_t finishTime = clock();
std::cout << " --------------------------------- Finished registration process." << std::endl;
float tot_t = (float) (((double) (finishTime - initTime)) / CLOCKS_PER_SEC);
root["time"]["processing"] = tot_t;
//
// Write out final results ---------------------------------------------------------
//
// Displacementfield
typename DisplacementFieldWriter::Pointer p = DisplacementFieldWriter::New();
p->SetFileName( (outPrefix + "_field.nii.gz" ).c_str() );
p->SetInput( functional->GetCurrentDisplacementField() );
p->Update();
// Contours and regions
size_t nCont = functional->GetCurrentContourPosition().size();
for ( size_t contid = 0; contid < nCont; contid++) {
bfs::path contPath(movingSurfaceNames[contid]);
WriterType::Pointer polyDataWriter = WriterType::New();
polyDataWriter->SetInput( functional->GetCurrentContourPosition()[contid] );
polyDataWriter->SetFileName( (outPrefix + "_" + contPath.filename().string()).c_str() );
polyDataWriter->Update();
typename ROIWriter::Pointer w = ROIWriter::New();
w->SetInput( functional->GetCurrentRegion(contid) );
w->SetFileName( (outPrefix + "_roi_" + contPath.stem().string() + ".nii.gz" ).c_str() );
w->Update();
}
// Last ROI (excluded region)
typename ROIWriter::Pointer w = ROIWriter::New();
w->SetInput( functional->GetCurrentRegion(nCont) );
w->SetFileName( (outPrefix + "_roi_background.nii.gz" ).c_str() );
w->Update();
// JSON Summary
root["summary"]["energy"]["total"] = opt->GetCurrentMetricValue();
root["summary"]["energy"]["data"] = functional->GetValue();
root["summary"]["energy"]["regularization"] = opt->GetCurrentRegularizationEnergy();
root["summary"]["iterations"] = opt->GetCurrentIteration();
root["summary"]["conv_status"] = opt->GetStopCondition();
root["summary"]["stop_msg"] = opt->GetStopConditionDescription();
// Set-up & write out log file
std::ofstream logfile((outPrefix + logFileName ).c_str());
logfile << root;
return EXIT_SUCCESS;
}
<commit_msg>Fixed minor error<commit_after>/*
Copyright (c) 2012, Oscar Esteban - [email protected]
with Biomedical Image Technology, UPM (BIT-UPM)
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 names of the BIT-UPM and LTS5-EPFL, 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 Oscar Esteban ''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 OSCAR ESTEBAN 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 "regseg.h"
int main(int argc, char *argv[]) {
std::string outPrefix;
std::vector< std::string > fixedImageNames, movingSurfaceNames;
std::string logFileName = ".log";
bool outImages = false;
size_t verbosity = 1;
bpo::options_description desc("Usage");
desc.add_options()
("help,h", "show help message")
("fixed-images,F", bpo::value < std::vector<std::string> > (&fixedImageNames)->multitoken()->required(), "fixed image file")
("moving-surfaces,M", bpo::value < std::vector<std::string> > (&movingSurfaceNames)->multitoken()->required(), "moving image file")
("output-prefix,o", bpo::value < std::string > (&outPrefix), "prefix for output files")
("output-all", bpo::bool_switch(&outImages),"output intermediate images")
("alpha,a", bpo::value< float > (), "alpha value in regularization")
("beta,b", bpo::value< float > (), "beta value in regularization")
("step-size,s", bpo::value< float > (), "step-size value in optimization")
("iterations,i", bpo::value< int > (), "number of iterations")
("grid-size,g", bpo::value< int > (), "grid size")
("logfile,l", bpo::value<std::string>(&logFileName), "log filename")
("verbosity,V", bpo::value<size_t>(&verbosity), "verbosity level ( 0 = no output; 5 = verbose )");
bpo::positional_options_description pdesc;
bpo::variables_map vmap;
bpo::store(
bpo::command_line_parser(argc, argv).options(desc).positional(pdesc).run(),
vmap);
if (vmap.count("help")) {
std::cout << desc << std::endl;
return 1;
}
try {
bpo::notify(vmap);
} catch (boost::exception_detail::clone_impl
< boost::exception_detail::error_info_injector< boost::program_options::required_option> > &err) {
std::cout << "Error: " << err.what() << std::endl;
std::cout << desc << std::endl;
return EXIT_FAILURE;
}
// Create the JSON output object
Json::Value root;
root["description"] = "RSTK Summary File";
std::time_t time;
root["information"] = std::ctime( &time );
// Read fixed image(s) --------------------------------------------------------------
clock_t preProcessStart = clock();
// Initialize LevelSet function
FunctionalType::Pointer functional = FunctionalType::New();
// Connect Optimizer
OptimizerPointer opt = Optimizer::New();
opt->SetFunctional( functional );
//typename ObserverType::Pointer o = ObserverType::New();
//o->SetCallbackFunction( opt, & PrintIteration );
//o->AddObserver( itk::IterationEvent(), o );
// Read target feature(s) -----------------------------------------------------------
root["inputs"]["target"]["components"]["size"] = Json::Int (fixedImageNames.size());
root["inputs"]["target"]["components"]["type"] = std::string("feature");
Json::Value targetjson(Json::arrayValue);
InputToVectorFilterType::Pointer comb = InputToVectorFilterType::New();
for (size_t i = 0; i < fixedImageNames.size(); i++ ) {
ImageReader::Pointer r = ImageReader::New();
r->SetFileName( fixedImageNames[i] );
r->Update();
comb->SetInput(i,r->GetOutput());
targetjson.append( fixedImageNames[i]);
}
root["inputs"]["target"]["components"] = targetjson;
ChannelType::DirectionType dir; dir.SetIdentity();
comb->Update();
ImageType::Pointer im = comb->GetOutput();
im->SetDirection( dir );
functional->SetReferenceImage( im );
// Read moving surface(s) -----------------------------------------------------------
root["inputs"]["moving"]["components"]["size"] = Json::Int (movingSurfaceNames.size());
root["inputs"]["moving"]["components"]["type"] = std::string("surface");
Json::Value movingjson(Json::arrayValue);
for (size_t i = 0; i < movingSurfaceNames.size(); i++) {
ReaderType::Pointer polyDataReader = ReaderType::New();
polyDataReader->SetFileName( movingSurfaceNames[i] );
polyDataReader->Update();
functional->AddShapePrior( polyDataReader->GetOutput() );
movingjson.append( movingSurfaceNames[i] );
}
root["inputs"]["moving"]["components"] = movingjson;
// Set up registration ------------------------------------------------------------
if (vmap.count("grid-size")) {
opt->SetGridSize( vmap["grid-size"].as<int>() );
}
if (vmap.count("iterations")) {
opt->SetNumberOfIterations( vmap["iterations"].as<int>() );
}
if (vmap.count("step-size")) {
opt->SetStepSize( vmap["step-size"].as<float>() );
}
if (vmap.count("alpha")) {
opt->SetAlpha( vmap["alpha"].as<float>() );
}
clock_t preProcessStop = clock();
float pre_tot_t = (float) (((double) (preProcessStop - preProcessStart)) / CLOCKS_PER_SEC);
root["time"]["preprocessing"] = pre_tot_t;
// Start registration -------------------------------------------------------------
std::cout << " --------------------------------- Starting registration process." << std::endl;
clock_t initTime = clock();
opt->Start();
clock_t finishTime = clock();
std::cout << " --------------------------------- Finished registration process." << std::endl;
float tot_t = (float) (((double) (finishTime - initTime)) / CLOCKS_PER_SEC);
root["time"]["processing"] = tot_t;
//
// Write out final results ---------------------------------------------------------
//
// Displacementfield
typename DisplacementFieldWriter::Pointer p = DisplacementFieldWriter::New();
p->SetFileName( (outPrefix + "_field.nii.gz" ).c_str() );
p->SetInput( functional->GetCurrentDisplacementField() );
p->Update();
// Contours and regions
size_t nCont = functional->GetCurrentContourPosition().size();
for ( size_t contid = 0; contid < nCont; contid++) {
bfs::path contPath(movingSurfaceNames[contid]);
WriterType::Pointer polyDataWriter = WriterType::New();
polyDataWriter->SetInput( functional->GetCurrentContourPosition()[contid] );
polyDataWriter->SetFileName( (outPrefix + "_" + contPath.filename().string()).c_str() );
polyDataWriter->Update();
typename ROIWriter::Pointer w = ROIWriter::New();
w->SetInput( functional->GetCurrentRegion(contid) );
w->SetFileName( (outPrefix + "_roi_" + contPath.stem().string() + ".nii.gz" ).c_str() );
w->Update();
}
// Last ROI (excluded region)
typename ROIWriter::Pointer w = ROIWriter::New();
w->SetInput( functional->GetCurrentRegion(nCont) );
w->SetFileName( (outPrefix + "_roi_background.nii.gz" ).c_str() );
w->Update();
// JSON Summary
root["summary"]["energy"]["total"] = opt->GetCurrentMetricValue();
root["summary"]["energy"]["data"] = functional->GetValue();
root["summary"]["energy"]["regularization"] = opt->GetCurrentRegularizationEnergy();
root["summary"]["iterations"] = Json::Int (opt->GetCurrentIteration());
root["summary"]["conv_status"] = opt->GetStopCondition();
root["summary"]["stop_msg"] = opt->GetStopConditionDescription();
// Set-up & write out log file
std::ofstream logfile((outPrefix + logFileName ).c_str());
logfile << root;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "CommonImport.h"
#include "CommonUtilities.h"
#include "CommonMeshUtilities.h"
#include "CommonAlembic.h"
#include <boost/algorithm/string.hpp>
#include <sstream>
bool parseBool(std::string value){
//std::istringstream(valuePair[1]) >> bExportSelected;
if( value.find("true") != std::string::npos || value.find("1") != std::string::npos ){
return true;
}
else{
return false;
}
}
bool IJobStringParser::parse(const std::string& jobString)
{
std::vector<std::string> tokens;
boost::split(tokens, jobString, boost::is_any_of(";"));
//if(tokens.empty()){
// return false;
//}
for(int j=0; j<tokens.size(); j++){
std::vector<std::string> valuePair;
boost::split(valuePair, tokens[j], boost::is_any_of("="));
if(valuePair.size() != 2){
ESS_LOG_WARNING("Skipping invalid token: "<<tokens[j]);
continue;
}
if(boost::iequals(valuePair[0], "filename")){
filename = valuePair[1];
}
else if(boost::iequals(valuePair[0], "normals")){
importNormals = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "uvs")){
importUVs = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "facesets")){
importFacesets = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "materialIds")){
importMaterialIds = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "attachToExisting")){
attachToExisting = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importStandinProperties")){
importStandinProperties = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importBoundingBoxes")){
importBoundingBoxes = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importVisibilityControllers")){
importVisibilityControllers = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "failOnUnsupported")){
failOnUnsupported = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "filters") || boost::iequals(valuePair[0], "identifiers")){
boost::split(nodesToImport, valuePair[1], boost::is_any_of(","));
}
else if(boost::iequals(valuePair[0], "includeChildren")){
includeChildren = parseBool(valuePair[1]);
}
else
{
extraParameters[valuePair[0]] = valuePair[1];
}
}
return true;
}
std::string IJobStringParser::buildJobString()
{
////Note: there are currently some minor differences between the apps. This function is somewhat XSI specific.
std::stringstream stream;
if(!filename.empty()){
stream<<"filename="<<filename<<";";
}
stream<<"normals="<<importNormals<<";uvs="<<importUVs<<";facesets="<<importFacesets;
stream<<";importVisibilityControllers="<<importVisibilityControllers<<";importStandinProperties="<<importStandinProperties;
stream<<";importBoundingBoxes="<<importBoundingBoxes<<";attachToExisting="<<attachToExisting<<";failOnUnsupported="<<failOnUnsupported;
if(!nodesToImport.empty()){
stream<<";identifiers=";
for(int i=0; i<nodesToImport.size(); i++){
stream<<nodesToImport[i];
if(i != nodesToImport.size()-1){
stream<<",";
}
}
}
return stream.str();
}
SceneNode::nodeTypeE getNodeType(Alembic::Abc::IObject iObj)
{
AbcG::MetaData metadata = iObj.getMetaData();
if(AbcG::IXform::matches(metadata)){
return SceneNode::ITRANSFORM;
//Note: this method assumes everything is an ITRANSFORM, this is corrected later on in the the method that builds the common scene graph
}
else if(AbcG::IPolyMesh::matches(metadata) ||
AbcG::ISubD::matches(metadata) ){
return SceneNode::POLYMESH;
}
else if(AbcG::ICamera::matches(metadata)){
return SceneNode::CAMERA;
}
else if(AbcG::IPoints::matches(metadata)){
return SceneNode::PARTICLES;
}
else if(AbcG::ICurves::matches(metadata)){
return SceneNode::CURVES;
}
else if(AbcG::ILight::matches(metadata)){
return SceneNode::LIGHT;
}
else if(AbcG::INuPatch::matches(metadata)){
return SceneNode::SURFACE;
}
return SceneNode::UNKNOWN;
}
struct AlembicISceneBuildElement
{
AbcObjectCache *pObjectCache;
SceneNodePtr parentNode;
AlembicISceneBuildElement(AbcObjectCache *pMyObjectCache, SceneNodePtr node):pObjectCache(pMyObjectCache), parentNode(node)
{}
};
SceneNodeAlembicPtr buildAlembicSceneGraph(AbcArchiveCache *pArchiveCache, AbcObjectCache *pRootObjectCache, int& nNumNodes)
{
ESS_PROFILE_SCOPE("buildAlembicSceneGraph");
std::list<AlembicISceneBuildElement> sceneStack;
Alembic::Abc::IObject rootObj = pRootObjectCache->obj;
SceneNodeAlembicPtr sceneRoot(new SceneNodeAlembic(pRootObjectCache));
sceneRoot->name = rootObj.getName();
sceneRoot->dccIdentifier = rootObj.getFullName();
sceneRoot->type = SceneNode::SCENE_ROOT;
for(size_t j=0; j<pRootObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( pRootObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, sceneRoot));
}
//sceneStack.push_back(AlembicISceneBuildElement(pRootObjectCache, NULL));
int numNodes = 0;
while( !sceneStack.empty() )
{
AlembicISceneBuildElement sElement = sceneStack.back();
Alembic::Abc::IObject iObj = sElement.pObjectCache->obj;
SceneNodePtr parentNode = sElement.parentNode;
sceneStack.pop_back();
numNodes++;
SceneNodeAlembicPtr newNode(new SceneNodeAlembic(sElement.pObjectCache));
newNode->name = iObj.getName();
newNode->dccIdentifier = iObj.getFullName();
newNode->type = getNodeType(iObj);
//select every node by default
newNode->selected = true;
if(parentNode){ //create bi-direction link if there is a parent
newNode->parent = parentNode.get();
parentNode->children.push_back(newNode);
//the parent transforms of geometry nodes should be to be external transforms
//(we don't a transform's type until we have seen what type(s) of child it has)
if( NodeCategory::get(iObj) == NodeCategory::GEOMETRY ){
if(parentNode->type == SceneNode::ITRANSFORM){
parentNode->type = SceneNode::ETRANSFORM;
}
else{
ESS_LOG_WARNING("node "<<iObj.getFullName()<<" does not have a parent transform.");
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(size_t j=0; j<sElement.pObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( sElement.pObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, newNode));
}
}
nNumNodes = numNodes;
return sceneRoot;
}
struct AttachStackElement
{
SceneNodeAppPtr currAppNode;
SceneNodeAlembicPtr currFileNode;
AttachStackElement(SceneNodeAppPtr appNode, SceneNodeAlembicPtr fileNode): currAppNode(appNode), currFileNode(fileNode)
{}
};
bool AttachSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams, CommonProgressBar *pbar)
{
ESS_PROFILE_SCOPE("AttachSceneFile");
//TODO: how to account for filtering?
//it would break the sibling namespace assumption. Perhaps we should require that all parent nodes of selected are imported.
//We would then not traverse unselected children
std::list<AttachStackElement> sceneStack;
for(SceneChildIterator it = appRoot->children.begin(); it != appRoot->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back(AttachStackElement(appNode, fileRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
if (pbar) pbar->start();
int count = 50;
while( !sceneStack.empty() )
{
if (count == 0)
{
count = 50;
if (pbar && pbar->isCancelled())
{
EC_LOG_WARNING("Import job cancelled by user");
return false;
}
if (pbar) pbar->incr(50);
}
else
--count;
AttachStackElement sElement = sceneStack.back();
SceneNodeAppPtr currAppNode = sElement.currAppNode;
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAlembicPtr newFileNode = currFileNode;
//Each set of siblings names in an Alembic file exist within a namespace
//This is not true for 3DS Max scene graphs, so we check for such conflicts using the "attached appNode flag"
bool bChildAttached = false;
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(currAppNode->name == fileNode->name){
ESS_LOG_WARNING("nodeMatch: "<<(*it)->name<<" = "<<fileNode->name);
if(fileNode->isAttached()){
ESS_LOG_ERROR("More than one match for node "<<(*it)->name);
return false;
}
else{
bChildAttached = currAppNode->replaceData(fileNode, jobParams, newFileNode);
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currAppNode->children.begin(); it != currAppNode->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back( AttachStackElement( appNode, newFileNode ) );
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
if (pbar) pbar->stop();
return true;
}
struct ImportStackElement
{
SceneNodeAlembicPtr currFileNode;
SceneNodeAppPtr parentAppNode;
ImportStackElement(SceneNodeAlembicPtr node, SceneNodeAppPtr parent):currFileNode(node), parentAppNode(parent)
{}
};
bool ImportSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams, CommonProgressBar *pbar)
{
ESS_PROFILE_SCOPE("ImportSceneFile");
//TODO skip unselected children, if thats we how we do filtering.
//compare to application scene graph to see if we need to rename nodes (or maybe we might throw an error)
std::list<ImportStackElement> sceneStack;
for(SceneChildIterator it = fileRoot->children.begin(); it != fileRoot->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
sceneStack.push_back(ImportStackElement(fileNode, appRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
if (pbar) pbar->start();
int count = 50;
while( !sceneStack.empty() )
{
if (count == 0)
{
count = 50;
if (pbar && pbar->isCancelled())
{
EC_LOG_WARNING("Import job cancelled by user");
return false;
}
if (pbar) pbar->incr(50);
}
else
--count;
ImportStackElement sElement = sceneStack.back();
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
SceneNodeAppPtr parentAppNode = sElement.parentAppNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAppPtr newAppNode;
bool bContinue = parentAppNode->addChild(currFileNode, jobParams, newAppNode);
if(!bContinue){
return false;
}
if(newAppNode){
//ESS_LOG_WARNING("newAppNode: "<<newAppNode->name<<" useCount: "<<newAppNode.use_count());
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(!fileNode->isSupported()) continue;
if( fileNode->isMerged() ){
//The child node was merged with its parent, so skip this child, and add its children
//(Although this case is technically possible, I think it will not be common)
SceneNodePtr& mergedChild = *it;
for(SceneChildIterator cit = mergedChild->children.begin(); cit != mergedChild->children.end(); cit++){
SceneNodeAlembicPtr cfileNode = reinterpret<SceneNode, SceneNodeAlembic>(*cit);
sceneStack.push_back( ImportStackElement( cfileNode, newAppNode ) );
}
}
else{
sceneStack.push_back( ImportStackElement( fileNode, newAppNode ) );
}
}
}
else{
//ESS_LOG_WARNING("newAppNode useCount: "<<newAppNode.use_count());
if( currFileNode->children.empty() == false ) {
EC_LOG_WARNING("Unsupported node: " << currFileNode->name << " has children that have not been imported." );
}
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
if (pbar) pbar->stop();
return true;
}
<commit_msg>more stuff for the progress bar!<commit_after>#include "CommonImport.h"
#include "CommonUtilities.h"
#include "CommonMeshUtilities.h"
#include "CommonAlembic.h"
#include <boost/algorithm/string.hpp>
#include <sstream>
bool parseBool(std::string value){
//std::istringstream(valuePair[1]) >> bExportSelected;
if( value.find("true") != std::string::npos || value.find("1") != std::string::npos ){
return true;
}
else{
return false;
}
}
bool IJobStringParser::parse(const std::string& jobString)
{
std::vector<std::string> tokens;
boost::split(tokens, jobString, boost::is_any_of(";"));
//if(tokens.empty()){
// return false;
//}
for(int j=0; j<tokens.size(); j++){
std::vector<std::string> valuePair;
boost::split(valuePair, tokens[j], boost::is_any_of("="));
if(valuePair.size() != 2){
ESS_LOG_WARNING("Skipping invalid token: "<<tokens[j]);
continue;
}
if(boost::iequals(valuePair[0], "filename")){
filename = valuePair[1];
}
else if(boost::iequals(valuePair[0], "normals")){
importNormals = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "uvs")){
importUVs = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "facesets")){
importFacesets = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "materialIds")){
importMaterialIds = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "attachToExisting")){
attachToExisting = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importStandinProperties")){
importStandinProperties = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importBoundingBoxes")){
importBoundingBoxes = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "importVisibilityControllers")){
importVisibilityControllers = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "failOnUnsupported")){
failOnUnsupported = parseBool(valuePair[1]);
}
else if(boost::iequals(valuePair[0], "filters") || boost::iequals(valuePair[0], "identifiers")){
boost::split(nodesToImport, valuePair[1], boost::is_any_of(","));
}
else if(boost::iequals(valuePair[0], "includeChildren")){
includeChildren = parseBool(valuePair[1]);
}
else
{
extraParameters[valuePair[0]] = valuePair[1];
}
}
return true;
}
std::string IJobStringParser::buildJobString()
{
////Note: there are currently some minor differences between the apps. This function is somewhat XSI specific.
std::stringstream stream;
if(!filename.empty()){
stream<<"filename="<<filename<<";";
}
stream<<"normals="<<importNormals<<";uvs="<<importUVs<<";facesets="<<importFacesets;
stream<<";importVisibilityControllers="<<importVisibilityControllers<<";importStandinProperties="<<importStandinProperties;
stream<<";importBoundingBoxes="<<importBoundingBoxes<<";attachToExisting="<<attachToExisting<<";failOnUnsupported="<<failOnUnsupported;
if(!nodesToImport.empty()){
stream<<";identifiers=";
for(int i=0; i<nodesToImport.size(); i++){
stream<<nodesToImport[i];
if(i != nodesToImport.size()-1){
stream<<",";
}
}
}
return stream.str();
}
SceneNode::nodeTypeE getNodeType(Alembic::Abc::IObject iObj)
{
AbcG::MetaData metadata = iObj.getMetaData();
if(AbcG::IXform::matches(metadata)){
return SceneNode::ITRANSFORM;
//Note: this method assumes everything is an ITRANSFORM, this is corrected later on in the the method that builds the common scene graph
}
else if(AbcG::IPolyMesh::matches(metadata) ||
AbcG::ISubD::matches(metadata) ){
return SceneNode::POLYMESH;
}
else if(AbcG::ICamera::matches(metadata)){
return SceneNode::CAMERA;
}
else if(AbcG::IPoints::matches(metadata)){
return SceneNode::PARTICLES;
}
else if(AbcG::ICurves::matches(metadata)){
return SceneNode::CURVES;
}
else if(AbcG::ILight::matches(metadata)){
return SceneNode::LIGHT;
}
else if(AbcG::INuPatch::matches(metadata)){
return SceneNode::SURFACE;
}
return SceneNode::UNKNOWN;
}
struct AlembicISceneBuildElement
{
AbcObjectCache *pObjectCache;
SceneNodePtr parentNode;
AlembicISceneBuildElement(AbcObjectCache *pMyObjectCache, SceneNodePtr node):pObjectCache(pMyObjectCache), parentNode(node)
{}
};
SceneNodeAlembicPtr buildAlembicSceneGraph(AbcArchiveCache *pArchiveCache, AbcObjectCache *pRootObjectCache, int& nNumNodes)
{
ESS_PROFILE_SCOPE("buildAlembicSceneGraph");
std::list<AlembicISceneBuildElement> sceneStack;
Alembic::Abc::IObject rootObj = pRootObjectCache->obj;
SceneNodeAlembicPtr sceneRoot(new SceneNodeAlembic(pRootObjectCache));
sceneRoot->name = rootObj.getName();
sceneRoot->dccIdentifier = rootObj.getFullName();
sceneRoot->type = SceneNode::SCENE_ROOT;
for(size_t j=0; j<pRootObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( pRootObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, sceneRoot));
}
//sceneStack.push_back(AlembicISceneBuildElement(pRootObjectCache, NULL));
int numNodes = 0;
while( !sceneStack.empty() )
{
AlembicISceneBuildElement sElement = sceneStack.back();
Alembic::Abc::IObject iObj = sElement.pObjectCache->obj;
SceneNodePtr parentNode = sElement.parentNode;
sceneStack.pop_back();
numNodes++;
SceneNodeAlembicPtr newNode(new SceneNodeAlembic(sElement.pObjectCache));
newNode->name = iObj.getName();
newNode->dccIdentifier = iObj.getFullName();
newNode->type = getNodeType(iObj);
//select every node by default
newNode->selected = true;
if(parentNode){ //create bi-direction link if there is a parent
newNode->parent = parentNode.get();
parentNode->children.push_back(newNode);
//the parent transforms of geometry nodes should be to be external transforms
//(we don't a transform's type until we have seen what type(s) of child it has)
if( NodeCategory::get(iObj) == NodeCategory::GEOMETRY ){
if(parentNode->type == SceneNode::ITRANSFORM){
parentNode->type = SceneNode::ETRANSFORM;
}
else{
ESS_LOG_WARNING("node "<<iObj.getFullName()<<" does not have a parent transform.");
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(size_t j=0; j<sElement.pObjectCache->childIdentifiers.size(); j++)
{
AbcObjectCache *pChildObjectCache = &( pArchiveCache->find( sElement.pObjectCache->childIdentifiers[j] )->second );
Alembic::AbcGeom::IObject childObj = pChildObjectCache->obj;
NodeCategory::type childCat = NodeCategory::get(childObj);
//we should change this to explicity check which node types are not support (e.g. facesets), so that we can still give out warnings
if( childCat == NodeCategory::UNSUPPORTED ) continue;// skip over unsupported types
sceneStack.push_back(AlembicISceneBuildElement(pChildObjectCache, newNode));
}
}
nNumNodes = numNodes;
return sceneRoot;
}
struct AttachStackElement
{
SceneNodeAppPtr currAppNode;
SceneNodeAlembicPtr currFileNode;
AttachStackElement(SceneNodeAppPtr appNode, SceneNodeAlembicPtr fileNode): currAppNode(appNode), currFileNode(fileNode)
{}
};
bool AttachSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams, CommonProgressBar *pbar)
{
ESS_PROFILE_SCOPE("AttachSceneFile");
//TODO: how to account for filtering?
//it would break the sibling namespace assumption. Perhaps we should require that all parent nodes of selected are imported.
//We would then not traverse unselected children
std::list<AttachStackElement> sceneStack;
for(SceneChildIterator it = appRoot->children.begin(); it != appRoot->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back(AttachStackElement(appNode, fileRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
if (pbar) pbar->start();
int count = 20;
while( !sceneStack.empty() )
{
if (count == 0)
{
count = 20;
if (pbar && pbar->isCancelled())
{
EC_LOG_WARNING("Attach job cancelled by user");
pbar->stop();
return false;
}
}
else
--count;
if (pbar) pbar->incr(1);
AttachStackElement sElement = sceneStack.back();
SceneNodeAppPtr currAppNode = sElement.currAppNode;
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAlembicPtr newFileNode = currFileNode;
//Each set of siblings names in an Alembic file exist within a namespace
//This is not true for 3DS Max scene graphs, so we check for such conflicts using the "attached appNode flag"
bool bChildAttached = false;
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(currAppNode->name == fileNode->name){
ESS_LOG_WARNING("nodeMatch: "<<(*it)->name<<" = "<<fileNode->name);
if(fileNode->isAttached()){
ESS_LOG_ERROR("More than one match for node "<<(*it)->name);
if (pbar) pbar->stop();
return false;
}
else{
bChildAttached = currAppNode->replaceData(fileNode, jobParams, newFileNode);
}
}
}
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currAppNode->children.begin(); it != currAppNode->children.end(); it++){
SceneNodeAppPtr appNode = reinterpret<SceneNode, SceneNodeApp>(*it);
sceneStack.push_back( AttachStackElement( appNode, newFileNode ) );
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
if (pbar) pbar->stop();
return true;
}
struct ImportStackElement
{
SceneNodeAlembicPtr currFileNode;
SceneNodeAppPtr parentAppNode;
ImportStackElement(SceneNodeAlembicPtr node, SceneNodeAppPtr parent):currFileNode(node), parentAppNode(parent)
{}
};
bool ImportSceneFile(SceneNodeAlembicPtr fileRoot, SceneNodeAppPtr appRoot, const IJobStringParser& jobParams, CommonProgressBar *pbar)
{
ESS_PROFILE_SCOPE("ImportSceneFile");
//TODO skip unselected children, if thats we how we do filtering.
//compare to application scene graph to see if we need to rename nodes (or maybe we might throw an error)
std::list<ImportStackElement> sceneStack;
for(SceneChildIterator it = fileRoot->children.begin(); it != fileRoot->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
sceneStack.push_back(ImportStackElement(fileNode, appRoot));
}
//TODO: abstract progress
//int intermittentUpdateInterval = std::max( (int)(nNumNodes / 100), (int)1 );
//int i = 0;
if (pbar) pbar->start();
int count = 20;
while( !sceneStack.empty() )
{
if (count == 0)
{
count = 20;
if (pbar && pbar->isCancelled())
{
EC_LOG_WARNING("Import job cancelled by user");
pbar->stop();
return false;
}
if (pbar) pbar->incr(1);
}
else
--count;
if (pbar) pbar->incr(1);
ImportStackElement sElement = sceneStack.back();
SceneNodeAlembicPtr currFileNode = sElement.currFileNode;
SceneNodeAppPtr parentAppNode = sElement.parentAppNode;
sceneStack.pop_back();
//if( i % intermittentUpdateInterval == 0 ) {
// prog.PutCaption(L"Importing "+CString(iObj.getFullName().c_str())+L" ...");
//}
//i++;
SceneNodeAppPtr newAppNode;
bool bContinue = parentAppNode->addChild(currFileNode, jobParams, newAppNode);
if(!bContinue){
if (pbar) pbar->stop();
return false;
}
if(newAppNode){
//ESS_LOG_WARNING("newAppNode: "<<newAppNode->name<<" useCount: "<<newAppNode.use_count());
//push the children as the last step, since we need to who the parent is first (we may have merged)
for(SceneChildIterator it = currFileNode->children.begin(); it != currFileNode->children.end(); it++){
SceneNodeAlembicPtr fileNode = reinterpret<SceneNode, SceneNodeAlembic>(*it);
if(!fileNode->isSupported()) continue;
if( fileNode->isMerged() ){
//The child node was merged with its parent, so skip this child, and add its children
//(Although this case is technically possible, I think it will not be common)
SceneNodePtr& mergedChild = *it;
for(SceneChildIterator cit = mergedChild->children.begin(); cit != mergedChild->children.end(); cit++){
SceneNodeAlembicPtr cfileNode = reinterpret<SceneNode, SceneNodeAlembic>(*cit);
sceneStack.push_back( ImportStackElement( cfileNode, newAppNode ) );
}
}
else{
sceneStack.push_back( ImportStackElement( fileNode, newAppNode ) );
}
}
}
else{
//ESS_LOG_WARNING("newAppNode useCount: "<<newAppNode.use_count());
if( currFileNode->children.empty() == false ) {
EC_LOG_WARNING("Unsupported node: " << currFileNode->name << " has children that have not been imported." );
}
}
//if(prog.IsCancelPressed()){
// break;
//}
//prog.Increment();
}
if (pbar) pbar->stop();
return true;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: AccessibilityHints.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2006-07-21 12:59:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "AccessibilityHints.hxx"
using namespace ::com::sun::star;
// -----------------------------------------------------------------------
TYPEINIT1(ScAccWinFocusLostHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccWinFocusLostHint - the current window lost its focus (to another application, view or document)
// -----------------------------------------------------------------------
ScAccWinFocusLostHint::ScAccWinFocusLostHint(
const uno::Reference< uno::XInterface >& xOld )
:
xOldAccessible(xOld)
{
}
ScAccWinFocusLostHint::~ScAccWinFocusLostHint()
{
}
// -----------------------------------------------------------------------
TYPEINIT1(ScAccWinFocusGotHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccWinFocusGotHint - the window got the focus (from another application, view or document)
// -----------------------------------------------------------------------
ScAccWinFocusGotHint::ScAccWinFocusGotHint(
const uno::Reference< uno::XInterface >& xNew )
:
xNewAccessible(xNew)
{
}
ScAccWinFocusGotHint::~ScAccWinFocusGotHint()
{
}
// -----------------------------------------------------------------------
TYPEINIT1(ScAccGridWinFocusLostHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccGridWinFocusLostHint - the current grid window lost its focus (to another application, view or document)
// -----------------------------------------------------------------------
ScAccGridWinFocusLostHint::ScAccGridWinFocusLostHint(ScSplitPos eOld,
const uno::Reference< uno::XInterface >& xOld )
:
ScAccWinFocusLostHint(xOld),
eOldGridWin(eOld)
{
}
ScAccGridWinFocusLostHint::~ScAccGridWinFocusLostHint()
{
}
// -----------------------------------------------------------------------
TYPEINIT1(ScAccGridWinFocusGotHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccGridWinFocusGotHint - the grid window got the focus (from another application, view or document)
// -----------------------------------------------------------------------
ScAccGridWinFocusGotHint::ScAccGridWinFocusGotHint(ScSplitPos eNew,
const uno::Reference< uno::XInterface >& xNew )
:
ScAccWinFocusGotHint(xNew),
eNewGridWin(eNew)
{
}
ScAccGridWinFocusGotHint::~ScAccGridWinFocusGotHint()
{
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.492); FILE MERGED 2008/03/31 17:15:06 rt 1.7.492.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: AccessibilityHints.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "AccessibilityHints.hxx"
using namespace ::com::sun::star;
// -----------------------------------------------------------------------
TYPEINIT1(ScAccWinFocusLostHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccWinFocusLostHint - the current window lost its focus (to another application, view or document)
// -----------------------------------------------------------------------
ScAccWinFocusLostHint::ScAccWinFocusLostHint(
const uno::Reference< uno::XInterface >& xOld )
:
xOldAccessible(xOld)
{
}
ScAccWinFocusLostHint::~ScAccWinFocusLostHint()
{
}
// -----------------------------------------------------------------------
TYPEINIT1(ScAccWinFocusGotHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccWinFocusGotHint - the window got the focus (from another application, view or document)
// -----------------------------------------------------------------------
ScAccWinFocusGotHint::ScAccWinFocusGotHint(
const uno::Reference< uno::XInterface >& xNew )
:
xNewAccessible(xNew)
{
}
ScAccWinFocusGotHint::~ScAccWinFocusGotHint()
{
}
// -----------------------------------------------------------------------
TYPEINIT1(ScAccGridWinFocusLostHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccGridWinFocusLostHint - the current grid window lost its focus (to another application, view or document)
// -----------------------------------------------------------------------
ScAccGridWinFocusLostHint::ScAccGridWinFocusLostHint(ScSplitPos eOld,
const uno::Reference< uno::XInterface >& xOld )
:
ScAccWinFocusLostHint(xOld),
eOldGridWin(eOld)
{
}
ScAccGridWinFocusLostHint::~ScAccGridWinFocusLostHint()
{
}
// -----------------------------------------------------------------------
TYPEINIT1(ScAccGridWinFocusGotHint, SfxHint);
// -----------------------------------------------------------------------
// ScAccGridWinFocusGotHint - the grid window got the focus (from another application, view or document)
// -----------------------------------------------------------------------
ScAccGridWinFocusGotHint::ScAccGridWinFocusGotHint(ScSplitPos eNew,
const uno::Reference< uno::XInterface >& xNew )
:
ScAccWinFocusGotHint(xNew),
eNewGridWin(eNew)
{
}
ScAccGridWinFocusGotHint::~ScAccGridWinFocusGotHint()
{
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <iostream>
#include <fstream>
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include "script/standard.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
void EnsureWalletIsUnlocked();
namespace bt = boost::posix_time;
// Extended DecodeDumpTime implementation, see this page for details:
// http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
const std::locale formats[] = {
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
};
const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
std::time_t pt_to_time_t(const bt::ptime& pt)
{
bt::ptime timet_start(boost::gregorian::date(1970,1,1));
bt::time_duration diff = pt - timet_start;
return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
}
int64_t DecodeDumpTime(const std::string& s)
{
bt::ptime pt;
for(size_t i=0; i<formats_n; ++i)
{
std::istringstream is(s);
is.imbue(formats[i]);
is >> pt;
if(pt != bt::ptime()) break;
}
return pt_to_time_t(pt);
}
std::string static EncodeDumpTime(int64_t nTime) {
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
std::string static EncodeDumpString(const std::string &str) {
std::stringstream ret;
BOOST_FOREACH(unsigned char c, str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos+2 < str.length()) {
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
pos += 2;
}
ret << c;
}
return ret.str();
}
class CTxDump
{
public:
CBlockIndex *pindex;
int64_t nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
UniValue importprivkey(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"importprivkey <Neutronprivkey> [label]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID vchAddress = key.GetPubKey().GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress))
return NullUniValue;
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKey(key))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
// whenever a key is imported, we need to scan the whole chain
pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"importwallet <filename>\n"
"Imports keys from a wallet dump file (see dumpwallet).");
EnsureWalletIsUnlocked();
ifstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
int64_t nTimeBegin = pindexBest->nTime;
bool fGood = true;
while (file.good()) {
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(vstr[0]))
continue;
bool fCompressed;
CKey key;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID keyid = key.GetPubKey().GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str());
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str());
if (!pwalletMain->AddKey(key)) {
fGood = false;
continue;
}
pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwalletMain->SetAddressBookName(keyid, strLabel);
nTimeBegin = std::min(nTimeBegin, nTime);
}
file.close();
CBlockIndex *pindex = pindexBest;
while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)
pindex = pindex->pprev;
if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
pwalletMain->nTimeFirstKey = nTimeBegin;
LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1);
pwalletMain->ScanForWalletTransactions(pindex);
pwalletMain->ReacceptWalletTransactions();
pwalletMain->MarkDirty();
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return NullUniValue;
}
UniValue dumpprivkey(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <Neutronaddress>\n"
"Reveals the private key corresponding to <Neutronaddress>.");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Neutron address");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CSecret vchSecret;
bool fCompressed;
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret, fCompressed).ToString();
}
UniValue dumpwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpwallet <filename>\n"
"Dumps all wallet keys in a human-readable format.");
EnsureWalletIsUnlocked();
ofstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CKeyID, int64_t> mapKeyBirth;
std::set<CKeyID> setKeyPool;
pwalletMain->GetKeyBirthTimes(mapKeyBirth);
pwalletMain->GetAllReserveKeys(setKeyPool);
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
vKeyBirth.push_back(std::make_pair(it->second, it->first));
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by Neutron %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str());
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str());
file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str());
file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str());
file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr = CBitcoinAddress(keyid).ToString();
bool IsCompressed;
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
if (pwalletMain->mapAddressBook.count(keyid)) {
CSecret secret = key.GetSecret(IsCompressed);
file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwalletMain->mapAddressBook[keyid]).c_str(), strAddr.c_str());
} else if (setKeyPool.count(keyid)) {
CSecret secret = key.GetSecret(IsCompressed);
file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str());
} else {
CSecret secret = key.GetSecret(IsCompressed);
file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str());
}
}
}
file << "\n";
file << "# End of dump\n";
file.close();
return NullUniValue;
}
<commit_msg>Add some additional debug maessages to rpcdump.cpp<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <iostream>
#include <fstream>
#include "init.h" // for pwalletMain
#include "bitcoinrpc.h"
#include "ui_interface.h"
#include "base58.h"
#include "script/standard.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/variant/get.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
void EnsureWalletIsUnlocked();
namespace bt = boost::posix_time;
// Extended DecodeDumpTime implementation, see this page for details:
// http://stackoverflow.com/questions/3786201/parsing-of-date-time-from-string-boost
const std::locale formats[] = {
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%dT%H:%M:%SZ")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y/%m/%d %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%d.%m.%Y %H:%M:%S")),
std::locale(std::locale::classic(),new bt::time_input_facet("%Y-%m-%d"))
};
const size_t formats_n = sizeof(formats)/sizeof(formats[0]);
std::time_t pt_to_time_t(const bt::ptime& pt)
{
bt::ptime timet_start(boost::gregorian::date(1970,1,1));
bt::time_duration diff = pt - timet_start;
return diff.ticks()/bt::time_duration::rep_type::ticks_per_second;
}
int64_t DecodeDumpTime(const std::string& s)
{
bt::ptime pt;
for(size_t i=0; i<formats_n; ++i)
{
std::istringstream is(s);
is.imbue(formats[i]);
is >> pt;
if(pt != bt::ptime()) break;
}
return pt_to_time_t(pt);
}
std::string static EncodeDumpTime(int64_t nTime) {
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
std::string static EncodeDumpString(const std::string &str) {
std::stringstream ret;
BOOST_FOREACH(unsigned char c, str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos+2 < str.length()) {
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
pos += 2;
}
ret << c;
}
return ret.str();
}
class CTxDump
{
public:
CBlockIndex *pindex;
int64_t nValue;
bool fSpent;
CWalletTx* ptx;
int nOut;
CTxDump(CWalletTx* ptx = NULL, int nOut = -1)
{
pindex = NULL;
nValue = 0;
fSpent = false;
this->ptx = ptx;
this->nOut = nOut;
}
};
UniValue importprivkey(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
{
throw runtime_error(
"importprivkey <Neutronprivkey> [label]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
}
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID vchAddress = key.GetPubKey().GetID();
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress))
{
LogPrintf("%s: Supplied key is already in wallet\n", __func__);
return NullUniValue;
}
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKey(key))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
else
LogPrintf("%s : Added key for address %s\n", __func__, CBitcoinAddress(key.GetPubKey().GetID()).ToString());
// whenever a key is imported, we need to scan the whole chain
pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
pwalletMain->MarkDirty();
}
return NullUniValue;
}
UniValue importwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"importwallet <filename>\n"
"Imports keys from a wallet dump file (see dumpwallet).");
EnsureWalletIsUnlocked();
ifstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
int64_t nTimeBegin = pindexBest->nTime;
bool fGood = true;
while (file.good()) {
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(vstr[0]))
continue;
bool fCompressed;
CKey key;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
CKeyID keyid = key.GetPubKey().GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString().c_str());
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString().c_str());
if (!pwalletMain->AddKey(key)) {
fGood = false;
continue;
}
pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwalletMain->SetAddressBookName(keyid, strLabel);
nTimeBegin = std::min(nTimeBegin, nTime);
}
file.close();
CBlockIndex *pindex = pindexBest;
while (pindex && pindex->pprev && pindex->nTime > nTimeBegin - 7200)
pindex = pindex->pprev;
if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
pwalletMain->nTimeFirstKey = nTimeBegin;
LogPrintf("Rescanning last %i blocks\n", pindexBest->nHeight - pindex->nHeight + 1);
pwalletMain->ScanForWalletTransactions(pindex);
pwalletMain->ReacceptWalletTransactions();
pwalletMain->MarkDirty();
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return NullUniValue;
}
UniValue dumpprivkey(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <Neutronaddress>\n"
"Reveals the private key corresponding to <Neutronaddress>.");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Neutron address");
if (fWalletUnlockStakingOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Wallet is unlocked for staking only.");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CSecret vchSecret;
bool fCompressed;
if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret, fCompressed).ToString();
}
UniValue dumpwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpwallet <filename>\n"
"Dumps all wallet keys in a human-readable format.");
EnsureWalletIsUnlocked();
ofstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CKeyID, int64_t> mapKeyBirth;
std::set<CKeyID> setKeyPool;
pwalletMain->GetKeyBirthTimes(mapKeyBirth);
pwalletMain->GetAllReserveKeys(setKeyPool);
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
vKeyBirth.push_back(std::make_pair(it->second, it->first));
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by Neutron %s (%s)\n", CLIENT_BUILD.c_str(), CLIENT_DATE.c_str());
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()).c_str());
file << strprintf("# * Best block at time of backup was %i (%s),\n", nBestHeight, hashBestChain.ToString().c_str());
file << strprintf("# mined on %s\n", EncodeDumpTime(pindexBest->nTime).c_str());
file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr = CBitcoinAddress(keyid).ToString();
bool IsCompressed;
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
if (pwalletMain->mapAddressBook.count(keyid)) {
CSecret secret = key.GetSecret(IsCompressed);
file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), EncodeDumpString(pwalletMain->mapAddressBook[keyid]).c_str(), strAddr.c_str());
} else if (setKeyPool.count(keyid)) {
CSecret secret = key.GetSecret(IsCompressed);
file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str());
} else {
CSecret secret = key.GetSecret(IsCompressed);
file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(secret, IsCompressed).ToString().c_str(), strTime.c_str(), strAddr.c_str());
}
}
}
file << "\n";
file << "# End of dump\n";
file.close();
return NullUniValue;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/screen_lock_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/user_view.h"
#include "chrome/browser/chromeos/login/username_view.h"
#include "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "chrome/browser/chromeos/login/textfield_with_margin.h"
#include "chrome/browser/chromeos/views/copy_background.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/border.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
namespace chromeos {
namespace {
const int kCornerRadius = 5;
// A Textfield for password, which also sets focus to itself
// when a mouse is clicked on it. This is necessary in screen locker
// as mouse events are grabbed in the screen locker.
class PasswordField : public TextfieldWithMargin {
public:
PasswordField()
: TextfieldWithMargin(views::Textfield::STYLE_PASSWORD) {
set_text_to_display_when_empty(
l10n_util::GetStringUTF16(IDS_LOGIN_EMPTY_PASSWORD_TEXT));
}
// views::View overrides.
virtual bool OnMousePressed(const views::MouseEvent& e) {
RequestFocus();
return false;
}
private:
DISALLOW_COPY_AND_ASSIGN(PasswordField);
};
} // namespace
using views::GridLayout;
using login::kBorderSize;
ScreenLockView::ScreenLockView(ScreenLocker* screen_locker)
: user_view_(NULL),
password_field_(NULL),
screen_locker_(screen_locker),
main_(NULL),
username_(NULL) {
DCHECK(screen_locker_);
}
gfx::Size ScreenLockView::GetPreferredSize() {
return main_->GetPreferredSize();
}
void ScreenLockView::Layout() {
int username_height = login::kSelectedLabelHeight;
main_->SetBounds(0, 0, width(), height());
username_->SetBounds(
kBorderSize,
login::kUserImageSize - username_height + kBorderSize,
login::kUserImageSize,
username_height);
}
void ScreenLockView::Init() {
registrar_.Add(this,
NotificationType::LOGIN_USER_IMAGE_CHANGED,
NotificationService::AllSources());
user_view_ = new UserView(this,
false, // is_login
true); // need_background
main_ = new views::View();
// Use rounded rect background.
views::Painter* painter =
CreateWizardPainter(&BorderDefinition::kUserBorder);
main_->set_background(
views::Background::CreateBackgroundPainter(true, painter));
main_->set_border(CreateWizardBorder(&BorderDefinition::kUserBorder));
// Password field.
password_field_ = new PasswordField();
password_field_->SetController(this);
password_field_->set_background(new CopyBackground(main_));
// User icon.
UserManager::User user = screen_locker_->user();
user_view_->SetImage(user.image(), user.image());
// User name.
std::wstring text = UTF8ToWide(user.GetDisplayName());
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
const gfx::Font& font = rb.GetFont(ResourceBundle::MediumBoldFont);
// Layouts image, textfield and button components.
GridLayout* layout = new GridLayout(main_);
main_->SetLayoutManager(layout);
views::ColumnSet* column_set = layout->AddColumnSet(0);
column_set->AddPaddingColumn(0, kBorderSize);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kBorderSize);
column_set = layout->AddColumnSet(1);
column_set->AddPaddingColumn(0, 5);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, 5);
layout->AddPaddingRow(0, kBorderSize);
layout->StartRow(0, 0);
layout->AddView(user_view_);
layout->AddPaddingRow(0, kBorderSize);
layout->StartRow(0, 1);
layout->AddView(password_field_);
layout->AddPaddingRow(0, kBorderSize);
AddChildView(main_);
UsernameView* username = new UsernameView(text);
username_ = username;
username->SetColor(login::kTextColor);
username->SetFont(font);
AddChildView(username);
}
void ScreenLockView::ClearAndSetFocusToPassword() {
password_field_->RequestFocus();
password_field_->SetText(string16());
}
void ScreenLockView::SetSignoutEnabled(bool enabled) {
user_view_->SetSignoutEnabled(enabled);
}
gfx::Rect ScreenLockView::GetPasswordBoundsRelativeTo(const views::View* view) {
gfx::Point p;
views::View::ConvertPointToView(password_field_, view, &p);
return gfx::Rect(p, size());
}
void ScreenLockView::SetEnabled(bool enabled) {
views::View::SetEnabled(enabled);
if (!enabled) {
user_view_->StartThrobber();
// TODO(oshima): Re-enabling does not move the focus to the view
// that had a focus (issue http://crbug.com/43131).
// Clear focus on the textfield so that re-enabling can set focus
// back to the text field.
// FocusManager may be null if the view does not have
// associated Widget yet.
if (password_field_->GetFocusManager())
password_field_->GetFocusManager()->ClearFocus();
} else {
user_view_->StopThrobber();
}
password_field_->SetEnabled(enabled);
}
void ScreenLockView::OnSignout() {
screen_locker_->Signout();
}
bool ScreenLockView::HandleKeystroke(
views::Textfield* sender,
const views::Textfield::Keystroke& keystroke) {
screen_locker_->ClearErrors();
if (keystroke.GetKeyboardCode() == app::VKEY_RETURN) {
screen_locker_->Authenticate(password_field_->text());
return true;
}
return false;
}
void ScreenLockView::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type != NotificationType::LOGIN_USER_IMAGE_CHANGED || !user_view_)
return;
UserManager::User* user = Details<UserManager::User>(details).ptr();
if (screen_locker_->user().email() != user->email())
return;
user_view_->SetImage(user->image(), user->image());
}
void ScreenLockView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && this == child)
WizardAccessibilityHelper::GetInstance()->MaybeEnableAccessibility(this);
}
} // namespace chromeos
<commit_msg>[cros] Update ScreenLock view: correct password hint & layout.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/screen_lock_view.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/user_view.h"
#include "chrome/browser/chromeos/login/username_view.h"
#include "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "chrome/browser/chromeos/login/textfield_with_margin.h"
#include "chrome/browser/chromeos/views/copy_background.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/border.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
namespace chromeos {
namespace {
const int kCornerRadius = 5;
// A Textfield for password, which also sets focus to itself
// when a mouse is clicked on it. This is necessary in screen locker
// as mouse events are grabbed in the screen locker.
class PasswordField : public TextfieldWithMargin {
public:
PasswordField()
: TextfieldWithMargin(views::Textfield::STYLE_PASSWORD) {
set_text_to_display_when_empty(
l10n_util::GetStringUTF16(IDS_LOGIN_POD_EMPTY_PASSWORD_TEXT));
}
// views::View overrides.
virtual bool OnMousePressed(const views::MouseEvent& e) {
RequestFocus();
return false;
}
private:
DISALLOW_COPY_AND_ASSIGN(PasswordField);
};
} // namespace
using views::GridLayout;
using login::kBorderSize;
ScreenLockView::ScreenLockView(ScreenLocker* screen_locker)
: user_view_(NULL),
password_field_(NULL),
screen_locker_(screen_locker),
main_(NULL),
username_(NULL) {
DCHECK(screen_locker_);
}
gfx::Size ScreenLockView::GetPreferredSize() {
return main_->GetPreferredSize();
}
void ScreenLockView::Layout() {
int username_height = login::kSelectedLabelHeight;
main_->SetBounds(0, 0, width(), height());
username_->SetBounds(
kBorderSize,
login::kUserImageSize - username_height + kBorderSize,
login::kUserImageSize,
username_height);
}
void ScreenLockView::Init() {
registrar_.Add(this,
NotificationType::LOGIN_USER_IMAGE_CHANGED,
NotificationService::AllSources());
user_view_ = new UserView(this,
false, // is_login
true); // need_background
main_ = new views::View();
// Use rounded rect background.
views::Painter* painter =
CreateWizardPainter(&BorderDefinition::kUserBorder);
main_->set_background(
views::Background::CreateBackgroundPainter(true, painter));
main_->set_border(CreateWizardBorder(&BorderDefinition::kUserBorder));
// Password field.
password_field_ = new PasswordField();
password_field_->SetController(this);
password_field_->set_background(new CopyBackground(main_));
// User icon.
UserManager::User user = screen_locker_->user();
user_view_->SetImage(user.image(), user.image());
// User name.
std::wstring text = UTF8ToWide(user.GetDisplayName());
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
const gfx::Font& font = rb.GetFont(ResourceBundle::MediumBoldFont);
// Layouts image, textfield and button components.
GridLayout* layout = new GridLayout(main_);
main_->SetLayoutManager(layout);
views::ColumnSet* column_set = layout->AddColumnSet(0);
column_set->AddPaddingColumn(0, kBorderSize);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kBorderSize);
column_set = layout->AddColumnSet(1);
column_set->AddPaddingColumn(0, kBorderSize);
column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kBorderSize);
layout->AddPaddingRow(0, kBorderSize);
layout->StartRow(0, 0);
layout->AddView(user_view_);
layout->AddPaddingRow(0, kBorderSize);
layout->StartRow(0, 1);
layout->AddView(password_field_);
layout->AddPaddingRow(0, kBorderSize);
AddChildView(main_);
UsernameView* username = new UsernameView(text);
username_ = username;
username->SetColor(login::kTextColor);
username->SetFont(font);
AddChildView(username);
}
void ScreenLockView::ClearAndSetFocusToPassword() {
password_field_->RequestFocus();
password_field_->SetText(string16());
}
void ScreenLockView::SetSignoutEnabled(bool enabled) {
user_view_->SetSignoutEnabled(enabled);
}
gfx::Rect ScreenLockView::GetPasswordBoundsRelativeTo(const views::View* view) {
gfx::Point p;
views::View::ConvertPointToView(password_field_, view, &p);
return gfx::Rect(p, size());
}
void ScreenLockView::SetEnabled(bool enabled) {
views::View::SetEnabled(enabled);
if (!enabled) {
user_view_->StartThrobber();
// TODO(oshima): Re-enabling does not move the focus to the view
// that had a focus (issue http://crbug.com/43131).
// Clear focus on the textfield so that re-enabling can set focus
// back to the text field.
// FocusManager may be null if the view does not have
// associated Widget yet.
if (password_field_->GetFocusManager())
password_field_->GetFocusManager()->ClearFocus();
} else {
user_view_->StopThrobber();
}
password_field_->SetEnabled(enabled);
}
void ScreenLockView::OnSignout() {
screen_locker_->Signout();
}
bool ScreenLockView::HandleKeystroke(
views::Textfield* sender,
const views::Textfield::Keystroke& keystroke) {
screen_locker_->ClearErrors();
if (keystroke.GetKeyboardCode() == app::VKEY_RETURN) {
screen_locker_->Authenticate(password_field_->text());
return true;
}
return false;
}
void ScreenLockView::Observe(
NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type != NotificationType::LOGIN_USER_IMAGE_CHANGED || !user_view_)
return;
UserManager::User* user = Details<UserManager::User>(details).ptr();
if (screen_locker_->user().email() != user->email())
return;
user_view_->SetImage(user->image(), user->image());
}
void ScreenLockView::ViewHierarchyChanged(bool is_add,
views::View* parent,
views::View* child) {
if (is_add && this == child)
WizardAccessibilityHelper::GetInstance()->MaybeEnableAccessibility(this);
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE,
IDS_EXTENSION_ENABLE_INCOGNITO_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING,
IDS_EXTENSION_ENABLE_INCOGNITO_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON,
IDS_EXTENSION_PROMPT_ENABLE_INCOGNITO_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
// TODO(estade): remove this function when the old install UI is removed. It
// is commented out on linux/gtk due to compiler warnings.
#if !defined(TOOLKIT_GTK)
static std::wstring GetInstallWarning(Extension* extension) {
// If the extension has a plugin, it's easy: the plugin has the most severe
// warning.
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension))
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS);
// Otherwise, we go in descending order of severity: all hosts, several hosts,
// a single host, no hosts. For each of these, we also have a variation of the
// message for when api permissions are also requested.
if (extension->HasAccessToAllHosts()) {
if (extension->api_permissions().empty())
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_ALL_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_ALL_HOSTS_AND_BROWSER);
}
const std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() > 1) {
if (extension->api_permissions().empty())
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_MULTIPLE_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_MULTIPLE_HOSTS_AND_BROWSER);
}
if (hosts.size() == 1) {
if (extension->api_permissions().empty())
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_SINGLE_HOST,
UTF8ToWide(*hosts.begin()));
else
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_SINGLE_HOST_AND_BROWSER,
UTF8ToWide(*hosts.begin()));
}
DCHECK(hosts.size() == 0);
if (extension->api_permissions().empty())
return L"";
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_BROWSER);
}
#endif
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasApiPermission(Extension::kTabPermission) ||
extension->HasApiPermission(Extension::kBookmarkPermission)) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
#endif
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this))
#if defined(TOOLKIT_GTK)
, previous_use_gtk_theme_(false)
#endif
{}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_gtk_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmEnableIncognito(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(ENABLE_INCOGNITO_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(extension);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
#if defined(TOOLKIT_VIEWS)
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
if (extension->browser_action() ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
DCHECK(browser);
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(extension);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
#else
ShowExtensionInstallUIPromptImpl(
profile_, delegate_, extension_, &icon_,
WideToUTF16Hack(GetInstallWarning(extension_)), INSTALL_PROMPT);
#endif
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
case ENABLE_INCOGNITO_PROMPT: {
string16 message =
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT_WARNING_INCOGNITO,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, ENABLE_INCOGNITO_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(Extension* new_theme) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate = GetNewInfoBarDelegate(new_theme,
tab_contents);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_));
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewInfoBarDelegate(
Extension* new_theme, TabContents* tab_contents) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id_, previous_use_gtk_theme_);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id_);
#endif
}
<commit_msg>Use the infobar for installed extensions in incognito, since the browser action will not be visible.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_install_ui.h"
#include <map>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/theme_installed_infobar_delegate.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#if defined(TOOLKIT_VIEWS) // TODO(port)
#include "chrome/browser/views/extensions/extension_installed_bubble.h"
#elif defined(TOOLKIT_GTK)
#include "chrome/browser/gtk/extension_installed_bubble_gtk.h"
#endif
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/platform_util.h"
#include "chrome/common/url_constants.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#if defined(TOOLKIT_GTK)
#include "chrome/browser/extensions/gtk_theme_installed_infobar_delegate.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#endif
#if defined(OS_MACOSX)
#include "chrome/browser/cocoa/extension_installed_bubble_bridge.h"
#endif
// static
const int ExtensionInstallUI::kTitleIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_TITLE,
IDS_EXTENSION_UNINSTALL_PROMPT_TITLE,
IDS_EXTENSION_ENABLE_INCOGNITO_PROMPT_TITLE
};
// static
const int ExtensionInstallUI::kHeadingIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING,
IDS_EXTENSION_ENABLE_INCOGNITO_PROMPT_HEADING
};
// static
const int ExtensionInstallUI::kButtonIds[NUM_PROMPT_TYPES] = {
IDS_EXTENSION_PROMPT_INSTALL_BUTTON,
IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON,
IDS_EXTENSION_PROMPT_ENABLE_INCOGNITO_BUTTON
};
namespace {
// We also show the severe warning if the extension has access to any file://
// URLs. They aren't *quite* as dangerous as full access to the system via
// NPAPI, but pretty dang close. Content scripts are currently the only way
// that extension can get access to file:// URLs.
static bool ExtensionHasFileAccess(Extension* extension) {
for (UserScriptList::const_iterator script =
extension->content_scripts().begin();
script != extension->content_scripts().end();
++script) {
for (UserScript::PatternList::const_iterator pattern =
script->url_patterns().begin();
pattern != script->url_patterns().end();
++pattern) {
if (pattern->scheme() == chrome::kFileScheme)
return true;
}
}
return false;
}
// TODO(estade): remove this function when the old install UI is removed. It
// is commented out on linux/gtk due to compiler warnings.
#if !defined(TOOLKIT_GTK)
static std::wstring GetInstallWarning(Extension* extension) {
// If the extension has a plugin, it's easy: the plugin has the most severe
// warning.
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension))
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS);
// Otherwise, we go in descending order of severity: all hosts, several hosts,
// a single host, no hosts. For each of these, we also have a variation of the
// message for when api permissions are also requested.
if (extension->HasAccessToAllHosts()) {
if (extension->api_permissions().empty())
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_ALL_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_ALL_HOSTS_AND_BROWSER);
}
const std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() > 1) {
if (extension->api_permissions().empty())
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_MULTIPLE_HOSTS);
else
return l10n_util::GetString(
IDS_EXTENSION_PROMPT_WARNING_MULTIPLE_HOSTS_AND_BROWSER);
}
if (hosts.size() == 1) {
if (extension->api_permissions().empty())
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_SINGLE_HOST,
UTF8ToWide(*hosts.begin()));
else
return l10n_util::GetStringF(
IDS_EXTENSION_PROMPT_WARNING_SINGLE_HOST_AND_BROWSER,
UTF8ToWide(*hosts.begin()));
}
DCHECK(hosts.size() == 0);
if (extension->api_permissions().empty())
return L"";
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_WARNING_BROWSER);
}
#endif
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
static void GetV2Warnings(Extension* extension,
std::vector<string16>* warnings) {
if (!extension->plugins().empty() || ExtensionHasFileAccess(extension)) {
// TODO(aa): This one is a bit awkward. Should we have a separate
// presentation for this case?
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_FULL_ACCESS));
return;
}
if (extension->HasAccessToAllHosts()) {
warnings->push_back(
l10n_util::GetStringUTF16(IDS_EXTENSION_PROMPT2_WARNING_ALL_HOSTS));
} else {
std::set<std::string> hosts = extension->GetEffectiveHostPermissions();
if (hosts.size() == 1) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_1_HOST,
UTF8ToUTF16(*hosts.begin())));
} else if (hosts.size() == 2) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_2_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin()))));
} else if (hosts.size() == 3) {
warnings->push_back(
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT2_WARNING_3_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
UTF8ToUTF16(*(++++hosts.begin()))));
} else if (hosts.size() >= 4) {
warnings->push_back(
l10n_util::GetStringFUTF16(
IDS_EXTENSION_PROMPT2_WARNING_4_OR_MORE_HOSTS,
UTF8ToUTF16(*hosts.begin()),
UTF8ToUTF16(*(++hosts.begin())),
IntToString16(hosts.size() - 2)));
}
}
if (extension->HasApiPermission(Extension::kTabPermission) ||
extension->HasApiPermission(Extension::kBookmarkPermission)) {
warnings->push_back(
l10n_util::GetStringUTF16(
IDS_EXTENSION_PROMPT2_WARNING_BROWSING_HISTORY));
}
// TODO(aa): Geolocation, camera/mic, what else?
}
#endif
} // namespace
ExtensionInstallUI::ExtensionInstallUI(Profile* profile)
: profile_(profile),
ui_loop_(MessageLoop::current()),
extension_(NULL),
delegate_(NULL),
prompt_type_(NUM_PROMPT_TYPES),
ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(this))
#if defined(TOOLKIT_GTK)
, previous_use_gtk_theme_(false)
#endif
{}
void ExtensionInstallUI::ConfirmInstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
// We special-case themes to not show any confirm UI. Instead they are
// immediately installed, and then we show an infobar (see OnInstallSuccess)
// to allow the user to revert if they don't like it.
if (extension->IsTheme()) {
// Remember the current theme in case the user pressed undo.
Extension* previous_theme = profile_->GetTheme();
if (previous_theme)
previous_theme_id_ = previous_theme->id();
#if defined(TOOLKIT_GTK)
// On Linux, we also need to take the user's system settings into account
// to undo theme installation.
previous_use_gtk_theme_ =
GtkThemeProvider::GetFrom(profile_)->UseGtkTheme();
#endif
delegate->InstallUIProceed(false);
return;
}
ShowConfirmation(INSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmUninstall(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(UNINSTALL_PROMPT);
}
void ExtensionInstallUI::ConfirmEnableIncognito(Delegate* delegate,
Extension* extension) {
DCHECK(ui_loop_ == MessageLoop::current());
extension_ = extension;
delegate_ = delegate;
ShowConfirmation(ENABLE_INCOGNITO_PROMPT);
}
void ExtensionInstallUI::OnInstallSuccess(Extension* extension) {
if (extension->IsTheme()) {
ShowThemeInfoBar(extension);
return;
}
// GetLastActiveWithProfile will fail on the build bots. This needs to be
// implemented differently if any test is created which depends on
// ExtensionInstalledBubble showing.
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
#if defined(TOOLKIT_VIEWS)
if (!browser)
return;
ExtensionInstalledBubble::Show(extension, browser, icon_);
#elif defined(OS_MACOSX)
DCHECK(browser);
// Note that browser actions don't appear in incognito mode initially,
// so fall back to the generic case.
if ((extension->browser_action() && !browser->profile()->IsOffTheRecord()) ||
(extension->page_action() &&
!extension->page_action()->default_icon_path().empty())) {
ExtensionInstalledBubbleCocoa::ShowExtensionInstalledBubble(
browser->window()->GetNativeHandle(),
extension, browser, icon_);
} else {
// If the extension is of type GENERIC, meaning it doesn't have a UI
// surface to display for this window, launch infobar instead of popup
// bubble, because we have no guaranteed wrench menu button to point to.
ShowGenericExtensionInstalledInfoBar(extension);
}
#elif defined(TOOLKIT_GTK)
if (!browser)
return;
ExtensionInstalledBubbleGtk::Show(extension, browser, icon_);
#endif // TOOLKIT_VIEWS
}
void ExtensionInstallUI::OnInstallFailure(const std::string& error) {
DCHECK(ui_loop_ == MessageLoop::current());
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
platform_util::SimpleErrorBox(
browser ? browser->window()->GetNativeHandle() : NULL,
l10n_util::GetStringUTF16(IDS_EXTENSION_INSTALL_FAILURE_TITLE),
UTF8ToUTF16(error));
}
void ExtensionInstallUI::OnOverinstallAttempted(Extension* extension) {
ShowThemeInfoBar(extension);
}
void ExtensionInstallUI::OnImageLoaded(
SkBitmap* image, ExtensionResource resource, int index) {
if (image)
icon_ = *image;
else
icon_ = SkBitmap();
if (icon_.empty()) {
icon_ = *ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_EXTENSION_DEFAULT_ICON);
}
switch (prompt_type_) {
case INSTALL_PROMPT: {
NotificationService* service = NotificationService::current();
service->Notify(NotificationType::EXTENSION_WILL_SHOW_CONFIRM_DIALOG,
Source<ExtensionInstallUI>(this),
NotificationService::NoDetails());
#if defined(OS_WIN) || defined(TOOLKIT_GTK)
std::vector<string16> warnings;
GetV2Warnings(extension_, &warnings);
ShowExtensionInstallUIPrompt2Impl(
profile_, delegate_, extension_, &icon_, warnings);
#else
ShowExtensionInstallUIPromptImpl(
profile_, delegate_, extension_, &icon_,
WideToUTF16Hack(GetInstallWarning(extension_)), INSTALL_PROMPT);
#endif
break;
}
case UNINSTALL_PROMPT: {
string16 message =
l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_CONFIRMATION);
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, UNINSTALL_PROMPT);
break;
}
case ENABLE_INCOGNITO_PROMPT: {
string16 message =
l10n_util::GetStringFUTF16(IDS_EXTENSION_PROMPT_WARNING_INCOGNITO,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
ShowExtensionInstallUIPromptImpl(profile_, delegate_, extension_, &icon_,
message, ENABLE_INCOGNITO_PROMPT);
break;
}
default:
NOTREACHED() << "Unknown message";
break;
}
}
void ExtensionInstallUI::ShowThemeInfoBar(Extension* new_theme) {
if (!new_theme->IsTheme())
return;
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
// First find any previous theme preview infobars.
InfoBarDelegate* old_delegate = NULL;
for (int i = 0; i < tab_contents->infobar_delegate_count(); ++i) {
InfoBarDelegate* delegate = tab_contents->GetInfoBarDelegateAt(i);
if (delegate->AsThemePreviewInfobarDelegate()) {
old_delegate = delegate;
break;
}
}
// Then either replace that old one or add a new one.
InfoBarDelegate* new_delegate = GetNewInfoBarDelegate(new_theme,
tab_contents);
if (old_delegate)
tab_contents->ReplaceInfoBar(old_delegate, new_delegate);
else
tab_contents->AddInfoBar(new_delegate);
}
void ExtensionInstallUI::ShowConfirmation(PromptType prompt_type) {
// Load the image asynchronously. For the response, check OnImageLoaded.
prompt_type_ = prompt_type;
ExtensionResource image =
extension_->GetIconPath(Extension::EXTENSION_ICON_LARGE);
tracker_.LoadImage(extension_, image,
gfx::Size(Extension::EXTENSION_ICON_LARGE,
Extension::EXTENSION_ICON_LARGE),
ImageLoadingTracker::DONT_CACHE);
}
#if defined(OS_MACOSX)
void ExtensionInstallUI::ShowGenericExtensionInstalledInfoBar(
Extension* new_extension) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (!browser)
return;
TabContents* tab_contents = browser->GetSelectedTabContents();
if (!tab_contents)
return;
std::wstring msg = l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING,
UTF8ToWide(new_extension->name())) +
L" " + l10n_util::GetString(IDS_EXTENSION_INSTALLED_MANAGE_INFO_MAC);
InfoBarDelegate* delegate = new SimpleAlertInfoBarDelegate(
tab_contents, msg, new SkBitmap(icon_));
tab_contents->AddInfoBar(delegate);
}
#endif
InfoBarDelegate* ExtensionInstallUI::GetNewInfoBarDelegate(
Extension* new_theme, TabContents* tab_contents) {
#if defined(TOOLKIT_GTK)
return new GtkThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id_, previous_use_gtk_theme_);
#else
return new ThemeInstalledInfoBarDelegate(tab_contents, new_theme,
previous_theme_id_);
#endif
}
<|endoftext|>
|
<commit_before>// StdLib.cpp
// This file is part of the EScript programming language (http://escript.berlios.de)
//
// Copyright (C) 2011-2013 Claudius Jähn <[email protected]>
// Copyright (C) 2012 Benjamin Eikel <[email protected]>
//
// Licensed under the MIT License. See LICENSE file for details.
// ---------------------------------------------------------------------------------
#include "StdLib.h"
#include "../EScript/Basics.h"
#include "../EScript/StdObjects.h"
#include "../EScript/Objects/Callables/UserFunction.h"
#include "../EScript/Compiler/Compiler.h"
#include "../EScript/Compiler/Parser.h"
#include "../EScript/Utils/IO/IO.h"
#include "../EScript/Utils/StringUtils.h"
#include "../EScript/Consts.h"
#include "ext/JSON.h"
#include <sstream>
#include <stdlib.h>
#include <ctime>
#include <unistd.h>
#include <cstdlib>
#if defined(_WIN32)
#include <windows.h>
#endif
namespace EScript{
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if(!o) return;
if(level>maxLevel) {
std::cout << " ... " << std::endl;
return;
}
if(Array * a = dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef = a->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "]";
} else if(Map * m = dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef = m->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)
std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "}";
} else {
if(dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
std::cout.flush();
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const StringId seachPathsId("__searchPaths");
std::string file(IO::condensePath(filename));
if( IO::getEntryType(file)!=IO::TYPE_FILE ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue())){
for(ERef<Iterator> itRef = searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(IO::condensePath(valueRef.toString()+'/'+filename));
if( IO::getEntryType(s)==IO::TYPE_FILE ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
ObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const StringId mapId("__loadOnce_loadedFiles");
std::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );
Map * m = dynamic_cast<Map*>(runtime.getAttribute(mapId).getValue());
if(m==nullptr){
m = Map::create();
runtime.setAttribute(mapId, Attribute(m));
}
ObjRef obj = m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return nullptr;
}
m->setValue(create(condensedFilename), create(true));
std::unordered_map<StringId,ObjRef> staticVars;
return _loadAndExecute(runtime,condensedFilename,staticVars);
}
#if defined(_WIN32)
static LARGE_INTEGER _getPerformanceCounter();
// execute this as soon as possible (when the global static variables are initialized)
static LARGE_INTEGER _clockStart = _getPerformanceCounter();
// wrapper for the windows high performance timer.
LARGE_INTEGER _getPerformanceCounter(){
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return c;
}
#endif
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION(globals,"addSearchPath",1,1,{
static const StringId seachPathsId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(rt.getAttribute(seachPathsId).getValue());
if(searchPaths == nullptr){
searchPaths = Array::create();
rt.setAttribute(seachPathsId, Attribute(searchPaths));
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return nullptr;
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION(globals,"assert",1,2, {
if(!parameter[0].toBool()){
rt.setException(parameter.count()>1?parameter[1].toString():"Assert failed.");
}
return nullptr;
})
//! [ESF] string chr(number)
ES_FUN(globals,"chr",1,1, StringUtils::utf32_to_utf8(parameter[0].to<uint32_t>(rt)))
// clock
{
#if defined(_WIN32)
typedef LARGE_INTEGER timer_t;
static timer_t frequency;
if(!QueryPerformanceFrequency(&frequency)) {
std::cout <<("QueryPerformanceFrequency failed, timer will not work properly!");
}
//! [ESF] number clock()
ES_FUNCTION(globals,"clock",0,0,{
LARGE_INTEGER time = _getPerformanceCounter();
return static_cast<double>(time.QuadPart-_clockStart.QuadPart) / static_cast<double>(frequency.QuadPart);
})
#else
//! [ESF] number clock()
ES_FUN(globals,"clock",0,0,static_cast<double>(clock())/CLOCKS_PER_SEC)
#endif
}
typedef std::unordered_map<StringId,ObjRef> staticVarMap_t;
//! [ESF] Object eval(string, Map _staticVariables)
ES_FUNCTION(globals,"eval",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _eval(rt,
CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),
staticVars);
})
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(nullptr):static_cast<time_t>(parameter[0].to<int>(rt));
tm *d = localtime (& t );
Map * m = Map::create();
m->setValue(create("seconds"), create(d->tm_sec));
m->setValue(create("minutes"), create(d->tm_min));
m->setValue(create("hours"), create(d->tm_hour));
m->setValue(create("mday"), create(d->tm_mday));
m->setValue(create("mon"), create(d->tm_mon+1));
m->setValue(create("year"), create(d->tm_year+1900));
m->setValue(create("wday"), create(d->tm_wday));
m->setValue(create("yday"), create(d->tm_yday));
m->setValue(create("isdst"), create(d->tm_isdst));
return m;
})
//! [ESF] string|void getEnv(String)
ES_FUNCTION(globals,"getEnv",1,1,{
const char * value = std::getenv(parameter[0].toString().c_str());
if(value==nullptr)
return nullptr;
return std::string(value);
})
//! [ESF] string getOS()
ES_FUN(globals,"getOS",0,0,StdLib::getOS())
//! [ESF] Runtime getRuntime( )
ES_FUN(globals,"getRuntime",0,0, &rt)
//! [ESF] mixed load(string filename, Map _staticVars)
ES_FUNCTION(globals,"load",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _loadAndExecute(rt,findFile(rt,parameter[0].toString()),staticVars);
})
//! [ESF] mixed loadOnce(string filename)
ES_FUN(globals,"loadOnce",1,1,StdLib::loadOnce(rt,parameter[0].toString()))
//! [ESF] Number ord(String [,pos] )
ES_FUNCTION(globals,"ord",1,2, {
const uint32_t codePoint = parameter[0].to<const String*>(rt)->_getStringData().getCodePoint(parameter[1].toInt(0));
if(codePoint == static_cast<uint32_t>(~0))
return false;
else
return codePoint;
})
//! [ESF] void out(...)
ES_FUNCTION(globals,"out",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout.flush();
return nullptr;
})
//! [ESF] void outln(...)
ES_FUNCTION(globals,"outln",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout << std::endl;
return nullptr;
})
//! [ESF] BlockStatement parse(string) @deprecated
ES_FUNCTION(globals,"parse",1,1, {
std::vector<StringId> injectedStaticVars;
Compiler compiler(rt.getLogger());
auto compileUnit = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),injectedStaticVars);
return compileUnit.first.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ES_FUN(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION(globals,"print_r",0,-1, {
std::cout << "\n";
for(const auto & param : parameter) {
if(!param.isNull()) {
print_r(param.get());
}
}
return nullptr;
})
//! [ESF] number system(command)
ES_FUN(globals,"system",1,1,system(parameter[0].toString().c_str()))
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION(globals, "exec", 2, 2, {
Array * array = assertType<Array>(rt, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = nullptr;
Number * result = create(execv(parameter[0].toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
//! [ESF] number time()
ES_FUN(globals,"time",0,0,static_cast<double>(time(nullptr)))
//! [ESF] string toJSON(obj[,formatted = true])
ES_FUN(globals,"toJSON",1,2,JSON::toJSON(parameter[0].get(),parameter[1].toBool(true)))
}
}
<commit_msg>Remove unused include.<commit_after>// StdLib.cpp
// This file is part of the EScript programming language (http://escript.berlios.de)
//
// Copyright (C) 2011-2013 Claudius Jähn <[email protected]>
// Copyright (C) 2012 Benjamin Eikel <[email protected]>
//
// Licensed under the MIT License. See LICENSE file for details.
// ---------------------------------------------------------------------------------
#include "StdLib.h"
#include "../EScript/Basics.h"
#include "../EScript/StdObjects.h"
#include "../EScript/Objects/Callables/UserFunction.h"
#include "../EScript/Compiler/Compiler.h"
#include "../EScript/Utils/IO/IO.h"
#include "../EScript/Utils/StringUtils.h"
#include "../EScript/Consts.h"
#include "ext/JSON.h"
#include <sstream>
#include <stdlib.h>
#include <ctime>
#include <unistd.h>
#include <cstdlib>
#if defined(_WIN32)
#include <windows.h>
#endif
namespace EScript{
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if(!o) return;
if(level>maxLevel) {
std::cout << " ... " << std::endl;
return;
}
if(Array * a = dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef = a->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "]";
} else if(Map * m = dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef = m->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)
std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "}";
} else {
if(dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
std::cout.flush();
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const StringId seachPathsId("__searchPaths");
std::string file(IO::condensePath(filename));
if( IO::getEntryType(file)!=IO::TYPE_FILE ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue())){
for(ERef<Iterator> itRef = searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(IO::condensePath(valueRef.toString()+'/'+filename));
if( IO::getEntryType(s)==IO::TYPE_FILE ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
ObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const StringId mapId("__loadOnce_loadedFiles");
std::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );
Map * m = dynamic_cast<Map*>(runtime.getAttribute(mapId).getValue());
if(m==nullptr){
m = Map::create();
runtime.setAttribute(mapId, Attribute(m));
}
ObjRef obj = m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return nullptr;
}
m->setValue(create(condensedFilename), create(true));
std::unordered_map<StringId,ObjRef> staticVars;
return _loadAndExecute(runtime,condensedFilename,staticVars);
}
#if defined(_WIN32)
static LARGE_INTEGER _getPerformanceCounter();
// execute this as soon as possible (when the global static variables are initialized)
static LARGE_INTEGER _clockStart = _getPerformanceCounter();
// wrapper for the windows high performance timer.
LARGE_INTEGER _getPerformanceCounter(){
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return c;
}
#endif
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION(globals,"addSearchPath",1,1,{
static const StringId seachPathsId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(rt.getAttribute(seachPathsId).getValue());
if(searchPaths == nullptr){
searchPaths = Array::create();
rt.setAttribute(seachPathsId, Attribute(searchPaths));
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return nullptr;
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION(globals,"assert",1,2, {
if(!parameter[0].toBool()){
rt.setException(parameter.count()>1?parameter[1].toString():"Assert failed.");
}
return nullptr;
})
//! [ESF] string chr(number)
ES_FUN(globals,"chr",1,1, StringUtils::utf32_to_utf8(parameter[0].to<uint32_t>(rt)))
// clock
{
#if defined(_WIN32)
typedef LARGE_INTEGER timer_t;
static timer_t frequency;
if(!QueryPerformanceFrequency(&frequency)) {
std::cout <<("QueryPerformanceFrequency failed, timer will not work properly!");
}
//! [ESF] number clock()
ES_FUNCTION(globals,"clock",0,0,{
LARGE_INTEGER time = _getPerformanceCounter();
return static_cast<double>(time.QuadPart-_clockStart.QuadPart) / static_cast<double>(frequency.QuadPart);
})
#else
//! [ESF] number clock()
ES_FUN(globals,"clock",0,0,static_cast<double>(clock())/CLOCKS_PER_SEC)
#endif
}
typedef std::unordered_map<StringId,ObjRef> staticVarMap_t;
//! [ESF] Object eval(string, Map _staticVariables)
ES_FUNCTION(globals,"eval",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _eval(rt,
CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),
staticVars);
})
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(nullptr):static_cast<time_t>(parameter[0].to<int>(rt));
tm *d = localtime (& t );
Map * m = Map::create();
m->setValue(create("seconds"), create(d->tm_sec));
m->setValue(create("minutes"), create(d->tm_min));
m->setValue(create("hours"), create(d->tm_hour));
m->setValue(create("mday"), create(d->tm_mday));
m->setValue(create("mon"), create(d->tm_mon+1));
m->setValue(create("year"), create(d->tm_year+1900));
m->setValue(create("wday"), create(d->tm_wday));
m->setValue(create("yday"), create(d->tm_yday));
m->setValue(create("isdst"), create(d->tm_isdst));
return m;
})
//! [ESF] string|void getEnv(String)
ES_FUNCTION(globals,"getEnv",1,1,{
const char * value = std::getenv(parameter[0].toString().c_str());
if(value==nullptr)
return nullptr;
return std::string(value);
})
//! [ESF] string getOS()
ES_FUN(globals,"getOS",0,0,StdLib::getOS())
//! [ESF] Runtime getRuntime( )
ES_FUN(globals,"getRuntime",0,0, &rt)
//! [ESF] mixed load(string filename, Map _staticVars)
ES_FUNCTION(globals,"load",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _loadAndExecute(rt,findFile(rt,parameter[0].toString()),staticVars);
})
//! [ESF] mixed loadOnce(string filename)
ES_FUN(globals,"loadOnce",1,1,StdLib::loadOnce(rt,parameter[0].toString()))
//! [ESF] Number ord(String [,pos] )
ES_FUNCTION(globals,"ord",1,2, {
const uint32_t codePoint = parameter[0].to<const String*>(rt)->_getStringData().getCodePoint(parameter[1].toInt(0));
if(codePoint == static_cast<uint32_t>(~0))
return false;
else
return codePoint;
})
//! [ESF] void out(...)
ES_FUNCTION(globals,"out",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout.flush();
return nullptr;
})
//! [ESF] void outln(...)
ES_FUNCTION(globals,"outln",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout << std::endl;
return nullptr;
})
//! [ESF] BlockStatement parse(string) @deprecated
ES_FUNCTION(globals,"parse",1,1, {
std::vector<StringId> injectedStaticVars;
Compiler compiler(rt.getLogger());
auto compileUnit = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),injectedStaticVars);
return compileUnit.first.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ES_FUN(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION(globals,"print_r",0,-1, {
std::cout << "\n";
for(const auto & param : parameter) {
if(!param.isNull()) {
print_r(param.get());
}
}
return nullptr;
})
//! [ESF] number system(command)
ES_FUN(globals,"system",1,1,system(parameter[0].toString().c_str()))
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION(globals, "exec", 2, 2, {
Array * array = assertType<Array>(rt, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = nullptr;
Number * result = create(execv(parameter[0].toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
//! [ESF] number time()
ES_FUN(globals,"time",0,0,static_cast<double>(time(nullptr)))
//! [ESF] string toJSON(obj[,formatted = true])
ES_FUN(globals,"toJSON",1,2,JSON::toJSON(parameter[0].get(),parameter[1].toBool(true)))
}
}
<|endoftext|>
|
<commit_before>//===-- PPCHazardRecognizers.cpp - PowerPC Hazard Recognizer Impls --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements hazard recognizers for scheduling on PowerPC processors.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "pre-RA-sched"
#include "PPCHazardRecognizers.h"
#include "PPC.h"
#include "PPCInstrInfo.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// PowerPC 970 Hazard Recognizer
//
// This models the dispatch group formation of the PPC970 processor. Dispatch
// groups are bundles of up to five instructions that can contain various mixes
// of instructions. The PPC970 can dispatch a peak of 4 non-branch and one
// branch instruction per-cycle.
//
// There are a number of restrictions to dispatch group formation: some
// instructions can only be issued in the first slot of a dispatch group, & some
// instructions fill an entire dispatch group. Additionally, only branches can
// issue in the 5th (last) slot.
//
// Finally, there are a number of "structural" hazards on the PPC970. These
// conditions cause large performance penalties due to misprediction, recovery,
// and replay logic that has to happen. These cases include setting a CTR and
// branching through it in the same dispatch group, and storing to an address,
// then loading from the same address within a dispatch group. To avoid these
// conditions, we insert no-op instructions when appropriate.
//
// FIXME: This is missing some significant cases:
// 1. Modeling of microcoded instructions.
// 2. Handling of serialized operations.
// 3. Handling of the esoteric cases in "Resource-based Instruction Grouping".
//
PPCHazardRecognizer970::PPCHazardRecognizer970(const TargetInstrInfo &tii)
: TII(tii) {
EndDispatchGroup();
}
void PPCHazardRecognizer970::EndDispatchGroup() {
DOUT << "=== Start of dispatch group\n";
NumIssued = 0;
// Structural hazard info.
HasCTRSet = false;
NumStores = 0;
}
PPCII::PPC970_Unit
PPCHazardRecognizer970::GetInstrType(unsigned Opcode,
bool &isFirst, bool &isSingle,
bool &isCracked,
bool &isLoad, bool &isStore) {
if (Opcode < ISD::BUILTIN_OP_END) {
isFirst = isSingle = isCracked = isLoad = isStore = false;
return PPCII::PPC970_Pseudo;
}
Opcode -= ISD::BUILTIN_OP_END;
const TargetInstrDescriptor &TID = TII.get(Opcode);
isLoad = TID.Flags & M_LOAD_FLAG;
isStore = TID.Flags & M_STORE_FLAG;
unsigned TSFlags = TID.TSFlags;
isFirst = TSFlags & PPCII::PPC970_First;
isSingle = TSFlags & PPCII::PPC970_Single;
isCracked = TSFlags & PPCII::PPC970_Cracked;
return (PPCII::PPC970_Unit)(TSFlags & PPCII::PPC970_Mask);
}
/// isLoadOfStoredAddress - If we have a load from the previously stored pointer
/// as indicated by StorePtr1/StorePtr2/StoreSize, return true.
bool PPCHazardRecognizer970::
isLoadOfStoredAddress(unsigned LoadSize, SDOperand Ptr1, SDOperand Ptr2) const {
for (unsigned i = 0, e = NumStores; i != e; ++i) {
// Handle exact and commuted addresses.
if (Ptr1 == StorePtr1[i] && Ptr2 == StorePtr2[i])
return true;
if (Ptr2 == StorePtr1[i] && Ptr1 == StorePtr2[i])
return true;
// Okay, we don't have an exact match, if this is an indexed offset, see if
// we have overlap (which happens during fp->int conversion for example).
if (StorePtr2[i] == Ptr2) {
if (ConstantSDNode *StoreOffset = dyn_cast<ConstantSDNode>(StorePtr1[i]))
if (ConstantSDNode *LoadOffset = dyn_cast<ConstantSDNode>(Ptr1)) {
// Okay the base pointers match, so we have [c1+r] vs [c2+r]. Check
// to see if the load and store actually overlap.
int StoreOffs = StoreOffset->getValue();
int LoadOffs = LoadOffset->getValue();
if (StoreOffs < LoadOffs) {
if (int(StoreOffs+StoreSize[i]) > LoadOffs) return true;
} else {
if (int(LoadOffs+LoadSize) > StoreOffs) return true;
}
}
}
}
return false;
}
/// getHazardType - We return hazard for any non-branch instruction that would
/// terminate terminate the dispatch group. We turn NoopHazard for any
/// instructions that wouldn't terminate the dispatch group that would cause a
/// pipeline flush.
HazardRecognizer::HazardType PPCHazardRecognizer970::
getHazardType(SDNode *Node) {
bool isFirst, isSingle, isCracked, isLoad, isStore;
PPCII::PPC970_Unit InstrType =
GetInstrType(Node->getOpcode(), isFirst, isSingle, isCracked,
isLoad, isStore);
if (InstrType == PPCII::PPC970_Pseudo) return NoHazard;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
// We can only issue a PPC970_First/PPC970_Single instruction (such as
// crand/mtspr/etc) if this is the first cycle of the dispatch group.
if (NumIssued != 0 && (isFirst || isSingle))
return Hazard;
// If this instruction is cracked into two ops by the decoder, we know that
// it is not a branch and that it cannot issue if 3 other instructions are
// already in the dispatch group.
if (isCracked && NumIssued > 2)
return Hazard;
switch (InstrType) {
default: assert(0 && "Unknown instruction type!");
case PPCII::PPC970_FXU:
case PPCII::PPC970_LSU:
case PPCII::PPC970_FPU:
case PPCII::PPC970_VALU:
case PPCII::PPC970_VPERM:
// We can only issue a branch as the last instruction in a group.
if (NumIssued == 4) return Hazard;
break;
case PPCII::PPC970_CRU:
// We can only issue a CR instruction in the first two slots.
if (NumIssued >= 2) return Hazard;
break;
case PPCII::PPC970_BRU:
break;
}
// Do not allow MTCTR and BCTRL to be in the same dispatch group.
if (HasCTRSet && (Opcode == PPC::BCTRL_Macho || Opcode == PPC::BCTRL_ELF))
return NoopHazard;
// If this is a load following a store, make sure it's not to the same or
// overlapping address.
if (isLoad && NumStores) {
unsigned LoadSize;
switch (Opcode) {
default: assert(0 && "Unknown load!");
case PPC::LBZ: case PPC::LBZU:
case PPC::LBZX:
case PPC::LBZ8: case PPC::LBZU8:
case PPC::LBZX8:
case PPC::LVEBX:
LoadSize = 1;
break;
case PPC::LHA: case PPC::LHAU:
case PPC::LHAX:
case PPC::LHZ: case PPC::LHZU:
case PPC::LHZX:
case PPC::LVEHX:
case PPC::LHBRX:
case PPC::LHA8: case PPC::LHAU8:
case PPC::LHAX8:
case PPC::LHZ8: case PPC::LHZU8:
case PPC::LHZX8:
LoadSize = 2;
break;
case PPC::LFS: case PPC::LFSU:
case PPC::LFSX:
case PPC::LWZ: case PPC::LWZU:
case PPC::LWZX:
case PPC::LWA:
case PPC::LWAX:
case PPC::LVEWX:
case PPC::LWBRX:
case PPC::LWZ8:
case PPC::LWZX8:
LoadSize = 4;
break;
case PPC::LFD: case PPC::LFDU:
case PPC::LFDX:
case PPC::LD: case PPC::LDU:
case PPC::LDX:
LoadSize = 8;
break;
case PPC::LVX:
LoadSize = 16;
break;
}
if (isLoadOfStoredAddress(LoadSize,
Node->getOperand(0), Node->getOperand(1)))
return NoopHazard;
}
return NoHazard;
}
void PPCHazardRecognizer970::EmitInstruction(SDNode *Node) {
bool isFirst, isSingle, isCracked, isLoad, isStore;
PPCII::PPC970_Unit InstrType =
GetInstrType(Node->getOpcode(), isFirst, isSingle, isCracked,
isLoad, isStore);
if (InstrType == PPCII::PPC970_Pseudo) return;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
// Update structural hazard information.
if (Opcode == PPC::MTCTR) HasCTRSet = true;
// Track the address stored to.
if (isStore) {
unsigned ThisStoreSize;
switch (Opcode) {
default: assert(0 && "Unknown store instruction!");
case PPC::STB: case PPC::STB8:
case PPC::STBU: case PPC::STBU8:
case PPC::STBX: case PPC::STBX8:
case PPC::STVEBX:
ThisStoreSize = 1;
break;
case PPC::STH: case PPC::STH8:
case PPC::STHU: case PPC::STHU8:
case PPC::STHX: case PPC::STHX8:
case PPC::STVEHX:
case PPC::STHBRX:
ThisStoreSize = 2;
break;
case PPC::STFS:
case PPC::STFSU:
case PPC::STFSX:
case PPC::STWX: case PPC::STWX8:
case PPC::STWUX:
case PPC::STW: case PPC::STW8:
case PPC::STWU: case PPC::STWU8:
case PPC::STVEWX:
case PPC::STFIWX:
case PPC::STWBRX:
ThisStoreSize = 4;
break;
case PPC::STD_32:
case PPC::STDX_32:
case PPC::STD:
case PPC::STDU:
case PPC::STFD:
case PPC::STFDX:
case PPC::STDX:
case PPC::STDUX:
ThisStoreSize = 8;
break;
case PPC::STVX:
ThisStoreSize = 16;
break;
}
StoreSize[NumStores] = ThisStoreSize;
StorePtr1[NumStores] = Node->getOperand(1);
StorePtr2[NumStores] = Node->getOperand(2);
++NumStores;
}
if (InstrType == PPCII::PPC970_BRU || isSingle)
NumIssued = 4; // Terminate a d-group.
++NumIssued;
// If this instruction is cracked into two ops by the decoder, remember that
// we issued two pieces.
if (isCracked)
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::AdvanceCycle() {
assert(NumIssued < 5 && "Illegal dispatch group!");
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::EmitNoop() {
AdvanceCycle();
}
<commit_msg>LVXL and STVXL are also a load and store resp.<commit_after>//===-- PPCHazardRecognizers.cpp - PowerPC Hazard Recognizer Impls --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements hazard recognizers for scheduling on PowerPC processors.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "pre-RA-sched"
#include "PPCHazardRecognizers.h"
#include "PPC.h"
#include "PPCInstrInfo.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// PowerPC 970 Hazard Recognizer
//
// This models the dispatch group formation of the PPC970 processor. Dispatch
// groups are bundles of up to five instructions that can contain various mixes
// of instructions. The PPC970 can dispatch a peak of 4 non-branch and one
// branch instruction per-cycle.
//
// There are a number of restrictions to dispatch group formation: some
// instructions can only be issued in the first slot of a dispatch group, & some
// instructions fill an entire dispatch group. Additionally, only branches can
// issue in the 5th (last) slot.
//
// Finally, there are a number of "structural" hazards on the PPC970. These
// conditions cause large performance penalties due to misprediction, recovery,
// and replay logic that has to happen. These cases include setting a CTR and
// branching through it in the same dispatch group, and storing to an address,
// then loading from the same address within a dispatch group. To avoid these
// conditions, we insert no-op instructions when appropriate.
//
// FIXME: This is missing some significant cases:
// 1. Modeling of microcoded instructions.
// 2. Handling of serialized operations.
// 3. Handling of the esoteric cases in "Resource-based Instruction Grouping".
//
PPCHazardRecognizer970::PPCHazardRecognizer970(const TargetInstrInfo &tii)
: TII(tii) {
EndDispatchGroup();
}
void PPCHazardRecognizer970::EndDispatchGroup() {
DOUT << "=== Start of dispatch group\n";
NumIssued = 0;
// Structural hazard info.
HasCTRSet = false;
NumStores = 0;
}
PPCII::PPC970_Unit
PPCHazardRecognizer970::GetInstrType(unsigned Opcode,
bool &isFirst, bool &isSingle,
bool &isCracked,
bool &isLoad, bool &isStore) {
if (Opcode < ISD::BUILTIN_OP_END) {
isFirst = isSingle = isCracked = isLoad = isStore = false;
return PPCII::PPC970_Pseudo;
}
Opcode -= ISD::BUILTIN_OP_END;
const TargetInstrDescriptor &TID = TII.get(Opcode);
isLoad = TID.Flags & M_LOAD_FLAG;
isStore = TID.Flags & M_STORE_FLAG;
unsigned TSFlags = TID.TSFlags;
isFirst = TSFlags & PPCII::PPC970_First;
isSingle = TSFlags & PPCII::PPC970_Single;
isCracked = TSFlags & PPCII::PPC970_Cracked;
return (PPCII::PPC970_Unit)(TSFlags & PPCII::PPC970_Mask);
}
/// isLoadOfStoredAddress - If we have a load from the previously stored pointer
/// as indicated by StorePtr1/StorePtr2/StoreSize, return true.
bool PPCHazardRecognizer970::
isLoadOfStoredAddress(unsigned LoadSize, SDOperand Ptr1, SDOperand Ptr2) const {
for (unsigned i = 0, e = NumStores; i != e; ++i) {
// Handle exact and commuted addresses.
if (Ptr1 == StorePtr1[i] && Ptr2 == StorePtr2[i])
return true;
if (Ptr2 == StorePtr1[i] && Ptr1 == StorePtr2[i])
return true;
// Okay, we don't have an exact match, if this is an indexed offset, see if
// we have overlap (which happens during fp->int conversion for example).
if (StorePtr2[i] == Ptr2) {
if (ConstantSDNode *StoreOffset = dyn_cast<ConstantSDNode>(StorePtr1[i]))
if (ConstantSDNode *LoadOffset = dyn_cast<ConstantSDNode>(Ptr1)) {
// Okay the base pointers match, so we have [c1+r] vs [c2+r]. Check
// to see if the load and store actually overlap.
int StoreOffs = StoreOffset->getValue();
int LoadOffs = LoadOffset->getValue();
if (StoreOffs < LoadOffs) {
if (int(StoreOffs+StoreSize[i]) > LoadOffs) return true;
} else {
if (int(LoadOffs+LoadSize) > StoreOffs) return true;
}
}
}
}
return false;
}
/// getHazardType - We return hazard for any non-branch instruction that would
/// terminate terminate the dispatch group. We turn NoopHazard for any
/// instructions that wouldn't terminate the dispatch group that would cause a
/// pipeline flush.
HazardRecognizer::HazardType PPCHazardRecognizer970::
getHazardType(SDNode *Node) {
bool isFirst, isSingle, isCracked, isLoad, isStore;
PPCII::PPC970_Unit InstrType =
GetInstrType(Node->getOpcode(), isFirst, isSingle, isCracked,
isLoad, isStore);
if (InstrType == PPCII::PPC970_Pseudo) return NoHazard;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
// We can only issue a PPC970_First/PPC970_Single instruction (such as
// crand/mtspr/etc) if this is the first cycle of the dispatch group.
if (NumIssued != 0 && (isFirst || isSingle))
return Hazard;
// If this instruction is cracked into two ops by the decoder, we know that
// it is not a branch and that it cannot issue if 3 other instructions are
// already in the dispatch group.
if (isCracked && NumIssued > 2)
return Hazard;
switch (InstrType) {
default: assert(0 && "Unknown instruction type!");
case PPCII::PPC970_FXU:
case PPCII::PPC970_LSU:
case PPCII::PPC970_FPU:
case PPCII::PPC970_VALU:
case PPCII::PPC970_VPERM:
// We can only issue a branch as the last instruction in a group.
if (NumIssued == 4) return Hazard;
break;
case PPCII::PPC970_CRU:
// We can only issue a CR instruction in the first two slots.
if (NumIssued >= 2) return Hazard;
break;
case PPCII::PPC970_BRU:
break;
}
// Do not allow MTCTR and BCTRL to be in the same dispatch group.
if (HasCTRSet && (Opcode == PPC::BCTRL_Macho || Opcode == PPC::BCTRL_ELF))
return NoopHazard;
// If this is a load following a store, make sure it's not to the same or
// overlapping address.
if (isLoad && NumStores) {
unsigned LoadSize;
switch (Opcode) {
default: assert(0 && "Unknown load!");
case PPC::LBZ: case PPC::LBZU:
case PPC::LBZX:
case PPC::LBZ8: case PPC::LBZU8:
case PPC::LBZX8:
case PPC::LVEBX:
LoadSize = 1;
break;
case PPC::LHA: case PPC::LHAU:
case PPC::LHAX:
case PPC::LHZ: case PPC::LHZU:
case PPC::LHZX:
case PPC::LVEHX:
case PPC::LHBRX:
case PPC::LHA8: case PPC::LHAU8:
case PPC::LHAX8:
case PPC::LHZ8: case PPC::LHZU8:
case PPC::LHZX8:
LoadSize = 2;
break;
case PPC::LFS: case PPC::LFSU:
case PPC::LFSX:
case PPC::LWZ: case PPC::LWZU:
case PPC::LWZX:
case PPC::LWA:
case PPC::LWAX:
case PPC::LVEWX:
case PPC::LWBRX:
case PPC::LWZ8:
case PPC::LWZX8:
LoadSize = 4;
break;
case PPC::LFD: case PPC::LFDU:
case PPC::LFDX:
case PPC::LD: case PPC::LDU:
case PPC::LDX:
LoadSize = 8;
break;
case PPC::LVX:
case PPC::LVXL:
LoadSize = 16;
break;
}
if (isLoadOfStoredAddress(LoadSize,
Node->getOperand(0), Node->getOperand(1)))
return NoopHazard;
}
return NoHazard;
}
void PPCHazardRecognizer970::EmitInstruction(SDNode *Node) {
bool isFirst, isSingle, isCracked, isLoad, isStore;
PPCII::PPC970_Unit InstrType =
GetInstrType(Node->getOpcode(), isFirst, isSingle, isCracked,
isLoad, isStore);
if (InstrType == PPCII::PPC970_Pseudo) return;
unsigned Opcode = Node->getOpcode()-ISD::BUILTIN_OP_END;
// Update structural hazard information.
if (Opcode == PPC::MTCTR) HasCTRSet = true;
// Track the address stored to.
if (isStore) {
unsigned ThisStoreSize;
switch (Opcode) {
default: assert(0 && "Unknown store instruction!");
case PPC::STB: case PPC::STB8:
case PPC::STBU: case PPC::STBU8:
case PPC::STBX: case PPC::STBX8:
case PPC::STVEBX:
ThisStoreSize = 1;
break;
case PPC::STH: case PPC::STH8:
case PPC::STHU: case PPC::STHU8:
case PPC::STHX: case PPC::STHX8:
case PPC::STVEHX:
case PPC::STHBRX:
ThisStoreSize = 2;
break;
case PPC::STFS:
case PPC::STFSU:
case PPC::STFSX:
case PPC::STWX: case PPC::STWX8:
case PPC::STWUX:
case PPC::STW: case PPC::STW8:
case PPC::STWU: case PPC::STWU8:
case PPC::STVEWX:
case PPC::STFIWX:
case PPC::STWBRX:
ThisStoreSize = 4;
break;
case PPC::STD_32:
case PPC::STDX_32:
case PPC::STD:
case PPC::STDU:
case PPC::STFD:
case PPC::STFDX:
case PPC::STDX:
case PPC::STDUX:
ThisStoreSize = 8;
break;
case PPC::STVX:
case PPC::STVXL:
ThisStoreSize = 16;
break;
}
StoreSize[NumStores] = ThisStoreSize;
StorePtr1[NumStores] = Node->getOperand(1);
StorePtr2[NumStores] = Node->getOperand(2);
++NumStores;
}
if (InstrType == PPCII::PPC970_BRU || isSingle)
NumIssued = 4; // Terminate a d-group.
++NumIssued;
// If this instruction is cracked into two ops by the decoder, remember that
// we issued two pieces.
if (isCracked)
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::AdvanceCycle() {
assert(NumIssued < 5 && "Illegal dispatch group!");
++NumIssued;
if (NumIssued == 5)
EndDispatchGroup();
}
void PPCHazardRecognizer970::EmitNoop() {
AdvanceCycle();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ConfigurationAccess.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-17 13:06:36 $
*
* 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_chart2.hxx"
#include "ConfigurationAccess.hxx"
#include "macros.hxx"
// header for class SvtSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
// header for class ConfigItem
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
namespace
{
bool lcl_IsMetric()
{
SvtSysLocale aSysLocale;
const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();
MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();
return ( eSys == MEASURE_METRIC );
}
}//end anonymous namespace
class CalcConfigItem : public ::utl::ConfigItem
{
public:
CalcConfigItem();
virtual ~CalcConfigItem();
FieldUnit getFieldUnit();
};
CalcConfigItem::CalcConfigItem()
: ConfigItem( ::rtl::OUString( C2U( "Office.Calc/Layout" )))
{
}
CalcConfigItem::~CalcConfigItem()
{
}
FieldUnit CalcConfigItem::getFieldUnit()
{
FieldUnit eResult( FUNIT_CM );
uno::Sequence< ::rtl::OUString > aNames( 1 );
if( lcl_IsMetric() )
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/Metric" ));
else
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/NonMetric" ));
uno::Sequence< uno::Any > aResult( GetProperties( aNames ));
sal_Int32 nValue;
if( aResult[ 0 ] >>= nValue )
eResult = static_cast< FieldUnit >( nValue );
return eResult;
}
ConfigurationAccess::ConfigurationAccess()
: m_pCalcConfigItem(0)
{
m_pCalcConfigItem = new CalcConfigItem();
}
ConfigurationAccess::~ConfigurationAccess()
{
delete m_pCalcConfigItem;
}
FieldUnit ConfigurationAccess::getFieldUnit()
{
FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );
return aUnit;
}
//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.12); FILE MERGED 2006/10/18 17:08:22 bm 1.2.12.3: RESYNC: (1.2-1.3); FILE MERGED 2005/11/30 15:57:10 iha 1.2.12.2: missing ! leads to crash in getConfigurationAccess() 2005/11/29 18:03:38 bm 1.2.12.1: ConfigurationAccess is a singleton now (ViewSingletons no longer needed)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ConfigurationAccess.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-05-22 18:06:47 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "ConfigurationAccess.hxx"
#include "macros.hxx"
// header for class SvtSysLocale
#ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX
#include <svtools/syslocale.hxx>
#endif
// header for class ConfigItem
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
namespace
{
bool lcl_IsMetric()
{
SvtSysLocale aSysLocale;
const LocaleDataWrapper* pLocWrapper = aSysLocale.GetLocaleDataPtr();
MeasurementSystem eSys = pLocWrapper->getMeasurementSystemEnum();
return ( eSys == MEASURE_METRIC );
}
}//end anonymous namespace
// ----------------------------------------
class CalcConfigItem : public ::utl::ConfigItem
{
public:
CalcConfigItem();
virtual ~CalcConfigItem();
FieldUnit getFieldUnit();
};
CalcConfigItem::CalcConfigItem()
: ConfigItem( ::rtl::OUString( C2U( "Office.Calc/Layout" )))
{
}
CalcConfigItem::~CalcConfigItem()
{
}
FieldUnit CalcConfigItem::getFieldUnit()
{
FieldUnit eResult( FUNIT_CM );
uno::Sequence< ::rtl::OUString > aNames( 1 );
if( lcl_IsMetric() )
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/Metric" ));
else
aNames[ 0 ] = ::rtl::OUString( C2U( "Other/MeasureUnit/NonMetric" ));
uno::Sequence< uno::Any > aResult( GetProperties( aNames ));
sal_Int32 nValue;
if( aResult[ 0 ] >>= nValue )
eResult = static_cast< FieldUnit >( nValue );
return eResult;
}
// ----------------------------------------
ConfigurationAccess * ConfigurationAccess::m_pThis = 0;
// private, use static getConfigurationAccess method
ConfigurationAccess::ConfigurationAccess()
: m_pCalcConfigItem(0)
{
m_pCalcConfigItem = new CalcConfigItem();
}
// static
ConfigurationAccess * ConfigurationAccess::getConfigurationAccess()
{
// note: not threadsafe
if( !m_pThis )
m_pThis = new ConfigurationAccess();
return m_pThis;
}
ConfigurationAccess::~ConfigurationAccess()
{
delete m_pCalcConfigItem;
}
FieldUnit ConfigurationAccess::getFieldUnit()
{
OSL_ASSERT( m_pCalcConfigItem );
FieldUnit aUnit( m_pCalcConfigItem->getFieldUnit() );
return aUnit;
}
//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>
|
<commit_before>//===-- SparcV9TargetMachine.cpp - SparcV9 Target Machine Implementation --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Primary interface to machine description for the UltraSPARC. Primarily just
// initializes machine-dependent parameters in class TargetMachine, and creates
// machine-dependent subclasses for classes such as TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "MappingInfo.h"
#include "MachineFunctionInfo.h"
#include "MachineCodeForInstruction.h"
#include "SparcV9Internals.h"
#include "SparcV9TargetMachine.h"
#include "SparcV9BurgISel.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcV9Instr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
namespace llvm {
bool EmitMappingInfo = false;
}
namespace {
cl::opt<bool> DisableSched("disable-sched",
cl::desc("Disable local scheduling pass"));
cl::opt<bool> DisablePeephole("disable-peephole",
cl::desc("Disable peephole optimization pass"));
cl::opt<bool, true> EmitMappingInfoOpt("enable-maps",
cl::location(EmitMappingInfo),
cl::init(false),
cl::desc("Emit LLVM-to-MachineCode mapping info to assembly"));
cl::opt<bool> EnableModSched("enable-modsched",
cl::desc("Enable modulo scheduling pass instead of local scheduling"), cl::Hidden);
// Register the target.
RegisterTarget<SparcV9TargetMachine> X("sparcv9", " SPARC V9");
}
unsigned SparcV9TargetMachine::getJITMatchQuality() {
#if defined(__sparcv9)
return 10;
#else
return 0;
#endif
}
unsigned SparcV9TargetMachine::getModuleMatchQuality(const Module &M) {
// We strongly match "sparcv9-*".
std::string TT = M.getTargetTriple();
if (TT.size() >= 8 && std::string(TT.begin(), TT.begin()+8) == "sparcv9-")
return 20;
if (M.getEndianness() == Module::BigEndian &&
M.getPointerSize() == Module::Pointer64)
return 10; // Weak match
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return getJITMatchQuality()/2;
}
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).getInfo<SparcV9FunctionInfo>()->CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "DestroyMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
MachineFunction::destruct(&F);
return false;
}
};
FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
}
FunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
SparcV9TargetMachine::SparcV9TargetMachine(const Module &M,
IntrinsicLowering *il)
: TargetMachine("UltraSparcV9-Native", il, false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
jitInfo(*this) {
}
/// addPassesToEmitAssembly - This method controls the entire code generation
/// process for the ultra sparc.
///
bool
SparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(*this));
PM.add(createLowerSelectPass());
// Clean up after pre-selection.
PM.add(createReassociatePass());
// If the user's trying to read the generated code, they'll need to see the
// transformed input.
if (PrintMachineCode)
PM.add(new PrintModulePass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
// Insert empty stackslots in the stack frame of each function
// so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
PM.add(createSparcV9BurgInstSelector(*this));
if(PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before modulo scheduling:\n"));
//Use ModuloScheduling if enabled, otherwise use local scheduling if not disabled.
if(EnableModSched)
PM.add(createModuloSchedulingPass(*this));
else {
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
}
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Final code:\n"));
if (EmitMappingInfo) {
PM.add(createInternalGlobalMapperPass());
PM.add(getMappingInfoAsmPrinterPass(Out));
}
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
PM.add(createAsmPrinterPass(Out, *this));
// Free machine-code IR which is no longer needed:
PM.add(createSparcV9MachineCodeDestructionPass());
// Emit bytecode to the assembly file into its special section next
if (EmitMappingInfo)
PM.add(createBytecodeAsmPrinterPass(Out));
return false;
}
/// addPassesToJITCompile - This method controls the JIT method of code
/// generation for the UltraSparcV9.
///
void SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(TM));
PM.add(createLowerSelectPass());
// Clean up after pre-selection.
PM.add(createReassociatePass());
// If the user's trying to read the generated code, they'll need to see the
// transformed input.
if (PrintMachineCode)
PM.add(new PrintFunctionPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(TM));
PM.add(createSparcV9BurgInstSelector(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Final code:\n"));
}
<commit_msg>Chris is a pain ;) Removing reassociate.<commit_after>//===-- SparcV9TargetMachine.cpp - SparcV9 Target Machine Implementation --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Primary interface to machine description for the UltraSPARC. Primarily just
// initializes machine-dependent parameters in class TargetMachine, and creates
// machine-dependent subclasses for classes such as TargetInstrInfo.
//
//===----------------------------------------------------------------------===//
#include "llvm/Function.h"
#include "llvm/PassManager.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/CodeGen/InstrScheduling.h"
#include "llvm/CodeGen/IntrinsicLowering.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "MappingInfo.h"
#include "MachineFunctionInfo.h"
#include "MachineCodeForInstruction.h"
#include "SparcV9Internals.h"
#include "SparcV9TargetMachine.h"
#include "SparcV9BurgISel.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
static const unsigned ImplicitRegUseList[] = { 0 }; /* not used yet */
// Build the MachineInstruction Description Array...
const TargetInstrDescriptor llvm::SparcV9MachineInstrDesc[] = {
#define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS) \
{ OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS, 0, \
ImplicitRegUseList, ImplicitRegUseList },
#include "SparcV9Instr.def"
};
//---------------------------------------------------------------------------
// Command line options to control choice of code generation passes.
//---------------------------------------------------------------------------
namespace llvm {
bool EmitMappingInfo = false;
}
namespace {
cl::opt<bool> DisableSched("disable-sched",
cl::desc("Disable local scheduling pass"));
cl::opt<bool> DisablePeephole("disable-peephole",
cl::desc("Disable peephole optimization pass"));
cl::opt<bool, true> EmitMappingInfoOpt("enable-maps",
cl::location(EmitMappingInfo),
cl::init(false),
cl::desc("Emit LLVM-to-MachineCode mapping info to assembly"));
cl::opt<bool> EnableModSched("enable-modsched",
cl::desc("Enable modulo scheduling pass instead of local scheduling"), cl::Hidden);
// Register the target.
RegisterTarget<SparcV9TargetMachine> X("sparcv9", " SPARC V9");
}
unsigned SparcV9TargetMachine::getJITMatchQuality() {
#if defined(__sparcv9)
return 10;
#else
return 0;
#endif
}
unsigned SparcV9TargetMachine::getModuleMatchQuality(const Module &M) {
// We strongly match "sparcv9-*".
std::string TT = M.getTargetTriple();
if (TT.size() >= 8 && std::string(TT.begin(), TT.begin()+8) == "sparcv9-")
return 20;
if (M.getEndianness() == Module::BigEndian &&
M.getPointerSize() == Module::Pointer64)
return 10; // Weak match
else if (M.getEndianness() != Module::AnyEndianness ||
M.getPointerSize() != Module::AnyPointerSize)
return 0; // Match for some other target
return getJITMatchQuality()/2;
}
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).getInfo<SparcV9FunctionInfo>()->CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "DestroyMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
MachineFunction::destruct(&F);
return false;
}
};
FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
}
FunctionPass *llvm::createSparcV9MachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
SparcV9TargetMachine::SparcV9TargetMachine(const Module &M,
IntrinsicLowering *il)
: TargetMachine("UltraSparcV9-Native", il, false),
schedInfo(*this),
regInfo(*this),
frameInfo(*this),
jitInfo(*this) {
}
/// addPassesToEmitAssembly - This method controls the entire code generation
/// process for the ultra sparc.
///
bool
SparcV9TargetMachine::addPassesToEmitAssembly(PassManager &PM, std::ostream &Out)
{
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(*this));
PM.add(createLowerSelectPass());
// If the user's trying to read the generated code, they'll need to see the
// transformed input.
if (PrintMachineCode)
PM.add(new PrintModulePass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(*this));
// Insert empty stackslots in the stack frame of each function
// so %fp+offset-8 and %fp+offset-16 are empty slots now!
PM.add(createStackSlotsPass(*this));
PM.add(createSparcV9BurgInstSelector(*this));
if(PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before modulo scheduling:\n"));
//Use ModuloScheduling if enabled, otherwise use local scheduling if not disabled.
if(EnableModSched)
PM.add(createModuloSchedulingPass(*this));
else {
if (!DisableSched)
PM.add(createInstructionSchedulingWithSSAPass(*this));
}
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(*this));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Final code:\n"));
if (EmitMappingInfo) {
PM.add(createInternalGlobalMapperPass());
PM.add(getMappingInfoAsmPrinterPass(Out));
}
// Output assembly language to the .s file. Assembly emission is split into
// two parts: Function output and Global value output. This is because
// function output is pipelined with all of the rest of code generation stuff,
// allowing machine code representations for functions to be free'd after the
// function has been emitted.
PM.add(createAsmPrinterPass(Out, *this));
// Free machine-code IR which is no longer needed:
PM.add(createSparcV9MachineCodeDestructionPass());
// Emit bytecode to the assembly file into its special section next
if (EmitMappingInfo)
PM.add(createBytecodeAsmPrinterPass(Out));
return false;
}
/// addPassesToJITCompile - This method controls the JIT method of code
/// generation for the UltraSparcV9.
///
void SparcV9JITInfo::addPassesToJITCompile(FunctionPassManager &PM) {
// FIXME: Implement efficient support for garbage collection intrinsics.
PM.add(createLowerGCPass());
// Replace malloc and free instructions with library calls.
PM.add(createLowerAllocationsPass());
// FIXME: implement the switch instruction in the instruction selector.
PM.add(createLowerSwitchPass());
// FIXME: implement the invoke/unwind instructions!
PM.add(createLowerInvokePass());
// decompose multi-dimensional array references into single-dim refs
PM.add(createDecomposeMultiDimRefsPass());
// Lower LLVM code to the form expected by the SPARCv9 instruction selector.
PM.add(createPreSelectionPass(TM));
PM.add(createLowerSelectPass());
// If the user's trying to read the generated code, they'll need to see the
// transformed input.
if (PrintMachineCode)
PM.add(new PrintFunctionPass());
// Construct and initialize the MachineFunction object for this fn.
PM.add(createMachineCodeConstructionPass(TM));
PM.add(createSparcV9BurgInstSelector(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Before reg alloc:\n"));
PM.add(getRegisterAllocator(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "After reg alloc:\n"));
PM.add(createPrologEpilogInsertionPass());
if (!DisablePeephole)
PM.add(createPeepholeOptsPass(TM));
if (PrintMachineCode)
PM.add(createMachineFunctionPrinterPass(&std::cerr, "Final code:\n"));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "chrome/browser/search_engines/template_url_fetcher.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/search_engines/template_url_parser.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/net/url_fetcher.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
// RequestDelegate ------------------------------------------------------------
class TemplateURLFetcher::RequestDelegate : public URLFetcher::Delegate,
public NotificationObserver {
public:
RequestDelegate(TemplateURLFetcher* fetcher,
const std::wstring& keyword,
const GURL& osdd_url,
const GURL& favicon_url,
TabContents* source,
bool autodetected)
: ALLOW_THIS_IN_INITIALIZER_LIST(url_fetcher_(osdd_url,
URLFetcher::GET, this)),
fetcher_(fetcher),
keyword_(keyword),
osdd_url_(osdd_url),
favicon_url_(favicon_url),
autodetected_(autodetected),
source_(source) {
url_fetcher_.set_request_context(fetcher->profile()->GetRequestContext());
url_fetcher_.Start();
registrar_.Add(this,
NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(source_));
}
// URLFetcher::Delegate:
// If data contains a valid OSDD, a TemplateURL is created and added to
// the TemplateURLModel.
virtual void OnURLFetchComplete(const URLFetcher* source,
const GURL& url,
const URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data);
// NotificationObserver:
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);
DCHECK(source == Source<TabContents>(source_));
source_ = NULL;
}
// URL of the OSDD.
const GURL& url() const { return osdd_url_; }
// Keyword to use.
const std::wstring keyword() const { return keyword_; }
private:
URLFetcher url_fetcher_;
TemplateURLFetcher* fetcher_;
std::wstring keyword_;
const GURL osdd_url_;
const GURL favicon_url_;
bool autodetected_;
// The TabContents where this request originated. Can be NULL if the
// originating tab is closed. If NULL, the engine is not added.
TabContents* source_;
// Handles registering for our notifications.
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(RequestDelegate);
};
void TemplateURLFetcher::RequestDelegate::OnURLFetchComplete(
const URLFetcher* source,
const GURL& url,
const URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
// Make sure we can still replace the keyword.
if (response_code != 200) {
fetcher_->RequestCompleted(this);
// WARNING: RequestCompleted deletes us.
return;
}
scoped_ptr<TemplateURL> template_url(new TemplateURL());
if (TemplateURLParser::Parse(
reinterpret_cast<const unsigned char*>(data.c_str()),
data.length(),
NULL,
template_url.get()) &&
template_url->url() && template_url->url()->SupportsReplacement()) {
if (!autodetected_ || keyword_.empty()) {
// Generate new keyword from URL in OSDD for none autodetected case.
// Previous keyword was generated from URL where OSDD was placed and
// it gives wrong result when OSDD is located on third party site that
// has nothing in common with search engine in OSDD.
GURL keyword_url(WideToUTF16Hack(template_url->url()->url()));
std::wstring new_keyword = TemplateURLModel::GenerateKeyword(
keyword_url, false);
if (!new_keyword.empty())
keyword_ = new_keyword;
}
TemplateURLModel* model = fetcher_->profile()->GetTemplateURLModel();
const TemplateURL* existing_url;
if (keyword_.empty() ||
!model || !model->loaded() ||
!model->CanReplaceKeyword(keyword_, template_url->url()->url(),
&existing_url)) {
// TODO(pamg): If we're coming from JS (not autodetected) and this URL
// already exists in the model, consider bringing up the
// EditKeywordController to edit it. This would be helpful feedback in
// the case of clicking a button twice, and annoying in the case of a
// page that calls AddSearchProvider() in JS without a user action.
fetcher_->RequestCompleted(this);
// WARNING: RequestCompleted deletes us.
return;
}
if (existing_url)
model->Remove(existing_url);
// The short name is what is shown to the user. We preserve original names
// since it is better when generated keyword in many cases.
template_url->set_keyword(keyword_);
template_url->set_originating_url(osdd_url_);
// The page may have specified a URL to use for favicons, if not, set it.
if (!template_url->GetFavIconURL().is_valid())
template_url->SetFavIconURL(favicon_url_);
if (autodetected_) {
// Mark the keyword as replaceable so it can be removed if necessary.
template_url->set_safe_for_autoreplace(true);
model->Add(template_url.release());
} else if (source_ && source_->delegate()) {
// Confirm addition and allow user to edit default choices. It's ironic
// that only *non*-autodetected additions get confirmed, but the user
// expects feedback that his action did something.
// The source TabContents' delegate takes care of adding the URL to the
// model, which takes ownership, or of deleting it if the add is
// cancelled.
source_->delegate()->ConfirmAddSearchProvider(template_url.release(),
fetcher_->profile());
}
}
fetcher_->RequestCompleted(this);
// WARNING: RequestCompleted deletes us.
}
// TemplateURLFetcher ---------------------------------------------------------
TemplateURLFetcher::TemplateURLFetcher(Profile* profile) : profile_(profile) {
DCHECK(profile_);
}
TemplateURLFetcher::~TemplateURLFetcher() {
}
void TemplateURLFetcher::ScheduleDownload(const std::wstring& keyword,
const GURL& osdd_url,
const GURL& favicon_url,
TabContents* source,
bool autodetected) {
DCHECK(!keyword.empty() && osdd_url.is_valid());
// Make sure we aren't already downloading this request.
for (std::vector<RequestDelegate*>::iterator i = requests_->begin();
i != requests_->end(); ++i) {
if ((*i)->url() == osdd_url || (*i)->keyword() == keyword)
return;
}
requests_->push_back(
new RequestDelegate(this, keyword, osdd_url, favicon_url, source,
autodetected));
}
void TemplateURLFetcher::RequestCompleted(RequestDelegate* request) {
DCHECK(find(requests_->begin(), requests_->end(), request) !=
requests_->end());
requests_->erase(find(requests_->begin(), requests_->end(), request));
delete request;
}
<commit_msg>Always ask the user when adding a search engine from JS.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "chrome/browser/search_engines/template_url_fetcher.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/browser/search_engines/template_url_parser.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/tab_contents_delegate.h"
#include "chrome/common/net/url_fetcher.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
// RequestDelegate ------------------------------------------------------------
class TemplateURLFetcher::RequestDelegate : public URLFetcher::Delegate,
public NotificationObserver {
public:
RequestDelegate(TemplateURLFetcher* fetcher,
const std::wstring& keyword,
const GURL& osdd_url,
const GURL& favicon_url,
TabContents* source,
bool autodetected)
: ALLOW_THIS_IN_INITIALIZER_LIST(url_fetcher_(osdd_url,
URLFetcher::GET, this)),
fetcher_(fetcher),
keyword_(keyword),
osdd_url_(osdd_url),
favicon_url_(favicon_url),
autodetected_(autodetected),
source_(source) {
url_fetcher_.set_request_context(fetcher->profile()->GetRequestContext());
url_fetcher_.Start();
registrar_.Add(this,
NotificationType::TAB_CONTENTS_DESTROYED,
Source<TabContents>(source_));
}
// URLFetcher::Delegate:
// If data contains a valid OSDD, a TemplateURL is created and added to
// the TemplateURLModel.
virtual void OnURLFetchComplete(const URLFetcher* source,
const GURL& url,
const URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data);
// NotificationObserver:
virtual void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED);
DCHECK(source == Source<TabContents>(source_));
source_ = NULL;
}
// URL of the OSDD.
const GURL& url() const { return osdd_url_; }
// Keyword to use.
const std::wstring keyword() const { return keyword_; }
private:
URLFetcher url_fetcher_;
TemplateURLFetcher* fetcher_;
std::wstring keyword_;
const GURL osdd_url_;
const GURL favicon_url_;
bool autodetected_;
// The TabContents where this request originated. Can be NULL if the
// originating tab is closed. If NULL, the engine is not added.
TabContents* source_;
// Handles registering for our notifications.
NotificationRegistrar registrar_;
DISALLOW_COPY_AND_ASSIGN(RequestDelegate);
};
void TemplateURLFetcher::RequestDelegate::OnURLFetchComplete(
const URLFetcher* source,
const GURL& url,
const URLRequestStatus& status,
int response_code,
const ResponseCookies& cookies,
const std::string& data) {
// Make sure we can still replace the keyword.
if (response_code != 200) {
fetcher_->RequestCompleted(this);
// WARNING: RequestCompleted deletes us.
return;
}
scoped_ptr<TemplateURL> template_url(new TemplateURL());
if (TemplateURLParser::Parse(
reinterpret_cast<const unsigned char*>(data.c_str()),
data.length(),
NULL,
template_url.get()) &&
template_url->url() && template_url->url()->SupportsReplacement()) {
if (!autodetected_ || keyword_.empty()) {
// Generate new keyword from URL in OSDD for none autodetected case.
// Previous keyword was generated from URL where OSDD was placed and
// it gives wrong result when OSDD is located on third party site that
// has nothing in common with search engine in OSDD.
GURL keyword_url(WideToUTF16Hack(template_url->url()->url()));
std::wstring new_keyword = TemplateURLModel::GenerateKeyword(
keyword_url, false);
if (!new_keyword.empty())
keyword_ = new_keyword;
}
TemplateURLModel* model = fetcher_->profile()->GetTemplateURLModel();
const TemplateURL* existing_url;
if (keyword_.empty() ||
!model || !model->loaded() ||
!model->CanReplaceKeyword(keyword_, template_url->url()->url(),
&existing_url)) {
if (autodetected_ || !model || !model->loaded()) {
fetcher_->RequestCompleted(this);
// WARNING: RequestCompleted deletes us.
return;
}
// If we're coming from JS (neither autodetected nor failure to load the
// template URL model) and this URL already exists in the model, we bring
// up the EditKeywordController to edit it. This is helpful feedback in
// the case of clicking a button twice, and annoying in the case of a
// page that calls AddSearchProvider() in JS without a user action.
keyword_.clear();
existing_url = NULL;
}
if (existing_url)
model->Remove(existing_url);
// The short name is what is shown to the user. We preserve original names
// since it is better when generated keyword in many cases.
template_url->set_keyword(keyword_);
template_url->set_originating_url(osdd_url_);
// The page may have specified a URL to use for favicons, if not, set it.
if (!template_url->GetFavIconURL().is_valid())
template_url->SetFavIconURL(favicon_url_);
if (autodetected_) {
// Mark the keyword as replaceable so it can be removed if necessary.
template_url->set_safe_for_autoreplace(true);
model->Add(template_url.release());
} else if (source_ && source_->delegate()) {
// Confirm addition and allow user to edit default choices. It's ironic
// that only *non*-autodetected additions get confirmed, but the user
// expects feedback that his action did something.
// The source TabContents' delegate takes care of adding the URL to the
// model, which takes ownership, or of deleting it if the add is
// cancelled.
source_->delegate()->ConfirmAddSearchProvider(template_url.release(),
fetcher_->profile());
}
}
fetcher_->RequestCompleted(this);
// WARNING: RequestCompleted deletes us.
}
// TemplateURLFetcher ---------------------------------------------------------
TemplateURLFetcher::TemplateURLFetcher(Profile* profile) : profile_(profile) {
DCHECK(profile_);
}
TemplateURLFetcher::~TemplateURLFetcher() {
}
void TemplateURLFetcher::ScheduleDownload(const std::wstring& keyword,
const GURL& osdd_url,
const GURL& favicon_url,
TabContents* source,
bool autodetected) {
DCHECK(!keyword.empty() && osdd_url.is_valid());
// Make sure we aren't already downloading this request.
for (std::vector<RequestDelegate*>::iterator i = requests_->begin();
i != requests_->end(); ++i) {
if ((*i)->url() == osdd_url || (*i)->keyword() == keyword)
return;
}
requests_->push_back(
new RequestDelegate(this, keyword, osdd_url, favicon_url, source,
autodetected));
}
void TemplateURLFetcher::RequestCompleted(RequestDelegate* request) {
DCHECK(find(requests_->begin(), requests_->end(), request) !=
requests_->end());
requests_->erase(find(requests_->begin(), requests_->end(), request));
delete request;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/password_change_processor.h"
#include <string>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_store.h"
#include "chrome/browser/password_manager/password_store_change.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/glue/password_model_associator.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/protocol/password_specifics.pb.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "content/common/notification_type.h"
#include "webkit/glue/password_form.h"
namespace browser_sync {
PasswordChangeProcessor::PasswordChangeProcessor(
PasswordModelAssociator* model_associator,
PasswordStore* password_store,
UnrecoverableErrorHandler* error_handler)
: ChangeProcessor(error_handler),
model_associator_(model_associator),
password_store_(password_store),
observing_(false),
expected_loop_(MessageLoop::current()) {
DCHECK(model_associator);
DCHECK(error_handler);
#if defined(OS_MACOSX)
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
#else
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
#endif
StartObserving();
}
PasswordChangeProcessor::~PasswordChangeProcessor() {
DCHECK(expected_loop_ == MessageLoop::current());
}
void PasswordChangeProcessor::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(expected_loop_ == MessageLoop::current());
DCHECK(NotificationType::LOGINS_CHANGED == type);
if (!observing_)
return;
DCHECK(running());
sync_api::WriteTransaction trans(share_handle());
sync_api::ReadNode password_root(&trans);
if (!password_root.InitByTagLookup(kPasswordTag)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Server did not create the top-level password node. "
"We might be running against an out-of-date server.");
return;
}
PasswordStoreChangeList* changes =
Details<PasswordStoreChangeList>(details).ptr();
for (PasswordStoreChangeList::iterator change = changes->begin();
change != changes->end(); ++change) {
std::string tag = PasswordModelAssociator::MakeTag(change->form());
switch (change->type()) {
case PasswordStoreChange::ADD: {
sync_api::WriteNode sync_node(&trans);
if (!sync_node.InitUniqueByCreation(syncable::PASSWORDS,
password_root, tag)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Failed to create password sync node.");
return;
}
PasswordModelAssociator::WriteToSyncNode(change->form(), &sync_node);
model_associator_->Associate(&tag, sync_node.GetId());
break;
}
case PasswordStoreChange::UPDATE: {
sync_api::WriteNode sync_node(&trans);
int64 sync_id = model_associator_->GetSyncIdFromChromeId(tag);
if (sync_api::kInvalidId == sync_id) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Unexpected notification for: ");
return;
} else {
if (!sync_node.InitByIdLookup(sync_id)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password node lookup failed.");
return;
}
}
PasswordModelAssociator::WriteToSyncNode(change->form(), &sync_node);
break;
}
case PasswordStoreChange::REMOVE: {
sync_api::WriteNode sync_node(&trans);
int64 sync_id = model_associator_->GetSyncIdFromChromeId(tag);
if (sync_api::kInvalidId == sync_id) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Unexpected notification");
return;
} else {
if (!sync_node.InitByIdLookup(sync_id)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password node lookup failed.");
return;
}
model_associator_->Disassociate(sync_node.GetId());
sync_node.Remove();
}
break;
}
}
}
}
void PasswordChangeProcessor::ApplyChangesFromSyncModel(
const sync_api::BaseTransaction* trans,
const sync_api::SyncManager::ChangeRecord* changes,
int change_count) {
DCHECK(expected_loop_ == MessageLoop::current());
if (!running())
return;
sync_api::ReadNode password_root(trans);
if (!password_root.InitByTagLookup(kPasswordTag)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password root node lookup failed.");
return;
}
DCHECK(deleted_passwords_.empty() && new_passwords_.empty() &&
updated_passwords_.empty());
for (int i = 0; i < change_count; ++i) {
if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
changes[i].action) {
DCHECK(changes[i].specifics.HasExtension(sync_pb::password))
<< "Password specifics data not present on delete!";
DCHECK(changes[i].extra.get());
sync_api::SyncManager::ExtraPasswordChangeRecordData* extra =
changes[i].extra.get();
const sync_pb::PasswordSpecificsData& password = extra->unencrypted();
webkit_glue::PasswordForm form;
PasswordModelAssociator::CopyPassword(password, &form);
deleted_passwords_.push_back(form);
model_associator_->Disassociate(changes[i].id);
continue;
}
sync_api::ReadNode sync_node(trans);
if (!sync_node.InitByIdLookup(changes[i].id)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password node lookup failed.");
return;
}
// Check that the changed node is a child of the passwords folder.
DCHECK(password_root.GetId() == sync_node.GetParentId());
DCHECK(syncable::PASSWORDS == sync_node.GetModelType());
const sync_pb::PasswordSpecificsData& password_data =
sync_node.GetPasswordSpecifics();
webkit_glue::PasswordForm password;
PasswordModelAssociator::CopyPassword(password_data, &password);
if (sync_api::SyncManager::ChangeRecord::ACTION_ADD == changes[i].action) {
std::string tag(PasswordModelAssociator::MakeTag(password));
model_associator_->Associate(&tag, sync_node.GetId());
new_passwords_.push_back(password);
} else {
DCHECK(sync_api::SyncManager::ChangeRecord::ACTION_UPDATE ==
changes[i].action);
updated_passwords_.push_back(password);
}
}
}
void PasswordChangeProcessor::CommitChangesFromSyncModel() {
DCHECK(expected_loop_ == MessageLoop::current());
if (!running())
return;
StopObserving();
if (!model_associator_->WriteToPasswordStore(&new_passwords_,
&updated_passwords_,
&deleted_passwords_)) {
error_handler()->OnUnrecoverableError(FROM_HERE, "Error writing passwords");
return;
}
deleted_passwords_.clear();
new_passwords_.clear();
updated_passwords_.clear();
StartObserving();
}
void PasswordChangeProcessor::StartImpl(Profile* profile) {
DCHECK(expected_loop_ == MessageLoop::current());
observing_ = true;
}
void PasswordChangeProcessor::StopImpl() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
observing_ = false;
}
void PasswordChangeProcessor::StartObserving() {
DCHECK(expected_loop_ == MessageLoop::current());
notification_registrar_.Add(this,
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(password_store_));
}
void PasswordChangeProcessor::StopObserving() {
DCHECK(expected_loop_ == MessageLoop::current());
notification_registrar_.Remove(this,
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(password_store_));
}
} // namespace browser_sync
<commit_msg>Don't shut down sync and deadlock when trying to remove passwords that sync doesn't know about. This is weird but not a fatal error.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/glue/password_change_processor.h"
#include <string>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_store.h"
#include "chrome/browser/password_manager/password_store_change.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/glue/password_model_associator.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/protocol/password_specifics.pb.h"
#include "content/common/notification_details.h"
#include "content/common/notification_source.h"
#include "content/common/notification_type.h"
#include "webkit/glue/password_form.h"
namespace browser_sync {
PasswordChangeProcessor::PasswordChangeProcessor(
PasswordModelAssociator* model_associator,
PasswordStore* password_store,
UnrecoverableErrorHandler* error_handler)
: ChangeProcessor(error_handler),
model_associator_(model_associator),
password_store_(password_store),
observing_(false),
expected_loop_(MessageLoop::current()) {
DCHECK(model_associator);
DCHECK(error_handler);
#if defined(OS_MACOSX)
DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::UI));
#else
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));
#endif
StartObserving();
}
PasswordChangeProcessor::~PasswordChangeProcessor() {
DCHECK(expected_loop_ == MessageLoop::current());
}
void PasswordChangeProcessor::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(expected_loop_ == MessageLoop::current());
DCHECK(NotificationType::LOGINS_CHANGED == type);
if (!observing_)
return;
DCHECK(running());
sync_api::WriteTransaction trans(share_handle());
sync_api::ReadNode password_root(&trans);
if (!password_root.InitByTagLookup(kPasswordTag)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Server did not create the top-level password node. "
"We might be running against an out-of-date server.");
return;
}
PasswordStoreChangeList* changes =
Details<PasswordStoreChangeList>(details).ptr();
for (PasswordStoreChangeList::iterator change = changes->begin();
change != changes->end(); ++change) {
std::string tag = PasswordModelAssociator::MakeTag(change->form());
switch (change->type()) {
case PasswordStoreChange::ADD: {
sync_api::WriteNode sync_node(&trans);
if (!sync_node.InitUniqueByCreation(syncable::PASSWORDS,
password_root, tag)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Failed to create password sync node.");
return;
}
PasswordModelAssociator::WriteToSyncNode(change->form(), &sync_node);
model_associator_->Associate(&tag, sync_node.GetId());
break;
}
case PasswordStoreChange::UPDATE: {
sync_api::WriteNode sync_node(&trans);
int64 sync_id = model_associator_->GetSyncIdFromChromeId(tag);
if (sync_api::kInvalidId == sync_id) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Unexpected notification for: ");
return;
} else {
if (!sync_node.InitByIdLookup(sync_id)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password node lookup failed.");
return;
}
}
PasswordModelAssociator::WriteToSyncNode(change->form(), &sync_node);
break;
}
case PasswordStoreChange::REMOVE: {
sync_api::WriteNode sync_node(&trans);
int64 sync_id = model_associator_->GetSyncIdFromChromeId(tag);
if (sync_api::kInvalidId == sync_id) {
// We've been asked to remove a password that we don't know about.
// That's weird, but apparently we were already in the requested
// state, so it's not really an unrecoverable error. Just return.
LOG(WARNING) << "Trying to delete nonexistent password sync node!";
return;
} else {
if (!sync_node.InitByIdLookup(sync_id)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password node lookup failed.");
return;
}
model_associator_->Disassociate(sync_node.GetId());
sync_node.Remove();
}
break;
}
}
}
}
void PasswordChangeProcessor::ApplyChangesFromSyncModel(
const sync_api::BaseTransaction* trans,
const sync_api::SyncManager::ChangeRecord* changes,
int change_count) {
DCHECK(expected_loop_ == MessageLoop::current());
if (!running())
return;
sync_api::ReadNode password_root(trans);
if (!password_root.InitByTagLookup(kPasswordTag)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password root node lookup failed.");
return;
}
DCHECK(deleted_passwords_.empty() && new_passwords_.empty() &&
updated_passwords_.empty());
for (int i = 0; i < change_count; ++i) {
if (sync_api::SyncManager::ChangeRecord::ACTION_DELETE ==
changes[i].action) {
DCHECK(changes[i].specifics.HasExtension(sync_pb::password))
<< "Password specifics data not present on delete!";
DCHECK(changes[i].extra.get());
sync_api::SyncManager::ExtraPasswordChangeRecordData* extra =
changes[i].extra.get();
const sync_pb::PasswordSpecificsData& password = extra->unencrypted();
webkit_glue::PasswordForm form;
PasswordModelAssociator::CopyPassword(password, &form);
deleted_passwords_.push_back(form);
model_associator_->Disassociate(changes[i].id);
continue;
}
sync_api::ReadNode sync_node(trans);
if (!sync_node.InitByIdLookup(changes[i].id)) {
error_handler()->OnUnrecoverableError(FROM_HERE,
"Password node lookup failed.");
return;
}
// Check that the changed node is a child of the passwords folder.
DCHECK(password_root.GetId() == sync_node.GetParentId());
DCHECK(syncable::PASSWORDS == sync_node.GetModelType());
const sync_pb::PasswordSpecificsData& password_data =
sync_node.GetPasswordSpecifics();
webkit_glue::PasswordForm password;
PasswordModelAssociator::CopyPassword(password_data, &password);
if (sync_api::SyncManager::ChangeRecord::ACTION_ADD == changes[i].action) {
std::string tag(PasswordModelAssociator::MakeTag(password));
model_associator_->Associate(&tag, sync_node.GetId());
new_passwords_.push_back(password);
} else {
DCHECK(sync_api::SyncManager::ChangeRecord::ACTION_UPDATE ==
changes[i].action);
updated_passwords_.push_back(password);
}
}
}
void PasswordChangeProcessor::CommitChangesFromSyncModel() {
DCHECK(expected_loop_ == MessageLoop::current());
if (!running())
return;
StopObserving();
if (!model_associator_->WriteToPasswordStore(&new_passwords_,
&updated_passwords_,
&deleted_passwords_)) {
error_handler()->OnUnrecoverableError(FROM_HERE, "Error writing passwords");
return;
}
deleted_passwords_.clear();
new_passwords_.clear();
updated_passwords_.clear();
StartObserving();
}
void PasswordChangeProcessor::StartImpl(Profile* profile) {
DCHECK(expected_loop_ == MessageLoop::current());
observing_ = true;
}
void PasswordChangeProcessor::StopImpl() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
observing_ = false;
}
void PasswordChangeProcessor::StartObserving() {
DCHECK(expected_loop_ == MessageLoop::current());
notification_registrar_.Add(this,
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(password_store_));
}
void PasswordChangeProcessor::StopObserving() {
DCHECK(expected_loop_ == MessageLoop::current());
notification_registrar_.Remove(this,
NotificationType::LOGINS_CHANGED,
Source<PasswordStore>(password_store_));
}
} // namespace browser_sync
<|endoftext|>
|
<commit_before>#include "EnvimetReader.h"
#include <vtkObjectFactory.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkInformationVector.h>
#include <vtkInformation.h>
#include <vtkSmartPointer.h>
#include <vtkPointData.h>
#include <vtkDataArray.h>
#include <vtkFloatArray.h>
#include <vtkDataArraySelection.h>
#include <vtkCallbackCommand.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
vtkStandardNewMacro(EnvimetReader);
EnvimetReader::EnvimetReader()
: _infoFileRead(false)
{
FileName = NULL;
NumberOfNestingCells = 12;
SetNumberOfInputPorts(0);
SetNumberOfOutputPorts(1);
PointDataArraySelection = vtkDataArraySelection::New();
SelectionObserver = vtkCallbackCommand::New();
SelectionObserver->SetCallback(&EnvimetReader::SelectionModifiedCallback);
SelectionObserver->SetClientData(this);
PointDataArraySelection->AddObserver(vtkCommand::ModifiedEvent, this->SelectionObserver);
XCoordinates = vtkFloatArray::New();
YCoordinates = vtkFloatArray::New();
ZCoordinates = vtkFloatArray::New();
}
EnvimetReader::~EnvimetReader()
{
XCoordinates->Delete();
YCoordinates->Delete();
ZCoordinates->Delete();
PointDataArraySelection->RemoveObserver(this->SelectionObserver);
SelectionObserver->Delete();
PointDataArraySelection->Delete();
}
int EnvimetReader::CanReadFile(const char *name, const char *extension)
{
// Check if file exists
struct stat fs;
if (stat(name, &fs) != 0)
{
vtkErrorMacro(<< "The file " << name << " does not exist.")
return 0;
}
if(std::string(name).rfind(extension) == std::string::npos)
{
vtkErrorMacro(<< "The file " <<name << " has the wrong extension. Expected: " << extension);
return 0;
}
else
return 1;
}
int EnvimetReader::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
if(_infoFileRead)
return 1;
vtkInformation *outInfo = outputVector->GetInformationObject(0);
if(!FileName)
{
vtkErrorMacro(<< "A FileName must be specified.");
return -1;
}
if(!CanReadFile(FileName, ".EDI"))
return -1;
std::ifstream in (FileName, std::ifstream::in);
if(!in.is_open())
{
vtkErrorMacro(<< "File " << this->FileName << " could not be opened");
return -1;
}
std::string line;
std::getline(in, line);
// TODO "Waldstr 07:00:00 07.09.2013"
std::getline(in, line);
XDimension = std::stoi(line);
std::getline(in, line);
YDimension = std::stoi(line);
std::getline(in, line);
ZDimension = std::stoi(line);
std::getline(in, line);
// TODO "51"?
// Array names
while(line.find("Gridspacing") == std::string::npos)
{
std::getline(in, line);
if(line.find("Gridspacing") == std::string::npos)
PointDataArraySelection->AddArray(line.c_str());
}
PointDataArraySelection->DisableAllArrays();
XCoordinates->Reset();
XCoordinates->InsertNextValue(0.0f);
for(int i = 0; i < XDimension; i++)
{
std::getline(in, line);
const float cellSize = std::stof(line);
XCoordinates->InsertNextValue(XCoordinates->GetValue(i) + cellSize);
}
YCoordinates->Reset();
YCoordinates->InsertNextValue(0.0f);
for(int i = 0; i < YDimension; i++)
{
std::getline(in, line);
const float cellSize = std::stof(line);
YCoordinates->InsertNextValue(YCoordinates->GetValue(i) + cellSize);
}
ZCoordinates->Reset();
ZCoordinates->InsertNextValue(0.0f);
for(int i = 0; i < ZDimension; i++)
{
std::getline(in, line);
const float cellSize = std::stof(line);
ZCoordinates->InsertNextValue(ZCoordinates->GetValue(i) + cellSize);
}
in.close();
_infoFileRead = true;
int ext[6] = { NumberOfNestingCells - 1, XDimension - NumberOfNestingCells - 1,
NumberOfNestingCells - 1, YDimension - NumberOfNestingCells - 1,
0, ZDimension - 1 };
double origin[3] = {0, 0, 0};
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), ext, 6);
outInfo->Set(vtkDataObject::ORIGIN(), origin, 3);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
return 1;
}
int EnvimetReader::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
vtkRectilinearGrid *output = vtkRectilinearGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
output->SetExtent(
outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()));
// Points
output->SetDimensions(XDimension, YDimension, ZDimension);
output->SetXCoordinates(XCoordinates);
output->SetYCoordinates(YCoordinates);
output->SetZCoordinates(ZCoordinates);
if(PointDataArraySelection->GetNumberOfArraysEnabled() == 0)
{
vtkErrorMacro(<< "No data arrays enabled. Only the mesh itself was loaded.")
return 1;
}
std::string asciiFileName = std::string(FileName);
std::string binaryFileName = asciiFileName.substr(0, asciiFileName.size() - 3).append("EDT");
if(!CanReadFile(binaryFileName.c_str(), ".EDT"))
return -1;
std::ifstream in (binaryFileName.c_str(), std::ifstream::in | std::ios::binary);
if(!in.is_open())
{
vtkErrorMacro(<< "File " << binaryFileName.c_str() << " could not be opened");
return -1;
}
const vtkIdType numTuples = XDimension * YDimension * ZDimension;
const int numArrays = PointDataArraySelection->GetNumberOfArraysEnabled();
int numArraysRead = 0;
UpdateProgress(0.0f);
for(int arrayIndex = 0; arrayIndex < PointDataArraySelection->GetNumberOfArrays(); arrayIndex++)
{
if(PointDataArraySelection->GetArraySetting(arrayIndex) &&
!output->GetPointData()->HasArray(GetPointArrayName(arrayIndex)))
{
// Read into vtk array
float *floats = new float[numTuples];
in.read(reinterpret_cast<char *>(&floats[0]), sizeof(float) * numTuples);
vtkFloatArray *floatArray = vtkFloatArray::New();
floatArray->SetName(PointDataArraySelection->GetArrayName(arrayIndex));
floatArray->SetNumberOfTuples(numTuples);
floatArray->SetArray(floats, numTuples, 0); // Ownership of floats is handed over to floatArray
output->GetPointData()->AddArray(floatArray);
UpdateProgress(numArraysRead * 1 / numArrays);
if(numArraysRead == numArrays)
break;
}
else
// Move on to the next array
in.seekg(sizeof(float) * numTuples, std::ios_base::cur);
}
UpdateProgress(1.0f);
in.close();
return 1;
}
void EnvimetReader::SelectionModifiedCallback(vtkObject*, unsigned long, void* clientdata, void*)
{
static_cast<EnvimetReader*>(clientdata)->Modified();
}
int EnvimetReader::GetNumberOfPointArrays()
{
return PointDataArraySelection->GetNumberOfArrays();
}
const char * EnvimetReader::GetPointArrayName(int index)
{
return PointDataArraySelection->GetArrayName(index);
}
int EnvimetReader::GetPointArrayStatus(const char *name)
{
return PointDataArraySelection->ArrayIsEnabled(name);
}
void EnvimetReader::SetPointArrayStatus(const char *name, int status)
{
if(status)
PointDataArraySelection->EnableArray(name);
else
PointDataArraySelection->DisableArray(name);
}
void EnvimetReader::PrintSelf(ostream& os, vtkIndent indent)
{
Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (FileName ? FileName : "(none)") << "\n";
}
<commit_msg>VS 2008 compatible string to number conversion.<commit_after>#include "EnvimetReader.h"
#include <vtkObjectFactory.h>
#include <vtkStreamingDemandDrivenPipeline.h>
#include <vtkInformationVector.h>
#include <vtkInformation.h>
#include <vtkSmartPointer.h>
#include <vtkPointData.h>
#include <vtkDataArray.h>
#include <vtkFloatArray.h>
#include <vtkDataArraySelection.h>
#include <vtkCallbackCommand.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
vtkStandardNewMacro(EnvimetReader);
EnvimetReader::EnvimetReader()
: _infoFileRead(false)
{
FileName = NULL;
NumberOfNestingCells = 12;
SetNumberOfInputPorts(0);
SetNumberOfOutputPorts(1);
PointDataArraySelection = vtkDataArraySelection::New();
SelectionObserver = vtkCallbackCommand::New();
SelectionObserver->SetCallback(&EnvimetReader::SelectionModifiedCallback);
SelectionObserver->SetClientData(this);
PointDataArraySelection->AddObserver(vtkCommand::ModifiedEvent, this->SelectionObserver);
XCoordinates = vtkFloatArray::New();
YCoordinates = vtkFloatArray::New();
ZCoordinates = vtkFloatArray::New();
}
EnvimetReader::~EnvimetReader()
{
XCoordinates->Delete();
YCoordinates->Delete();
ZCoordinates->Delete();
PointDataArraySelection->RemoveObserver(this->SelectionObserver);
SelectionObserver->Delete();
PointDataArraySelection->Delete();
}
int EnvimetReader::CanReadFile(const char *name, const char *extension)
{
// Check if file exists
struct stat fs;
if (stat(name, &fs) != 0)
{
vtkErrorMacro(<< "The file " << name << " does not exist.")
return 0;
}
if(std::string(name).rfind(extension) == std::string::npos)
{
vtkErrorMacro(<< "The file " <<name << " has the wrong extension. Expected: " << extension);
return 0;
}
else
return 1;
}
int EnvimetReader::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
if(_infoFileRead)
return 1;
vtkInformation *outInfo = outputVector->GetInformationObject(0);
if(!FileName)
{
vtkErrorMacro(<< "A FileName must be specified.");
return -1;
}
if(!CanReadFile(FileName, ".EDI"))
return -1;
std::ifstream in (FileName, std::ifstream::in);
if(!in.is_open())
{
vtkErrorMacro(<< "File " << this->FileName << " could not be opened");
return -1;
}
std::string line;
std::getline(in, line);
// TODO "Waldstr 07:00:00 07.09.2013"
std::getline(in, line);
XDimension = atoi(line.c_str());
std::getline(in, line);
YDimension = atoi(line.c_str());
std::getline(in, line);
ZDimension = atoi(line.c_str());
std::getline(in, line);
// TODO "51"?
// Array names
while(line.find("Gridspacing") == std::string::npos)
{
std::getline(in, line);
if(line.find("Gridspacing") == std::string::npos)
PointDataArraySelection->AddArray(line.c_str());
}
PointDataArraySelection->DisableAllArrays();
XCoordinates->Reset();
XCoordinates->InsertNextValue(0.0f);
for(int i = 0; i < XDimension; i++)
{
std::getline(in, line);
const float cellSize = atof(line.c_str());
XCoordinates->InsertNextValue(XCoordinates->GetValue(i) + cellSize);
}
YCoordinates->Reset();
YCoordinates->InsertNextValue(0.0f);
for(int i = 0; i < YDimension; i++)
{
std::getline(in, line);
const float cellSize = atof(line.c_str());
YCoordinates->InsertNextValue(YCoordinates->GetValue(i) + cellSize);
}
ZCoordinates->Reset();
ZCoordinates->InsertNextValue(0.0f);
for(int i = 0; i < ZDimension; i++)
{
std::getline(in, line);
const float cellSize = atof(line.c_str());
ZCoordinates->InsertNextValue(ZCoordinates->GetValue(i) + cellSize);
}
in.close();
_infoFileRead = true;
int ext[6] = { NumberOfNestingCells - 1, XDimension - NumberOfNestingCells - 1,
NumberOfNestingCells - 1, YDimension - NumberOfNestingCells - 1,
0, ZDimension - 1 };
double origin[3] = {0, 0, 0};
outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), ext, 6);
outInfo->Set(vtkDataObject::ORIGIN(), origin, 3);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
return 1;
}
int EnvimetReader::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
vtkInformation *outInfo = outputVector->GetInformationObject(0);
vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_FLOAT, 1);
vtkRectilinearGrid *output = vtkRectilinearGrid::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
output->SetExtent(
outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()));
// Points
output->SetDimensions(XDimension, YDimension, ZDimension);
output->SetXCoordinates(XCoordinates);
output->SetYCoordinates(YCoordinates);
output->SetZCoordinates(ZCoordinates);
if(PointDataArraySelection->GetNumberOfArraysEnabled() == 0)
{
vtkErrorMacro(<< "No data arrays enabled. Only the mesh itself was loaded.")
return 1;
}
std::string asciiFileName = std::string(FileName);
std::string binaryFileName = asciiFileName.substr(0, asciiFileName.size() - 3).append("EDT");
if(!CanReadFile(binaryFileName.c_str(), ".EDT"))
return -1;
std::ifstream in (binaryFileName.c_str(), std::ifstream::in | std::ios::binary);
if(!in.is_open())
{
vtkErrorMacro(<< "File " << binaryFileName.c_str() << " could not be opened");
return -1;
}
const vtkIdType numTuples = XDimension * YDimension * ZDimension;
const int numArrays = PointDataArraySelection->GetNumberOfArraysEnabled();
int numArraysRead = 0;
UpdateProgress(0.0f);
for(int arrayIndex = 0; arrayIndex < PointDataArraySelection->GetNumberOfArrays(); arrayIndex++)
{
if(PointDataArraySelection->GetArraySetting(arrayIndex) &&
!output->GetPointData()->HasArray(GetPointArrayName(arrayIndex)))
{
// Read into vtk array
float *floats = new float[numTuples];
in.read(reinterpret_cast<char *>(&floats[0]), sizeof(float) * numTuples);
vtkFloatArray *floatArray = vtkFloatArray::New();
floatArray->SetName(PointDataArraySelection->GetArrayName(arrayIndex));
floatArray->SetNumberOfTuples(numTuples);
floatArray->SetArray(floats, numTuples, 0); // Ownership of floats is handed over to floatArray
output->GetPointData()->AddArray(floatArray);
UpdateProgress(numArraysRead * 1 / numArrays);
if(numArraysRead == numArrays)
break;
}
else
// Move on to the next array
in.seekg(sizeof(float) * numTuples, std::ios_base::cur);
}
UpdateProgress(1.0f);
in.close();
return 1;
}
void EnvimetReader::SelectionModifiedCallback(vtkObject*, unsigned long, void* clientdata, void*)
{
static_cast<EnvimetReader*>(clientdata)->Modified();
}
int EnvimetReader::GetNumberOfPointArrays()
{
return PointDataArraySelection->GetNumberOfArrays();
}
const char * EnvimetReader::GetPointArrayName(int index)
{
return PointDataArraySelection->GetArrayName(index);
}
int EnvimetReader::GetPointArrayStatus(const char *name)
{
return PointDataArraySelection->ArrayIsEnabled(name);
}
void EnvimetReader::SetPointArrayStatus(const char *name, int status)
{
if(status)
PointDataArraySelection->EnableArray(name);
else
PointDataArraySelection->DisableArray(name);
}
void EnvimetReader::PrintSelf(ostream& os, vtkIndent indent)
{
Superclass::PrintSelf(os,indent);
os << indent << "File Name: "
<< (FileName ? FileName : "(none)") << "\n";
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File Monodomain.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Monodomain cardiac electrophysiology homogenised model.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <CardiacEPSolver/EquationSystems/Monodomain.h>
#include <CardiacEPSolver/Filters/FilterCheckpointCellModel.h>
namespace Nektar
{
/**
* @class Monodomain
*
* Base model of cardiac electrophysiology of the form
* \f{align*}{
* \frac{\partial u}{\partial t} = \nabla^2 u + J_{ion},
* \f}
* where the reaction term, \f$J_{ion}\f$ is defined by a specific cell
* model.
*
* This implementation, at present, treats the reaction terms explicitly
* and the diffusive element implicitly.
*/
/**
* Registers the class with the Factory.
*/
string Monodomain::className
= GetEquationSystemFactory().RegisterCreatorFunction(
"Monodomain",
Monodomain::create,
"Monodomain model of cardiac electrophysiology.");
/**
*
*/
Monodomain::Monodomain(
const LibUtilities::SessionReaderSharedPtr& pSession)
: UnsteadySystem(pSession)
{
}
/**
*
*/
void Monodomain::v_InitObject()
{
UnsteadySystem::v_InitObject();
m_session->LoadParameter("Chi", m_chi);
m_session->LoadParameter("Cm", m_capMembrane);
std::string vCellModel;
m_session->LoadSolverInfo("CELLMODEL", vCellModel, "");
ASSERTL0(vCellModel != "", "Cell Model not specified.");
m_cell = GetCellModelFactory().CreateInstance(
vCellModel, m_session, m_fields[0]);
m_intVariables.push_back(0);
// Load variable coefficients
StdRegions::VarCoeffType varCoeffEnum[6] = {
StdRegions::eVarCoeffD00,
StdRegions::eVarCoeffD01,
StdRegions::eVarCoeffD11,
StdRegions::eVarCoeffD02,
StdRegions::eVarCoeffD12,
StdRegions::eVarCoeffD22
};
std::string aniso_var[3] = {"fx", "fy", "fz"};
const int nq = m_fields[0]->GetNpoints();
const int nVarDiffCmpts = m_spacedim * (m_spacedim + 1) / 2;
// Allocate storage for variable coeffs and initialize to 1.
for (int i = 0; i < nVarDiffCmpts; ++i)
{
m_vardiff[varCoeffEnum[i]] = Array<OneD, NekDouble>(nq, 1.0);
}
// Apply fibre map f \in [0,1], scale to conductivity range
// [o_min,o_max], specified by the session parameters o_min and o_max
if (m_session->DefinesFunction("AnisotropicConductivity"))
{
if (m_session->DefinesCmdLineArgument("verbose"))
{
cout << "Loading Anisotropic Fibre map." << endl;
}
NekDouble o_min = m_session->GetParameter("o_min");
NekDouble o_max = m_session->GetParameter("o_max");
int k = 0;
Array<OneD, NekDouble> vTemp_i;
Array<OneD, NekDouble> vTemp_j;
/*
* Diffusivity matrix D is upper triangular and defined as
* d_00 d_01 d_02
* d_11 d_12
* d_22
*
* Given a principle fibre direction _f_ the diffusivity is given
* by
* d_ij = { D_2 + (D_1 - D_2) f_i f_j if i==j
* { (D_1 - D_2) f_i f_j if i!=j
*
* The vector _f_ is given in terms of the variables fx,fy,fz in the
* function AnisotropicConductivity. The values of D_1 and D_2 are
* the parameters o_max and o_min, respectively.
*/
// Loop through columns of D
for (int j = 0; j < m_spacedim; ++j)
{
ASSERTL0(m_session->DefinesFunction("AnisotropicConductivity",
aniso_var[j]),
"Function 'AnisotropicConductivity' not correctly "
"defined.");
EvaluateFunction(aniso_var[j], vTemp_j,
"AnisotropicConductivity");
// Loop through rows of D
for (int i = 0; i < j + 1; ++i)
{
ASSERTL0(m_session->DefinesFunction(
"AnisotropicConductivity",aniso_var[i]),
"Function 'AnisotropicConductivity' not correctly "
"defined.");
EvaluateFunction(aniso_var[i], vTemp_i,
"AnisotropicConductivity");
Vmath::Vmul(nq, vTemp_i, 1, vTemp_j, 1,
m_vardiff[varCoeffEnum[k]], 1);
Vmath::Smul(nq, o_max-o_min,
m_vardiff[varCoeffEnum[k]], 1,
m_vardiff[varCoeffEnum[k]], 1);
if (i == j)
{
Vmath::Sadd(nq, o_min,
m_vardiff[varCoeffEnum[k]], 1,
m_vardiff[varCoeffEnum[k]], 1);
}
++k;
}
}
}
// Scale by scar map (range 0->1) derived from intensity map
// (range d_min -> d_max)
if (m_session->DefinesFunction("IsotropicConductivity"))
{
if (m_session->DefinesCmdLineArgument("verbose"))
{
cout << "Loading Isotropic Conductivity map." << endl;
}
std::string varName = "intensity";
NekDouble f_min = m_session->GetParameter("d_min");
NekDouble f_max = m_session->GetParameter("d_max");
Array<OneD, NekDouble> vTemp;
EvaluateFunction(varName, vTemp, "IsotropicConductivity");
// Threshold based on d_min, d_max
for (int j = 0; j < nq; ++j)
{
vTemp[j] = (vTemp[j] < f_min ? f_min : vTemp[j]);
vTemp[j] = (vTemp[j] > f_max ? f_max : vTemp[j]);
}
// Rescale to s \in [0,1] (0 maps to d_max, 1 maps to d_min)
Vmath::Sadd(nq, -f_min, vTemp, 1, vTemp, 1);
Vmath::Smul(nq, -1.0/(f_max-f_min), vTemp, 1, vTemp, 1);
Vmath::Sadd(nq, 1.0, vTemp, 1, vTemp, 1);
// Scale anisotropic conductivity values
for (int i = 0; i < m_spacedim; ++i)
{
Vmath::Vmul(nq, vTemp, 1,
m_vardiff[varCoeffEnum[i]], 1,
m_vardiff[varCoeffEnum[i]], 1);
}
}
// Write out conductivity values
for (int i = 0; i < m_spacedim; ++i)
{
// Transform variable coefficient and write out to file.
m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[i]],
m_fields[0]->UpdateCoeffs());
std::stringstream filename;
filename << "Conductivity_" << aniso_var[i];
if (m_comm->GetSize() > 1)
{
filename << "_P" << m_comm->GetRank();
}
filename << ".fld";
WriteFld(filename.str());
}
// Search through the loaded filters and pass the cell model to any
// CheckpointCellModel filters loaded.
int k = 0;
const LibUtilities::FilterMap& f = m_session->GetFilters();
LibUtilities::FilterMap::const_iterator x;
for (x = f.begin(); x != f.end(); ++x, ++k)
{
if (x->first == "CheckpointCellModel")
{
boost::shared_ptr<FilterCheckpointCellModel> c
= boost::dynamic_pointer_cast<FilterCheckpointCellModel>(
m_filters[k]);
c->SetCellModel(m_cell);
}
}
// Load stimuli
m_stimulus = Stimulus::LoadStimuli(m_session, m_fields[0]);
if (!m_explicitDiffusion)
{
m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);
}
m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);
}
/**
*
*/
Monodomain::~Monodomain()
{
}
/**
* @param inarray Input array.
* @param outarray Output array.
* @param time Current simulation time.
* @param lambda Timestep.
*/
void Monodomain::DoImplicitSolve(
const Array<OneD, const Array<OneD, NekDouble> >&inarray,
Array<OneD, Array<OneD, NekDouble> >&outarray,
const NekDouble time,
const NekDouble lambda)
{
int nvariables = inarray.num_elements();
int nq = m_fields[0]->GetNpoints();
StdRegions::ConstFactorMap factors;
// lambda = \Delta t
factors[StdRegions::eFactorLambda] = 1.0/lambda*m_chi*m_capMembrane;
// We solve ( \nabla^2 - HHlambda ) Y[i] = rhs [i]
// inarray = input: \hat{rhs} -> output: \hat{Y}
// outarray = output: nabla^2 \hat{Y}
// where \hat = modal coeffs
for (int i = 0; i < nvariables; ++i)
{
// Multiply 1.0/timestep
Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,
m_fields[i]->UpdatePhys(), 1);
// Solve a system of equations with Helmholtz solver and transform
// back into physical space.
m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),
m_fields[i]->UpdateCoeffs(), NullFlagList,
factors, m_vardiff);
m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),
m_fields[i]->UpdatePhys());
m_fields[i]->SetPhysState(true);
// Copy the solution vector (required as m_fields must be set).
outarray[i] = m_fields[i]->GetPhys();
}
}
/**
*
*/
void Monodomain::DoOdeRhs(
const Array<OneD, const Array<OneD, NekDouble> >&inarray,
Array<OneD, Array<OneD, NekDouble> >&outarray,
const NekDouble time)
{
// Compute I_ion
m_cell->TimeIntegrate(inarray, outarray, time);
// Compute I_stim
for (unsigned int i = 0; i < m_stimulus.size(); ++i)
{
m_stimulus[i]->Update(outarray, time);
}
}
/**
*
*/
void Monodomain::v_SetInitialConditions(NekDouble initialtime,
bool dumpInitialConditions)
{
EquationSystem::v_SetInitialConditions(initialtime,
dumpInitialConditions);
m_cell->Initialise();
}
/**
*
*/
void Monodomain::v_GenerateSummary(SummaryList& s)
{
UnsteadySystem::v_GenerateSummary(s);
if (m_session->DefinesFunction("d00") &&
m_session->GetFunctionType("d00", "intensity")
== LibUtilities::eFunctionTypeExpression)
{
AddSummaryItem(s, "Diffusivity-x",
m_session->GetFunction("d00", "intensity")->GetExpression());
}
if (m_session->DefinesFunction("d11") &&
m_session->GetFunctionType("d11", "intensity")
== LibUtilities::eFunctionTypeExpression)
{
AddSummaryItem(s, "Diffusivity-y",
m_session->GetFunction("d11", "intensity")->GetExpression());
}
if (m_session->DefinesFunction("d22") &&
m_session->GetFunctionType("d22", "intensity")
== LibUtilities::eFunctionTypeExpression)
{
AddSummaryItem(s, "Diffusivity-z",
m_session->GetFunction("d22", "intensity")->GetExpression());
}
m_cell->GenerateSummary(s);
}
}
<commit_msg>Fixed output of conductivity tensor.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File Monodomain.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Monodomain cardiac electrophysiology homogenised model.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <CardiacEPSolver/EquationSystems/Monodomain.h>
#include <CardiacEPSolver/Filters/FilterCheckpointCellModel.h>
namespace Nektar
{
/**
* @class Monodomain
*
* Base model of cardiac electrophysiology of the form
* \f{align*}{
* \frac{\partial u}{\partial t} = \nabla^2 u + J_{ion},
* \f}
* where the reaction term, \f$J_{ion}\f$ is defined by a specific cell
* model.
*
* This implementation, at present, treats the reaction terms explicitly
* and the diffusive element implicitly.
*/
/**
* Registers the class with the Factory.
*/
string Monodomain::className
= GetEquationSystemFactory().RegisterCreatorFunction(
"Monodomain",
Monodomain::create,
"Monodomain model of cardiac electrophysiology.");
/**
*
*/
Monodomain::Monodomain(
const LibUtilities::SessionReaderSharedPtr& pSession)
: UnsteadySystem(pSession)
{
}
/**
*
*/
void Monodomain::v_InitObject()
{
UnsteadySystem::v_InitObject();
m_session->LoadParameter("Chi", m_chi);
m_session->LoadParameter("Cm", m_capMembrane);
std::string vCellModel;
m_session->LoadSolverInfo("CELLMODEL", vCellModel, "");
ASSERTL0(vCellModel != "", "Cell Model not specified.");
m_cell = GetCellModelFactory().CreateInstance(
vCellModel, m_session, m_fields[0]);
m_intVariables.push_back(0);
// Load variable coefficients
StdRegions::VarCoeffType varCoeffEnum[6] = {
StdRegions::eVarCoeffD00,
StdRegions::eVarCoeffD01,
StdRegions::eVarCoeffD11,
StdRegions::eVarCoeffD02,
StdRegions::eVarCoeffD12,
StdRegions::eVarCoeffD22
};
std::string varCoeffString[6] = {"xx","xy","yy","xz","yz","zz"};
std::string aniso_var[3] = {"fx", "fy", "fz"};
const int nq = m_fields[0]->GetNpoints();
const int nVarDiffCmpts = m_spacedim * (m_spacedim + 1) / 2;
// Allocate storage for variable coeffs and initialize to 1.
for (int i = 0; i < nVarDiffCmpts; ++i)
{
m_vardiff[varCoeffEnum[i]] = Array<OneD, NekDouble>(nq, 1.0);
}
// Apply fibre map f \in [0,1], scale to conductivity range
// [o_min,o_max], specified by the session parameters o_min and o_max
if (m_session->DefinesFunction("AnisotropicConductivity"))
{
if (m_session->DefinesCmdLineArgument("verbose"))
{
cout << "Loading Anisotropic Fibre map." << endl;
}
NekDouble o_min = m_session->GetParameter("o_min");
NekDouble o_max = m_session->GetParameter("o_max");
int k = 0;
Array<OneD, NekDouble> vTemp_i;
Array<OneD, NekDouble> vTemp_j;
/*
* Diffusivity matrix D is upper triangular and defined as
* d_00 d_01 d_02
* d_11 d_12
* d_22
*
* Given a principle fibre direction _f_ the diffusivity is given
* by
* d_ij = { D_2 + (D_1 - D_2) f_i f_j if i==j
* { (D_1 - D_2) f_i f_j if i!=j
*
* The vector _f_ is given in terms of the variables fx,fy,fz in the
* function AnisotropicConductivity. The values of D_1 and D_2 are
* the parameters o_max and o_min, respectively.
*/
// Loop through columns of D
for (int j = 0; j < m_spacedim; ++j)
{
ASSERTL0(m_session->DefinesFunction("AnisotropicConductivity",
aniso_var[j]),
"Function 'AnisotropicConductivity' not correctly "
"defined.");
EvaluateFunction(aniso_var[j], vTemp_j,
"AnisotropicConductivity");
// Loop through rows of D
for (int i = 0; i < j + 1; ++i)
{
ASSERTL0(m_session->DefinesFunction(
"AnisotropicConductivity",aniso_var[i]),
"Function 'AnisotropicConductivity' not correctly "
"defined.");
EvaluateFunction(aniso_var[i], vTemp_i,
"AnisotropicConductivity");
Vmath::Vmul(nq, vTemp_i, 1, vTemp_j, 1,
m_vardiff[varCoeffEnum[k]], 1);
Vmath::Smul(nq, o_max-o_min,
m_vardiff[varCoeffEnum[k]], 1,
m_vardiff[varCoeffEnum[k]], 1);
if (i == j)
{
Vmath::Sadd(nq, o_min,
m_vardiff[varCoeffEnum[k]], 1,
m_vardiff[varCoeffEnum[k]], 1);
}
++k;
}
}
}
// Scale by scar map (range 0->1) derived from intensity map
// (range d_min -> d_max)
if (m_session->DefinesFunction("IsotropicConductivity"))
{
if (m_session->DefinesCmdLineArgument("verbose"))
{
cout << "Loading Isotropic Conductivity map." << endl;
}
std::string varName = "intensity";
NekDouble f_min = m_session->GetParameter("d_min");
NekDouble f_max = m_session->GetParameter("d_max");
Array<OneD, NekDouble> vTemp;
EvaluateFunction(varName, vTemp, "IsotropicConductivity");
// Threshold based on d_min, d_max
for (int j = 0; j < nq; ++j)
{
vTemp[j] = (vTemp[j] < f_min ? f_min : vTemp[j]);
vTemp[j] = (vTemp[j] > f_max ? f_max : vTemp[j]);
}
// Rescale to s \in [0,1] (0 maps to d_max, 1 maps to d_min)
Vmath::Sadd(nq, -f_min, vTemp, 1, vTemp, 1);
Vmath::Smul(nq, -1.0/(f_max-f_min), vTemp, 1, vTemp, 1);
Vmath::Sadd(nq, 1.0, vTemp, 1, vTemp, 1);
// Scale anisotropic conductivity values
for (int i = 0; i < m_spacedim; ++i)
{
Vmath::Vmul(nq, vTemp, 1,
m_vardiff[varCoeffEnum[i]], 1,
m_vardiff[varCoeffEnum[i]], 1);
}
}
// Write out conductivity values
for (int j = 0, k = 0; j < m_spacedim; ++j)
{
// Loop through rows of D
for (int i = 0; i < j + 1; ++i)
{
// Transform variable coefficient and write out to file.
m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[k]],
m_fields[0]->UpdateCoeffs());
std::stringstream filename;
filename << "Conductivity_" << varCoeffString[k];
if (m_comm->GetSize() > 1)
{
filename << "_P" << m_comm->GetRank();
}
filename << ".fld";
WriteFld(filename.str());
++k;
}
}
// Search through the loaded filters and pass the cell model to any
// CheckpointCellModel filters loaded.
int k = 0;
const LibUtilities::FilterMap& f = m_session->GetFilters();
LibUtilities::FilterMap::const_iterator x;
for (x = f.begin(); x != f.end(); ++x, ++k)
{
if (x->first == "CheckpointCellModel")
{
boost::shared_ptr<FilterCheckpointCellModel> c
= boost::dynamic_pointer_cast<FilterCheckpointCellModel>(
m_filters[k]);
c->SetCellModel(m_cell);
}
}
// Load stimuli
m_stimulus = Stimulus::LoadStimuli(m_session, m_fields[0]);
if (!m_explicitDiffusion)
{
m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);
}
m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);
}
/**
*
*/
Monodomain::~Monodomain()
{
}
/**
* @param inarray Input array.
* @param outarray Output array.
* @param time Current simulation time.
* @param lambda Timestep.
*/
void Monodomain::DoImplicitSolve(
const Array<OneD, const Array<OneD, NekDouble> >&inarray,
Array<OneD, Array<OneD, NekDouble> >&outarray,
const NekDouble time,
const NekDouble lambda)
{
int nvariables = inarray.num_elements();
int nq = m_fields[0]->GetNpoints();
StdRegions::ConstFactorMap factors;
// lambda = \Delta t
factors[StdRegions::eFactorLambda] = 1.0/lambda*m_chi*m_capMembrane;
// We solve ( \nabla^2 - HHlambda ) Y[i] = rhs [i]
// inarray = input: \hat{rhs} -> output: \hat{Y}
// outarray = output: nabla^2 \hat{Y}
// where \hat = modal coeffs
for (int i = 0; i < nvariables; ++i)
{
// Multiply 1.0/timestep
Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,
m_fields[i]->UpdatePhys(), 1);
// Solve a system of equations with Helmholtz solver and transform
// back into physical space.
m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),
m_fields[i]->UpdateCoeffs(), NullFlagList,
factors, m_vardiff);
m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),
m_fields[i]->UpdatePhys());
m_fields[i]->SetPhysState(true);
// Copy the solution vector (required as m_fields must be set).
outarray[i] = m_fields[i]->GetPhys();
}
}
/**
*
*/
void Monodomain::DoOdeRhs(
const Array<OneD, const Array<OneD, NekDouble> >&inarray,
Array<OneD, Array<OneD, NekDouble> >&outarray,
const NekDouble time)
{
// Compute I_ion
m_cell->TimeIntegrate(inarray, outarray, time);
// Compute I_stim
for (unsigned int i = 0; i < m_stimulus.size(); ++i)
{
m_stimulus[i]->Update(outarray, time);
}
}
/**
*
*/
void Monodomain::v_SetInitialConditions(NekDouble initialtime,
bool dumpInitialConditions)
{
EquationSystem::v_SetInitialConditions(initialtime,
dumpInitialConditions);
m_cell->Initialise();
}
/**
*
*/
void Monodomain::v_GenerateSummary(SummaryList& s)
{
UnsteadySystem::v_GenerateSummary(s);
if (m_session->DefinesFunction("d00") &&
m_session->GetFunctionType("d00", "intensity")
== LibUtilities::eFunctionTypeExpression)
{
AddSummaryItem(s, "Diffusivity-x",
m_session->GetFunction("d00", "intensity")->GetExpression());
}
if (m_session->DefinesFunction("d11") &&
m_session->GetFunctionType("d11", "intensity")
== LibUtilities::eFunctionTypeExpression)
{
AddSummaryItem(s, "Diffusivity-y",
m_session->GetFunction("d11", "intensity")->GetExpression());
}
if (m_session->DefinesFunction("d22") &&
m_session->GetFunctionType("d22", "intensity")
== LibUtilities::eFunctionTypeExpression)
{
AddSummaryItem(s, "Diffusivity-z",
m_session->GetFunction("d22", "intensity")->GetExpression());
}
m_cell->GenerateSummary(s);
}
}
<|endoftext|>
|
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* MPIAggregator.cpp
*
* Created on: Feb 20, 2018
* Author: William F Godoy [email protected]
*/
#include "MPIAggregator.h"
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace aggregator
{
MPIAggregator::MPIAggregator() {}
MPIAggregator::~MPIAggregator()
{
if (m_IsActive)
{
m_Comm.Free("freeing aggregators comm in MPIAggregator "
"destructor, not recommended");
}
}
void MPIAggregator::Init(const size_t subStreams,
helper::Comm const &parentComm)
{
}
void MPIAggregator::SwapBuffers(const int step) noexcept {}
void MPIAggregator::ResetBuffers() noexcept {}
format::Buffer &MPIAggregator::GetConsumerBuffer(format::Buffer &buffer)
{
return buffer;
}
void MPIAggregator::Close()
{
if (m_IsActive)
{
m_Comm.Free("freeing aggregators comm at Close\n");
m_IsActive = false;
}
}
// PROTECTED
void MPIAggregator::InitComm(const size_t subStreams,
helper::Comm const &parentComm)
{
int parentRank = parentComm.Rank();
int parentSize = parentComm.Size();
const size_t process = static_cast<size_t>(parentRank);
const size_t processes = static_cast<size_t>(parentSize);
// Divide the processes into S=subStreams groups.
const size_t q = processes / subStreams;
const size_t r = processes % subStreams;
// Groups [0,r) have size q+1. Groups [r,S) have size q.
const size_t firstInSmallGroups = r * (q + 1);
// Within each group the first process becomes its consumer.
if (process >= firstInSmallGroups)
{
m_SubStreamIndex = r + (process - firstInSmallGroups) / q;
m_ConsumerRank = static_cast<int>(firstInSmallGroups +
(m_SubStreamIndex - r) * q);
}
else
{
m_SubStreamIndex = process / (q + 1);
m_ConsumerRank = static_cast<int>(m_SubStreamIndex * (q + 1));
}
m_Comm = parentComm.Split(m_ConsumerRank, parentRank,
"creating aggregators comm with split at Open");
m_Rank = m_Comm.Rank();
m_Size = m_Comm.Size();
if (m_Rank != 0)
{
m_IsConsumer = false;
}
m_IsActive = true;
m_SubStreams = subStreams;
}
void MPIAggregator::HandshakeRank(const int rank)
{
int message = -1;
if (m_Rank == rank)
{
message = m_Rank;
}
m_Comm.Bcast(&message, 1, rank, "handshake with aggregator rank 0 at Open");
}
} // end namespace aggregator
} // end namespace adios2
<commit_msg>clang-format<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* MPIAggregator.cpp
*
* Created on: Feb 20, 2018
* Author: William F Godoy [email protected]
*/
#include "MPIAggregator.h"
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace aggregator
{
MPIAggregator::MPIAggregator() {}
MPIAggregator::~MPIAggregator()
{
if (m_IsActive)
{
m_Comm.Free("freeing aggregators comm in MPIAggregator "
"destructor, not recommended");
}
}
void MPIAggregator::Init(const size_t subStreams,
helper::Comm const &parentComm)
{
}
void MPIAggregator::SwapBuffers(const int step) noexcept {}
void MPIAggregator::ResetBuffers() noexcept {}
format::Buffer &MPIAggregator::GetConsumerBuffer(format::Buffer &buffer)
{
return buffer;
}
void MPIAggregator::Close()
{
if (m_IsActive)
{
m_Comm.Free("freeing aggregators comm at Close\n");
m_IsActive = false;
}
}
// PROTECTED
void MPIAggregator::InitComm(const size_t subStreams,
helper::Comm const &parentComm)
{
int parentRank = parentComm.Rank();
int parentSize = parentComm.Size();
const size_t process = static_cast<size_t>(parentRank);
const size_t processes = static_cast<size_t>(parentSize);
// Divide the processes into S=subStreams groups.
const size_t q = processes / subStreams;
const size_t r = processes % subStreams;
// Groups [0,r) have size q+1. Groups [r,S) have size q.
const size_t firstInSmallGroups = r * (q + 1);
// Within each group the first process becomes its consumer.
if (process >= firstInSmallGroups)
{
m_SubStreamIndex = r + (process - firstInSmallGroups) / q;
m_ConsumerRank =
static_cast<int>(firstInSmallGroups + (m_SubStreamIndex - r) * q);
}
else
{
m_SubStreamIndex = process / (q + 1);
m_ConsumerRank = static_cast<int>(m_SubStreamIndex * (q + 1));
}
m_Comm = parentComm.Split(m_ConsumerRank, parentRank,
"creating aggregators comm with split at Open");
m_Rank = m_Comm.Rank();
m_Size = m_Comm.Size();
if (m_Rank != 0)
{
m_IsConsumer = false;
}
m_IsActive = true;
m_SubStreams = subStreams;
}
void MPIAggregator::HandshakeRank(const int rank)
{
int message = -1;
if (m_Rank == rank)
{
message = m_Rank;
}
m_Comm.Bcast(&message, 1, rank, "handshake with aggregator rank 0 at Open");
}
} // end namespace aggregator
} // end namespace adios2
<|endoftext|>
|
<commit_before>#include <QFile>
#include <QString>
#include <QStack>
#include <core/logger/Logging.h>
#include "AdvancedTemplateProcessor.h"
namespace Quartz {
const QString ADV_TOKEN_FIRST = QString{ "$" };
const QString ADV_TOKEN_SEC = QString{ "[" };
const QString ADV_FOREACH_DELEM = QString{ ":>" };
const QString ADV_FOREACH_KW = QString{ "FOREACH" };
const QString ADV_FOR_KW = QString{ "FOREACH" };
const QString ADV_IF_KW = QString{ "IF" };
const QString ADV_FOR_IN_KW = QString{ "IN" };
struct AdvancedTemplateProcessor::Data
{
explicit Data()
{
}
};
AdvancedTemplateProcessor::AdvancedTemplateProcessor(
const TemplateProcessor::Variables &vars )
: TemplateProcessor{ vars }
, m_data{ new Data{}}
{
}
AdvancedTemplateProcessor::~AdvancedTemplateProcessor()
{
}
bool AdvancedTemplateProcessor::process( QString &input,
QTextStream &output )
{
bool result = false;
if( ! input.isEmpty() ) {
auto blockExpanded = processBlocks( QStringRef{ &input });
result = TemplateProcessor::process( blockExpanded, output );
}
else {
QZ_ERROR( "Qz:Cmn:Tmpl" ) << "Invalid template text given";
}
return result;
}
QString AdvancedTemplateProcessor::processBlocks( const QStringRef &input ) {
auto cursor = 0;
auto matchCount = 0;
auto inMatch = false;
auto blockStart = -1;
QString result;
QTextStream stream{ &result };
while( cursor < input.size() ) {
auto token = input[ cursor ];
if( matchCount == 0 && token == ADV_TOKEN_FIRST ) {
++ matchCount;
}
else if( matchCount == 1 && token == ADV_TOKEN_SEC ) {
++ matchCount;
blockStart = cursor + 1;
if( inMatch ) {
auto block = processBlocks( input.right( cursor ));
stream << block;
}
}
else {
if( matchCount == 1 ) {
//because I ate the first token in the first if
stream << ADV_TOKEN_FIRST;
matchCount = 0;
}
stream << token;
}
if( inMatch ) {
matchCount = 0;
auto unmatchCount = 0;
++ cursor;
while( inMatch && cursor < input.size() ) {
token = input[ cursor ];
if( unmatchCount == 0 && token == ADV_TOKEN_SEC ) {
++ unmatchCount;
}
else if( unmatchCount == 1 && token == ADV_TOKEN_FIRST ) {
auto block = input.mid( blockStart, cursor - 2 );
if( block.startsWith( ADV_FOREACH_KW )) {
result = processForeach( *block.string() );
}
else if( block.startsWith( ADV_IF_KW )) {
result = processIf( *block.string() );
}
else if( block.startsWith( ADV_FOR_KW )) {
result = processFor( *block.string() );
}
inMatch = false;
++ cursor;
-- unmatchCount;
break;
}
++ cursor;
}
}
else {
++ cursor;
}
}
return result;
}
QString AdvancedTemplateProcessor::processForeach( const QString &input )
{
//To support loop like:
//$[forach val in list :>
// cout << val;
//]$
auto segments = input.split( ADV_FOREACH_DELEM );
if( segments.size() != 2 ) {
QZ_ERROR( "Qz:Cmn:Tmpl" ) << "Malformed foreach loop found";
return input;
}
auto validate = []( const QStringList &tokens ) -> bool {
return tokens.size() == 4
&& tokens.at( 0 ) == ADV_FOREACH_KW
&& tokens.at( 2 ) == ADV_FOR_IN_KW;
};
auto forTokens = segments.at( 0 ).split( QRegExp("\\s+"),
QString::SkipEmptyParts );
if( validate( forTokens )) {
QString varValue{};
auto varName = forTokens.at( 1 );
auto list = var( forTokens.at( 3 )).toStringList();
auto provider = [ & ]( const QString &key,
const QString &def ) -> QString {
if( key == varName ) {
return varValue;
}
auto var = this->var( key );
if( ! var.isValid() ) {
return this->toString( var );
}
return def;
};
QString block;
QTextStream stream{ &block };
foreach( const QString &item, list ) {
varValue = item;
TemplateProcessor::process( input, stream, provider );
}
return block;
}
else {
//print errore
}
return input;
}
QString AdvancedTemplateProcessor::processFor( const QString &/*input*/ )
{
//To support loops like:
//$[for i in range(1, 100)]$
//Not implemented yet
return QString{};
}
QString AdvancedTemplateProcessor::processIf( const QString &/*input*/ )
{
//TO support conditions like
//$[if var == "0"]$
return QString{}; //not supported yet
}
}
<commit_msg>[WIP] Better parsing logic for for loops<commit_after>#include <QFile>
#include <QString>
#include <QStack>
#include <core/logger/Logging.h>
#include "AdvancedTemplateProcessor.h"
namespace Quartz {
const QString ADV_TOKEN_FIRST = QString{ "$" };
const QString ADV_TOKEN_SEC = QString{ "[" };
const QString ADV_FOREACH_DELEM = QString{ ":>" };
const QString ADV_FOREACH_KW = QString{ "FOREACH" };
const QString ADV_FOR_KW = QString{ "FOREACH" };
const QString ADV_IF_KW = QString{ "IF" };
const QString ADV_FOR_IN_KW = QString{ "IN" };
struct AdvancedTemplateProcessor::Data
{
explicit Data()
{
}
};
AdvancedTemplateProcessor::AdvancedTemplateProcessor(
const TemplateProcessor::Variables &vars )
: TemplateProcessor{ vars }
, m_data{ new Data{}}
{
}
AdvancedTemplateProcessor::~AdvancedTemplateProcessor()
{
}
bool AdvancedTemplateProcessor::process( QString &input,
QTextStream &output )
{
bool result = false;
if( ! input.isEmpty() ) {
auto blockExpanded = processBlocks( QStringRef{ &input });
result = TemplateProcessor::process( blockExpanded, output );
}
else {
QZ_ERROR( "Qz:Cmn:Tmpl" ) << "Invalid template text given";
}
return result;
}
QString AdvancedTemplateProcessor::processBlocks( const QStringRef &input ) {
auto cursor = 0;
auto matchCount = 0;
auto inMatch = false;
auto blockStart = -1;
QString result;
QTextStream stream{ &result };
while( cursor < input.size() ) {
auto token = input[ cursor ];
if( matchCount == 0 && token == ADV_TOKEN_FIRST ) {
++ matchCount;
}
else if( matchCount == 1 && token == ADV_TOKEN_SEC ) {
++ matchCount;
blockStart = cursor + 1;
if( inMatch ) {
auto block = processBlocks( input.right( cursor ));
stream << block;
}
}
else {
if( matchCount == 1 ) {
//because I ate the first token in the first if
stream << ADV_TOKEN_FIRST;
matchCount = 0;
}
stream << token;
}
if( inMatch ) {
matchCount = 0;
auto unmatchCount = 0;
++ cursor;
while( inMatch && cursor < input.size() ) {
token = input[ cursor ];
if( unmatchCount == 0 && token == ADV_TOKEN_SEC ) {
++ unmatchCount;
}
else if( unmatchCount == 1 && token == ADV_TOKEN_FIRST ) {
auto block = input.mid( blockStart, cursor - 2 );
if( block.startsWith( ADV_FOREACH_KW )) {
result = processForeach( *block.string() );
}
else if( block.startsWith( ADV_IF_KW )) {
result = processIf( *block.string() );
}
else if( block.startsWith( ADV_FOR_KW )) {
result = processFor( *block.string() );
}
inMatch = false;
++ cursor;
-- unmatchCount;
break;
}
++ cursor;
}
}
else {
++ cursor;
}
}
return result;
}
QString AdvancedTemplateProcessor::processForeach( const QString &input )
{
//To support loop like:
//$[forach val in list :>
// cout << val;
//]$
auto segments = input.split( ADV_FOREACH_DELEM );
if( segments.size() != 2 ) {
QZ_ERROR( "Qz:Cmn:Tmpl" ) << "Malformed foreach loop found";
return input;
}
auto validate = []( const QStringList &tokens ) -> bool {
return tokens.size() == 4
&& tokens.at( 0 ) == ADV_FOREACH_KW
&& tokens.at( 2 ) == ADV_FOR_IN_KW;
};
auto forTokens = segments.at( 0 ).split( QRegExp("\\s+"),
QString::SkipEmptyParts );
if( validate( forTokens )) {
QString varValue{};
auto varName = forTokens.at( 1 );
auto list = var( forTokens.at( 3 )).toStringList();
auto provider = [ & ]( const QString &key,
const QString &def ) -> QString {
if( key == varName ) {
return varValue;
}
auto var = this->var( key );
if( ! var.isValid() ) {
return this->toString( var );
}
return def;
};
QString block;
QTextStream stream{ &block };
foreach( const QString &item, list ) {
varValue = item;
TemplateProcessor::process( input, stream, provider );
}
return block;
}
else {
//print errore
}
return input;
}
bool isWhiteSpace( const QChar &ch )
{
return ch == ' '
|| ch == '\t'
|| ch == '\n'
|| ch == '\r';
}
QString AdvancedTemplateProcessor::processFor( const QString &input )
{
//To support loops like:
//$[for i in range(1, 100)]$
//Not implemented yet
auto cursor = 0;
auto is = [ & ]( const QString &token ) -> bool {
bool result = true;
auto dupCursor = cursor;
for( auto i = 0; i < token.size(); ++ i, ++ dupCursor ) {
if( dupCursor >= input.size()
|| input[ dupCursor ] != token[ i ]) {
result = false;
break;
}
}
if( result ) {
cursor = cursor + token.size();
}
return result;
};
auto tokenStart = 0;
auto tokenNumber = 0;
QString content;
QString varName;
QString listName;
while( cursor <= input.size() ) {
if( isWhiteSpace( input[ cursor ]) || cursor == input.size() ) {
auto num = cursor - tokenStart - 1;
if( num != 0 ) {
auto token = input.mid( tokenStart, num );
++ cursor;
if( tokenNumber == 0 && token == ADV_FOREACH_KW ) {
//expected
continue;
}
else if( tokenNumber == 2 && token == ADV_FOR_IN_KW ) {
//expected
continue;
}
else if( tokenNumber == 1 ) {
varName = token;
}
else if( tokenNumber == 3 ) {
//range or list
}
}
}
else {
tokenStart = cursor;
}
}
return QString{};
}
QString AdvancedTemplateProcessor::processIf( const QString &/*input*/ )
{
//TO support conditions like
//$[if var == "0"]$
return QString{}; //not supported yet
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <iostream>
#include <boost/thread/tss.hpp>
#include <libport/cassert>
#include <libport/containers.hh>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <libport/fnmatch.h>
#include <libport/foreach.hh>
#include <libport/format.hh>
#include <libport/ip-semaphore.hh>
#include <libport/lockable.hh>
#include <libport/pthread.h>
#include <libport/thread-data.hh>
#include <libport/tokenizer.hh>
#include <libport/unistd.h>
#include <libport/utime.hh>
#include <libport/windows.hh>
#include <sched/coroutine-data.hh>
#ifndef WIN32
# include <syslog.h>
#endif
#ifndef LIBPORT_DEBUG_DISABLE
GD_CATEGORY(Libport.Debug);
namespace libport
{
LIBPORT_API boost::function0<local_data&> debugger_data;
LIBPORT_API Debug* debugger = 0;
LIBPORT_API Debug::levels::Level Debug::filter_(levels::log);
local_data&
debugger_data_thread_local()
{
static boost::thread_specific_ptr<local_data> storage;
if (!storage.get())
storage.reset(new local_data);
return *storage;
}
local_data::local_data()
: indent(0)
{}
namespace debug
{
// Wether categories are enabled by default.
static bool default_category_state = true;
LIBPORT_API void
uninitialized_msg(const std::string& msg)
{
static bool dump =
getenv("GD_LEVEL") && libport::streq(getenv("GD_LEVEL"), "DUMP");
if (dump)
{
static bool tail = false;
if (!tail++)
std::cerr << "[Libport.Debug] "
<< "Uninitialized debug, fallback to stderr." << std::endl;
std::cerr << "[Libport.Debug] " << msg;
if (msg.empty() || msg[msg.size() - 1] != '\n')
std::cerr << std::endl;
}
}
// Categories added so far.
categories_type&
categories()
{
static categories_type categories;
return categories;
}
static unsigned
current_pattern()
{
static unsigned current = 0;
return current++;
}
// Patterns added so far.
patterns_type&
patterns()
{
static patterns_type patterns;
return patterns;
}
// Maximum category width.
size_t&
categories_largest()
{
static size_t res = 0;
return res;
}
// Add a new category, look if it matches a pattern.
Symbol
add_category(Symbol name)
{
int order = -1;
bool value = default_category_state;
foreach (patterns_type::value_type& s, patterns())
{
if (fnmatch(s.first.name_get(), name.name_get()) == 0)
{
if (int(s.second.second) > order)
{
value = s.second.first;
order = s.second.second;
}
}
}
categories()[name] = value;
size_t size = name.name_get().size();
if (categories_largest() < size)
categories_largest() = size;
return name;
}
// Add a new category pattern.
int
enable_category(Symbol pattern, bool enabled)
{
patterns()[pattern] = std::make_pair(true, current_pattern());
foreach (categories_type::value_type& s, categories())
{
if (fnmatch(pattern.name_get(), s.first.name_get()) == 0)
s.second = enabled;
}
return 42;
}
// Disable a new category pattern.
int
disable_category(Symbol pattern)
{
return enable_category(pattern, false);
}
// Enable/Disable a new category pattern with modifier.
int
auto_category(Symbol pattern)
{
std::string p = pattern.name_get();
char modifier = p[0];
if (modifier == '+' || modifier == '-')
p = p.substr(1);
else
modifier = '+';
return enable_category(Symbol(p), modifier == '+');
}
bool test_category(Symbol name)
{
return categories()[name];
}
typedef enum
{
ENABLE,
DISABLE,
AUTO,
} category_modifier_type;
static void set_category_state(const char* list,
const category_modifier_type state)
{
// If the mode is "AUTO", then if the first specs is to enable
// ("+...") then the default is to disable, otherwise enable.
// If the mode if not AUTO, then the default is the converse of
// the mode: ENABLE -> false, and DISABLE => true.
debug::default_category_state =
state == AUTO ? (*list == '-') : (state != ENABLE);
// Also set existing to default_category_state.
foreach (categories_type::value_type& v, categories())
v.second = debug::default_category_state;
std::string s(list); // Do not pass temporary to make_tokenizer.
tokenizer_type t = make_tokenizer(s, ",");
foreach (const std::string& elem, t)
{
Symbol pattern(elem);
switch (state)
{
case ENABLE:
case DISABLE:
enable_category(pattern, state == ENABLE);
break;
case AUTO:
auto_category(pattern);
break;
}
}
}
}
Debug::Debug()
: locations_(getenv("GD_LOC"))
, timestamps_(getenv("GD_TIME") || getenv("GD_TIMESTAMP_US"))
{
// Process enabled/disabled/auto categories in environment.
if (const char* cp = getenv("GD_CATEGORY"))
debug::set_category_state(cp, debug::AUTO);
else
{
if (const char* cp = getenv("GD_ENABLE_CATEGORY"))
debug::set_category_state(cp, debug::ENABLE);
if (const char* cp = getenv("GD_DISABLE_CATEGORY"))
debug::set_category_state(cp, debug::DISABLE);
}
if (const char* lvl_c = getenv("GD_LEVEL"))
filter(lvl_c);
}
Debug::~Debug()
{}
void
Debug::filter(levels::Level lvl)
{
filter_ = lvl;
}
void
Debug::filter(const std::string& lvl)
{
if (lvl == "NONE" || lvl == "0")
filter(Debug::levels::none);
else if (lvl == "LOG" || lvl == "1")
filter(Debug::levels::log);
else if (lvl == "TRACE" || lvl == "2")
filter(Debug::levels::trace);
else if (lvl == "DEBUG" || lvl == "3")
filter(Debug::levels::debug);
else if (lvl == "DUMP" || lvl == "4")
filter(Debug::levels::dump);
else
// Don't use GD_ABORT here, we can be in the debugger constructor!
pabort("invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])");
}
unsigned
Debug::indentation() const
{
return debugger_data().indent;
}
Debug::levels::Level
Debug::level()
{
return filter_;
}
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static IPSemaphore& sem()
{
static IPSemaphore res(1);
return res;
}
# endif
void
Debug::debug(const std::string& msg,
types::Type type,
debug::category_type category,
const std::string& fun,
const std::string& file,
unsigned line)
{
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static bool useLock = getenv("GD_USE_LOCK") || getenv("GD_PID");
libport::Finally f;
if (useLock)
{
--sem();
f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));
}
# endif
message(category, msg, type, fun, file, line);
}
Debug*
Debug::push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
message_push(category, msg, fun, file, line);
return this;
}
std::string
Debug::category_format(debug::category_type cat) const
{
std::string res = cat;
size_t size = res.size();
size_t largest = debug::categories_largest();
if (size < largest)
{
size_t diff = largest - size;
res = std::string(diff / 2, ' ')
+ res
+ std::string(diff / 2 + diff % 2, ' ');
}
return res;
}
namespace opts
{
void cb_debug_fun(const std::string& lvl)
{
GD_DEBUGGER->filter(lvl);
}
OptionValued::callback_type cb_debug(cb_debug_fun);
OptionValue
debug("set the debug level in NONE, LOG (default), TRACE, DEBUG, DUMP",
"debug", 'd', "LEVEL", cb_debug);
}
ConsoleDebug::ConsoleDebug()
{}
namespace
{
inline
std::string
time()
{
static bool us = getenv("GD_TIMESTAMP_US");
if (us)
return string_cast(utime());
time_t now = std::time(0);
struct tm* ts = std::localtime(&now);
char buf[80];
strftime(buf, sizeof buf, "%a %Y-%m-%d %H:%M:%S %Z", ts);
return buf;
}
inline
std::string
color(int color, bool bold = true)
{
static bool tty = isatty(STDERR_FILENO);
static bool force = getenv("GD_COLOR");
static bool force_disable = getenv("GD_NO_COLOR");
return (((tty || force) && !force_disable)
? format("[33;0%s;%sm", bold ? 1 : 0, color)
: "");
}
}
static Debug::colors::Color
msg_color(Debug::types::Type type)
{
switch (type)
{
case Debug::types::info:
return Debug::colors::white;
case Debug::types::warn:
return Debug::colors::yellow;
case Debug::types::error:
return Debug::colors::red;
};
GD_UNREACHABLE();
}
void
ConsoleDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::ostringstream ostr;
Debug::colors::Color c = msg_color(type);
if (timestamps())
ostr << color(c) << time() << " ";
ostr << color(colors::purple)
<< "[" << category_format(category) << "] ";
{
static bool pid = getenv("GD_PID");
if (pid)
ostr << "[" << getpid() << "] ";
}
#ifndef WIN32
{
static bool thread = getenv("GD_THREAD");
if (thread)
ostr << "[" << pthread_self() << "] ";
}
#endif
ostr << color(c);
for (unsigned i = 0; i < debugger_data().indent; ++i)
ostr << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
ostr.write(msg.c_str(), msg.size() - 1);
else
ostr << msg;
if (locations())
ostr << color(colors::blue)
<< " (" << fun << ", " << file << ":" << line << ")";
ostr << color(colors::white);
std::cerr << ostr.str() << std::endl;
}
void
ConsoleDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
ConsoleDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
std::string gd_ihexdump(const unsigned char* data, unsigned size)
{
std::string res =
format("\"%s\"",
libport::escape(std::string((const char*)data, (size_t)(size))));
bool first = true;
for (unsigned i = 0; i < size; ++i)
{
if (first)
first = false;
else
res += " ";
// Cast to int, or boost::format will print the character.
res += format("0x%x", static_cast<unsigned int>(data[i]));
}
return res;
}
#ifndef WIN32
/*-------------.
| Syslog debug |
`-------------*/
SyslogDebug::SyslogDebug(const std::string& program)
{
openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);
syslog(LOG_INFO | LOG_DAEMON, "%s",
format("Opening syslog session for '%s'", program).c_str());
}
SyslogDebug::~SyslogDebug()
{
syslog(LOG_INFO | LOG_DAEMON, "Closing syslog session.");
closelog();
}
static
int type_to_prio(Debug::types::Type t)
{
switch (t)
{
#define CASE(In, Out) \
case Debug::types::In: return Out; break
CASE(info, LOG_INFO);
CASE(warn, LOG_WARNING);
CASE(error, LOG_ERR);
#undef CASE
}
// Pacify Gcc.
libport::abort();
}
void
SyslogDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::stringstream s;
s << "[" << category_format(category) << "] ";
for (unsigned i = 0; i < debugger_data().indent; ++i)
s << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
s.write(msg.c_str(), msg.size() - 1);
else
s << msg;
if (locations())
s << " (" << fun << ", " << file << ":" << line << ")";
int prio = type_to_prio(type) | LOG_DAEMON;
syslog(prio, "%s", s.str().c_str());
}
void
SyslogDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
SyslogDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
#endif
boost::function0<Debug*> make_debugger;
namespace debug
{
void clear()
{
#if FIXME
delete debugger();
#endif
}
}
}
#endif
<commit_msg>Fix GD_CATEGORY behavior.<commit_after>/*
* Copyright (C) 2008-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <iostream>
#include <boost/thread/tss.hpp>
#include <libport/cassert>
#include <libport/compiler.hh>
#include <libport/containers.hh>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <libport/fnmatch.h>
#include <libport/foreach.hh>
#include <libport/format.hh>
#include <libport/ip-semaphore.hh>
#include <libport/lockable.hh>
#include <libport/pthread.h>
#include <libport/thread-data.hh>
#include <libport/tokenizer.hh>
#include <libport/unistd.h>
#include <libport/utime.hh>
#include <libport/windows.hh>
#include <sched/coroutine-data.hh>
#ifndef WIN32
# include <syslog.h>
#endif
#ifndef LIBPORT_DEBUG_DISABLE
GD_CATEGORY(Libport.Debug);
namespace libport
{
LIBPORT_API boost::function0<local_data&> debugger_data;
LIBPORT_API Debug* debugger = 0;
LIBPORT_API Debug::levels::Level Debug::filter_(levels::log);
local_data&
debugger_data_thread_local()
{
static boost::thread_specific_ptr<local_data> storage;
if (!storage.get())
storage.reset(new local_data);
return *storage;
}
local_data::local_data()
: indent(0)
{}
namespace debug
{
// Whether categories are enabled by default.
static bool default_category_state = true;
LIBPORT_API void
uninitialized_msg(const std::string& msg)
{
static bool dump =
getenv("GD_LEVEL") && libport::streq(getenv("GD_LEVEL"), "DUMP");
if (dump)
{
static bool tail = false;
if (!tail++)
std::cerr << "[Libport.Debug] "
<< "Uninitialized debug, fallback to stderr." << std::endl;
std::cerr << "[Libport.Debug] " << msg;
if (msg.empty() || msg[msg.size() - 1] != '\n')
std::cerr << std::endl;
}
}
// Categories added so far.
ATTRIBUTE_PURE
categories_type&
categories()
{
static categories_type categories;
return categories;
}
namespace
{
ATTRIBUTE_PURE
static unsigned
current_pattern()
{
static unsigned current = 0;
return current++;
}
// Patterns added so far.
ATTRIBUTE_PURE
patterns_type&
patterns()
{
static patterns_type patterns;
return patterns;
}
// Maximum category width.
ATTRIBUTE_PURE
size_t&
categories_largest()
{
static size_t res = 0;
return res;
}
inline
bool
match(Symbol globbing, Symbol string)
{
return fnmatch(globbing.name_get(), string.name_get()) == 0;
}
}
/// Add a new category, look if it matches a pattern.
Symbol
add_category(Symbol name)
{
int order = -1;
bool value = default_category_state;
foreach (patterns_type::value_type& s, patterns())
if (match(s.first, name)
&& order < int(s.second.second))
{
value = s.second.first;
order = s.second.second;
}
categories()[name] = value;
categories_largest() =
std::max(categories_largest(), name.name_get().size());
return name;
}
/// Add a new category pattern.
int
enable_category(Symbol pattern, bool enabled)
{
patterns()[pattern] = std::make_pair(enabled, current_pattern());
foreach (categories_type::value_type& s, categories())
if (match(pattern, s.first))
s.second = enabled;
return 42;
}
// Disable a new category pattern.
int
disable_category(Symbol pattern)
{
return enable_category(pattern, false);
}
// Enable/Disable a new category pattern with modifier.
int
auto_category(Symbol pattern)
{
std::string p = pattern.name_get();
char modifier = p[0];
if (modifier == '+' || modifier == '-')
p = p.substr(1);
else
modifier = '+';
return enable_category(Symbol(p), modifier == '+');
}
bool test_category(Symbol name)
{
return categories()[name];
}
typedef enum
{
ENABLE,
DISABLE,
AUTO,
} category_modifier_type;
/// Enable/disable categories, already seen or future.
///
/// Called by GD_INIT.
///
/// \param list the value of the environment var (GD_CATEGORY, etc.).
/// \param state the associated state (AUTO, ENABLE, DISABLE).
static
void
set_category_state(const char* list, const category_modifier_type state)
{
// If the mode is "AUTO", then if the first specs is to enable
// ("-...") then the default is to enable, otherwise disable.
// If the mode if not AUTO, then the default is the converse of
// the mode: ENABLE -> false, and DISABLE => true.
default_category_state =
state == AUTO ? (*list == '-') : (state != ENABLE);
// Set all the existing categories to the default behavior
// before running the per-pattern tests.
foreach (categories_type::value_type& v, categories())
v.second = default_category_state;
std::string s(list); // Do not pass temporary to make_tokenizer.
tokenizer_type t = make_tokenizer(s, ",");
foreach (const std::string& elem, t)
{
Symbol pattern(elem);
switch (state)
{
case ENABLE:
case DISABLE:
enable_category(pattern, state == ENABLE);
break;
case AUTO:
auto_category(pattern);
break;
}
}
}
}
Debug::Debug()
: locations_(getenv("GD_LOC"))
, timestamps_(getenv("GD_TIME") || getenv("GD_TIMESTAMP_US"))
{
// Process enabled/disabled/auto categories in environment.
if (const char* cp = getenv("GD_CATEGORY"))
debug::set_category_state(cp, debug::AUTO);
else
{
if (const char* cp = getenv("GD_ENABLE_CATEGORY"))
debug::set_category_state(cp, debug::ENABLE);
if (const char* cp = getenv("GD_DISABLE_CATEGORY"))
debug::set_category_state(cp, debug::DISABLE);
}
if (const char* lvl_c = getenv("GD_LEVEL"))
filter(lvl_c);
}
Debug::~Debug()
{}
void
Debug::filter(levels::Level lvl)
{
filter_ = lvl;
}
void
Debug::filter(const std::string& lvl)
{
if (lvl == "NONE" || lvl == "0")
filter(Debug::levels::none);
else if (lvl == "LOG" || lvl == "1")
filter(Debug::levels::log);
else if (lvl == "TRACE" || lvl == "2")
filter(Debug::levels::trace);
else if (lvl == "DEBUG" || lvl == "3")
filter(Debug::levels::debug);
else if (lvl == "DUMP" || lvl == "4")
filter(Debug::levels::dump);
else
// Don't use GD_ABORT here, we can be in the debugger constructor!
pabort("invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])");
}
unsigned
Debug::indentation() const
{
return debugger_data().indent;
}
Debug::levels::Level
Debug::level()
{
return filter_;
}
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static IPSemaphore& sem()
{
static IPSemaphore res(1);
return res;
}
# endif
void
Debug::debug(const std::string& msg,
types::Type type,
debug::category_type category,
const std::string& fun,
const std::string& file,
unsigned line)
{
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static bool useLock = getenv("GD_USE_LOCK") || getenv("GD_PID");
libport::Finally f;
if (useLock)
{
--sem();
f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));
}
# endif
message(category, msg, type, fun, file, line);
}
Debug*
Debug::push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
message_push(category, msg, fun, file, line);
return this;
}
std::string
Debug::category_format(debug::category_type cat) const
{
std::string res = cat;
size_t size = res.size();
size_t largest = debug::categories_largest();
if (size < largest)
{
size_t diff = largest - size;
res = std::string(diff / 2, ' ')
+ res
+ std::string(diff / 2 + diff % 2, ' ');
}
return res;
}
namespace opts
{
void cb_debug_fun(const std::string& lvl)
{
GD_DEBUGGER->filter(lvl);
}
OptionValued::callback_type cb_debug(cb_debug_fun);
OptionValue
debug("set the debug level in NONE, LOG (default), TRACE, DEBUG, DUMP",
"debug", 'd', "LEVEL", cb_debug);
}
ConsoleDebug::ConsoleDebug()
{}
namespace
{
inline
std::string
time()
{
static bool us = getenv("GD_TIMESTAMP_US");
if (us)
return string_cast(utime());
time_t now = std::time(0);
struct tm* ts = std::localtime(&now);
char buf[80];
strftime(buf, sizeof buf, "%a %Y-%m-%d %H:%M:%S %Z", ts);
return buf;
}
inline
std::string
color(int color, bool bold = true)
{
static bool tty = isatty(STDERR_FILENO);
static bool force = getenv("GD_COLOR");
static bool force_disable = getenv("GD_NO_COLOR");
return (((tty || force) && !force_disable)
? format("[33;0%s;%sm", bold ? 1 : 0, color)
: "");
}
}
static Debug::colors::Color
msg_color(Debug::types::Type type)
{
switch (type)
{
case Debug::types::info:
return Debug::colors::white;
case Debug::types::warn:
return Debug::colors::yellow;
case Debug::types::error:
return Debug::colors::red;
};
GD_UNREACHABLE();
}
void
ConsoleDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::ostringstream ostr;
Debug::colors::Color c = msg_color(type);
if (timestamps())
ostr << color(c) << time() << " ";
ostr << color(colors::purple)
<< "[" << category_format(category) << "] ";
{
static bool pid = getenv("GD_PID");
if (pid)
ostr << "[" << getpid() << "] ";
}
#ifndef WIN32
{
static bool thread = getenv("GD_THREAD");
if (thread)
ostr << "[" << pthread_self() << "] ";
}
#endif
ostr << color(c);
for (unsigned i = 0; i < debugger_data().indent; ++i)
ostr << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
ostr.write(msg.c_str(), msg.size() - 1);
else
ostr << msg;
if (locations())
ostr << color(colors::blue)
<< " (" << fun << ", " << file << ":" << line << ")";
ostr << color(colors::white);
std::cerr << ostr.str() << std::endl;
}
void
ConsoleDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
ConsoleDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
std::string gd_ihexdump(const unsigned char* data, unsigned size)
{
std::string res =
format("\"%s\"",
libport::escape(std::string((const char*)data, (size_t)(size))));
bool first = true;
for (unsigned i = 0; i < size; ++i)
{
if (first)
first = false;
else
res += " ";
// Cast to int, or boost::format will print the character.
res += format("0x%x", static_cast<unsigned int>(data[i]));
}
return res;
}
#ifndef WIN32
/*-------------.
| Syslog debug |
`-------------*/
SyslogDebug::SyslogDebug(const std::string& program)
{
openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);
syslog(LOG_INFO | LOG_DAEMON, "%s",
format("Opening syslog session for '%s'", program).c_str());
}
SyslogDebug::~SyslogDebug()
{
syslog(LOG_INFO | LOG_DAEMON, "Closing syslog session.");
closelog();
}
static
int type_to_prio(Debug::types::Type t)
{
switch (t)
{
#define CASE(In, Out) \
case Debug::types::In: return Out; break
CASE(info, LOG_INFO);
CASE(warn, LOG_WARNING);
CASE(error, LOG_ERR);
#undef CASE
}
// Pacify Gcc.
libport::abort();
}
void
SyslogDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::stringstream s;
s << "[" << category_format(category) << "] ";
for (unsigned i = 0; i < debugger_data().indent; ++i)
s << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
s.write(msg.c_str(), msg.size() - 1);
else
s << msg;
if (locations())
s << " (" << fun << ", " << file << ":" << line << ")";
int prio = type_to_prio(type) | LOG_DAEMON;
syslog(prio, "%s", s.str().c_str());
}
void
SyslogDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
GD_INDENTATION_INC();
}
void
SyslogDebug::pop()
{
assert_gt(debugger_data().indent, 0u);
GD_INDENTATION_DEC();
}
#endif
boost::function0<Debug*> make_debugger;
namespace debug
{
void clear()
{
#if FIXME
delete debugger();
#endif
}
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <iostream>
#include <libport/cassert>
#include <libport/containers.hh>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <libport/foreach.hh>
#include <libport/format.hh>
#include <libport/ip-semaphore.hh>
#include <libport/lockable.hh>
#include <libport/pthread.h>
#include <libport/windows.hh>
#include <libport/unistd.h>
#ifndef WIN32
# include <syslog.h>
#endif
#ifndef LIBPORT_DEBUG_DISABLE
GD_CATEGORY(libport::Debug);
namespace libport
{
namespace debug
{
categories_type& get_categories()
{
static categories_type categories;
return categories;
}
size_t&
categories_largest()
{
static size_t res = 0;
return res;
}
Symbol
add_category(Symbol name)
{
get_categories()[name] = true;
size_t size = name.name_get().size();
if (categories_largest() < size)
categories_largest() = size;
return name;
}
int enable_category(Symbol name)
{
get_categories()[name] = true;
return 42;
}
int disable_category(Symbol name)
{
get_categories()[name] = false;
return 42;
}
bool test_category(Symbol name)
{
return get_categories()[name];
}
}
Debug::Debug()
: locations_(getenv("GD_LOC"))
, timestamps_(getenv("GD_TIME"))
, filter_(levels::log)
{
if (const char* lvl_c = getenv("GD_LEVEL"))
filter(lvl_c);
}
Debug::~Debug()
{}
void
Debug::filter(levels::Level lvl)
{
filter_ = lvl;
}
void
Debug::filter(const std::string& lvl)
{
if (lvl == "NONE" || lvl == "0")
filter(Debug::levels::none);
else if (lvl == "LOG" || lvl == "1")
filter(Debug::levels::log);
else if (lvl == "TRACE" || lvl == "2")
filter(Debug::levels::trace);
else if (lvl == "DEBUG" || lvl == "3")
filter(Debug::levels::debug);
else if (lvl == "DUMP" || lvl == "4")
filter(Debug::levels::dump);
else
// Don't use GD_ABORT here, we can be in the debugger constructor!
pabort("invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])");
}
Debug::levels::Level
Debug::level() const
{
return filter_;
}
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static IPSemaphore& sem()
{
static IPSemaphore res(1);
return res;
}
# endif
void
Debug::debug(const std::string& msg,
types::Type type,
debug::category_type category,
const std::string& fun,
const std::string& file,
unsigned line)
{
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static bool useLock = getenv("GD_USE_LOCK") || getenv("GD_PID");
libport::Finally f;
if (useLock)
{
--sem();
f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));
}
# endif
message(category, msg, type, fun, file, line);
}
Debug*
Debug::push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
message_push(category, msg, fun, file, line);
return this;
}
std::string
Debug::category_format(debug::category_type cat) const
{
std::string res = cat;
size_t size = res.size();
size_t largest = debug::categories_largest();
if (size < largest)
{
size_t diff = largest - size;
res = std::string(diff / 2, ' ')
+ res
+ std::string(diff / 2 + diff % 2, ' ');
}
return res;
}
void Debug::abort()
{
libport::abort();
}
namespace opts
{
void cb_debug_fun(const std::string& lvl)
{
GD_DEBUGGER->filter(lvl);
}
OptionValued::callback_type cb_debug(&cb_debug_fun);
OptionValue
debug("set the debug level in NONE, LOG (default), TRACE, DEBUG, DUMP",
"debug", 'd', "LEVEL", &cb_debug);
}
ConsoleDebug::ConsoleDebug()
: indent_(0)
{}
namespace
{
inline
std::string
time()
{
time_t now = std::time(0);
struct tm* ts = std::localtime(&now);
char buf[80];
strftime(buf, sizeof buf, "%a %Y-%m-%d %H:%M:%S %Z", ts);
return buf;
}
inline
std::string
color(int color, bool bold = true)
{
static bool tty = isatty(STDERR_FILENO);
static bool force = getenv("GD_COLOR");
return (tty || force
? format("[33;0%s;%sm", bold ? 1 : 0, color)
: "");
}
inline
std::string
reset()
{
return color(0);
}
}
static Debug::colors::Color
msg_color(Debug::types::Type type)
{
switch (type)
{
case Debug::types::info:
return Debug::colors::white;
case Debug::types::warn:
return Debug::colors::yellow;
case Debug::types::error:
return Debug::colors::red;
};
GD_UNREACHABLE();
}
void
ConsoleDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::ostringstream ostr;
Debug::colors::Color c = msg_color(type);
if (timestamps())
ostr << color(c) << time() << " ";
ostr << color(colors::purple)
<< "[" << category_format(category) << "] ";
{
static bool pid = getenv("GD_PID");
if (pid)
ostr << "[" << getpid() << "] ";
}
#ifndef WIN32
{
static bool thread = getenv("GD_THREAD");
if (thread)
ostr << "[" << pthread_self() << "] ";
}
#endif
ostr << color(c);
for (unsigned i = 0; i < indent_; ++i)
ostr << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
ostr.write(msg.c_str(), msg.size() - 1);
else
ostr << msg;
if (locations())
ostr << color(colors::blue)
<< " (" << fun << ", " << file << ":" << line << ")";
ostr << color(colors::white);
std::cerr << ostr.str() << std::endl;
}
void
ConsoleDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
indent_ += 2;
}
void
ConsoleDebug::pop()
{
indent_ -= 2;
}
std::string gd_ihexdump(const unsigned char* data, unsigned size)
{
std::string res =
format("\"%s\"",
libport::escape(std::string((const char*)data, (size_t)(size))));
bool first = true;
for (unsigned i = 0; i < size; ++i)
{
if (first)
first = false;
else
res += " ";
// Cast to int, or boost::format will print the character.
res += format("0x%x", static_cast<unsigned int>(data[i]));
}
return res;
}
#ifndef WIN32
/*-------------.
| Syslog debug |
`-------------*/
SyslogDebug::SyslogDebug(const std::string& program)
{
openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);
syslog(LOG_INFO | LOG_DAEMON, "%s",
format("Opening syslog session for '%s'", program).c_str());
}
SyslogDebug::~SyslogDebug()
{
syslog(LOG_INFO | LOG_DAEMON, "Closing syslog session.");
closelog();
}
static
int type_to_prio(Debug::types::Type t)
{
switch (t)
{
#define CASE(In, Out) \
case Debug::types::In: return Out; break
CASE(info, LOG_INFO);
CASE(warn, LOG_WARNING);
CASE(error, LOG_ERR);
// Pacify Gcc.
}
libport::abort();
#undef CASE
}
void
SyslogDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::stringstream s;
s << "[" << category_format(category) << "] ";
for (unsigned i = 0; i < indent_; ++i)
s << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
s.write(msg.c_str(), msg.size() - 1);
else
s << msg;
if (locations())
s << " (" << fun << ", " << file << ":" << line << ")";
int prio = type_to_prio(type) | LOG_DAEMON;
syslog(prio, "%s", s.str().c_str());
}
void
SyslogDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
indent_ += 2;
}
void
SyslogDebug::pop()
{
indent_ -= 2;
}
#endif
boost::function0<Debug*> make_debugger;
AbstractLocalData<Debug>* debugger_data;
typedef std::map<pthread_t, Debug*> map_type;
// Do not make it an actual object, as it is sometimes used on
// dtors, and the order to destruction is not specified. Using a
// dynamically allocated object protects us from this.
static map_type* pdebuggers = new map_type;
libport::Lockable debugger_mutex_;
namespace debug
{
void clear()
{
#if FIXME
typedef std::pair<pthread_t, Debug*> entry;
foreach (entry p, *pdebuggers)
{
delete p.second;
p.second = 0;
}
#endif
delete pdebuggers;
pdebuggers = 0;
}
}
Debug* debugger()
{
libport::BlockLock lock(debugger_mutex_);
bool no_gd_init = false;
if (!debugger_data)
{
debugger_data =
new LocalData<Debug, ::libport::localdata::Thread>;
no_gd_init = true;
}
Debug *d = debugger_data->get();
if (!d)
{
if (make_debugger.empty())
{
d = new ConsoleDebug;
no_gd_init = true;
}
else
d = make_debugger();
debugger_data->set(d);
}
if (no_gd_init)
{
# define _GD_WARN(Message) \
d->debug(Message, ::libport::Debug::types::warn, \
GD_CATEGORY_GET(), GD_FUNCTION, __FILE__, __LINE__) \
_GD_WARN("GD_INIT was not invoked, defaulting to console logs");
# undef _GD_WARN
}
return d;
}
}
#endif
<commit_msg>Debug: assert there is not more pops than pushs.<commit_after>/*
* Copyright (C) 2008-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <iostream>
#include <libport/cassert>
#include <libport/containers.hh>
#include <libport/cstdio>
#include <libport/debug.hh>
#include <libport/escape.hh>
#include <libport/foreach.hh>
#include <libport/format.hh>
#include <libport/ip-semaphore.hh>
#include <libport/lockable.hh>
#include <libport/pthread.h>
#include <libport/windows.hh>
#include <libport/unistd.h>
#ifndef WIN32
# include <syslog.h>
#endif
#ifndef LIBPORT_DEBUG_DISABLE
GD_CATEGORY(libport::Debug);
namespace libport
{
namespace debug
{
categories_type& get_categories()
{
static categories_type categories;
return categories;
}
size_t&
categories_largest()
{
static size_t res = 0;
return res;
}
Symbol
add_category(Symbol name)
{
get_categories()[name] = true;
size_t size = name.name_get().size();
if (categories_largest() < size)
categories_largest() = size;
return name;
}
int enable_category(Symbol name)
{
get_categories()[name] = true;
return 42;
}
int disable_category(Symbol name)
{
get_categories()[name] = false;
return 42;
}
bool test_category(Symbol name)
{
return get_categories()[name];
}
}
Debug::Debug()
: locations_(getenv("GD_LOC"))
, timestamps_(getenv("GD_TIME"))
, filter_(levels::log)
{
if (const char* lvl_c = getenv("GD_LEVEL"))
filter(lvl_c);
}
Debug::~Debug()
{}
void
Debug::filter(levels::Level lvl)
{
filter_ = lvl;
}
void
Debug::filter(const std::string& lvl)
{
if (lvl == "NONE" || lvl == "0")
filter(Debug::levels::none);
else if (lvl == "LOG" || lvl == "1")
filter(Debug::levels::log);
else if (lvl == "TRACE" || lvl == "2")
filter(Debug::levels::trace);
else if (lvl == "DEBUG" || lvl == "3")
filter(Debug::levels::debug);
else if (lvl == "DUMP" || lvl == "4")
filter(Debug::levels::dump);
else
// Don't use GD_ABORT here, we can be in the debugger constructor!
pabort("invalid debug level (NONE, LOG, TRACE, DEBUG, DUMP or [0-4])");
}
Debug::levels::Level
Debug::level() const
{
return filter_;
}
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static IPSemaphore& sem()
{
static IPSemaphore res(1);
return res;
}
# endif
void
Debug::debug(const std::string& msg,
types::Type type,
debug::category_type category,
const std::string& fun,
const std::string& file,
unsigned line)
{
# ifdef LIBPORT_HAVE_IP_SEMAPHORE
static bool useLock = getenv("GD_USE_LOCK") || getenv("GD_PID");
libport::Finally f;
if (useLock)
{
--sem();
f << boost::bind(&IPSemaphore::operator++, boost::ref(sem()));
}
# endif
message(category, msg, type, fun, file, line);
}
Debug*
Debug::push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
message_push(category, msg, fun, file, line);
return this;
}
std::string
Debug::category_format(debug::category_type cat) const
{
std::string res = cat;
size_t size = res.size();
size_t largest = debug::categories_largest();
if (size < largest)
{
size_t diff = largest - size;
res = std::string(diff / 2, ' ')
+ res
+ std::string(diff / 2 + diff % 2, ' ');
}
return res;
}
void Debug::abort()
{
libport::abort();
}
namespace opts
{
void cb_debug_fun(const std::string& lvl)
{
GD_DEBUGGER->filter(lvl);
}
OptionValued::callback_type cb_debug(&cb_debug_fun);
OptionValue
debug("set the debug level in NONE, LOG (default), TRACE, DEBUG, DUMP",
"debug", 'd', "LEVEL", &cb_debug);
}
ConsoleDebug::ConsoleDebug()
: indent_(0)
{}
namespace
{
inline
std::string
time()
{
time_t now = std::time(0);
struct tm* ts = std::localtime(&now);
char buf[80];
strftime(buf, sizeof buf, "%a %Y-%m-%d %H:%M:%S %Z", ts);
return buf;
}
inline
std::string
color(int color, bool bold = true)
{
static bool tty = isatty(STDERR_FILENO);
static bool force = getenv("GD_COLOR");
return (tty || force
? format("[33;0%s;%sm", bold ? 1 : 0, color)
: "");
}
inline
std::string
reset()
{
return color(0);
}
}
static Debug::colors::Color
msg_color(Debug::types::Type type)
{
switch (type)
{
case Debug::types::info:
return Debug::colors::white;
case Debug::types::warn:
return Debug::colors::yellow;
case Debug::types::error:
return Debug::colors::red;
};
GD_UNREACHABLE();
}
void
ConsoleDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::ostringstream ostr;
Debug::colors::Color c = msg_color(type);
if (timestamps())
ostr << color(c) << time() << " ";
ostr << color(colors::purple)
<< "[" << category_format(category) << "] ";
{
static bool pid = getenv("GD_PID");
if (pid)
ostr << "[" << getpid() << "] ";
}
#ifndef WIN32
{
static bool thread = getenv("GD_THREAD");
if (thread)
ostr << "[" << pthread_self() << "] ";
}
#endif
ostr << color(c);
for (unsigned i = 0; i < indent_; ++i)
ostr << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
ostr.write(msg.c_str(), msg.size() - 1);
else
ostr << msg;
if (locations())
ostr << color(colors::blue)
<< " (" << fun << ", " << file << ":" << line << ")";
ostr << color(colors::white);
std::cerr << ostr.str() << std::endl;
}
void
ConsoleDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
indent_ += 2;
}
void
ConsoleDebug::pop()
{
assert_gt(indent_, 0);
indent_ -= 2;
}
std::string gd_ihexdump(const unsigned char* data, unsigned size)
{
std::string res =
format("\"%s\"",
libport::escape(std::string((const char*)data, (size_t)(size))));
bool first = true;
for (unsigned i = 0; i < size; ++i)
{
if (first)
first = false;
else
res += " ";
// Cast to int, or boost::format will print the character.
res += format("0x%x", static_cast<unsigned int>(data[i]));
}
return res;
}
#ifndef WIN32
/*-------------.
| Syslog debug |
`-------------*/
SyslogDebug::SyslogDebug(const std::string& program)
{
openlog(strdup(program.c_str()), LOG_PID, LOG_DAEMON);
syslog(LOG_INFO | LOG_DAEMON, "%s",
format("Opening syslog session for '%s'", program).c_str());
}
SyslogDebug::~SyslogDebug()
{
syslog(LOG_INFO | LOG_DAEMON, "Closing syslog session.");
closelog();
}
static
int type_to_prio(Debug::types::Type t)
{
switch (t)
{
#define CASE(In, Out) \
case Debug::types::In: return Out; break
CASE(info, LOG_INFO);
CASE(warn, LOG_WARNING);
CASE(error, LOG_ERR);
// Pacify Gcc.
}
libport::abort();
#undef CASE
}
void
SyslogDebug::message(debug::category_type category,
const std::string& msg,
types::Type type,
const std::string& fun,
const std::string& file,
unsigned line)
{
std::stringstream s;
s << "[" << category_format(category) << "] ";
for (unsigned i = 0; i < indent_; ++i)
s << " ";
// As syslog would do, don't issue the users' \n.
if (!msg.empty() && msg[msg.size() - 1] == '\n')
s.write(msg.c_str(), msg.size() - 1);
else
s << msg;
if (locations())
s << " (" << fun << ", " << file << ":" << line << ")";
int prio = type_to_prio(type) | LOG_DAEMON;
syslog(prio, "%s", s.str().c_str());
}
void
SyslogDebug::message_push(debug::category_type category,
const std::string& msg,
const std::string& fun,
const std::string& file,
unsigned line)
{
debug(msg, types::info, category, fun, file, line);
indent_ += 2;
}
void
SyslogDebug::pop()
{
assert_gt(indent_, 0);
indent_ -= 2;
}
#endif
boost::function0<Debug*> make_debugger;
AbstractLocalData<Debug>* debugger_data;
typedef std::map<pthread_t, Debug*> map_type;
// Do not make it an actual object, as it is sometimes used on
// dtors, and the order to destruction is not specified. Using a
// dynamically allocated object protects us from this.
static map_type* pdebuggers = new map_type;
libport::Lockable debugger_mutex_;
namespace debug
{
void clear()
{
#if FIXME
typedef std::pair<pthread_t, Debug*> entry;
foreach (entry p, *pdebuggers)
{
delete p.second;
p.second = 0;
}
#endif
delete pdebuggers;
pdebuggers = 0;
}
}
Debug* debugger()
{
libport::BlockLock lock(debugger_mutex_);
bool no_gd_init = false;
if (!debugger_data)
{
debugger_data =
new LocalData<Debug, ::libport::localdata::Thread>;
no_gd_init = true;
}
Debug *d = debugger_data->get();
if (!d)
{
if (make_debugger.empty())
{
d = new ConsoleDebug;
no_gd_init = true;
}
else
d = make_debugger();
debugger_data->set(d);
}
if (no_gd_init)
{
# define _GD_WARN(Message) \
d->debug(Message, ::libport::Debug::types::warn, \
GD_CATEGORY_GET(), GD_FUNCTION, __FILE__, __LINE__) \
_GD_WARN("GD_INIT was not invoked, defaulting to console logs");
# undef _GD_WARN
}
return d;
}
}
#endif
<|endoftext|>
|
<commit_before>#include "shaders.h"
#define INVALID_SHADER 0
#define DEBUG_SHADER_ERRORS true
//
// AnyShader
//
AnyShader::AnyShader() {
//empty
}
AnyShader::~AnyShader() {
//empty
}
/**
* Create the shader program.
*/
bool AnyShader::create() {
if (failed) {
return false;
}
if (prog != INVALID_PROGRAM) {
return true;
}
//compile
GLuint handle = glCreateProgram();
if (handle == INVALID_PROGRAM) {
error = "glCreateProgram failed.";
return false;
}
if (!vertexShader.empty()) {
GLuint vertShader = compileShader(vertexShader, GL_VERTEX_SHADER);
if (vertShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, vertShader);
glDeleteShader(vertShader);
}
if (!fragmentShader.empty()) {
GLuint fragShader = compileShader(fragmentShader, GL_FRAGMENT_SHADER);
if (fragShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, fragShader);
glDeleteShader(fragShader);
}
//link
glLinkProgram(handle);
GLint linkStatus;
glGetProgramiv(handle, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
//cleanup
glDeleteProgram(handle);
//get error
GLchar messages[256];
glGetProgramInfoLog(handle, sizeof(messages), 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
printf("shader linking failed: %s\n", messages);
}
return false;
}
prog = handle;
//initialize
initShader();
return true;
}
/**
* Compile a shader.
*
* Note: sets error on failure.
*/
GLuint AnyShader::compileShader(std::string source, const GLenum type) {
GLint compileStatus;
GLuint handle = glCreateShader(type);
if (handle == INVALID_SHADER) {
error = "glCreateShader() failed";
return -1;
}
#ifdef RPI
//add GLSL version
source = "#version 100\n" + source;
#endif
char *src = (char *)source.c_str();
glShaderSource(handle, 1, &src, NULL);
glCompileShader(handle);
//get status
glGetShaderiv(handle, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus == GL_FALSE) {
//free
glDeleteShader(handle);
handle = INVALID_SHADER;
//get error
GLchar messages[256];
glGetShaderInfoLog(handle, sizeof(messages), 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
printf("shader compilation error: %s\n", messages);
}
error = std::string(messages);
}
return handle;
}
/**
* Destroy the shader.
*
* Note: has to be called in OpenGL thread.
*/
void AnyShader::destroy() {
if (prog != INVALID_PROGRAM) {
glDeleteProgram(prog);
prog = INVALID_PROGRAM;
}
//reset failed
failed = false;
}
/**
* Get attribute location.
*/
GLint AnyShader::getAttributeLocation(std::string name) {
GLint loc = glGetAttribLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of attribute %s\n", name.c_str());
}
}
return loc;
}
/**
* Get uniform location.
*/
GLint AnyShader::getUniformLocation(std::string name) {
GLint loc = glGetUniformLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of uniform %s\n", name.c_str());
}
}
return loc;
}
/**
* Use the shader.
*
* Note: has to be called before any setters are used!
*/
void AnyShader::useShader() {
glUseProgram(prog);
}
//
// AnyAminoShader
//
AnyAminoShader::AnyAminoShader() : AnyShader() {
//default vertex shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
void main() {
gl_Position = mvp * trans * pos;
}
)";
}
/**
* Initialize the shader.
*/
void AnyAminoShader::initShader() {
useShader();
//attributes
aPos = getAttributeLocation("pos");
//uniforms
uMVP = getUniformLocation("mvp");
uTrans = getUniformLocation("trans");
}
/**
* Set transformation matrix.
*/
void AnyAminoShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {
glUniformMatrix4fv(uMVP, 1, GL_FALSE, modelView);
glUniformMatrix4fv(uTrans, 1, GL_FALSE, transition);
}
/**
* Draw triangles.
*/
void AnyAminoShader::drawTriangles(GLfloat *verts, GLsizei dim, GLsizei vertices, GLenum mode) {
//x/y coords per vertex
glVertexAttribPointer(aPos, dim, GL_FLOAT, GL_FALSE, 0, verts);
//draw
glEnableVertexAttribArray(aPos);
glDrawArrays(mode, 0, vertices);
glDisableVertexAttribArray(aPos);
}
//
// ColorShader
//
/**
* Create color shader.
*/
ColorShader::ColorShader() : AnyAminoShader() {
//shaders
fragmentShader = R"(
uniform vec4 color;
void main() {
gl_FragColor = color;
}
)";
}
/**
* Initialize the color shader.
*/
void ColorShader::initShader() {
AnyAminoShader::initShader();
//uniforms
uColor = getUniformLocation("color");
}
/**
* Set color.
*/
void ColorShader::setColor(GLfloat color[4]) {
glUniform4f(uColor, color[0], color[1], color[2], color[3]);
}
//
// TextureShader
//
TextureShader::TextureShader() : AnyAminoShader() {
//shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
attribute vec2 tex_coord;
varying vec2 uv;
void main() {
gl_Position = mvp * trans * pos;
uv = tex_coord;
}
)";
//Note: supports clamp to border, using transparent texture
fragmentShader = R"(
varying vec2 uv;
uniform float opacity;
uniform sampler2D tex;
float clamp_to_border_factor(vec2 coords) {
bvec2 out1 = greaterThan(coords, vec2(1, 1));
bvec2 out2 = lessThan(coords, vec2(0,0));
bool do_clamp = (any(out1) || any(out2));
return float(!do_clamp);
}
void main() {
vec4 pixel = texture2D(tex, uv);
gl_FragColor = vec4(pixel.rgb, pixel.a * opacity * clamp_to_border_factor(uv));
}
)";
}
/**
* Initialize the color shader.
*/
void TextureShader::initShader() {
AnyAminoShader::initShader();
//attributes
aTexCoord = getAttributeLocation("tex_coord");
//uniforms
uOpacity = getUniformLocation("opacity");
uTex = getUniformLocation("tex");
//default values
glUniform1i(uTex, 0); //GL_TEXTURE0
}
/**
* Set opacity.
*/
void TextureShader::setOpacity(GLfloat opacity) {
glUniform1f(uOpacity, opacity);
}
/**
* Draw texture.
*/
void TextureShader::drawTexture(GLfloat *verts, GLsizei dim, GLfloat texcoords[][2], GLsizei vertices, GLenum mode) {
glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 0, texcoords);
glEnableVertexAttribArray(aTexCoord);
glActiveTexture(GL_TEXTURE0);
drawTriangles(verts, dim, vertices, mode);
glDisableVertexAttribArray(aTexCoord);
}
<commit_msg>GCC fix<commit_after>#include "shaders.h"
#define INVALID_SHADER 0
#define DEBUG_SHADER_ERRORS true
//
// AnyShader
//
AnyShader::AnyShader() {
//empty
}
AnyShader::~AnyShader() {
//empty
}
/**
* Create the shader program.
*/
bool AnyShader::create() {
if (failed) {
return false;
}
if (prog != INVALID_PROGRAM) {
return true;
}
//compile
GLuint handle = glCreateProgram();
if (handle == INVALID_PROGRAM) {
error = "glCreateProgram failed.";
return false;
}
if (!vertexShader.empty()) {
GLuint vertShader = compileShader(vertexShader, GL_VERTEX_SHADER);
if (vertShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, vertShader);
glDeleteShader(vertShader);
}
if (!fragmentShader.empty()) {
GLuint fragShader = compileShader(fragmentShader, GL_FRAGMENT_SHADER);
if (fragShader == INVALID_SHADER) {
//cleanup
glDeleteProgram(handle);
return false;
}
glAttachShader(handle, fragShader);
glDeleteShader(fragShader);
}
//link
glLinkProgram(handle);
GLint linkStatus;
glGetProgramiv(handle, GL_LINK_STATUS, &linkStatus);
if (linkStatus == GL_FALSE) {
//cleanup
glDeleteProgram(handle);
//get error
GLchar messages[256];
glGetProgramInfoLog(handle, sizeof(messages), 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
printf("shader linking failed: %s\n", messages);
}
return false;
}
prog = handle;
//initialize
initShader();
return true;
}
/**
* Compile a shader.
*
* Note: sets error on failure.
*/
GLuint AnyShader::compileShader(std::string source, const GLenum type) {
GLint compileStatus;
GLuint handle = glCreateShader(type);
if (handle == INVALID_SHADER) {
error = "glCreateShader() failed";
return -1;
}
#ifdef RPI
//add GLSL version
source = "#version 100\n" + source;
#endif
GLchar *src = (GLchar *)source.c_str();
glShaderSource(handle, 1, (const GLchar **)&src, NULL);
glCompileShader(handle);
//get status
glGetShaderiv(handle, GL_COMPILE_STATUS, &compileStatus);
if (compileStatus == GL_FALSE) {
//free
glDeleteShader(handle);
handle = INVALID_SHADER;
//get error
GLchar messages[256];
glGetShaderInfoLog(handle, sizeof(messages), 0, &messages[0]);
if (DEBUG_SHADER_ERRORS) {
printf("shader compilation error: %s\n", messages);
}
error = std::string(messages);
}
return handle;
}
/**
* Destroy the shader.
*
* Note: has to be called in OpenGL thread.
*/
void AnyShader::destroy() {
if (prog != INVALID_PROGRAM) {
glDeleteProgram(prog);
prog = INVALID_PROGRAM;
}
//reset failed
failed = false;
}
/**
* Get attribute location.
*/
GLint AnyShader::getAttributeLocation(std::string name) {
GLint loc = glGetAttribLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of attribute %s\n", name.c_str());
}
}
return loc;
}
/**
* Get uniform location.
*/
GLint AnyShader::getUniformLocation(std::string name) {
GLint loc = glGetUniformLocation(prog, name.c_str());
if (DEBUG_SHADER_ERRORS) {
if (loc == -1) {
printf("could not get location of uniform %s\n", name.c_str());
}
}
return loc;
}
/**
* Use the shader.
*
* Note: has to be called before any setters are used!
*/
void AnyShader::useShader() {
glUseProgram(prog);
}
//
// AnyAminoShader
//
AnyAminoShader::AnyAminoShader() : AnyShader() {
//default vertex shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
void main() {
gl_Position = mvp * trans * pos;
}
)";
}
/**
* Initialize the shader.
*/
void AnyAminoShader::initShader() {
useShader();
//attributes
aPos = getAttributeLocation("pos");
//uniforms
uMVP = getUniformLocation("mvp");
uTrans = getUniformLocation("trans");
}
/**
* Set transformation matrix.
*/
void AnyAminoShader::setTransformation(GLfloat modelView[16], GLfloat transition[16]) {
glUniformMatrix4fv(uMVP, 1, GL_FALSE, modelView);
glUniformMatrix4fv(uTrans, 1, GL_FALSE, transition);
}
/**
* Draw triangles.
*/
void AnyAminoShader::drawTriangles(GLfloat *verts, GLsizei dim, GLsizei vertices, GLenum mode) {
//x/y coords per vertex
glVertexAttribPointer(aPos, dim, GL_FLOAT, GL_FALSE, 0, verts);
//draw
glEnableVertexAttribArray(aPos);
glDrawArrays(mode, 0, vertices);
glDisableVertexAttribArray(aPos);
}
//
// ColorShader
//
/**
* Create color shader.
*/
ColorShader::ColorShader() : AnyAminoShader() {
//shaders
fragmentShader = R"(
uniform vec4 color;
void main() {
gl_FragColor = color;
}
)";
}
/**
* Initialize the color shader.
*/
void ColorShader::initShader() {
AnyAminoShader::initShader();
//uniforms
uColor = getUniformLocation("color");
}
/**
* Set color.
*/
void ColorShader::setColor(GLfloat color[4]) {
glUniform4f(uColor, color[0], color[1], color[2], color[3]);
}
//
// TextureShader
//
TextureShader::TextureShader() : AnyAminoShader() {
//shader
vertexShader = R"(
uniform mat4 mvp;
uniform mat4 trans;
attribute vec4 pos;
attribute vec2 tex_coord;
varying vec2 uv;
void main() {
gl_Position = mvp * trans * pos;
uv = tex_coord;
}
)";
//Note: supports clamp to border, using transparent texture
fragmentShader = R"(
varying vec2 uv;
uniform float opacity;
uniform sampler2D tex;
float clamp_to_border_factor(vec2 coords) {
bvec2 out1 = greaterThan(coords, vec2(1, 1));
bvec2 out2 = lessThan(coords, vec2(0,0));
bool do_clamp = (any(out1) || any(out2));
return float(!do_clamp);
}
void main() {
vec4 pixel = texture2D(tex, uv);
gl_FragColor = vec4(pixel.rgb, pixel.a * opacity * clamp_to_border_factor(uv));
}
)";
}
/**
* Initialize the color shader.
*/
void TextureShader::initShader() {
AnyAminoShader::initShader();
//attributes
aTexCoord = getAttributeLocation("tex_coord");
//uniforms
uOpacity = getUniformLocation("opacity");
uTex = getUniformLocation("tex");
//default values
glUniform1i(uTex, 0); //GL_TEXTURE0
}
/**
* Set opacity.
*/
void TextureShader::setOpacity(GLfloat opacity) {
glUniform1f(uOpacity, opacity);
}
/**
* Draw texture.
*/
void TextureShader::drawTexture(GLfloat *verts, GLsizei dim, GLfloat texcoords[][2], GLsizei vertices, GLenum mode) {
glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 0, texcoords);
glEnableVertexAttribArray(aTexCoord);
glActiveTexture(GL_TEXTURE0);
drawTriangles(verts, dim, vertices, mode);
glDisableVertexAttribArray(aTexCoord);
}
<|endoftext|>
|
<commit_before>/*
* Shared memory for sharing data between worker processes.
*
* author: Max Kellermann <[email protected]>
*/
#include "shm.hxx"
#include "system/Error.hxx"
#include "util/RefCount.hxx"
#include <inline/poison.h>
#include <inline/list.h>
#include <daemon/log.h>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <assert.h>
#include <stdint.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
struct page {
struct list_head siblings;
unsigned num_pages;
uint8_t *data;
};
struct shm {
RefCount ref;
const size_t page_size;
const unsigned num_pages;
/** this lock protects the linked list */
boost::interprocess::interprocess_mutex mutex;
struct list_head available;
struct page pages[1];
shm(size_t _page_size, unsigned _num_pages)
:page_size(_page_size), num_pages(_num_pages) {
ref.Init();
list_init(&available);
list_add(&pages[0].siblings, &available);
pages[0].num_pages = num_pages;
pages[0].data = GetData();
}
static unsigned CalcHeaderPages(size_t page_size, unsigned num_pages) {
size_t header_size = sizeof(struct shm) +
(num_pages - 1) * sizeof(struct page);
return (header_size + page_size - 1) / page_size;
}
unsigned CalcHeaderPages() const {
return CalcHeaderPages(page_size, num_pages);
}
uint8_t *At(size_t offset) {
return (uint8_t *)this + offset;
}
const uint8_t *At(size_t offset) const {
return (const uint8_t *)this + offset;
}
uint8_t *GetData() {
return At(page_size * CalcHeaderPages());
}
const uint8_t *GetData() const {
return At(page_size * CalcHeaderPages());
}
unsigned PageNumber(const void *p) const {
ptrdiff_t difference = (const uint8_t *)p - GetData();
unsigned page_number = difference / page_size;
assert(difference % page_size == 0);
assert(page_number < num_pages);
return page_number;
}
struct page *FindAvailable(unsigned want_pages);
struct page *SplitPage(struct page *page, unsigned want_pages);
/**
* Merge this page with its adjacent pages if possible, to create
* bigger "available" areas.
*/
void Merge(struct page *page);
void *Allocate(unsigned want_pages);
void Free(const void *p);
};
struct shm *
shm_new(size_t page_size, unsigned num_pages)
{
assert(page_size >= sizeof(size_t));
assert(num_pages > 0);
const unsigned header_pages = shm::CalcHeaderPages(page_size, num_pages);
void *p = mmap(nullptr, page_size * (header_pages + num_pages),
PROT_READ|PROT_WRITE,
MAP_ANONYMOUS|MAP_SHARED,
-1, 0);
if (p == (void *)-1)
throw MakeErrno("mmap() failed");
return ::new(p) struct shm(page_size, num_pages);
}
void
shm_ref(struct shm *shm)
{
assert(shm != nullptr);
shm->ref.Get();
}
void
shm_close(struct shm *shm)
{
unsigned header_pages;
int ret;
assert(shm != nullptr);
if (shm->ref.Put())
shm->~shm();
header_pages = shm->CalcHeaderPages();
ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages));
if (ret < 0)
daemon_log(1, "munmap() failed: %s\n", strerror(errno));
}
size_t
shm_page_size(const struct shm *shm)
{
return shm->page_size;
}
struct page *
shm::FindAvailable(unsigned want_pages)
{
for (struct page *page = (struct page *)available.next;
&page->siblings != &available;
page = (struct page *)page->siblings.next)
if (page->num_pages >= want_pages)
return page;
return nullptr;
}
struct page *
shm::SplitPage(struct page *page, unsigned want_pages)
{
assert(page->num_pages > want_pages);
page->num_pages -= want_pages;
page[page->num_pages].data = page->data + page_size * page->num_pages;
page += page->num_pages;
page->num_pages = want_pages;
return page;
}
void *
shm::Allocate(unsigned want_pages)
{
assert(want_pages > 0);
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(mutex);
struct page *page = FindAvailable(want_pages);
if (page == nullptr) {
return nullptr;
}
assert(page->num_pages >= want_pages);
page = (struct page *)available.next;
if (page->num_pages == want_pages) {
list_remove(&page->siblings);
lock.unlock();
poison_undefined(page->data, page_size * want_pages);
return page->data;
} else {
page = SplitPage(page, want_pages);
lock.unlock();
poison_undefined(page->data, page_size * want_pages);
return page->data;
}
}
void *
shm_alloc(struct shm *shm, unsigned want_pages)
{
return shm->Allocate(want_pages);
}
/** merge this page with its adjacent pages if possible, to create
bigger "available" areas */
void
shm::Merge(struct page *page)
{
unsigned page_number = PageNumber(page->data);
/* merge with previous page? */
struct page *other = (struct page *)page->siblings.prev;
if (&other->siblings != &available &&
PageNumber(other->data) + other->num_pages == page_number) {
other->num_pages += page->num_pages;
list_remove(&page->siblings);
page = other;
}
/* merge with next page? */
other = (struct page *)page->siblings.next;
if (&other->siblings != &available &&
page_number + page->num_pages == PageNumber(other->data)) {
page->num_pages += other->num_pages;
list_remove(&other->siblings);
}
}
void
shm::Free(const void *p)
{
unsigned page_number = PageNumber(p);
struct page *page = &pages[page_number];
struct page *prev;
poison_noaccess(page->data, page_size * page->num_pages);
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(mutex);
for (prev = (struct page *)&available;
prev->siblings.next != &available;
prev = (struct page *)prev->siblings.next) {
}
list_add(&page->siblings, &prev->siblings);
Merge(page);
}
void
shm_free(struct shm *shm, const void *p)
{
shm->Free(p);
}
<commit_msg>shm/shm: move struct page into struct shm<commit_after>/*
* Shared memory for sharing data between worker processes.
*
* author: Max Kellermann <[email protected]>
*/
#include "shm.hxx"
#include "system/Error.hxx"
#include "util/RefCount.hxx"
#include <inline/poison.h>
#include <inline/list.h>
#include <daemon/log.h>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <assert.h>
#include <stdint.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
struct shm {
RefCount ref;
const size_t page_size;
const unsigned num_pages;
/** this lock protects the linked list */
boost::interprocess::interprocess_mutex mutex;
struct Page {
struct list_head siblings;
unsigned num_pages;
uint8_t *data;
};
struct list_head available;
Page pages[1];
shm(size_t _page_size, unsigned _num_pages)
:page_size(_page_size), num_pages(_num_pages) {
ref.Init();
list_init(&available);
list_add(&pages[0].siblings, &available);
pages[0].num_pages = num_pages;
pages[0].data = GetData();
}
static unsigned CalcHeaderPages(size_t page_size, unsigned num_pages) {
size_t header_size = sizeof(struct shm) +
(num_pages - 1) * sizeof(Page);
return (header_size + page_size - 1) / page_size;
}
unsigned CalcHeaderPages() const {
return CalcHeaderPages(page_size, num_pages);
}
uint8_t *At(size_t offset) {
return (uint8_t *)this + offset;
}
const uint8_t *At(size_t offset) const {
return (const uint8_t *)this + offset;
}
uint8_t *GetData() {
return At(page_size * CalcHeaderPages());
}
const uint8_t *GetData() const {
return At(page_size * CalcHeaderPages());
}
unsigned PageNumber(const void *p) const {
ptrdiff_t difference = (const uint8_t *)p - GetData();
unsigned page_number = difference / page_size;
assert(difference % page_size == 0);
assert(page_number < num_pages);
return page_number;
}
Page *FindAvailable(unsigned want_pages);
Page *SplitPage(Page *page, unsigned want_pages);
/**
* Merge this page with its adjacent pages if possible, to create
* bigger "available" areas.
*/
void Merge(Page *page);
void *Allocate(unsigned want_pages);
void Free(const void *p);
};
struct shm *
shm_new(size_t page_size, unsigned num_pages)
{
assert(page_size >= sizeof(size_t));
assert(num_pages > 0);
const unsigned header_pages = shm::CalcHeaderPages(page_size, num_pages);
void *p = mmap(nullptr, page_size * (header_pages + num_pages),
PROT_READ|PROT_WRITE,
MAP_ANONYMOUS|MAP_SHARED,
-1, 0);
if (p == (void *)-1)
throw MakeErrno("mmap() failed");
return ::new(p) struct shm(page_size, num_pages);
}
void
shm_ref(struct shm *shm)
{
assert(shm != nullptr);
shm->ref.Get();
}
void
shm_close(struct shm *shm)
{
unsigned header_pages;
int ret;
assert(shm != nullptr);
if (shm->ref.Put())
shm->~shm();
header_pages = shm->CalcHeaderPages();
ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages));
if (ret < 0)
daemon_log(1, "munmap() failed: %s\n", strerror(errno));
}
size_t
shm_page_size(const struct shm *shm)
{
return shm->page_size;
}
shm::Page *
shm::FindAvailable(unsigned want_pages)
{
for (Page *page = (Page *)available.next;
&page->siblings != &available;
page = (Page *)page->siblings.next)
if (page->num_pages >= want_pages)
return page;
return nullptr;
}
shm::Page *
shm::SplitPage(Page *page, unsigned want_pages)
{
assert(page->num_pages > want_pages);
page->num_pages -= want_pages;
page[page->num_pages].data = page->data + page_size * page->num_pages;
page += page->num_pages;
page->num_pages = want_pages;
return page;
}
void *
shm::Allocate(unsigned want_pages)
{
assert(want_pages > 0);
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(mutex);
Page *page = FindAvailable(want_pages);
if (page == nullptr) {
return nullptr;
}
assert(page->num_pages >= want_pages);
page = (Page *)available.next;
if (page->num_pages == want_pages) {
list_remove(&page->siblings);
lock.unlock();
poison_undefined(page->data, page_size * want_pages);
return page->data;
} else {
page = SplitPage(page, want_pages);
lock.unlock();
poison_undefined(page->data, page_size * want_pages);
return page->data;
}
}
void *
shm_alloc(struct shm *shm, unsigned want_pages)
{
return shm->Allocate(want_pages);
}
/** merge this page with its adjacent pages if possible, to create
bigger "available" areas */
void
shm::Merge(Page *page)
{
unsigned page_number = PageNumber(page->data);
/* merge with previous page? */
Page *other = (Page *)page->siblings.prev;
if (&other->siblings != &available &&
PageNumber(other->data) + other->num_pages == page_number) {
other->num_pages += page->num_pages;
list_remove(&page->siblings);
page = other;
}
/* merge with next page? */
other = (Page *)page->siblings.next;
if (&other->siblings != &available &&
page_number + page->num_pages == PageNumber(other->data)) {
page->num_pages += other->num_pages;
list_remove(&other->siblings);
}
}
void
shm::Free(const void *p)
{
unsigned page_number = PageNumber(p);
Page *page = &pages[page_number];
Page *prev;
poison_noaccess(page->data, page_size * page->num_pages);
boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(mutex);
for (prev = (Page *)&available;
prev->siblings.next != &available;
prev = (Page *)prev->siblings.next) {
}
list_add(&page->siblings, &prev->siblings);
Merge(page);
}
void
shm_free(struct shm *shm, const void *p)
{
shm->Free(p);
}
<|endoftext|>
|
<commit_before>#include <GL/glew.h>
#include "Surface.hpp"
#include "SimpleWindow.hpp"
#include <QApplication>
#include <GL/glx.h>
namespace fast {
void Surface::create(
std::vector<Float<3> > vertices,
std::vector<Float<3> > normals,
std::vector<Uint<3> > triangles) {
if(mIsInitialized) {
// Delete old data
freeAll();
}
mIsInitialized = true;
for(unsigned int i = 0; i < vertices.size(); i++) {
SurfaceVertex v;
v.position = vertices[i];
v.normal = normals[i];
mVertices.push_back(v);
}
for(unsigned int i = 0; i < triangles.size(); i++) {
mVertices[triangles[i].x()].triangles.push_back(i);
mVertices[triangles[i].y()].triangles.push_back(i);
mVertices[triangles[i].z()].triangles.push_back(i);
}
mNrOfTriangles = triangles.size();
}
void Surface::create(unsigned int nrOfTriangles) {
if(mIsInitialized) {
// Delete old data
freeAll();
}
mIsInitialized = true;
mNrOfTriangles = nrOfTriangles;
}
bool Surface::isAnyDataBeingAccessed() {
return mVBODataIsBeingAccessed || mHostDataIsBeingAccessed;
}
VertexBufferObjectAccess Surface::getVertexBufferObjectAccess(
accessType type,
OpenCLDevice::pointer device) {
if(!mIsInitialized)
throw Exception("Surface has not been initialized.");
if(mSurfaceIsBeingWrittenTo)
throw Exception("Requesting access to an image that is already being written to.");
if (type == ACCESS_READ_WRITE) {
if (isAnyDataBeingAccessed()) {
throw Exception(
"Trying to get write access to an object that is already being accessed");
}
mSurfaceIsBeingWrittenTo = true;
}
if(!mVBOHasData) {
// TODO create VBO
// Have to have a drawable available before glewInit and glGenBuffers
if(glXGetCurrentDrawable() == 0) { // TODO make this work on all platforms
SimpleWindow::initializeQtApp();
// Need a drawable for this to work
QGLWidget* widget = new QGLWidget;
widget->show();
widget->hide(); // TODO should probably delete widget as well
std::cout << "created a drawable" << std::endl;
}
setOpenGLContext(device->getGLContext());
GLenum err = glewInit();
if(err != GLEW_OK)
throw Exception("GLEW init error");
glGenBuffers(1, &mVBOID);
glBindBuffer(GL_ARRAY_BUFFER, mVBOID);
glBufferData(GL_ARRAY_BUFFER, mNrOfTriangles*18*sizeof(cl_float), NULL, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glFinish();
std::cout << "Created VBO with ID " << mVBOID << std::endl;
// TODO Transfer data if any exist
mVBOHasData = true;
mVBODataIsUpToDate = true;
} else {
if(!mVBODataIsUpToDate) {
// TODO Update data
}
}
mVBODataIsBeingAccessed = true;
return VertexBufferObjectAccess(mVBOID, &mVBODataIsBeingAccessed, &mSurfaceIsBeingWrittenTo);
}
SurfacePointerAccess Surface::getSurfacePointerAccess(accessType access) {
if(!mIsInitialized)
throw Exception("Surface has not been initialized.");
throw Exception("Not implemented yet!");
}
Surface::~Surface() {
freeAll();
}
Surface::Surface() {
mIsInitialized = false;
mVBOHasData = false;
mHostHasData = false;
mSurfaceIsBeingWrittenTo = false;
mVBODataIsBeingAccessed = false;
mHostDataIsBeingAccessed = false;
}
void Surface::freeAll() {
// TODO finish
if(mVBOHasData)
glDeleteBuffers(1, &mVBOID);
}
void Surface::free(ExecutionDevice::pointer device) {
// TODO
}
unsigned int Surface::getNrOfTriangles() const {
return mNrOfTriangles;
}
BoundingBox Surface::getBoundingBox() const {
return mBoundingBox;
}
void Surface::setBoundingBox(BoundingBox box) {
mBoundingBox = box;
}
} // end namespace fast
<commit_msg>added some preprocessor ifs around the glxGetCurrentDrawable in getVBOAccess<commit_after>#include <GL/glew.h>
#include "Surface.hpp"
#include "SimpleWindow.hpp"
#include <QApplication>
#include <GL/glx.h>
namespace fast {
void Surface::create(
std::vector<Float<3> > vertices,
std::vector<Float<3> > normals,
std::vector<Uint<3> > triangles) {
if(mIsInitialized) {
// Delete old data
freeAll();
}
mIsInitialized = true;
for(unsigned int i = 0; i < vertices.size(); i++) {
SurfaceVertex v;
v.position = vertices[i];
v.normal = normals[i];
mVertices.push_back(v);
}
for(unsigned int i = 0; i < triangles.size(); i++) {
mVertices[triangles[i].x()].triangles.push_back(i);
mVertices[triangles[i].y()].triangles.push_back(i);
mVertices[triangles[i].z()].triangles.push_back(i);
}
mNrOfTriangles = triangles.size();
}
void Surface::create(unsigned int nrOfTriangles) {
if(mIsInitialized) {
// Delete old data
freeAll();
}
mIsInitialized = true;
mNrOfTriangles = nrOfTriangles;
}
bool Surface::isAnyDataBeingAccessed() {
return mVBODataIsBeingAccessed || mHostDataIsBeingAccessed;
}
VertexBufferObjectAccess Surface::getVertexBufferObjectAccess(
accessType type,
OpenCLDevice::pointer device) {
if(!mIsInitialized)
throw Exception("Surface has not been initialized.");
if(mSurfaceIsBeingWrittenTo)
throw Exception("Requesting access to an image that is already being written to.");
if (type == ACCESS_READ_WRITE) {
if (isAnyDataBeingAccessed()) {
throw Exception(
"Trying to get write access to an object that is already being accessed");
}
mSurfaceIsBeingWrittenTo = true;
}
if(!mVBOHasData) {
// TODO create VBO
// Have to have a drawable available before glewInit and glGenBuffers
#if defined(__APPLE__) || defined(__MACOSX)
#else
#if _WIN32
#else
if(glXGetCurrentDrawable() == 0) { // TODO make this work on all platforms
SimpleWindow::initializeQtApp();
// Need a drawable for this to work
QGLWidget* widget = new QGLWidget;
widget->show();
widget->hide(); // TODO should probably delete widget as well
std::cout << "created a drawable" << std::endl;
}
#endif
#endif
setOpenGLContext(device->getGLContext());
GLenum err = glewInit();
if(err != GLEW_OK)
throw Exception("GLEW init error");
glGenBuffers(1, &mVBOID);
glBindBuffer(GL_ARRAY_BUFFER, mVBOID);
glBufferData(GL_ARRAY_BUFFER, mNrOfTriangles*18*sizeof(cl_float), NULL, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glFinish();
std::cout << "Created VBO with ID " << mVBOID << std::endl;
// TODO Transfer data if any exist
mVBOHasData = true;
mVBODataIsUpToDate = true;
} else {
if(!mVBODataIsUpToDate) {
// TODO Update data
}
}
mVBODataIsBeingAccessed = true;
return VertexBufferObjectAccess(mVBOID, &mVBODataIsBeingAccessed, &mSurfaceIsBeingWrittenTo);
}
SurfacePointerAccess Surface::getSurfacePointerAccess(accessType access) {
if(!mIsInitialized)
throw Exception("Surface has not been initialized.");
throw Exception("Not implemented yet!");
}
Surface::~Surface() {
freeAll();
}
Surface::Surface() {
mIsInitialized = false;
mVBOHasData = false;
mHostHasData = false;
mSurfaceIsBeingWrittenTo = false;
mVBODataIsBeingAccessed = false;
mHostDataIsBeingAccessed = false;
}
void Surface::freeAll() {
// TODO finish
if(mVBOHasData)
glDeleteBuffers(1, &mVBOID);
}
void Surface::free(ExecutionDevice::pointer device) {
// TODO
}
unsigned int Surface::getNrOfTriangles() const {
return mNrOfTriangles;
}
BoundingBox Surface::getBoundingBox() const {
return mBoundingBox;
}
void Surface::setBoundingBox(BoundingBox box) {
mBoundingBox = box;
}
} // end namespace fast
<|endoftext|>
|
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Modules/Visualization/ShowField.h>
#include <Dataflow/Network/ModuleStateInterface.h> //TODO: extract into intermediate
#include <Core/Datatypes/Color.h>
#include <QColorDialog>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
ShowFieldDialog::ShowFieldDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent),
defaultMeshColor_(Qt::gray)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
addCheckBoxManager(showNodesCheckBox_, ShowFieldModule::ShowNodes);
addCheckBoxManager(showEdgesCheckBox_, ShowFieldModule::ShowEdges);
addCheckBoxManager(showFacesCheckBox_, ShowFieldModule::ShowFaces);
addCheckBoxManager(enableTransparencyNodesCheckBox_, ShowFieldModule::NodeTransparency);
addCheckBoxManager(enableTransparencyEdgesCheckBox_, ShowFieldModule::EdgeTransparency);
addCheckBoxManager(enableTransparencyFacesCheckBox_, ShowFieldModule::FaceTransparency);
addCheckBoxManager(invertNormalsCheckBox, ShowFieldModule::FaceInvertNormals);
buttonBox->setVisible(false);
connect(defaultMeshColorButton_, SIGNAL(clicked()), this, SLOT(assignDefaultMeshColor()));
connect(nodesAsPointsButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));
connect(nodesAsSpheresButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));
pushNodeType();
}
void ShowFieldDialog::push()
{
if (!pulling_)
{
pushColor();
}
}
void ShowFieldDialog::pull()
{
pull_newVersionToReplaceOld();
Pulling p(this);
ColorRGB color(state_->getValue(ShowFieldModule::DefaultMeshColor).getString());
defaultMeshColor_ = QColor(
static_cast<int>(color.r() * 255.0),
static_cast<int>(color.g() * 255.0),
static_cast<int>(color.b() * 255.0));
}
void ShowFieldDialog::assignDefaultMeshColor()
{
auto newColor = QColorDialog::getColor(defaultMeshColor_, this, "Choose default mesh color");
if (newColor.isValid())
{
defaultMeshColor_ = newColor;
//TODO: set color of button to this color
//defaultMeshColorButton_->set
pushColor();
}
}
void ShowFieldDialog::pushColor()
{
state_->setValue(ShowFieldModule::DefaultMeshColor, ColorRGB(defaultMeshColor_.red(), defaultMeshColor_.green(), defaultMeshColor_.blue()).toString());
}
void ShowFieldDialog::pushNodeType()
{
state_->setValue(ShowFieldModule::NodeAsPoints, nodesAsPointsButton_->isChecked());
state_->setValue(ShowFieldModule::NodeAsSpheres, nodesAsSpheresButton_->isChecked());
}
<commit_msg>Ensure default color is propogated properly.<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Scientific Computing and Imaging Institute,
University of Utah.
License for the specific language governing rights and limitations under
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 <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Modules/Visualization/ShowField.h>
#include <Dataflow/Network/ModuleStateInterface.h> //TODO: extract into intermediate
#include <Core/Datatypes/Color.h>
#include <QColorDialog>
using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Visualization;
using namespace SCIRun::Core::Datatypes;
ShowFieldDialog::ShowFieldDialog(const std::string& name, ModuleStateHandle state,
QWidget* parent /* = 0 */)
: ModuleDialogGeneric(state, parent),
defaultMeshColor_(Qt::gray)
{
setupUi(this);
setWindowTitle(QString::fromStdString(name));
fixSize();
addCheckBoxManager(showNodesCheckBox_, ShowFieldModule::ShowNodes);
addCheckBoxManager(showEdgesCheckBox_, ShowFieldModule::ShowEdges);
addCheckBoxManager(showFacesCheckBox_, ShowFieldModule::ShowFaces);
addCheckBoxManager(enableTransparencyNodesCheckBox_, ShowFieldModule::NodeTransparency);
addCheckBoxManager(enableTransparencyEdgesCheckBox_, ShowFieldModule::EdgeTransparency);
addCheckBoxManager(enableTransparencyFacesCheckBox_, ShowFieldModule::FaceTransparency);
addCheckBoxManager(invertNormalsCheckBox, ShowFieldModule::FaceInvertNormals);
buttonBox->setVisible(false);
connect(defaultMeshColorButton_, SIGNAL(clicked()), this, SLOT(assignDefaultMeshColor()));
connect(nodesAsPointsButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));
connect(nodesAsSpheresButton_, SIGNAL(clicked()), this, SLOT(pushNodeType()));
pushNodeType();
pushColor();
}
void ShowFieldDialog::push()
{
if (!pulling_)
{
pushColor();
}
}
void ShowFieldDialog::pull()
{
pull_newVersionToReplaceOld();
Pulling p(this);
ColorRGB color(state_->getValue(ShowFieldModule::DefaultMeshColor).getString());
defaultMeshColor_ = QColor(
static_cast<int>(color.r() * 255.0),
static_cast<int>(color.g() * 255.0),
static_cast<int>(color.b() * 255.0));
}
void ShowFieldDialog::assignDefaultMeshColor()
{
auto newColor = QColorDialog::getColor(defaultMeshColor_, this, "Choose default mesh color");
if (newColor.isValid())
{
defaultMeshColor_ = newColor;
//TODO: set color of button to this color
//defaultMeshColorButton_->set
pushColor();
}
}
void ShowFieldDialog::pushColor()
{
state_->setValue(ShowFieldModule::DefaultMeshColor, ColorRGB(defaultMeshColor_.red(), defaultMeshColor_.green(), defaultMeshColor_.blue()).toString());
}
void ShowFieldDialog::pushNodeType()
{
state_->setValue(ShowFieldModule::NodeAsPoints, nodesAsPointsButton_->isChecked());
state_->setValue(ShowFieldModule::NodeAsSpheres, nodesAsSpheresButton_->isChecked());
}
<|endoftext|>
|
<commit_before>/*
* FILE: 1A.cpp
*
* @author: Arafat Hasan Jenin <arafathasanjenin[at]gmail[dot]com>
*
* LINK:
*
* DATE CREATED: 03-09-17 21:47:10 (BST)
* LAST MODIFIED: 03-09-17 23:53:47 (BST)
*
* DESCRIPTION:
*
* DEVELOPMENT HISTORY:
* Date Version Description
* --------------------------------------------------------------------
* 03-09-17 1.0 File Created
*
*/
/*
// ___ ___ ___ ___
// / /\ / /\ /__/\ ___ /__/\
// / /:/ / /:/_ \ \:\ / /\ \ \:\
// /__/::\ / /:/ /\ \ \:\ / /:/ \ \:\
// \__\/\:\ / /:/ /:/_ _____\__\:\ /__/::\ _____\__\:\
// \ \:\ /__/:/ /:/ /\ /__/::::::::\ \__\/\:\__ /__/::::::::\
// \__\:\ \ \:\/:/ /:/ \ \:\~~\~~\/ \ \:\/\ \ \:\~~\~~\/
// / /:/ \ \::/ /:/ \ \:\ ~~~ \__\::/ \ \:\ ~~~
// /__/:/ \ \:\/:/ \ \:\ /__/:/ \ \:\
// \__\/ \ \::/ \ \:\ \__\/ \ \:\
// \__\/ \__\/ \__\/
*/
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <climits>
#include <cmath>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <utility>
#include <sstream>
#include <algorithm>
#include <stack>
#include <set>
#include <list>
#include <map>
#include <queue>
#include <deque>
#include <vector>
#include <stdint.h> //uint32_t
#include <functional>
#include <bitset>
using namespace std;
typedef long long ll;
typedef double lf;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
typedef vector<int> vi;
#define __FastIO ios_base::sync_with_stdio(false); cin.tie(0)
#define For(i, a, b) for (__typeof (a) i=a; i<=b; i++)
#define Rof(i, b, a) for (__typeof (a) i=b; i>=a; i--)
#define Rep(i, n) for (__typeof (n) i=0; i<n; i++)
#define Forit(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i)
#define all(ar) ar.begin(), ar.end()
#define fill(ar, val) memset(ar, val, sizeof(ar))
#define clr(a) memset(a, 0, sizeof a)
#define nl cout << '\n';
#define sp cout << ' ';
#define gc getchar
#define chk cout << "##########\n"
#define pb push_back
#define debug1(x) cout << #x << ": " << x << endl
#define debug2(x, y) cout << #x << ": " << x << '\t' << #y << ": " << y << endl
#define debug3(x, y, z) cout << #x << ": " << x << '\t' << #y << ": " << y << '\t' << #z << ": " << z << endl
#define max(a, b) (a < b ? b : a)
#define min(a, b) (a > b ? b : a)
#define sq(a) (a * a)
#define PI acos(-1.0)
#define INF 0x7fffffff
#define MOD 1000000007
#define EPS 1e-10
#define MAX 10000005
////////////////////////// START HERE //////////////////////////
int main() {
__FastIO;
ll n, m, a;
cin >> n >> m >> a;
return !(cout << (((ll) round (ceil(n / (lf) a))) * \
((ll) round(ceil(m / (lf) a)))) << '\n');
}
<commit_msg>21 Sep, 2018<commit_after>/*
* FILE: 1A.cpp
*
* @author: Arafat Hasan Jenin <arafathasanjenin[at]gmail[dot]com>
*
* LINK:
*
* DATE CREATED: 03-09-17 21:47:10 (BST)
* LAST MODIFIED: 03-09-17 23:53:47 (BST)
*
* DESCRIPTION:
*
* DEVELOPMENT HISTORY:
* Date Version Description
* --------------------------------------------------------------------
* 03-09-17 1.0 File Created
*
*/
/*
// ___ ___ ___ ___
// / /\ / /\ /__/\ ___ /__/\
// / /:/ / /:/_ \ \:\ / /\ \ \:\
// /__/::\ / /:/ /\ \ \:\ / /:/ \ \:\
// \__\/\:\ / /:/ /:/_ _____\__\:\ /__/::\ _____\__\:\
// \ \:\ /__/:/ /:/ /\ /__/::::::::\ \__\/\:\__ /__/::::::::\
// \__\:\ \ \:\/:/ /:/ \ \:\~~\~~\/ \ \:\/\ \ \:\~~\~~\/
// / /:/ \ \::/ /:/ \ \:\ ~~~ \__\::/ \ \:\ ~~~
// /__/:/ \ \:\/:/ \ \:\ /__/:/ \ \:\
// \__\/ \ \::/ \ \:\ \__\/ \ \:\
// \__\/ \__\/ \__\/
*/
/////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <climits>
#include <cmath>
#include <cstring>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <utility>
#include <sstream>
#include <algorithm>
#include <stack>
#include <set>
#include <list>
#include <map>
#include <queue>
#include <deque>
#include <vector>
#include <stdint.h> //uint32_t
#include <functional>
#include <bitset>
using namespace std;
typedef long long ll;
typedef double lf;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector<pii> vpii;
typedef vector<int> vi;
#define __FastIO ios_base::sync_with_stdio(false); cin.tie(0)
#define For(i, a, b) for (__typeof (a) i=a; i<=b; i++)
#define Rof(i, b, a) for (__typeof (a) i=b; i>=a; i--)
#define Rep(i, n) for (__typeof (n) i=0; i<n; i++)
#define Forit(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i)
#define all(ar) ar.begin(), ar.end()
#define fill(ar, val) memset(ar, val, sizeof(ar))
#define clr(a) memset(a, 0, sizeof a)
#define nl cout << '\n';
#define sp cout << ' ';
#define gc getchar
#define chk cout << "##########\n"
#define pb push_back
#define debug1(x) cout << #x << ": " << x << endl
#define debug2(x, y) cout << #x << ": " << x << '\t' << #y << ": " << y << endl
#define debug3(x, y, z) cout << #x << ": " << x << '\t' << #y << ": " << y << '\t' << #z << ": " << z << endl
#define max(a, b) (a < b ? b : a)
#define min(a, b) (a > b ? b : a)
#define sq(a) (a * a)
#define PI acos(-1.0)
#define INF 0x7fffffff
#define MOD 1000000007
#define EPS 1e-10
#define MAX 10000005
////////////////////////// START HERE //////////////////////////
int main() {
__FastIO;
ll n, m, a;
cin >> n >> m >> a;
return !(cout << (((ll) round (ceil(n / (lf) a))) * \
((ll) round(ceil(m / (lf) a)))) << '\n');
}
<|endoftext|>
|
<commit_before>
#include <tree.hpp>
#include <catch.hpp>
SCENARIO("null")
{
Tree<int> a;
REQUIRE(a.tree_one()==NULL);
}
SCENARIO("add")
{
Tree <int> a;
bool b=a.add(5);
REQUIRE(b == 1);
}
SCENARIO("find")
{
Tree<int> a;
a.add(5);
bool b = a.find(5);
REQUIRE(b == 1);
}
SCENARIO("del1")
{
Tree<int> a;
a.add(5);
a.add(4);
a.add(7);
a.add(8);
a.add(2);
a.add(6);
a.del(7);
bool b = a.find(7);
REQUIRE(b == 0);
}
SCENARIO("del2")
{
Tree<int> a;
a.add(5);
a.add(4);
a.add(7);
a.add(8);
a.add(2);
a.add(6);
a.del(2);
bool b = a.find(2);
REQUIRE(b == 0);
}
SCENARIO("del3")
{
Tree<int> a;
a.add(5);
a.add(4);
a.add(7);
a.add(8);
a.add(2);
a.add(6);
a.add(1);
a.del(2);
bool b = a.find(2);
REQUIRE(b == 0);
}
SCENARIO("del4")
{
Tree<int> a;
a.add(5);
a.add(4);
a.add(7);
a.add(8);
a.add(2);
a.add(6);
a.add(3);
a.del(2);
bool b = a.find(2);
REQUIRE(b == 0);
}
SCENARIO("del5")
{
Tree<int> a;
a.add(5);
a.add(4);
a.add(7);
a.add(8);
a.add(2);
a.add(6);
a.add(3);
bool b = a.del(15);;
REQUIRE(b == 0);
}
SCENARIO("file")
{
Tree<int> a, c;
c.add(3);
c.add(2);
c.add(1);
c.add(5);
c.pr("Tr.txt");
a.file_tree("Tr.txt");
bool b = a.find(3);
REQUIRE(b == 1);
b = a.find(2);
REQUIRE(b == 1);
b = a.find(1);
REQUIRE(b == 1);
b = a.find(5);
REQUIRE(b == 1);
}
SCENARIO("BST delete non inserted element", "[delete]")
{
Tree<int> tree = {8};
REQUIRE( !tree.del(4) );
REQUIRE( !tree.isEmpty() );
}
SCENARIO("BST delete root without children", "[delete]")
{
Tree<int> tree = {8};
REQUIRE( tree.del(8) );
REQUIRE( tree.isEmpty() );
}
SCENARIO("BST delete root with one child", "[delete]")
{
Tree<int> tree = {8, 4, 3};
REQUIRE( tree.del(8) );
REQUIRE( tree == Tree<int>({4, 3}) );
}
SCENARIO("BST delete root with children", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(8) );
REQUIRE( tree == Tree<int>({9, 4, 3, 10, 13, 11, 12}) );
}
SCENARIO("BST delete non root without children", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(3) );
REQUIRE( tree == Tree<int>({8, 4, 10, 9, 13, 11, 12}) );
}
SCENARIO("BST delete non root with one child", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(11) );
REQUIRE( tree == Tree<int>({8, 4, 3, 10, 9, 13, 12}) );
}
SCENARIO("BST delete non root with children", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(10) );
REQUIRE( tree == Tree<int>({8, 4, 3, 11, 9, 13, 12}) );
}
<commit_msg>Update init.cpp<commit_after>
#include <tree.hpp>
#include <catch.hpp>
SCENARIO("null")
{
Tree<int> a;
REQUIRE(a.tree_one()==NULL);
}
SCENARIO("add")
{
Tree <int> a;
bool b=a.add(5);
REQUIRE(b == 1);
}
SCENARIO("find")
{
Tree<int> a;
a.add(5);
bool b = a.find(5);
REQUIRE(b == 1);
}
SCENARIO("file")
{
Tree<int> a, c;
c.add(3);
c.add(2);
c.add(1);
c.add(5);
c.pr("Tr.txt");
a.file_tree("Tr.txt");
bool b = a.find(3);
REQUIRE(b == 1);
b = a.find(2);
REQUIRE(b == 1);
b = a.find(1);
REQUIRE(b == 1);
b = a.find(5);
REQUIRE(b == 1);
}
SCENARIO("BST delete non inserted element", "[delete]")
{
Tree<int> tree = {8};
REQUIRE( !tree.del(4) );
REQUIRE( !tree.isEmpty() );
}
SCENARIO("BST delete root without children", "[delete]")
{
Tree<int> tree = {8};
REQUIRE( tree.del(8) );
REQUIRE( tree.isEmpty() );
}
SCENARIO("BST delete root with one child", "[delete]")
{
Tree<int> tree = {8, 4, 3};
REQUIRE( tree.del(8) );
REQUIRE( tree == Tree<int>({4, 3}) );
}
SCENARIO("BST delete root with children", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(8) );
REQUIRE( tree == Tree<int>({9, 4, 3, 10, 13, 11, 12}) );
}
SCENARIO("BST delete non root without children", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(3) );
REQUIRE( tree == Tree<int>({8, 4, 10, 9, 13, 11, 12}) );
}
SCENARIO("BST delete non root with one child", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(11) );
REQUIRE( tree == Tree<int>({8, 4, 3, 10, 9, 13, 12}) );
}
SCENARIO("BST delete non root with children", "[delete]")
{
Tree<int> tree = {8, 4, 3, 10, 9, 13, 11, 12};
REQUIRE( tree.del(10) );
REQUIRE( tree == Tree<int>({8, 4, 3, 11, 9, 13, 12}) );
}
<|endoftext|>
|
<commit_before>#include "taichi_grid.h"
#include <taichi/common/meta.h>
#include <tuple>
TC_NAMESPACE_BEGIN
namespace stencilang {
template <int _i, int _j, int _k>
struct Offset {
static constexpr int i = _i;
static constexpr int j = _j;
static constexpr int k = _k;
};
template <typename _a, typename _b>
struct Add {
using a = _a;
using b = _b;
static std::string serialize() {
return a::serialize() + " + " + b::serialize();
}
// args:
// 0: linearized based (output) address
// 1, ...: channels
template <typename... Args>
TC_FORCE_INLINE static auto evaluate(Args const &... args) {
auto ret_a = a::evaluate(args...);
auto ret_b = b::evaluate(args...);
return _mm256_add_ps(ret_a, ret_b);
}
};
template <int _channel, typename _offset>
struct Input {
static constexpr int channel = _channel;
using offset = _offset;
template <typename O>
auto operator+(const O &o) {
return Add<Input, O>();
}
static std::string serialize() {
return fmt::format("D{}({:+},{:+},{:+})", channel, offset::i, offset::j,
offset::k);
};
template <typename... Args>
TC_FORCE_INLINE static __m256 evaluate(Args const &... args) {
int base = std::get<0>(std::tuple<Args const &...>(args...));
using pad_type = typename std::decay_t<decltype(
std::get<channel + 1>(std::tuple<Args const &...>(args...)))>;
auto const &pad =
std::get<channel + 1>(std::tuple<Args const &...>(args...));
constexpr int offset =
pad_type::template relative_offset<offset::i, offset::j, offset::k>();
return _mm256_loadu_ps(&pad.linearized_data[base + offset]);
}
};
}
struct Node {
constexpr static int num_channels = 16;
using element_type = real;
/*
NodeFlags &flags() {
return bit::reinterpret_bits<NodeFlags>(channels[15]);
}
*/
};
template <>
constexpr bool is_SOA<Node>() {
return true;
}
using Block = TBlock<Node, char, TSize3D<8>, 0, 1>;
auto stencil = [](const std::vector<std::string> ¶ms) {
using namespace stencilang;
auto left = Input<0, Offset<0, 0, -1>>();
auto right = Input<0, Offset<0, 0, 1>>();
auto sum = left + right;
TC_P(sum.serialize());
using GridScratchPadCh = TGridScratchPad<Block, real>;
using GridScratchPadCh2 = TGridScratchPad<Block, real, 2>;
GridScratchPadCh2 pad;
for (auto ind : pad.region()) {
pad.node(ind) = ind.k;
}
float32 _ret[8];
auto ret = (__m256 *)&_ret[0];
*ret = sum.evaluate(1, pad);
TC_P(_ret);
};
TC_REGISTER_TASK(stencil);
TC_NAMESPACE_END
<commit_msg>test two pad case<commit_after>#include "taichi_grid.h"
#include <taichi/common/meta.h>
#include <tuple>
TC_NAMESPACE_BEGIN
namespace stencilang {
template <int _i, int _j, int _k>
struct Offset {
static constexpr int i = _i;
static constexpr int j = _j;
static constexpr int k = _k;
};
template <typename _a, typename _b>
struct Add {
using a = _a;
using b = _b;
static std::string serialize() {
return a::serialize() + " + " + b::serialize();
}
// args:
// 0: linearized based (output) address
// 1, ...: channels
template <typename... Args>
TC_FORCE_INLINE static auto evaluate(Args const &... args) {
auto ret_a = a::evaluate(args...);
auto ret_b = b::evaluate(args...);
return _mm256_add_ps(ret_a, ret_b);
}
};
template <int _channel, typename _offset>
struct Input {
static constexpr int channel = _channel;
using offset = _offset;
template <typename O>
auto operator+(const O &o) {
return Add<Input, O>();
}
static std::string serialize() {
return fmt::format("D{}({:+},{:+},{:+})", channel, offset::i, offset::j,
offset::k);
};
template <typename... Args>
TC_FORCE_INLINE static __m256 evaluate(Args const &... args) {
int base = std::get<0>(std::tuple<Args const &...>(args...));
using pad_type = typename std::decay_t<decltype(
std::get<channel + 1>(std::tuple<Args const &...>(args...)))>;
auto const &pad =
std::get<channel + 1>(std::tuple<Args const &...>(args...));
constexpr int offset =
pad_type::template relative_offset<offset::i, offset::j, offset::k>();
return _mm256_loadu_ps(&pad.linearized_data[base + offset]);
}
};
}
struct Node {
constexpr static int num_channels = 16;
using element_type = real;
/*
NodeFlags &flags() {
return bit::reinterpret_bits<NodeFlags>(channels[15]);
}
*/
};
template <>
constexpr bool is_SOA<Node>() {
return true;
}
using Block = TBlock<Node, char, TSize3D<8>, 0, 1>;
auto stencil = [](const std::vector<std::string> ¶ms) {
using namespace stencilang;
auto left = Input<0, Offset<0, 0, -1>>();
auto right = Input<1, Offset<0, 0, 1>>();
auto sum = left + right;
TC_P(sum.serialize());
using GridScratchPadCh = TGridScratchPad<Block, real>;
using GridScratchPadCh2 = TGridScratchPad<Block, real, 2>;
GridScratchPadCh2 pad1;
for (auto ind : pad1.region()) {
pad1.node(ind) = ind.k;
}
GridScratchPadCh2 pad2;
for (auto ind : pad1.region()) {
pad2.node(ind) = -ind.k;
}
float32 _ret[8];
auto ret = (__m256 *)&_ret[0];
*ret = sum.evaluate(1, pad1, pad2);
TC_P(_ret);
};
TC_REGISTER_TASK(stencil);
TC_NAMESPACE_END
<|endoftext|>
|
<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// 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 https://mozilla.org/MPL/2.0/.
#include "ImageDescriber_CCTAG.hpp"
#include <aliceVision/system/gpu.hpp>
#include <cctag/ICCTag.hpp>
#include <cctag/utils/LogTime.hpp>
//#define CPU_ADAPT_OF_GPU_PART //todo: #ifdef depreciated
#ifdef CPU_ADAPT_OF_GPU_PART
#include "cctag/progBase/MemoryPool.hpp"
#endif
namespace aliceVision {
namespace feature {
ImageDescriber_CCTAG::CCTagParameters::CCTagParameters(size_t nRings)
: _internalParams(new cctag::Parameters(nRings))
{
#ifdef WITH_CUDA // CCTAG_WITH_CUDA
_internalParams->_useCuda = system::gpuSupportCUDA(3,5);
else
_internalParams->_useCuda = false;
#endif
}
ImageDescriber_CCTAG::CCTagParameters::~CCTagParameters()
{
}
bool ImageDescriber_CCTAG::CCTagParameters::setPreset(EImageDescriberPreset preset)
{
switch(preset)
{
// Normal lighting conditions: normal contrast
case EImageDescriberPreset::LOW:
case EImageDescriberPreset::MEDIUM:
case EImageDescriberPreset::NORMAL:
_cannyThrLow = 0.01f;
_cannyThrHigh = 0.04f;
break;
// Low lighting conditions: very low contrast
case EImageDescriberPreset::HIGH:
case EImageDescriberPreset::ULTRA:
_cannyThrLow = 0.002f;
_cannyThrHigh = 0.01f;
break;
}
return true;
}
ImageDescriber_CCTAG::ImageDescriber_CCTAG(const std::size_t nRings)
: ImageDescriber()
, _params(nRings)
{}
ImageDescriber_CCTAG::~ImageDescriber_CCTAG()
{
}
bool ImageDescriber_CCTAG::useCuda() const
{
return _params._internalParams->_useCuda;
}
void ImageDescriber_CCTAG::allocate(std::unique_ptr<Regions> ®ions) const
{
regions.reset( new CCTAG_Regions );
}
void ImageDescriber_CCTAG::setConfigurationPreset(EImageDescriberPreset preset)
{
_params.setPreset(preset);
}
EImageDescriberType ImageDescriber_CCTAG::getDescriberType() const
{
if(_params._internalParams->_nCrowns == 3)
return EImageDescriberType::CCTAG3;
if(_params._internalParams->_nCrowns == 4)
return EImageDescriberType::CCTAG4;
throw std::out_of_range("Invalid number of rings, can't find CCTag imageDescriber type !");
}
void ImageDescriber_CCTAG::setUseCuda(bool useCuda)
{
_params._internalParams->_useCuda = useCuda;
}
bool ImageDescriber_CCTAG::describe(const image::Image<unsigned char>& image,
std::unique_ptr<Regions> ®ions,
const image::Image<unsigned char> * mask)
{
if ( !_doAppend )
allocate(regions);
// else regions are added to the current vector of features/descriptors
// Build alias to cached data
CCTAG_Regions * regionsCasted = dynamic_cast<CCTAG_Regions*>(regions.get());
// reserve some memory for faster keypoint saving
regionsCasted->Features().reserve(regionsCasted->Features().size() + 50);
regionsCasted->Descriptors().reserve(regionsCasted->Descriptors().size() + 50);
boost::ptr_list<cctag::ICCTag> cctags;
cctag::logtime::Mgmt* durations = new cctag::logtime::Mgmt( 25 );
// cctag::CCTagMarkersBank bank(_params._nCrowns);
#ifndef CPU_ADAPT_OF_GPU_PART
const cv::Mat graySrc(cv::Size(image.Width(), image.Height()), CV_8UC1, (unsigned char *) image.data(), cv::Mat::AUTO_STEP);
//// Invert the image
//cv::Mat invertImg;
//cv::bitwise_not(graySrc,invertImg);
cctag::cctagDetection(cctags, _cudaPipe, 1,graySrc, *_params._internalParams, durations);
#else //todo: #ifdef depreciated
cctag::MemoryPool::instance().updateMemoryAuthorizedWithRAM();
cctag::View cctagView((const unsigned char *) image.data(), image.Width(), image.Height(), image.Depth()*image.Width());
boost::ptr_list<cctag::ICCTag> cctags;
cctag::cctagDetection(cctags, _cudaPipe, 1 ,cctagView._grayView ,*_params._internalParams, durations );
#endif
durations->print( std::cerr );
for (const auto & cctag : cctags)
{
if ( cctag.getStatus() > 0 )
{
ALICEVISION_LOG_DEBUG(" New CCTag: Id" << cctag.id() << " ; Location ( " << cctag.x() << " , " << cctag.y() << " ) ");
// Add its associated descriptor
Descriptor<unsigned char,128> desc;
for(std::size_t i=0; i< desc.size(); ++i)
{
desc[i] = (unsigned char) 0;
}
desc[cctag.id()] = (unsigned char) 255;
regionsCasted->Descriptors().push_back(desc);
regionsCasted->Features().push_back(SIOPointFeature(cctag.x(), cctag.y()));
}
}
cctags.clear();
return true;
}
} // namespace feature
} // namespace aliceVision
<commit_msg>[feature] cctag: build typo fix<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2016 AliceVision contributors.
// Copyright (c) 2012 openMVG contributors.
// 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 https://mozilla.org/MPL/2.0/.
#include "ImageDescriber_CCTAG.hpp"
#include <aliceVision/system/gpu.hpp>
#include <cctag/ICCTag.hpp>
#include <cctag/utils/LogTime.hpp>
//#define CPU_ADAPT_OF_GPU_PART //todo: #ifdef depreciated
#ifdef CPU_ADAPT_OF_GPU_PART
#include "cctag/progBase/MemoryPool.hpp"
#endif
namespace aliceVision {
namespace feature {
ImageDescriber_CCTAG::CCTagParameters::CCTagParameters(size_t nRings)
: _internalParams(new cctag::Parameters(nRings))
{
#ifdef WITH_CUDA // CCTAG_WITH_CUDA
_internalParams->_useCuda = system::gpuSupportCUDA(3,5);
#else
_internalParams->_useCuda = false;
#endif
}
ImageDescriber_CCTAG::CCTagParameters::~CCTagParameters()
{
}
bool ImageDescriber_CCTAG::CCTagParameters::setPreset(EImageDescriberPreset preset)
{
switch(preset)
{
// Normal lighting conditions: normal contrast
case EImageDescriberPreset::LOW:
case EImageDescriberPreset::MEDIUM:
case EImageDescriberPreset::NORMAL:
_cannyThrLow = 0.01f;
_cannyThrHigh = 0.04f;
break;
// Low lighting conditions: very low contrast
case EImageDescriberPreset::HIGH:
case EImageDescriberPreset::ULTRA:
_cannyThrLow = 0.002f;
_cannyThrHigh = 0.01f;
break;
}
return true;
}
ImageDescriber_CCTAG::ImageDescriber_CCTAG(const std::size_t nRings)
: ImageDescriber()
, _params(nRings)
{}
ImageDescriber_CCTAG::~ImageDescriber_CCTAG()
{
}
bool ImageDescriber_CCTAG::useCuda() const
{
return _params._internalParams->_useCuda;
}
void ImageDescriber_CCTAG::allocate(std::unique_ptr<Regions> ®ions) const
{
regions.reset( new CCTAG_Regions );
}
void ImageDescriber_CCTAG::setConfigurationPreset(EImageDescriberPreset preset)
{
_params.setPreset(preset);
}
EImageDescriberType ImageDescriber_CCTAG::getDescriberType() const
{
if(_params._internalParams->_nCrowns == 3)
return EImageDescriberType::CCTAG3;
if(_params._internalParams->_nCrowns == 4)
return EImageDescriberType::CCTAG4;
throw std::out_of_range("Invalid number of rings, can't find CCTag imageDescriber type !");
}
void ImageDescriber_CCTAG::setUseCuda(bool useCuda)
{
_params._internalParams->_useCuda = useCuda;
}
bool ImageDescriber_CCTAG::describe(const image::Image<unsigned char>& image,
std::unique_ptr<Regions> ®ions,
const image::Image<unsigned char> * mask)
{
if ( !_doAppend )
allocate(regions);
// else regions are added to the current vector of features/descriptors
// Build alias to cached data
CCTAG_Regions * regionsCasted = dynamic_cast<CCTAG_Regions*>(regions.get());
// reserve some memory for faster keypoint saving
regionsCasted->Features().reserve(regionsCasted->Features().size() + 50);
regionsCasted->Descriptors().reserve(regionsCasted->Descriptors().size() + 50);
boost::ptr_list<cctag::ICCTag> cctags;
cctag::logtime::Mgmt* durations = new cctag::logtime::Mgmt( 25 );
// cctag::CCTagMarkersBank bank(_params._nCrowns);
#ifndef CPU_ADAPT_OF_GPU_PART
const cv::Mat graySrc(cv::Size(image.Width(), image.Height()), CV_8UC1, (unsigned char *) image.data(), cv::Mat::AUTO_STEP);
//// Invert the image
//cv::Mat invertImg;
//cv::bitwise_not(graySrc,invertImg);
cctag::cctagDetection(cctags, _cudaPipe, 1,graySrc, *_params._internalParams, durations);
#else //todo: #ifdef depreciated
cctag::MemoryPool::instance().updateMemoryAuthorizedWithRAM();
cctag::View cctagView((const unsigned char *) image.data(), image.Width(), image.Height(), image.Depth()*image.Width());
boost::ptr_list<cctag::ICCTag> cctags;
cctag::cctagDetection(cctags, _cudaPipe, 1 ,cctagView._grayView ,*_params._internalParams, durations );
#endif
durations->print( std::cerr );
for (const auto & cctag : cctags)
{
if ( cctag.getStatus() > 0 )
{
ALICEVISION_LOG_DEBUG(" New CCTag: Id" << cctag.id() << " ; Location ( " << cctag.x() << " , " << cctag.y() << " ) ");
// Add its associated descriptor
Descriptor<unsigned char,128> desc;
for(std::size_t i=0; i< desc.size(); ++i)
{
desc[i] = (unsigned char) 0;
}
desc[cctag.id()] = (unsigned char) 255;
regionsCasted->Descriptors().push_back(desc);
regionsCasted->Features().push_back(SIOPointFeature(cctag.x(), cctag.y()));
}
}
cctags.clear();
return true;
}
} // namespace feature
} // namespace aliceVision
<|endoftext|>
|
<commit_before>#include <binary_search_tree.hpp>
#include <catch.hpp>
SCENARIO("default constructor")
{
BinarySearchTree<int> bst;
REQUIRE(bst.root() == nullptr);
}
SCENARIO("insertElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE(bst.value_() == 7);
REQUIRE(bst.leftNode_() == nullptr);
REQUIRE(bst.rightNode_() == nullptr);
}
SCENARIO("findElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE( bst.isFound(7) == 1);
}
SCENARIO("infile")
{
BinarySearchTree<int> bst;
bst.infile("file.txt");
REQUIRE( bst.count() == 0);
}
SCENARIO("_count")
{
BinarySearchTree<int> bst;
int count = 0;
bst.insert(7);
count = bst._count();
REQUIRE( count == 1);
}
<commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp>
#include <catch.hpp>
SCENARIO("default constructor")
{
BinarySearchTree<int> bst;
REQUIRE(bst.root() == nullptr);
}
SCENARIO("insertElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE(bst.value_() == 7);
REQUIRE(bst.leftNode_() == nullptr);
REQUIRE(bst.rightNode_() == nullptr);
}
SCENARIO("findElement")
{
BinarySearchTree<int> bst;
bst.insert(7);
REQUIRE( bst.isFound(7) == 1);
}
SCENARIO("infile")
{
BinarySearchTree<int> bst;
bst.infile("file.txt");
REQUIRE( bst.count() == 0);
}
SCENARIO("_count")
{
BinarySearchTree<int> bst;
int count = 0;
bst.insert(7);
count = bst.count(bst._root());
REQUIRE( count == 1);
}
<|endoftext|>
|
<commit_before><commit_msg>~SdUnoPageBackground() gets a SolarMutexGuard<commit_after><|endoftext|>
|
<commit_before>/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <python/helpers/python_exceptions.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_cluster.h>
#include <vistk/python/util/python_gil.h>
#include <boost/python/args.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/module.hpp>
#include <boost/python/override.hpp>
/**
* \file process_cluster.cxx
*
* \brief Python bindings for \link vistk::process_cluster\endlink.
*/
using namespace boost::python;
class wrap_process_cluster
: public vistk::process_cluster
, public wrapper<vistk::process_cluster>
{
public:
wrap_process_cluster(vistk::config_t const& config);
~wrap_process_cluster();
properties_t _base_properties() const;
void _base_reconfigure(vistk::config_t const& conf);
vistk::processes_t processes() const;
connections_t input_mappings() const;
connections_t output_mappings() const;
connections_t internal_connections() const;
void _map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key);
void _add_process(name_t const& name_, type_t const& type_, vistk::config_t const& config);
void _map_input(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _map_output(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port);
properties_t _properties() const;
void _reconfigure(vistk::config_t const& conf);
void _declare_input_port(port_t const& port, port_info_t const& info);
void _declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_output_port(port_t const& port, port_info_t const& info);
void _declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info);
void _declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_);
};
static object cluster_from_process(vistk::process_t const& process);
BOOST_PYTHON_MODULE(process_cluster)
{
class_<wrap_process_cluster, boost::noncopyable>("PythonProcessCluster"
, "The base class for Python process clusters."
, no_init)
.def(init<vistk::config_t>())
.def("name", &vistk::process::name
, "Returns the name of the process.")
.def("type", &vistk::process::type
, "Returns the type of the process.")
.def_readonly("type_any", &vistk::process::type_any)
.def_readonly("type_none", &vistk::process::type_none)
.def_readonly("type_data_dependent", &vistk::process::type_data_dependent)
.def_readonly("type_flow_dependent", &vistk::process::type_flow_dependent)
.def_readonly("flag_output_const", &vistk::process::flag_output_const)
.def_readonly("flag_input_static", &vistk::process::flag_input_static)
.def_readonly("flag_input_mutable", &vistk::process::flag_input_mutable)
.def_readonly("flag_input_nodep", &vistk::process::flag_input_nodep)
.def_readonly("flag_required", &vistk::process::flag_required)
.def("_base_properties", &wrap_process_cluster::_base_properties
, "Base class properties.")
.def("_base_reconfigure", &wrap_process_cluster::_base_reconfigure
, (arg("config"))
, "Base class reconfigure.")
.def("map_config", &wrap_process_cluster::_map_config
, (arg("key"), arg("name"), arg("mapped_key"))
, "Map a configuration value to a process.")
.def("add_process", &wrap_process_cluster::_add_process
, (arg("name"), arg("type"), arg("config") = vistk::config::empty_config())
, "Add a process to the cluster.")
.def("map_input", &wrap_process_cluster::_map_input
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map a port on the cluster to an input port.")
.def("map_output", &wrap_process_cluster::_map_output
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map an output port to a port on the cluster.")
.def("connect", &wrap_process_cluster::_connect
, (arg("upstream_name"), arg("upstream_port"), arg("downstream_name"), arg("downstream_port"))
, "Connect two ports within the cluster.")
.def("_properties", &wrap_process_cluster::_properties, &wrap_process_cluster::_base_properties
, "The properties on the subclass.")
.def("_reconfigure", &wrap_process_cluster::_reconfigure, &wrap_process_cluster::_base_reconfigure
, (arg("config"))
, "Runtime configuration for subclasses.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port
, (arg("port"), arg("info"))
, "Declare an input port on the process.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an input port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port
, (arg("port"), arg("info"))
, "Declare an output port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an output port on the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key
, (arg("key"), arg("info"))
, "Declare a configuration key for the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key_1
, (arg("key"), arg("default"), arg("description"))
, "Declare a configuration key for the process.")
.def("processes", &vistk::process_cluster::processes
, "Processes in the cluster.")
.def("input_mappings", &vistk::process_cluster::input_mappings
, "Input mappings for the cluster.")
.def("output_mappings", &vistk::process_cluster::output_mappings
, "Output mappings for the cluster.")
.def("internal_connections", &vistk::process_cluster::internal_connections
, "Connections internal to the cluster.")
;
def("cluster_from_process", cluster_from_process
, (arg("process"))
, "Returns the process as a cluster or None if the process is not a cluster.");
implicitly_convertible<vistk::process_cluster_t, vistk::process_t>();
}
wrap_process_cluster
::wrap_process_cluster(vistk::config_t const& config)
: vistk::process_cluster(config)
{
}
wrap_process_cluster
::~wrap_process_cluster()
{
}
vistk::process::properties_t
wrap_process_cluster
::_base_properties() const
{
return process_cluster::_properties();
}
void
wrap_process_cluster
::_base_reconfigure(vistk::config_t const& conf)
{
return process_cluster::_reconfigure(conf);
}
void
wrap_process_cluster
::_map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key)
{
map_config(key, name_, mapped_key);
}
void
wrap_process_cluster
::_add_process(name_t const& name_, type_t const& type_, vistk::config_t const& conf)
{
add_process(name_, type_, conf);
}
void
wrap_process_cluster
::_map_input(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_input(port, name_, mapped_port);
}
void
wrap_process_cluster
::_map_output(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_output(port, name_, mapped_port);
}
void
wrap_process_cluster
::_connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port)
{
connect(upstream_name, upstream_port,
downstream_name, downstream_port);
}
vistk::process::properties_t
wrap_process_cluster
::_properties() const
{
{
vistk::python::python_gil const gil;
(void)gil;
override const f = get_override("_properties");
if (f)
{
HANDLE_PYTHON_EXCEPTION(return f())
}
}
return _base_properties();
}
void
wrap_process_cluster
::_reconfigure(vistk::config_t const& conf)
{
{
vistk::python::python_gil const gil;
(void)gil;
override const f = get_override("_reconfigure");
if (f)
{
HANDLE_PYTHON_EXCEPTION(f(conf))
}
}
_base_reconfigure(conf);
}
void
wrap_process_cluster
::_declare_input_port(port_t const& port, port_info_t const& info)
{
declare_input_port(port, info);
}
void
wrap_process_cluster
::_declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_input_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_output_port(port_t const& port, port_info_t const& info)
{
declare_output_port(port, info);
}
void
wrap_process_cluster
::_declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_output_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info)
{
declare_configuration_key(key, info);
}
void
wrap_process_cluster
::_declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_)
{
declare_configuration_key(key, def_, description_);
}
object
cluster_from_process(vistk::process_t const& process)
{
vistk::process_cluster_t const cluster = boost::dynamic_pointer_cast<vistk::process_cluster>(process);
if (!cluster)
{
return object();
}
return object(cluster);
}
<commit_msg>Add missing return<commit_after>/*ckwg +5
* Copyright 2012-2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include <python/helpers/python_exceptions.h>
#include <vistk/pipeline/config.h>
#include <vistk/pipeline/process.h>
#include <vistk/pipeline/process_cluster.h>
#include <vistk/python/util/python_gil.h>
#include <boost/python/args.hpp>
#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/module.hpp>
#include <boost/python/override.hpp>
/**
* \file process_cluster.cxx
*
* \brief Python bindings for \link vistk::process_cluster\endlink.
*/
using namespace boost::python;
class wrap_process_cluster
: public vistk::process_cluster
, public wrapper<vistk::process_cluster>
{
public:
wrap_process_cluster(vistk::config_t const& config);
~wrap_process_cluster();
properties_t _base_properties() const;
void _base_reconfigure(vistk::config_t const& conf);
vistk::processes_t processes() const;
connections_t input_mappings() const;
connections_t output_mappings() const;
connections_t internal_connections() const;
void _map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key);
void _add_process(name_t const& name_, type_t const& type_, vistk::config_t const& config);
void _map_input(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _map_output(port_t const& port, name_t const& name_, port_t const& mapped_port);
void _connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port);
properties_t _properties() const;
void _reconfigure(vistk::config_t const& conf);
void _declare_input_port(port_t const& port, port_info_t const& info);
void _declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_output_port(port_t const& port, port_info_t const& info);
void _declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_);
void _declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info);
void _declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_);
};
static object cluster_from_process(vistk::process_t const& process);
BOOST_PYTHON_MODULE(process_cluster)
{
class_<wrap_process_cluster, boost::noncopyable>("PythonProcessCluster"
, "The base class for Python process clusters."
, no_init)
.def(init<vistk::config_t>())
.def("name", &vistk::process::name
, "Returns the name of the process.")
.def("type", &vistk::process::type
, "Returns the type of the process.")
.def_readonly("type_any", &vistk::process::type_any)
.def_readonly("type_none", &vistk::process::type_none)
.def_readonly("type_data_dependent", &vistk::process::type_data_dependent)
.def_readonly("type_flow_dependent", &vistk::process::type_flow_dependent)
.def_readonly("flag_output_const", &vistk::process::flag_output_const)
.def_readonly("flag_input_static", &vistk::process::flag_input_static)
.def_readonly("flag_input_mutable", &vistk::process::flag_input_mutable)
.def_readonly("flag_input_nodep", &vistk::process::flag_input_nodep)
.def_readonly("flag_required", &vistk::process::flag_required)
.def("_base_properties", &wrap_process_cluster::_base_properties
, "Base class properties.")
.def("_base_reconfigure", &wrap_process_cluster::_base_reconfigure
, (arg("config"))
, "Base class reconfigure.")
.def("map_config", &wrap_process_cluster::_map_config
, (arg("key"), arg("name"), arg("mapped_key"))
, "Map a configuration value to a process.")
.def("add_process", &wrap_process_cluster::_add_process
, (arg("name"), arg("type"), arg("config") = vistk::config::empty_config())
, "Add a process to the cluster.")
.def("map_input", &wrap_process_cluster::_map_input
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map a port on the cluster to an input port.")
.def("map_output", &wrap_process_cluster::_map_output
, (arg("port"), arg("name"), arg("mapped_port"))
, "Map an output port to a port on the cluster.")
.def("connect", &wrap_process_cluster::_connect
, (arg("upstream_name"), arg("upstream_port"), arg("downstream_name"), arg("downstream_port"))
, "Connect two ports within the cluster.")
.def("_properties", &wrap_process_cluster::_properties, &wrap_process_cluster::_base_properties
, "The properties on the subclass.")
.def("_reconfigure", &wrap_process_cluster::_reconfigure, &wrap_process_cluster::_base_reconfigure
, (arg("config"))
, "Runtime configuration for subclasses.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port
, (arg("port"), arg("info"))
, "Declare an input port on the process.")
.def("declare_input_port", &wrap_process_cluster::_declare_input_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an input port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port
, (arg("port"), arg("info"))
, "Declare an output port on the process.")
.def("declare_output_port", &wrap_process_cluster::_declare_output_port_1
, (arg("port"), arg("type"), arg("flags"), arg("description"), arg("frequency") = vistk::process::port_frequency_t(1))
, "Declare an output port on the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key
, (arg("key"), arg("info"))
, "Declare a configuration key for the process.")
.def("declare_configuration_key", &wrap_process_cluster::_declare_configuration_key_1
, (arg("key"), arg("default"), arg("description"))
, "Declare a configuration key for the process.")
.def("processes", &vistk::process_cluster::processes
, "Processes in the cluster.")
.def("input_mappings", &vistk::process_cluster::input_mappings
, "Input mappings for the cluster.")
.def("output_mappings", &vistk::process_cluster::output_mappings
, "Output mappings for the cluster.")
.def("internal_connections", &vistk::process_cluster::internal_connections
, "Connections internal to the cluster.")
;
def("cluster_from_process", cluster_from_process
, (arg("process"))
, "Returns the process as a cluster or None if the process is not a cluster.");
implicitly_convertible<vistk::process_cluster_t, vistk::process_t>();
}
wrap_process_cluster
::wrap_process_cluster(vistk::config_t const& config)
: vistk::process_cluster(config)
{
}
wrap_process_cluster
::~wrap_process_cluster()
{
}
vistk::process::properties_t
wrap_process_cluster
::_base_properties() const
{
return process_cluster::_properties();
}
void
wrap_process_cluster
::_base_reconfigure(vistk::config_t const& conf)
{
return process_cluster::_reconfigure(conf);
}
void
wrap_process_cluster
::_map_config(vistk::config::key_t const& key, name_t const& name_, vistk::config::key_t const& mapped_key)
{
map_config(key, name_, mapped_key);
}
void
wrap_process_cluster
::_add_process(name_t const& name_, type_t const& type_, vistk::config_t const& conf)
{
add_process(name_, type_, conf);
}
void
wrap_process_cluster
::_map_input(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_input(port, name_, mapped_port);
}
void
wrap_process_cluster
::_map_output(port_t const& port, name_t const& name_, port_t const& mapped_port)
{
map_output(port, name_, mapped_port);
}
void
wrap_process_cluster
::_connect(name_t const& upstream_name, port_t const& upstream_port,
name_t const& downstream_name, port_t const& downstream_port)
{
connect(upstream_name, upstream_port,
downstream_name, downstream_port);
}
vistk::process::properties_t
wrap_process_cluster
::_properties() const
{
{
vistk::python::python_gil const gil;
(void)gil;
override const f = get_override("_properties");
if (f)
{
HANDLE_PYTHON_EXCEPTION(return f())
}
}
return _base_properties();
}
void
wrap_process_cluster
::_reconfigure(vistk::config_t const& conf)
{
{
vistk::python::python_gil const gil;
(void)gil;
override const f = get_override("_reconfigure");
if (f)
{
HANDLE_PYTHON_EXCEPTION(f(conf))
return;
}
}
_base_reconfigure(conf);
}
void
wrap_process_cluster
::_declare_input_port(port_t const& port, port_info_t const& info)
{
declare_input_port(port, info);
}
void
wrap_process_cluster
::_declare_input_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_input_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_output_port(port_t const& port, port_info_t const& info)
{
declare_output_port(port, info);
}
void
wrap_process_cluster
::_declare_output_port_1(port_t const& port,
port_type_t const& type_,
port_flags_t const& flags_,
port_description_t const& description_,
port_frequency_t const& frequency_)
{
declare_output_port(port, type_, flags_, description_, frequency_);
}
void
wrap_process_cluster
::_declare_configuration_key(vistk::config::key_t const& key, conf_info_t const& info)
{
declare_configuration_key(key, info);
}
void
wrap_process_cluster
::_declare_configuration_key_1(vistk::config::key_t const& key,
vistk::config::value_t const& def_,
vistk::config::description_t const& description_)
{
declare_configuration_key(key, def_, description_);
}
object
cluster_from_process(vistk::process_t const& process)
{
vistk::process_cluster_t const cluster = boost::dynamic_pointer_cast<vistk::process_cluster>(process);
if (!cluster)
{
return object();
}
return object(cluster);
}
<|endoftext|>
|
<commit_before>#include "BVSConfig.h"
#include<iostream>
#include<fstream>
BVSConfig::BVSConfig(std::string name, int argc, char** argv)
: name(name)
, mutex()
, optionStore()
{
if (argc!=0 && argv!=nullptr)
{
loadCommandLine(argc, argv);
}
}
BVSConfig& BVSConfig::getName(std::string& name)
{
name = name;
return *this;
}
BVSConfig& BVSConfig::showOptionStore()
{
// TODO lock guard
mutex.lock();
std::cout << "[BVSConfig] OPTION = VALUE" << std::endl;
for ( auto it : optionStore)
{
std::cout << "[BVSConfig] " << it.first << " = " << it.second << std::endl;
}
mutex.unlock();
return *this;
}
std::map<std::string, std::string> BVSConfig::dumpOptionStore()
{
// TODO lock guard
mutex.lock();
std::map<std::string, std::string> dump = optionStore;
mutex.unlock();
return dump;
}
BVSConfig& BVSConfig::loadCommandLine(int argc, char** argv)
{
/* algorithm:
* FOR EACH command line argument
* DO
* CASE --bvs.config=...
* CHECK missing argument
* SAVE config path
* CASE --bvs.options=...
* CHECK missing argument
* SEPARATE option list into option=value pairs and add
* DONE
*/
// search for --bvs.* command line options
std::string option;
std::string configFile;
for (int i=1; i<argc; i++)
{
option = argv[i];
// check for config
if (!option.compare(0, 13, "--bvs.config="))
{
option.erase(0, 13);
// check for missing argument
if (option.empty())
{
std::cerr << "[ERROR|BVSConfig] no argument after --bvs.config=" << std::endl;
exit(1);
}
// save config file for later use
configFile = option;
//std::cout << "[BVSConfig] --bvs.config: " << configFile << std::endl;
}
// check for additional options
if (!option.compare(0, 14, "--bvs.options="))
{
option.erase(0,14);
// check for missing argument
if (option.empty())
{
std::cerr<< "[ERROR|BVSConfig] no argument after --bvs.options=" << std::endl;
exit(1);
}
//std::cout << "[BVSConfig] --bvs.options: " << option << std::endl;
// separate option string and add to optionStore
std::string bvsOption;
size_t separatorPos = 0;
size_t equalPos;
mutex.lock();
while (separatorPos != std::string::npos)
{
separatorPos = option.find_first_of(':');
bvsOption = option.substr(0, separatorPos);
equalPos = bvsOption.find_first_of("=");
optionStore[bvsOption.substr(0, equalPos)] = bvsOption.substr(equalPos+1, bvsOption.size());
//std::cout << "[BVSConfig] adding: " << bvsOption.substr(0, equalPos) << " -> " << bvsOption.substr(equalPos+1, bvsOption.size()) << std::endl;
option.erase(0, separatorPos+1);
}
mutex.unlock();
}
}
if (!configFile.empty()) loadConfigFile(configFile);
return *this;
}
BVSConfig& BVSConfig::loadConfigFile(const std::string& configFile)
{
std::ifstream file(configFile.c_str(), std::ifstream::in);
std::string line;
std::string tmp;
std::string option;
std::string section;
bool insideQuotes;
bool append;
size_t pos;
size_t posComment;
int lineNumber = 0;
// check if file can be read from
if (!file.is_open())
{
std::cerr << "[ERROR|BVSConfig] file not found: " << configFile << std::endl;
exit(1);
}
/* algorithm:
* FOR EACH line in config file
* DO
* REMOVE all whitespace/tabs, except inside '' and "" pairs
* CHECK for ' and "
* CHECK for inside quotation
* CHECK for whitespace/tabs
* IGNORE comments and empty lines
* CHECK for section [...]
* CHECK section status
* CHECK for +option (appending)
* FIND delimiter
* APPEND option if set
* CHECK if option exists
* ADD option if not already in store
* DONE
*/
// parse file
// TODO lock guard
mutex.lock();
while(getline(file, line))
{
tmp.clear();
insideQuotes = false;
append = false;
lineNumber++;
//remove all whitespace/tabs except inside of '' or "" (useful for whitespace in for example status messages or other output)
for (unsigned int i=0; i<line.length(); i++)
{
// check quotation status, ignore character
if (line[i]=='\'' || line [i]=='"')
{
insideQuotes = !insideQuotes;
continue;
}
// add everything inside quotations
if (insideQuotes)
{
tmp += line[i];
continue;
}
// add only if not whitespace/tabs
if (line[i]!=' ' && line[i]!='\t') tmp += line[i];
}
// ignore comments and empty lines
if (tmp[0]=='#' || tmp.length()==0) continue;
// check for section
if (tmp[0]=='[')
{
pos = tmp.find_first_of(']');
section = tmp.substr(1, pos-1);
continue;
}
// ignore option if section empty
if (section.empty())
{
std::cerr << "[ERROR|BVSConfig] found option belonging to no section in " << configFile << ":" << lineNumber << ": " << line << std::endl;
exit(1);
}
// check for +option (appending)
if (tmp[0]=='+')
{
append = true;
tmp.erase(0, 1);
}
// find '=' delimiter and prepend section name
pos = tmp.find_first_of('=');
option = section + '.' + tmp.substr(0, pos);
// check for empty option name
if (option.length()==section.length()+1 )
{
std::cerr << "[ERROR|BVSConfig] found line starting with '=' in " << configFile << ":" << lineNumber << ": " << line << std::endl;
exit(1);
}
// strip inline comment
posComment = tmp.find_first_of('#');
tmp = tmp.substr(pos+1, posComment-pos-1);
// append option if set
if (append)
{
// check if option exists
if (optionStore.find(option)==optionStore.end())
{
std::cerr << "[ERROR|BVSConfig] cannot append to non existing option in " << configFile << ":" << lineNumber << ": " << line << std::endl;
exit(1);
}
optionStore[option] = optionStore[option] + "," + tmp;
continue;
}
// only add when not already in store, thus command-line options can override config file options and first occurence is used
if (optionStore.find(option)==optionStore.end())
{
optionStore[option] = tmp;
//std::cout << "[BVSConfig] adding: " << option << " -> " << tmp.substr(pos+1, posComment-pos-1) << std::endl;
}
}
mutex.unlock();
return *this;
}
std::string BVSConfig::searchOption(const std::string& option)
{
// TODO lock guard
mutex.lock();
// search for option in store
if(optionStore.find(option)!=optionStore.end())
{
//std::cout << "found: " << option << " --> " << optionStore[option] << std::endl;
std::string tmp = optionStore[option];
mutex.unlock();
return tmp;
}
else
{
std::cerr << "[ERROR|BVSConfig] option not found: " << option << std::endl;
exit(-1);
}
}
template<> BVSConfig& BVSConfig::convertStringTo<std::string>(const std::string& input, std::string& output)
{
output = input;
return *this;
}
template<> BVSConfig& BVSConfig::convertStringTo<bool>(const std::string& input, bool& b)
{
// check for possible matches to various versions meaning true
if (input=="1" || input=="true" || input=="True" || input=="TRUE" || input=="on" || input=="On" || input=="ON" || input=="yes" || input=="Yes" || input=="YES")
{
b = true;
}
else
{
b = false;
}
return *this;
}
<commit_msg>config: add todo<commit_after>#include "BVSConfig.h"
#include<iostream>
#include<fstream>
BVSConfig::BVSConfig(std::string name, int argc, char** argv)
: name(name)
, mutex()
, optionStore()
{
if (argc!=0 && argv!=nullptr)
{
loadCommandLine(argc, argv);
}
}
BVSConfig& BVSConfig::getName(std::string& name)
{
name = name;
return *this;
}
BVSConfig& BVSConfig::showOptionStore()
{
// TODO lock guard
mutex.lock();
std::cout << "[BVSConfig] OPTION = VALUE" << std::endl;
for ( auto it : optionStore)
{
std::cout << "[BVSConfig] " << it.first << " = " << it.second << std::endl;
}
mutex.unlock();
return *this;
}
std::map<std::string, std::string> BVSConfig::dumpOptionStore()
{
// TODO lock guard
mutex.lock();
std::map<std::string, std::string> dump = optionStore;
mutex.unlock();
return dump;
}
BVSConfig& BVSConfig::loadCommandLine(int argc, char** argv)
{
/* algorithm:
* FOR EACH command line argument
* DO
* CASE --bvs.config=...
* CHECK missing argument
* SAVE config path
* CASE --bvs.options=...
* CHECK missing argument
* SEPARATE option list into option=value pairs and add
* DONE
*/
// search for --bvs.* command line options
std::string option;
std::string configFile;
for (int i=1; i<argc; i++)
{
option = argv[i];
// check for config
if (!option.compare(0, 13, "--bvs.config="))
{
option.erase(0, 13);
// check for missing argument
if (option.empty())
{
std::cerr << "[ERROR|BVSConfig] no argument after --bvs.config=" << std::endl;
exit(1);
}
// save config file for later use
configFile = option;
//std::cout << "[BVSConfig] --bvs.config: " << configFile << std::endl;
}
// check for additional options
if (!option.compare(0, 14, "--bvs.options="))
{
option.erase(0,14);
// check for missing argument
if (option.empty())
{
std::cerr<< "[ERROR|BVSConfig] no argument after --bvs.options=" << std::endl;
exit(1);
}
//std::cout << "[BVSConfig] --bvs.options: " << option << std::endl;
// separate option string and add to optionStore
std::string bvsOption;
size_t separatorPos = 0;
size_t equalPos;
mutex.lock();
while (separatorPos != std::string::npos)
{
separatorPos = option.find_first_of(':');
bvsOption = option.substr(0, separatorPos);
equalPos = bvsOption.find_first_of("=");
optionStore[bvsOption.substr(0, equalPos)] = bvsOption.substr(equalPos+1, bvsOption.size());
//std::cout << "[BVSConfig] adding: " << bvsOption.substr(0, equalPos) << " -> " << bvsOption.substr(equalPos+1, bvsOption.size()) << std::endl;
option.erase(0, separatorPos+1);
}
mutex.unlock();
}
}
if (!configFile.empty()) loadConfigFile(configFile);
return *this;
}
BVSConfig& BVSConfig::loadConfigFile(const std::string& configFile)
{
std::ifstream file(configFile.c_str(), std::ifstream::in);
std::string line;
std::string tmp;
std::string option;
std::string section;
bool insideQuotes;
bool append;
size_t pos;
size_t posComment;
int lineNumber = 0;
// check if file can be read from
if (!file.is_open())
{
std::cerr << "[ERROR|BVSConfig] file not found: " << configFile << std::endl;
exit(1);
}
/* algorithm:
* FOR EACH line in config file
* DO
* REMOVE all whitespace/tabs, except inside '' and "" pairs
* CHECK for ' and "
* CHECK for inside quotation
* CHECK for whitespace/tabs
* IGNORE comments and empty lines
* CHECK for section [...]
* CHECK section status
* CHECK for +option (appending)
* FIND delimiter
* APPEND option if set
* CHECK if option exists
* ADD option if not already in store
* DONE
*/
// parse file
// TODO lock guard
mutex.lock();
while(getline(file, line))
{
tmp.clear();
insideQuotes = false;
append = false;
lineNumber++;
//remove all whitespace/tabs except inside of '' or "" (useful for whitespace in for example status messages or other output)
for (unsigned int i=0; i<line.length(); i++)
{
// check quotation status, ignore character
if (line[i]=='\'' || line [i]=='"')
{
insideQuotes = !insideQuotes;
continue;
}
// add everything inside quotations
if (insideQuotes)
{
tmp += line[i];
continue;
}
// add only if not whitespace/tabs
// TODO use isspace() instead (from <cctype>)
if (line[i]!=' ' && line[i]!='\t') tmp += line[i];
}
// ignore comments and empty lines
if (tmp[0]=='#' || tmp.length()==0) continue;
// check for section
if (tmp[0]=='[')
{
pos = tmp.find_first_of(']');
section = tmp.substr(1, pos-1);
continue;
}
// ignore option if section empty
if (section.empty())
{
std::cerr << "[ERROR|BVSConfig] found option belonging to no section in " << configFile << ":" << lineNumber << ": " << line << std::endl;
exit(1);
}
// check for +option (appending)
if (tmp[0]=='+')
{
append = true;
tmp.erase(0, 1);
}
// find '=' delimiter and prepend section name
pos = tmp.find_first_of('=');
option = section + '.' + tmp.substr(0, pos);
// check for empty option name
if (option.length()==section.length()+1 )
{
std::cerr << "[ERROR|BVSConfig] found line starting with '=' in " << configFile << ":" << lineNumber << ": " << line << std::endl;
exit(1);
}
// strip inline comment
posComment = tmp.find_first_of('#');
tmp = tmp.substr(pos+1, posComment-pos-1);
// append option if set
if (append)
{
// check if option exists
if (optionStore.find(option)==optionStore.end())
{
std::cerr << "[ERROR|BVSConfig] cannot append to non existing option in " << configFile << ":" << lineNumber << ": " << line << std::endl;
exit(1);
}
optionStore[option] = optionStore[option] + "," + tmp;
continue;
}
// only add when not already in store, thus command-line options can override config file options and first occurence is used
if (optionStore.find(option)==optionStore.end())
{
optionStore[option] = tmp;
//std::cout << "[BVSConfig] adding: " << option << " -> " << tmp.substr(pos+1, posComment-pos-1) << std::endl;
}
}
mutex.unlock();
return *this;
}
std::string BVSConfig::searchOption(const std::string& option)
{
// TODO lock guard
mutex.lock();
// search for option in store
if(optionStore.find(option)!=optionStore.end())
{
//std::cout << "found: " << option << " --> " << optionStore[option] << std::endl;
std::string tmp = optionStore[option];
mutex.unlock();
return tmp;
}
else
{
std::cerr << "[ERROR|BVSConfig] option not found: " << option << std::endl;
exit(-1);
}
}
template<> BVSConfig& BVSConfig::convertStringTo<std::string>(const std::string& input, std::string& output)
{
output = input;
return *this;
}
template<> BVSConfig& BVSConfig::convertStringTo<bool>(const std::string& input, bool& b)
{
// check for possible matches to various versions meaning true
if (input=="1" || input=="true" || input=="True" || input=="TRUE" || input=="on" || input=="On" || input=="ON" || input=="yes" || input=="Yes" || input=="YES")
{
b = true;
}
else
{
b = false;
}
return *this;
}
<|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 "qbluetoothtransferreply.h"
#include "qbluetoothaddress.h"
QTM_BEGIN_NAMESPACE
/*!
\class QBluetoothTransferReply
\brief The QBluetoothTransferReply class contains the data and headers for a request sent with
QBluetoothTranferManager.
\ingroup connectivity-bluetooth
\inmodule QtConnectivity
In additional to a copy of the QBluetoothTransferRequest object used to create the request,
QBluetoothTransferReply contains the contents of the reply itself.
QBluetoothTransferReply is a sequential-access QIODevice, which means that once data is read
from the object, it no longer kept by the device. It is therefore the application's
responsibility to keep this data if it needs to. Whenever more data is received and processed,
the readyRead() signal is emitted.
The downloadProgress() signal is also emitted when data is received, but the number of bytes
contained in it may not represent the actual bytes received, if any transformation is done to
the contents (for example, decompressing and removing the protocol overhead).
Even though QBluetoothTransferReply is a QIODevice connected to the contents of the reply, it
also emits the uploadProgress() signal, which indicates the progress of the upload for
operations that have such content.
*/
/*!
\fn QBluetoothTransferReply::abort()
Aborts this reply.
*/
void QBluetoothTransferReply::abort()
{
}
/*!
\fn void QBluetoothTransferReply::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
This signal is emitted whenever data is received. The \a bytesReceived parameter contains the
total number of bytes received so far out of \a bytesTotal expected for the entire transfer.
*/
/*!
\fn void QBluetoothTransferReply::finished()
This signal is emitted when the transfer is complete.
*/
/*!
\fn void QBluetoothTransferReply::uploadProgress(qint64 bytesSent, qint64 bytesTotal)
This signal is emitted whenever data is sent. The \a bytesSent parameter contains the total
number of bytes sent so far out of \a bytesTotal.
*/
/*!
Constructs a new QBluetoothTransferReply with parent \a parent.
*/
QBluetoothTransferReply::QBluetoothTransferReply(QObject *parent)
: QObject(parent)
{
}
/*!
Destroys the QBluetoothTransferReply object.
*/
QBluetoothTransferReply::~QBluetoothTransferReply()
{
}
/*!
Returns the attribute associated with the code \a code. If the attribute has not been set, it
returns an invalid QVariant.
*/
QVariant QBluetoothTransferReply::attribute(QBluetoothTransferRequest::Attribute code) const
{
return m_attributes[code];
}
/*!
\fn void QBluetoothTransferReply::isFinished()
Returns true if this reply has finished; otherwise returns false.
*/
//bool QBluetoothTransferReply::isFinished() const
//{
// return false;
//}
/*!
\fn void QBluetoothTransferReply::isRunning()
Returns true if this reply is running; otherwise returns false.
*/
//bool QBluetoothTransferReply::isRunning() const
//{
// return false;
//}
/*!
Returns the QBluetoothTransferManager that was used to create this QBluetoothTransferReply
object.
*/
QBluetoothTransferManager *QBluetoothTransferReply::manager() const
{
return m_manager;
}
/*!
Returns the type of operation that this reply is for.
*/
QBluetoothTransferManager::Operation QBluetoothTransferReply::operation() const
{
return m_operation;
}
/*!
Returns a copy of the QBluetoothTransferRequest object used to create this
QBluetoothTransferReply.
*/
//QBluetoothTransferRequest QBluetoothTransferReply::request() const
//{
// return QBluetoothTransferRequest(QBluetoothAddress());
//}
/*!
Sets the operation of this QBluetoothTransferReply to \a operation.
*/
void QBluetoothTransferReply::setOperation(QBluetoothTransferManager::Operation operation)
{
m_operation = operation;
}
#include "moc_qbluetoothtransferreply.cpp"
QTM_END_NAMESPACE
<commit_msg>Docs: fixed some doc function signatures.<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 "qbluetoothtransferreply.h"
#include "qbluetoothaddress.h"
QTM_BEGIN_NAMESPACE
/*!
\class QBluetoothTransferReply
\brief The QBluetoothTransferReply class contains the data and headers for a request sent with
QBluetoothTranferManager.
\ingroup connectivity-bluetooth
\inmodule QtConnectivity
In additional to a copy of the QBluetoothTransferRequest object used to create the request,
QBluetoothTransferReply contains the contents of the reply itself.
QBluetoothTransferReply is a sequential-access QIODevice, which means that once data is read
from the object, it no longer kept by the device. It is therefore the application's
responsibility to keep this data if it needs to. Whenever more data is received and processed,
the readyRead() signal is emitted.
The downloadProgress() signal is also emitted when data is received, but the number of bytes
contained in it may not represent the actual bytes received, if any transformation is done to
the contents (for example, decompressing and removing the protocol overhead).
Even though QBluetoothTransferReply is a QIODevice connected to the contents of the reply, it
also emits the uploadProgress() signal, which indicates the progress of the upload for
operations that have such content.
*/
/*!
\fn QBluetoothTransferReply::abort()
Aborts this reply.
*/
void QBluetoothTransferReply::abort()
{
}
/*!
\fn void QBluetoothTransferReply::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
This signal is emitted whenever data is received. The \a bytesReceived parameter contains the
total number of bytes received so far out of \a bytesTotal expected for the entire transfer.
*/
/*!
\fn void QBluetoothTransferReply::finished(QBluetoothTransferReply *)
This signal is emitted when the transfer is complete.
*/
/*!
\fn void QBluetoothTransferReply::uploadProgress(qint64 bytesSent, qint64 bytesTotal)
This signal is emitted whenever data is sent. The \a bytesSent parameter contains the total
number of bytes sent so far out of \a bytesTotal.
*/
/*!
Constructs a new QBluetoothTransferReply with parent \a parent.
*/
QBluetoothTransferReply::QBluetoothTransferReply(QObject *parent)
: QObject(parent)
{
}
/*!
Destroys the QBluetoothTransferReply object.
*/
QBluetoothTransferReply::~QBluetoothTransferReply()
{
}
/*!
Returns the attribute associated with the code \a code. If the attribute has not been set, it
returns an invalid QVariant.
*/
QVariant QBluetoothTransferReply::attribute(QBluetoothTransferRequest::Attribute code) const
{
return m_attributes[code];
}
/*!
\fn bool QBluetoothTransferReply::isFinished() const
Returns true if this reply has finished; otherwise returns false.
*/
//bool QBluetoothTransferReply::isFinished() const
//{
// return false;
//}
/*!
\fn bool QBluetoothTransferReply::isRunning() const
Returns true if this reply is running; otherwise returns false.
*/
//bool QBluetoothTransferReply::isRunning() const
//{
// return false;
//}
/*!
Returns the QBluetoothTransferManager that was used to create this QBluetoothTransferReply
object.
*/
QBluetoothTransferManager *QBluetoothTransferReply::manager() const
{
return m_manager;
}
/*!
Returns the type of operation that this reply is for.
*/
QBluetoothTransferManager::Operation QBluetoothTransferReply::operation() const
{
return m_operation;
}
/*
Returns a copy of the QBluetoothTransferRequest object used to create this
QBluetoothTransferReply.
*/
//QBluetoothTransferRequest QBluetoothTransferReply::request() const
//{
// return QBluetoothTransferRequest(QBluetoothAddress());
//}
/*!
Sets the operation of this QBluetoothTransferReply to \a operation.
*/
void QBluetoothTransferReply::setOperation(QBluetoothTransferManager::Operation operation)
{
m_operation = operation;
}
#include "moc_qbluetoothtransferreply.cpp"
QTM_END_NAMESPACE
<|endoftext|>
|
<commit_before><commit_msg>Create 1078 - Multiplication Table.cpp<commit_after><|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2016 Henry Zhang. All rights reserved.
*
****************************************************************************/
/**
* @file ex12_11.cpp
* Explain whether the following call to the process function
* defined on page 464 is correct. If not, how would you correct the call?
* shared_ptr<int> p(new int(42));
* process(shared_ptr<int>(p.get()));
* @author Herny Zhang <[email protected]>
*/
#include <vector>
using std::vector;
#include <memory>
using std::shared_ptr;
#include <iostream>
using std::cout;
using std::endl;
void process(shared_ptr<int> ptr)
{
cout << "insided the process function: " << ptr.use_count() << endl;
}
int main(int argc, char const *argv[])
{
shared_ptr<int> p(new int(42));
cout << p.use_count() << endl;
process(shared_ptr<int>(p.get()));
cout << p.use_count() << endl;
// cout << *p << endl; //undefined, the memory to which p points was freed
// why execute p.reset() won't corrupt.
// p.reset(); // double freed or corruption was generated.
// delete p.get(); // double freed or corruption was generated.
return 0;
}
// int main(int argc, char const *argv[])
// {
// {
// shared_ptr<int> p(new int(42));
// cout << p.use_count() << endl;
// process(shared_ptr<int>(p.get()));
// cout << p.use_count() << endl;
// }
// return 0;
// }<commit_msg>add more test codes for ch12 exercise 12.11.<commit_after>/****************************************************************************
*
* Copyright (c) 2016 Henry Zhang. All rights reserved.
*
****************************************************************************/
/**
* @file ex12_11.cpp
* Explain whether the following call to the process function
* defined on page 464 is correct. If not, how would you correct the call?
* shared_ptr<int> p(new int(42));
* process(shared_ptr<int>(p.get()));
* @author Herny Zhang <[email protected]>
*/
#include <vector>
using std::vector;
#include <memory>
using std::shared_ptr;
#include <iostream>
using std::cout;
using std::endl;
void process(shared_ptr<int> ptr)
{
cout << "insided the process function: " << ptr.use_count() << endl;
}
int main(int argc, char const *argv[])
{
shared_ptr<int> p(new int(42));
cout << p.use_count() << endl;
process(shared_ptr<int>(p.get()));
cout << p.use_count() << endl;
// cout << *p << endl; //undefined, the memory to which p points was freed
// why execute p.reset() won't corrupt.
// p.reset(); // double freed or corruption was generated.
// delete p.get(); // double freed or corruption was generated.
return 0;
}
// int main(int argc, char const *argv[])
// {
// {
// shared_ptr<int> p(new int(42));
// cout << p.use_count() << endl;
// process(shared_ptr<int>(p.get()));
// cout << p.use_count() << endl;
// }
// return 0;
// }
// class Test
// {
// public:
// Test() : i(0) { cout << "Test constructor." << endl; }
// ~Test() { cout << "Test destructor." << endl; }
// private:
// int i;
// };
// void process(shared_ptr<Test> ptr)
// {
// cout << "insided the process function: " << ptr.use_count() << endl;
// }
// int main(int argc, char const *argv[])
// {
// {
// shared_ptr<Test> p(new Test());
// cout << p.use_count() << endl;
// process(shared_ptr<Test>(p.get()));
// cout << p.use_count() << endl;
// // delete p.get();
// }
// return 0;
// }
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/lib/pstates_pgpe.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 pstates_pgpe.H
/// @brief Pstate structures and support routines for PGPE Hcode
///
// *HWP HW Owner : Rahul Batra <[email protected]>
// *HWP HW Owner : Michael Floyd <[email protected]>
// *HWP Team : PM
// *HWP Level : 1
// *HWP Consumed by : PGPE:HS
#ifndef __PSTATES_PGPE_H__
#define __PSTATES_PGPE_H__
#include <pstates_common.H>
// #include <pstates_qme.h>
/// PstateParmsBlock Magic Number
///
/// This magic number identifies a particular version of the
/// PstateParmsBlock and its substructures. The version number should be
/// kept up to date as changes are made to the layout or contents of the
/// structure.
#define PSTATE_PARMSBLOCK_MAGIC 0x5053544154453030ull /* PSTATE00 */
#ifndef __ASSEMBLER__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/// Control Attributes
typedef union
{
uint8_t value[128];
union
{
uint8_t pstates_enabled;
uint8_t resclk_enabled;
uint8_t wof_enabled;
uint8_t dds_enabled;
uint8_t ocs_enabled;
uint8_t underv_enabled;
uint8_t overv_enabled;
uint8_t throttle_control_enabled;
} fields;
} Attributes_t;
/// Resonant Clock Stepping Entry
///
/// @todo needs refinement for P10 yet.
typedef union
{
uint16_t value;
struct
{
#ifdef _BIG_ENDIAN
uint16_t sector_buffer : 4;
uint16_t spare1 : 1;
uint16_t pulse_enable : 1;
uint16_t pulse_mode : 2;
uint16_t resonant_switch : 4;
uint16_t spare4 : 4;
#else
uint16_t spare4 : 4;
uint16_t resonant_switch : 4;
uint16_t pulse_mode : 2;
uint16_t pulse_enable : 1;
uint16_t spare1 : 1;
uint16_t sector_buffer : 4;
#endif // _BIG_ENDIAN
} fields;
} ResClkStepEntry_t;
/// @todo needs refinement for P10 yet.
#define RESCLK_FREQ_REGIONS 8
#define RESCLK_STEPS 64
#define RESCLK_L3_STEPS 4
/// These define the Run-time rails that are controlled by the PGPE during
/// Pstate operations.
#define RUNTIME_RAILS 2
#define RUNTIME_RAIL_VDD 0
#define RUNTIME_RAIL_VCS 1
/// Resonant Clock Setup
typedef struct
{
uint8_t freq_mhz[RESCLK_FREQ_REGIONS];
uint8_t index[RESCLK_FREQ_REGIONS];
ResClkStepEntry_t steparray[RESCLK_STEPS];
uint16_t step_delay_ns; // Max delay: 65.536us
uint8_t l3_steparray[RESCLK_L3_STEPS];
uint16_t l3_threshold_mv;
} ResClkSetup_t;
/// #W Entry Data Points as per V19
typedef struct
{
union
{
uint64_t value;
struct
{
#ifdef _BIG_ENDIAN
uint64_t spare1 : 6;
uint64_t calb_adj : 2;
uint64_t insrtn_dely : 8;
uint64_t spare2 : 1;
uint64_t trip_offset : 3;
uint64_t data0_select : 4;
uint64_t data1_select : 4;
uint64_t data2_select : 4;
uint64_t large_droop : 4;
uint64_t small_droop : 4;
uint64_t slopeA_start : 4;
uint64_t slopeA_end : 4;
uint64_t slopeB_start : 4;
uint64_t slopeB_end : 4;
uint64_t slopeA_cycles : 4;
uint64_t slopeB_cycles : 4;
#else
uint64_t slopeB_cycles : 4;
uint64_t slopeA_cycles : 4;
uint64_t slopeB_end : 4;
uint64_t slopeB_start : 4;
uint64_t slopeA_end : 4;
uint64_t slopeA_start : 4;
uint64_t small_droop : 4;
uint64_t large_droop : 4;
uint64_t data2_select : 4;
uint64_t data1_select : 4;
uint64_t data0_select : 4;
uint64_t trip_offset : 3;
uint64_t spare2 : 1;
uint64_t insrtn_dely : 8;
uint64_t calb_adj : 2;
uint64_t spare1 : 6;
#endif
} fields;
} digital_droop_sensor_config;
} PoundWEntry_t;
/// #W DPLL Settings
typedef struct
{
union
{
uint16_t value;
struct
{
#ifdef _BIG_ENDIAN
uint16_t N_S_drop_3p125pct : 4;
uint16_t N_L_drop_3p125pct : 4;
uint16_t L_S_return_3p125pct : 4;
uint16_t S_N_return_3p125pct : 4;
#else
uint16_t S_N_return_3p125pct : 4;
uint16_t L_S_return_3p125pct : 4;
uint16_t N_L_drop_3p125pct : 4;
uint16_t N_S_drop_3p125pct : 4;
#endif // _BIG_ENDIAN /// #W Other Settings
} fields;
};
} PoundWDpllSettings_t;
/// #W Other Settings
typedef struct
{
uint8_t dds_calibration_version;
PoundWDpllSettings_t dpll_settings;
uint8_t light_throttle_settings[10];
uint8_t harsh_throttle_settings[10];
uint16_t droop_freq_resp_reference;
uint8_t large_droop_mode_reg_setting[8];
uint8_t misc_droop_mode_reg_setting[8];
uint8_t spare[215];
} PoundWOther_t;
/// #W VPD Structure
///
/// Part specific data to manage the Digital Droop Sensor (DDS)
typedef struct
{
PoundWEntry_t entry[MAXIMUM_CORES][NUM_PV_POINTS];
PoundWOther_t other;
uint8_t rsvd[256];
} PoundW_t;
/// Voltage Regulation Module (VRM) Control Settings
typedef struct
{
/// The exponent of the exponential encoding of Pstate stepping delay
uint8_t stepdelay_range;
/// The significand of the exponential encoding of Pstate stepping delay
uint8_t stepdelay_value;
uint8_t spare[2];
/// Time between ext VRM detects write voltage cmd and when voltage begins to move
uint32_t transition_start_ns[RUNTIME_RAILS];
/// Transition rate for an increasing voltage excursion
uint32_t transition_rate_inc_uv_per_us[RUNTIME_RAILS];
/// Transition rate for an decreasing voltage excursion
uint32_t transition_rate_dec_uv_per_us[RUNTIME_RAILS];
/// Delay to account for rail settling
uint32_t stabilization_time_us[RUNTIME_RAILS];
/// External VRM transition step size
uint32_t step_size_mv[RUNTIME_RAILS];
} VRMParms_t;
/// @todo Need to define the DDS control block
/// Pstate Parameter consumed by PGPE
///
/// The GlobalPstateParameterBlock is an abstraction of a set of voltage/frequency
/// operating points along with hardware limits.
///
typedef struct
{
union
{
uint64_t value;
struct
{
uint64_t eye_catcher : 56;
uint64_t version : 8 ;
} fields;
} magic;
Attributes_t attr;
uint32_t reference_frequency_khz; // Pstate[0] frequency
uint32_t frequency_step_khz;
uint32_t occ_complex_frequency_mhz; // Needed for FITs
uint32_t dpll_pstate0_value; // @todo why this and reference_frequency_khz?
/// VPD operating points are biased but without load-line correction.
/// Frequencies are in MHz, voltages are specified in units of 1mV, currents
/// are specified in units of 10mA, and temperatures are specified in 0.5
/// degrees C.
PoundVOpPoint_t operating_points_set[NUM_VPD_PTS_SET][NUM_PV_POINTS];
uint32_t spare0[16]; // 128B word-aligned
PoundVBias_t poundv_biases_0p05pct[NUM_PV_POINTS]; // Values in 0.5%
SysPowerDistParms_t vdd_sysparm;
SysPowerDistParms_t vcs_sysparm;
SysPowerDistParms_t vdn_sysparm;
/// #W Other Settings
VRMParms_t ext_vrm_parms;
uint32_t safe_voltage_mv;
uint32_t safe_frequency_khz;
/// DDS Data
/// DDSParmBlock dds;
/// @todo need to define the DDS parm block
/// The following are needed to generated the Pstate Table to HOMER.
ResClkSetup_t resclk;
/// Precalculated VPD Slopes
/// All are in 4.12 decimal form into uint16_t integer value
uint16_t ps_voltage_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t voltage_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t ps_ac_current_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t ps_dc_current_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t ac_current_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t dc_current_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
//AvsBusTopology
AvsBusTopology_t avs_bus_topology;
uint32_t core_on_ratio_vdd;
uint32_t l3_on_ratio_vdd;
uint32_t mma_on_ratio_vdd;
uint32_t core_on_ratio_vcs;
uint32_t l3_on_ratio_vcs;
uint32_t vdd_vratio_weight;
uint32_t vcs_vratio_weight;
// Biased Compare VID operating points
// @todo RTC 201083 Add DDS GPPB values
// CompareVIDPoints_t vid_point_set[NUM_PV_POINTS];
// Biased Threshold operation points
// uint8_t threshold_set[NUM_PV_POINTS][NUM_THRESHOLD_POINTS];
// pstate-volt compare slopes
// int16_t ps_vid_compare_slopes[VPD_NUM_SLOPES_REGION];
// pstate-volt threshold slopes
// int16_t ps_dds_thresh_slopes[VPD_NUM_SLOPES_REGION][NUM_THRESHOLD_POINTS];
// Jump value operating points
// uint8_t jump_value_set[NUM_PV_POINTS][NUM_JUMP_VALUES];
// Jump-value slopes
// int16_t ps_dds_jump_slopes[VPD_NUM_SLOPES_REGION][NUM_JUMP_VALUES];
//} __attribute__((packed, aligned(1024))) GlobalPstateParmBlock_t;
} GlobalPstateParmBlock_t;
#ifdef __cplusplus
} // end extern C
#endif
#endif /* __ASSEMBLER__ */
#endif /* __PSTATES_PGPE_H__ */
<commit_msg>PGPE: DDS Calculation<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p10/procedures/hwp/lib/pstates_pgpe.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 pstates_pgpe.H
/// @brief Pstate structures and support routines for PGPE Hcode
///
// *HWP HW Owner : Rahul Batra <[email protected]>
// *HWP HW Owner : Michael Floyd <[email protected]>
// *HWP Team : PM
// *HWP Level : 1
// *HWP Consumed by : PGPE:HS
#ifndef __PSTATES_PGPE_H__
#define __PSTATES_PGPE_H__
#include <pstates_common.H>
// #include <pstates_qme.h>
/// PstateParmsBlock Magic Number
///
/// This magic number identifies a particular version of the
/// PstateParmsBlock and its substructures. The version number should be
/// kept up to date as changes are made to the layout or contents of the
/// structure.
#define PSTATE_PARMSBLOCK_MAGIC 0x5053544154453030ull /* PSTATE00 */
#ifndef __ASSEMBLER__
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
enum POUNDW_DDS_FIELDS
{
TRIP_OFFSET = 0,
DATA0_OFFSET = 1,
DATA1_OFFSET = 2,
DATA2_OFFSET = 3,
LARGE_DROOP_DETECT = 4,
SMALL_DROOP_DETECT = 5,
SLOPEA_START_DETECT = 6,
SLOPEA_END_DETECT = 7,
SLOPEB_START_DETECT = 8,
SLOPEB_END_DETECT = 9,
SLOPEA_CYCLES = 10,
SLOPEB_CYCLES = 11,
NUM_POUNDW_DDS_FIELDS = 12
};
/// Control Attributes
typedef union
{
uint8_t value[128];
union
{
uint8_t pstates_enabled;
uint8_t resclk_enabled;
uint8_t wof_enabled;
uint8_t dds_enabled;
uint8_t ocs_enabled;
uint8_t underv_enabled;
uint8_t overv_enabled;
uint8_t throttle_control_enabled;
} fields;
} Attributes_t;
/// Resonant Clock Stepping Entry
///
/// @todo needs refinement for P10 yet.
typedef union
{
uint16_t value;
struct
{
#ifdef _BIG_ENDIAN
uint16_t sector_buffer : 4;
uint16_t spare1 : 1;
uint16_t pulse_enable : 1;
uint16_t pulse_mode : 2;
uint16_t resonant_switch : 4;
uint16_t spare4 : 4;
#else
uint16_t spare4 : 4;
uint16_t resonant_switch : 4;
uint16_t pulse_mode : 2;
uint16_t pulse_enable : 1;
uint16_t spare1 : 1;
uint16_t sector_buffer : 4;
#endif // _BIG_ENDIAN
} fields;
} ResClkStepEntry_t;
/// @todo needs refinement for P10 yet.
#define RESCLK_FREQ_REGIONS 8
#define RESCLK_STEPS 64
#define RESCLK_L3_STEPS 4
/// These define the Run-time rails that are controlled by the PGPE during
/// Pstate operations.
#define RUNTIME_RAILS 2
#define RUNTIME_RAIL_VDD 0
#define RUNTIME_RAIL_VCS 1
/// Resonant Clock Setup
typedef struct
{
uint8_t freq_mhz[RESCLK_FREQ_REGIONS];
uint8_t index[RESCLK_FREQ_REGIONS];
ResClkStepEntry_t steparray[RESCLK_STEPS];
uint16_t step_delay_ns; // Max delay: 65.536us
uint8_t l3_steparray[RESCLK_L3_STEPS];
uint16_t l3_threshold_mv;
} ResClkSetup_t;
/// #W Entry Data Points as per V19
typedef struct
{
union
{
uint64_t value;
struct
{
#ifdef _BIG_ENDIAN
uint64_t spare1 : 6;
uint64_t calb_adj : 2;
uint64_t insrtn_dely : 8;
uint64_t spare2 : 1;
uint64_t trip_offset : 3;
uint64_t data0_select : 4;
uint64_t data1_select : 4;
uint64_t data2_select : 4;
uint64_t large_droop : 4;
uint64_t small_droop : 4;
uint64_t slopeA_start : 4;
uint64_t slopeA_end : 4;
uint64_t slopeB_start : 4;
uint64_t slopeB_end : 4;
uint64_t slopeA_cycles : 4;
uint64_t slopeB_cycles : 4;
#else
uint64_t slopeB_cycles : 4;
uint64_t slopeA_cycles : 4;
uint64_t slopeB_end : 4;
uint64_t slopeB_start : 4;
uint64_t slopeA_end : 4;
uint64_t slopeA_start : 4;
uint64_t small_droop : 4;
uint64_t large_droop : 4;
uint64_t data2_select : 4;
uint64_t data1_select : 4;
uint64_t data0_select : 4;
uint64_t trip_offset : 3;
uint64_t spare2 : 1;
uint64_t insrtn_dely : 8;
uint64_t calb_adj : 2;
uint64_t spare1 : 6;
#endif
} fields;
} ddsc;
} PoundWEntry_t;
/// #W DPLL Settings
typedef struct
{
union
{
uint16_t value;
struct
{
#ifdef _BIG_ENDIAN
uint16_t N_S_drop_3p125pct : 4;
uint16_t N_L_drop_3p125pct : 4;
uint16_t L_S_return_3p125pct : 4;
uint16_t S_N_return_3p125pct : 4;
#else
uint16_t S_N_return_3p125pct : 4;
uint16_t L_S_return_3p125pct : 4;
uint16_t N_L_drop_3p125pct : 4;
uint16_t N_S_drop_3p125pct : 4;
#endif // _BIG_ENDIAN /// #W Other Settings
} fields;
};
} PoundWDpllSettings_t;
/// #W Other Settings
typedef struct
{
uint8_t dds_calibration_version;
PoundWDpllSettings_t dpll_settings;
uint8_t light_throttle_settings[10];
uint8_t harsh_throttle_settings[10];
uint16_t droop_freq_resp_reference;
uint8_t large_droop_mode_reg_setting[8];
uint8_t misc_droop_mode_reg_setting[8];
uint8_t spare[215];
} PoundWOther_t;
/// #W VPD Structure
///
/// Part specific data to manage the Digital Droop Sensor (DDS)
typedef struct
{
PoundWEntry_t entry[MAXIMUM_CORES][NUM_PV_POINTS];
PoundWOther_t other;
uint8_t rsvd[256];
} PoundW_t;
/// Voltage Regulation Module (VRM) Control Settings
typedef struct
{
/// The exponent of the exponential encoding of Pstate stepping delay
uint8_t stepdelay_range;
/// The significand of the exponential encoding of Pstate stepping delay
uint8_t stepdelay_value;
uint8_t spare[2];
/// Time between ext VRM detects write voltage cmd and when voltage begins to move
uint32_t transition_start_ns[RUNTIME_RAILS];
/// Transition rate for an increasing voltage excursion
uint32_t transition_rate_inc_uv_per_us[RUNTIME_RAILS];
/// Transition rate for an decreasing voltage excursion
uint32_t transition_rate_dec_uv_per_us[RUNTIME_RAILS];
/// Delay to account for rail settling
uint32_t stabilization_time_us[RUNTIME_RAILS];
/// External VRM transition step size
uint32_t step_size_mv[RUNTIME_RAILS];
} VRMParms_t;
/// @todo Need to define the DDS control block
/// Pstate Parameter consumed by PGPE
///
/// The GlobalPstateParameterBlock is an abstraction of a set of voltage/frequency
/// operating points along with hardware limits.
///
typedef struct
{
union
{
uint64_t value;
struct
{
uint64_t eye_catcher : 56;
uint64_t version : 8 ;
} fields;
} magic;
Attributes_t attr;
uint32_t reference_frequency_khz; // Pstate[0] frequency
uint32_t frequency_step_khz;
uint32_t occ_complex_frequency_mhz; // Needed for FITs
uint32_t dpll_pstate0_value; // @todo why this and reference_frequency_khz?
/// VPD operating points are biased but without load-line correction.
/// Frequencies are in MHz, voltages are specified in units of 1mV, currents
/// are specified in units of 10mA, and temperatures are specified in 0.5
/// degrees C.
PoundVOpPoint_t operating_points_set[NUM_VPD_PTS_SET][NUM_PV_POINTS];
uint32_t spare0[16]; // 128B word-aligned
PoundVBias_t poundv_biases_0p05pct[NUM_PV_POINTS]; // Values in 0.5%
SysPowerDistParms_t vdd_sysparm;
SysPowerDistParms_t vcs_sysparm;
SysPowerDistParms_t vdn_sysparm;
/// #W Other Settings
VRMParms_t ext_vrm_parms;
uint32_t safe_voltage_mv;
uint32_t safe_frequency_khz;
/// DDS Data
/// DDSParmBlock dds;
/// @todo need to define the DDS parm block
PoundWEntry_t dds[MAXIMUM_CORES][NUM_PV_POINTS];
/// The following are needed to generated the Pstate Table to HOMER.
ResClkSetup_t resclk;
/// Precalculated VPD Slopes
/// All are in 4.12 decimal form into uint16_t integer value
uint16_t ps_voltage_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t voltage_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t ps_ac_current_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t ps_dc_current_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t ac_current_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t dc_current_ps_slopes[RUNTIME_RAILS][NUM_VPD_PTS_SET][VPD_NUM_SLOPES_REGION];
uint16_t ps_dds_delay_slopes[NUM_VPD_PTS_SET][MAXIMUM_CORES][VPD_NUM_SLOPES_REGION];
uint8_t ps_dds_slopes[NUM_POUNDW_DDS_FIELDS ][NUM_VPD_PTS_SET][MAXIMUM_CORES][VPD_NUM_SLOPES_REGION];
//AvsBusTopology
AvsBusTopology_t avs_bus_topology;
uint32_t core_on_ratio_vdd;
uint32_t l3_on_ratio_vdd;
uint32_t mma_on_ratio_vdd;
uint32_t core_on_ratio_vcs;
uint32_t l3_on_ratio_vcs;
uint32_t vdd_vratio_weight;
uint32_t vcs_vratio_weight;
// Biased Compare VID operating points
// @todo RTC 201083 Add DDS GPPB values
// CompareVIDPoints_t vid_point_set[NUM_PV_POINTS];
// Biased Threshold operation points
// uint8_t threshold_set[NUM_PV_POINTS][NUM_THRESHOLD_POINTS];
// pstate-volt compare slopes
// int16_t ps_vid_compare_slopes[VPD_NUM_SLOPES_REGION];
// pstate-volt threshold slopes
// int16_t ps_dds_thresh_slopes[VPD_NUM_SLOPES_REGION][NUM_THRESHOLD_POINTS];
// Jump value operating points
// uint8_t jump_value_set[NUM_PV_POINTS][NUM_JUMP_VALUES];
// Jump-value slopes
// int16_t ps_dds_jump_slopes[VPD_NUM_SLOPES_REGION][NUM_JUMP_VALUES];
//} __attribute__((packed, aligned(1024))) GlobalPstateParmBlock_t;
} GlobalPstateParmBlock_t;
#ifdef __cplusplus
} // end extern C
#endif
#endif /* __ASSEMBLER__ */
#endif /* __PSTATES_PGPE_H__ */
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkSurface.h"
#include "mitkInteractionConst.h"
#include "mitkSurfaceOperation.h"
#include <vtkPolyData.h>
#include <itkSmartPointerForwardReference.txx>
mitk::Surface::Surface() :
m_CalculateBoundingBox( false )
{
this->InitializeEmpty();
}
mitk::Surface::~Surface()
{
this->ClearData();
}
void mitk::Surface::ClearData()
{
for ( VTKPolyDataSeries::iterator it = m_PolyDataSeries.begin(); it != m_PolyDataSeries.end(); ++it )
{
if ( ( *it ) != NULL )
( *it )->Delete();
}
m_PolyDataSeries.clear();
Superclass::ClearData();
}
void mitk::Surface::InitializeEmpty()
{
vtkPolyData* pdnull = NULL;
m_PolyDataSeries.resize( 1, pdnull );
Superclass::InitializeTimeSlicedGeometry(1);
m_Initialized = true;
}
void mitk::Surface::SetVtkPolyData( vtkPolyData* polydata, unsigned int t )
{
// Adapt the size of the data vector if necessary
this->Expand( t+1 );
if(m_PolyDataSeries[ t ] != NULL)
{
// we do not need the reference on the object any longer
m_PolyDataSeries[ t ]->Delete();
}
m_PolyDataSeries[ t ] = polydata;
// call m_VtkPolyData->Register(NULL) to tell
// the reference counting that we want to keep a
// reference on the object
if(m_PolyDataSeries[ t ] != NULL)
{
m_PolyDataSeries[ t ]->Register( NULL );
}
this->Modified();
m_CalculateBoundingBox = true;
}
bool mitk::Surface::IsEmpty(unsigned int t) const
{
if(!IsInitialized())
return false;
vtkPolyData* polydata = const_cast<Surface*>(this)->GetVtkPolyData(t);
return
(polydata == NULL) ||
(
(polydata->GetNumberOfVerts() <= 0) &&
(polydata->GetNumberOfPolys() <= 0) &&
(polydata->GetNumberOfStrips() <= 0) &&
(polydata->GetNumberOfLines() <= 0)
);
}
vtkPolyData* mitk::Surface::GetVtkPolyData( unsigned int t )
{
if ( t < m_PolyDataSeries.size() )
{
vtkPolyData* polydata = m_PolyDataSeries[ t ];
if((polydata==NULL) && (GetSource().GetPointer()!=NULL))
{
RegionType requestedregion;
requestedregion.SetIndex(3, t);
requestedregion.SetSize(3, 1);
SetRequestedRegion(&requestedregion);
GetSource()->Update();
}
polydata = m_PolyDataSeries[ t ];
return polydata;
}
else
return NULL;
}
void mitk::Surface::UpdateOutputInformation()
{
if ( this->GetSource() )
{
this->GetSource()->UpdateOutputInformation();
}
if ( ( m_CalculateBoundingBox ) && ( m_PolyDataSeries.size() > 0 ) )
CalculateBoundingBox();
else
GetTimeSlicedGeometry()->UpdateInformation();
}
void mitk::Surface::CalculateBoundingBox()
{
//
// first make sure, that the associated time sliced geometry has
// the same number of geometry 3d's as vtkPolyDatas are present
//
mitk::TimeSlicedGeometry* timeGeometry = GetTimeSlicedGeometry();
if ( timeGeometry->GetTimeSteps() != m_PolyDataSeries.size() )
{
itkExceptionMacro(<<"timeGeometry->GetTimeSteps() != m_PolyDataSeries.size() -- use Initialize(timeSteps) with correct number of timeSteps!");
}
//
// Iterate over the vtkPolyDatas and update the Geometry
// information of each of the items.
//
for ( unsigned int i = 0 ; i < m_PolyDataSeries.size() ; ++i )
{
vtkPolyData* polyData = m_PolyDataSeries[ i ];
vtkFloatingPointType bounds[ ] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
if ( ( polyData != NULL ) && ( polyData->GetNumberOfPoints() > 0 ) )
{
polyData->Update();
polyData->ComputeBounds();
polyData->GetBounds( bounds );
}
mitk::Geometry3D::Pointer g3d = timeGeometry->GetGeometry3D( i );
assert( g3d.IsNotNull() );
g3d->SetFloatBounds( bounds );
}
timeGeometry->UpdateInformation();
mitk::BoundingBox::Pointer bb = const_cast<mitk::BoundingBox*>( timeGeometry->GetBoundingBox() );
itkDebugMacro( << "boundingbox min: "<< bb->GetMinimum());
itkDebugMacro( << "boundingbox max: "<< bb->GetMaximum());
m_CalculateBoundingBox = false;
}
void mitk::Surface::SetRequestedRegionToLargestPossibleRegion()
{
m_RequestedRegion = GetLargestPossibleRegion();
}
bool mitk::Surface::RequestedRegionIsOutsideOfTheBufferedRegion()
{
RegionType::IndexValueType end = m_RequestedRegion.GetIndex(3)+m_RequestedRegion.GetSize(3);
if(((RegionType::IndexValueType)m_PolyDataSeries.size())<end)
return true;
for( RegionType::IndexValueType t=m_RequestedRegion.GetIndex(3); t<end; ++t )
if(m_PolyDataSeries[t]==NULL)
return true;
return false;
}
bool mitk::Surface::VerifyRequestedRegion()
{
if( (m_RequestedRegion.GetIndex(3)>=0) &&
(m_RequestedRegion.GetIndex(3)+m_RequestedRegion.GetSize(3)<=m_PolyDataSeries.size()) )
return true;
return false;
}
void mitk::Surface::SetRequestedRegion( itk::DataObject *data )
{
mitk::Surface *surfaceData;
surfaceData = dynamic_cast<mitk::Surface*>(data);
if (surfaceData)
{
m_RequestedRegion = surfaceData->GetRequestedRegion();
}
else
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::SetRequestedRegion(DataObject*) cannot cast " << typeid(data).name() << " to " << typeid(Surface*).name() );
}
}
void mitk::Surface::SetRequestedRegion(Surface::RegionType *region) //by arin
{
if(region!=NULL)
{
m_RequestedRegion = *region;
}
else
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::SetRequestedRegion(Surface::RegionType*) cannot cast " << typeid(region).name() << " to " << typeid(Surface*).name() );
}
}
void mitk::Surface::CopyInformation( const itk::DataObject * data)
{
Superclass::CopyInformation( data );
const mitk::Surface* surfaceData;
surfaceData = dynamic_cast<const mitk::Surface*>( data );
if ( surfaceData )
{
m_LargestPossibleRegion = surfaceData->GetLargestPossibleRegion();
}
else
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::CopyInformation(const DataObject *data) cannot cast " << typeid(data).name() << " to " << typeid(surfaceData).name() );
}
}
void mitk::Surface::Update()
{
if ( GetSource() == NULL )
{
for ( VTKPolyDataSeries::iterator it = m_PolyDataSeries.begin() ; it != m_PolyDataSeries.end() ; ++it )
{
if ( ( *it ) != NULL )
( *it )->Update();
}
}
Superclass::Update();
}
void mitk::Surface::Expand( unsigned int timeSteps )
{
// check if the vector is long enough to contain the new element
// at the given position. If not, expand it with sufficient zero-filled elements.
if ( timeSteps > m_PolyDataSeries.size() )
{
Superclass::Expand( timeSteps );
vtkPolyData* pdnull = NULL;
m_PolyDataSeries.resize( timeSteps, pdnull );
m_CalculateBoundingBox = true;
}
}
void mitk::Surface::ExecuteOperation(Operation *operation)
{
switch ( operation->GetOperationType() )
{
case OpSURFACECHANGED:
mitk::SurfaceOperation* surfOp = dynamic_cast<mitk::SurfaceOperation*>(operation);
if( ! surfOp ) break;
unsigned int time = surfOp->GetTimeStep();
if(m_PolyDataSeries[ time ] != NULL)
{
vtkPolyData* updatePoly = surfOp->GetVtkPolyData();
if( updatePoly ){
this->SetVtkPolyData( updatePoly, time );
this->CalculateBoundingBox();
}
}
break;
}
this->Modified();
}
unsigned int mitk::Surface::GetSizeOfPolyDataSeries() const
{
return m_PolyDataSeries.size();
}
void mitk::Surface::Graft( const DataObject* data )
{
const Self* surface;
try
{
surface = dynamic_cast<const Self*>( data );
}
catch(...)
{
itkExceptionMacro( << "mitk::Surface::Graft cannot cast "
<< typeid(data).name() << " to "
<< typeid(const Self *).name() );
return;
}
if(!surface)
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::Graft cannot cast "
<< typeid(data).name() << " to "
<< typeid(const Self *).name() );
return;
}
this->CopyInformation( data );
//clear list of PolyData's
m_PolyDataSeries.clear();
// do copy
for (unsigned int i=0; i<surface->GetSizeOfPolyDataSeries(); i++)
{
m_PolyDataSeries.push_back(vtkPolyData::New());
m_PolyDataSeries.back()->DeepCopy( const_cast<mitk::Surface*>(surface)->GetVtkPolyData( i ) );
//CopyStructure( const_cast<mitk::Surface*>(surface)->GetVtkPolyData( i ) );
}
}
void mitk::Surface::PrintSelf( std::ostream& os, itk::Indent indent ) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Number PolyDatas: " << m_PolyDataSeries.size() << "\n";
unsigned int i = 0;
for (VTKPolyDataSeries::const_iterator it = m_PolyDataSeries.begin(); it != m_PolyDataSeries.end(); ++it)
{
vtkPolyData* pd = *it;
os << "\n";
os << indent << "Number of cells " << pd->GetNumberOfCells() << ": \n";
os << indent << "Number of points " << pd->GetNumberOfPoints() << ": \n\n";
os << indent << "VTKPolyData : \n";
pd->Print(os);
}
}<commit_msg>STYLE: removed unused variable<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkSurface.h"
#include "mitkInteractionConst.h"
#include "mitkSurfaceOperation.h"
#include <vtkPolyData.h>
#include <itkSmartPointerForwardReference.txx>
mitk::Surface::Surface() :
m_CalculateBoundingBox( false )
{
this->InitializeEmpty();
}
mitk::Surface::~Surface()
{
this->ClearData();
}
void mitk::Surface::ClearData()
{
for ( VTKPolyDataSeries::iterator it = m_PolyDataSeries.begin(); it != m_PolyDataSeries.end(); ++it )
{
if ( ( *it ) != NULL )
( *it )->Delete();
}
m_PolyDataSeries.clear();
Superclass::ClearData();
}
void mitk::Surface::InitializeEmpty()
{
vtkPolyData* pdnull = NULL;
m_PolyDataSeries.resize( 1, pdnull );
Superclass::InitializeTimeSlicedGeometry(1);
m_Initialized = true;
}
void mitk::Surface::SetVtkPolyData( vtkPolyData* polydata, unsigned int t )
{
// Adapt the size of the data vector if necessary
this->Expand( t+1 );
if(m_PolyDataSeries[ t ] != NULL)
{
// we do not need the reference on the object any longer
m_PolyDataSeries[ t ]->Delete();
}
m_PolyDataSeries[ t ] = polydata;
// call m_VtkPolyData->Register(NULL) to tell
// the reference counting that we want to keep a
// reference on the object
if(m_PolyDataSeries[ t ] != NULL)
{
m_PolyDataSeries[ t ]->Register( NULL );
}
this->Modified();
m_CalculateBoundingBox = true;
}
bool mitk::Surface::IsEmpty(unsigned int t) const
{
if(!IsInitialized())
return false;
vtkPolyData* polydata = const_cast<Surface*>(this)->GetVtkPolyData(t);
return
(polydata == NULL) ||
(
(polydata->GetNumberOfVerts() <= 0) &&
(polydata->GetNumberOfPolys() <= 0) &&
(polydata->GetNumberOfStrips() <= 0) &&
(polydata->GetNumberOfLines() <= 0)
);
}
vtkPolyData* mitk::Surface::GetVtkPolyData( unsigned int t )
{
if ( t < m_PolyDataSeries.size() )
{
vtkPolyData* polydata = m_PolyDataSeries[ t ];
if((polydata==NULL) && (GetSource().GetPointer()!=NULL))
{
RegionType requestedregion;
requestedregion.SetIndex(3, t);
requestedregion.SetSize(3, 1);
SetRequestedRegion(&requestedregion);
GetSource()->Update();
}
polydata = m_PolyDataSeries[ t ];
return polydata;
}
else
return NULL;
}
void mitk::Surface::UpdateOutputInformation()
{
if ( this->GetSource() )
{
this->GetSource()->UpdateOutputInformation();
}
if ( ( m_CalculateBoundingBox ) && ( m_PolyDataSeries.size() > 0 ) )
CalculateBoundingBox();
else
GetTimeSlicedGeometry()->UpdateInformation();
}
void mitk::Surface::CalculateBoundingBox()
{
//
// first make sure, that the associated time sliced geometry has
// the same number of geometry 3d's as vtkPolyDatas are present
//
mitk::TimeSlicedGeometry* timeGeometry = GetTimeSlicedGeometry();
if ( timeGeometry->GetTimeSteps() != m_PolyDataSeries.size() )
{
itkExceptionMacro(<<"timeGeometry->GetTimeSteps() != m_PolyDataSeries.size() -- use Initialize(timeSteps) with correct number of timeSteps!");
}
//
// Iterate over the vtkPolyDatas and update the Geometry
// information of each of the items.
//
for ( unsigned int i = 0 ; i < m_PolyDataSeries.size() ; ++i )
{
vtkPolyData* polyData = m_PolyDataSeries[ i ];
vtkFloatingPointType bounds[ ] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
if ( ( polyData != NULL ) && ( polyData->GetNumberOfPoints() > 0 ) )
{
polyData->Update();
polyData->ComputeBounds();
polyData->GetBounds( bounds );
}
mitk::Geometry3D::Pointer g3d = timeGeometry->GetGeometry3D( i );
assert( g3d.IsNotNull() );
g3d->SetFloatBounds( bounds );
}
timeGeometry->UpdateInformation();
mitk::BoundingBox::Pointer bb = const_cast<mitk::BoundingBox*>( timeGeometry->GetBoundingBox() );
itkDebugMacro( << "boundingbox min: "<< bb->GetMinimum());
itkDebugMacro( << "boundingbox max: "<< bb->GetMaximum());
m_CalculateBoundingBox = false;
}
void mitk::Surface::SetRequestedRegionToLargestPossibleRegion()
{
m_RequestedRegion = GetLargestPossibleRegion();
}
bool mitk::Surface::RequestedRegionIsOutsideOfTheBufferedRegion()
{
RegionType::IndexValueType end = m_RequestedRegion.GetIndex(3)+m_RequestedRegion.GetSize(3);
if(((RegionType::IndexValueType)m_PolyDataSeries.size())<end)
return true;
for( RegionType::IndexValueType t=m_RequestedRegion.GetIndex(3); t<end; ++t )
if(m_PolyDataSeries[t]==NULL)
return true;
return false;
}
bool mitk::Surface::VerifyRequestedRegion()
{
if( (m_RequestedRegion.GetIndex(3)>=0) &&
(m_RequestedRegion.GetIndex(3)+m_RequestedRegion.GetSize(3)<=m_PolyDataSeries.size()) )
return true;
return false;
}
void mitk::Surface::SetRequestedRegion( itk::DataObject *data )
{
mitk::Surface *surfaceData;
surfaceData = dynamic_cast<mitk::Surface*>(data);
if (surfaceData)
{
m_RequestedRegion = surfaceData->GetRequestedRegion();
}
else
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::SetRequestedRegion(DataObject*) cannot cast " << typeid(data).name() << " to " << typeid(Surface*).name() );
}
}
void mitk::Surface::SetRequestedRegion(Surface::RegionType *region) //by arin
{
if(region!=NULL)
{
m_RequestedRegion = *region;
}
else
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::SetRequestedRegion(Surface::RegionType*) cannot cast " << typeid(region).name() << " to " << typeid(Surface*).name() );
}
}
void mitk::Surface::CopyInformation( const itk::DataObject * data)
{
Superclass::CopyInformation( data );
const mitk::Surface* surfaceData;
surfaceData = dynamic_cast<const mitk::Surface*>( data );
if ( surfaceData )
{
m_LargestPossibleRegion = surfaceData->GetLargestPossibleRegion();
}
else
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::CopyInformation(const DataObject *data) cannot cast " << typeid(data).name() << " to " << typeid(surfaceData).name() );
}
}
void mitk::Surface::Update()
{
if ( GetSource() == NULL )
{
for ( VTKPolyDataSeries::iterator it = m_PolyDataSeries.begin() ; it != m_PolyDataSeries.end() ; ++it )
{
if ( ( *it ) != NULL )
( *it )->Update();
}
}
Superclass::Update();
}
void mitk::Surface::Expand( unsigned int timeSteps )
{
// check if the vector is long enough to contain the new element
// at the given position. If not, expand it with sufficient zero-filled elements.
if ( timeSteps > m_PolyDataSeries.size() )
{
Superclass::Expand( timeSteps );
vtkPolyData* pdnull = NULL;
m_PolyDataSeries.resize( timeSteps, pdnull );
m_CalculateBoundingBox = true;
}
}
void mitk::Surface::ExecuteOperation(Operation *operation)
{
switch ( operation->GetOperationType() )
{
case OpSURFACECHANGED:
mitk::SurfaceOperation* surfOp = dynamic_cast<mitk::SurfaceOperation*>(operation);
if( ! surfOp ) break;
unsigned int time = surfOp->GetTimeStep();
if(m_PolyDataSeries[ time ] != NULL)
{
vtkPolyData* updatePoly = surfOp->GetVtkPolyData();
if( updatePoly ){
this->SetVtkPolyData( updatePoly, time );
this->CalculateBoundingBox();
}
}
break;
}
this->Modified();
}
unsigned int mitk::Surface::GetSizeOfPolyDataSeries() const
{
return m_PolyDataSeries.size();
}
void mitk::Surface::Graft( const DataObject* data )
{
const Self* surface;
try
{
surface = dynamic_cast<const Self*>( data );
}
catch(...)
{
itkExceptionMacro( << "mitk::Surface::Graft cannot cast "
<< typeid(data).name() << " to "
<< typeid(const Self *).name() );
return;
}
if(!surface)
{
// pointer could not be cast back down
itkExceptionMacro( << "mitk::Surface::Graft cannot cast "
<< typeid(data).name() << " to "
<< typeid(const Self *).name() );
return;
}
this->CopyInformation( data );
//clear list of PolyData's
m_PolyDataSeries.clear();
// do copy
for (unsigned int i=0; i<surface->GetSizeOfPolyDataSeries(); i++)
{
m_PolyDataSeries.push_back(vtkPolyData::New());
m_PolyDataSeries.back()->DeepCopy( const_cast<mitk::Surface*>(surface)->GetVtkPolyData( i ) );
//CopyStructure( const_cast<mitk::Surface*>(surface)->GetVtkPolyData( i ) );
}
}
void mitk::Surface::PrintSelf( std::ostream& os, itk::Indent indent ) const
{
Superclass::PrintSelf(os, indent);
os << indent << "Number PolyDatas: " << m_PolyDataSeries.size() << "\n";
for (VTKPolyDataSeries::const_iterator it = m_PolyDataSeries.begin(); it != m_PolyDataSeries.end(); ++it)
{
vtkPolyData* pd = *it;
os << "\n";
os << indent << "Number of cells " << pd->GetNumberOfCells() << ": \n";
os << indent << "Number of points " << pd->GetNumberOfPoints() << ": \n\n";
os << indent << "VTKPolyData : \n";
pd->Print(os);
}
}<|endoftext|>
|
<commit_before>#include "mitkDataTreeNode.h"
#include "mitkMapperFactory.h"
#include <vtkTransform.h>
#include "mitkProperties.h"
#include "mitkFloatProperty.h"
#include "mitkStringProperty.h"
#include "mitkBoolProperty.h"
#include "mitkColorProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkGeometry3D.h"
//##ModelId=3D6A0E8C02CC
mitk::Mapper* mitk::DataTreeNode::GetMapper(MapperSlotId id) const
{
if (mappers[id].IsNull())
{
mappers[id] = MapperFactory::CreateMapper(const_cast<DataTreeNode*>(this),id);
}
return mappers[id];
}
//##ModelId=3E32C49D00A8
mitk::BaseData* mitk::DataTreeNode::GetData() const
{
return m_Data;
}
mitk::Interactor::Pointer mitk::DataTreeNode::GetInteractor() const
{
return m_Interactor;
}
//##ModelId=3E33F4E4025B
void mitk::DataTreeNode::SetData(mitk::BaseData* baseData)
{
if(m_Data!=baseData)
{
m_Data=baseData;
Modified();
}
}
void mitk::DataTreeNode::SetInteractor(mitk::Interactor* interactor)
{
m_Interactor = interactor;
}
//##ModelId=3E33F5D702AA
mitk::DataTreeNode::DataTreeNode() : m_Data(NULL)
{
memset(mappers, 0, sizeof(mappers));
m_PropertyList = PropertyList::New();
}
//##ModelId=3E33F5D702D3
mitk::DataTreeNode::~DataTreeNode()
{
}
//##ModelId=3E33F5D7032D
mitk::DataTreeNode& mitk::DataTreeNode::operator=(const DataTreeNode& right)
{
mitk::DataTreeNode* node=mitk::DataTreeNode::New();
node->SetData(right.GetData());
return *node;
}
mitk::DataTreeNode& mitk::DataTreeNode::operator=(mitk::BaseData* right)
{
mitk::DataTreeNode* node=mitk::DataTreeNode::New();
node->SetData(right);
return *node;
}
#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::istream& mitk::operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::istream& operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
{
dtn = mitk::DataTreeNode::New();
//i >> av.get();
return i;
}
#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::ostream& mitk::operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::ostream& operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
{
if(dtn->GetData()!=NULL)
o<<dtn->GetData()->GetNameOfClass();
else
o<<"empty data";
return o;
}
//##ModelId=3E69331903C9
void mitk::DataTreeNode::SetMapper(MapperSlotId id, mitk::Mapper* mapper)
{
mappers[id] = mapper;
if (mapper!=NULL)
mapper->SetInput(this);
}
//##ModelId=3E860A5C0032
void mitk::DataTreeNode::UpdateOutputInformation()
{
if (this->GetSource())
{
this->GetSource()->UpdateOutputInformation();
}
}
//##ModelId=3E860A5E011B
void mitk::DataTreeNode::SetRequestedRegionToLargestPossibleRegion()
{
}
//##ModelId=3E860A5F03D9
bool mitk::DataTreeNode::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return false;
}
//##ModelId=3E860A620080
bool mitk::DataTreeNode::VerifyRequestedRegion()
{
return true;
}
//##ModelId=3E860A640156
void mitk::DataTreeNode::SetRequestedRegion(itk::DataObject *data)
{
}
//##ModelId=3E860A6601DB
void mitk::DataTreeNode::CopyInformation(const itk::DataObject *data)
{
}
//##ModelId=3E3FE0420273
mitk::PropertyList::Pointer mitk::DataTreeNode::GetPropertyList(const mitk::BaseRenderer* renderer) const
{
if(renderer==NULL)
return m_PropertyList;
mitk::PropertyList::Pointer & propertyList = m_MapOfPropertyLists[renderer];
if(propertyList.IsNull())
propertyList = mitk::PropertyList::New();
assert(m_MapOfPropertyLists[renderer].IsNotNull());
return propertyList;
}
//##ModelId=3EF189DB0111
mitk::BaseProperty::Pointer mitk::DataTreeNode::GetProperty(const char *propertyKey, const mitk::BaseRenderer* renderer) const
{
if(propertyKey==NULL)
return NULL;
std::map<const mitk::BaseRenderer*,mitk::PropertyList::Pointer>::const_iterator it;
//does a renderer-specific PropertyList exist?
it=m_MapOfPropertyLists.find(renderer);
if(it==m_MapOfPropertyLists.end())
//no? use the renderer-independent one!
return m_PropertyList->GetProperty(propertyKey);
//does the renderer-specific PropertyList contain the @a propertyKey?
//and is it enabled
mitk::BaseProperty::Pointer property;
property=it->second->GetProperty(propertyKey);
if(property.IsNotNull() && property->GetEnabled())
//yes? return it
return property;
//no? use the renderer-independent one!
return m_PropertyList->GetProperty(propertyKey);
}
bool mitk::DataTreeNode::GetBoolProperty(const char* propertyKey, bool& boolValue, mitk::BaseRenderer* renderer) const
{
mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(boolprop.IsNull())
return false;
boolValue = boolprop->GetBool();
return true;
}
bool mitk::DataTreeNode::GetIntProperty(const char* propertyKey, int &intValue, mitk::BaseRenderer* renderer) const
{
mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(intprop.IsNull())
return false;
intValue = intprop->GetValue();
return true;
}
bool mitk::DataTreeNode::GetStringProperty(const char* propertyKey, const char* string, mitk::BaseRenderer* renderer) const
{
mitk::StringProperty::Pointer stringProp = dynamic_cast<mitk::StringProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(stringProp.IsNull())
{
return false;
}
else
{
memcpy((void*)string, stringProp->GetString(), strlen(stringProp->GetString()) + 1 );
return true;
}
}
bool mitk::DataTreeNode::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* propertyKey) const
{
mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(colorprop.IsNull())
return false;
memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float));
return true;
}
//##ModelId=3EF19420016B
bool mitk::DataTreeNode::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* propertyKey) const
{
mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(opacityprop.IsNull())
return false;
opacity=opacityprop->GetValue();
return true;
}
//##ModelId=3EF194220204
bool mitk::DataTreeNode::GetLevelWindow(mitk::LevelWindow &levelWindow, mitk::BaseRenderer* renderer, const char* propertyKey) const
{
mitk::LevelWindowProperty::Pointer levWinProp = dynamic_cast<mitk::LevelWindowProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(levWinProp.IsNull())
return false;
levelWindow=levWinProp->GetLevelWindow();
return true;
}
void mitk::DataTreeNode::SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::ColorProperty::Pointer prop;
prop = new mitk::ColorProperty(color);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::DataTreeNode::SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer, const char* propertyKey)
{
float color[3];
color[0]=red;
color[1]=green;
color[2]=blue;
SetColor(color, renderer, propertyKey);
}
//##ModelId=3EF196360303
void mitk::DataTreeNode::SetColor(const float rgb[3], mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::ColorProperty::Pointer prop;
prop = new mitk::ColorProperty(rgb);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
//##ModelId=3EF1966703D6
void mitk::DataTreeNode::SetVisibility(bool visible, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::BoolProperty::Pointer prop;
prop = new mitk::BoolProperty(visible);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
//##ModelId=3EF196880095
void mitk::DataTreeNode::SetOpacity(float opacity, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::FloatProperty::Pointer prop;
prop = new mitk::FloatProperty(opacity);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
//##ModelId=3EF1969A0181
void mitk::DataTreeNode::SetLevelWindow(mitk::LevelWindow levelWindow, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::LevelWindowProperty::Pointer prop;
prop = new mitk::LevelWindowProperty(levelWindow);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::DataTreeNode::SetIntProperty(const char* propertyKey, int intValue, mitk::BaseRenderer* renderer)
{
mitk::IntProperty::Pointer prop;
prop = new mitk::IntProperty(intValue);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::DataTreeNode::SetProperty(const char *propertyKey,
BaseProperty* propertyValue,
const mitk::BaseRenderer* renderer)
{
GetPropertyList(renderer)->SetProperty(propertyKey, propertyValue);
}
//##ModelId=3ED91D050121
vtkTransform* mitk::DataTreeNode::GetVtkTransform() const
{
assert(m_Data!=NULL);
assert(m_Data->GetGeometry()!=NULL);
return m_Data->GetGeometry()->GetVtkTransform();
}
unsigned long mitk::DataTreeNode::GetMTime() const
{
if((m_Data.IsNotNull()) && (Superclass::GetMTime()<m_Data->GetMTime()))
{
Modified();
}
return Superclass::GetMTime();
}
<commit_msg>corrected GetMTime: since GetMTime of a itk::DataObject returns only its MTime, not the PipelineMTime, the source (if available) is now taken into account.<commit_after>#include "mitkDataTreeNode.h"
#include "mitkMapperFactory.h"
#include <vtkTransform.h>
#include "mitkProperties.h"
#include "mitkFloatProperty.h"
#include "mitkStringProperty.h"
#include "mitkBoolProperty.h"
#include "mitkColorProperty.h"
#include "mitkLevelWindowProperty.h"
#include "mitkGeometry3D.h"
//##ModelId=3D6A0E8C02CC
mitk::Mapper* mitk::DataTreeNode::GetMapper(MapperSlotId id) const
{
if (mappers[id].IsNull())
{
mappers[id] = MapperFactory::CreateMapper(const_cast<DataTreeNode*>(this),id);
}
return mappers[id];
}
//##ModelId=3E32C49D00A8
mitk::BaseData* mitk::DataTreeNode::GetData() const
{
return m_Data;
}
mitk::Interactor::Pointer mitk::DataTreeNode::GetInteractor() const
{
return m_Interactor;
}
//##ModelId=3E33F4E4025B
void mitk::DataTreeNode::SetData(mitk::BaseData* baseData)
{
if(m_Data!=baseData)
{
m_Data=baseData;
Modified();
}
}
void mitk::DataTreeNode::SetInteractor(mitk::Interactor* interactor)
{
m_Interactor = interactor;
}
//##ModelId=3E33F5D702AA
mitk::DataTreeNode::DataTreeNode() : m_Data(NULL)
{
memset(mappers, 0, sizeof(mappers));
m_PropertyList = PropertyList::New();
}
//##ModelId=3E33F5D702D3
mitk::DataTreeNode::~DataTreeNode()
{
}
//##ModelId=3E33F5D7032D
mitk::DataTreeNode& mitk::DataTreeNode::operator=(const DataTreeNode& right)
{
mitk::DataTreeNode* node=mitk::DataTreeNode::New();
node->SetData(right.GetData());
return *node;
}
mitk::DataTreeNode& mitk::DataTreeNode::operator=(mitk::BaseData* right)
{
mitk::DataTreeNode* node=mitk::DataTreeNode::New();
node->SetData(right);
return *node;
}
#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::istream& mitk::operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::istream& operator>>( MBI_STD::istream& i, mitk::DataTreeNode::Pointer& dtn )
#endif
{
dtn = mitk::DataTreeNode::New();
//i >> av.get();
return i;
}
#if (_MSC_VER > 1200) || !defined(_MSC_VER)
MBI_STD::ostream& mitk::operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
#if ((defined(_MSC_VER)) && (_MSC_VER <= 1200))
MBI_STD::ostream& operator<<( MBI_STD::ostream& o, mitk::DataTreeNode::Pointer& dtn)
#endif
{
if(dtn->GetData()!=NULL)
o<<dtn->GetData()->GetNameOfClass();
else
o<<"empty data";
return o;
}
//##ModelId=3E69331903C9
void mitk::DataTreeNode::SetMapper(MapperSlotId id, mitk::Mapper* mapper)
{
mappers[id] = mapper;
if (mapper!=NULL)
mapper->SetInput(this);
}
//##ModelId=3E860A5C0032
void mitk::DataTreeNode::UpdateOutputInformation()
{
if (this->GetSource())
{
this->GetSource()->UpdateOutputInformation();
}
}
//##ModelId=3E860A5E011B
void mitk::DataTreeNode::SetRequestedRegionToLargestPossibleRegion()
{
}
//##ModelId=3E860A5F03D9
bool mitk::DataTreeNode::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return false;
}
//##ModelId=3E860A620080
bool mitk::DataTreeNode::VerifyRequestedRegion()
{
return true;
}
//##ModelId=3E860A640156
void mitk::DataTreeNode::SetRequestedRegion(itk::DataObject *data)
{
}
//##ModelId=3E860A6601DB
void mitk::DataTreeNode::CopyInformation(const itk::DataObject *data)
{
}
//##ModelId=3E3FE0420273
mitk::PropertyList::Pointer mitk::DataTreeNode::GetPropertyList(const mitk::BaseRenderer* renderer) const
{
if(renderer==NULL)
return m_PropertyList;
mitk::PropertyList::Pointer & propertyList = m_MapOfPropertyLists[renderer];
if(propertyList.IsNull())
propertyList = mitk::PropertyList::New();
assert(m_MapOfPropertyLists[renderer].IsNotNull());
return propertyList;
}
//##ModelId=3EF189DB0111
mitk::BaseProperty::Pointer mitk::DataTreeNode::GetProperty(const char *propertyKey, const mitk::BaseRenderer* renderer) const
{
if(propertyKey==NULL)
return NULL;
std::map<const mitk::BaseRenderer*,mitk::PropertyList::Pointer>::const_iterator it;
//does a renderer-specific PropertyList exist?
it=m_MapOfPropertyLists.find(renderer);
if(it==m_MapOfPropertyLists.end())
//no? use the renderer-independent one!
return m_PropertyList->GetProperty(propertyKey);
//does the renderer-specific PropertyList contain the @a propertyKey?
//and is it enabled
mitk::BaseProperty::Pointer property;
property=it->second->GetProperty(propertyKey);
if(property.IsNotNull() && property->GetEnabled())
//yes? return it
return property;
//no? use the renderer-independent one!
return m_PropertyList->GetProperty(propertyKey);
}
bool mitk::DataTreeNode::GetBoolProperty(const char* propertyKey, bool& boolValue, mitk::BaseRenderer* renderer) const
{
mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(boolprop.IsNull())
return false;
boolValue = boolprop->GetBool();
return true;
}
bool mitk::DataTreeNode::GetIntProperty(const char* propertyKey, int &intValue, mitk::BaseRenderer* renderer) const
{
mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(intprop.IsNull())
return false;
intValue = intprop->GetValue();
return true;
}
bool mitk::DataTreeNode::GetStringProperty(const char* propertyKey, const char* string, mitk::BaseRenderer* renderer) const
{
mitk::StringProperty::Pointer stringProp = dynamic_cast<mitk::StringProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(stringProp.IsNull())
{
return false;
}
else
{
memcpy((void*)string, stringProp->GetString(), strlen(stringProp->GetString()) + 1 );
return true;
}
}
bool mitk::DataTreeNode::GetColor(float rgb[3], mitk::BaseRenderer* renderer, const char* propertyKey) const
{
mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(colorprop.IsNull())
return false;
memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float));
return true;
}
//##ModelId=3EF19420016B
bool mitk::DataTreeNode::GetOpacity(float &opacity, mitk::BaseRenderer* renderer, const char* propertyKey) const
{
mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(opacityprop.IsNull())
return false;
opacity=opacityprop->GetValue();
return true;
}
//##ModelId=3EF194220204
bool mitk::DataTreeNode::GetLevelWindow(mitk::LevelWindow &levelWindow, mitk::BaseRenderer* renderer, const char* propertyKey) const
{
mitk::LevelWindowProperty::Pointer levWinProp = dynamic_cast<mitk::LevelWindowProperty*>(GetProperty(propertyKey, renderer).GetPointer());
if(levWinProp.IsNull())
return false;
levelWindow=levWinProp->GetLevelWindow();
return true;
}
void mitk::DataTreeNode::SetColor(const mitk::Color &color, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::ColorProperty::Pointer prop;
prop = new mitk::ColorProperty(color);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::DataTreeNode::SetColor(float red, float green, float blue, mitk::BaseRenderer* renderer, const char* propertyKey)
{
float color[3];
color[0]=red;
color[1]=green;
color[2]=blue;
SetColor(color, renderer, propertyKey);
}
//##ModelId=3EF196360303
void mitk::DataTreeNode::SetColor(const float rgb[3], mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::ColorProperty::Pointer prop;
prop = new mitk::ColorProperty(rgb);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
//##ModelId=3EF1966703D6
void mitk::DataTreeNode::SetVisibility(bool visible, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::BoolProperty::Pointer prop;
prop = new mitk::BoolProperty(visible);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
//##ModelId=3EF196880095
void mitk::DataTreeNode::SetOpacity(float opacity, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::FloatProperty::Pointer prop;
prop = new mitk::FloatProperty(opacity);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
//##ModelId=3EF1969A0181
void mitk::DataTreeNode::SetLevelWindow(mitk::LevelWindow levelWindow, mitk::BaseRenderer* renderer, const char* propertyKey)
{
mitk::LevelWindowProperty::Pointer prop;
prop = new mitk::LevelWindowProperty(levelWindow);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::DataTreeNode::SetIntProperty(const char* propertyKey, int intValue, mitk::BaseRenderer* renderer)
{
mitk::IntProperty::Pointer prop;
prop = new mitk::IntProperty(intValue);
GetPropertyList(renderer)->SetProperty(propertyKey, prop);
}
void mitk::DataTreeNode::SetProperty(const char *propertyKey,
BaseProperty* propertyValue,
const mitk::BaseRenderer* renderer)
{
GetPropertyList(renderer)->SetProperty(propertyKey, propertyValue);
}
//##ModelId=3ED91D050121
vtkTransform* mitk::DataTreeNode::GetVtkTransform() const
{
assert(m_Data!=NULL);
assert(m_Data->GetGeometry()!=NULL);
return m_Data->GetGeometry()->GetVtkTransform();
}
unsigned long mitk::DataTreeNode::GetMTime() const
{
unsigned long time = Superclass::GetMTime();
if(m_Data.IsNotNull())
{
if((time < m_Data->GetMTime()) ||
((m_Data->GetSource() != NULL) && (time < m_Data->GetSource()->GetMTime()))
)
Modified();
}
return Superclass::GetMTime();
}
<|endoftext|>
|
<commit_before>//
// C++ Interface: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <[email protected]>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef _BUILTIN_FUNCS_HPP
#define _BUILTIN_FUNCS_HPP
#include "Common.hpp"
#include "Func.hpp"
#include <cmath>
#include <cstdlib>
#include <cassert>
#include "RandomNumberGenerators.hpp"
/* Wrappers for all the builtin functions
The arg_list pointer is a list of floats. Its
size is equal to the number of arguments the parameter
takes */
class FuncWrappers {
/* Values to optimize the sigmoid function */
static const int R = 32767;
static const int RR = 65534;
public:
static inline float int_wrapper(float * arg_list) {
return floor(arg_list[0]);
}
static inline float sqr_wrapper(float * arg_list) {
return pow(2, arg_list[0]);
}
static inline float sign_wrapper(float * arg_list) {
return -arg_list[0];
}
static inline float min_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[1];
return arg_list[0];
}
static inline float max_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[0];
return arg_list[1];
}
/* consult your AI book */
static inline float sigmoid_wrapper(float * arg_list) {
return (RR / (1 + exp( -(((float)(arg_list[0])) * arg_list[1]) / R) - R));
}
static inline float bor_wrapper(float * arg_list) {
return (float)((int)arg_list[0] || (int)arg_list[1]);
}
static inline float band_wrapper(float * arg_list) {
return (float)((int)arg_list[0] && (int)arg_list[1]);
}
static inline float bnot_wrapper(float * arg_list) {
return (float)(!(int)arg_list[0]);
}
static inline float if_wrapper(float * arg_list) {
if ((int)arg_list[0] == 0)
return arg_list[2];
return arg_list[1];
}
static inline float rand_wrapper(float * arg_list) {
float l=1;
// printf("RAND ARG:(%d)\n", (int)arg_list[0]);
if ((int)arg_list[0] > 0)
l = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);
return l;
}
static inline float equal_wrapper(float * arg_list) {
return (arg_list[0] == arg_list[1]);
}
static inline float above_wrapper(float * arg_list) {
return (arg_list[0] > arg_list[1]);
}
static inline float below_wrapper(float * arg_list) {
return (arg_list[0] < arg_list[1]);
}
static float sin_wrapper(float * arg_list) {
assert(arg_list);
//return .5;
float d = sinf(*arg_list);
return d;
//return (sin (arg_list[0]));
}
static inline float cos_wrapper(float * arg_list) {
return (cos (arg_list[0]));
}
static inline float tan_wrapper(float * arg_list) {
return (tan(arg_list[0]));
}
static inline float asin_wrapper(float * arg_list) {
return (asin (arg_list[0]));
}
static inline float acos_wrapper(float * arg_list) {
return (acos (arg_list[0]));
}
static inline float atan_wrapper(float * arg_list) {
return (atan (arg_list[0]));
}
static inline float atan2_wrapper(float * arg_list) {
return (atan2 (arg_list[0], arg_list[1]));
}
static inline float pow_wrapper(float * arg_list) {
return (pow (arg_list[0], arg_list[1]));
}
static inline float exp_wrapper(float * arg_list) {
return (exp(arg_list[0]));
}
static inline float abs_wrapper(float * arg_list) {
return (fabs(arg_list[0]));
}
static inline float log_wrapper(float* arg_list) {
return (log (arg_list[0]));
}
static inline float log10_wrapper(float * arg_list) {
return (log10 (arg_list[0]));
}
static inline float sqrt_wrapper(float * arg_list) {
return (sqrt (arg_list[0]));
}
static inline float nchoosek_wrapper(float * arg_list) {
unsigned long cnm = 1UL;
int i, f;
int n, m;
n = (int)arg_list[0];
m = (int)arg_list[1];
if (m*2 >n) m = n-m;
for (i=1 ; i <= m; n--, i++)
{
if ((f=n) % i == 0)
f /= i;
else cnm /= i;
cnm *= f;
}
return (float)cnm;
}
static inline float fact_wrapper(float * arg_list) {
int result = 1;
int n = (int)arg_list[0];
while (n > 1) {
result = result * n;
n--;
}
return (float)result;
}
};
#include <map>
class BuiltinFuncs {
public:
static int init_builtin_func_db();
static int destroy_builtin_func_db();
static int load_all_builtin_func();
static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );
static int insert_func( Func *func );
static int remove_func( Func *func );
static Func *find_func( const std::string & name );
private:
static std::map<std::string, Func*> builtin_func_tree;
static volatile bool initialized;
};
#endif
<commit_msg>another crucial fix by mastertrenten. --this line, and those below, will be ignored--<commit_after>//
// C++ Interface: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <[email protected]>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef _BUILTIN_FUNCS_HPP
#define _BUILTIN_FUNCS_HPP
#include "Common.hpp"
#include "Func.hpp"
#include <cmath>
#include <cstdlib>
#include <cassert>
#include "RandomNumberGenerators.hpp"
/* Wrappers for all the builtin functions
The arg_list pointer is a list of floats. Its
size is equal to the number of arguments the parameter
takes */
class FuncWrappers {
/* Values to optimize the sigmoid function */
static const int R = 32767;
static const int RR = 65534;
public:
static inline float int_wrapper(float * arg_list) {
return floor(arg_list[0]);
}
static inline float sqr_wrapper(float * arg_list) {
return pow(arg_list[0], 2);
}
static inline float sigmoid_wrapper(float * arg_list)
{
const double t = (1+exp(-arg_list[0]*arg_list[1]));
return (fabs(t) > 0.00001) ? 1.0/t : 0;
}
static inline float sign_wrapper(float * arg_list) {
return -arg_list[0];
}
static inline float min_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[1];
return arg_list[0];
}
static inline float max_wrapper(float * arg_list) {
if (arg_list[0] > arg_list[1])
return arg_list[0];
return arg_list[1];
}
static inline float bor_wrapper(float * arg_list) {
return (float)((int)arg_list[0] || (int)arg_list[1]);
}
static inline float band_wrapper(float * arg_list) {
return (float)((int)arg_list[0] && (int)arg_list[1]);
}
static inline float bnot_wrapper(float * arg_list) {
return (float)(!(int)arg_list[0]);
}
static inline float if_wrapper(float * arg_list) {
if ((int)arg_list[0] == 0)
return arg_list[2];
return arg_list[1];
}
static inline float rand_wrapper(float * arg_list) {
float l=1;
// printf("RAND ARG:(%d)\n", (int)arg_list[0]);
if ((int)arg_list[0] > 0)
l = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);
return l;
}
static inline float equal_wrapper(float * arg_list) {
return (arg_list[0] == arg_list[1]);
}
static inline float above_wrapper(float * arg_list) {
return (arg_list[0] > arg_list[1]);
}
static inline float below_wrapper(float * arg_list) {
return (arg_list[0] < arg_list[1]);
}
static float sin_wrapper(float * arg_list) {
assert(arg_list);
//return .5;
float d = sinf(*arg_list);
return d;
//return (sin (arg_list[0]));
}
static inline float cos_wrapper(float * arg_list) {
return (cos (arg_list[0]));
}
static inline float tan_wrapper(float * arg_list) {
return (tan(arg_list[0]));
}
static inline float asin_wrapper(float * arg_list) {
return (asin (arg_list[0]));
}
static inline float acos_wrapper(float * arg_list) {
return (acos (arg_list[0]));
}
static inline float atan_wrapper(float * arg_list) {
return (atan (arg_list[0]));
}
static inline float atan2_wrapper(float * arg_list) {
return (atan2 (arg_list[0], arg_list[1]));
}
static inline float pow_wrapper(float * arg_list) {
return (pow (arg_list[0], arg_list[1]));
}
static inline float exp_wrapper(float * arg_list) {
return (exp(arg_list[0]));
}
static inline float abs_wrapper(float * arg_list) {
return (fabs(arg_list[0]));
}
static inline float log_wrapper(float* arg_list) {
return (log (arg_list[0]));
}
static inline float log10_wrapper(float * arg_list) {
return (log10 (arg_list[0]));
}
static inline float sqrt_wrapper(float * arg_list) {
return (sqrt (arg_list[0]));
}
static inline float nchoosek_wrapper(float * arg_list) {
unsigned long cnm = 1UL;
int i, f;
int n, m;
n = (int)arg_list[0];
m = (int)arg_list[1];
if (m*2 >n) m = n-m;
for (i=1 ; i <= m; n--, i++)
{
if ((f=n) % i == 0)
f /= i;
else cnm /= i;
cnm *= f;
}
return (float)cnm;
}
static inline float fact_wrapper(float * arg_list) {
int result = 1;
int n = (int)arg_list[0];
while (n > 1) {
result = result * n;
n--;
}
return (float)result;
}
};
#include <map>
class BuiltinFuncs {
public:
static int init_builtin_func_db();
static int destroy_builtin_func_db();
static int load_all_builtin_func();
static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );
static int insert_func( Func *func );
static int remove_func( Func *func );
static Func *find_func( const std::string & name );
private:
static std::map<std::string, Func*> builtin_func_tree;
static volatile bool initialized;
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013, Christian Loose
* 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.
*/
#include "telnetclient.h"
#include <QDebug>
#include <QTcpSocket>
#include "telnetcommands.h"
namespace q5250 {
void OutputData(const QByteArray &data)
{
// qDebug() << "--- SERVER ---";
// for (int i = 0; i < data.size(); ++i) {
// qDebug() << QString::number(uchar(data[i]), 16)
// << QString::number(uchar(data[i]))
// << data[i];
// }
}
namespace Command {
//enum Commands {
// SE = 240,
// SB = 250,
// WILL = 251,
// WONT = 252,
// DO = 253,
// DONT = 254,
// IAC = 255
//};
Commands fromByte(const unsigned char byte)
{
return (Commands)byte;
}
//bool isOptionCommand(const unsigned char byte)
//{
// Commands command = fromByte(byte);
// return command == Command::WILL || command == Command::WONT ||
// command == Command::DO || command == Command::DONT;
//}
}
namespace Option {
enum Options {
TRANSMIT_BINARY = 0, // RFC856
ECHO = 1, // RFC857
SUPPRESS_GO_AHEAD = 3, // RFC858
STATUS = 5, // RFC859
LOGOUT = 18, // RFC727
TERMINAL_TYPE = 24, // RFC1091
END_OF_RECORD = 25, // RFC885
NAWS = 31, // RFC1073
NEW_ENVIRON = 39 // RFC1572
};
Options fromByte(const unsigned char byte)
{
return (Options)byte;
}
}
namespace SubnegotiationCommand {
enum {
IS = 0,
SEND = 1
};
}
class TelnetClient::Private : public QObject
{
Q_OBJECT
public:
explicit Private(TelnetClient *parent);
void setSocket(QTcpSocket *socket);
TelnetClient *q;
QTcpSocket *socket;
QString terminalType;
QByteArray buffer;
QMap<Option::Options, bool> modes;
QList<QPair<unsigned char, unsigned char>> sentOptions;
bool connected;
void consume();
int parseCommand(const QByteArray &data);
Command::Commands replyFor(Command::Commands command, bool allowed);
void sendCommand(Command::Commands command, Option::Options option);
void sendCommand(const char *command, int length);
void sendString(const QString &str);
bool isOptionAllowed(Option::Options option);
bool isOptionCommand(const QByteArray &data);
bool isSubnegotiationCommand(const QByteArray &data);
QByteArray subnegotiationParameters(const QByteArray &data);
void stateTerminalType(const QByteArray &data);
void setMode(Command::Commands command, Option::Options option);
bool replyNeeded(Command::Commands command, Option::Options option);
void addSentOption(const unsigned char command, const unsigned char option);
bool alreadySent(const unsigned char command, const unsigned char option);
public slots:
void socketConnected();
void socketReadyRead();
};
TelnetClient::Private::Private(TelnetClient *parent) :
q(parent),
socket(0),
connected(false),
terminalType("UNKNOWN")
{
setSocket(new QTcpSocket(this));
}
void TelnetClient::Private::setSocket(QTcpSocket *s)
{
if (socket) {
socket->flush();
}
delete socket;
socket = s;
connected = false;
if (socket) {
connect(socket, &QTcpSocket::connected, this, &Private::socketConnected);
connect(socket, &QTcpSocket::readyRead, this, &Private::socketReadyRead);
}
}
void TelnetClient::Private::consume()
{
int currentPos = 0;
int previousPos = -1;
while (previousPos < currentPos && currentPos < buffer.size()) {
previousPos = currentPos;
const uchar c = (uchar)buffer[currentPos];
switch (c) {
case Command::IAC:
currentPos += parseCommand(buffer.mid(currentPos));
break;
default:
QByteArray data = buffer.mid(currentPos);
emit q->dataReceived(data);
currentPos += data.size();
break;
}
}
if (currentPos < buffer.size()) {
buffer = buffer.mid(currentPos);
} else {
buffer.clear();
}
}
int TelnetClient::Private::parseCommand(const QByteArray &data)
{
if (data.isEmpty()) return 0;
if (isOptionCommand(data)) {
Command::Commands command = Command::fromByte(data[1]);
Option::Options option = Option::fromByte(data[2]);
if (replyNeeded(command, option)) {
bool allowed = isOptionAllowed(option);
sendCommand(replyFor(command, allowed), option);
setMode(command, option);
}
return 3;
}
if (isSubnegotiationCommand(data)) {
QByteArray parameters = subnegotiationParameters(data);
Option::Options option = Option::fromByte(parameters[0]);
switch (option) {
case Option::TERMINAL_TYPE:
stateTerminalType(parameters);
break;
default:
break;
}
return parameters.size() + 4;
}
return 0;
}
Command::Commands TelnetClient::Private::replyFor(Command::Commands command, bool allowed)
{
switch (command) {
case Command::DO:
return allowed ? Command::WILL : Command::WONT;
break;
case Command::DONT:
return Command::WONT;
case Command::WILL:
return allowed ? Command::DO : Command::DONT;
case Command::WONT:
return Command::DONT;
default:
break;
}
}
void TelnetClient::Private::sendCommand(Command::Commands command, Option::Options option)
{
QByteArray replyData;
replyData.resize(3);
replyData[0] = Command::IAC;
replyData[1] = command;
replyData[2] = option;
if (alreadySent(replyData[1], replyData[2]))
return;
addSentOption(replyData[1], replyData[2]);
socket->write(replyData);
}
void TelnetClient::Private::sendCommand(const char *command, int length)
{
QByteArray replyData(command, length);
socket->write(replyData);
}
void TelnetClient::Private::sendString(const QString &str)
{
socket->write(str.toLocal8Bit());
}
bool TelnetClient::Private::isOptionAllowed(Option::Options option)
{
// the following telnet options are supported
return option == Option::END_OF_RECORD ||
option == Option::NEW_ENVIRON ||
option == Option::TERMINAL_TYPE ||
option == Option::TRANSMIT_BINARY;
}
bool TelnetClient::Private::isOptionCommand(const QByteArray &data)
{
return data.size() >= 3 && Command::isOptionCommand(data[1]);
}
bool TelnetClient::Private::isSubnegotiationCommand(const QByteArray &data)
{
return data.size() >= 4 && Command::fromByte(data[1]) == Command::SB;
}
QByteArray TelnetClient::Private::subnegotiationParameters(const QByteArray &data)
{
for (int i = 2; i < data.size() - 1; ++i) {
if (Command::fromByte(data[i]) == Command::IAC && Command::fromByte(data[i+1]) == Command::SE) {
return data.mid(2, i-2);
}
}
return QByteArray();
}
void TelnetClient::Private::stateTerminalType(const QByteArray &data)
{
if (data[1] != SubnegotiationCommand::SEND)
return;
const char c1[4] = { (char)Command::IAC, (char)Command::SB, Option::TERMINAL_TYPE, SubnegotiationCommand::IS };
sendCommand(c1, sizeof(c1));
sendString(terminalType);
const char c2[2] = { (char)Command::IAC, (char)Command::SE };
sendCommand(c2, sizeof(c2));
}
void TelnetClient::Private::setMode(Command::Commands command, Option::Options option)
{
if (command != Command::DO && command != Command::DONT)
return;
modes[option] = (command == Command::DO);
}
bool TelnetClient::Private::replyNeeded(Command::Commands command, Option::Options option)
{
if (command == Command::DO || command == Command::DONT) {
// RFC854 requires that we don't acknowledge
// requests to enter a mode we're already in
if (command == Command::DO && modes[option])
return false;
if (command == Command::DONT && !modes[option])
return false;
}
return true;
}
void TelnetClient::Private::addSentOption(const unsigned char command, const unsigned char option)
{
sentOptions.append(QPair<unsigned char, unsigned char>(command, option));
}
bool TelnetClient::Private::alreadySent(const unsigned char command, const unsigned char option)
{
QPair<unsigned char, unsigned char> value(command, option);
if (sentOptions.contains(value)) {
sentOptions.removeAll(value);
return true;
}
return false;
}
void TelnetClient::Private::socketConnected()
{
connected = true;
}
void TelnetClient::Private::socketReadyRead()
{
buffer.append(socket->readAll());
OutputData(buffer);
consume();
}
TelnetClient::TelnetClient(QObject *parent) :
QObject(parent),
d(new Private(this))
{
}
TelnetClient::~TelnetClient()
{
}
void TelnetClient::setTerminalType(const QString &terminalType)
{
d->terminalType = terminalType;
}
QString TelnetClient::terminalType() const
{
return d->terminalType;
}
void TelnetClient::connectToHost(const QString &hostName, quint16 port)
{
if (d->connected) {
qWarning() << "telnet client is already connected";
return;
}
qDebug() << "client connects to host" << hostName << "on port" << port;
d->socket->connectToHost(hostName, port);
}
} // namespace q5250
#include "telnetclient.moc"
<commit_msg>Integrate TelnetParser into TelnetClient<commit_after>/*
* Copyright (c) 2013, Christian Loose
* 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.
*/
#include "telnetclient.h"
#include <QDebug>
#include <QTcpSocket>
#include "telnetcommands.h"
#include "telnetparser.h"
namespace q5250 {
void OutputData(const QByteArray &data)
{
qDebug() << "--- SERVER ---";
for (int i = 0; i < data.size(); ++i) {
qDebug() << QString::number(uchar(data[i]), 16)
<< QString::number(uchar(data[i]))
<< data[i];
}
}
namespace Command {
Commands fromByte(const unsigned char byte)
{
return (Commands)byte;
}
}
namespace Option {
enum Options {
TRANSMIT_BINARY = 0, // RFC856
ECHO = 1, // RFC857
SUPPRESS_GO_AHEAD = 3, // RFC858
STATUS = 5, // RFC859
LOGOUT = 18, // RFC727
TERMINAL_TYPE = 24, // RFC1091
END_OF_RECORD = 25, // RFC885
NAWS = 31, // RFC1073
NEW_ENVIRON = 39 // RFC1572
};
Options fromByte(const unsigned char byte)
{
return (Options)byte;
}
}
namespace SubnegotiationCommand {
enum {
IS = 0,
SEND = 1
};
}
class TelnetClient::Private : public QObject
{
Q_OBJECT
public:
explicit Private(TelnetClient *parent);
void setSocket(QTcpSocket *socket);
TelnetClient *q;
QTcpSocket *socket;
QString terminalType;
QByteArray buffer;
QMap<Option::Options, bool> modes;
QList<QPair<unsigned char, unsigned char>> sentOptions;
bool connected;
Command::Commands replyFor(Command::Commands command, bool allowed);
void sendCommand(Command::Commands command, Option::Options option);
void sendCommand(const char *command, int length);
void sendString(const QString &str);
bool isOptionAllowed(Option::Options option);
QByteArray subnegotiationParameters(const QByteArray &data);
void stateTerminalType(uchar subnegotiationCommand);
void setMode(Command::Commands command, Option::Options option);
bool replyNeeded(Command::Commands command, Option::Options option);
void addSentOption(const unsigned char command, const unsigned char option);
bool alreadySent(const unsigned char command, const unsigned char option);
public slots:
void socketConnected();
void socketReadyRead();
void optionCommandReceived(uchar commandByte, uchar optionByte);
void subnegotationReceived(uchar optionByte, uchar subnegotiationCommand);
private:
TelnetParser parser;
};
TelnetClient::Private::Private(TelnetClient *parent) :
q(parent),
socket(0),
connected(false),
terminalType("UNKNOWN")
{
setSocket(new QTcpSocket(this));
connect(&parser, &TelnetParser::dataReceived,
q, &TelnetClient::dataReceived);
connect(&parser, &TelnetParser::optionCommandReceived,
this, &Private::optionCommandReceived);
connect(&parser, &TelnetParser::subnegotationReceived,
this, &Private::subnegotationReceived);
}
void TelnetClient::Private::setSocket(QTcpSocket *s)
{
if (socket) {
socket->flush();
}
delete socket;
socket = s;
connected = false;
if (socket) {
connect(socket, &QTcpSocket::connected, this, &Private::socketConnected);
connect(socket, &QTcpSocket::readyRead, this, &Private::socketReadyRead);
}
}
//int TelnetClient::Private::parseCommand(const QByteArray &data)
//{
// if (data.isEmpty()) return 0;
// if (isOptionCommand(data)) {
// Command::Commands command = Command::fromByte(data[1]);
// Option::Options option = Option::fromByte(data[2]);
// if (replyNeeded(command, option)) {
// bool allowed = isOptionAllowed(option);
// sendCommand(replyFor(command, allowed), option);
// setMode(command, option);
// }
// return 3;
// }
// if (isSubnegotiationCommand(data)) {
// QByteArray parameters = subnegotiationParameters(data);
// Option::Options option = Option::fromByte(parameters[0]);
// switch (option) {
// case Option::TERMINAL_TYPE:
// stateTerminalType(parameters);
// break;
// default:
// break;
// }
// return parameters.size() + 4;
// }
// return 0;
//}
Command::Commands TelnetClient::Private::replyFor(Command::Commands command, bool allowed)
{
switch (command) {
case Command::DO:
return allowed ? Command::WILL : Command::WONT;
break;
case Command::DONT:
return Command::WONT;
case Command::WILL:
return allowed ? Command::DO : Command::DONT;
case Command::WONT:
return Command::DONT;
default:
break;
}
}
void TelnetClient::Private::sendCommand(Command::Commands command, Option::Options option)
{
QByteArray replyData;
replyData.resize(3);
replyData[0] = Command::IAC;
replyData[1] = command;
replyData[2] = option;
if (alreadySent(replyData[1], replyData[2]))
return;
addSentOption(replyData[1], replyData[2]);
socket->write(replyData);
}
void TelnetClient::Private::sendCommand(const char *command, int length)
{
QByteArray replyData(command, length);
socket->write(replyData);
}
void TelnetClient::Private::sendString(const QString &str)
{
socket->write(str.toLocal8Bit());
}
bool TelnetClient::Private::isOptionAllowed(Option::Options option)
{
// the following telnet options are supported
return option == Option::END_OF_RECORD ||
option == Option::NEW_ENVIRON ||
option == Option::TERMINAL_TYPE ||
option == Option::TRANSMIT_BINARY;
}
QByteArray TelnetClient::Private::subnegotiationParameters(const QByteArray &data)
{
for (int i = 2; i < data.size() - 1; ++i) {
if (Command::fromByte(data[i]) == Command::IAC && Command::fromByte(data[i+1]) == Command::SE) {
return data.mid(2, i-2);
}
}
return QByteArray();
}
void TelnetClient::Private::stateTerminalType(uchar subnegotiationCommand)
{
if (subnegotiationCommand != SubnegotiationCommand::SEND)
return;
const char c1[4] = { (char)Command::IAC, (char)Command::SB, Option::TERMINAL_TYPE, SubnegotiationCommand::IS };
sendCommand(c1, sizeof(c1));
sendString(terminalType);
const char c2[2] = { (char)Command::IAC, (char)Command::SE };
sendCommand(c2, sizeof(c2));
}
void TelnetClient::Private::setMode(Command::Commands command, Option::Options option)
{
if (command != Command::DO && command != Command::DONT)
return;
modes[option] = (command == Command::DO);
}
bool TelnetClient::Private::replyNeeded(Command::Commands command, Option::Options option)
{
if (command == Command::DO || command == Command::DONT) {
// RFC854 requires that we don't acknowledge
// requests to enter a mode we're already in
if (command == Command::DO && modes[option])
return false;
if (command == Command::DONT && !modes[option])
return false;
}
return true;
}
void TelnetClient::Private::addSentOption(const unsigned char command, const unsigned char option)
{
sentOptions.append(QPair<unsigned char, unsigned char>(command, option));
}
bool TelnetClient::Private::alreadySent(const unsigned char command, const unsigned char option)
{
QPair<unsigned char, unsigned char> value(command, option);
if (sentOptions.contains(value)) {
sentOptions.removeAll(value);
return true;
}
return false;
}
void TelnetClient::Private::socketConnected()
{
connected = true;
}
void TelnetClient::Private::socketReadyRead()
{
// buffer.append(socket->readAll());
buffer = socket->readAll();
// OutputData(buffer);
parser.parse(buffer);
}
void TelnetClient::Private::optionCommandReceived(uchar commandByte, uchar optionByte)
{
Command::Commands command = Command::fromByte(commandByte);
Option::Options option = Option::fromByte(optionByte);
if (replyNeeded(command, option)) {
bool allowed = isOptionAllowed(option);
sendCommand(replyFor(command, allowed), option);
setMode(command, option);
}
}
void TelnetClient::Private::subnegotationReceived(uchar optionByte, uchar subnegotiationCommand)
{
Option::Options option = Option::fromByte(optionByte);
switch (option) {
case Option::TERMINAL_TYPE:
stateTerminalType(subnegotiationCommand/*parameters*/);
break;
default:
break;
}
}
TelnetClient::TelnetClient(QObject *parent) :
QObject(parent),
d(new Private(this))
{
}
TelnetClient::~TelnetClient()
{
}
void TelnetClient::setTerminalType(const QString &terminalType)
{
d->terminalType = terminalType;
}
QString TelnetClient::terminalType() const
{
return d->terminalType;
}
void TelnetClient::connectToHost(const QString &hostName, quint16 port)
{
if (d->connected) {
qWarning() << "telnet client is already connected";
return;
}
qDebug() << "client connects to host" << hostName << "on port" << port;
d->socket->connectToHost(hostName, port);
}
} // namespace q5250
#include "telnetclient.moc"
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
map <string ,int> Dict;
bool end=false;
//debug
#ifdef LOCAL
#define fp stdin
#else
FILE *fp;
#endif
char last=0;
char ch;
string getword(){
string s;
if (last){
s.push_back(last);
last=0;
}
while((ch=getc(fp))!=EOF){
//printf("is :%c\n",ch);
if(ch=='-'){
if((ch=getc(fp))=='\n'){
continue;
}else{
last=ch;
break;
}
}
if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z')
s.push_back(ch);
else
break;
}
if(ch==EOF) end=true;
transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower);
return s;
}
int main(int argc, char const *argv[])
{
#ifndef LOCAL
fp=fopen("case1.in","r");
#else
printf("used LOCAL");
#endif
string word;
while(!end){
word=getword();
if(!dict.count(word)) dict[word]=0;
printf("%s",word);}
return 0;
}
<commit_msg>update uoj1109<commit_after>#include <cstdio>
#include <algorithm>
#include <string>
#include <map>
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
map <string ,int> dict;
bool end=false;
//debug
#ifdef LOCAL
#define fp stdin
#else
FILE *fp;
#endif
char last=0;
char ch;
string getword(){
string s;
if (last){
s.push_back(last);
last=0;
}
while((ch=getc(fp))!=EOF){
//printf("is :%c\n",ch);
if(ch=='-'){
if((ch=getc(fp))=='\n'){
continue;
}else{
last=ch;
break;
}
}
if(ch>='A'&&ch<='Z' || ch>='a'&&ch<='z')
s.push_back(ch);
else
break;
}
if(ch==EOF) end=true;
transform(s.begin(), s.end(), s.begin(), (int (*)(int))tolower);
return s;
}
int main(int argc, char const *argv[])
{
#ifndef LOCAL
fp=fopen("case1.in","r");
#else
printf("used LOCAL");
#endif
string word;
while(!end){
word=getword();
if(!dict.count(word)) dict[word]=0;
cout<<word<<endl;}
return 0;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue<string> lv1;
queue<string> lv2;
queue<string> lv3;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
printf("test\n");
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
}
}
users++;
if(users<=usernum){
cin >>temptime>>templv>>temp;
}
else
return 0;
}while(temptime<=now);
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i < time; ++i)
{
read(i);
cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
}
return 0;
}<commit_msg>update uoj2254<commit_after>#include <stdio.h>
#include <queue>
#include <vector>
#include <utility>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue<string> lv1;
queue<string> lv2;
queue<string> lv3;
string temp;
int templv;
int temptime=0;
int usernum;
int users=0;
int read(int now){
if(now < temptime || users>usernum) return 0;
do{
printf("test\n");
if(temp.empty()){
}else{
switch(templv){
case 1:
lv1.push(temp);break;
case 2:
lv2.push(temp);break;
case 3:
lv3.push(temp);break;
}
}
users++;
if(users<=usernum){
cin >>temptime>>templv>>temp;
}
else
return 0;
}while(temptime<=now);
}
void pop(){
if(lv3.size()>0){
cout<<lv3.front()<<endl;
lv3.pop();
return;
}
if(lv2.size()>0){
cout<<lv2.front()<<endl;
lv2.pop();
return;
}
if(lv1.size()>0){
cout<<lv1.front()<<endl;
lv1.pop();
return;
}
}
int main(int argc, char const *argv[])
{
int time;
scanf("%d%d",&usernum,&time);
for (int i = 0; i < time; ++i)
{
read(i);
cout<<i<<"\n"<<lv1.size()<<lv2.size()<<lv3.size()<<endl;
if(i%5==0)
pop();
}
return 0;
}<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "documentmodel.h"
#include "ieditor.h"
#include <coreplugin/documentmanager.h>
#include <coreplugin/idocument.h>
#include <utils/algorithm.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QDir>
#include <QIcon>
#include <QMimeData>
#include <QUrl>
namespace Core {
class DocumentModelPrivate : public QAbstractItemModel
{
Q_OBJECT
public:
DocumentModelPrivate();
~DocumentModelPrivate();
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
QMimeData *mimeData(const QModelIndexList &indexes) const;
QModelIndex parent(const QModelIndex &/*index*/) const { return QModelIndex(); }
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const;
Qt::DropActions supportedDragActions() const;
QStringList mimeTypes() const;
void addEntry(DocumentModel::Entry *entry);
void removeDocument(int idx);
int indexOfFilePath(const QString &filePath) const;
int indexOfDocument(IDocument *document) const;
private slots:
friend class DocumentModel;
void itemChanged();
private:
const QIcon m_lockedIcon;
const QIcon m_unlockedIcon;
QList<DocumentModel::Entry *> m_entries;
QMap<IDocument *, QList<IEditor *> > m_editors;
};
DocumentModelPrivate::DocumentModelPrivate() :
m_lockedIcon(QLatin1String(":/core/images/locked.png")),
m_unlockedIcon(QLatin1String(":/core/images/unlocked.png"))
{
}
DocumentModelPrivate::~DocumentModelPrivate()
{
qDeleteAll(m_entries);
}
static DocumentModelPrivate *d;
DocumentModel::Entry::Entry() :
document(0)
{
}
DocumentModel::DocumentModel()
{
}
void DocumentModel::init()
{
d = new DocumentModelPrivate;
}
void DocumentModel::destroy()
{
delete d;
}
QIcon DocumentModel::lockedIcon()
{
return d->m_lockedIcon;
}
QIcon DocumentModel::unlockedIcon()
{
return d->m_unlockedIcon;
}
QAbstractItemModel *DocumentModel::model()
{
return d;
}
QString DocumentModel::Entry::fileName() const
{
return document ? document->filePath() : m_fileName;
}
QString DocumentModel::Entry::displayName() const
{
return document ? document->displayName() : m_displayName;
}
Id DocumentModel::Entry::id() const
{
return document ? document->id() : m_id;
}
int DocumentModelPrivate::columnCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return 2;
return 0;
}
int DocumentModelPrivate::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return m_entries.count() + 1/*<no document>*/;
return 0;
}
void DocumentModel::addEditor(IEditor *editor, bool *isNewDocument)
{
if (!editor)
return;
QList<IEditor *> &editorList = d->m_editors[editor->document()];
bool isNew = editorList.isEmpty();
if (isNewDocument)
*isNewDocument = isNew;
editorList << editor;
if (isNew) {
Entry *entry = new Entry;
entry->document = editor->document();
d->addEntry(entry);
}
}
void DocumentModel::addRestoredDocument(const QString &fileName, const QString &displayName, Id id)
{
Entry *entry = new Entry;
entry->m_fileName = fileName;
entry->m_displayName = displayName;
entry->m_id = id;
d->addEntry(entry);
}
DocumentModel::Entry *DocumentModel::firstRestoredEntry()
{
return Utils::findOrDefault(d->m_entries, [](Entry *entry) { return !entry->document; });
}
void DocumentModelPrivate::addEntry(DocumentModel::Entry *entry)
{
QString fileName = entry->fileName();
// replace a non-loaded entry (aka 'restored') if possible
int previousIndex = indexOfFilePath(fileName);
if (previousIndex >= 0) {
if (entry->document && m_entries.at(previousIndex)->document == 0) {
DocumentModel::Entry *previousEntry = m_entries.at(previousIndex);
m_entries[previousIndex] = entry;
delete previousEntry;
connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged()));
} else {
delete entry;
}
return;
}
int index;
QString displayName = entry->displayName();
for (index = 0; index < m_entries.count(); ++index) {
if (displayName.localeAwareCompare(m_entries.at(index)->displayName()) < 0)
break;
}
int row = index + 1/*<no document>*/;
beginInsertRows(QModelIndex(), row, row);
m_entries.insert(index, entry);
if (entry->document)
connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged()));
endInsertRows();
}
int DocumentModelPrivate::indexOfFilePath(const QString &filePath) const
{
if (filePath.isEmpty())
return -1;
const QString fixedPath = DocumentManager::fixFileName(filePath, DocumentManager::KeepLinks);
return Utils::indexOf(m_entries, [&fixedPath](DocumentModel::Entry *entry) {
return DocumentManager::fixFileName(entry->fileName(),
DocumentManager::KeepLinks) == fixedPath;
});
}
void DocumentModel::removeEntry(DocumentModel::Entry *entry)
{
QTC_ASSERT(!entry->document, return); // we wouldn't know what to do with the associated editors
int index = d->m_entries.indexOf(entry);
d->removeDocument(index);
}
void DocumentModel::removeEditor(IEditor *editor, bool *lastOneForDocument)
{
if (lastOneForDocument)
*lastOneForDocument = false;
QTC_ASSERT(editor, return);
IDocument *document = editor->document();
QTC_ASSERT(d->m_editors.contains(document), return);
d->m_editors[document].removeAll(editor);
if (d->m_editors.value(document).isEmpty()) {
if (lastOneForDocument)
*lastOneForDocument = true;
d->m_editors.remove(document);
d->removeDocument(indexOfDocument(document));
}
}
void DocumentModel::removeDocument(const QString &fileName)
{
int index = d->indexOfFilePath(fileName);
QTC_ASSERT(!d->m_entries.at(index)->document, return); // we wouldn't know what to do with the associated editors
d->removeDocument(index);
}
void DocumentModelPrivate::removeDocument(int idx)
{
if (idx < 0)
return;
QTC_ASSERT(idx < d->m_entries.size(), return);
IDocument *document = d->m_entries.at(idx)->document;
int row = idx + 1/*<no document>*/;
beginRemoveRows(QModelIndex(), row, row);
delete d->m_entries.takeAt(idx);
endRemoveRows();
if (document)
disconnect(document, SIGNAL(changed()), this, SLOT(itemChanged()));
}
void DocumentModel::removeAllRestoredEntries()
{
for (int i = d->m_entries.count()-1; i >= 0; --i) {
if (!d->m_entries.at(i)->document) {
int row = i + 1/*<no document>*/;
d->beginRemoveRows(QModelIndex(), row, row);
delete d->m_entries.takeAt(i);
d->endRemoveRows();
}
}
}
QList<IEditor *> DocumentModel::editorsForDocument(IDocument *document)
{
return d->m_editors.value(document);
}
QList<IEditor *> DocumentModel::editorsForOpenedDocuments()
{
return editorsForDocuments(openedDocuments());
}
QList<IEditor *> DocumentModel::editorsForDocuments(const QList<IDocument *> &documents)
{
QList<IEditor *> result;
foreach (IDocument *document, documents)
result += d->m_editors.value(document);
return result;
}
int DocumentModel::indexOfDocument(IDocument *document)
{
return d->indexOfDocument(document);
}
int DocumentModelPrivate::indexOfDocument(IDocument *document) const
{
return Utils::indexOf(m_entries, [&document](DocumentModel::Entry *entry) {
return entry->document == document;
});
}
DocumentModel::Entry *DocumentModel::entryForDocument(IDocument *document)
{
return Utils::findOrDefault(d->m_entries,
[&document](Entry *entry) { return entry->document == document; });
}
QList<IDocument *> DocumentModel::openedDocuments()
{
return d->m_editors.keys();
}
IDocument *DocumentModel::documentForFilePath(const QString &filePath)
{
const int index = d->indexOfFilePath(filePath);
if (index < 0)
return 0;
return d->m_entries.at(index)->document;
}
QList<IEditor *> DocumentModel::editorsForFilePath(const QString &filePath)
{
IDocument *document = documentForFilePath(filePath);
if (document)
return editorsForDocument(document);
return QList<IEditor *>();
}
QModelIndex DocumentModelPrivate::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent)
if (column < 0 || column > 1 || row < 0 || row >= m_entries.count() + 1/*<no document>*/)
return QModelIndex();
return createIndex(row, column);
}
Qt::DropActions DocumentModelPrivate::supportedDragActions() const
{
return Qt::MoveAction;
}
QStringList DocumentModelPrivate::mimeTypes() const
{
return Utils::FileDropSupport::mimeTypesForFilePaths();
}
DocumentModel::Entry *DocumentModel::entryAtRow(int row)
{
int entryIndex = row - 1/*<no document>*/;
if (entryIndex < 0)
return 0;
return d->m_entries[entryIndex];
}
int DocumentModel::entryCount()
{
return d->m_entries.count();
}
QVariant DocumentModelPrivate::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || (index.column() != 0 && role < Qt::UserRole))
return QVariant();
int entryIndex = index.row() - 1/*<no document>*/;
if (entryIndex < 0) {
// <no document> entry
switch (role) {
case Qt::DisplayRole:
return tr("<no document>");
case Qt::ToolTipRole:
return tr("No document is selected.");
default:
return QVariant();
}
}
const DocumentModel::Entry *e = m_entries.at(entryIndex);
switch (role) {
case Qt::DisplayRole:
return (e->document && e->document->isModified())
? e->displayName() + QLatin1Char('*')
: e->displayName();
case Qt::DecorationRole:
{
bool showLock = false;
if (e->document) {
showLock = e->document->filePath().isEmpty()
? false
: e->document->isFileReadOnly();
} else {
showLock = !QFileInfo(e->m_fileName).isWritable();
}
return showLock ? m_lockedIcon : QIcon();
}
case Qt::ToolTipRole:
return e->fileName().isEmpty()
? e->displayName()
: QDir::toNativeSeparators(e->fileName());
default:
return QVariant();
}
return QVariant();
}
Qt::ItemFlags DocumentModelPrivate::flags(const QModelIndex &index) const
{
const DocumentModel::Entry *e = DocumentModel::entryAtRow(index.row());
if (!e || e->fileName().isEmpty())
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
return Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QMimeData *DocumentModelPrivate::mimeData(const QModelIndexList &indexes) const
{
auto data = new Utils::FileDropMimeData;
foreach (const QModelIndex &index, indexes) {
const DocumentModel::Entry *e = DocumentModel::entryAtRow(index.row());
if (!e || e->fileName().isEmpty())
continue;
data->addFile(e->fileName());
}
return data;
}
int DocumentModel::rowOfDocument(IDocument *document)
{
if (!document)
return 0 /*<no document>*/;
return indexOfDocument(document) + 1/*<no document>*/;
}
void DocumentModelPrivate::itemChanged()
{
IDocument *document = qobject_cast<IDocument *>(sender());
int idx = indexOfDocument(document);
if (idx < 0)
return;
QModelIndex mindex = index(idx + 1/*<no document>*/, 0);
emit dataChanged(mindex, mindex);
}
QList<DocumentModel::Entry *> DocumentModel::entries()
{
return d->m_entries;
}
} // namespace Core
#include "documentmodel.moc"
<commit_msg>Editor: Open only one editor for symlink and its target.<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "documentmodel.h"
#include "ieditor.h"
#include <coreplugin/documentmanager.h>
#include <coreplugin/idocument.h>
#include <utils/algorithm.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QDir>
#include <QIcon>
#include <QMimeData>
#include <QUrl>
namespace Core {
class DocumentModelPrivate : public QAbstractItemModel
{
Q_OBJECT
public:
DocumentModelPrivate();
~DocumentModelPrivate();
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
QMimeData *mimeData(const QModelIndexList &indexes) const;
QModelIndex parent(const QModelIndex &/*index*/) const { return QModelIndex(); }
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QModelIndex index(int row, int column = 0, const QModelIndex &parent = QModelIndex()) const;
Qt::DropActions supportedDragActions() const;
QStringList mimeTypes() const;
void addEntry(DocumentModel::Entry *entry);
void removeDocument(int idx);
int indexOfFilePath(const QString &filePath) const;
int indexOfDocument(IDocument *document) const;
private slots:
friend class DocumentModel;
void itemChanged();
private:
const QIcon m_lockedIcon;
const QIcon m_unlockedIcon;
QList<DocumentModel::Entry *> m_entries;
QMap<IDocument *, QList<IEditor *> > m_editors;
};
DocumentModelPrivate::DocumentModelPrivate() :
m_lockedIcon(QLatin1String(":/core/images/locked.png")),
m_unlockedIcon(QLatin1String(":/core/images/unlocked.png"))
{
}
DocumentModelPrivate::~DocumentModelPrivate()
{
qDeleteAll(m_entries);
}
static DocumentModelPrivate *d;
DocumentModel::Entry::Entry() :
document(0)
{
}
DocumentModel::DocumentModel()
{
}
void DocumentModel::init()
{
d = new DocumentModelPrivate;
}
void DocumentModel::destroy()
{
delete d;
}
QIcon DocumentModel::lockedIcon()
{
return d->m_lockedIcon;
}
QIcon DocumentModel::unlockedIcon()
{
return d->m_unlockedIcon;
}
QAbstractItemModel *DocumentModel::model()
{
return d;
}
QString DocumentModel::Entry::fileName() const
{
return document ? document->filePath() : m_fileName;
}
QString DocumentModel::Entry::displayName() const
{
return document ? document->displayName() : m_displayName;
}
Id DocumentModel::Entry::id() const
{
return document ? document->id() : m_id;
}
int DocumentModelPrivate::columnCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return 2;
return 0;
}
int DocumentModelPrivate::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return m_entries.count() + 1/*<no document>*/;
return 0;
}
void DocumentModel::addEditor(IEditor *editor, bool *isNewDocument)
{
if (!editor)
return;
QList<IEditor *> &editorList = d->m_editors[editor->document()];
bool isNew = editorList.isEmpty();
if (isNewDocument)
*isNewDocument = isNew;
editorList << editor;
if (isNew) {
Entry *entry = new Entry;
entry->document = editor->document();
d->addEntry(entry);
}
}
void DocumentModel::addRestoredDocument(const QString &fileName, const QString &displayName, Id id)
{
Entry *entry = new Entry;
entry->m_fileName = fileName;
entry->m_displayName = displayName;
entry->m_id = id;
d->addEntry(entry);
}
DocumentModel::Entry *DocumentModel::firstRestoredEntry()
{
return Utils::findOrDefault(d->m_entries, [](Entry *entry) { return !entry->document; });
}
void DocumentModelPrivate::addEntry(DocumentModel::Entry *entry)
{
QString fileName = entry->fileName();
// replace a non-loaded entry (aka 'restored') if possible
int previousIndex = indexOfFilePath(fileName);
if (previousIndex >= 0) {
if (entry->document && m_entries.at(previousIndex)->document == 0) {
DocumentModel::Entry *previousEntry = m_entries.at(previousIndex);
m_entries[previousIndex] = entry;
delete previousEntry;
connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged()));
} else {
delete entry;
}
return;
}
int index;
QString displayName = entry->displayName();
for (index = 0; index < m_entries.count(); ++index) {
if (displayName.localeAwareCompare(m_entries.at(index)->displayName()) < 0)
break;
}
int row = index + 1/*<no document>*/;
beginInsertRows(QModelIndex(), row, row);
m_entries.insert(index, entry);
if (entry->document)
connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged()));
endInsertRows();
}
int DocumentModelPrivate::indexOfFilePath(const QString &filePath) const
{
if (filePath.isEmpty())
return -1;
const QString fixedPath = DocumentManager::fixFileName(filePath, DocumentManager::ResolveLinks);
return Utils::indexOf(m_entries, [&fixedPath](DocumentModel::Entry *entry) {
return DocumentManager::fixFileName(entry->fileName(),
DocumentManager::ResolveLinks) == fixedPath;
});
}
void DocumentModel::removeEntry(DocumentModel::Entry *entry)
{
QTC_ASSERT(!entry->document, return); // we wouldn't know what to do with the associated editors
int index = d->m_entries.indexOf(entry);
d->removeDocument(index);
}
void DocumentModel::removeEditor(IEditor *editor, bool *lastOneForDocument)
{
if (lastOneForDocument)
*lastOneForDocument = false;
QTC_ASSERT(editor, return);
IDocument *document = editor->document();
QTC_ASSERT(d->m_editors.contains(document), return);
d->m_editors[document].removeAll(editor);
if (d->m_editors.value(document).isEmpty()) {
if (lastOneForDocument)
*lastOneForDocument = true;
d->m_editors.remove(document);
d->removeDocument(indexOfDocument(document));
}
}
void DocumentModel::removeDocument(const QString &fileName)
{
int index = d->indexOfFilePath(fileName);
QTC_ASSERT(!d->m_entries.at(index)->document, return); // we wouldn't know what to do with the associated editors
d->removeDocument(index);
}
void DocumentModelPrivate::removeDocument(int idx)
{
if (idx < 0)
return;
QTC_ASSERT(idx < d->m_entries.size(), return);
IDocument *document = d->m_entries.at(idx)->document;
int row = idx + 1/*<no document>*/;
beginRemoveRows(QModelIndex(), row, row);
delete d->m_entries.takeAt(idx);
endRemoveRows();
if (document)
disconnect(document, SIGNAL(changed()), this, SLOT(itemChanged()));
}
void DocumentModel::removeAllRestoredEntries()
{
for (int i = d->m_entries.count()-1; i >= 0; --i) {
if (!d->m_entries.at(i)->document) {
int row = i + 1/*<no document>*/;
d->beginRemoveRows(QModelIndex(), row, row);
delete d->m_entries.takeAt(i);
d->endRemoveRows();
}
}
}
QList<IEditor *> DocumentModel::editorsForDocument(IDocument *document)
{
return d->m_editors.value(document);
}
QList<IEditor *> DocumentModel::editorsForOpenedDocuments()
{
return editorsForDocuments(openedDocuments());
}
QList<IEditor *> DocumentModel::editorsForDocuments(const QList<IDocument *> &documents)
{
QList<IEditor *> result;
foreach (IDocument *document, documents)
result += d->m_editors.value(document);
return result;
}
int DocumentModel::indexOfDocument(IDocument *document)
{
return d->indexOfDocument(document);
}
int DocumentModelPrivate::indexOfDocument(IDocument *document) const
{
return Utils::indexOf(m_entries, [&document](DocumentModel::Entry *entry) {
return entry->document == document;
});
}
DocumentModel::Entry *DocumentModel::entryForDocument(IDocument *document)
{
return Utils::findOrDefault(d->m_entries,
[&document](Entry *entry) { return entry->document == document; });
}
QList<IDocument *> DocumentModel::openedDocuments()
{
return d->m_editors.keys();
}
IDocument *DocumentModel::documentForFilePath(const QString &filePath)
{
const int index = d->indexOfFilePath(filePath);
if (index < 0)
return 0;
return d->m_entries.at(index)->document;
}
QList<IEditor *> DocumentModel::editorsForFilePath(const QString &filePath)
{
IDocument *document = documentForFilePath(filePath);
if (document)
return editorsForDocument(document);
return QList<IEditor *>();
}
QModelIndex DocumentModelPrivate::index(int row, int column, const QModelIndex &parent) const
{
Q_UNUSED(parent)
if (column < 0 || column > 1 || row < 0 || row >= m_entries.count() + 1/*<no document>*/)
return QModelIndex();
return createIndex(row, column);
}
Qt::DropActions DocumentModelPrivate::supportedDragActions() const
{
return Qt::MoveAction;
}
QStringList DocumentModelPrivate::mimeTypes() const
{
return Utils::FileDropSupport::mimeTypesForFilePaths();
}
DocumentModel::Entry *DocumentModel::entryAtRow(int row)
{
int entryIndex = row - 1/*<no document>*/;
if (entryIndex < 0)
return 0;
return d->m_entries[entryIndex];
}
int DocumentModel::entryCount()
{
return d->m_entries.count();
}
QVariant DocumentModelPrivate::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || (index.column() != 0 && role < Qt::UserRole))
return QVariant();
int entryIndex = index.row() - 1/*<no document>*/;
if (entryIndex < 0) {
// <no document> entry
switch (role) {
case Qt::DisplayRole:
return tr("<no document>");
case Qt::ToolTipRole:
return tr("No document is selected.");
default:
return QVariant();
}
}
const DocumentModel::Entry *e = m_entries.at(entryIndex);
switch (role) {
case Qt::DisplayRole:
return (e->document && e->document->isModified())
? e->displayName() + QLatin1Char('*')
: e->displayName();
case Qt::DecorationRole:
{
bool showLock = false;
if (e->document) {
showLock = e->document->filePath().isEmpty()
? false
: e->document->isFileReadOnly();
} else {
showLock = !QFileInfo(e->m_fileName).isWritable();
}
return showLock ? m_lockedIcon : QIcon();
}
case Qt::ToolTipRole:
return e->fileName().isEmpty()
? e->displayName()
: QDir::toNativeSeparators(e->fileName());
default:
return QVariant();
}
return QVariant();
}
Qt::ItemFlags DocumentModelPrivate::flags(const QModelIndex &index) const
{
const DocumentModel::Entry *e = DocumentModel::entryAtRow(index.row());
if (!e || e->fileName().isEmpty())
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
return Qt::ItemIsDragEnabled | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QMimeData *DocumentModelPrivate::mimeData(const QModelIndexList &indexes) const
{
auto data = new Utils::FileDropMimeData;
foreach (const QModelIndex &index, indexes) {
const DocumentModel::Entry *e = DocumentModel::entryAtRow(index.row());
if (!e || e->fileName().isEmpty())
continue;
data->addFile(e->fileName());
}
return data;
}
int DocumentModel::rowOfDocument(IDocument *document)
{
if (!document)
return 0 /*<no document>*/;
return indexOfDocument(document) + 1/*<no document>*/;
}
void DocumentModelPrivate::itemChanged()
{
IDocument *document = qobject_cast<IDocument *>(sender());
int idx = indexOfDocument(document);
if (idx < 0)
return;
QModelIndex mindex = index(idx + 1/*<no document>*/, 0);
emit dataChanged(mindex, mindex);
}
QList<DocumentModel::Entry *> DocumentModel::entries()
{
return d->m_entries;
}
} // namespace Core
#include "documentmodel.moc"
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "guiappwizard.h"
#include "guiappwizarddialog.h"
#include "qt4projectmanagerconstants.h"
#include <cpptools/cppmodelmanagerinterface.h>
#include <designer/cpp/formclasswizardparameters.h>
#include <coreplugin/icore.h>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QUuid>
#include <QtCore/QFileInfo>
#include <QtCore/QSharedPointer>
#include <QtGui/QIcon>
static const char *mainSourceFileC = "main";
static const char *mainWindowUiContentsC =
"\n <widget class=\"QMenuBar\" name=\"menuBar\" />"
"\n <widget class=\"QToolBar\" name=\"mainToolBar\" />"
"\n <widget class=\"QWidget\" name=\"centralWidget\" />"
"\n <widget class=\"QStatusBar\" name=\"statusBar\" />";
static const char *mainWindowMobileUiContentsC =
"\n <widget class=\"QWidget\" name=\"centralWidget\" />";
static const char *baseClassesC[] = { "QMainWindow", "QWidget", "QDialog" };
static inline QStringList baseClasses()
{
QStringList rc;
const int baseClassCount = sizeof(baseClassesC)/sizeof(const char *);
for (int i = 0; i < baseClassCount; i++)
rc.push_back(QLatin1String(baseClassesC[i]));
return rc;
}
namespace Qt4ProjectManager {
namespace Internal {
GuiAppWizard::GuiAppWizard()
: QtWizard(QLatin1String("C.Qt4Gui"),
QLatin1String(Constants::QT_APP_WIZARD_CATEGORY),
QLatin1String(Constants::QT_APP_WIZARD_TR_SCOPE),
QLatin1String(Constants::QT_APP_WIZARD_TR_CATEGORY),
tr("Qt Gui Application"),
tr("Creates a Qt Gui Application with one form."),
QIcon(QLatin1String(":/wizards/images/gui.png")))
{
}
QWizard *GuiAppWizard::createWizardDialog(QWidget *parent,
const QString &defaultPath,
const WizardPageList &extensionPages) const
{
GuiAppWizardDialog *dialog = new GuiAppWizardDialog(displayName(), icon(), extensionPages,
showModulesPageForApplications(),
parent);
dialog->setPath(defaultPath);
dialog->setProjectName(GuiAppWizardDialog::uniqueProjectName(defaultPath));
// Order! suffixes first to generate files correctly
dialog->setLowerCaseFiles(QtWizard::lowerCaseFiles());
dialog->setSuffixes(headerSuffix(), sourceSuffix(), formSuffix());
dialog->setBaseClasses(baseClasses());
return dialog;
}
// Use the class generation utils provided by the designer plugin
static inline bool generateFormClass(const GuiAppParameters ¶ms,
const Core::GeneratedFile &uiFile,
Core::GeneratedFile *formSource,
Core::GeneratedFile *formHeader,
QString *errorMessage)
{
// Retrieve parameters from settings
Designer::FormClassWizardGenerationParameters fgp;
fgp.fromSettings(Core::ICore::instance()->settings());
Designer::FormClassWizardParameters fp;
fp.setUiTemplate(uiFile.contents());
fp.setUiFile(uiFile.path());
fp.setClassName(params.className);
fp.setSourceFile(params.sourceFileName);
fp.setHeaderFile(params.headerFileName);
QString headerContents;
QString sourceContents;
if (!fp.generateCpp(fgp, &headerContents, &sourceContents, 4)) {
*errorMessage = QLatin1String("Internal error: Unable to generate the form classes.");
return false;
}
formHeader->setContents(headerContents);
formSource->setContents(sourceContents);
return true;
}
Core::GeneratedFiles GuiAppWizard::generateFiles(const QWizard *w,
QString *errorMessage) const
{
const GuiAppWizardDialog *dialog = qobject_cast<const GuiAppWizardDialog *>(w);
const QtProjectParameters projectParams = dialog->projectParameters();
const QString projectPath = projectParams.projectPath();
const GuiAppParameters params = dialog->parameters();
const QString license = CppTools::AbstractEditorSupport::licenseTemplate();
// Generate file names. Note that the path for the project files is the
// newly generated project directory.
const QString templatePath = templateDir();
// Create files: main source
QString contents;
const QString mainSourceFileName = buildFileName(projectPath, QLatin1String(mainSourceFileC), sourceSuffix());
Core::GeneratedFile mainSource(mainSourceFileName);
if (!parametrizeTemplate(templatePath, QLatin1String("main.cpp"), params, &contents, errorMessage))
return Core::GeneratedFiles();
mainSource.setContents(license + contents);
// Create files: form source with or without form
const QString formSourceFileName = buildFileName(projectPath, params.sourceFileName, sourceSuffix());
const QString formHeaderName = buildFileName(projectPath, params.headerFileName, headerSuffix());
Core::GeneratedFile formSource(formSourceFileName);
Core::GeneratedFile formHeader(formHeaderName);
QSharedPointer<Core::GeneratedFile> form;
if (params.designerForm) {
// Create files: form
const QString formName = buildFileName(projectPath, params.formFileName, formSuffix());
form = QSharedPointer<Core::GeneratedFile>(new Core::GeneratedFile(formName));
if (!parametrizeTemplate(templatePath, QLatin1String("widget.ui"), params, &contents, errorMessage))
return Core::GeneratedFiles();
form->setContents(contents);
if (!generateFormClass(params, *form, &formSource, &formHeader, errorMessage))
return Core::GeneratedFiles();
} else {
const QString formSourceTemplate = QLatin1String("mywidget.cpp");
if (!parametrizeTemplate(templatePath, formSourceTemplate, params, &contents, errorMessage))
return Core::GeneratedFiles();
formSource.setContents(license + contents);
// Create files: form header
const QString formHeaderTemplate = QLatin1String("mywidget.h");
if (!parametrizeTemplate(templatePath, formHeaderTemplate, params, &contents, errorMessage))
return Core::GeneratedFiles();
formHeader.setContents(license + contents);
}
// Create files: profile
const QString profileName = buildFileName(projectPath, projectParams.fileName, profileSuffix());
Core::GeneratedFile profile(profileName);
contents.clear();
{
QTextStream proStr(&contents);
QtProjectParameters::writeProFileHeader(proStr);
projectParams.writeProFile(proStr);
proStr << "\n\nSOURCES += " << QFileInfo(mainSourceFileName).fileName()
<< "\\\n " << QFileInfo(formSource.path()).fileName()
<< "\n\nHEADERS += " << QFileInfo(formHeader.path()).fileName();
if (params.designerForm)
proStr << "\n\nFORMS += " << QFileInfo(form->path()).fileName();
if (params.isMobileApplication) {
// Generate a development Symbian UID for the application:
QString uid3String = QLatin1String("0xe") + QUuid::createUuid().toString().mid(1, 7);
proStr << "\n\nCONFIG += mobility"
<< "\nMOBILITY = "
<< "\n\nsymbian {"
<< "\n TARGET.UID3 = " << uid3String
<< "\n TARGET.CAPABILITY = "
<< "\n TARGET.EPOCSTACKSIZE = 0x14000"
<< "\n TARGET.EPOCHEAPSIZE = 0x020000 0x800000"
<< "\n}";
}
proStr << '\n';
}
profile.setContents(contents);
// List
Core::GeneratedFiles rc;
rc << mainSource << formSource << formHeader;
if (params.designerForm)
rc << *form;
rc << profile;
return rc;
}
bool GuiAppWizard::parametrizeTemplate(const QString &templatePath, const QString &templateName,
const GuiAppParameters ¶ms,
QString *target, QString *errorMessage)
{
QString fileName = templatePath;
fileName += QDir::separator();
fileName += templateName;
QFile inFile(fileName);
if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
*errorMessage = tr("The template file '%1' could not be opened for reading: %2").arg(fileName, inFile.errorString());
return false;
}
QString contents = QString::fromUtf8(inFile.readAll());
contents.replace(QLatin1String("%QAPP_INCLUDE%"), QLatin1String("QtGui/QApplication"));
contents.replace(QLatin1String("%INCLUDE%"), params.headerFileName);
contents.replace(QLatin1String("%CLASS%"), params.className);
contents.replace(QLatin1String("%BASECLASS%"), params.baseClassName);
contents.replace(QLatin1String("%WIDGET_HEIGHT%"), QString::number(params.widgetHeight));
contents.replace(QLatin1String("%WIDGET_WIDTH%"), QString::number(params.widgetWidth));
const QChar dot = QLatin1Char('.');
QString preDef = params.headerFileName.toUpper();
preDef.replace(dot, QLatin1Char('_'));
contents.replace("%PRE_DEF%", preDef.toUtf8());
const QString uiFileName = params.formFileName;
QString uiHdr = QLatin1String("ui_");
uiHdr += uiFileName.left(uiFileName.indexOf(dot));
uiHdr += QLatin1String(".h");
contents.replace(QLatin1String("%UI_HDR%"), uiHdr);
if (params.baseClassName == QLatin1String("QMainWindow")) {
if (params.isMobileApplication)
contents.replace(QLatin1String("%CENTRAL_WIDGET%"), QLatin1String(mainWindowMobileUiContentsC));
else
contents.replace(QLatin1String("%CENTRAL_WIDGET%"), QLatin1String(mainWindowUiContentsC));
} else {
contents.remove(QLatin1String("%CENTRAL_WIDGET%"));
}
*target = contents;
return true;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Comment out capability setting in generated pro-file<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "guiappwizard.h"
#include "guiappwizarddialog.h"
#include "qt4projectmanagerconstants.h"
#include <cpptools/cppmodelmanagerinterface.h>
#include <designer/cpp/formclasswizardparameters.h>
#include <coreplugin/icore.h>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QUuid>
#include <QtCore/QFileInfo>
#include <QtCore/QSharedPointer>
#include <QtGui/QIcon>
static const char *mainSourceFileC = "main";
static const char *mainWindowUiContentsC =
"\n <widget class=\"QMenuBar\" name=\"menuBar\" />"
"\n <widget class=\"QToolBar\" name=\"mainToolBar\" />"
"\n <widget class=\"QWidget\" name=\"centralWidget\" />"
"\n <widget class=\"QStatusBar\" name=\"statusBar\" />";
static const char *mainWindowMobileUiContentsC =
"\n <widget class=\"QWidget\" name=\"centralWidget\" />";
static const char *baseClassesC[] = { "QMainWindow", "QWidget", "QDialog" };
static inline QStringList baseClasses()
{
QStringList rc;
const int baseClassCount = sizeof(baseClassesC)/sizeof(const char *);
for (int i = 0; i < baseClassCount; i++)
rc.push_back(QLatin1String(baseClassesC[i]));
return rc;
}
namespace Qt4ProjectManager {
namespace Internal {
GuiAppWizard::GuiAppWizard()
: QtWizard(QLatin1String("C.Qt4Gui"),
QLatin1String(Constants::QT_APP_WIZARD_CATEGORY),
QLatin1String(Constants::QT_APP_WIZARD_TR_SCOPE),
QLatin1String(Constants::QT_APP_WIZARD_TR_CATEGORY),
tr("Qt Gui Application"),
tr("Creates a Qt Gui Application with one form."),
QIcon(QLatin1String(":/wizards/images/gui.png")))
{
}
QWizard *GuiAppWizard::createWizardDialog(QWidget *parent,
const QString &defaultPath,
const WizardPageList &extensionPages) const
{
GuiAppWizardDialog *dialog = new GuiAppWizardDialog(displayName(), icon(), extensionPages,
showModulesPageForApplications(),
parent);
dialog->setPath(defaultPath);
dialog->setProjectName(GuiAppWizardDialog::uniqueProjectName(defaultPath));
// Order! suffixes first to generate files correctly
dialog->setLowerCaseFiles(QtWizard::lowerCaseFiles());
dialog->setSuffixes(headerSuffix(), sourceSuffix(), formSuffix());
dialog->setBaseClasses(baseClasses());
return dialog;
}
// Use the class generation utils provided by the designer plugin
static inline bool generateFormClass(const GuiAppParameters ¶ms,
const Core::GeneratedFile &uiFile,
Core::GeneratedFile *formSource,
Core::GeneratedFile *formHeader,
QString *errorMessage)
{
// Retrieve parameters from settings
Designer::FormClassWizardGenerationParameters fgp;
fgp.fromSettings(Core::ICore::instance()->settings());
Designer::FormClassWizardParameters fp;
fp.setUiTemplate(uiFile.contents());
fp.setUiFile(uiFile.path());
fp.setClassName(params.className);
fp.setSourceFile(params.sourceFileName);
fp.setHeaderFile(params.headerFileName);
QString headerContents;
QString sourceContents;
if (!fp.generateCpp(fgp, &headerContents, &sourceContents, 4)) {
*errorMessage = QLatin1String("Internal error: Unable to generate the form classes.");
return false;
}
formHeader->setContents(headerContents);
formSource->setContents(sourceContents);
return true;
}
Core::GeneratedFiles GuiAppWizard::generateFiles(const QWizard *w,
QString *errorMessage) const
{
const GuiAppWizardDialog *dialog = qobject_cast<const GuiAppWizardDialog *>(w);
const QtProjectParameters projectParams = dialog->projectParameters();
const QString projectPath = projectParams.projectPath();
const GuiAppParameters params = dialog->parameters();
const QString license = CppTools::AbstractEditorSupport::licenseTemplate();
// Generate file names. Note that the path for the project files is the
// newly generated project directory.
const QString templatePath = templateDir();
// Create files: main source
QString contents;
const QString mainSourceFileName = buildFileName(projectPath, QLatin1String(mainSourceFileC), sourceSuffix());
Core::GeneratedFile mainSource(mainSourceFileName);
if (!parametrizeTemplate(templatePath, QLatin1String("main.cpp"), params, &contents, errorMessage))
return Core::GeneratedFiles();
mainSource.setContents(license + contents);
// Create files: form source with or without form
const QString formSourceFileName = buildFileName(projectPath, params.sourceFileName, sourceSuffix());
const QString formHeaderName = buildFileName(projectPath, params.headerFileName, headerSuffix());
Core::GeneratedFile formSource(formSourceFileName);
Core::GeneratedFile formHeader(formHeaderName);
QSharedPointer<Core::GeneratedFile> form;
if (params.designerForm) {
// Create files: form
const QString formName = buildFileName(projectPath, params.formFileName, formSuffix());
form = QSharedPointer<Core::GeneratedFile>(new Core::GeneratedFile(formName));
if (!parametrizeTemplate(templatePath, QLatin1String("widget.ui"), params, &contents, errorMessage))
return Core::GeneratedFiles();
form->setContents(contents);
if (!generateFormClass(params, *form, &formSource, &formHeader, errorMessage))
return Core::GeneratedFiles();
} else {
const QString formSourceTemplate = QLatin1String("mywidget.cpp");
if (!parametrizeTemplate(templatePath, formSourceTemplate, params, &contents, errorMessage))
return Core::GeneratedFiles();
formSource.setContents(license + contents);
// Create files: form header
const QString formHeaderTemplate = QLatin1String("mywidget.h");
if (!parametrizeTemplate(templatePath, formHeaderTemplate, params, &contents, errorMessage))
return Core::GeneratedFiles();
formHeader.setContents(license + contents);
}
// Create files: profile
const QString profileName = buildFileName(projectPath, projectParams.fileName, profileSuffix());
Core::GeneratedFile profile(profileName);
contents.clear();
{
QTextStream proStr(&contents);
QtProjectParameters::writeProFileHeader(proStr);
projectParams.writeProFile(proStr);
proStr << "\n\nSOURCES += " << QFileInfo(mainSourceFileName).fileName()
<< "\\\n " << QFileInfo(formSource.path()).fileName()
<< "\n\nHEADERS += " << QFileInfo(formHeader.path()).fileName();
if (params.designerForm)
proStr << "\n\nFORMS += " << QFileInfo(form->path()).fileName();
if (params.isMobileApplication) {
// Generate a development Symbian UID for the application:
QString uid3String = QLatin1String("0xe") + QUuid::createUuid().toString().mid(1, 7);
proStr << "\n\nCONFIG += mobility"
<< "\nMOBILITY = "
<< "\n\nsymbian {"
<< "\n TARGET.UID3 = " << uid3String
<< "\n # TARGET.CAPABILITY += "
<< "\n TARGET.EPOCSTACKSIZE = 0x14000"
<< "\n TARGET.EPOCHEAPSIZE = 0x020000 0x800000"
<< "\n}";
}
proStr << '\n';
}
profile.setContents(contents);
// List
Core::GeneratedFiles rc;
rc << mainSource << formSource << formHeader;
if (params.designerForm)
rc << *form;
rc << profile;
return rc;
}
bool GuiAppWizard::parametrizeTemplate(const QString &templatePath, const QString &templateName,
const GuiAppParameters ¶ms,
QString *target, QString *errorMessage)
{
QString fileName = templatePath;
fileName += QDir::separator();
fileName += templateName;
QFile inFile(fileName);
if (!inFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
*errorMessage = tr("The template file '%1' could not be opened for reading: %2").arg(fileName, inFile.errorString());
return false;
}
QString contents = QString::fromUtf8(inFile.readAll());
contents.replace(QLatin1String("%QAPP_INCLUDE%"), QLatin1String("QtGui/QApplication"));
contents.replace(QLatin1String("%INCLUDE%"), params.headerFileName);
contents.replace(QLatin1String("%CLASS%"), params.className);
contents.replace(QLatin1String("%BASECLASS%"), params.baseClassName);
contents.replace(QLatin1String("%WIDGET_HEIGHT%"), QString::number(params.widgetHeight));
contents.replace(QLatin1String("%WIDGET_WIDTH%"), QString::number(params.widgetWidth));
const QChar dot = QLatin1Char('.');
QString preDef = params.headerFileName.toUpper();
preDef.replace(dot, QLatin1Char('_'));
contents.replace("%PRE_DEF%", preDef.toUtf8());
const QString uiFileName = params.formFileName;
QString uiHdr = QLatin1String("ui_");
uiHdr += uiFileName.left(uiFileName.indexOf(dot));
uiHdr += QLatin1String(".h");
contents.replace(QLatin1String("%UI_HDR%"), uiHdr);
if (params.baseClassName == QLatin1String("QMainWindow")) {
if (params.isMobileApplication)
contents.replace(QLatin1String("%CENTRAL_WIDGET%"), QLatin1String(mainWindowMobileUiContentsC));
else
contents.replace(QLatin1String("%CENTRAL_WIDGET%"), QLatin1String(mainWindowUiContentsC));
} else {
contents.remove(QLatin1String("%CENTRAL_WIDGET%"));
}
*target = contents;
return true;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>
|
<commit_before>#include <iostream>
#include <aruco/aruco.h>
#include <aruco/cvdrawingutils.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Int32.h"
//TODO viki needs to be changed when using Rpi
#include </home/viki/ROSta-Bot/devel/include/position_sensoring/position.h>
#include </home/viki/ROSta-Bot/devel/include/position_sensoring/marker_visible.h>
using namespace cv;
using namespace aruco;
using namespace position_sensoring;
////Delay before next image retrieval
//const int WAIT_TIME = 2;
////The size of the marker in meters
//const float MARKER_SIZE = .16;
//const float DISTANCE_CONSTANT = 7183.16666666666666;
//Path to files
string boardConfigFile;
string cameraConfigFile;
VideoCapture videoCapture;
Mat inputImage,inputImageCopy;
BoardConfiguration boardConfig;
BoardDetector boardDetector;
CameraParameters cameraParams;
Mat rvec, tvec; // for storing translation and rotation matrices
//int boardHeight = 500;
//int boardWidth = 500;
Vector<Marker> markers;
int currentCameraAngle = -1;
int targetAngle = -1;
// Copied from ArUco library
void getObjectAndImagePoints(Board &B, vector<cv::Point3f> &objPoints,vector<cv::Point2f> &imagePoints) {
//composes the matrices
int nPoints=B.size()*4;
int cIdx=0;
for (size_t i=0;i<B.size();i++) {
const aruco::MarkerInfo & mInfo=B.conf.getMarkerInfo(B[i].id);
for (int j=0;j<4;j++,cIdx++) {
imagePoints.push_back(B[i][j]);
objPoints.push_back( mInfo[j]);
}
}
}
/**
* current_camera_angle callback
*/
void current_camera_angle_callback(const std_msgs::Int32::ConstPtr& message) {
// upcate current_camera_angle
currentCameraAngle = message->data;
}
int main(int argc,char **argv) {
ros::init(argc, argv, "position_sensor");
ros::NodeHandle n;
// publish to topic "target_distance", hold 1000 of these message in the buffer before discarding
ros::Publisher positionPub = n.advertise<position_sensoring::position>("range_data", 1000);
position_sensoring::position positionMsg;
// publish to the topic "marker_visible" hold 1000 of these messages in the buffer before discarding
ros::Publisher markerPub = n.advertise<position_sensoring::marker_visible>("is_marker_visible", 1000);
position_sensoring::marker_visible markerMsg;
// publish new target angle to Arduino
ros::Publisher updateTargetAngle = n.advertise<std_msgs::Int32>("target_camera_angle", 1000);
// listen to current angle of camera (relative to motor)
ros::Subscriber updateCurrentCameraAngle = n.subscribe("current_camera_angle", 1, current_camera_angle_callback);
try {
if (argc != 3) {
cerr << "Usage: boardConfig.yml camera_config.yml " << endl;
return -1;
}
//Read the board configuration file
boardConfigFile = argv[1];
boardConfig.readFromFile(boardConfigFile);
//IE: boardConfig.readFromFile("/home/viki/ROSta-Bot/src/position_sensoring/src/single_marker.yml");
//Get the camera configurations
cameraConfigFile = argv[2];
cameraParams.readFromXMLFile(cameraConfigFile);
// IE: cameraParams.readFromXMLFile("/home/viki/ROSta-Bot/src/position_sensoring/src/cam_param.yml");
//Open the camera
videoCapture.open(0);
//make sure camera is open
if (!videoCapture.isOpened()) {
cerr << "Could not open the video" << endl;
return -1;
}
//read an image from camera
videoCapture >> inputImage;
boardDetector.setParams(boardConfig, cameraParams);
while (videoCapture.grab()) {
//retrieve an image from the camera
videoCapture.retrieve(inputImage);
boardDetector.detect(inputImage);
// detect the markers, and for each marker, determine pose and position
markers = boardDetector.getDetectedMarkers();
for (unsigned int i = 0; i < markers.size(); i++) {
Marker m = markers[i];
//Display data to the meatbag humans
// for (int i = 0; i < 4; i++) {
// cout << "(" << m[i].x << "," << m[i].y << ") ";
// Point2f a(m[i].x, m[i].y);
// }
// cout << endl;
// brute force way to set up the camera matrix and parameters...may need to calibrate using ArUco
// if we do decide to use a calibrated parameter, then get ride of these lines...
// we read from a board configuration, so probably dont need to do this. hopefully
// cv::Mat CamMatrix = cv::Mat::eye(3, 3, CV_32F);
//CamMatrix.at<float>(0, 0) = 500;
//CamMatrix.at<float>(1, 1) = 500;
//CamMatrix.at<float>(0, 2) = inputImageCopy.size().width / 2;
//CamMatrix.at<float>(1, 2) = inputImageCopy.size().height / 2;
//cameraParams.setParams(CamMatrix, cv::Mat::zeros(1, 5, CV_32F), inputImageCopy.size());
vector <cv::Point3f> objPoints;
vector <cv::Point2f> imgPoints;
// get "3d" points of the object in real space, get "2d" points of the object in a flat image
getObjectAndImagePoints(boardDetector.getDetectedBoard(), objPoints, imgPoints);
// solve for transition matrix and store in rvec
// solve for rotation matrix and store in tvec
solvePnP(objPoints, imgPoints, cameraParams.CameraMatrix, cameraParams.Distorsion, rvec, tvec);
// determine the position of the "camera" --> which in our case, will be the robot as well
cv::Mat R;
cv::Rodrigues(rvec, R);
cv::Mat cameraRotationVector;
cv::Rodrigues(R.t(), cameraRotationVector);
cv::Mat cameraTranslationVector = -R.t() * tvec;
// Don't print stuff to the screen, for SPEED.
// // print the translation vectors (distance between marker and camera in x, y, z direction)
// cout << "Camera position " << cameraTranslationVector.at<double>(0) << ", " << cameraTranslationVector.at<double>(1) << ", " << cameraTranslationVector.at<double>(2) << endl;
//
// // print the pose vectors (orientation between marker and camera in x,y,z direction -- angle of rotation for each)
// cout << "Camera pose " << cameraRotationVector.at<double>(0) << ", " << cameraRotationVector.at<double>(1) << ", " << cameraRotationVector.at<double>(2) << endl;
// converting data from meters to centimeters
positionMsg.xDistance = cameraTranslationVector.at<double>(0) * 100.0;
positionMsg.yDistance = cameraTranslationVector.at<double>(1) * 100.0;
positionMsg.zDistance = cameraTranslationVector.at<double>(2) * 100.0;
positionMsg.xPose = cameraRotationVector.at<double>(0) * 100.0;
positionMsg.yPose = cameraRotationVector.at<double>(1) * 100.0;
positionMsg.zPose = cameraRotationVector.at<double>(2) * 100.0;
positionPub.publish(positionMsg);
// if the beacon is about to not be visible, rotate the camera
// starting with a small threshold first for testing purposes
if(positionMsg.yPose > 3 || positionMsg.yPose < -3){
targetAngle = currentCameraAngle + positionMsg.yPose;
std_msgs::Int32 theta;
theta.data = targetAngle;
updateTargetAngle.publish(theta);
}
}
// not sure where this really belongs...
ros::spinOnce();
}
return 0;
} // end try
catch (std::exception &ex) {
cout << "Exception :" << ex.what() << endl;
} // end catch
} // end main
<commit_msg>Possible fix for camera tracking.<commit_after>#include <iostream>
#include <aruco/aruco.h>
#include <aruco/cvdrawingutils.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Int32.h"
//TODO viki needs to be changed when using Rpi
#include </home/viki/ROSta-Bot/devel/include/position_sensoring/position.h>
#include </home/viki/ROSta-Bot/devel/include/position_sensoring/marker_visible.h>
using namespace cv;
using namespace aruco;
using namespace position_sensoring;
////Delay before next image retrieval
//const int WAIT_TIME = 2;
////The size of the marker in meters
//const float MARKER_SIZE = .16;
//const float DISTANCE_CONSTANT = 7183.16666666666666;
//Path to files
string boardConfigFile;
string cameraConfigFile;
VideoCapture videoCapture;
Mat inputImage,inputImageCopy;
BoardConfiguration boardConfig;
BoardDetector boardDetector;
CameraParameters cameraParams;
Mat rvec, tvec; // for storing translation and rotation matrices
//int boardHeight = 500;
//int boardWidth = 500;
Vector<Marker> markers;
int currentCameraAngle = -1;
int targetAngle = -1;
// Copied from ArUco library
void getObjectAndImagePoints(Board &B, vector<cv::Point3f> &objPoints,vector<cv::Point2f> &imagePoints) {
//composes the matrices
int nPoints=B.size()*4;
int cIdx=0;
for (size_t i=0;i<B.size();i++) {
const aruco::MarkerInfo & mInfo=B.conf.getMarkerInfo(B[i].id);
for (int j=0;j<4;j++,cIdx++) {
imagePoints.push_back(B[i][j]);
objPoints.push_back( mInfo[j]);
}
}
}
/**
* current_camera_angle callback
*/
void current_camera_angle_callback(const std_msgs::Int32::ConstPtr& message) {
// upcate current_camera_angle
currentCameraAngle = message->data;
}
int main(int argc,char **argv) {
ros::init(argc, argv, "position_sensor");
ros::NodeHandle n;
// publish to topic "target_distance", hold 1000 of these message in the buffer before discarding
ros::Publisher positionPub = n.advertise<position_sensoring::position>("range_data", 1000);
position_sensoring::position positionMsg;
// publish to the topic "marker_visible" hold 1000 of these messages in the buffer before discarding
ros::Publisher markerPub = n.advertise<position_sensoring::marker_visible>("is_marker_visible", 1000);
position_sensoring::marker_visible markerMsg;
// publish new target angle to Arduino
ros::Publisher updateTargetAngle = n.advertise<std_msgs::Int32>("target_camera_angle", 1000);
// listen to current angle of camera (relative to motor)
ros::Subscriber updateCurrentCameraAngle = n.subscribe("current_camera_angle", 1, current_camera_angle_callback);
try {
if (argc != 3) {
cerr << "Usage: boardConfig.yml camera_config.yml " << endl;
return -1;
}
//Read the board configuration file
boardConfigFile = argv[1];
boardConfig.readFromFile(boardConfigFile);
//IE: boardConfig.readFromFile("/home/viki/ROSta-Bot/src/position_sensoring/src/single_marker.yml");
//Get the camera configurations
cameraConfigFile = argv[2];
cameraParams.readFromXMLFile(cameraConfigFile);
// IE: cameraParams.readFromXMLFile("/home/viki/ROSta-Bot/src/position_sensoring/src/cam_param.yml");
//Open the camera
videoCapture.open(0);
//make sure camera is open
if (!videoCapture.isOpened()) {
cerr << "Could not open the video" << endl;
return -1;
}
//read an image from camera
videoCapture >> inputImage;
boardDetector.setParams(boardConfig, cameraParams);
while (videoCapture.grab()) {
//retrieve an image from the camera
videoCapture.retrieve(inputImage);
boardDetector.detect(inputImage);
// detect the markers, and for each marker, determine pose and position
markers = boardDetector.getDetectedMarkers();
for (unsigned int i = 0; i < markers.size(); i++) {
Marker m = markers[i];
//Display data to the meatbag humans
// for (int i = 0; i < 4; i++) {
// cout << "(" << m[i].x << "," << m[i].y << ") ";
// Point2f a(m[i].x, m[i].y);
// }
// cout << endl;
// brute force way to set up the camera matrix and parameters...may need to calibrate using ArUco
// if we do decide to use a calibrated parameter, then get ride of these lines...
// we read from a board configuration, so probably dont need to do this. hopefully
// cv::Mat CamMatrix = cv::Mat::eye(3, 3, CV_32F);
//CamMatrix.at<float>(0, 0) = 500;
//CamMatrix.at<float>(1, 1) = 500;
//CamMatrix.at<float>(0, 2) = inputImageCopy.size().width / 2;
//CamMatrix.at<float>(1, 2) = inputImageCopy.size().height / 2;
//cameraParams.setParams(CamMatrix, cv::Mat::zeros(1, 5, CV_32F), inputImageCopy.size());
vector <cv::Point3f> objPoints;
vector <cv::Point2f> imgPoints;
// get "3d" points of the object in real space, get "2d" points of the object in a flat image
getObjectAndImagePoints(boardDetector.getDetectedBoard(), objPoints, imgPoints);
// solve for transition matrix and store in rvec
// solve for rotation matrix and store in tvec
solvePnP(objPoints, imgPoints, cameraParams.CameraMatrix, cameraParams.Distorsion, rvec, tvec);
// determine the position of the "camera" --> which in our case, will be the robot as well
cv::Mat R;
cv::Rodrigues(rvec, R);
cv::Mat cameraRotationVector;
cv::Rodrigues(R.t(), cameraRotationVector);
cv::Mat cameraTranslationVector = -R.t() * tvec;
// Don't print stuff to the screen, for SPEED.
// // print the translation vectors (distance between marker and camera in x, y, z direction)
// cout << "Camera position " << cameraTranslationVector.at<double>(0) << ", " << cameraTranslationVector.at<double>(1) << ", " << cameraTranslationVector.at<double>(2) << endl;
//
// // print the pose vectors (orientation between marker and camera in x,y,z direction -- angle of rotation for each)
// cout << "Camera pose " << cameraRotationVector.at<double>(0) << ", " << cameraRotationVector.at<double>(1) << ", " << cameraRotationVector.at<double>(2) << endl;
// converting data from meters to centimeters
positionMsg.xDistance = cameraTranslationVector.at<double>(0) * 100.0;
positionMsg.yDistance = cameraTranslationVector.at<double>(1) * 100.0;
positionMsg.zDistance = cameraTranslationVector.at<double>(2) * 100.0;
positionMsg.xPose = cameraRotationVector.at<double>(0) * 100.0;
positionMsg.yPose = cameraRotationVector.at<double>(1) * 100.0;
positionMsg.zPose = cameraRotationVector.at<double>(2) * 100.0;
positionPub.publish(positionMsg);
// if the beacon is about to not be visible, rotate the camera
// starting with a small threshold first for testing purposes
if(positionMsg.yPose > 3 || positionMsg.yPose < -3){
if(positionmsg.yPose > 3 ){
targetAngle = currentCameraAngle - 3;
}
else {
targetAngle = currentCameraAngle + 3;
}
std_msgs::Int32 theta;
theta.data = targetAngle;
updateTargetAngle.publish(theta);
}
}
// not sure where this really belongs...
ros::spinOnce();
}
return 0;
} // end try
catch (std::exception &ex) {
cout << "Exception :" << ex.what() << endl;
} // end catch
} // end main
<|endoftext|>
|
<commit_before>// Copyright 2018 The Amber 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 "src/verifier.h"
#include <cmath>
#include <string>
#include <vector>
#include "src/command.h"
namespace amber {
namespace {
const double kEpsilon = 0.000001;
const double kDefaultTexelTolerance = 0.002;
// It returns true if the difference is within the given error.
// If |is_tolerance_percent| is true, the actual tolerance will be
// relative value i.e., |tolerance| / 100 * fabs(expected).
// Otherwise, this method uses the absolute value i.e., |tolerance|.
bool IsEqualWithTolerance(const double real,
const double expected,
double tolerance,
const bool is_tolerance_percent = true) {
double difference = std::fabs(real - expected);
if (is_tolerance_percent) {
if (difference > ((tolerance / 100.0) * std::fabs(expected))) {
return false;
}
} else if (difference > tolerance) {
return false;
}
return true;
}
template <typename T>
Result CheckValue(const ProbeSSBOCommand* command,
const uint8_t* memory,
const std::vector<Value>& values) {
const auto comp = command->GetComparator();
const auto& tolerance = command->GetTolerances();
const T* ptr = reinterpret_cast<const T*>(memory);
for (size_t i = 0; i < values.size(); ++i) {
const T val = values[i].IsInteger() ? static_cast<T>(values[i].AsUint64())
: static_cast<T>(values[i].AsDouble());
switch (comp) {
case ProbeSSBOCommand::Comparator::kEqual:
if (values[i].IsInteger()) {
if (static_cast<uint64_t>(*ptr) != static_cast<uint64_t>(val)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" == " + std::to_string(val) + ", at index " +
std::to_string(i));
}
} else {
if (!IsEqualWithTolerance(static_cast<const double>(*ptr),
static_cast<const double>(val), kEpsilon)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" == " + std::to_string(val) + ", at index " +
std::to_string(i));
}
}
break;
case ProbeSSBOCommand::Comparator::kNotEqual:
if (values[i].IsInteger()) {
if (static_cast<uint64_t>(*ptr) == static_cast<uint64_t>(val)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" != " + std::to_string(val) + ", at index " +
std::to_string(i));
}
} else {
if (IsEqualWithTolerance(static_cast<const double>(*ptr),
static_cast<const double>(val), kEpsilon)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" != " + std::to_string(val) + ", at index " +
std::to_string(i));
}
}
break;
case ProbeSSBOCommand::Comparator::kFuzzyEqual:
if (!IsEqualWithTolerance(
static_cast<const double>(*ptr), static_cast<const double>(val),
command->HasTolerances() ? tolerance[0].value : kEpsilon,
command->HasTolerances() ? tolerance[0].is_percent : true)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" ~= " + std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kLess:
if (*ptr >= val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) + " < " +
std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kLessOrEqual:
if (*ptr > val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" <= " + std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kGreater:
if (*ptr <= val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) + " > " +
std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kGreaterOrEqual:
if (*ptr < val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" >= " + std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
}
++ptr;
}
return {};
}
void SetupToleranceForTexels(const ProbeCommand* command,
double* tolerance,
bool* is_tolerance_percent) {
if (command->HasTolerances()) {
const auto& tol = command->GetTolerances();
if (tol.size() == 4) {
tolerance[0] = tol[0].value;
tolerance[1] = tol[1].value;
tolerance[2] = tol[2].value;
tolerance[3] = tol[3].value;
is_tolerance_percent[0] = tol[0].is_percent;
is_tolerance_percent[1] = tol[1].is_percent;
is_tolerance_percent[2] = tol[2].is_percent;
is_tolerance_percent[3] = tol[3].is_percent;
} else {
tolerance[0] = tol[0].value;
tolerance[1] = tol[0].value;
tolerance[2] = tol[0].value;
tolerance[3] = tol[0].value;
is_tolerance_percent[0] = tol[0].is_percent;
is_tolerance_percent[1] = tol[0].is_percent;
is_tolerance_percent[2] = tol[0].is_percent;
is_tolerance_percent[3] = tol[0].is_percent;
}
} else {
tolerance[0] = kDefaultTexelTolerance;
tolerance[1] = kDefaultTexelTolerance;
tolerance[2] = kDefaultTexelTolerance;
tolerance[3] = kDefaultTexelTolerance;
is_tolerance_percent[0] = false;
is_tolerance_percent[1] = false;
is_tolerance_percent[2] = false;
is_tolerance_percent[3] = false;
}
}
} // namespace
Verifier::Verifier() = default;
Verifier::~Verifier() = default;
Result Verifier::Probe(const ProbeCommand* command,
uint32_t texel_stride,
uint32_t row_stride,
uint32_t frame_width,
uint32_t frame_height,
const void* buf) {
uint32_t x = 0;
uint32_t y = 0;
uint32_t width = 0;
uint32_t height = 0;
if (command->IsWholeWindow()) {
width = frame_width;
height = frame_height;
} else if (command->IsRelative()) {
x = static_cast<uint32_t>(static_cast<float>(frame_width) *
command->GetX());
y = static_cast<uint32_t>(static_cast<float>(frame_height) *
command->GetY());
width = static_cast<uint32_t>(static_cast<float>(frame_width) *
command->GetWidth());
height = static_cast<uint32_t>(static_cast<float>(frame_height) *
command->GetHeight());
} else {
x = static_cast<uint32_t>(command->GetX());
y = static_cast<uint32_t>(command->GetY());
width = static_cast<uint32_t>(command->GetWidth());
height = static_cast<uint32_t>(command->GetHeight());
}
if (x + width > frame_width || y + height > frame_height) {
return Result(
"Line " + std::to_string(command->GetLine()) +
": Verifier::Probe Position(" + std::to_string(x + width - 1) + ", " +
std::to_string(y + height - 1) + ") is out of framebuffer scope (" +
std::to_string(frame_width) + "," + std::to_string(frame_height) + ")");
}
if (row_stride < frame_width * texel_stride) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier::Probe Row stride of " +
std::to_string(row_stride) + " is too small for " +
std::to_string(frame_width) + " texels of " +
std::to_string(texel_stride) + " bytes each");
}
double tolerance[4] = {0, 0, 0, 0};
bool is_tolerance_percent[4] = {0, 0, 0, 0};
SetupToleranceForTexels(command, tolerance, is_tolerance_percent);
// TODO(jaebaek): Support all VkFormat
const uint8_t* ptr = static_cast<const uint8_t*>(buf);
uint32_t count_of_invalid_pixels = 0;
uint32_t first_invalid_i = 0;
uint32_t first_invalid_j = 0;
for (uint32_t j = 0; j < height; ++j) {
const uint8_t* p = ptr + row_stride * (j + y) + texel_stride * x;
for (uint32_t i = 0; i < width; ++i) {
// TODO(jaebaek): Get actual pixel values based on frame buffer formats.
if (!IsEqualWithTolerance(
static_cast<const double>(command->GetR()),
static_cast<const double>(p[texel_stride * i]) / 255.0,
tolerance[0], is_tolerance_percent[0]) ||
!IsEqualWithTolerance(
static_cast<const double>(command->GetG()),
static_cast<const double>(p[texel_stride * i + 1]) / 255.0,
tolerance[1], is_tolerance_percent[1]) ||
!IsEqualWithTolerance(
static_cast<const double>(command->GetB()),
static_cast<const double>(p[texel_stride * i + 2]) / 255.0,
tolerance[2], is_tolerance_percent[2]) ||
(command->IsRGBA() &&
!IsEqualWithTolerance(
static_cast<const double>(command->GetA()),
static_cast<const double>(p[texel_stride * i + 3]) / 255.0,
tolerance[3], is_tolerance_percent[3]))) {
if (!count_of_invalid_pixels) {
first_invalid_i = i;
first_invalid_j = j;
}
++count_of_invalid_pixels;
}
}
}
if (count_of_invalid_pixels) {
const uint8_t* p = ptr + row_stride * (first_invalid_j + y) +
texel_stride * (x + first_invalid_i);
return Result(
"Line " + std::to_string(command->GetLine()) +
": Probe failed at: " + std::to_string(x + first_invalid_i) + ", " +
std::to_string(first_invalid_j + y) + "\n" +
" Expected RGBA: " + std::to_string(command->GetR() * 255) + ", " +
std::to_string(command->GetG() * 255) + ", " +
std::to_string(command->GetB() * 255) +
(command->IsRGBA() ? ", " + std::to_string(command->GetA() * 255) +
"\n Actual RGBA: "
: "\n Actual RGB: ") +
std::to_string(static_cast<int>(p[0])) + ", " +
std::to_string(static_cast<int>(p[1])) + ", " +
std::to_string(static_cast<int>(p[2])) +
(command->IsRGBA() ? ", " + std::to_string(static_cast<int>(p[3]))
: "") +
"\n" + "Probe failed in " + std::to_string(count_of_invalid_pixels) +
" pixels");
}
return {};
}
Result Verifier::ProbeSSBO(const ProbeSSBOCommand* command,
size_t size_in_bytes,
const void* cpu_memory) {
const auto& values = command->GetValues();
if (!cpu_memory) {
return values.empty() ? Result()
: Result(
"Verifier::ProbeSSBO actual data is empty "
"while expected data is not");
}
const auto& datum_type = command->GetDatumType();
size_t bytes_per_elem = datum_type.SizeInBytes() / datum_type.RowCount() /
datum_type.ColumnCount();
size_t offset = static_cast<size_t>(command->GetOffset());
if (values.size() * bytes_per_elem + offset > size_in_bytes) {
return Result(
"Line " + std::to_string(command->GetLine()) +
": Verifier::ProbeSSBO has more expected values than SSBO size");
}
if (offset % bytes_per_elem != 0) {
return Result(
"Line " + std::to_string(command->GetLine()) +
": Verifier::ProbeSSBO given offset is not multiple of bytes_per_elem");
}
const uint8_t* ptr = static_cast<const uint8_t*>(cpu_memory) + offset;
if (datum_type.IsInt8())
return CheckValue<int8_t>(command, ptr, values);
if (datum_type.IsUint8())
return CheckValue<uint8_t>(command, ptr, values);
if (datum_type.IsInt16())
return CheckValue<int16_t>(command, ptr, values);
if (datum_type.IsUint16())
return CheckValue<uint16_t>(command, ptr, values);
if (datum_type.IsInt32())
return CheckValue<int32_t>(command, ptr, values);
if (datum_type.IsUint32())
return CheckValue<uint32_t>(command, ptr, values);
if (datum_type.IsInt64())
return CheckValue<int64_t>(command, ptr, values);
if (datum_type.IsUint64())
return CheckValue<uint64_t>(command, ptr, values);
if (datum_type.IsFloat())
return CheckValue<float>(command, ptr, values);
if (datum_type.IsDouble())
return CheckValue<double>(command, ptr, values);
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier::ProbeSSBO unknown datum type");
}
} // namespace amber
<commit_msg>Remove consts to make CTS happy (#237)<commit_after>// Copyright 2018 The Amber 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 "src/verifier.h"
#include <cmath>
#include <string>
#include <vector>
#include "src/command.h"
namespace amber {
namespace {
const double kEpsilon = 0.000001;
const double kDefaultTexelTolerance = 0.002;
// It returns true if the difference is within the given error.
// If |is_tolerance_percent| is true, the actual tolerance will be
// relative value i.e., |tolerance| / 100 * fabs(expected).
// Otherwise, this method uses the absolute value i.e., |tolerance|.
bool IsEqualWithTolerance(const double real,
const double expected,
double tolerance,
const bool is_tolerance_percent = true) {
double difference = std::fabs(real - expected);
if (is_tolerance_percent) {
if (difference > ((tolerance / 100.0) * std::fabs(expected))) {
return false;
}
} else if (difference > tolerance) {
return false;
}
return true;
}
template <typename T>
Result CheckValue(const ProbeSSBOCommand* command,
const uint8_t* memory,
const std::vector<Value>& values) {
const auto comp = command->GetComparator();
const auto& tolerance = command->GetTolerances();
const T* ptr = reinterpret_cast<const T*>(memory);
for (size_t i = 0; i < values.size(); ++i) {
const T val = values[i].IsInteger() ? static_cast<T>(values[i].AsUint64())
: static_cast<T>(values[i].AsDouble());
switch (comp) {
case ProbeSSBOCommand::Comparator::kEqual:
if (values[i].IsInteger()) {
if (static_cast<uint64_t>(*ptr) != static_cast<uint64_t>(val)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" == " + std::to_string(val) + ", at index " +
std::to_string(i));
}
} else {
if (!IsEqualWithTolerance(static_cast<const double>(*ptr),
static_cast<const double>(val), kEpsilon)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" == " + std::to_string(val) + ", at index " +
std::to_string(i));
}
}
break;
case ProbeSSBOCommand::Comparator::kNotEqual:
if (values[i].IsInteger()) {
if (static_cast<uint64_t>(*ptr) == static_cast<uint64_t>(val)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" != " + std::to_string(val) + ", at index " +
std::to_string(i));
}
} else {
if (IsEqualWithTolerance(static_cast<const double>(*ptr),
static_cast<const double>(val), kEpsilon)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" != " + std::to_string(val) + ", at index " +
std::to_string(i));
}
}
break;
case ProbeSSBOCommand::Comparator::kFuzzyEqual:
if (!IsEqualWithTolerance(
static_cast<const double>(*ptr), static_cast<const double>(val),
command->HasTolerances() ? tolerance[0].value : kEpsilon,
command->HasTolerances() ? tolerance[0].is_percent : true)) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" ~= " + std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kLess:
if (*ptr >= val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) + " < " +
std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kLessOrEqual:
if (*ptr > val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" <= " + std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kGreater:
if (*ptr <= val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) + " > " +
std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
case ProbeSSBOCommand::Comparator::kGreaterOrEqual:
if (*ptr < val) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier failed: " + std::to_string(*ptr) +
" >= " + std::to_string(val) + ", at index " +
std::to_string(i));
}
break;
}
++ptr;
}
return {};
}
void SetupToleranceForTexels(const ProbeCommand* command,
double* tolerance,
bool* is_tolerance_percent) {
if (command->HasTolerances()) {
const auto& tol = command->GetTolerances();
if (tol.size() == 4) {
tolerance[0] = tol[0].value;
tolerance[1] = tol[1].value;
tolerance[2] = tol[2].value;
tolerance[3] = tol[3].value;
is_tolerance_percent[0] = tol[0].is_percent;
is_tolerance_percent[1] = tol[1].is_percent;
is_tolerance_percent[2] = tol[2].is_percent;
is_tolerance_percent[3] = tol[3].is_percent;
} else {
tolerance[0] = tol[0].value;
tolerance[1] = tol[0].value;
tolerance[2] = tol[0].value;
tolerance[3] = tol[0].value;
is_tolerance_percent[0] = tol[0].is_percent;
is_tolerance_percent[1] = tol[0].is_percent;
is_tolerance_percent[2] = tol[0].is_percent;
is_tolerance_percent[3] = tol[0].is_percent;
}
} else {
tolerance[0] = kDefaultTexelTolerance;
tolerance[1] = kDefaultTexelTolerance;
tolerance[2] = kDefaultTexelTolerance;
tolerance[3] = kDefaultTexelTolerance;
is_tolerance_percent[0] = false;
is_tolerance_percent[1] = false;
is_tolerance_percent[2] = false;
is_tolerance_percent[3] = false;
}
}
} // namespace
Verifier::Verifier() = default;
Verifier::~Verifier() = default;
Result Verifier::Probe(const ProbeCommand* command,
uint32_t texel_stride,
uint32_t row_stride,
uint32_t frame_width,
uint32_t frame_height,
const void* buf) {
uint32_t x = 0;
uint32_t y = 0;
uint32_t width = 0;
uint32_t height = 0;
if (command->IsWholeWindow()) {
width = frame_width;
height = frame_height;
} else if (command->IsRelative()) {
x = static_cast<uint32_t>(static_cast<float>(frame_width) *
command->GetX());
y = static_cast<uint32_t>(static_cast<float>(frame_height) *
command->GetY());
width = static_cast<uint32_t>(static_cast<float>(frame_width) *
command->GetWidth());
height = static_cast<uint32_t>(static_cast<float>(frame_height) *
command->GetHeight());
} else {
x = static_cast<uint32_t>(command->GetX());
y = static_cast<uint32_t>(command->GetY());
width = static_cast<uint32_t>(command->GetWidth());
height = static_cast<uint32_t>(command->GetHeight());
}
if (x + width > frame_width || y + height > frame_height) {
return Result(
"Line " + std::to_string(command->GetLine()) +
": Verifier::Probe Position(" + std::to_string(x + width - 1) + ", " +
std::to_string(y + height - 1) + ") is out of framebuffer scope (" +
std::to_string(frame_width) + "," + std::to_string(frame_height) + ")");
}
if (row_stride < frame_width * texel_stride) {
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier::Probe Row stride of " +
std::to_string(row_stride) + " is too small for " +
std::to_string(frame_width) + " texels of " +
std::to_string(texel_stride) + " bytes each");
}
double tolerance[4] = {0, 0, 0, 0};
bool is_tolerance_percent[4] = {0, 0, 0, 0};
SetupToleranceForTexels(command, tolerance, is_tolerance_percent);
// TODO(jaebaek): Support all VkFormat
const uint8_t* ptr = static_cast<const uint8_t*>(buf);
uint32_t count_of_invalid_pixels = 0;
uint32_t first_invalid_i = 0;
uint32_t first_invalid_j = 0;
for (uint32_t j = 0; j < height; ++j) {
const uint8_t* p = ptr + row_stride * (j + y) + texel_stride * x;
for (uint32_t i = 0; i < width; ++i) {
// TODO(jaebaek): Get actual pixel values based on frame buffer formats.
if (!IsEqualWithTolerance(
static_cast<double>(command->GetR()),
static_cast<double>(p[texel_stride * i]) / 255.0, tolerance[0],
is_tolerance_percent[0]) ||
!IsEqualWithTolerance(
static_cast<double>(command->GetG()),
static_cast<double>(p[texel_stride * i + 1]) / 255.0,
tolerance[1], is_tolerance_percent[1]) ||
!IsEqualWithTolerance(
static_cast<double>(command->GetB()),
static_cast<double>(p[texel_stride * i + 2]) / 255.0,
tolerance[2], is_tolerance_percent[2]) ||
(command->IsRGBA() &&
!IsEqualWithTolerance(
static_cast<double>(command->GetA()),
static_cast<double>(p[texel_stride * i + 3]) / 255.0,
tolerance[3], is_tolerance_percent[3]))) {
if (!count_of_invalid_pixels) {
first_invalid_i = i;
first_invalid_j = j;
}
++count_of_invalid_pixels;
}
}
}
if (count_of_invalid_pixels) {
const uint8_t* p = ptr + row_stride * (first_invalid_j + y) +
texel_stride * (x + first_invalid_i);
return Result(
"Line " + std::to_string(command->GetLine()) +
": Probe failed at: " + std::to_string(x + first_invalid_i) + ", " +
std::to_string(first_invalid_j + y) + "\n" +
" Expected RGBA: " + std::to_string(command->GetR() * 255) + ", " +
std::to_string(command->GetG() * 255) + ", " +
std::to_string(command->GetB() * 255) +
(command->IsRGBA() ? ", " + std::to_string(command->GetA() * 255) +
"\n Actual RGBA: "
: "\n Actual RGB: ") +
std::to_string(static_cast<int>(p[0])) + ", " +
std::to_string(static_cast<int>(p[1])) + ", " +
std::to_string(static_cast<int>(p[2])) +
(command->IsRGBA() ? ", " + std::to_string(static_cast<int>(p[3]))
: "") +
"\n" + "Probe failed in " + std::to_string(count_of_invalid_pixels) +
" pixels");
}
return {};
}
Result Verifier::ProbeSSBO(const ProbeSSBOCommand* command,
size_t size_in_bytes,
const void* cpu_memory) {
const auto& values = command->GetValues();
if (!cpu_memory) {
return values.empty() ? Result()
: Result(
"Verifier::ProbeSSBO actual data is empty "
"while expected data is not");
}
const auto& datum_type = command->GetDatumType();
size_t bytes_per_elem = datum_type.SizeInBytes() / datum_type.RowCount() /
datum_type.ColumnCount();
size_t offset = static_cast<size_t>(command->GetOffset());
if (values.size() * bytes_per_elem + offset > size_in_bytes) {
return Result(
"Line " + std::to_string(command->GetLine()) +
": Verifier::ProbeSSBO has more expected values than SSBO size");
}
if (offset % bytes_per_elem != 0) {
return Result(
"Line " + std::to_string(command->GetLine()) +
": Verifier::ProbeSSBO given offset is not multiple of bytes_per_elem");
}
const uint8_t* ptr = static_cast<const uint8_t*>(cpu_memory) + offset;
if (datum_type.IsInt8())
return CheckValue<int8_t>(command, ptr, values);
if (datum_type.IsUint8())
return CheckValue<uint8_t>(command, ptr, values);
if (datum_type.IsInt16())
return CheckValue<int16_t>(command, ptr, values);
if (datum_type.IsUint16())
return CheckValue<uint16_t>(command, ptr, values);
if (datum_type.IsInt32())
return CheckValue<int32_t>(command, ptr, values);
if (datum_type.IsUint32())
return CheckValue<uint32_t>(command, ptr, values);
if (datum_type.IsInt64())
return CheckValue<int64_t>(command, ptr, values);
if (datum_type.IsUint64())
return CheckValue<uint64_t>(command, ptr, values);
if (datum_type.IsFloat())
return CheckValue<float>(command, ptr, values);
if (datum_type.IsDouble())
return CheckValue<double>(command, ptr, values);
return Result("Line " + std::to_string(command->GetLine()) +
": Verifier::ProbeSSBO unknown datum type");
}
} // namespace amber
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "97dd275"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>l test harness<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX ""
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "46408ec"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.