text
stringlengths 54
60.6k
|
|---|
<commit_before>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* 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 <vlGraphics/FontManager.hpp>
#include <vlCore/Log.hpp>
#include <algorithm>
#include "ft2build.h"
#include FT_FREETYPE_H
using namespace vl;
//-----------------------------------------------------------------------------
FontManager::FontManager(void* free_type_library)
{
mFreeTypeLibrary = free_type_library;
if (!free_type_library)
{
FT_Library freetype = NULL;
FT_Error error = FT_Init_FreeType( &freetype );
mFreeTypeLibrary = freetype;
if ( error )
{
Log::error("FontManager::FontManager(): an error occurred during FreeType library initialization!\n");
VL_TRAP()
}
}
}
//-----------------------------------------------------------------------------
FontManager::~FontManager()
{
releaseAllFonts();
if (mFreeTypeLibrary)
{
FT_Done_FreeType( (FT_Library)mFreeTypeLibrary );
mFreeTypeLibrary = NULL;
}
}
//-----------------------------------------------------------------------------
Font* FontManager::acquireFont(const String& path, int size, bool smooth)
{
ref<Font> font;
for(unsigned i=0; !font && i<mFonts.size(); ++i)
if (fonts()[i]->filePath() == path && fonts()[i]->size() == size && fonts()[i]->smooth() == smooth)
font = fonts()[0];
if (!font)
{
font = new Font(this);
font->loadFont(path);
font->setSize(size);
font->setSmooth(smooth);
mFonts.push_back( font );
}
return font.get();
}
//-----------------------------------------------------------------------------
void FontManager::releaseFont(Font* font)
{
std::vector< ref<Font> >::iterator it = std::find(mFonts.begin(), mFonts.end(), font);
if (it != mFonts.end())
mFonts.erase(it);
}
//-----------------------------------------------------------------------------
void FontManager::releaseAllFonts()
{
for(unsigned i=0; i<mFonts.size(); ++i)
mFonts[i]->releaseFreeTypeData();
}
//-----------------------------------------------------------------------------
<commit_msg>BUG: fixed FontManager::acquireFont().<commit_after>/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* 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 <vlGraphics/FontManager.hpp>
#include <vlCore/Log.hpp>
#include <algorithm>
#include "ft2build.h"
#include FT_FREETYPE_H
using namespace vl;
//-----------------------------------------------------------------------------
FontManager::FontManager(void* free_type_library)
{
mFreeTypeLibrary = free_type_library;
if (!free_type_library)
{
FT_Library freetype = NULL;
FT_Error error = FT_Init_FreeType( &freetype );
mFreeTypeLibrary = freetype;
if ( error )
{
Log::error("FontManager::FontManager(): an error occurred during FreeType library initialization!\n");
VL_TRAP()
}
}
}
//-----------------------------------------------------------------------------
FontManager::~FontManager()
{
releaseAllFonts();
if (mFreeTypeLibrary)
{
FT_Done_FreeType( (FT_Library)mFreeTypeLibrary );
mFreeTypeLibrary = NULL;
}
}
//-----------------------------------------------------------------------------
Font* FontManager::acquireFont(const String& path, int size, bool smooth)
{
ref<Font> font;
for(unsigned i=0; !font && i<mFonts.size(); ++i)
if (fonts()[i]->filePath() == path && fonts()[i]->size() == size && fonts()[i]->smooth() == smooth)
font = fonts()[i];
if (!font)
{
font = new Font(this);
font->loadFont(path);
font->setSize(size);
font->setSmooth(smooth);
mFonts.push_back( font );
}
return font.get();
}
//-----------------------------------------------------------------------------
void FontManager::releaseFont(Font* font)
{
std::vector< ref<Font> >::iterator it = std::find(mFonts.begin(), mFonts.end(), font);
if (it != mFonts.end())
mFonts.erase(it);
}
//-----------------------------------------------------------------------------
void FontManager::releaseAllFonts()
{
for(unsigned i=0; i<mFonts.size(); ++i)
mFonts[i]->releaseFreeTypeData();
}
//-----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include "inc.h"
#include <functional>
#include <algorithm>
#include <iterator>
#include <type_traits>
NS_BEGIN(elloop);
using namespace std;
using namespace std::placeholders;
void print(int n1, int n2, int n3)
{
p(n1); p(" "); p(n2); p(" "); p(n3); cr;
}
template <typename T1, typename T2>
auto add(const T1 & t1, const T2& t2) -> decltype(t1 + t2)
{
return t1 + t2;
}
double multiply(double d1, double d2)
{
return d1 * d2;
}
double divide(double d1, int n)
{
assert(n != 0);
return d1 / n;
}
int ret4()
{
pln("ret4() called");
return 4;
}
class Foo
{
public:
void f(int n1, int n2, int n3)
{
p(n1); p(" "); p(n2); p(" "); p(n3); cr;
}
void print()
{
psln(a_);
}
int a_ { 100 };
};
class Movable
{
public:
Movable(int size = 1000000) : size_(size)
{
hugeMem_ = new int[size_];
}
~Movable()
{
if (hugeMem_)
{
delete hugeMem_;
}
}
Movable(Movable&& moved) : hugeMem_(moved.hugeMem_)
{
pln("Movable move ctr called");
moved.hugeMem_ = nullptr;
}
int *hugeMem_;
int size_;
};
Movable returnMovable()
{
Movable m;
LOGD("in %s, m.hugeMem_ is : %x\n", __FUNCTION__, m.hugeMem_);
return m;
}
void useMoveable(Movable m1, Movable m2)
{
psln(m1.hugeMem_);
psln(m2.hugeMem_);
}
// prototype of template function bind.
// template <class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);
// template <class Ret, class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindNormalFunction, @);
//----------------------------- extreme situation ------------------------------
auto emptyArg = bind(multiply, 1, 2);
EXPECT_EQ(2, emptyArg());
auto need2arg = bind(multiply, _1, _2);
EXPECT_EQ(2, need2arg(1, 2));
EXPECT_EQ(2, need2arg(1, 2, ret4()));
//--------------------- bind normal function -----------------------------------
auto same = bind(multiply, _1, _2);
EXPECT_EQ(200.0, same(2, 100));
auto doublize = bind(multiply, _1, 2.0);
EXPECT_EQ(200.0, doublize(100));
auto ret_20 = bind(multiply, 2, 10);
EXPECT_EQ(20.0, ret_20());
double d1 = divide(10, 2);
EXPECT_EQ(5, d1);
auto revertDivide = bind(divide, _2, _1);
double d2 = revertDivide(10, 2);
EXPECT_EQ(1 / 5.0, d2);
auto rounding = bind<int>(divide, _1, _2);
auto i1 = rounding(10, 3);
bool isSameType = is_same<int, decltype(i1)>::value;
EXPECT_TRUE(isSameType);
EXPECT_EQ(3, i1);
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, UsePlaceholders, @);
auto arg3 = bind(print, _3, _2, _1);
arg3(1, 2, 3); // 3 2 1
auto arg2 = bind(print, _1, _1, _2);
arg2(1, 2); // 1 1 2
auto arg1 = bind(print, _1, _1, _1);
arg1(1); // 1 1 1
auto arg0 = bind(print, 1, 1, 1);
arg0(); // 1 1 1
arg0(2); // 1 1 1, 2 is ignored.
arg0(2,2,2); // 1 1 1, 2 2 2 is ignored.
// try to accept 4 args
auto arg4 = bind(print, _2, _3, _4);
//arg4(1, 2, 3); // compile error, too few args.ɶ in call
arg4(1, 2, 3, 4); // 2 3 4; 1 is ignored.
arg4(1, 2, 3, 4, 5); // ok, 5 is ignored.
arg4(1, 2, 3, 4, 5, 6, 7, 8); // ok, 5~8 are ignored. ɶ in call
// try to accept 5 args
auto arg5 = bind(print, _1, _3, _5);
arg5(1, 2, 3, 4, 5); // 1 3 5; 2,4 is ingored.
/*
if fn() need N args, then the number of placeholders S, and the number of normal args
V, should satisfy N == S + V.
*/
// try to use more than 3 placeholders
auto hold4 = bind(print, _1, _2, _3, _4); // һ in bind
// error, too many args, caused by too many placeholders in definition of hold4.
//hold4(1, 2, 3, 4);
// try to use fewer than 3 placeholders.
auto hold2 = bind(print, _1, _2); // һ in definition
// error, too few args, caused by too few placeholders in definition of hold2.
//hold2(1, 2, 3);
//auto hold_100 = bind(print, _100, _1, _2); // max placeholders is _20 (VC++)
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindMemberFunction, @);
Foo foo;
Foo &foo_ref = foo;
auto mfarg4 = bind(&Foo::f, _1, _2, _3, _4);
// or use object directly.
mfarg4(foo, 10, 20, 30); // 10 20 30;
// use object pointer.
mfarg4(&foo, 10, 20, 30); // 10 20 30;
// use object ref.
mfarg4(foo_ref, 10, 20, 30); // 10 20 30;
auto mfarg3 = bind(&Foo::f, _1, _2, _3, 30);
mfarg3(&foo, 10, 20); // 10 20 30;
auto mfarg2 = bind(&Foo::f, _1, _2, 20, 30);
mfarg2(&foo, 10); // 10 20 30;
auto mfarg1 = bind(&Foo::f, _1, 10, 20, 30);
mfarg1(foo); // 10 20 30;
auto mfarg0 = bind(&Foo::f, foo, 10, 20, 30);
mfarg0(); // 10 20 30
auto mfarg01 = bind(&Foo::f, &foo, 10, 20, 30);
mfarg01(); // 10 20 30
auto mfarg02 = bind(&Foo::f, foo_ref, 10, 20, 30);
mfarg02(); // 10 20 30
// assign a mem_func to std::function.
std::function<void(int, int, int)> normal_func;
normal_func = bind(&Foo::f, foo, _1, _2, _3);
normal_func(10, 20, 30); // 10 20 30
//------------------------------ bind member var ----------------------------
auto bindMv = bind(&Foo::a_, _1);
psln(bindMv(foo)); // bindMv(foo) = 100
//psln(bindMv(&foo)); // bindMv(foo) = 100
psln(bindMv(foo_ref)); // bindMv(foo) = 100
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, SubexpressionOfBind, @);
//--------------------------------- nested bind--------------------------------
auto addby1 = [](int x) -> int
{
cout << "addby1() called" << endl;
return (x + 1);
};
auto nestedF = bind(print, _1, bind(addby1, _1), _2);
nestedF(1, 3); // addby1() called<cr> 1 2 3
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindTemplateFunction, @);
// work with template function.
auto addby2 = bind(add<double, double>, _1, 2.0);
psln(addby2(10.2)); // 12.2
// TODO : why bind can't work with template function?
//auto addBy2 = bind<double>(add, _1, 2.0);
// ANSWER: stupid!
// bind<T> means bind's return value f, will return a value of type T.
// for example:
auto addby2_int = bind<int>(add<double, double>, _1, 2.0);
psln(addby2_int(10.2)); // 12
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, ReferenceWrapperBind, @);
//--------------------------------- test ref ---------------------------------
int x(10);
auto bindRef = bind(print, 1, std::cref(x), x);
bindRef(); // 1 10 10;
x = 100;
bindRef(); // 1 100 10;
END_TEST;
//-------------------------------- bind movable obj --------------------------------
BEGIN_TEST(FunctorTest, BindMovable, @);
//Movable movable;
//psln(movable.hugeMem_);
//auto bindMoved = bind(useMoveable, _1, _2);
//bindMoved(returnMovable(), returnMovable());
//psln(movable.hugeMem_);
END_TEST;
//----------------------------- Bind Predefined Functors -----------------------------
RUN_GTEST(FunctorTest, BindPredefinedFunctors, @);
// all predefined functors:
// negate, plus, minus, multiplies, divides, modulus, equal_to,
// not_equal_to, less, greater, less_equal, greater_equal,
// logical_not, logical_and, logical_or, bit_and, bit_or, bit_xor
auto tenTimes = bind(multiplies<int>(), _1, 10);
EXPECT_EQ(100, tenTimes(10));
EXPECT_EQ(200, tenTimes(20));
EXPECT_EQ(300, tenTimes(30));
// nested bind.
vector<int> v {1, 2, 3, 4, 5, 6, 7, 8};
// output v[i] if 10*v[i] > 50.
copy_if(v.begin(), v.end(),
ostream_iterator<int>(cout, ", "),
bind(greater<int>(),
bind(multiplies<int>(), _1, 10),
50)); // 6,7,8,
cr;
END_TEST;
//----------------------------- Bind container Ref -----------------------------
RUN_GTEST(FunctorTest, BindContainerElemByRef, @);
END_TEST;
//----------------------- c++98 mem_fun and c++11 mem_fn -----------------------
BEGIN_TEST(FunctorTest, Mem_FunTest, @);
using std::for_each;
using std::mem_fun;
// 1. mem_fun is for a pointer to an obj.
vector<Foo*> fpv;
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());
for_each(fpv.begin(), fpv.end(), mem_fun(&Foo::print));
for_each(fpv.begin(), fpv.end(), [&](Foo* foo)
{
delete foo;
foo = nullptr;
});
// 2. mem_fun_ref is for obj.
vector<Foo> fv;
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());
for_each(fv.begin(), fv.end(), mem_fun_ref(&Foo::print));
// 3. mem_fn work for obj, ref to obj and ptr to obj.
Foo foo;
Foo &foo_ref = foo;
Foo *fp = &foo;
auto callMemFn = mem_fn(&Foo::f);
callMemFn(foo, 1, 2, 3);
callMemFn(foo_ref, 1, 2, 3);
callMemFn(fp, 1, 2, 3);
END_TEST;
NS_END(elloop);<commit_msg>bind vs mem_fn<commit_after>#include "gtest/gtest.h"
#include "inc.h"
#include <functional>
#include <algorithm>
#include <iterator>
#include <type_traits>
NS_BEGIN(elloop);
using namespace std;
using namespace std::placeholders;
void print(int n1, int n2, int n3)
{
p(n1); p(" "); p(n2); p(" "); p(n3); cr;
}
template <typename T1, typename T2>
auto add(const T1 & t1, const T2& t2) -> decltype(t1 + t2)
{
return t1 + t2;
}
double multiply(double d1, double d2)
{
return d1 * d2;
}
double divide(double d1, int n)
{
assert(n != 0);
return d1 / n;
}
int ret4()
{
pln("ret4() called");
return 4;
}
class Foo
{
public:
void f(int n1, int n2, int n3)
{
p(n1); p(" "); p(n2); p(" "); p(n3); cr;
}
void print()
{
psln(a_);
}
int a_ { 100 };
};
class Movable
{
public:
Movable(int size = 1000000) : size_(size)
{
hugeMem_ = new int[size_];
}
~Movable()
{
if (hugeMem_)
{
delete hugeMem_;
}
}
Movable(Movable&& moved) : hugeMem_(moved.hugeMem_)
{
pln("Movable move ctr called");
moved.hugeMem_ = nullptr;
}
int *hugeMem_;
int size_;
};
Movable returnMovable()
{
Movable m;
LOGD("in %s, m.hugeMem_ is : %x\n", __FUNCTION__, m.hugeMem_);
return m;
}
void useMoveable(Movable m1, Movable m2)
{
psln(m1.hugeMem_);
psln(m2.hugeMem_);
}
// prototype of template function bind.
// template <class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);
// template <class Ret, class Fn, class... Args>
// /* unspecified */ bind(Fn&& fn, Args&&... args);
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindNormalFunction, @);
//----------------------------- extreme situation ------------------------------
auto emptyArg = bind(multiply, 1, 2);
EXPECT_EQ(2, emptyArg());
auto need2arg = bind(multiply, _1, _2);
EXPECT_EQ(2, need2arg(1, 2));
EXPECT_EQ(2, need2arg(1, 2, ret4()));
//--------------------- bind normal function -----------------------------------
auto same = bind(multiply, _1, _2);
EXPECT_EQ(200.0, same(2, 100));
auto doublize = bind(multiply, _1, 2.0);
EXPECT_EQ(200.0, doublize(100));
auto ret_20 = bind(multiply, 2, 10);
EXPECT_EQ(20.0, ret_20());
double d1 = divide(10, 2);
EXPECT_EQ(5, d1);
auto revertDivide = bind(divide, _2, _1);
double d2 = revertDivide(10, 2);
EXPECT_EQ(1 / 5.0, d2);
auto rounding = bind<int>(divide, _1, _2);
auto i1 = rounding(10, 3);
bool isSameType = is_same<int, decltype(i1)>::value;
EXPECT_TRUE(isSameType);
EXPECT_EQ(3, i1);
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, UsePlaceholders, @);
auto arg3 = bind(print, _3, _2, _1);
arg3(1, 2, 3); // 3 2 1
auto arg2 = bind(print, _1, _1, _2);
arg2(1, 2); // 1 1 2
auto arg1 = bind(print, _1, _1, _1);
arg1(1); // 1 1 1
auto arg0 = bind(print, 1, 1, 1);
arg0(); // 1 1 1
arg0(2); // 1 1 1, 2 is ignored.
arg0(2,2,2); // 1 1 1, 2 2 2 is ignored.
// try to accept 4 args
auto arg4 = bind(print, _2, _3, _4);
//arg4(1, 2, 3); // compile error, too few args.ɶ in call
arg4(1, 2, 3, 4); // 2 3 4; 1 is ignored.
arg4(1, 2, 3, 4, 5); // ok, 5 is ignored.
arg4(1, 2, 3, 4, 5, 6, 7, 8); // ok, 5~8 are ignored. ɶ in call
// try to accept 5 args
auto arg5 = bind(print, _1, _3, _5);
arg5(1, 2, 3, 4, 5); // 1 3 5; 2,4 is ingored.
/*
if fn() need N args, then the number of placeholders S, and the number of normal args
V, should satisfy N == S + V.
*/
// try to use more than 3 placeholders
auto hold4 = bind(print, _1, _2, _3, _4); // һ in bind
// error, too many args, caused by too many placeholders in definition of hold4.
//hold4(1, 2, 3, 4);
// try to use fewer than 3 placeholders.
auto hold2 = bind(print, _1, _2); // һ in definition
// error, too few args, caused by too few placeholders in definition of hold2.
//hold2(1, 2, 3);
//auto hold_100 = bind(print, _100, _1, _2); // max placeholders is _20 (VC++)
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindMemberFunction, @);
Foo foo;
Foo &foo_ref = foo;
auto mfarg4 = bind(&Foo::f, _1, _2, _3, _4);
// or use object directly.
mfarg4(foo, 10, 20, 30); // 10 20 30;
// use object pointer.
mfarg4(&foo, 10, 20, 30); // 10 20 30;
// use object ref.
mfarg4(foo_ref, 10, 20, 30); // 10 20 30;
auto mfarg3 = bind(&Foo::f, _1, _2, _3, 30);
mfarg3(&foo, 10, 20); // 10 20 30;
auto mfarg2 = bind(&Foo::f, _1, _2, 20, 30);
mfarg2(&foo, 10); // 10 20 30;
auto mfarg1 = bind(&Foo::f, _1, 10, 20, 30);
mfarg1(foo); // 10 20 30;
auto mfarg0 = bind(&Foo::f, foo, 10, 20, 30);
mfarg0(); // 10 20 30
auto mfarg01 = bind(&Foo::f, &foo, 10, 20, 30);
mfarg01(); // 10 20 30
auto mfarg02 = bind(&Foo::f, foo_ref, 10, 20, 30);
mfarg02(); // 10 20 30
// assign a mem_func to std::function.
std::function<void(int, int, int)> normal_func;
normal_func = bind(&Foo::f, foo, _1, _2, _3);
normal_func(10, 20, 30); // 10 20 30
//------------------------------ bind member var ----------------------------
auto bindMv = bind(&Foo::a_, _1);
psln(bindMv(foo)); // bindMv(foo) = 100
//psln(bindMv(&foo)); // bindMv(foo) = 100
psln(bindMv(foo_ref)); // bindMv(foo) = 100
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, SubexpressionOfBind, @);
//--------------------------------- nested bind--------------------------------
auto addby1 = [](int x) -> int
{
cout << "addby1() called" << endl;
return (x + 1);
};
auto nestedF = bind(print, _1, bind(addby1, _1), _2);
nestedF(1, 3); // addby1() called<cr> 1 2 3
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, BindTemplateFunction, @);
// work with template function.
auto addby2 = bind(add<double, double>, _1, 2.0);
psln(addby2(10.2)); // 12.2
// TODO : why bind can't work with template function?
//auto addBy2 = bind<double>(add, _1, 2.0);
// ANSWER: stupid!
// bind<T> means bind's return value f, will return a value of type T.
// for example:
auto addby2_int = bind<int>(add<double, double>, _1, 2.0);
psln(addby2_int(10.2)); // 12
END_TEST;
//----------------------------- begin of new test -----------------------------
BEGIN_TEST(FunctorTest, ReferenceWrapperBind, @);
//--------------------------------- test ref ---------------------------------
int x(10);
auto bindRef = bind(print, 1, std::cref(x), x);
bindRef(); // 1 10 10;
x = 100;
bindRef(); // 1 100 10;
END_TEST;
//-------------------------------- bind movable obj --------------------------------
BEGIN_TEST(FunctorTest, BindMovable, @);
//Movable movable;
//psln(movable.hugeMem_);
//auto bindMoved = bind(useMoveable, _1, _2);
//bindMoved(returnMovable(), returnMovable());
//psln(movable.hugeMem_);
END_TEST;
//----------------------------- Bind Predefined Functors -----------------------------
BEGIN_TEST(FunctorTest, BindPredefinedFunctors, @);
// all predefined functors:
// negate, plus, minus, multiplies, divides, modulus, equal_to,
// not_equal_to, less, greater, less_equal, greater_equal,
// logical_not, logical_and, logical_or, bit_and, bit_or, bit_xor
auto tenTimes = bind(multiplies<int>(), _1, 10);
EXPECT_EQ(100, tenTimes(10));
EXPECT_EQ(200, tenTimes(20));
EXPECT_EQ(300, tenTimes(30));
vector<int> v {1, 2, 3, 4, 5, 6, 7, 8};
// nested bind. output v[i] if 10*v[i] > 50.
copy_if(v.begin(), v.end(),
ostream_iterator<int>(cout, ", "),
bind(greater<int>(),
bind(multiplies<int>(), _1, 10),
50)); // 6,7,8,
cr;
END_TEST;
//----------------------------- Bind container Ref -----------------------------
BEGIN_TEST(FunctorTest, BindContainerElemByRef, @);
END_TEST;
//----------------------- c++98 mem_fun and c++11 mem_fn -----------------------
BEGIN_TEST(FunctorTest, Mem_FunTest, @);
using std::for_each;
using std::mem_fun;
// 1. mem_fun is for a pointer to an obj.
vector<Foo*> fpv;
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());
fpv.push_back(new Foo());
for_each(fpv.begin(), fpv.end(), mem_fun(&Foo::print));
cr;
for_each(fpv.begin(), fpv.end(), bind(&Foo::print, _1)); // also can use bind
cr;
for_each(fpv.begin(), fpv.end(), [&](Foo* foo)
{
delete foo;
foo = nullptr;
});
// 2. mem_fun_ref is for obj.
vector<Foo> fv;
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());
fv.push_back(Foo());
for_each(fv.begin(), fv.end(), mem_fun_ref(&Foo::print));
cr;
for_each(fv.begin(), fv.end(), bind(&Foo::print, _1)); // also can use bind
cr;
// 3. mem_fn work for obj, ref to obj and ptr to obj.
Foo foo;
Foo &foo_ref = foo;
Foo *fp = &foo;
auto callMemFn = mem_fn(&Foo::f);
callMemFn(foo, 1, 2, 3);
callMemFn(foo_ref, 1, 2, 3);
callMemFn(fp, 1, 2, 3);
END_TEST;
NS_END(elloop);<|endoftext|>
|
<commit_before>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)
#ifndef CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP
#define CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP
//
// typedefs for windows.h types to avoid pulling in entire system header for simple types
//
typedef void* HANDLE;
#endif
<commit_msg>crunch_base - Added DWORD to wintypes.hp<commit_after>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)
#ifndef CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP
#define CRUNCH_BASE_PLATFORM_WIN32_WINTYPES_HPP
//
// typedefs for windows.h types to avoid pulling in entire system header for simple types
//
typedef void* HANDLE;
typedef unsigned long DWORD;
#endif
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <DuiDebug>
#include <DuiDismissEvent>
#include "duiscenewindow.h"
#include "duiscenewindowmodel.h"
#include "duiscenewindow_p.h"
#include "duiscene.h"
#include "duiscenemanager.h"
#include "duiscenemanager_p.h"
#include "duiapplication.h"
#include "duiscenewindowview.h"
#include "duiwindow.h"
#include "duiwidgetcreator.h"
DUI_REGISTER_WIDGET_NO_CREATE(DuiSceneWindow)
DuiSceneWindowPrivate::DuiSceneWindowPrivate()
{
managedManually = false;
shown = false;
dismissed = false;
policy = DuiSceneWindow::KeepWhenDone;
effect = NULL;
}
void DuiSceneWindowPrivate::appear(bool now, DuiWindow *window, DuiSceneWindow::DeletionPolicy policy)
{
Q_Q(DuiSceneWindow);
if (!window) {
window = DuiApplication::activeWindow();
if (!window) {
// TODO: Create and show() a Dui[Application]Window on the fly?
duiWarning("DuiSceneWindow")
<< "Construct and show DuiWindow before showing a scene window";
return;
}
}
if (now) {
window->sceneManager()->showWindowNow(q, policy);
} else {
window->sceneManager()->showWindow(q, policy);
}
}
DuiSceneWindow::DuiSceneWindow(QGraphicsItem *parent) :
DuiWidgetController(new DuiSceneWindowPrivate, new DuiSceneWindowModel, parent)
{
Q_D(DuiSceneWindow);
d->windowType = PlainSceneWindow;
// TODO: Remove this along with deprecated windowShown() and windowHidden()
connect(this, SIGNAL(appeared()), SIGNAL(windowShown()));
connect(this, SIGNAL(disappeared()), SIGNAL(windowHidden()));
}
bool DuiSceneWindowPrivate::dismiss(bool now)
{
Q_Q(DuiSceneWindow);
/* ABI FREEZE: Release this
DuiDismissEvent dismissEvent;
QApplication::sendEvent(q, &dismissEvent);
if (!dismissEvent.isAccepted()) {
return false;
}
*/
if (q->sceneManager()) {
if (now) {
q->sceneManager()->closeWindowNow(q);
} else {
q->sceneManager()->closeWindow(q);
}
}
return true;
}
DuiSceneWindow::DuiSceneWindow(DuiSceneWindowPrivate *dd, DuiSceneWindowModel *model, DuiSceneWindow::WindowType windowType, const QString &viewType, QGraphicsItem *parent) :
DuiWidgetController(dd, model, parent)
{
Q_D(DuiSceneWindow);
setViewType(viewType);
d->windowType = windowType;
// TODO: Remove this along with deprecated windowShown() and windowHidden()
connect(this, SIGNAL(appeared()), SIGNAL(windowShown()));
connect(this, SIGNAL(disappeared()), SIGNAL(windowHidden()));
}
DuiSceneWindow::~DuiSceneWindow()
{
if (sceneManager())
sceneManager()->d_func()->detachWindow(this);
}
DuiSceneWindow::WindowType DuiSceneWindow::windowType() const
{
Q_D(const DuiSceneWindow);
return d->windowType;
}
DuiSceneWindow::DeletionPolicy DuiSceneWindow::deletionPolicy() const
{
Q_D(const DuiSceneWindow);
return d->policy;
}
bool DuiSceneWindow::isManagedManually() const
{
Q_D(const DuiSceneWindow);
return d->managedManually;
}
void DuiSceneWindow::setManagedManually(bool managedManually)
{
Q_D(DuiSceneWindow);
d->managedManually = managedManually;
}
void DuiSceneWindow::appear(DuiWindow *window, DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(false, window, policy);
}
void DuiSceneWindow::appearNow(DuiWindow *window, DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(true, window, policy);
}
void DuiSceneWindow::appear(DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(false, 0, policy);
}
void DuiSceneWindow::appearNow(DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(true, 0, policy);
}
void DuiSceneWindow::disappear()
{
if (sceneManager())
sceneManager()->hideWindow(this);
}
void DuiSceneWindow::disappearNow()
{
if (sceneManager())
sceneManager()->hideWindowNow(this);
}
Qt::Alignment DuiSceneWindow::alignment() const
{
Qt::Alignment result = 0;
if (view()) {
const DuiSceneWindowView *sceneWindowView =
qobject_cast<const DuiSceneWindowView *>(view());
if (sceneWindowView) {
result = sceneWindowView->alignment();
}
}
if (layoutDirection() == Qt::RightToLeft) {
if (result.testFlag(Qt::AlignLeft)) {
result &= ~Qt::AlignLeft;
result |= Qt::AlignRight;
} else if (result.testFlag(Qt::AlignRight)) {
result &= ~Qt::AlignRight;
result |= Qt::AlignLeft;
}
}
return result;
}
QPointF DuiSceneWindow::offset() const
{
QPointF result;
if (view()) {
const DuiSceneWindowView *sceneWindowView =
qobject_cast<const DuiSceneWindowView *>(view());
if (sceneWindowView) {
result = sceneWindowView->offset();
}
} else {
result = QPointF(0, 0);
}
return result;
}
bool DuiSceneWindow::dismiss()
{
Q_D(DuiSceneWindow);
return d->dismiss(false);
}
bool DuiSceneWindow::dismissNow()
{
Q_D(DuiSceneWindow);
return d->dismiss(true);
}
/* ABI FREEZE: Release this
void DuiSceneWindow::dismissEvent(DuiDismissEvent *event)
{
event->accept();
}
*/
void DuiSceneWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
dismiss();
}
bool DuiSceneWindow::event(QEvent *event)
{
/* ABI FREEZE: Release this
if (event->type() == DuiDismissEvent::eventType()) {
dismissEvent(static_cast<DuiDismissEvent *>(event));
}
*/
return DuiWidgetController::event(event);
}
<commit_msg>Changes: Workaround for NB#157036 - DuiDialog doesn't emit rejected when dialog is disposed on clicking the dimmed area.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <DuiDebug>
#include <DuiDismissEvent>
#include "duiscenewindow.h"
#include "duiscenewindowmodel.h"
#include "duiscenewindow_p.h"
#include "duiscene.h"
#include "duiscenemanager.h"
#include "duiscenemanager_p.h"
#include "duiapplication.h"
#include "duiscenewindowview.h"
#include "duiwindow.h"
#include "duidialog.h"
#include "duiwidgetcreator.h"
DUI_REGISTER_WIDGET_NO_CREATE(DuiSceneWindow)
DuiSceneWindowPrivate::DuiSceneWindowPrivate()
{
managedManually = false;
shown = false;
dismissed = false;
policy = DuiSceneWindow::KeepWhenDone;
effect = NULL;
}
void DuiSceneWindowPrivate::appear(bool now, DuiWindow *window, DuiSceneWindow::DeletionPolicy policy)
{
Q_Q(DuiSceneWindow);
if (!window) {
window = DuiApplication::activeWindow();
if (!window) {
// TODO: Create and show() a Dui[Application]Window on the fly?
duiWarning("DuiSceneWindow")
<< "Construct and show DuiWindow before showing a scene window";
return;
}
}
if (now) {
window->sceneManager()->showWindowNow(q, policy);
} else {
window->sceneManager()->showWindow(q, policy);
}
}
DuiSceneWindow::DuiSceneWindow(QGraphicsItem *parent) :
DuiWidgetController(new DuiSceneWindowPrivate, new DuiSceneWindowModel, parent)
{
Q_D(DuiSceneWindow);
d->windowType = PlainSceneWindow;
// TODO: Remove this along with deprecated windowShown() and windowHidden()
connect(this, SIGNAL(appeared()), SIGNAL(windowShown()));
connect(this, SIGNAL(disappeared()), SIGNAL(windowHidden()));
}
bool DuiSceneWindowPrivate::dismiss(bool now)
{
Q_Q(DuiSceneWindow);
/* ABI FREEZE: Release this
DuiDismissEvent dismissEvent;
QApplication::sendEvent(q, &dismissEvent);
if (!dismissEvent.isAccepted()) {
return false;
}
*/
// BEGIN WORKAROUND: Remove it after abi freeze.
DuiDialog* dlg = qobject_cast<DuiDialog*>(q);
if (dlg) {
dlg->done(DuiDialog::Rejected);
return true;
}
// END WORKAROUND
if (q->sceneManager()) {
if (now) {
q->sceneManager()->closeWindowNow(q);
} else {
q->sceneManager()->closeWindow(q);
}
}
return true;
}
DuiSceneWindow::DuiSceneWindow(DuiSceneWindowPrivate *dd, DuiSceneWindowModel *model, DuiSceneWindow::WindowType windowType, const QString &viewType, QGraphicsItem *parent) :
DuiWidgetController(dd, model, parent)
{
Q_D(DuiSceneWindow);
setViewType(viewType);
d->windowType = windowType;
// TODO: Remove this along with deprecated windowShown() and windowHidden()
connect(this, SIGNAL(appeared()), SIGNAL(windowShown()));
connect(this, SIGNAL(disappeared()), SIGNAL(windowHidden()));
}
DuiSceneWindow::~DuiSceneWindow()
{
if (sceneManager())
sceneManager()->d_func()->detachWindow(this);
}
DuiSceneWindow::WindowType DuiSceneWindow::windowType() const
{
Q_D(const DuiSceneWindow);
return d->windowType;
}
DuiSceneWindow::DeletionPolicy DuiSceneWindow::deletionPolicy() const
{
Q_D(const DuiSceneWindow);
return d->policy;
}
bool DuiSceneWindow::isManagedManually() const
{
Q_D(const DuiSceneWindow);
return d->managedManually;
}
void DuiSceneWindow::setManagedManually(bool managedManually)
{
Q_D(DuiSceneWindow);
d->managedManually = managedManually;
}
void DuiSceneWindow::appear(DuiWindow *window, DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(false, window, policy);
}
void DuiSceneWindow::appearNow(DuiWindow *window, DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(true, window, policy);
}
void DuiSceneWindow::appear(DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(false, 0, policy);
}
void DuiSceneWindow::appearNow(DuiSceneWindow::DeletionPolicy policy)
{
Q_D(DuiSceneWindow);
d->appear(true, 0, policy);
}
void DuiSceneWindow::disappear()
{
if (sceneManager())
sceneManager()->hideWindow(this);
}
void DuiSceneWindow::disappearNow()
{
if (sceneManager())
sceneManager()->hideWindowNow(this);
}
Qt::Alignment DuiSceneWindow::alignment() const
{
Qt::Alignment result = 0;
if (view()) {
const DuiSceneWindowView *sceneWindowView =
qobject_cast<const DuiSceneWindowView *>(view());
if (sceneWindowView) {
result = sceneWindowView->alignment();
}
}
if (layoutDirection() == Qt::RightToLeft) {
if (result.testFlag(Qt::AlignLeft)) {
result &= ~Qt::AlignLeft;
result |= Qt::AlignRight;
} else if (result.testFlag(Qt::AlignRight)) {
result &= ~Qt::AlignRight;
result |= Qt::AlignLeft;
}
}
return result;
}
QPointF DuiSceneWindow::offset() const
{
QPointF result;
if (view()) {
const DuiSceneWindowView *sceneWindowView =
qobject_cast<const DuiSceneWindowView *>(view());
if (sceneWindowView) {
result = sceneWindowView->offset();
}
} else {
result = QPointF(0, 0);
}
return result;
}
bool DuiSceneWindow::dismiss()
{
Q_D(DuiSceneWindow);
return d->dismiss(false);
}
bool DuiSceneWindow::dismissNow()
{
Q_D(DuiSceneWindow);
return d->dismiss(true);
}
/* ABI FREEZE: Release this
void DuiSceneWindow::dismissEvent(DuiDismissEvent *event)
{
event->accept();
}
*/
void DuiSceneWindow::closeEvent(QCloseEvent *event)
{
event->ignore();
dismiss();
}
bool DuiSceneWindow::event(QEvent *event)
{
/* ABI FREEZE: Release this
if (event->type() == DuiDismissEvent::eventType()) {
dismissEvent(static_cast<DuiDismissEvent *>(event));
}
*/
return DuiWidgetController::event(event);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2004 by *
* Jason Kivlighn (jkivlighn@gmail.com) *
* Unai Garro (ugarro@users.sourceforge.net) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "recipelistview.h"
#include <qintdict.h>
#include <qdatastream.h>
#include <qtooltip.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kconfig.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kprogress.h>
#include "backends/recipedb.h"
class UncategorizedItem : public QListViewItem
{
public:
UncategorizedItem( QListView *lv ) : QListViewItem( lv, i18n("Uncategorized") ){}
int rtti() const { return 1006; }
};
RecipeItemDrag::RecipeItemDrag( RecipeListItem *recipeItem, QWidget *dragSource, const char *name )
: QStoredDrag( RECIPEITEMMIMETYPE, dragSource, name )
{
if ( recipeItem ) {
QByteArray data;
QDataStream out( data, IO_WriteOnly );
out << recipeItem->recipeID();
out << recipeItem->title();
setEncodedData( data );
}
}
bool RecipeItemDrag::canDecode( QMimeSource* e )
{
return e->provides( RECIPEITEMMIMETYPE );
}
bool RecipeItemDrag::decode( const QMimeSource* e, RecipeListItem& item )
{
if ( !e )
return false;
QByteArray data = e->encodedData( RECIPEITEMMIMETYPE );
if ( data.isEmpty() )
return false;
QString title;
int recipeID;
QDataStream in( data, IO_ReadOnly );
in >> recipeID;
in >> title;
item.setTitle( title );
item.setRecipeID( recipeID );
return true;
}
class RecipeListToolTip : public QToolTip
{
public:
RecipeListToolTip( RecipeListView *view ) : QToolTip(view->viewport()), m_view(view)
{}
void maybeTip( const QPoint &point )
{
QListViewItem *item = m_view->itemAt( point );
if ( item ) {
QString text = m_view->tooltip(item,0);
if ( !text.isEmpty() )
tip( m_view->itemRect( item ), text );
}
}
private:
RecipeListView *m_view;
};
RecipeListView::RecipeListView( QWidget *parent, RecipeDB *db ) : StdCategoryListView( parent, db ),
flat_list( false ),
m_uncat_item(0),
m_progress_dlg(0)
{
setColumnText( 0, i18n( "Recipe" ) );
KConfig *config = KGlobal::config(); config->setGroup( "Performance" );
curr_limit = config->readNumEntry("CategoryLimit",-1);
KIconLoader il;
setPixmap( il.loadIcon( "categories", KIcon::NoGroup, 16 ) );
setSelectionMode( QListView::Extended );
(void)new RecipeListToolTip(this);
}
void RecipeListView::init()
{
connect( database, SIGNAL( recipeCreated( const Element &, const ElementList & ) ), SLOT( createRecipe( const Element &, const ElementList & ) ) );
connect( database, SIGNAL( recipeRemoved( int ) ), SLOT( removeRecipe( int ) ) );
connect( database, SIGNAL( recipeRemoved( int, int ) ), SLOT( removeRecipe( int, int ) ) );
connect( database, SIGNAL( recipeModified( const Element &, const ElementList & ) ), SLOT( modifyRecipe( const Element &, const ElementList & ) ) );
StdCategoryListView::init();
}
QDragObject *RecipeListView::dragObject()
{
RecipeListItem * item = dynamic_cast<RecipeListItem*>( currentItem() );
if ( item != 0 ) {
RecipeItemDrag * obj = new RecipeItemDrag( item, this, "Recipe drag item" );
/*const QPixmap *pm = item->pixmap(0);
if( pm )
obj->setPixmap( *pm );*/
return obj;
}
return 0;
}
bool RecipeListView::acceptDrag( QDropEvent *event ) const
{
return RecipeItemDrag::canDecode( event );
}
QString RecipeListView::tooltip(QListViewItem *item, int column) const
{
if ( item->rtti() == RECIPELISTITEM_RTTI ) {
RecipeListItem *recipe_it = (RecipeListItem*)item;
Recipe r;
database->loadRecipe(&r,RecipeDB::Meta|RecipeDB::Noatime,recipe_it->recipeID() );
KLocale *locale = KGlobal::locale();
return QString("<center><b>%7</b></center><center>__________</center>%1 %2<br />%3 %4<br />%5 %6")
.arg(i18n("Created:")).arg(locale->formatDateTime(r.ctime))
.arg(i18n("Modified:")).arg(locale->formatDateTime(r.mtime))
.arg(i18n("Last Accessed:")).arg(locale->formatDateTime(r.atime))
.arg(recipe_it->title());
}/* Maybe this would be handy
else if ( item->rtti() == CATEGORYLISTITEM_RTTI ) {
CategoryListItem *cat_it = (CategoryListItem*)item;
return QString("<b>%1</b><hr />%2: %3")
.arg(cat_it->categoryName())
.arg(i18n("Recipes"))
.arg(QString::number(WHATEVER THE CHILD COUNT IS));
}*/
return QString::null;
}
void RecipeListView::load(int limit, int offset)
{
m_uncat_item = 0;
if ( flat_list ) {
ElementList recipeList;
database->loadRecipeList( &recipeList );
ElementList::const_iterator recipe_it;
for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) {
Recipe recipe;
recipe.recipeID = ( *recipe_it ).id;
recipe.title = ( *recipe_it ).name;
createRecipe( recipe, -1 );
}
}
else {
StdCategoryListView::load(limit,offset);
if ( offset == 0 ) {
ElementList recipeList;
database->loadUncategorizedRecipes( &recipeList );
ElementList::const_iterator recipe_it;
for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) {
Recipe recipe;
recipe.recipeID = ( *recipe_it ).id;
recipe.title = ( *recipe_it ).name;
createRecipe( recipe, -1 );
}
}
}
}
void RecipeListView::populate( QListViewItem *item )
{
CategoryItemInfo *cat_item = dynamic_cast<CategoryItemInfo*>(item);
if ( !cat_item || cat_item->isPopulated() ) return;
delete item->firstChild(); //delete the "pseudo item"
if ( m_progress_dlg ){
m_progress_dlg->progressBar()->advance(1);
kapp->processEvents();
}
StdCategoryListView::populate(item);
if ( !flat_list ) {
int id = cat_item->categoryId();
// Now show the recipes
ElementList recipeList;
database->loadRecipeList( &recipeList, id );
ElementList::const_iterator recipe_it;
for ( recipe_it = recipeList.begin(); recipe_it != recipeList.end(); ++recipe_it ) {
Recipe recipe;
recipe.recipeID = ( *recipe_it ).id;
recipe.title = ( *recipe_it ).name;
createRecipe( recipe, id );
}
}
}
void RecipeListView::populateAll( QListViewItem *parent )
{
bool first = false;
if ( !parent ) {
first = true;
m_progress_dlg = new KProgressDialog(this,"populate_all_prog_dlg",QString::null,i18n("Loading recipes"),true);
m_progress_dlg->setAllowCancel(false);
m_progress_dlg->progressBar()->setTotalSteps(0);
m_progress_dlg->progressBar()->setPercentageVisible(false);
m_progress_dlg->grabKeyboard(); //don't let the user keep hitting keys
parent = firstChild();
}
else {
populate( parent );
parent = parent->firstChild();
}
for ( QListViewItem *item = parent; item; item = item->nextSibling() ) {
if ( m_progress_dlg && m_progress_dlg->wasCancelled() )
break;
populateAll( item );
}
if ( first ) {
delete m_progress_dlg;
m_progress_dlg = 0;
}
}
void RecipeListView::createRecipe( const Recipe &recipe, int parent_id )
{
if ( parent_id == -1 ) {
if ( !m_uncat_item && curr_offset == 0 ) {
m_uncat_item = new UncategorizedItem(this);
if ( childCount() == 1 ) //only call createElement if this is the only item in the list
createElement(m_uncat_item); //otherwise, this item won't stay at the top
}
if ( m_uncat_item )
new RecipeListItem( m_uncat_item, recipe );
}
else {
CategoryListItem *parent = (CategoryListItem*)items_map[ parent_id ];
if ( parent && parent->isPopulated() )
createElement(new RecipeListItem( parent, recipe ));
}
}
void RecipeListView::createRecipe( const Element &recipe_el, const ElementList &categories )
{
Recipe recipe;
recipe.recipeID = recipe_el.id;
recipe.title = recipe_el.name;
if ( categories.count() == 0 ) {
createRecipe( recipe, -1 );
}
else {
for ( ElementList::const_iterator cat_it = categories.begin(); cat_it != categories.end(); ++cat_it ) {
int cur_cat_id = ( *cat_it ).id;
QListViewItemIterator iterator( this );
while ( iterator.current() ) {
if ( iterator.current() ->rtti() == 1001 ) {
CategoryListItem * cat_item = ( CategoryListItem* ) iterator.current();
if ( cat_item->categoryId() == cur_cat_id ) {
createRecipe( recipe, cur_cat_id );
}
}
++iterator;
}
}
}
}
void RecipeListView::createElement( QListViewItem *item )
{
CategoryItemInfo *cat_item = dynamic_cast<CategoryItemInfo*>(item);
if ( !cat_item || cat_item->isPopulated() ) return;
#if 0
ElementList list;
database->loadRecipeList( &list, cat_item->categoryId() );
if ( list.count() > 0 )
#endif
new PseudoListItem( item );
CategoryListView::createElement(item);
}
void RecipeListView::modifyRecipe( const Element &recipe, const ElementList &categories )
{
removeRecipe( recipe.id );
createRecipe( recipe, categories );
}
void RecipeListView::removeRecipe( int id )
{
QListViewItemIterator iterator( this );
while ( iterator.current() ) {
if ( iterator.current() ->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current();
if ( recipe_it->recipeID() == id ) {
removeElement(recipe_it);
//delete the "Uncategorized" item if we removed the last recipe that was under it
if ( m_uncat_item->childCount() == 0 ) {
delete m_uncat_item;
m_uncat_item = 0;
}
}
}
++iterator;
}
}
void RecipeListView::removeRecipe( int recipe_id, int cat_id )
{
QListViewItem * item = items_map[ cat_id ];
//find out if this is the only category the recipe belongs to
int finds = 0;
QListViewItemIterator iterator( this );
while ( iterator.current() ) {
if ( iterator.current() ->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current();
if ( recipe_it->recipeID() == recipe_id ) {
if ( finds > 1 )
break;
finds++;
}
}
++iterator;
}
//do this to only iterate over children of 'item'
QListViewItem *pEndItem = NULL;
QListViewItem *pStartItem = item;
do {
if ( pStartItem->nextSibling() )
pEndItem = pStartItem->nextSibling();
else
pStartItem = pStartItem->parent();
}
while ( pStartItem && !pEndItem );
iterator = QListViewItemIterator( item );
while ( iterator.current() != pEndItem ) {
if ( iterator.current() ->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current();
if ( recipe_it->recipeID() == recipe_id ) {
if ( finds == 1 ) {
//the item is now uncategorized
if ( !m_uncat_item && curr_offset == 0 )
m_uncat_item = new UncategorizedItem(this);
if ( m_uncat_item ) {
Recipe r;
r.title = recipe_it->title(); r.recipeID = recipe_id;
new RecipeListItem(m_uncat_item,r);
}
}
removeElement(recipe_it);
break;
}
}
++iterator;
}
}
void RecipeListView::removeCategory( int id )
{
QListViewItem * item = items_map[ id ];
if ( !item )
return ; //this may have been deleted already by its parent being deleted
moveChildrenToRoot( item );
StdCategoryListView::removeCategory( id );
}
void RecipeListView::moveChildrenToRoot( QListViewItem *item )
{
QListViewItem * next_sibling;
for ( QListViewItem * it = item->firstChild(); it; it = next_sibling ) {
next_sibling = it->nextSibling();
if ( it->rtti() == 1000 ) {
RecipeListItem *recipe_it = (RecipeListItem*) it;
Recipe r;
r.title = recipe_it->title(); r.recipeID = recipe_it->recipeID();
//the item is now uncategorized
removeElement(it,false);
it->parent() ->takeItem( it );
if ( !m_uncat_item && curr_offset == 0 )
m_uncat_item = new UncategorizedItem(this);
if ( m_uncat_item )
new RecipeListItem(m_uncat_item,r);
}
moveChildrenToRoot( it );
delete it;
}
}
#include "recipelistview.moc"
<commit_msg>Show recipes in alphabetical order (like it used to be)<commit_after>/***************************************************************************
* Copyright (C) 2004 by *
* Jason Kivlighn (jkivlighn@gmail.com) *
* Unai Garro (ugarro@users.sourceforge.net) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
***************************************************************************/
#include "recipelistview.h"
#include <qintdict.h>
#include <qdatastream.h>
#include <qtooltip.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kconfig.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <kprogress.h>
#include "backends/recipedb.h"
class UncategorizedItem : public QListViewItem
{
public:
UncategorizedItem( QListView *lv ) : QListViewItem( lv, i18n("Uncategorized") ){}
int rtti() const { return 1006; }
};
RecipeItemDrag::RecipeItemDrag( RecipeListItem *recipeItem, QWidget *dragSource, const char *name )
: QStoredDrag( RECIPEITEMMIMETYPE, dragSource, name )
{
if ( recipeItem ) {
QByteArray data;
QDataStream out( data, IO_WriteOnly );
out << recipeItem->recipeID();
out << recipeItem->title();
setEncodedData( data );
}
}
bool RecipeItemDrag::canDecode( QMimeSource* e )
{
return e->provides( RECIPEITEMMIMETYPE );
}
bool RecipeItemDrag::decode( const QMimeSource* e, RecipeListItem& item )
{
if ( !e )
return false;
QByteArray data = e->encodedData( RECIPEITEMMIMETYPE );
if ( data.isEmpty() )
return false;
QString title;
int recipeID;
QDataStream in( data, IO_ReadOnly );
in >> recipeID;
in >> title;
item.setTitle( title );
item.setRecipeID( recipeID );
return true;
}
class RecipeListToolTip : public QToolTip
{
public:
RecipeListToolTip( RecipeListView *view ) : QToolTip(view->viewport()), m_view(view)
{}
void maybeTip( const QPoint &point )
{
QListViewItem *item = m_view->itemAt( point );
if ( item ) {
QString text = m_view->tooltip(item,0);
if ( !text.isEmpty() )
tip( m_view->itemRect( item ), text );
}
}
private:
RecipeListView *m_view;
};
RecipeListView::RecipeListView( QWidget *parent, RecipeDB *db ) : StdCategoryListView( parent, db ),
flat_list( false ),
m_uncat_item(0),
m_progress_dlg(0)
{
setColumnText( 0, i18n( "Recipe" ) );
KConfig *config = KGlobal::config(); config->setGroup( "Performance" );
curr_limit = config->readNumEntry("CategoryLimit",-1);
KIconLoader il;
setPixmap( il.loadIcon( "categories", KIcon::NoGroup, 16 ) );
setSelectionMode( QListView::Extended );
(void)new RecipeListToolTip(this);
}
void RecipeListView::init()
{
connect( database, SIGNAL( recipeCreated( const Element &, const ElementList & ) ), SLOT( createRecipe( const Element &, const ElementList & ) ) );
connect( database, SIGNAL( recipeRemoved( int ) ), SLOT( removeRecipe( int ) ) );
connect( database, SIGNAL( recipeRemoved( int, int ) ), SLOT( removeRecipe( int, int ) ) );
connect( database, SIGNAL( recipeModified( const Element &, const ElementList & ) ), SLOT( modifyRecipe( const Element &, const ElementList & ) ) );
StdCategoryListView::init();
}
QDragObject *RecipeListView::dragObject()
{
RecipeListItem * item = dynamic_cast<RecipeListItem*>( currentItem() );
if ( item != 0 ) {
RecipeItemDrag * obj = new RecipeItemDrag( item, this, "Recipe drag item" );
/*const QPixmap *pm = item->pixmap(0);
if( pm )
obj->setPixmap( *pm );*/
return obj;
}
return 0;
}
bool RecipeListView::acceptDrag( QDropEvent *event ) const
{
return RecipeItemDrag::canDecode( event );
}
QString RecipeListView::tooltip(QListViewItem *item, int column) const
{
if ( item->rtti() == RECIPELISTITEM_RTTI ) {
RecipeListItem *recipe_it = (RecipeListItem*)item;
Recipe r;
database->loadRecipe(&r,RecipeDB::Meta|RecipeDB::Noatime,recipe_it->recipeID() );
KLocale *locale = KGlobal::locale();
return QString("<center><b>%7</b></center><center>__________</center>%1 %2<br />%3 %4<br />%5 %6")
.arg(i18n("Created:")).arg(locale->formatDateTime(r.ctime))
.arg(i18n("Modified:")).arg(locale->formatDateTime(r.mtime))
.arg(i18n("Last Accessed:")).arg(locale->formatDateTime(r.atime))
.arg(recipe_it->title());
}/* Maybe this would be handy
else if ( item->rtti() == CATEGORYLISTITEM_RTTI ) {
CategoryListItem *cat_it = (CategoryListItem*)item;
return QString("<b>%1</b><hr />%2: %3")
.arg(cat_it->categoryName())
.arg(i18n("Recipes"))
.arg(QString::number(WHATEVER THE CHILD COUNT IS));
}*/
return QString::null;
}
void RecipeListView::load(int limit, int offset)
{
m_uncat_item = 0;
if ( flat_list ) {
ElementList recipeList;
database->loadRecipeList( &recipeList );
ElementList::const_iterator recipe_it;
for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) {
Recipe recipe;
recipe.recipeID = ( *recipe_it ).id;
recipe.title = ( *recipe_it ).name;
createRecipe( recipe, -1 );
}
}
else {
StdCategoryListView::load(limit,offset);
if ( offset == 0 ) {
ElementList recipeList;
database->loadUncategorizedRecipes( &recipeList );
ElementList::const_iterator recipe_it;
for ( recipe_it = recipeList.begin();recipe_it != recipeList.end();++recipe_it ) {
Recipe recipe;
recipe.recipeID = ( *recipe_it ).id;
recipe.title = ( *recipe_it ).name;
createRecipe( recipe, -1 );
}
}
}
}
void RecipeListView::populate( QListViewItem *item )
{
CategoryItemInfo *cat_item = dynamic_cast<CategoryItemInfo*>(item);
if ( !cat_item || cat_item->isPopulated() ) return;
delete item->firstChild(); //delete the "pseudo item"
if ( m_progress_dlg ){
m_progress_dlg->progressBar()->advance(1);
kapp->processEvents();
}
StdCategoryListView::populate(item);
if ( !flat_list ) {
int id = cat_item->categoryId();
// Now show the recipes
ElementList recipeList;
database->loadRecipeList( &recipeList, id );
ElementList::const_iterator recipe_it;
for ( recipe_it = recipeList.begin(); recipe_it != recipeList.end(); ++recipe_it ) {
Recipe recipe;
recipe.recipeID = ( *recipe_it ).id;
recipe.title = ( *recipe_it ).name;
createRecipe( recipe, id );
}
}
}
void RecipeListView::populateAll( QListViewItem *parent )
{
bool first = false;
if ( !parent ) {
first = true;
m_progress_dlg = new KProgressDialog(this,"populate_all_prog_dlg",QString::null,i18n("Loading recipes"),true);
m_progress_dlg->setAllowCancel(false);
m_progress_dlg->progressBar()->setTotalSteps(0);
m_progress_dlg->progressBar()->setPercentageVisible(false);
m_progress_dlg->grabKeyboard(); //don't let the user keep hitting keys
parent = firstChild();
}
else {
populate( parent );
parent = parent->firstChild();
}
for ( QListViewItem *item = parent; item; item = item->nextSibling() ) {
if ( m_progress_dlg && m_progress_dlg->wasCancelled() )
break;
populateAll( item );
}
if ( first ) {
delete m_progress_dlg;
m_progress_dlg = 0;
}
}
void RecipeListView::createRecipe( const Recipe &recipe, int parent_id )
{
if ( parent_id == -1 ) {
if ( !m_uncat_item && curr_offset == 0 ) {
m_uncat_item = new UncategorizedItem(this);
if ( childCount() == 1 ) //only call createElement if this is the only item in the list
createElement(m_uncat_item); //otherwise, this item won't stay at the top
}
if ( m_uncat_item )
new RecipeListItem( m_uncat_item, recipe );
}
else {
CategoryListItem *parent = (CategoryListItem*)items_map[ parent_id ];
if ( parent && parent->isPopulated() )
createElement(new RecipeListItem( parent, recipe ));
}
}
void RecipeListView::createRecipe( const Element &recipe_el, const ElementList &categories )
{
Recipe recipe;
recipe.recipeID = recipe_el.id;
recipe.title = recipe_el.name;
if ( categories.count() == 0 ) {
createRecipe( recipe, -1 );
}
else {
for ( ElementList::const_iterator cat_it = categories.begin(); cat_it != categories.end(); ++cat_it ) {
int cur_cat_id = ( *cat_it ).id;
QListViewItemIterator iterator( this );
while ( iterator.current() ) {
if ( iterator.current() ->rtti() == 1001 ) {
CategoryListItem * cat_item = ( CategoryListItem* ) iterator.current();
if ( cat_item->categoryId() == cur_cat_id ) {
createRecipe( recipe, cur_cat_id );
}
}
++iterator;
}
}
}
}
void RecipeListView::createElement( QListViewItem *item )
{
CategoryItemInfo *cat_item = dynamic_cast<CategoryItemInfo*>(item);
#if 0
ElementList list;
database->loadRecipeList( &list, cat_item->categoryId() );
if ( list.count() > 0 )
#endif
if ( cat_item )
new PseudoListItem( item );
CategoryListView::createElement(item);
}
void RecipeListView::modifyRecipe( const Element &recipe, const ElementList &categories )
{
removeRecipe( recipe.id );
createRecipe( recipe, categories );
}
void RecipeListView::removeRecipe( int id )
{
QListViewItemIterator iterator( this );
while ( iterator.current() ) {
if ( iterator.current() ->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current();
if ( recipe_it->recipeID() == id ) {
removeElement(recipe_it);
//delete the "Uncategorized" item if we removed the last recipe that was under it
if ( m_uncat_item->childCount() == 0 ) {
delete m_uncat_item;
m_uncat_item = 0;
}
}
}
++iterator;
}
}
void RecipeListView::removeRecipe( int recipe_id, int cat_id )
{
QListViewItem * item = items_map[ cat_id ];
//find out if this is the only category the recipe belongs to
int finds = 0;
QListViewItemIterator iterator( this );
while ( iterator.current() ) {
if ( iterator.current() ->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current();
if ( recipe_it->recipeID() == recipe_id ) {
if ( finds > 1 )
break;
finds++;
}
}
++iterator;
}
//do this to only iterate over children of 'item'
QListViewItem *pEndItem = NULL;
QListViewItem *pStartItem = item;
do {
if ( pStartItem->nextSibling() )
pEndItem = pStartItem->nextSibling();
else
pStartItem = pStartItem->parent();
}
while ( pStartItem && !pEndItem );
iterator = QListViewItemIterator( item );
while ( iterator.current() != pEndItem ) {
if ( iterator.current() ->rtti() == 1000 ) {
RecipeListItem * recipe_it = ( RecipeListItem* ) iterator.current();
if ( recipe_it->recipeID() == recipe_id ) {
if ( finds == 1 ) {
//the item is now uncategorized
if ( !m_uncat_item && curr_offset == 0 )
m_uncat_item = new UncategorizedItem(this);
if ( m_uncat_item ) {
Recipe r;
r.title = recipe_it->title(); r.recipeID = recipe_id;
new RecipeListItem(m_uncat_item,r);
}
}
removeElement(recipe_it);
break;
}
}
++iterator;
}
}
void RecipeListView::removeCategory( int id )
{
QListViewItem * item = items_map[ id ];
if ( !item )
return ; //this may have been deleted already by its parent being deleted
moveChildrenToRoot( item );
StdCategoryListView::removeCategory( id );
}
void RecipeListView::moveChildrenToRoot( QListViewItem *item )
{
QListViewItem * next_sibling;
for ( QListViewItem * it = item->firstChild(); it; it = next_sibling ) {
next_sibling = it->nextSibling();
if ( it->rtti() == 1000 ) {
RecipeListItem *recipe_it = (RecipeListItem*) it;
Recipe r;
r.title = recipe_it->title(); r.recipeID = recipe_it->recipeID();
//the item is now uncategorized
removeElement(it,false);
it->parent() ->takeItem( it );
if ( !m_uncat_item && curr_offset == 0 )
m_uncat_item = new UncategorizedItem(this);
if ( m_uncat_item )
new RecipeListItem(m_uncat_item,r);
}
moveChildrenToRoot( it );
delete it;
}
}
#include "recipelistview.moc"
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "types.hh"
#include <algorithm>
namespace sstables {
static constexpr int TOMBSTONE_HISTOGRAM_BIN_SIZE = 100;
/**
* ColumnStats holds information about the columns for one row inside sstable
*/
struct column_stats {
/** how many columns are there in the row */
uint64_t column_count;
uint64_t start_offset;
uint64_t row_size;
/** the largest (client-supplied) timestamp in the row */
uint64_t min_timestamp;
uint64_t max_timestamp;
int max_local_deletion_time;
/** histogram of tombstone drop time */
streaming_histogram tombstone_histogram;
/** max and min column names according to comparator */
std::vector<bytes> min_column_names;
std::vector<bytes> max_column_names;
bool has_legacy_counter_shards;
column_stats() {
column_count = 0;
start_offset = 0;
row_size = 0;
min_timestamp = std::numeric_limits<uint64_t>::max();
max_timestamp = std::numeric_limits<uint64_t>::min();
max_local_deletion_time = std::numeric_limits<int>::min();
tombstone_histogram = streaming_histogram(TOMBSTONE_HISTOGRAM_BIN_SIZE);
has_legacy_counter_shards = false;
}
void reset() {
*this = column_stats();
}
void update_min_timestamp(uint64_t potential_min) {
min_timestamp = std::min(min_timestamp, potential_min);
}
void update_max_timestamp(uint64_t potential_max) {
max_timestamp = std::max(max_timestamp, potential_max);
}
void update_max_local_deletion_time(int potential_value) {
max_local_deletion_time = std::max(max_local_deletion_time, potential_value);
}
};
class metadata_collector {
public:
static constexpr double NO_COMPRESSION_RATIO = -1.0;
static estimated_histogram default_column_count_histogram() {
// EH of 114 can track a max value of 2395318855, i.e., > 2B columns
return estimated_histogram(114);
}
static estimated_histogram default_row_size_histogram() {
// EH of 150 can track a max value of 1697806495183, i.e., > 1.5PB
return estimated_histogram(150);
}
static streaming_histogram default_tombstone_drop_time_histogram() {
return streaming_histogram(TOMBSTONE_HISTOGRAM_BIN_SIZE);
}
static replay_position replay_position_none() {
// Cassandra says the following about replay position none:
// NONE is used for SSTables that are streamed from other nodes and thus have no relationship
// with our local commitlog. The values satisfy the critera that
// - no real commitlog segment will have the given id
// - it will sort before any real replayposition, so it will be effectively ignored by getReplayPosition
return replay_position(-1UL, 0U);
}
private:
estimated_histogram _estimated_row_size = default_row_size_histogram();
estimated_histogram _estimated_column_count = default_column_count_histogram();
replay_position _replay_position = replay_position_none();
uint64_t _min_timestamp = std::numeric_limits<uint64_t>::max();
uint64_t _max_timestamp = std::numeric_limits<uint64_t>::min();
uint64_t _repaired_at = 0;
int _max_local_deletion_time = std::numeric_limits<int>::min();
double _compression_ratio = NO_COMPRESSION_RATIO;
// FIXME: add C++ version of protected Set<Integer> ancestors = new HashSet<>();
streaming_histogram _estimated_tombstone_drop_time = default_tombstone_drop_time_histogram();
int _sstable_level = 0;
std::vector<bytes> _min_column_names;
std::vector<bytes> _max_column_names;
bool _has_legacy_counter_shards = false;
private:
/*
* Convert a vector of bytes into a disk array of disk_string<uint16_t>.
*/
static void convert(disk_array<uint32_t, disk_string<uint16_t>>&to, std::vector<bytes>&& from) {
to.elements.resize(from.size());
for (auto i = 0U; i < from.size(); i++) {
to.elements[i].value = std::move(from[i]);
}
}
public:
void add_row_size(uint64_t row_size) {
_estimated_row_size.add(row_size);
}
void add_column_count(uint64_t column_count) {
_estimated_column_count.add(column_count);
}
void merge_tombstone_histogram(streaming_histogram& histogram) {
_estimated_tombstone_drop_time.merge(histogram);
}
/**
* Ratio is compressed/uncompressed and it is
* if you have 1.x then compression isn't helping
*/
void add_compression_ratio(uint64_t compressed, uint64_t uncompressed) {
_compression_ratio = (double) compressed/uncompressed;
}
void update_min_timestamp(uint64_t potential_min) {
_min_timestamp = std::min(_min_timestamp, potential_min);
}
void update_max_timestamp(uint64_t potential_max) {
_max_timestamp = std::max(_max_timestamp, potential_max);
}
void update_max_local_deletion_time(int max_local_deletion_time) {
_max_local_deletion_time = std::max(_max_local_deletion_time, max_local_deletion_time);
}
void set_replay_position(replay_position rp) {
_replay_position = rp;
}
void set_repaired_at(uint64_t repaired_at) {
_repaired_at = repaired_at;
}
void sstable_level(int sstable_level) {
_sstable_level = sstable_level;
}
void update_min_column_names(std::vector<bytes>& min_column_names) {
if (min_column_names.size() > 0) {
column_name_helper::merge_min_components(_min_column_names, std::move(min_column_names));
}
}
void update_max_column_names(std::vector<bytes>& max_column_names) {
if (max_column_names.size() > 0) {
column_name_helper::merge_max_components(_max_column_names, std::move(max_column_names));
}
}
void update_has_legacy_counter_shards(bool has_legacy_counter_shards) {
_has_legacy_counter_shards = _has_legacy_counter_shards || has_legacy_counter_shards;
}
void update(column_stats& stats) {
update_min_timestamp(stats.min_timestamp);
update_max_timestamp(stats.max_timestamp);
update_max_local_deletion_time(stats.max_local_deletion_time);
add_row_size(stats.row_size);
add_column_count(stats.column_count);
merge_tombstone_histogram(stats.tombstone_histogram);
update_min_column_names(stats.min_column_names);
update_max_column_names(stats.max_column_names);
update_has_legacy_counter_shards(stats.has_legacy_counter_shards);
}
void construct_stats(stats_metadata& m) {
m.estimated_row_size = std::move(_estimated_row_size);
m.estimated_column_count = std::move(_estimated_column_count);
m.position = _replay_position;
m.min_timestamp = _min_timestamp;
m.max_timestamp = _max_timestamp;
m.max_local_deletion_time = _max_local_deletion_time;
m.compression_ratio = _compression_ratio;
m.estimated_tombstone_drop_time = std::move(_estimated_tombstone_drop_time);
m.sstable_level = _sstable_level;
m.repaired_at = _repaired_at;
convert(m.min_column_names, std::move(_min_column_names));
convert(m.max_column_names, std::move(_max_column_names));
m.has_legacy_counter_shards = _has_legacy_counter_shards;
}
};
}
<commit_msg>sstables: extend metadata collector to add ancestors<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "types.hh"
#include <algorithm>
namespace sstables {
static constexpr int TOMBSTONE_HISTOGRAM_BIN_SIZE = 100;
/**
* ColumnStats holds information about the columns for one row inside sstable
*/
struct column_stats {
/** how many columns are there in the row */
uint64_t column_count;
uint64_t start_offset;
uint64_t row_size;
/** the largest (client-supplied) timestamp in the row */
uint64_t min_timestamp;
uint64_t max_timestamp;
int max_local_deletion_time;
/** histogram of tombstone drop time */
streaming_histogram tombstone_histogram;
/** max and min column names according to comparator */
std::vector<bytes> min_column_names;
std::vector<bytes> max_column_names;
bool has_legacy_counter_shards;
column_stats() {
column_count = 0;
start_offset = 0;
row_size = 0;
min_timestamp = std::numeric_limits<uint64_t>::max();
max_timestamp = std::numeric_limits<uint64_t>::min();
max_local_deletion_time = std::numeric_limits<int>::min();
tombstone_histogram = streaming_histogram(TOMBSTONE_HISTOGRAM_BIN_SIZE);
has_legacy_counter_shards = false;
}
void reset() {
*this = column_stats();
}
void update_min_timestamp(uint64_t potential_min) {
min_timestamp = std::min(min_timestamp, potential_min);
}
void update_max_timestamp(uint64_t potential_max) {
max_timestamp = std::max(max_timestamp, potential_max);
}
void update_max_local_deletion_time(int potential_value) {
max_local_deletion_time = std::max(max_local_deletion_time, potential_value);
}
};
class metadata_collector {
public:
static constexpr double NO_COMPRESSION_RATIO = -1.0;
static estimated_histogram default_column_count_histogram() {
// EH of 114 can track a max value of 2395318855, i.e., > 2B columns
return estimated_histogram(114);
}
static estimated_histogram default_row_size_histogram() {
// EH of 150 can track a max value of 1697806495183, i.e., > 1.5PB
return estimated_histogram(150);
}
static streaming_histogram default_tombstone_drop_time_histogram() {
return streaming_histogram(TOMBSTONE_HISTOGRAM_BIN_SIZE);
}
static replay_position replay_position_none() {
// Cassandra says the following about replay position none:
// NONE is used for SSTables that are streamed from other nodes and thus have no relationship
// with our local commitlog. The values satisfy the critera that
// - no real commitlog segment will have the given id
// - it will sort before any real replayposition, so it will be effectively ignored by getReplayPosition
return replay_position(-1UL, 0U);
}
private:
estimated_histogram _estimated_row_size = default_row_size_histogram();
estimated_histogram _estimated_column_count = default_column_count_histogram();
replay_position _replay_position = replay_position_none();
uint64_t _min_timestamp = std::numeric_limits<uint64_t>::max();
uint64_t _max_timestamp = std::numeric_limits<uint64_t>::min();
uint64_t _repaired_at = 0;
int _max_local_deletion_time = std::numeric_limits<int>::min();
double _compression_ratio = NO_COMPRESSION_RATIO;
std::set<int> _ancestors;
streaming_histogram _estimated_tombstone_drop_time = default_tombstone_drop_time_histogram();
int _sstable_level = 0;
std::vector<bytes> _min_column_names;
std::vector<bytes> _max_column_names;
bool _has_legacy_counter_shards = false;
private:
/*
* Convert a vector of bytes into a disk array of disk_string<uint16_t>.
*/
static void convert(disk_array<uint32_t, disk_string<uint16_t>>&to, std::vector<bytes>&& from) {
to.elements.resize(from.size());
for (auto i = 0U; i < from.size(); i++) {
to.elements[i].value = std::move(from[i]);
}
}
public:
void add_row_size(uint64_t row_size) {
_estimated_row_size.add(row_size);
}
void add_column_count(uint64_t column_count) {
_estimated_column_count.add(column_count);
}
void merge_tombstone_histogram(streaming_histogram& histogram) {
_estimated_tombstone_drop_time.merge(histogram);
}
/**
* Ratio is compressed/uncompressed and it is
* if you have 1.x then compression isn't helping
*/
void add_compression_ratio(uint64_t compressed, uint64_t uncompressed) {
_compression_ratio = (double) compressed/uncompressed;
}
void update_min_timestamp(uint64_t potential_min) {
_min_timestamp = std::min(_min_timestamp, potential_min);
}
void update_max_timestamp(uint64_t potential_max) {
_max_timestamp = std::max(_max_timestamp, potential_max);
}
void update_max_local_deletion_time(int max_local_deletion_time) {
_max_local_deletion_time = std::max(_max_local_deletion_time, max_local_deletion_time);
}
void set_replay_position(replay_position rp) {
_replay_position = rp;
}
void set_repaired_at(uint64_t repaired_at) {
_repaired_at = repaired_at;
}
void add_ancestor(int generation) {
_ancestors.insert(generation);
}
void sstable_level(int sstable_level) {
_sstable_level = sstable_level;
}
void update_min_column_names(std::vector<bytes>& min_column_names) {
if (min_column_names.size() > 0) {
column_name_helper::merge_min_components(_min_column_names, std::move(min_column_names));
}
}
void update_max_column_names(std::vector<bytes>& max_column_names) {
if (max_column_names.size() > 0) {
column_name_helper::merge_max_components(_max_column_names, std::move(max_column_names));
}
}
void update_has_legacy_counter_shards(bool has_legacy_counter_shards) {
_has_legacy_counter_shards = _has_legacy_counter_shards || has_legacy_counter_shards;
}
void update(column_stats& stats) {
update_min_timestamp(stats.min_timestamp);
update_max_timestamp(stats.max_timestamp);
update_max_local_deletion_time(stats.max_local_deletion_time);
add_row_size(stats.row_size);
add_column_count(stats.column_count);
merge_tombstone_histogram(stats.tombstone_histogram);
update_min_column_names(stats.min_column_names);
update_max_column_names(stats.max_column_names);
update_has_legacy_counter_shards(stats.has_legacy_counter_shards);
}
void construct_stats(stats_metadata& m) {
m.estimated_row_size = std::move(_estimated_row_size);
m.estimated_column_count = std::move(_estimated_column_count);
m.position = _replay_position;
m.min_timestamp = _min_timestamp;
m.max_timestamp = _max_timestamp;
m.max_local_deletion_time = _max_local_deletion_time;
m.compression_ratio = _compression_ratio;
m.estimated_tombstone_drop_time = std::move(_estimated_tombstone_drop_time);
m.sstable_level = _sstable_level;
m.repaired_at = _repaired_at;
convert(m.min_column_names, std::move(_min_column_names));
convert(m.max_column_names, std::move(_max_column_names));
m.has_legacy_counter_shards = _has_legacy_counter_shards;
}
};
}
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_GPU_KERNELS_COPY_HPP
#define STAN_MATH_GPU_KERNELS_COPY_HPP
#ifdef STAN_OPENCL
#include <stan/math/gpu/kernel_cl.hpp>
namespace stan {
namespace math {
namespace opencl_kernels {
// \cond
const char *copy_kernel_code = STRINGIFY(
// \endcond
/**
* Copy one matrix to another
* @param[in] A The matrix to copy.
* @param[out] B The matrix to copy A to.
* @param rows The number of rows in A.
* @param cols The number of cols in A.
* @note Code is a <code>const char*</code> held in
* <code>copy_kernel_code.</code>
* Kernel used in math/gpu/matrix_gpu.hpp.
* This kernel uses the helper macros available in helpers.cl.
*/
__kernel void copy(__global double *A, __global double *B,
unsigned int rows, unsigned int cols) {
int i = get_global_id(0);
int j = get_global_id(1);
if (i < rows && j < cols) {
B(i, j) = A(i, j);
}
}
// \cond
);
// \endcond
/**
* See the docs for \link kernels/copy.hpp copy() \endlink
*/
const global_range_kernel<cl::Buffer, cl::Buffer, int, int> copy(
"copy", copy_kernel_code);
} // namespace opencl_kernels
} // namespace math
} // namespace stan
#endif
#endif
<commit_msg>cpplint fix<commit_after>#ifndef STAN_MATH_GPU_KERNELS_COPY_HPP
#define STAN_MATH_GPU_KERNELS_COPY_HPP
#ifdef STAN_OPENCL
#include <stan/math/gpu/kernel_cl.hpp>
#include <algorithm>
namespace stan {
namespace math {
namespace opencl_kernels {
// \cond
const char *copy_kernel_code = STRINGIFY(
// \endcond
/**
* Copy one matrix to another
* @param[in] A The matrix to copy.
* @param[out] B The matrix to copy A to.
* @param rows The number of rows in A.
* @param cols The number of cols in A.
* @note Code is a <code>const char*</code> held in
* <code>copy_kernel_code.</code>
* Kernel used in math/gpu/matrix_gpu.hpp.
* This kernel uses the helper macros available in helpers.cl.
*/
__kernel void copy(__global double *A, __global double *B,
unsigned int rows, unsigned int cols) {
int i = get_global_id(0);
int j = get_global_id(1);
if (i < rows && j < cols) {
B(i, j) = A(i, j);
}
}
// \cond
);
// \endcond
/**
* See the docs for \link kernels/copy.hpp copy() \endlink
*/
const global_range_kernel<cl::Buffer, cl::Buffer, int, int> copy(
"copy", copy_kernel_code);
} // namespace opencl_kernels
} // namespace math
} // namespace stan
#endif
#endif
<|endoftext|>
|
<commit_before><commit_msg>migrate ImpNumberFill implementation to OUStringBuffer<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: connctrl.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: hr $ $Date: 2007-06-27 16:54:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// include ---------------------------------------------------------------
#include <svx/xoutx.hxx>
#include <svx/svdoedge.hxx>
#include <svx/svdattrx.hxx>
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef _SVDVIEW_HXX //autogen
#include <svx/svdview.hxx>
#endif
#include <svx/svdpage.hxx> // SdrObjList
#include "connctrl.hxx"
#include <svx/dialmgr.hxx>
#include "dlgutil.hxx"
// #110094#
#ifndef _SDR_CONTACT_OBJECTCONTACTOFOBJLISTPAINTER_HXX
#include <svx/sdr/contact/objectcontactofobjlistpainter.hxx>
#endif
// #110094#
#ifndef _SDR_CONTACT_DISPLAYINFO_HXX
#include <svx/sdr/contact/displayinfo.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
/*************************************************************************
|*
|* Ctor SvxXConnectionPreview
|*
*************************************************************************/
SvxXConnectionPreview::SvxXConnectionPreview( Window* pParent, const ResId& rResId,
const SfxItemSet& rInAttrs ) :
Control ( pParent, rResId ),
rAttrs ( rInAttrs ),
pEdgeObj( NULL ),
pObjList( NULL ),
pView ( NULL )
{
pExtOutDev = new XOutputDevice( this );
SetMapMode( MAP_100TH_MM );
SetStyles();
}
/*************************************************************************
|*
|* Dtor SvxXConnectionPreview
|*
*************************************************************************/
SvxXConnectionPreview::~SvxXConnectionPreview()
{
delete pObjList;
delete pExtOutDev;
}
/*************************************************************************
|*
|* Dtor SvxXConnectionPreview
|*
*************************************************************************/
void SvxXConnectionPreview::Construct()
{
DBG_ASSERT( pView, "Keine gueltige View Uebergeben!" );
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
ULONG nMarkCount = rMarkList.GetMarkCount();
if( nMarkCount >= 1 )
{
BOOL bFound = FALSE;
const SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
for( USHORT i = 0; i < nMarkCount && !bFound; i++ )
{
pObj = rMarkList.GetMark( i )->GetMarkedSdrObj();
UINT32 nInv = pObj->GetObjInventor();
UINT16 nId = pObj->GetObjIdentifier();
if( nInv == SdrInventor && nId == OBJ_EDGE )
{
bFound = TRUE;
SdrEdgeObj* pTmpEdgeObj = (SdrEdgeObj*) pObj;
pEdgeObj = (SdrEdgeObj*) pTmpEdgeObj->Clone();
SdrObjConnection& rConn1 = (SdrObjConnection&)pEdgeObj->GetConnection( TRUE );
SdrObjConnection& rConn2 = (SdrObjConnection&)pEdgeObj->GetConnection( FALSE );
rConn1 = pTmpEdgeObj->GetConnection( TRUE );
rConn2 = pTmpEdgeObj->GetConnection( FALSE );
SdrObject* pTmpObj1 = pTmpEdgeObj->GetConnectedNode( TRUE );
SdrObject* pTmpObj2 = pTmpEdgeObj->GetConnectedNode( FALSE );
// #110094#
// potential memory leak here (!). Create SdrObjList only when there is
// not yet one.
if(!pObjList)
{
pObjList = new SdrObjList( pView->GetModel(), NULL );
}
if( pTmpObj1 )
{
SdrObject* pObj1 = pTmpObj1->Clone();
pObjList->InsertObject( pObj1 );
pEdgeObj->ConnectToNode( TRUE, pObj1 );
}
if( pTmpObj2 )
{
SdrObject* pObj2 = pTmpObj2->Clone();
pObjList->InsertObject( pObj2 );
pEdgeObj->ConnectToNode( FALSE, pObj2 );
}
pObjList->InsertObject( pEdgeObj );
}
}
}
if( !pEdgeObj )
pEdgeObj = new SdrEdgeObj();
// Groesse anpassen
if( pObjList )
{
OutputDevice* pOD = pView->GetFirstOutputDevice(); // GetWin( 0 );
Rectangle aRect = pObjList->GetAllObjBoundRect();
MapMode aMapMode = GetMapMode();
aMapMode.SetMapUnit( pOD->GetMapMode().GetMapUnit() );
SetMapMode( aMapMode );
MapMode aDisplayMap( aMapMode );
Point aNewPos;
Size aNewSize;
const Size aWinSize = PixelToLogic( GetOutputSizePixel(), aDisplayMap );
const long nWidth = aWinSize.Width();
const long nHeight = aWinSize.Height();
double fRectWH = (double) aRect.GetWidth() / aRect.GetHeight();
double fWinWH = (double) nWidth / nHeight;
// Bitmap an Thumbgroesse anpassen (hier nicht!)
if ( fRectWH < fWinWH)
{
aNewSize.Width() = (long) ( (double) nHeight * fRectWH );
aNewSize.Height()= nHeight;
}
else
{
aNewSize.Width() = nWidth;
aNewSize.Height()= (long) ( (double) nWidth / fRectWH );
}
Fraction aFrac1( aWinSize.Width(), aRect.GetWidth() );
Fraction aFrac2( aWinSize.Height(), aRect.GetHeight() );
Fraction aMinFrac( aFrac1 <= aFrac2 ? aFrac1 : aFrac2 );
// MapMode umsetzen
aDisplayMap.SetScaleX( aMinFrac );
aDisplayMap.SetScaleY( aMinFrac );
// Zentrierung
aNewPos.X() = ( nWidth - aNewSize.Width() ) >> 1;
aNewPos.Y() = ( nHeight - aNewSize.Height() ) >> 1;
aDisplayMap.SetOrigin( LogicToLogic( aNewPos, aMapMode, aDisplayMap ) );
SetMapMode( aDisplayMap );
// Ursprung
aNewPos = aDisplayMap.GetOrigin();
aNewPos -= Point( aRect.TopLeft().X(), aRect.TopLeft().Y() );
aDisplayMap.SetOrigin( aNewPos );
SetMapMode( aDisplayMap );
Point aPos;
MouseEvent aMEvt( aPos, 1, 0, MOUSE_RIGHT );
MouseButtonDown( aMEvt );
/*
Point aPt( -aRect.TopLeft().X(), -aRect.TopLeft().Y() );
aMapMode.SetOrigin( aPt );
// Skalierung
Size aSize = GetOutputSize();
Fraction aFrac1( aSize.Width(), aRect.GetWidth() );
Fraction aFrac2( aSize.Height(), aRect.GetHeight() );
Fraction aMaxFrac( aFrac1 > aFrac2 ? aFrac1 : aFrac2 );
Fraction aMinFrac( aFrac1 <= aFrac2 ? aFrac1 : aFrac2 );
BOOL bChange = (BOOL) ( (double)aMinFrac > 1.0 );
aMapMode.SetScaleX( aMinFrac );
aMapMode.SetScaleY( aMinFrac );
// zentrieren
long nXXL = aSize.Width() > aRect.GetWidth() ? aSize.Width() : aRect.GetWidth();
long nXS = aSize.Width() <= aRect.GetWidth() ? aSize.Width() : aRect.GetWidth();
if( bChange )
{
long nTmp = nXXL; nXXL = nXS; nXS = nTmp;
}
long nX = (long) ( (double)aMinFrac * (double)nXXL );
nX = (long) ( (double)labs( nXS - nX ) / (double)aMinFrac / 2.0 );
long nYXL = aSize.Height() > aRect.GetHeight() ? aSize.Height() : aRect.GetHeight();
long nYS = aSize.Height() <= aRect.GetHeight() ? aSize.Height() : aRect.GetHeight();
if( bChange )
{
long nTmp = nXXL; nXXL = nXS; nXS = nTmp;
}
long nY = (long) ( (double)aMinFrac * (double)nYXL );
nY = (long) ( (double)labs( nYS - nY ) / (double)aMinFrac / 2.0 );
aPt += Point( nX, nY );
aMapMode.SetOrigin( aPt );
SetMapMode( aMapMode );
*/
}
}
/*************************************************************************
|*
|* SvxXConnectionPreview: Paint()
|*
*************************************************************************/
void SvxXConnectionPreview::Paint( const Rectangle& )
{
SdrPaintInfoRec aInfoRec;
//pEdgeObj->Paint( *pExtOutDev, aInfoRec );
if( pObjList )
{
// #110094#
// This will not work anymore. To not start at Adam and Eve, i will
// ATM not try to change all this stuff to really using an own model
// and a view. I will just try to provide a mechanism to paint such
// objects without own model and without a page/view with the new
// mechanism.
//
//pObjList->Paint( *pExtOutDev, aInfoRec );
// New stuff: Use a ObjectContactOfObjListPainter.
sdr::contact::SdrObjectVector aObjectVector;
for(sal_uInt32 a(0L); a < pObjList->GetObjCount(); a++)
{
SdrObject* pObject = pObjList->GetObj(a);
DBG_ASSERT(pObject,
"SvxXConnectionPreview::Paint: Corrupt ObjectList (!)");
aObjectVector.push_back(pObject);
}
sdr::contact::ObjectContactOfObjListPainter aPainter(aObjectVector);
sdr::contact::DisplayInfo aDisplayInfo;
aDisplayInfo.SetExtendedOutputDevice(pExtOutDev);
aDisplayInfo.SetPaintInfoRec(&aInfoRec);
aDisplayInfo.SetOutputDevice(pExtOutDev->GetOutDev());
// do processing
aPainter.ProcessDisplay(aDisplayInfo);
// prepare delete
aPainter.PrepareDelete();
}
}
/*************************************************************************
|*
|* SvxXConnectionPreview: SetAttributes()
|*
*************************************************************************/
void SvxXConnectionPreview::SetAttributes( const SfxItemSet& rInAttrs )
{
//pEdgeObj->SetItemSetAndBroadcast(rInAttrs);
pEdgeObj->SetMergedItemSetAndBroadcast(rInAttrs);
Invalidate();
}
/*************************************************************************
|*
|* Ermittelt die Anzahl der Linienversaetze anhand des Preview-Objektes
|*
*************************************************************************/
USHORT SvxXConnectionPreview::GetLineDeltaAnz()
{
const SfxItemSet& rSet = pEdgeObj->GetMergedItemSet();
sal_uInt16 nCount(0);
if(SFX_ITEM_DONTCARE != rSet.GetItemState(SDRATTR_EDGELINEDELTAANZ))
nCount = ((const SdrEdgeLineDeltaAnzItem&)rSet.Get(SDRATTR_EDGELINEDELTAANZ)).GetValue();
return nCount;
}
/*************************************************************************
|*
|* SvxXConnectionPreview: MouseButtonDown()
|*
*************************************************************************/
void SvxXConnectionPreview::MouseButtonDown( const MouseEvent& rMEvt )
{
BOOL bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift();
BOOL bZoomOut = rMEvt.IsRight() || rMEvt.IsShift();
BOOL bCtrl = rMEvt.IsMod1();
if( bZoomIn || bZoomOut )
{
MapMode aMapMode = GetMapMode();
Fraction aXFrac = aMapMode.GetScaleX();
Fraction aYFrac = aMapMode.GetScaleY();
Fraction* pMultFrac;
if( bZoomIn )
{
if( bCtrl )
pMultFrac = new Fraction( 3, 2 );
else
pMultFrac = new Fraction( 11, 10 );
}
else
{
if( bCtrl )
pMultFrac = new Fraction( 2, 3 );
else
pMultFrac = new Fraction( 10, 11 );
}
aXFrac *= *pMultFrac;
aYFrac *= *pMultFrac;
if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 &&
(double)aYFrac > 0.001 && (double)aYFrac < 1000.0 )
{
aMapMode.SetScaleX( aXFrac );
aMapMode.SetScaleY( aYFrac );
SetMapMode( aMapMode );
Size aOutSize( GetOutputSize() );
Point aPt( aMapMode.GetOrigin() );
long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
aPt.X() += nX;
aPt.Y() += nY;
aMapMode.SetOrigin( aPt );
SetMapMode( aMapMode );
Invalidate();
}
delete pMultFrac;
}
}
void SvxXConnectionPreview::SetStyles()
{
const StyleSettings& rStyles = Application::GetSettings().GetStyleSettings();
SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );
SetBackground( Wallpaper( Color( rStyles.GetFieldColor() ) ) );
}
void SvxXConnectionPreview::DataChanged( const DataChangedEvent& rDCEvt )
{
Control::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
SetStyles();
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.13.368); FILE MERGED 2008/04/01 15:50:14 thb 1.13.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:07 thb 1.13.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:20 rt 1.13.368.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: connctrl.cxx,v $
* $Revision: 1.14 $
*
* 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_svx.hxx"
// include ---------------------------------------------------------------
#include <svx/xoutx.hxx>
#include <svx/svdoedge.hxx>
#include <svx/svdattrx.hxx>
#include <svx/svdmark.hxx>
#include <svx/svdview.hxx>
#include <svx/svdpage.hxx> // SdrObjList
#include "connctrl.hxx"
#include <svx/dialmgr.hxx>
#include "dlgutil.hxx"
// #110094#
#include <svx/sdr/contact/objectcontactofobjlistpainter.hxx>
// #110094#
#include <svx/sdr/contact/displayinfo.hxx>
#include <vcl/svapp.hxx>
/*************************************************************************
|*
|* Ctor SvxXConnectionPreview
|*
*************************************************************************/
SvxXConnectionPreview::SvxXConnectionPreview( Window* pParent, const ResId& rResId,
const SfxItemSet& rInAttrs ) :
Control ( pParent, rResId ),
rAttrs ( rInAttrs ),
pEdgeObj( NULL ),
pObjList( NULL ),
pView ( NULL )
{
pExtOutDev = new XOutputDevice( this );
SetMapMode( MAP_100TH_MM );
SetStyles();
}
/*************************************************************************
|*
|* Dtor SvxXConnectionPreview
|*
*************************************************************************/
SvxXConnectionPreview::~SvxXConnectionPreview()
{
delete pObjList;
delete pExtOutDev;
}
/*************************************************************************
|*
|* Dtor SvxXConnectionPreview
|*
*************************************************************************/
void SvxXConnectionPreview::Construct()
{
DBG_ASSERT( pView, "Keine gueltige View Uebergeben!" );
const SdrMarkList& rMarkList = pView->GetMarkedObjectList();
ULONG nMarkCount = rMarkList.GetMarkCount();
if( nMarkCount >= 1 )
{
BOOL bFound = FALSE;
const SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj();
for( USHORT i = 0; i < nMarkCount && !bFound; i++ )
{
pObj = rMarkList.GetMark( i )->GetMarkedSdrObj();
UINT32 nInv = pObj->GetObjInventor();
UINT16 nId = pObj->GetObjIdentifier();
if( nInv == SdrInventor && nId == OBJ_EDGE )
{
bFound = TRUE;
SdrEdgeObj* pTmpEdgeObj = (SdrEdgeObj*) pObj;
pEdgeObj = (SdrEdgeObj*) pTmpEdgeObj->Clone();
SdrObjConnection& rConn1 = (SdrObjConnection&)pEdgeObj->GetConnection( TRUE );
SdrObjConnection& rConn2 = (SdrObjConnection&)pEdgeObj->GetConnection( FALSE );
rConn1 = pTmpEdgeObj->GetConnection( TRUE );
rConn2 = pTmpEdgeObj->GetConnection( FALSE );
SdrObject* pTmpObj1 = pTmpEdgeObj->GetConnectedNode( TRUE );
SdrObject* pTmpObj2 = pTmpEdgeObj->GetConnectedNode( FALSE );
// #110094#
// potential memory leak here (!). Create SdrObjList only when there is
// not yet one.
if(!pObjList)
{
pObjList = new SdrObjList( pView->GetModel(), NULL );
}
if( pTmpObj1 )
{
SdrObject* pObj1 = pTmpObj1->Clone();
pObjList->InsertObject( pObj1 );
pEdgeObj->ConnectToNode( TRUE, pObj1 );
}
if( pTmpObj2 )
{
SdrObject* pObj2 = pTmpObj2->Clone();
pObjList->InsertObject( pObj2 );
pEdgeObj->ConnectToNode( FALSE, pObj2 );
}
pObjList->InsertObject( pEdgeObj );
}
}
}
if( !pEdgeObj )
pEdgeObj = new SdrEdgeObj();
// Groesse anpassen
if( pObjList )
{
OutputDevice* pOD = pView->GetFirstOutputDevice(); // GetWin( 0 );
Rectangle aRect = pObjList->GetAllObjBoundRect();
MapMode aMapMode = GetMapMode();
aMapMode.SetMapUnit( pOD->GetMapMode().GetMapUnit() );
SetMapMode( aMapMode );
MapMode aDisplayMap( aMapMode );
Point aNewPos;
Size aNewSize;
const Size aWinSize = PixelToLogic( GetOutputSizePixel(), aDisplayMap );
const long nWidth = aWinSize.Width();
const long nHeight = aWinSize.Height();
double fRectWH = (double) aRect.GetWidth() / aRect.GetHeight();
double fWinWH = (double) nWidth / nHeight;
// Bitmap an Thumbgroesse anpassen (hier nicht!)
if ( fRectWH < fWinWH)
{
aNewSize.Width() = (long) ( (double) nHeight * fRectWH );
aNewSize.Height()= nHeight;
}
else
{
aNewSize.Width() = nWidth;
aNewSize.Height()= (long) ( (double) nWidth / fRectWH );
}
Fraction aFrac1( aWinSize.Width(), aRect.GetWidth() );
Fraction aFrac2( aWinSize.Height(), aRect.GetHeight() );
Fraction aMinFrac( aFrac1 <= aFrac2 ? aFrac1 : aFrac2 );
// MapMode umsetzen
aDisplayMap.SetScaleX( aMinFrac );
aDisplayMap.SetScaleY( aMinFrac );
// Zentrierung
aNewPos.X() = ( nWidth - aNewSize.Width() ) >> 1;
aNewPos.Y() = ( nHeight - aNewSize.Height() ) >> 1;
aDisplayMap.SetOrigin( LogicToLogic( aNewPos, aMapMode, aDisplayMap ) );
SetMapMode( aDisplayMap );
// Ursprung
aNewPos = aDisplayMap.GetOrigin();
aNewPos -= Point( aRect.TopLeft().X(), aRect.TopLeft().Y() );
aDisplayMap.SetOrigin( aNewPos );
SetMapMode( aDisplayMap );
Point aPos;
MouseEvent aMEvt( aPos, 1, 0, MOUSE_RIGHT );
MouseButtonDown( aMEvt );
/*
Point aPt( -aRect.TopLeft().X(), -aRect.TopLeft().Y() );
aMapMode.SetOrigin( aPt );
// Skalierung
Size aSize = GetOutputSize();
Fraction aFrac1( aSize.Width(), aRect.GetWidth() );
Fraction aFrac2( aSize.Height(), aRect.GetHeight() );
Fraction aMaxFrac( aFrac1 > aFrac2 ? aFrac1 : aFrac2 );
Fraction aMinFrac( aFrac1 <= aFrac2 ? aFrac1 : aFrac2 );
BOOL bChange = (BOOL) ( (double)aMinFrac > 1.0 );
aMapMode.SetScaleX( aMinFrac );
aMapMode.SetScaleY( aMinFrac );
// zentrieren
long nXXL = aSize.Width() > aRect.GetWidth() ? aSize.Width() : aRect.GetWidth();
long nXS = aSize.Width() <= aRect.GetWidth() ? aSize.Width() : aRect.GetWidth();
if( bChange )
{
long nTmp = nXXL; nXXL = nXS; nXS = nTmp;
}
long nX = (long) ( (double)aMinFrac * (double)nXXL );
nX = (long) ( (double)labs( nXS - nX ) / (double)aMinFrac / 2.0 );
long nYXL = aSize.Height() > aRect.GetHeight() ? aSize.Height() : aRect.GetHeight();
long nYS = aSize.Height() <= aRect.GetHeight() ? aSize.Height() : aRect.GetHeight();
if( bChange )
{
long nTmp = nXXL; nXXL = nXS; nXS = nTmp;
}
long nY = (long) ( (double)aMinFrac * (double)nYXL );
nY = (long) ( (double)labs( nYS - nY ) / (double)aMinFrac / 2.0 );
aPt += Point( nX, nY );
aMapMode.SetOrigin( aPt );
SetMapMode( aMapMode );
*/
}
}
/*************************************************************************
|*
|* SvxXConnectionPreview: Paint()
|*
*************************************************************************/
void SvxXConnectionPreview::Paint( const Rectangle& )
{
SdrPaintInfoRec aInfoRec;
//pEdgeObj->Paint( *pExtOutDev, aInfoRec );
if( pObjList )
{
// #110094#
// This will not work anymore. To not start at Adam and Eve, i will
// ATM not try to change all this stuff to really using an own model
// and a view. I will just try to provide a mechanism to paint such
// objects without own model and without a page/view with the new
// mechanism.
//
//pObjList->Paint( *pExtOutDev, aInfoRec );
// New stuff: Use a ObjectContactOfObjListPainter.
sdr::contact::SdrObjectVector aObjectVector;
for(sal_uInt32 a(0L); a < pObjList->GetObjCount(); a++)
{
SdrObject* pObject = pObjList->GetObj(a);
DBG_ASSERT(pObject,
"SvxXConnectionPreview::Paint: Corrupt ObjectList (!)");
aObjectVector.push_back(pObject);
}
sdr::contact::ObjectContactOfObjListPainter aPainter(aObjectVector);
sdr::contact::DisplayInfo aDisplayInfo;
aDisplayInfo.SetExtendedOutputDevice(pExtOutDev);
aDisplayInfo.SetPaintInfoRec(&aInfoRec);
aDisplayInfo.SetOutputDevice(pExtOutDev->GetOutDev());
// do processing
aPainter.ProcessDisplay(aDisplayInfo);
// prepare delete
aPainter.PrepareDelete();
}
}
/*************************************************************************
|*
|* SvxXConnectionPreview: SetAttributes()
|*
*************************************************************************/
void SvxXConnectionPreview::SetAttributes( const SfxItemSet& rInAttrs )
{
//pEdgeObj->SetItemSetAndBroadcast(rInAttrs);
pEdgeObj->SetMergedItemSetAndBroadcast(rInAttrs);
Invalidate();
}
/*************************************************************************
|*
|* Ermittelt die Anzahl der Linienversaetze anhand des Preview-Objektes
|*
*************************************************************************/
USHORT SvxXConnectionPreview::GetLineDeltaAnz()
{
const SfxItemSet& rSet = pEdgeObj->GetMergedItemSet();
sal_uInt16 nCount(0);
if(SFX_ITEM_DONTCARE != rSet.GetItemState(SDRATTR_EDGELINEDELTAANZ))
nCount = ((const SdrEdgeLineDeltaAnzItem&)rSet.Get(SDRATTR_EDGELINEDELTAANZ)).GetValue();
return nCount;
}
/*************************************************************************
|*
|* SvxXConnectionPreview: MouseButtonDown()
|*
*************************************************************************/
void SvxXConnectionPreview::MouseButtonDown( const MouseEvent& rMEvt )
{
BOOL bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift();
BOOL bZoomOut = rMEvt.IsRight() || rMEvt.IsShift();
BOOL bCtrl = rMEvt.IsMod1();
if( bZoomIn || bZoomOut )
{
MapMode aMapMode = GetMapMode();
Fraction aXFrac = aMapMode.GetScaleX();
Fraction aYFrac = aMapMode.GetScaleY();
Fraction* pMultFrac;
if( bZoomIn )
{
if( bCtrl )
pMultFrac = new Fraction( 3, 2 );
else
pMultFrac = new Fraction( 11, 10 );
}
else
{
if( bCtrl )
pMultFrac = new Fraction( 2, 3 );
else
pMultFrac = new Fraction( 10, 11 );
}
aXFrac *= *pMultFrac;
aYFrac *= *pMultFrac;
if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 &&
(double)aYFrac > 0.001 && (double)aYFrac < 1000.0 )
{
aMapMode.SetScaleX( aXFrac );
aMapMode.SetScaleY( aYFrac );
SetMapMode( aMapMode );
Size aOutSize( GetOutputSize() );
Point aPt( aMapMode.GetOrigin() );
long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
aPt.X() += nX;
aPt.Y() += nY;
aMapMode.SetOrigin( aPt );
SetMapMode( aMapMode );
Invalidate();
}
delete pMultFrac;
}
}
void SvxXConnectionPreview::SetStyles()
{
const StyleSettings& rStyles = Application::GetSettings().GetStyleSettings();
SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );
SetBackground( Wallpaper( Color( rStyles.GetFieldColor() ) ) );
}
void SvxXConnectionPreview::DataChanged( const DataChangedEvent& rDCEvt )
{
Control::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
SetStyles();
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: eventdlg.cxx,v $
*
* $Revision: 1.14 $
*
* last change: $Author: hr $ $Date: 2007-06-27 17:04: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_svx.hxx"
// include ***************************************************************
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif
#include <comphelper/processfactory.hxx>
#ifndef _UNOTOOLS_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#include <rtl/ustring.hxx>
#include "eventdlg.hxx"
#include <sfx2/viewfrm.hxx>
#include <sfx2/evntconf.hxx>
#include <sfx2/macrconf.hxx>
#include <sfx2/minfitem.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfac.hxx>
#include <sfx2/fcontnr.hxx>
#include <svtools/eventcfg.hxx>
#ifndef _HEADERTABLISTBOX_HXX
#include "headertablistbox.hxx"
#endif
#ifndef _MACROPG_IMPL_HXX
#include "macropg_impl.hxx"
#endif
#include <svx/dialmgr.hxx>
#include <svx/dialogs.hrc>
#include "eventdlg.hrc"
#include "helpid.hrc"
#include "selector.hxx"
#include "cfg.hxx"
using ::rtl::OUString;
using namespace ::com::sun::star;
// -----------------------------------------------------------------------
SvxEventConfigPage::SvxEventConfigPage( Window* pParent, const SfxItemSet& rSet ) :
_SvxMacroTabPage( pParent, SVX_RES(RID_SVXPAGE_EVENTS), rSet ),
aSaveInText( this, SVX_RES( TXT_SAVEIN ) ),
aSaveInListBox( this, SVX_RES( LB_SAVEIN ) ),
bAppConfig ( TRUE )
{
mpImpl->pStrEvent = new String( SVX_RES( STR_EVENT ));
mpImpl->pAssignedMacro = new String( SVX_RES( STR_ASSMACRO ));
mpImpl->pEventLB = new _HeaderTabListBox( this, SVX_RES( LB_EVENT ));
mpImpl->pAssignFT = new FixedText( this, SVX_RES( FT_ASSIGN ));
mpImpl->pAssignPB = new PushButton( this, SVX_RES( PB_ASSIGN ));
mpImpl->pDeletePB = new PushButton( this, SVX_RES( PB_DELETE ));
mpImpl->pMacroImg = new Image( SVX_RES( IMG_MACRO) );
mpImpl->pComponentImg = new Image( SVX_RES( IMG_COMPONENT) );
mpImpl->pMacroImg_h = new Image( SVX_RES( IMG_MACRO_H) );
mpImpl->pComponentImg_h = new Image( SVX_RES( IMG_COMPONENT_H) );
FreeResource();
// must be done after FreeResource is called
InitResources();
mpImpl->pEventLB->GetListBox().SetHelpId( HID_SVX_MACRO_LB_EVENT );
aSaveInListBox.SetSelectHdl( LINK( this, SvxEventConfigPage,
SelectHdl_Impl ) );
uno::Reference< document::XEventsSupplier > xSupplier;
// xSupplier = uno::Reference< document::XEventsSupplier >( new GlobalEventConfig());
xSupplier = uno::Reference< document::XEventsSupplier > (
::comphelper::getProcessServiceFactory()->createInstance(
OUString::createFromAscii(
"com.sun.star.frame.GlobalEventBroadcaster" ) ),
uno::UNO_QUERY );
uno::Reference< container::XNameReplace > xEvents_app, xEvents_doc;
USHORT nPos;
if ( xSupplier.is() )
{
xEvents_app = xSupplier->getEvents();
OUString label;
utl::ConfigManager::GetDirectConfigProperty(
utl::ConfigManager::PRODUCTNAME ) >>= label;
nPos = aSaveInListBox.InsertEntry( label );
aSaveInListBox.SetEntryData( nPos, new bool(true) );
aSaveInListBox.SelectEntryPos( nPos, TRUE );
}
uno::Reference< frame::XFramesSupplier > xFramesSupplier(
::comphelper::getProcessServiceFactory()->createInstance(
OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ),
uno::UNO_QUERY );
uno::Reference< frame::XModel > xModel;
uno::Reference< frame::XFrame > xFrame =
xFramesSupplier->getActiveFrame();
if ( xFrame.is() )
{
// first establish if this type of application module
// supports document configuration
uno::Reference< ::com::sun::star::frame::XModuleManager >
xModuleManager(
::comphelper::getProcessServiceFactory()->createInstance(
OUString( RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.frame.ModuleManager" ) ) ),
uno::UNO_QUERY );
OUString aModuleId;
try{
aModuleId = xModuleManager->identify( xFrame );
} catch(const uno::Exception&)
{ aModuleId = ::rtl::OUString(); }
if ( SvxConfigPage::CanConfig( aModuleId ) )
{
uno::Reference< frame::XController > xController =
xFrame->getController();
if ( xController.is() )
{
xModel = xController->getModel();
}
}
}
uno::Reference< util::XModifiable > xModifiable_doc;
if ( xModel.is() )
{
xSupplier = uno::Reference< document::XEventsSupplier >(
xModel, uno::UNO_QUERY );
if ( xSupplier.is() )
{
xEvents_doc = xSupplier->getEvents();
xModifiable_doc =
uno::Reference< util::XModifiable >( xModel, uno::UNO_QUERY );
OUString aTitle;
SvxScriptSelectorDialog::GetDocTitle( xModel, aTitle );
nPos = aSaveInListBox.InsertEntry( aTitle );
aSaveInListBox.SetEntryData( nPos, new bool(false) );
aSaveInListBox.SelectEntryPos( nPos, TRUE );
bAppConfig = false;
}
}
InitAndSetHandler( xEvents_app, xEvents_doc, xModifiable_doc );
SelectHdl_Impl( NULL );
}
// -----------------------------------------------------------------------
SvxEventConfigPage::~SvxEventConfigPage()
{
//DF Do I need to delete bools?
}
// -----------------------------------------------------------------------
IMPL_LINK( SvxEventConfigPage, SelectHdl_Impl, ListBox *, pBox )
{
(void)pBox;
bool* bApp = (bool*) aSaveInListBox.GetEntryData(
aSaveInListBox.GetSelectEntryPos());
mpImpl->pEventLB->SetUpdateMode( FALSE );
bAppConfig = *bApp;
if ( *bApp )
{
SetReadOnly( FALSE );
_SvxMacroTabPage::DisplayAppEvents( true );
}
else
{
bool isReadonly = FALSE;
uno::Reference< frame::XFramesSupplier > xFramesSupplier(
::comphelper::getProcessServiceFactory()->createInstance(
OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ),
uno::UNO_QUERY );
uno::Reference< frame::XFrame > xFrame =
xFramesSupplier->getActiveFrame();
if ( xFrame.is() )
{
uno::Reference< frame::XController > xController =
xFrame->getController();
if ( xController.is() )
{
uno::Reference< frame::XStorable > xStorable(
xController->getModel(), uno::UNO_QUERY );
isReadonly = xStorable->isReadonly();
}
}
SetReadOnly( isReadonly );
_SvxMacroTabPage::DisplayAppEvents( false );
}
mpImpl->pEventLB->SetUpdateMode( TRUE );
return TRUE;
}
// -----------------------------------------------------------------------
BOOL SvxEventConfigPage::FillItemSet( SfxItemSet& rSet )
{
return _SvxMacroTabPage::FillItemSet( rSet );
}
// -----------------------------------------------------------------------
void SvxEventConfigPage::Reset( const SfxItemSet& )
{
_SvxMacroTabPage::Reset();
}
<commit_msg>INTEGRATION: CWS basmgr03 (1.14.68); FILE MERGED 2007/08/24 05:20:37 fs 1.14.68.2: moved documentinfo to comphelper 2007/08/01 09:01:42 fs 1.14.68.1: in preparation of #i76129#: +LateInit taking a frame<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: eventdlg.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: kz $ $Date: 2007-10-09 15:17:38 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// include ***************************************************************
#ifndef _SVEDIT_HXX //autogen
#include <svtools/svmedit.hxx>
#endif
#ifndef TOOLS_DIAGNOSE_EX_H
#include <tools/diagnose_ex.h>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XEVENTSSUPPLIER_HPP_
#include <com/sun/star/document/XEventsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_
#include <com/sun/star/frame/XModuleManager.hpp>
#endif
#include <comphelper/processfactory.hxx>
#include <comphelper/documentinfo.hxx>
#include <unotools/configmgr.hxx>
#include <rtl/ustring.hxx>
#include "eventdlg.hxx"
#include <sfx2/viewfrm.hxx>
#include <sfx2/evntconf.hxx>
#include <sfx2/macrconf.hxx>
#include <sfx2/minfitem.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#include <sfx2/docfac.hxx>
#include <sfx2/fcontnr.hxx>
#include <svtools/eventcfg.hxx>
#ifndef _HEADERTABLISTBOX_HXX
#include "headertablistbox.hxx"
#endif
#ifndef _MACROPG_IMPL_HXX
#include "macropg_impl.hxx"
#endif
#include <svx/dialmgr.hxx>
#include <svx/dialogs.hrc>
#include "eventdlg.hrc"
#include "helpid.hrc"
#include "selector.hxx"
#include "cfg.hxx"
using ::rtl::OUString;
using namespace ::com::sun::star;
// -----------------------------------------------------------------------
SvxEventConfigPage::SvxEventConfigPage( Window *pParent, const SfxItemSet& rSet, SvxEventConfigPage::EarlyInit ) :
_SvxMacroTabPage( pParent, SVX_RES(RID_SVXPAGE_EVENTS), rSet ),
aSaveInText( this, SVX_RES( TXT_SAVEIN ) ),
aSaveInListBox( this, SVX_RES( LB_SAVEIN ) ),
bAppConfig ( TRUE )
{
mpImpl->pStrEvent = new String( SVX_RES( STR_EVENT ));
mpImpl->pAssignedMacro = new String( SVX_RES( STR_ASSMACRO ));
mpImpl->pEventLB = new _HeaderTabListBox( this, SVX_RES( LB_EVENT ));
mpImpl->pAssignFT = new FixedText( this, SVX_RES( FT_ASSIGN ));
mpImpl->pAssignPB = new PushButton( this, SVX_RES( PB_ASSIGN ));
mpImpl->pDeletePB = new PushButton( this, SVX_RES( PB_DELETE ));
mpImpl->pMacroImg = new Image( SVX_RES( IMG_MACRO) );
mpImpl->pComponentImg = new Image( SVX_RES( IMG_COMPONENT) );
mpImpl->pMacroImg_h = new Image( SVX_RES( IMG_MACRO_H) );
mpImpl->pComponentImg_h = new Image( SVX_RES( IMG_COMPONENT_H) );
FreeResource();
// must be done after FreeResource is called
InitResources();
mpImpl->pEventLB->GetListBox().SetHelpId( HID_SVX_MACRO_LB_EVENT );
aSaveInListBox.SetSelectHdl( LINK( this, SvxEventConfigPage,
SelectHdl_Impl ) );
uno::Reference< document::XEventsSupplier > xSupplier;
// xSupplier = uno::Reference< document::XEventsSupplier >( new GlobalEventConfig());
xSupplier = uno::Reference< document::XEventsSupplier > (
::comphelper::getProcessServiceFactory()->createInstance(
OUString::createFromAscii(
"com.sun.star.frame.GlobalEventBroadcaster" ) ),
uno::UNO_QUERY );
USHORT nPos(0);
if ( xSupplier.is() )
{
m_xAppEvents = xSupplier->getEvents();
OUString label;
utl::ConfigManager::GetDirectConfigProperty(
utl::ConfigManager::PRODUCTNAME ) >>= label;
nPos = aSaveInListBox.InsertEntry( label );
aSaveInListBox.SetEntryData( nPos, new bool(true) );
aSaveInListBox.SelectEntryPos( nPos, TRUE );
}
}
// -----------------------------------------------------------------------
void SvxEventConfigPage::LateInit( const uno::Reference< frame::XFrame >& _rxFrame )
{
SetFrame( _rxFrame );
ImplInitDocument();
InitAndSetHandler( m_xAppEvents, m_xDocumentEvents, m_xDocumentModifiable );
SelectHdl_Impl( NULL );
}
// -----------------------------------------------------------------------
SvxEventConfigPage::~SvxEventConfigPage()
{
//DF Do I need to delete bools?
}
// -----------------------------------------------------------------------
void SvxEventConfigPage::ImplInitDocument()
{
uno::Reference< frame::XFrame > xFrame( GetFrame() );
OUString aModuleId = SvxConfigPage::GetFrameWithDefaultAndIdentify( xFrame );
if ( !xFrame.is() )
return;
try
{
uno::Reference< frame::XModel > xModel;
if ( !SvxConfigPage::CanConfig( aModuleId ) )
return;
uno::Reference< frame::XController > xController =
xFrame->getController();
if ( xController.is() )
{
xModel = xController->getModel();
}
if ( !xModel.is() )
return;
uno::Reference< document::XEventsSupplier > xSupplier( xModel, uno::UNO_QUERY );
if ( xSupplier.is() )
{
m_xDocumentEvents = xSupplier->getEvents();
m_xDocumentModifiable = m_xDocumentModifiable.query( xModel );
OUString aTitle = ::comphelper::DocumentInfo::getDocumentTitle( xModel );
USHORT nPos = aSaveInListBox.InsertEntry( aTitle );
aSaveInListBox.SetEntryData( nPos, new bool(false) );
aSaveInListBox.SelectEntryPos( nPos, TRUE );
bAppConfig = false;
}
}
catch( const uno::Exception& )
{
DBG_UNHANDLED_EXCEPTION();
}
}
// -----------------------------------------------------------------------
IMPL_LINK( SvxEventConfigPage, SelectHdl_Impl, ListBox *, pBox )
{
(void)pBox;
bool* bApp = (bool*) aSaveInListBox.GetEntryData(
aSaveInListBox.GetSelectEntryPos());
mpImpl->pEventLB->SetUpdateMode( FALSE );
bAppConfig = *bApp;
if ( *bApp )
{
SetReadOnly( FALSE );
_SvxMacroTabPage::DisplayAppEvents( true );
}
else
{
bool isReadonly = FALSE;
uno::Reference< frame::XFramesSupplier > xFramesSupplier(
::comphelper::getProcessServiceFactory()->createInstance(
OUString::createFromAscii( "com.sun.star.frame.Desktop" ) ),
uno::UNO_QUERY );
uno::Reference< frame::XFrame > xFrame =
xFramesSupplier->getActiveFrame();
if ( xFrame.is() )
{
uno::Reference< frame::XController > xController =
xFrame->getController();
if ( xController.is() )
{
uno::Reference< frame::XStorable > xStorable(
xController->getModel(), uno::UNO_QUERY );
isReadonly = xStorable->isReadonly();
}
}
SetReadOnly( isReadonly );
_SvxMacroTabPage::DisplayAppEvents( false );
}
mpImpl->pEventLB->SetUpdateMode( TRUE );
return TRUE;
}
// -----------------------------------------------------------------------
BOOL SvxEventConfigPage::FillItemSet( SfxItemSet& rSet )
{
return _SvxMacroTabPage::FillItemSet( rSet );
}
// -----------------------------------------------------------------------
void SvxEventConfigPage::Reset( const SfxItemSet& )
{
_SvxMacroTabPage::Reset();
}
<|endoftext|>
|
<commit_before><commit_msg>tdf#92725 FormattedField: when model value is NULL, force empty display string<commit_after><|endoftext|>
|
<commit_before><commit_msg>fdo#76878 Revert "Resolves: #i116244# need to reset rotation..."<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <hintids.hxx>
#include <com/sun/star/i18n/ScriptType.hdl>
#include <fmtcntnt.hxx>
#include <txatbase.hxx>
#include <frmatr.hxx>
#include <viscrs.hxx>
#include <callnk.hxx>
#include <crsrsh.hxx>
#include <doc.hxx>
#include <frmfmt.hxx>
#include <txtfrm.hxx>
#include <tabfrm.hxx>
#include <rowfrm.hxx>
#include <fmtfsize.hxx>
#include <ndtxt.hxx>
#include <flyfrm.hxx>
#include <breakit.hxx>
#include<vcl/window.hxx>
SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos, bool bAktSelection )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ),
bHasSelection( bAktSelection )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// SPoint-Werte vom aktuellen Cursor merken
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
bHasSelection = ( *pCrsr->GetPoint() != *pCrsr->GetMark() );
if( ND_TEXTNODE & nNdTyp )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// eine Sonderbehandlung fuer die SwFeShell: diese setzt beim Loeschen
// der Kopf-/Fusszeile, Fussnoten den Cursor auf NULL (Node + Content)
// steht der Cursor auf keinem CntntNode, wird sich das im NdType
// gespeichert.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.bCallChgLnk ) // siehe ctor
return ;
// wird ueber Nodes getravellt, Formate ueberpruefen und im neuen
// Node wieder anmelden
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
bool bUpdatedTable = false;
SwFrm *myFrm=pCNd->GetFrm();
if (myFrm!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm->FindRowFrm( );
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
bUpdatedTable = true;
}
}
const SwDoc *pDoc=rShell.GetDoc();
const SwCntntNode *pNode = NULL;
if ( ( pDoc != NULL && nNode < pDoc->GetNodes( ).Count( ) ) )
{
pNode = pDoc->GetNodes()[nNode]->GetCntntNode();
}
if ( pNode != NULL )
{
SwFrm *myFrm2=pNode->GetFrm();
if (myFrm2!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm2->FindRowFrm();
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
bUpdatedTable = true;
}
}
}
if ( bUpdatedTable )
rShell.GetWin( )->Invalidate( 0 );
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
USHORT nNdWhich = pCNd->GetNodeType();
ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// melde die Shell beim akt. Node als abhaengig an, dadurch koennen
// alle Attribut-Aenderungen ueber den Link weiter gemeldet werden.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
/* immer, wenn zwischen Nodes gesprungen wird, kann es
* vorkommen, das neue Attribute gelten; die Text-Attribute.
* Es muesste also festgestellt werden, welche Attribute
* jetzt gelten; das kann auch gleich der Handler machen
*/
rShell.CallChgLnk();
}
else if( !bHasSelection != !(*pCurCrsr->GetPoint() != *pCurCrsr->GetMark()) )
{
// always call change link when selection changes
rShell.CallChgLnk();
}
else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// nur wenn mit Left/right getravellt, dann Text-Hints pruefen
// und sich nicht der Frame geaendert hat (Spalten!)
if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & Sele
++nCmp;
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
USHORT n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// nur Start oder Start und Ende gleich, dann immer
// beim Ueberlaufen von Start callen
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// hat das Attribut einen Bereich und dieser nicht leer
else if( pEnd && nStart < *pEnd &&
// dann teste, ob ueber Start/Ende getravellt wurde
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
if( pBreakIt->GetBreakIter().is() )
{
const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt();
if( !nCmp ||
pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp )
!= pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp - 1 ))
{
rShell.CallChgLnk();
return;
}
}
}
else
/* wenn mit Home/End/.. mehr als 1 Zeichen getravellt, dann
* immer den ChgLnk rufen, denn es kann hier nicht
* festgestellt werden, was sich geaendert; etwas kann
* veraendert sein.
*/
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
ASSERT( pIndex, "Fly ohne Cntnt" );
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
<commit_msg>#i114198# NULL pIndex in SwCallLink::~SwCallLink<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <hintids.hxx>
#include <com/sun/star/i18n/ScriptType.hdl>
#include <fmtcntnt.hxx>
#include <txatbase.hxx>
#include <frmatr.hxx>
#include <viscrs.hxx>
#include <callnk.hxx>
#include <crsrsh.hxx>
#include <doc.hxx>
#include <frmfmt.hxx>
#include <txtfrm.hxx>
#include <tabfrm.hxx>
#include <rowfrm.hxx>
#include <fmtfsize.hxx>
#include <ndtxt.hxx>
#include <flyfrm.hxx>
#include <breakit.hxx>
#include<vcl/window.hxx>
SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos, bool bAktSelection )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ),
bHasSelection( bAktSelection )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// SPoint-Werte vom aktuellen Cursor merken
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
bHasSelection = ( *pCrsr->GetPoint() != *pCrsr->GetMark() );
if( ND_TEXTNODE & nNdTyp )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// eine Sonderbehandlung fuer die SwFeShell: diese setzt beim Loeschen
// der Kopf-/Fusszeile, Fussnoten den Cursor auf NULL (Node + Content)
// steht der Cursor auf keinem CntntNode, wird sich das im NdType
// gespeichert.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.bCallChgLnk ) // siehe ctor
return ;
// wird ueber Nodes getravellt, Formate ueberpruefen und im neuen
// Node wieder anmelden
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
bool bUpdatedTable = false;
SwFrm *myFrm=pCNd->GetFrm();
if (myFrm!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm->FindRowFrm( );
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
bUpdatedTable = true;
}
}
const SwDoc *pDoc=rShell.GetDoc();
const SwCntntNode *pNode = NULL;
if ( ( pDoc != NULL && nNode < pDoc->GetNodes( ).Count( ) ) )
{
pNode = pDoc->GetNodes()[nNode]->GetCntntNode();
}
if ( pNode != NULL )
{
SwFrm *myFrm2=pNode->GetFrm();
if (myFrm2!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm2->FindRowFrm();
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
SwFmtFrmSize pSize = pLine->GetFrmFmt( )->GetFrmSize( );
pRow->Modify( NULL, &pSize );
bUpdatedTable = true;
}
}
}
if ( bUpdatedTable )
rShell.GetWin( )->Invalidate( 0 );
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
USHORT nNdWhich = pCNd->GetNodeType();
ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// melde die Shell beim akt. Node als abhaengig an, dadurch koennen
// alle Attribut-Aenderungen ueber den Link weiter gemeldet werden.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
/* immer, wenn zwischen Nodes gesprungen wird, kann es
* vorkommen, das neue Attribute gelten; die Text-Attribute.
* Es muesste also festgestellt werden, welche Attribute
* jetzt gelten; das kann auch gleich der Handler machen
*/
rShell.CallChgLnk();
}
else if( !bHasSelection != !(*pCurCrsr->GetPoint() != *pCurCrsr->GetMark()) )
{
// always call change link when selection changes
rShell.CallChgLnk();
}
else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// nur wenn mit Left/right getravellt, dann Text-Hints pruefen
// und sich nicht der Frame geaendert hat (Spalten!)
if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & Sele
++nCmp;
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
USHORT n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// nur Start oder Start und Ende gleich, dann immer
// beim Ueberlaufen von Start callen
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// hat das Attribut einen Bereich und dieser nicht leer
else if( pEnd && nStart < *pEnd &&
// dann teste, ob ueber Start/Ende getravellt wurde
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
if( pBreakIt->GetBreakIter().is() )
{
const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt();
if( !nCmp ||
pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp )
!= pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp - 1 ))
{
rShell.CallChgLnk();
return;
}
}
}
else
/* wenn mit Home/End/.. mehr als 1 Zeichen getravellt, dann
* immer den ChgLnk rufen, denn es kann hier nicht
* festgestellt werden, was sich geaendert; etwas kann
* veraendert sein.
*/
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
ASSERT( pIndex, "Fly ohne Cntnt" );
if (!pIndex)
return;
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>sw: check 0 paint window in RenderContextGuard<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: prtopt.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 17:14:33 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
Beschreibung: Ctor
--------------------------------------------------------------------*/
Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Content/Graphic", // 0
"Content/Table", // 1
"Content/Drawing", // 2
"Content/Control", // 3
"Content/Background", // 4
"Content/PrintBlack", // 5
"Content/Note", // 6
"Page/LeftPage", // 7
"Page/RightPage", // 8
"Page/Reversed", // 9
"Page/Brochure", // 10
"Output/SinglePrintJob", // 11
"Output/Fax", // 12
"Papertray/FromPrinterSetup"// 13
};
const int nCount = 14;
Sequence<OUString> aNames(nCount);
OUString* pNames = aNames.getArray();
for(int i = 0; i < nCount; i++)
{
pNames[i] = OUString::createFromAscii(aPropNames[i]);
}
return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") : C2U("Office.Writer/Print")),
bPrintGraphic(sal_True),
bPrintTable(sal_True),
bPrintDraw(sal_True),
bPrintControl(sal_True),
bPrintLeftPage(sal_True),
bPrintRightPage(sal_True),
bReverse(sal_False),
bPaperFromSetup(sal_False),
bPrintProspect(sal_False),
bPrintSingleJobs(sal_False),
bPrintPageBackground(!bWeb),
bPrintBlackFont(bWeb),
nPrintPostIts(POSTITS_NONE)
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
EnableNotification(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
DBG_ASSERT(pValues[nProp].hasValue(), "property value missing")
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case 0: bPrintGraphic = *(sal_Bool*)pValues[nProp].getValue(); break;
case 1: bPrintTable = *(sal_Bool*)pValues[nProp].getValue(); break;
case 2: bPrintDraw = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 3: bPrintControl = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 4: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue(); break;
case 5: bPrintBlackFont = *(sal_Bool*)pValues[nProp].getValue(); break;
case 6: pValues[nProp] >>= nPrintPostIts ; break;
case 7: bPrintLeftPage = *(sal_Bool*)pValues[nProp].getValue(); break;
case 8: bPrintRightPage = *(sal_Bool*)pValues[nProp].getValue(); break;
case 9: bReverse = *(sal_Bool*)pValues[nProp].getValue(); break;
case 10:bPrintProspect = *(sal_Bool*)pValues[nProp].getValue(); break;
case 11:bPrintSingleJobs = *(sal_Bool*)pValues[nProp].getValue(); break;
case 12: pValues[nProp] >>= sFaxName; break;
case 13: bPaperFromSetup = *(sal_Bool*)pValues[nProp].getValue(); break;
}
}
}
}
}
/* -----------------------------06.09.00 16:50--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------
---------------------------------------------------------------------------*/
void SwPrintOptions::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
BOOL bVal;
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
switch(nProp)
{
case 0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
case 1: bVal = bPrintTable ;pValues[nProp].setValue(&bVal, rType); break;
case 2: bVal = bPrintDraw ; pValues[nProp].setValue(&bVal, rType); break;
case 3: bVal = bPrintControl ; pValues[nProp].setValue(&bVal, rType); break;
case 4: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType); break;
case 5: bVal = bPrintBlackFont ; pValues[nProp].setValue(&bVal, rType); break;
case 6: pValues[nProp] <<= nPrintPostIts ; break;
case 7: bVal = bPrintLeftPage ; pValues[nProp].setValue(&bVal, rType); break;
case 8: bVal = bPrintRightPage ; pValues[nProp].setValue(&bVal, rType); break;
case 9: bVal = bReverse ; pValues[nProp].setValue(&bVal, rType); break;
case 10: bVal = bPrintProspect ; pValues[nProp].setValue(&bVal, rType); break;
case 11: bVal = bPrintSingleJobs ; pValues[nProp].setValue(&bVal, rType); break;
case 12: pValues[nProp] <<= sFaxName; break;
case 13: bVal = bPaperFromSetup ; pValues[nProp].setValue(&bVal, rType); break;
}
}
PutProperties(aNames, aValues);
}
/* -----------------------------06.09.00 16:46--------------------------------
---------------------------------------------------------------------------*/
void SwPrintOptions::Notify( const Sequence<rtl::OUString>& aPropertyNames)
{
DBG_ERROR("properties have been changed")
}
<commit_msg>Writer/Web adjustment<commit_after>/*************************************************************************
*
* $RCSfile: prtopt.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: os $ $Date: 2000-10-10 08:29:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
Beschreibung: Ctor
--------------------------------------------------------------------*/
Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Content/Graphic", // 0
"Content/Table", // 1
"Content/Control", // 2
"Content/Background", // 3
"Content/PrintBlack", // 4
"Content/Note", // 5
"Page/Reversed", // 6
"Page/Brochure", // 7
"Output/SinglePrintJob", // 8
"Output/Fax", // 9
"Papertray/FromPrinterSetup", // 10
"Content/Drawing", // 11 not in SW/Web
"Page/LeftPage", // 12 not in SW/Web
"Page/RightPage" // 13 not in SW/Web
};
const int nCount = bIsWeb ? 11 : 14;
Sequence<OUString> aNames(nCount);
OUString* pNames = aNames.getArray();
for(int i = 0; i < nCount; i++)
{
pNames[i] = OUString::createFromAscii(aPropNames[i]);
}
return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") : C2U("Office.Writer/Print")),
bPrintGraphic(sal_True),
bPrintTable(sal_True),
bPrintDraw(sal_True),
bPrintControl(sal_True),
bPrintLeftPage(sal_True),
bPrintRightPage(sal_True),
bReverse(sal_False),
bPaperFromSetup(sal_False),
bPrintProspect(sal_False),
bPrintSingleJobs(sal_False),
bPrintPageBackground(!bWeb),
bPrintBlackFont(bWeb),
nPrintPostIts(POSTITS_NONE),
bIsWeb(bWeb)
{
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
EnableNotification(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case 0: bPrintGraphic = *(sal_Bool*)pValues[nProp].getValue(); break;
case 1: bPrintTable = *(sal_Bool*)pValues[nProp].getValue(); break;
case 2: bPrintControl = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 3: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue(); break;
case 4: bPrintBlackFont = *(sal_Bool*)pValues[nProp].getValue(); break;
case 5: pValues[nProp] >>= nPrintPostIts ; break;
case 6: bReverse = *(sal_Bool*)pValues[nProp].getValue(); break;
case 7: bPrintProspect = *(sal_Bool*)pValues[nProp].getValue(); break;
case 8: bPrintSingleJobs = *(sal_Bool*)pValues[nProp].getValue(); break;
case 9: pValues[nProp] >>= sFaxName; break;
case 10: bPaperFromSetup = *(sal_Bool*)pValues[nProp].getValue(); break;
case 11: bPrintDraw = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 12: bPrintLeftPage = *(sal_Bool*)pValues[nProp].getValue(); break;
case 13: bPrintRightPage = *(sal_Bool*)pValues[nProp].getValue(); break;
}
}
}
}
}
/* -----------------------------06.09.00 16:50--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------
---------------------------------------------------------------------------*/
void SwPrintOptions::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
BOOL bVal;
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
switch(nProp)
{
case 0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
case 1: bVal = bPrintTable ;pValues[nProp].setValue(&bVal, rType); break;
case 2: bVal = bPrintControl ; pValues[nProp].setValue(&bVal, rType); break;
case 3: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType); break;
case 4: bVal = bPrintBlackFont ; pValues[nProp].setValue(&bVal, rType); break;
case 5: pValues[nProp] <<= nPrintPostIts ; break;
case 6: bVal = bReverse ; pValues[nProp].setValue(&bVal, rType); break;
case 7: bVal = bPrintProspect ; pValues[nProp].setValue(&bVal, rType); break;
case 8: bVal = bPrintSingleJobs ; pValues[nProp].setValue(&bVal, rType); break;
case 9: pValues[nProp] <<= sFaxName; break;
case 10: bVal = bPaperFromSetup ; pValues[nProp].setValue(&bVal, rType); break;
case 11: bVal = bPrintDraw ; pValues[nProp].setValue(&bVal, rType); break;
case 12: bVal = bPrintLeftPage ; pValues[nProp].setValue(&bVal, rType); break;
case 13: bVal = bPrintRightPage ; pValues[nProp].setValue(&bVal, rType); break;
}
}
PutProperties(aNames, aValues);
}
/* -----------------------------06.09.00 16:46--------------------------------
---------------------------------------------------------------------------*/
void SwPrintOptions::Notify( const Sequence<rtl::OUString>& aPropertyNames)
{
DBG_ERROR("properties have been changed")
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: envprt.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 22:54:29 $
*
* 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_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _SV_PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif
#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif
#include "swtypes.hxx"
#include "cmdid.h"
#include "envprt.hxx"
#include "envlop.hxx"
#include "uitool.hxx"
#include "envprt.hrc"
SwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet) :
SfxTabPage(pParent, SW_RES(TP_ENV_PRT), rSet),
aAlignBox (this, SW_RES(BOX_ALIGN )),
aTopButton (this, SW_RES(BTN_TOP )),
aBottomButton(this, SW_RES(BTN_BOTTOM )),
aRightText (this, SW_RES(TXT_RIGHT )),
aRightField (this, SW_RES(FLD_RIGHT )),
aDownText (this, SW_RES(TXT_DOWN )),
aDownField (this, SW_RES(FLD_DOWN )),
aPrinterInfo (this, SW_RES(TXT_PRINTER)),
aNoNameFL (this, SW_RES(FL_NONAME )),
aPrinterFL (this, SW_RES(FL_PRINTER )),
aPrtSetup (this, SW_RES(BTN_PRTSETUP))
{
FreeResource();
SetExchangeSupport();
// Metriken
FieldUnit eUnit = ::GetDfltMetric(FALSE);
SetMetric(aRightField, eUnit);
SetMetric(aDownField , eUnit);
// Handler installieren
aTopButton .SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aBottomButton.SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aPrtSetup .SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));
// Bitmaps
aBottomButton.GetClickHdl().Call(&aBottomButton);
// ToolBox
Size aSz = aAlignBox.CalcWindowSizePixel();
aAlignBox.SetSizePixel(aSz);
// aAlignBox.SetPosPixel(Point(aNoNameFL.GetPosPixel().X() + (aNoNameFL.GetSizePixel().Width() - aSz.Width()) / 2, aAlignBox.GetPosPixel().Y()));
aAlignBox.SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));
}
// --------------------------------------------------------------------------
SwEnvPrtPage::~SwEnvPrtPage()
{
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ClickHdl, Button *, EMPTYARG )
{
sal_Bool bHC = GetDisplayBackground().GetColor().IsDark();
if (aBottomButton.IsChecked())
{
// Briefumschlaege von unten
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_LOWER_H : BMP_HOR_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_LOWER_H : BMP_HOR_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_LOWER_H : BMP_HOR_RGHT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_LOWER_H : BMP_VER_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_LOWER_H : BMP_VER_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_LOWER_H : BMP_VER_RGHT_LOWER)));
}
else
{
// Briefumschlaege von oben
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_UPPER_H : BMP_HOR_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_UPPER_H : BMP_HOR_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_UPPER_H : BMP_HOR_RGHT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_UPPER_H : BMP_VER_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_UPPER_H : BMP_VER_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_UPPER_H : BMP_VER_RGHT_UPPER)));
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )
{
if (pBtn == &aPrtSetup)
{
// Druck-Setup aufrufen
if (pPrt)
{
PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
pDlg->SetPrinter(pPrt);
pDlg->Execute();
delete pDlg;
GrabFocus();
aPrinterInfo.SetText(pPrt->GetName());
}
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, AlignHdl, ToolBox *, EMPTYARG )
{
if (aAlignBox.GetCurItemId())
{
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT; i++)
aAlignBox.CheckItem(i, FALSE);
aAlignBox.CheckItem(aAlignBox.GetCurItemId(), TRUE);
}
else
{
// GetCurItemId() == 0 ist moeglich!
const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT, TRUE);
}
return 0;
}
// --------------------------------------------------------------------------
SfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
return new SwEnvPrtPage(pParent, rSet);
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::ActivatePage(const SfxItemSet& rSet)
{
if (pPrt)
aPrinterInfo.SetText(pPrt->GetName());
}
// --------------------------------------------------------------------------
int SwEnvPrtPage::DeactivatePage(SfxItemSet* pSet)
{
if( pSet )
FillItemSet(*pSet);
return SfxTabPage::LEAVE_PAGE;
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::FillItem(SwEnvItem& rItem)
{
USHORT nID = 0;
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT && !nID; i++)
if (aAlignBox.IsItemChecked(i))
nID = i;
rItem.eAlign = (SwEnvAlign) (nID - ITM_HOR_LEFT);
rItem.bPrintFromAbove = aTopButton.IsChecked();
rItem.lShiftRight = GetFldVal(aRightField);
rItem.lShiftDown = GetFldVal(aDownField );
}
// --------------------------------------------------------------------------
BOOL SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)
{
FillItem(GetParent()->aEnvItem);
rSet.Put(GetParent()->aEnvItem);
return TRUE;
}
// ----------------------------------------------------------------------------
void SwEnvPrtPage::Reset(const SfxItemSet& rSet)
{
// SfxItemSet aSet(rSet);
// aSet.Put(GetParent()->aEnvItem);
// Item auslesen
const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT);
if (rItem.bPrintFromAbove)
aTopButton .Check();
else
aBottomButton.Check();
SetFldVal(aRightField, rItem.lShiftRight);
SetFldVal(aDownField , rItem.lShiftDown );
ActivatePage(rSet);
ClickHdl(&aTopButton);
}
<commit_msg>INTEGRATION: CWS swwarnings (1.10.222); FILE MERGED 2007/04/03 13:01:08 tl 1.10.222.2: #i69287# warning-free code 2007/03/26 12:08:59 tl 1.10.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: envprt.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-09-27 11:42: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#ifndef _SV_PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif
#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif
#include "swtypes.hxx"
#include "cmdid.h"
#include "envprt.hxx"
#include "envlop.hxx"
#include "uitool.hxx"
#include "envprt.hrc"
SwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet) :
SfxTabPage(pParent, SW_RES(TP_ENV_PRT), rSet),
aAlignBox (this, SW_RES(BOX_ALIGN )),
aTopButton (this, SW_RES(BTN_TOP )),
aBottomButton(this, SW_RES(BTN_BOTTOM )),
aRightText (this, SW_RES(TXT_RIGHT )),
aRightField (this, SW_RES(FLD_RIGHT )),
aDownText (this, SW_RES(TXT_DOWN )),
aDownField (this, SW_RES(FLD_DOWN )),
aPrinterInfo (this, SW_RES(TXT_PRINTER)),
aNoNameFL (this, SW_RES(FL_NONAME )),
aPrinterFL (this, SW_RES(FL_PRINTER )),
aPrtSetup (this, SW_RES(BTN_PRTSETUP))
{
FreeResource();
SetExchangeSupport();
// Metriken
FieldUnit eUnit = ::GetDfltMetric(FALSE);
SetMetric(aRightField, eUnit);
SetMetric(aDownField , eUnit);
// Handler installieren
aTopButton .SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aBottomButton.SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aPrtSetup .SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));
// Bitmaps
aBottomButton.GetClickHdl().Call(&aBottomButton);
// ToolBox
Size aSz = aAlignBox.CalcWindowSizePixel();
aAlignBox.SetSizePixel(aSz);
// aAlignBox.SetPosPixel(Point(aNoNameFL.GetPosPixel().X() + (aNoNameFL.GetSizePixel().Width() - aSz.Width()) / 2, aAlignBox.GetPosPixel().Y()));
aAlignBox.SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));
}
// --------------------------------------------------------------------------
SwEnvPrtPage::~SwEnvPrtPage()
{
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ClickHdl, Button *, EMPTYARG )
{
sal_Bool bHC = GetDisplayBackground().GetColor().IsDark();
if (aBottomButton.IsChecked())
{
// Briefumschlaege von unten
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_LOWER_H : BMP_HOR_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_LOWER_H : BMP_HOR_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_LOWER_H : BMP_HOR_RGHT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_LOWER_H : BMP_VER_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_LOWER_H : BMP_VER_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_LOWER_H : BMP_VER_RGHT_LOWER)));
}
else
{
// Briefumschlaege von oben
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_UPPER_H : BMP_HOR_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_UPPER_H : BMP_HOR_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_UPPER_H : BMP_HOR_RGHT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_UPPER_H : BMP_VER_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_UPPER_H : BMP_VER_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_UPPER_H : BMP_VER_RGHT_UPPER)));
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )
{
if (pBtn == &aPrtSetup)
{
// Druck-Setup aufrufen
if (pPrt)
{
PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
pDlg->SetPrinter(pPrt);
pDlg->Execute();
delete pDlg;
GrabFocus();
aPrinterInfo.SetText(pPrt->GetName());
}
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, AlignHdl, ToolBox *, EMPTYARG )
{
if (aAlignBox.GetCurItemId())
{
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT; i++)
aAlignBox.CheckItem(i, FALSE);
aAlignBox.CheckItem(aAlignBox.GetCurItemId(), TRUE);
}
else
{
// GetCurItemId() == 0 ist moeglich!
const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT, TRUE);
}
return 0;
}
// --------------------------------------------------------------------------
SfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
return new SwEnvPrtPage(pParent, rSet);
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::ActivatePage(const SfxItemSet&)
{
if (pPrt)
aPrinterInfo.SetText(pPrt->GetName());
}
// --------------------------------------------------------------------------
int SwEnvPrtPage::DeactivatePage(SfxItemSet* _pSet)
{
if( _pSet )
FillItemSet(*_pSet);
return SfxTabPage::LEAVE_PAGE;
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::FillItem(SwEnvItem& rItem)
{
USHORT nID = 0;
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT && !nID; i++)
if (aAlignBox.IsItemChecked(i))
nID = i;
rItem.eAlign = (SwEnvAlign) (nID - ITM_HOR_LEFT);
rItem.bPrintFromAbove = aTopButton.IsChecked();
rItem.lShiftRight = static_cast< sal_Int32 >(GetFldVal(aRightField));
rItem.lShiftDown = static_cast< sal_Int32 >(GetFldVal(aDownField ));
}
// --------------------------------------------------------------------------
BOOL SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)
{
FillItem(GetParent()->aEnvItem);
rSet.Put(GetParent()->aEnvItem);
return TRUE;
}
// ----------------------------------------------------------------------------
void SwEnvPrtPage::Reset(const SfxItemSet& rSet)
{
// SfxItemSet aSet(rSet);
// aSet.Put(GetParent()->aEnvItem);
// Item auslesen
const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT);
if (rItem.bPrintFromAbove)
aTopButton .Check();
else
aBottomButton.Check();
SetFldVal(aRightField, rItem.lShiftRight);
SetFldVal(aDownField , rItem.lShiftDown );
ActivatePage(rSet);
ClickHdl(&aTopButton);
}
<|endoftext|>
|
<commit_before>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include "tfilestream.h"
#include "tstring.h"
#include "tdebug.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
# include <wchar.h>
# include <windows.h>
# include <io.h>
#else
# include <unistd.h>
#endif
#include <stdlib.h>
using namespace TagLib;
namespace {
#ifdef _WIN32
// For Windows
typedef FileName FileNameHandle;
// Using native file handles instead of file descriptors for reducing the resource consumption.
HANDLE openFile(const FileName &path, bool readOnly)
{
DWORD access = readOnly ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE);
if(wcslen(path) > 0)
return CreateFileW(path, access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
else
return CreateFileA(path, access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
}
size_t fread(void *ptr, size_t size, size_t nmemb, HANDLE stream)
{
DWORD read_len;
ReadFile(stream, ptr, size * nmemb, &read_len, NULL);
return (read_len / size);
}
size_t fwrite(const void *ptr, size_t size, size_t nmemb, HANDLE stream)
{
DWORD written_len;
WriteFile(stream, ptr, size * nmemb, &written_len, NULL);
return written_len;
}
#else
// For non-Windows
struct FileNameHandle : public std::string
{
FileNameHandle(FileName name) : std::string(name) {}
operator FileName () const { return c_str(); }
};
FILE *openFile(const FileName &path, bool readOnly)
{
return fopen(path, readOnly ? "rb" : "rb+");
}
#endif
}
class FileStream::FileStreamPrivate
{
public:
FileStreamPrivate(FileName fileName, bool openReadOnly);
#ifdef _WIN32
HANDLE file;
#else
FILE *file;
#endif
FileNameHandle name;
bool readOnly;
ulong size;
static const uint bufferSize = 1024;
};
FileStream::FileStreamPrivate::FileStreamPrivate(FileName fileName, bool openReadOnly) :
file(0),
name(fileName),
readOnly(true),
size(0)
{
// First try with read / write mode, if that fails, fall back to read only.
if(!openReadOnly)
file = openFile(name, false);
if(file)
readOnly = false;
else
file = openFile(name, true);
if(!file) {
debug("Could not open file " + String((const char *) name));
}
}
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
FileStream::FileStream(FileName file, bool openReadOnly)
{
d = new FileStreamPrivate(file, openReadOnly);
}
FileStream::~FileStream()
{
#ifdef _WIN32
if(d->file)
CloseHandle(d->file);
#else
if(d->file)
fclose(d->file);
#endif
delete d;
}
FileName FileStream::name() const
{
return d->name;
}
ByteVector FileStream::readBlock(ulong length)
{
if(!d->file) {
debug("FileStream::readBlock() -- Invalid File");
return ByteVector::null;
}
if(length == 0)
return ByteVector::null;
if(length > FileStreamPrivate::bufferSize &&
length > ulong(FileStream::length()))
{
length = FileStream::length();
}
ByteVector v(static_cast<uint>(length));
const int count = fread(v.data(), sizeof(char), length, d->file);
v.resize(count);
return v;
}
void FileStream::writeBlock(const ByteVector &data)
{
if(!d->file)
return;
if(d->readOnly) {
debug("File::writeBlock() -- attempted to write to a file that is not writable");
return;
}
fwrite(data.data(), sizeof(char), data.size(), d->file);
}
void FileStream::insert(const ByteVector &data, ulong start, ulong replace)
{
if(!d->file)
return;
if(data.size() == replace) {
seek(start);
writeBlock(data);
return;
}
else if(data.size() < replace) {
seek(start);
writeBlock(data);
removeBlock(start + data.size(), replace - data.size());
return;
}
// Woohoo! Faster (about 20%) than id3lib at last. I had to get hardcore
// and avoid TagLib's high level API for rendering just copying parts of
// the file that don't contain tag data.
//
// Now I'll explain the steps in this ugliness:
// First, make sure that we're working with a buffer that is longer than
// the *differnce* in the tag sizes. We want to avoid overwriting parts
// that aren't yet in memory, so this is necessary.
ulong bufferLength = bufferSize();
while(data.size() - replace > bufferLength)
bufferLength += bufferSize();
// Set where to start the reading and writing.
long readPosition = start + replace;
long writePosition = start;
ByteVector buffer;
ByteVector aboutToOverwrite(static_cast<uint>(bufferLength));
// This is basically a special case of the loop below. Here we're just
// doing the same steps as below, but since we aren't using the same buffer
// size -- instead we're using the tag size -- this has to be handled as a
// special case. We're also using File::writeBlock() just for the tag.
// That's a bit slower than using char *'s so, we're only doing it here.
seek(readPosition);
int bytesRead = fread(aboutToOverwrite.data(), sizeof(char), bufferLength, d->file);
readPosition += bufferLength;
seek(writePosition);
writeBlock(data);
writePosition += data.size();
buffer = aboutToOverwrite;
// In case we've already reached the end of file...
buffer.resize(bytesRead);
// Ok, here's the main loop. We want to loop until the read fails, which
// means that we hit the end of the file.
while(!buffer.isEmpty()) {
// Seek to the current read position and read the data that we're about
// to overwrite. Appropriately increment the readPosition.
seek(readPosition);
bytesRead = fread(aboutToOverwrite.data(), sizeof(char), bufferLength, d->file);
aboutToOverwrite.resize(bytesRead);
readPosition += bufferLength;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(ulong(bytesRead) < bufferLength)
clear();
// Seek to the write position and write our buffer. Increment the
// writePosition.
seek(writePosition);
fwrite(buffer.data(), sizeof(char), buffer.size(), d->file);
writePosition += buffer.size();
// Make the current buffer the data that we read in the beginning.
buffer = aboutToOverwrite;
// Again, we need this for the last write. We don't want to write garbage
// at the end of our file, so we need to set the buffer size to the amount
// that we actually read.
bufferLength = bytesRead;
}
}
void FileStream::removeBlock(ulong start, ulong length)
{
if(!d->file)
return;
ulong bufferLength = bufferSize();
long readPosition = start + length;
long writePosition = start;
ByteVector buffer(static_cast<uint>(bufferLength));
ulong bytesRead = 1;
while(bytesRead != 0) {
seek(readPosition);
bytesRead = fread(buffer.data(), sizeof(char), bufferLength, d->file);
readPosition += bytesRead;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(bytesRead < bufferLength)
clear();
seek(writePosition);
fwrite(buffer.data(), sizeof(char), bytesRead, d->file);
writePosition += bytesRead;
}
truncate(writePosition);
}
bool FileStream::readOnly() const
{
return d->readOnly;
}
bool FileStream::isOpen() const
{
return (d->file != NULL);
}
void FileStream::seek(long offset, Position p)
{
if(!d->file) {
debug("File::seek() -- trying to seek in a file that isn't opened.");
return;
}
#ifdef _WIN32
DWORD whence;
switch(p) {
case Beginning:
whence = FILE_BEGIN;
break;
case Current:
whence = FILE_CURRENT;
break;
case End:
whence = FILE_END;
break;
}
SetFilePointer(d->file, offset, NULL, whence);
#else
int whence;
switch(p) {
case Beginning:
whence = SEEK_SET;
break;
case Current:
whence = SEEK_CUR;
break;
case End:
whence = SEEK_END;
break;
}
fseek(d->file, offset, whence);
#endif
}
void FileStream::clear()
{
#ifdef _WIN32
// NOP
#else
clearerr(d->file);
#endif
}
long FileStream::tell() const
{
#ifdef _WIN32
return (long)SetFilePointer(d->file, 0, NULL, FILE_CURRENT);
#else
return ftell(d->file);
#endif
}
long FileStream::length()
{
// Do some caching in case we do multiple calls.
if(d->size > 0)
return d->size;
if(!d->file)
return 0;
long curpos = tell();
seek(0, End);
long endpos = tell();
seek(curpos, Beginning);
d->size = endpos;
return endpos;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void FileStream::truncate(long length)
{
#ifdef _WIN32
long current_pos = tell();
seek(length);
SetEndOfFile(d->file);
seek(current_pos);
#else
ftruncate(fileno(d->file), length);
#endif
}
TagLib::uint FileStream::bufferSize()
{
return FileStreamPrivate::bufferSize;
}
<commit_msg>Change some variables to follow the TagLib naming convention<commit_after>/***************************************************************************
copyright : (C) 2002 - 2008 by Scott Wheeler
email : wheeler@kde.org
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA *
* 02110-1301 USA *
* *
* Alternatively, this file is available under the Mozilla Public *
* License Version 1.1. You may obtain a copy of the License at *
* http://www.mozilla.org/MPL/ *
***************************************************************************/
#include "tfilestream.h"
#include "tstring.h"
#include "tdebug.h"
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#ifdef _WIN32
# include <wchar.h>
# include <windows.h>
# include <io.h>
#else
# include <unistd.h>
#endif
#include <stdlib.h>
using namespace TagLib;
namespace {
#ifdef _WIN32
// For Windows
typedef FileName FileNameHandle;
// Using native file handles instead of file descriptors for reducing the resource consumption.
HANDLE openFile(const FileName &path, bool readOnly)
{
DWORD access = readOnly ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE);
if(wcslen(path) > 0)
return CreateFileW(path, access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
else
return CreateFileA(path, access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
}
size_t fread(void *ptr, size_t size, size_t nmemb, HANDLE stream)
{
DWORD readLen;
ReadFile(stream, ptr, size * nmemb, &readLen, NULL);
return (readLen / size);
}
size_t fwrite(const void *ptr, size_t size, size_t nmemb, HANDLE stream)
{
DWORD writtenLen;
WriteFile(stream, ptr, size * nmemb, &writtenLen, NULL);
return writtenLen;
}
#else
// For non-Windows
struct FileNameHandle : public std::string
{
FileNameHandle(FileName name) : std::string(name) {}
operator FileName () const { return c_str(); }
};
FILE *openFile(const FileName &path, bool readOnly)
{
return fopen(path, readOnly ? "rb" : "rb+");
}
#endif
}
class FileStream::FileStreamPrivate
{
public:
FileStreamPrivate(FileName fileName, bool openReadOnly);
#ifdef _WIN32
HANDLE file;
#else
FILE *file;
#endif
FileNameHandle name;
bool readOnly;
ulong size;
static const uint bufferSize = 1024;
};
FileStream::FileStreamPrivate::FileStreamPrivate(FileName fileName, bool openReadOnly) :
file(0),
name(fileName),
readOnly(true),
size(0)
{
// First try with read / write mode, if that fails, fall back to read only.
if(!openReadOnly)
file = openFile(name, false);
if(file)
readOnly = false;
else
file = openFile(name, true);
if(!file) {
debug("Could not open file " + String((const char *) name));
}
}
////////////////////////////////////////////////////////////////////////////////
// public members
////////////////////////////////////////////////////////////////////////////////
FileStream::FileStream(FileName file, bool openReadOnly)
{
d = new FileStreamPrivate(file, openReadOnly);
}
FileStream::~FileStream()
{
#ifdef _WIN32
if(d->file)
CloseHandle(d->file);
#else
if(d->file)
fclose(d->file);
#endif
delete d;
}
FileName FileStream::name() const
{
return d->name;
}
ByteVector FileStream::readBlock(ulong length)
{
if(!d->file) {
debug("FileStream::readBlock() -- Invalid File");
return ByteVector::null;
}
if(length == 0)
return ByteVector::null;
if(length > FileStreamPrivate::bufferSize &&
length > ulong(FileStream::length()))
{
length = FileStream::length();
}
ByteVector v(static_cast<uint>(length));
const int count = fread(v.data(), sizeof(char), length, d->file);
v.resize(count);
return v;
}
void FileStream::writeBlock(const ByteVector &data)
{
if(!d->file)
return;
if(d->readOnly) {
debug("File::writeBlock() -- attempted to write to a file that is not writable");
return;
}
fwrite(data.data(), sizeof(char), data.size(), d->file);
}
void FileStream::insert(const ByteVector &data, ulong start, ulong replace)
{
if(!d->file)
return;
if(data.size() == replace) {
seek(start);
writeBlock(data);
return;
}
else if(data.size() < replace) {
seek(start);
writeBlock(data);
removeBlock(start + data.size(), replace - data.size());
return;
}
// Woohoo! Faster (about 20%) than id3lib at last. I had to get hardcore
// and avoid TagLib's high level API for rendering just copying parts of
// the file that don't contain tag data.
//
// Now I'll explain the steps in this ugliness:
// First, make sure that we're working with a buffer that is longer than
// the *differnce* in the tag sizes. We want to avoid overwriting parts
// that aren't yet in memory, so this is necessary.
ulong bufferLength = bufferSize();
while(data.size() - replace > bufferLength)
bufferLength += bufferSize();
// Set where to start the reading and writing.
long readPosition = start + replace;
long writePosition = start;
ByteVector buffer;
ByteVector aboutToOverwrite(static_cast<uint>(bufferLength));
// This is basically a special case of the loop below. Here we're just
// doing the same steps as below, but since we aren't using the same buffer
// size -- instead we're using the tag size -- this has to be handled as a
// special case. We're also using File::writeBlock() just for the tag.
// That's a bit slower than using char *'s so, we're only doing it here.
seek(readPosition);
int bytesRead = fread(aboutToOverwrite.data(), sizeof(char), bufferLength, d->file);
readPosition += bufferLength;
seek(writePosition);
writeBlock(data);
writePosition += data.size();
buffer = aboutToOverwrite;
// In case we've already reached the end of file...
buffer.resize(bytesRead);
// Ok, here's the main loop. We want to loop until the read fails, which
// means that we hit the end of the file.
while(!buffer.isEmpty()) {
// Seek to the current read position and read the data that we're about
// to overwrite. Appropriately increment the readPosition.
seek(readPosition);
bytesRead = fread(aboutToOverwrite.data(), sizeof(char), bufferLength, d->file);
aboutToOverwrite.resize(bytesRead);
readPosition += bufferLength;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(ulong(bytesRead) < bufferLength)
clear();
// Seek to the write position and write our buffer. Increment the
// writePosition.
seek(writePosition);
fwrite(buffer.data(), sizeof(char), buffer.size(), d->file);
writePosition += buffer.size();
// Make the current buffer the data that we read in the beginning.
buffer = aboutToOverwrite;
// Again, we need this for the last write. We don't want to write garbage
// at the end of our file, so we need to set the buffer size to the amount
// that we actually read.
bufferLength = bytesRead;
}
}
void FileStream::removeBlock(ulong start, ulong length)
{
if(!d->file)
return;
ulong bufferLength = bufferSize();
long readPosition = start + length;
long writePosition = start;
ByteVector buffer(static_cast<uint>(bufferLength));
ulong bytesRead = 1;
while(bytesRead != 0) {
seek(readPosition);
bytesRead = fread(buffer.data(), sizeof(char), bufferLength, d->file);
readPosition += bytesRead;
// Check to see if we just read the last block. We need to call clear()
// if we did so that the last write succeeds.
if(bytesRead < bufferLength)
clear();
seek(writePosition);
fwrite(buffer.data(), sizeof(char), bytesRead, d->file);
writePosition += bytesRead;
}
truncate(writePosition);
}
bool FileStream::readOnly() const
{
return d->readOnly;
}
bool FileStream::isOpen() const
{
return (d->file != NULL);
}
void FileStream::seek(long offset, Position p)
{
if(!d->file) {
debug("File::seek() -- trying to seek in a file that isn't opened.");
return;
}
#ifdef _WIN32
DWORD whence;
switch(p) {
case Beginning:
whence = FILE_BEGIN;
break;
case Current:
whence = FILE_CURRENT;
break;
case End:
whence = FILE_END;
break;
}
SetFilePointer(d->file, offset, NULL, whence);
#else
int whence;
switch(p) {
case Beginning:
whence = SEEK_SET;
break;
case Current:
whence = SEEK_CUR;
break;
case End:
whence = SEEK_END;
break;
}
fseek(d->file, offset, whence);
#endif
}
void FileStream::clear()
{
#ifdef _WIN32
// NOP
#else
clearerr(d->file);
#endif
}
long FileStream::tell() const
{
#ifdef _WIN32
return (long)SetFilePointer(d->file, 0, NULL, FILE_CURRENT);
#else
return ftell(d->file);
#endif
}
long FileStream::length()
{
// Do some caching in case we do multiple calls.
if(d->size > 0)
return d->size;
if(!d->file)
return 0;
long curpos = tell();
seek(0, End);
long endpos = tell();
seek(curpos, Beginning);
d->size = endpos;
return endpos;
}
////////////////////////////////////////////////////////////////////////////////
// protected members
////////////////////////////////////////////////////////////////////////////////
void FileStream::truncate(long length)
{
#ifdef _WIN32
long currentPos = tell();
seek(length);
SetEndOfFile(d->file);
seek(currentPos);
#else
ftruncate(fileno(d->file), length);
#endif
}
TagLib::uint FileStream::bufferSize()
{
return FileStreamPrivate::bufferSize;
}
<|endoftext|>
|
<commit_before>/**
* @file Cosa/IOStream/Driver/VWIO.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_IOSTREAM_DRIVER_VWIO_HH__
#define __COSA_IOSTREAM_DRIVER_VWIO_HH__
#include "Cosa/Types.h"
#include "Cosa/IOStream.hh"
#include "Cosa/VWI.hh"
/**
* IOStream driver for Virtual Wire Interface. Allow IOStream
* such as Trace over Virtual Wire connection. Please note that
* basic VWI is not reliable and characters may be lost due to
* noise, collisions, etc.
*/
class VWIO : public IOStream::Device {
private:
VWI::Transmitter m_tx;
uint8_t m_buffer[VWI::PAYLOAD_MAX];
uint8_t m_ix;
public:
/**
* Construct Virtual Wire Interface Output Stream.
* @param[in] pin output pin.
* @param[in] codec from receiver.
*/
VWIO(Board::DigitalPin pin, VWI::Codec* codec) :
IOStream::Device(),
m_tx(pin, codec),
m_ix(0)
{
}
/**
* @override
* Write character to output buffer. Flush if full or carrage return
* character. Returns character if successful otherwise on error or
* buffer full returns EOF(-1),
* @param[in] c character to write.
* @return character written or EOF(-1).
*/
virtual int putchar(char c)
{
m_buffer[m_ix++] = c;
if (m_ix == sizeof(m_buffer) || c == '\n') flush();
return (c & 0xff);
}
/**
* @override
* Flush internal device buffers. Wait for device to become idle.
* @return zero(0) or negative error code.
*/
virtual int flush()
{
int res = (m_tx.send(m_buffer, m_ix) == m_ix ? 0 : -1);
m_tx.await();
m_ix = 0;
return (res);
}
/**
* Start VWI transmitter driver.
* @param[in] baudrate serial bitrate (default 2000).
* @return true(1) if successful otherwise false(0)
*/
bool begin(uint16_t baudrate = 2000)
{
return (VWI::begin(baudrate) && m_tx.begin());
}
/**
* Stop VWI transitter device driver.
* @return true(1) if successful otherwise false(0)
*/
bool end()
{
return (m_tx.end());
}
};
#endif
<commit_msg>Ripple effect of change to IOStream::Device::flush().<commit_after>/**
* @file Cosa/IOStream/Driver/VWIO.hh
* @version 1.0
*
* @section License
* Copyright (C) 2013, Mikael Patel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*
* This file is part of the Arduino Che Cosa project.
*/
#ifndef __COSA_IOSTREAM_DRIVER_VWIO_HH__
#define __COSA_IOSTREAM_DRIVER_VWIO_HH__
#include "Cosa/Types.h"
#include "Cosa/IOStream.hh"
#include "Cosa/VWI.hh"
/**
* IOStream driver for Virtual Wire Interface. Allow IOStream
* such as Trace over Virtual Wire connection. Please note that
* basic VWI is not reliable and characters may be lost due to
* noise, collisions, etc.
*/
class VWIO : public IOStream::Device {
private:
VWI::Transmitter m_tx;
uint8_t m_buffer[VWI::PAYLOAD_MAX];
uint8_t m_ix;
public:
/**
* Construct Virtual Wire Interface Output Stream.
* @param[in] pin output pin.
* @param[in] codec from receiver.
*/
VWIO(Board::DigitalPin pin, VWI::Codec* codec) :
IOStream::Device(),
m_tx(pin, codec),
m_ix(0)
{
}
/**
* @override
* Write character to output buffer. Flush if full or carrage return
* character. Returns character if successful otherwise on error or
* buffer full returns EOF(-1),
* @param[in] c character to write.
* @return character written or EOF(-1).
*/
virtual int putchar(char c)
{
m_buffer[m_ix++] = c;
if (m_ix == sizeof(m_buffer) || c == '\n') flush();
return (c & 0xff);
}
/**
* @override
* Flush internal device buffers. Wait for device to become idle.
* @param[in] mode sleep mode on flush wait.
* @return zero(0) or negative error code.
*/
virtual int flush(uint8_mode = SLEEP_MODE_IDLE)
{
int res = (m_tx.send(m_buffer, m_ix) == m_ix ? 0 : -1);
m_tx.await();
m_ix = 0;
return (res);
}
/**
* Start VWI transmitter driver.
* @param[in] baudrate serial bitrate (default 4000).
* @return true(1) if successful otherwise false(0)
*/
bool begin(uint16_t baudrate = 4000)
{
return (VWI::begin(baudrate) && m_tx.begin());
}
/**
* Stop VWI transitter device driver.
* @return true(1) if successful otherwise false(0)
*/
bool end()
{
return (m_tx.end());
}
};
#endif
<|endoftext|>
|
<commit_before>/***********************************************************************
filename: HUDDemo.cpp
created: 11/8/2012
author: Lukas E Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & Thce CEGUI Development Team
*
* 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 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 "HUDDemo.h"
#include "CEGUI/CEGUI.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace CEGUI;
struct GamePlate
{
GamePlate(HUDDemo* hudDemo);
~GamePlate();
void update(float timeSinceLastUpdate);
int getPoints();
CEGUI::Window* d_window;
bool d_isComingFromRight;
bool d_isDestroyed;
};
GamePlate::GamePlate(HUDDemo* hudDemo)
: d_isDestroyed(false)
{
d_window = hudDemo->spawnPlate();
int randumNumber = rand() % 2;
d_isComingFromRight = (randumNumber == 0 ? false : true);
if(d_isComingFromRight)
{
d_window->setHorizontalAlignment(HA_RIGHT);
d_window->setPosition(d_window->getPosition() + CEGUI::UVector2(cegui_reldim(0.2f), cegui_absdim(0.0f)));
}
else
d_window->setPosition(d_window->getPosition() + CEGUI::UVector2(cegui_reldim(-0.2f), cegui_absdim(0.0f)));
}
GamePlate::~GamePlate()
{
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
winMgr.destroyWindow(d_window);
}
void GamePlate::update(float timeSinceLastUpdate)
{
CEGUI::UVector2 positionOffset;
if(d_isComingFromRight)
positionOffset = CEGUI::UVector2(cegui_reldim(timeSinceLastUpdate * -0.24f), cegui_absdim(0.f));
else
positionOffset = CEGUI::UVector2(cegui_reldim(timeSinceLastUpdate * 0.24f), cegui_absdim(0.f));
d_window->setPosition(d_window->getPosition() + positionOffset);
const CEGUI::UVector2& position = d_window->getPosition();
if(d_isComingFromRight)
{
if(position.d_x.d_scale < -1.2f)
d_isDestroyed = true;
}
else
{
if(position.d_x.d_scale > 1.2f)
d_isDestroyed = true;
}
}
int GamePlate::getPoints()
{
CEGUI::Window* window = d_window->getChild("ImageWindowObject");
CEGUI::String objectImage = window->getProperty("Image");
if(objectImage.compare(HUDDemo::s_imageNameBread) == 0)
return 2;
else if(objectImage.compare(HUDDemo::s_imageNamePoo) == 0)
return -6;
else if(objectImage.compare(HUDDemo::s_imageNameSteak) == 0)
return -13;
else if(objectImage.compare(HUDDemo::s_imageNamePrizza) == 0)
return 3;
else if(objectImage.compare(HUDDemo::s_imageNameVegPeople) == 0)
return 1;
else if(objectImage.compare(HUDDemo::s_imageNameVegFruits) == 0)
return 88;
return 0;
}
const CEGUI::String HUDDemo::s_imageNamePlate = "HUDDemo/Plate";
const CEGUI::String HUDDemo::s_imageNameBread = "HUDDemo/Bread";
const CEGUI::String HUDDemo::s_imageNamePoo = "HUDDemo/Poo";
const CEGUI::String HUDDemo::s_imageNamePrizza = "HUDDemo/Prizza";
const CEGUI::String HUDDemo::s_imageNameSteak = "HUDDemo/Steak";
const CEGUI::String HUDDemo::s_imageNameVegPeople = "HUDDemo/VegetablePeople";
const CEGUI::String HUDDemo::s_imageNameVegFruits = "HUDDemo/VegetablesAndFruits";
bool HUDDemo::initialise(CEGUI::GUIContext* guiContext)
{
using namespace CEGUI;
d_usedFiles = CEGUI::String(__FILE__);
d_guiContext = guiContext;
SchemeManager::getSingleton().createFromFile("HUDDemo.scheme");
SchemeManager::getSingleton().createFromFile("Generic.scheme");
FontManager::getSingleton().createFromFile("DejaVuSans-14.font");
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
// Load the HUDDemo Layout
d_rootIngame = winMgr.loadLayoutFromFile("HUDDemoIngame.layout");
d_rootGameOver = winMgr.loadLayoutFromFile("HUDDemoGameOver.layout");
d_root = winMgr.createWindow("DefaultWindow", "HUDDemoRoot");
d_root->addChild(d_rootIngame);
d_guiContext->setRootWindow(d_root);
if(!ImageManager::getSingleton().isDefined("HUDDemoGameOver"))
ImageManager::getSingleton().addFromImageFile("HUDDemoGameOver", "HUDDemoGameOver.png");
d_rootGameOver->getChild("GameOverImage")->setProperty("Image", "HUDDemoGameOver");
setupMouseCursor();
srand(static_cast<unsigned int >(time(0)));
d_lifeBar = static_cast<CEGUI::ProgressBar*>(d_rootIngame->getChild("TopBar/LifeBar"));
initGame();
d_rootIngame->getChild("BotBar/WeaponBGImage/LeftArrowArea")->subscribeEvent(CEGUI::Window::EventPointerActivate, Event::Subscriber(&HUDDemo::handleWeaponLeftArrowClicked, this));
d_rootIngame->getChild("BotBar/WeaponBGImage/RightArrowArea")->subscribeEvent(CEGUI::Window::EventPointerActivate, Event::Subscriber(&HUDDemo::handleWeaponRightArrowClicked, this));
d_rootGameOver->getChild("ButtonRestart")->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&HUDDemo::handleRestartButtonClicked, this));
return true;
}
/*************************************************************************
Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void HUDDemo::deinitialise()
{
while(!d_gamePlates.empty())
{
GamePlate* curPlate = d_gamePlates.back();
delete curPlate;
d_gamePlates.pop_back();
}
}
void HUDDemo::onEnteringSample()
{
initGame();
}
void HUDDemo::update(float timeSinceLastUpdate)
{
static float timeSinceLastSpawn(0.0f);
timeSinceLastSpawn += timeSinceLastUpdate;
updateMouseCursor();
if(timeSinceLastSpawn> 1.2f)
{
d_gamePlates.push_back(new GamePlate(this));
timeSinceLastSpawn -= 1.2f;
}
updatePlates(timeSinceLastUpdate);
delayDestroyWindows();
d_guiContext->markAsDirty();
}
void HUDDemo::setupMouseCursor()
{
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
d_mouseCursorWnd = winMgr.createWindow("Generic/Image");
d_mouseCursorWnd->setProperty("Image", "HUDDemo/Spoon");
d_mouseCursorWnd->setAspectMode(CEGUI::AM_EXPAND);
d_mouseCursorWnd->setAspectRatio(1.f);
d_mouseCursorWnd->setSize(CEGUI::USize(cegui_absdim(0.0f), cegui_reldim(0.1f)));
d_mouseCursorWnd->setAlwaysOnTop(true);
d_mouseCursorWnd->setPointerPassThroughEnabled(true);
d_rootIngame->addChild(d_mouseCursorWnd);
}
void HUDDemo::updateMouseCursor()
{
CEGUI::Vector2f position = d_guiContext->getPointerIndicator().getPosition();
// We want to position the image-window right top of the actual
// cursor point so we add its height
float absHeight = d_mouseCursorWnd->getPixelSize().d_height;
position.d_y -= absHeight;
d_mouseCursorWnd->setPosition(
CEGUI::UVector2(
cegui_absdim(position.d_x - 5.0f), cegui_absdim(position.d_y + 5.0f))
);
}
CEGUI::Window* HUDDemo::spawnPlate()
{
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
CEGUI::Window* plateRoot = winMgr.createWindow("DefaultWindow");
plateRoot->setSize(CEGUI::USize(cegui_absdim(0.0f), cegui_reldim(0.16f)));
plateRoot->setAspectMode(CEGUI::AM_EXPAND);
plateRoot->setAspectRatio(1.0f);
plateRoot->setRiseOnClickEnabled(false);
plateRoot->setPixelAligned(false);
plateRoot->subscribeEvent(CEGUI::Window::EventPointerPressHold, Event::Subscriber(&HUDDemo::handlePlateWindowClicked, this));
d_rootIngame->addChild(plateRoot);
CEGUI::Window* plateImgWnd = winMgr.createWindow("Generic/Image", "ImageWindowPlate");
plateImgWnd->setProperty("Image", s_imageNamePlate);
plateImgWnd->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_absdim(0.0f)));
plateImgWnd->setAspectRatio(3.308f);
plateImgWnd->setAspectMode(CEGUI::AM_EXPAND);
plateImgWnd->setVerticalAlignment(CEGUI::VA_BOTTOM);
plateImgWnd->setPointerPassThroughEnabled(true);
plateImgWnd->setPixelAligned(false);
plateRoot->addChild(plateImgWnd);
CEGUI::String image = getRandomGameImage();
CEGUI::Window* plateTopping = winMgr.createWindow("Generic/Image", "ImageWindowObject");
plateTopping->setProperty("Image", image);
plateTopping->setSize(CEGUI::USize(cegui_reldim(0.88f), cegui_absdim(0.0f)));
plateTopping->setAspectRatio(1.0f);
plateTopping->setAspectMode(CEGUI::AM_EXPAND);
plateTopping->setHorizontalAlignment(CEGUI::HA_CENTRE);
plateTopping->setPointerPassThroughEnabled(true);
plateTopping->setPixelAligned(false);
plateRoot->addChild(plateTopping);
int randumNumber = rand() % 10000;
float posY = randumNumber / 10000.0f;
plateRoot->setPosition(CEGUI::UVector2(cegui_absdim(0.0f), cegui_reldim(0.1f + 0.6f * posY)));
return plateRoot;
}
const CEGUI::String& HUDDemo::getRandomGameImage()
{
int randumNumber = rand() % 100;
if(randumNumber > 88)
return s_imageNamePoo;
else if(randumNumber > 72)
return s_imageNamePrizza;
else if(randumNumber > 55)
return s_imageNameSteak;
else if(randumNumber > 52)
return s_imageNameVegFruits;
else if(randumNumber > 25)
return s_imageNameVegPeople;
else if(randumNumber > 0)
return s_imageNameBread;
return s_imageNameBread;
}
void HUDDemo::updatePlates(float timeSinceLastUpdate)
{
unsigned int vectorSize = d_gamePlates.size();
for(unsigned int i = 0; i < vectorSize;)
{
GamePlate* currentPlate = d_gamePlates[i];
currentPlate->update(timeSinceLastUpdate);
if(currentPlate->d_isDestroyed)
{
delete currentPlate;
d_gamePlates[i] = d_gamePlates.back();
d_gamePlates.pop_back();
vectorSize = d_gamePlates.size();
}
else
++i;
}
}
void HUDDemo::updateScoreWindow()
{
CEGUI::Window* scoreWnd = d_rootIngame->getChild("TopBar/ScoreBGImage/Score");
scoreWnd->setText(CEGUI::PropertyHelper<int>::toString(d_score));
}
bool HUDDemo::handlePlateWindowClicked(const CEGUI::EventArgs& args)
{
const CEGUI::MouseEventArgs& mouseArgs = static_cast<const CEGUI::MouseEventArgs&>(args);
for(unsigned int i = 0; i < d_gamePlates.size(); ++i)
{
GamePlate* gamePlate = d_gamePlates[i];
if(gamePlate->d_window == mouseArgs.window)
{
int points = gamePlate->getPoints();
d_score += points;
updateScoreWindow();
if(points < 0)
{
float newProgress = d_lifeBar->getProgress() - 0.35f;
if(newProgress < 0.0f)
{
d_lives--;
handleLivesChanged();
newProgress = 1.0f;
}
d_lifeBar->setProgress(newProgress);
}
gamePlate->d_isDestroyed = true;
createScorePopup(mouseArgs.position, points);
}
}
return false;
}
void HUDDemo::createScorePopup(const CEGUI::Vector2<float>& mousePos, int points)
{
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
CEGUI::Window* popupWindow = winMgr.createWindow("HUDDemo/PopupLabel");
d_rootIngame->addChild(popupWindow);
popupWindow->setPosition(CEGUI::UVector2(cegui_absdim(mousePos.d_x), cegui_absdim(mousePos.d_y)));
popupWindow->setText(CEGUI::PropertyHelper<int>::toString(points));
popupWindow->setRiseOnClickEnabled(false);
popupWindow->subscribeEvent(AnimationInstance::EventAnimationEnded, Event::Subscriber(&HUDDemo::handleScorePopupAnimationEnded, this));
popupWindow->setPixelAligned(false);
popupWindow->setFont("DejaVuSans-14");
popupWindow->setPosition(popupWindow->getPosition() + CEGUI::UVector2(cegui_reldim(0.03f), cegui_reldim(-0.02f)));
if(points < 0)
popupWindow->setProperty("NormalTextColour", "FF880000");
else
{
popupWindow->setText( "+" + popupWindow->getText());
popupWindow->setProperty("NormalTextColour", "FF006600");
}
CEGUI::EventArgs args;
popupWindow->fireEvent("StartAnimation", args);
}
bool HUDDemo::handleScorePopupAnimationEnded(const CEGUI::EventArgs& args)
{
const CEGUI::AnimationEventArgs& animArgs = static_cast<const CEGUI::AnimationEventArgs&>(args);
CEGUI::Window* window = static_cast<CEGUI::Window*>( animArgs.instance->getTarget());
d_delayDestroyWindows.push_back(window);
return false;
}
void HUDDemo::delayDestroyWindows()
{
CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
while(!d_delayDestroyWindows.empty())
{
CEGUI::Window* curWindow = d_delayDestroyWindows.back();
winMgr.destroyWindow(curWindow);
d_delayDestroyWindows.pop_back();
}
}
void HUDDemo::handleLivesChanged()
{
bool life1Visible = (d_lives >= 1);
bool life2Visible = (d_lives >= 2);
bool life3Visible = (d_lives >= 3);
d_rootIngame->getChild("TopBar/Life1")->setAlpha( life1Visible ? 1.0f : 0.5f );
d_rootIngame->getChild("TopBar/Life2")->setAlpha( life2Visible ? 1.0f : 0.5f );
d_rootIngame->getChild("TopBar/Life3")->setAlpha( life3Visible ? 1.0f : 0.5f );
if(d_lives <= 0)
{
d_root->addChild(d_rootGameOver);
d_rootGameOver->addChild(d_mouseCursorWnd);
}
}
void HUDDemo::initGame()
{
d_lives = 3;
handleLivesChanged();
selectedWeapon(SW_Spoon);
d_score = 0;
updateScoreWindow();
d_lifeBar->setProgress(1.0f);
}
void HUDDemo::selectedWeapon(SelectedWeapon weapon)
{
d_selectedWeapon = weapon;
switch(d_selectedWeapon)
{
case SW_Spoon:
d_rootIngame->getChild("BotBar/WeaponSpoon")->setAlpha(1.0f);
d_rootIngame->getChild("BotBar/WeaponKnife")->setAlpha(0.5f);
d_rootIngame->getChild("BotBar/WeaponFork")->setAlpha(0.5f);
d_rootIngame->getChild("BotBar/WeaponBGImage/WeaponLabel")->setText("Le Spoon");
break;
case SW_Fork:
d_rootIngame->getChild("BotBar/WeaponSpoon")->setAlpha(0.5f);
d_rootIngame->getChild("BotBar/WeaponKnife")->setAlpha(0.5f);
d_rootIngame->getChild("BotBar/WeaponFork")->setAlpha(1.0f);
d_rootIngame->getChild("BotBar/WeaponBGImage/WeaponLabel")->setText("Le Fork");
break;
case SW_Knife:
d_rootIngame->getChild("BotBar/WeaponSpoon")->setAlpha(0.5f);
d_rootIngame->getChild("BotBar/WeaponKnife")->setAlpha(1.0f);
d_rootIngame->getChild("BotBar/WeaponFork")->setAlpha(0.5f);
d_rootIngame->getChild("BotBar/WeaponBGImage/WeaponLabel")->setText("Le Knife");
break;
default:
break;
}
}
bool HUDDemo::handleWeaponRightArrowClicked(const CEGUI::EventArgs& args)
{
int weaponIndex = static_cast<int>(d_selectedWeapon);
weaponIndex = (weaponIndex - 1) % 3;
if(weaponIndex < 0)
weaponIndex += 3;
selectedWeapon( static_cast<SelectedWeapon>(weaponIndex) );
return false;
}
bool HUDDemo::handleRestartButtonClicked(const CEGUI::EventArgs& args)
{
d_root->removeChild(d_rootGameOver);
d_rootIngame->addChild(d_mouseCursorWnd);
initGame();
return false;
}
bool HUDDemo::handleWeaponLeftArrowClicked(const CEGUI::EventArgs& args)
{
int weaponIndex = static_cast<int>(d_selectedWeapon);
selectedWeapon( static_cast<SelectedWeapon>(++weaponIndex % 3) );
return false;
}
/*************************************************************************
Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
static HUDDemo sample;
return sample;
}<commit_msg>Remove a file left undeleted from a merge<commit_after><|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "RequestManagerDelete.h"
using namespace std;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
Request::ErrorCode RequestManagerDelete::delete_authorization(
PoolSQL* pool,
int oid,
AuthRequest::Operation auth_op,
RequestAttributes& att)
{
PoolObjectSQL * object;
PoolObjectAuth perms;
if ( att.uid == 0 )
{
return SUCCESS;
}
object = pool->get(oid, true);
if ( object == 0 )
{
att.resp_id = oid;
return NO_EXISTS;
}
object->get_permissions(perms);
object->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(auth_op, perms); // <MANAGE|ADMIN> OBJECT
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
return AUTHORIZATION;
}
return SUCCESS;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void RequestManagerDelete::request_execute(xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
PoolObjectSQL * object;
string error_msg;
ErrorCode ec;
ec = delete_authorization(pool, oid, auth_op, att);
if ( ec != SUCCESS )
{
failure_response(ec, att);
return;
}
object = pool->get(oid,true);
if ( object == 0 )
{
att.resp_id = oid;
failure_response(NO_EXISTS, att);
return;
}
int rc = drop(oid, object, error_msg);
if ( rc != 0 )
{
att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " + error_msg;
failure_response(ACTION, att);
return;
}
aclm->del_resource_rules(oid, auth_object);
success_response(oid, att);
return;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int RequestManagerDelete::drop(
int oid,
PoolObjectSQL * object,
string& error_msg)
{
int cluster_id = get_cluster_id(object);
int rc = pool->drop(object, error_msg);
object->unlock();
if ( cluster_id != ClusterPool::NONE_CLUSTER_ID && rc == 0 )
{
Cluster * cluster = clpool->get(cluster_id, true);
if( cluster != 0 )
{
rc = del_from_cluster(cluster, oid, error_msg);
if ( rc < 0 )
{
cluster->unlock();
return rc;
}
clpool->update(cluster);
cluster->unlock();
}
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void TemplateDelete::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
bool recursive = false;
VMTemplate * object;
string error_msg;
vector<int> img_ids;
ErrorCode ec;
if (paramList.size() > 2)
{
recursive = xmlrpc_c::value_boolean(paramList.getBoolean(2));
}
ec = delete_authorization(pool, oid, auth_op, att);
if ( ec != SUCCESS )
{
failure_response(ec, att);
return;
}
object = static_cast<VMTemplatePool*>(pool)->get(oid, true);
if ( object == 0 )
{
att.resp_id = oid;
failure_response(NO_EXISTS, att);
return;
}
int rc = pool->drop(object, error_msg);
if (recursive)
{
img_ids = object->get_img_ids();
}
object->unlock();
if ( rc != 0 )
{
att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " + error_msg;
failure_response(ACTION, att);
return;
}
aclm->del_resource_rules(oid, auth_object);
if (recursive)
{
ErrorCode ec;
for (vector<int>::iterator it = img_ids.begin(); it != img_ids.end(); it++)
{
ec = ImageDelete::delete_img(*it, att);
if (ec != SUCCESS)
{
NebulaLog::log("ReM", Log::ERROR, failure_message(ec, att));
}
// TODO rollback?
}
}
success_response(oid, att);
return;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int HostDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
Nebula& nd = Nebula::instance();
InformationManager * im = nd.get_im();
HostPool * hpool = nd.get_hpool();
Host* host = static_cast<Host *>(object);
//Do not trigger delete event on IM if there are VMs running on the host
if ( host->get_share_running_vms() > 0 )
{
error_msg = "Can not remove a host with running VMs";
host->unlock();
return -1;
}
host->disable();
hpool->update(host);
host->unlock();
im->trigger(InformationManager::STOPMONITOR, oid);
return 0;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void ImageDelete::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
ErrorCode ec = delete_img(oid, att);
if ( ec == SUCCESS )
{
success_response(oid, att);
}
else
{
failure_response(ec, att);
}
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
Request::ErrorCode ImageDelete::delete_img(int oid, RequestAttributes& att)
{
Image * object;
string error_msg;
ErrorCode ec;
Nebula& nd = Nebula::instance();
ImageManager * imagem = nd.get_imagem();
AclManager * aclm = nd.get_aclm();
ImagePool * pool = nd.get_ipool();
PoolObjectSQL::ObjectType auth_object = PoolObjectSQL::IMAGE;
ec = delete_authorization(pool, oid, AuthRequest::MANAGE, att);
if ( ec != SUCCESS )
{
att.resp_obj = auth_object;
return ec;
}
object = pool->get(oid, false);
if ( object == 0 )
{
att.resp_id = oid;
return NO_EXISTS;
}
int rc = imagem->delete_image(oid, error_msg);
if ( rc != 0 )
{
att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " + error_msg;
return ACTION;
}
aclm->del_resource_rules(oid, auth_object);
return SUCCESS;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int GroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if ( rc == 0 )
{
aclm->del_gid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int ClusterDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if ( rc == 0 )
{
aclm->del_cid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int UserDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
set<int> group_set;
set<int>::iterator it;
User * user = static_cast<User *>(object);
group_set = user->get_groups();
if (oid == 0)
{
error_msg = "oneadmin cannot be deleted.";
object->unlock();
return -1;
}
int rc = pool->drop(object, error_msg);
object->unlock();
if ( rc == 0 )
{
Group * group;
for ( it = group_set.begin(); it != group_set.end(); it++ )
{
group = gpool->get(*it, true);
if( group == 0 )
{
continue;
}
group->del_user(oid);
gpool->update(group);
group->unlock();
}
aclm->del_uid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int ZoneDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if ( rc == 0 )
{
aclm->del_zid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int VirtualNetworkDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
VirtualNetwork * vnet = static_cast<VirtualNetwork *>(object);
if ( vnet->get_used() > 0 )
{
error_msg = "Can not remove a virtual network with leases in use";
vnet->unlock();
return -1;
}
int pvid = vnet->get_parent();
int uid = vnet->get_uid();
int gid = vnet->get_gid();
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if (pvid != -1)
{
vnet = (static_cast<VirtualNetworkPool *>(pool))->get(pvid, true);
if (vnet == 0)
{
return rc;
}
int freed = vnet->free_addr_by_owner(PoolObjectSQL::NET, oid);
pool->update(vnet);
vnet->unlock();
if (freed > 0)
{
ostringstream oss;
Template tmpl;
for (int i= 0 ; i < freed ; i++)
{
oss << " NIC = [ NETWORK_ID = " << pvid << " ]" << endl;
}
tmpl.parse_str_or_xml(oss.str(), error_msg);
Quotas::quota_del(Quotas::NETWORK, uid, gid, &tmpl);
}
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int SecurityGroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
if (object->get_oid() == 0)
{
error_msg = "The default security group (ID 0) cannot be deleted.";
object->unlock();
return -1;
}
SecurityGroup * sgroup = static_cast<SecurityGroup *>(object);
if ( sgroup->get_vms() > 0 )
{
error_msg = "The security group has VMs using it";
sgroup->unlock();
return -1;
}
return RequestManagerDelete::drop(oid, object, error_msg);
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int MarketPlaceAppDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
Nebula& nd = Nebula::instance();
MarketPlaceManager * marketm = nd.get_marketm();
MarketPlacePool * marketpool = nd.get_marketpool();
MarketPlaceApp * app = static_cast<MarketPlaceApp *>(object);
int mp_id = app->get_market_id();
app->unlock();
MarketPlace * mp = marketpool->get(mp_id, true);
if ( mp == 0 )
{
emsg = "Cannot find associated MARKETPLACE";
return -1;
}
std::string mp_name = mp->get_name();
std::string mp_data;
if ( !mp->is_action_supported(MarketPlaceApp::DELETE) )
{
emsg = "Delete disabled for market: " + mp_name;
mp->unlock();
return -1;
}
mp->to_xml(mp_data);
mp->unlock();
return marketm->delete_app(oid, mp_data, emsg);
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int MarketPlaceDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
MarketPlace * mp = static_cast<MarketPlace *>(object);
set<int> apps = mp->get_marketapp_ids();
int rc = pool->drop(object, emsg);
object->unlock();
if ( rc != 0 || apps.empty() )
{
return rc;
}
Nebula& nd = Nebula::instance();
MarketPlaceApp * app;
MarketPlaceAppPool * apppool = nd.get_apppool();
string app_error;
for ( set<int>::iterator i = apps.begin(); i != apps.end(); ++i )
{
app = apppool->get(*i, true);
if ( app == 0 )
{
continue;
}
if ( apppool->drop(app, app_error) != 0 )
{
ostringstream oss;
oss << "Cannot remove " << object_name(PoolObjectSQL::MARKETPLACEAPP)
<< " " << *i << ": " << app_error << ". ";
emsg = emsg + oss.str();
rc = -1;
}
app->unlock();
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
<commit_msg>feature #4317: Return error when a template image cannot be deleted (recursive mode)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */
/* */
/* 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 "RequestManagerDelete.h"
#include "NebulaUtil.h"
using namespace std;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
Request::ErrorCode RequestManagerDelete::delete_authorization(
PoolSQL* pool,
int oid,
AuthRequest::Operation auth_op,
RequestAttributes& att)
{
PoolObjectSQL * object;
PoolObjectAuth perms;
if ( att.uid == 0 )
{
return SUCCESS;
}
object = pool->get(oid, true);
if ( object == 0 )
{
att.resp_id = oid;
return NO_EXISTS;
}
object->get_permissions(perms);
object->unlock();
AuthRequest ar(att.uid, att.group_ids);
ar.add_auth(auth_op, perms); // <MANAGE|ADMIN> OBJECT
if (UserPool::authorize(ar) == -1)
{
att.resp_msg = ar.message;
return AUTHORIZATION;
}
return SUCCESS;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void RequestManagerDelete::request_execute(xmlrpc_c::paramList const& paramList,
RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
PoolObjectSQL * object;
string error_msg;
ErrorCode ec;
ec = delete_authorization(pool, oid, auth_op, att);
if ( ec != SUCCESS )
{
failure_response(ec, att);
return;
}
object = pool->get(oid,true);
if ( object == 0 )
{
att.resp_id = oid;
failure_response(NO_EXISTS, att);
return;
}
int rc = drop(oid, object, error_msg);
if ( rc != 0 )
{
att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " + error_msg;
failure_response(ACTION, att);
return;
}
aclm->del_resource_rules(oid, auth_object);
success_response(oid, att);
return;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int RequestManagerDelete::drop(
int oid,
PoolObjectSQL * object,
string& error_msg)
{
int cluster_id = get_cluster_id(object);
int rc = pool->drop(object, error_msg);
object->unlock();
if ( cluster_id != ClusterPool::NONE_CLUSTER_ID && rc == 0 )
{
Cluster * cluster = clpool->get(cluster_id, true);
if( cluster != 0 )
{
rc = del_from_cluster(cluster, oid, error_msg);
if ( rc < 0 )
{
cluster->unlock();
return rc;
}
clpool->update(cluster);
cluster->unlock();
}
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void TemplateDelete::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
bool recursive = false;
VMTemplate * object;
string error_msg;
vector<int> img_ids;
set<int> error_ids;
ErrorCode ec;
if (paramList.size() > 2)
{
recursive = xmlrpc_c::value_boolean(paramList.getBoolean(2));
}
ec = delete_authorization(pool, oid, auth_op, att);
if ( ec != SUCCESS )
{
failure_response(ec, att);
return;
}
object = static_cast<VMTemplatePool*>(pool)->get(oid, true);
if ( object == 0 )
{
att.resp_id = oid;
failure_response(NO_EXISTS, att);
return;
}
int rc = pool->drop(object, error_msg);
if (recursive)
{
img_ids = object->get_img_ids();
}
object->unlock();
if ( rc != 0 )
{
att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " + error_msg;
failure_response(ACTION, att);
return;
}
aclm->del_resource_rules(oid, auth_object);
if (recursive)
{
ErrorCode ec;
for (vector<int>::iterator it = img_ids.begin(); it != img_ids.end(); it++)
{
ec = ImageDelete::delete_img(*it, att);
if (ec != SUCCESS)
{
NebulaLog::log("ReM", Log::ERROR, failure_message(ec, att));
error_ids.insert(*it);
rc = -1;
}
}
}
if ( rc != 0 )
{
att.resp_msg = "Cannot delete " + object_name(PoolObjectSQL::IMAGE) +
": " + one_util::join<set<int>::iterator>(error_ids.begin(),
error_ids.end(), ',');
failure_response(ACTION, att);
return;
}
success_response(oid, att);
return;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int HostDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
Nebula& nd = Nebula::instance();
InformationManager * im = nd.get_im();
HostPool * hpool = nd.get_hpool();
Host* host = static_cast<Host *>(object);
//Do not trigger delete event on IM if there are VMs running on the host
if ( host->get_share_running_vms() > 0 )
{
error_msg = "Can not remove a host with running VMs";
host->unlock();
return -1;
}
host->disable();
hpool->update(host);
host->unlock();
im->trigger(InformationManager::STOPMONITOR, oid);
return 0;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
void ImageDelete::request_execute(
xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
int oid = xmlrpc_c::value_int(paramList.getInt(1));
ErrorCode ec = delete_img(oid, att);
if ( ec == SUCCESS )
{
success_response(oid, att);
}
else
{
failure_response(ec, att);
}
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
Request::ErrorCode ImageDelete::delete_img(int oid, RequestAttributes& att)
{
Image * object;
string error_msg;
ErrorCode ec;
Nebula& nd = Nebula::instance();
ImageManager * imagem = nd.get_imagem();
AclManager * aclm = nd.get_aclm();
ImagePool * pool = nd.get_ipool();
PoolObjectSQL::ObjectType auth_object = PoolObjectSQL::IMAGE;
ec = delete_authorization(pool, oid, AuthRequest::MANAGE, att);
if ( ec != SUCCESS )
{
att.resp_obj = auth_object;
return ec;
}
object = pool->get(oid, false);
if ( object == 0 )
{
att.resp_id = oid;
return NO_EXISTS;
}
int rc = imagem->delete_image(oid, error_msg);
if ( rc != 0 )
{
att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " + error_msg;
return ACTION;
}
aclm->del_resource_rules(oid, auth_object);
return SUCCESS;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int GroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if ( rc == 0 )
{
aclm->del_gid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int ClusterDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if ( rc == 0 )
{
aclm->del_cid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int UserDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
set<int> group_set;
set<int>::iterator it;
User * user = static_cast<User *>(object);
group_set = user->get_groups();
if (oid == 0)
{
error_msg = "oneadmin cannot be deleted.";
object->unlock();
return -1;
}
int rc = pool->drop(object, error_msg);
object->unlock();
if ( rc == 0 )
{
Group * group;
for ( it = group_set.begin(); it != group_set.end(); it++ )
{
group = gpool->get(*it, true);
if( group == 0 )
{
continue;
}
group->del_user(oid);
gpool->update(group);
group->unlock();
}
aclm->del_uid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int ZoneDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if ( rc == 0 )
{
aclm->del_zid_rules(oid);
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int VirtualNetworkDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
VirtualNetwork * vnet = static_cast<VirtualNetwork *>(object);
if ( vnet->get_used() > 0 )
{
error_msg = "Can not remove a virtual network with leases in use";
vnet->unlock();
return -1;
}
int pvid = vnet->get_parent();
int uid = vnet->get_uid();
int gid = vnet->get_gid();
int rc = RequestManagerDelete::drop(oid, object, error_msg);
if (pvid != -1)
{
vnet = (static_cast<VirtualNetworkPool *>(pool))->get(pvid, true);
if (vnet == 0)
{
return rc;
}
int freed = vnet->free_addr_by_owner(PoolObjectSQL::NET, oid);
pool->update(vnet);
vnet->unlock();
if (freed > 0)
{
ostringstream oss;
Template tmpl;
for (int i= 0 ; i < freed ; i++)
{
oss << " NIC = [ NETWORK_ID = " << pvid << " ]" << endl;
}
tmpl.parse_str_or_xml(oss.str(), error_msg);
Quotas::quota_del(Quotas::NETWORK, uid, gid, &tmpl);
}
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int SecurityGroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
if (object->get_oid() == 0)
{
error_msg = "The default security group (ID 0) cannot be deleted.";
object->unlock();
return -1;
}
SecurityGroup * sgroup = static_cast<SecurityGroup *>(object);
if ( sgroup->get_vms() > 0 )
{
error_msg = "The security group has VMs using it";
sgroup->unlock();
return -1;
}
return RequestManagerDelete::drop(oid, object, error_msg);
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int MarketPlaceAppDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
Nebula& nd = Nebula::instance();
MarketPlaceManager * marketm = nd.get_marketm();
MarketPlacePool * marketpool = nd.get_marketpool();
MarketPlaceApp * app = static_cast<MarketPlaceApp *>(object);
int mp_id = app->get_market_id();
app->unlock();
MarketPlace * mp = marketpool->get(mp_id, true);
if ( mp == 0 )
{
emsg = "Cannot find associated MARKETPLACE";
return -1;
}
std::string mp_name = mp->get_name();
std::string mp_data;
if ( !mp->is_action_supported(MarketPlaceApp::DELETE) )
{
emsg = "Delete disabled for market: " + mp_name;
mp->unlock();
return -1;
}
mp->to_xml(mp_data);
mp->unlock();
return marketm->delete_app(oid, mp_data, emsg);
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
int MarketPlaceDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
MarketPlace * mp = static_cast<MarketPlace *>(object);
set<int> apps = mp->get_marketapp_ids();
int rc = pool->drop(object, emsg);
object->unlock();
if ( rc != 0 || apps.empty() )
{
return rc;
}
Nebula& nd = Nebula::instance();
MarketPlaceApp * app;
MarketPlaceAppPool * apppool = nd.get_apppool();
string app_error;
for ( set<int>::iterator i = apps.begin(); i != apps.end(); ++i )
{
app = apppool->get(*i, true);
if ( app == 0 )
{
continue;
}
if ( apppool->drop(app, app_error) != 0 )
{
ostringstream oss;
oss << "Cannot remove " << object_name(PoolObjectSQL::MARKETPLACEAPP)
<< " " << *i << ": " << app_error << ". ";
emsg = emsg + oss.str();
rc = -1;
}
app->unlock();
}
return rc;
}
/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: invmerge.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 23:00:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include <vcl/window.hxx>
#include <tools/debug.hxx>
#include "invmerge.hxx"
//------------------------------------------------------------------
ScInvertMerger::ScInvertMerger( Window* pWindow ) :
pWin( pWindow )
{
// both rectangles empty
}
ScInvertMerger::~ScInvertMerger()
{
Flush();
}
void ScInvertMerger::Flush()
{
FlushLine();
FlushTotal();
DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" );
}
void ScInvertMerger::FlushTotal()
{
if( aTotalRect.IsEmpty() )
return; // nothing to do
pWin->Invert( aTotalRect, INVERT_HIGHLIGHT );
aTotalRect.SetEmpty();
}
void ScInvertMerger::FlushLine()
{
if( aLineRect.IsEmpty() )
return; // nothing to do
if ( aTotalRect.IsEmpty() )
{
aTotalRect = aLineRect; // start new total rect
}
else
{
if ( aLineRect.Left() == aTotalRect.Left() &&
aLineRect.Right() == aTotalRect.Right() &&
aLineRect.Top() == aTotalRect.Bottom() + 1 )
{
// extend total rect
aTotalRect.Bottom() = aLineRect.Bottom();
}
else
{
FlushTotal(); // draw old total rect
aTotalRect = aLineRect; // and start new one
}
}
aLineRect.SetEmpty();
}
void ScInvertMerger::AddRect( const Rectangle& rRect )
{
if ( aLineRect.IsEmpty() )
{
aLineRect = rRect; // start new line rect
}
else
{
Rectangle aJustified = rRect;
if ( rRect.Left() > rRect.Right() ) // switch for RTL layout
{
aJustified.Left() = rRect.Right();
aJustified.Right() = rRect.Left();
}
BOOL bDone = FALSE;
if ( aJustified.Top() == aLineRect.Top() &&
aJustified.Bottom() == aLineRect.Bottom() )
{
// try to extend line rect
if ( aJustified.Left() == aLineRect.Right() + 1 )
{
aLineRect.Right() = aJustified.Right();
bDone = TRUE;
}
else if ( aJustified.Right() + 1 == aLineRect.Left() ) // for RTL layout
{
aLineRect.Left() = aJustified.Left();
bDone = TRUE;
}
}
if (!bDone)
{
FlushLine(); // use old line rect for total rect
aLineRect = aJustified; // and start new one
}
}
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.3.214); FILE MERGED 2006/07/12 10:03:05 kaib 1.3.214.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: invmerge.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-07-21 15:02:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <vcl/window.hxx>
#include <tools/debug.hxx>
#include "invmerge.hxx"
//------------------------------------------------------------------
ScInvertMerger::ScInvertMerger( Window* pWindow ) :
pWin( pWindow )
{
// both rectangles empty
}
ScInvertMerger::~ScInvertMerger()
{
Flush();
}
void ScInvertMerger::Flush()
{
FlushLine();
FlushTotal();
DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" );
}
void ScInvertMerger::FlushTotal()
{
if( aTotalRect.IsEmpty() )
return; // nothing to do
pWin->Invert( aTotalRect, INVERT_HIGHLIGHT );
aTotalRect.SetEmpty();
}
void ScInvertMerger::FlushLine()
{
if( aLineRect.IsEmpty() )
return; // nothing to do
if ( aTotalRect.IsEmpty() )
{
aTotalRect = aLineRect; // start new total rect
}
else
{
if ( aLineRect.Left() == aTotalRect.Left() &&
aLineRect.Right() == aTotalRect.Right() &&
aLineRect.Top() == aTotalRect.Bottom() + 1 )
{
// extend total rect
aTotalRect.Bottom() = aLineRect.Bottom();
}
else
{
FlushTotal(); // draw old total rect
aTotalRect = aLineRect; // and start new one
}
}
aLineRect.SetEmpty();
}
void ScInvertMerger::AddRect( const Rectangle& rRect )
{
if ( aLineRect.IsEmpty() )
{
aLineRect = rRect; // start new line rect
}
else
{
Rectangle aJustified = rRect;
if ( rRect.Left() > rRect.Right() ) // switch for RTL layout
{
aJustified.Left() = rRect.Right();
aJustified.Right() = rRect.Left();
}
BOOL bDone = FALSE;
if ( aJustified.Top() == aLineRect.Top() &&
aJustified.Bottom() == aLineRect.Bottom() )
{
// try to extend line rect
if ( aJustified.Left() == aLineRect.Right() + 1 )
{
aLineRect.Right() = aJustified.Right();
bDone = TRUE;
}
else if ( aJustified.Right() + 1 == aLineRect.Left() ) // for RTL layout
{
aLineRect.Left() = aJustified.Left();
bDone = TRUE;
}
}
if (!bDone)
{
FlushLine(); // use old line rect for total rect
aLineRect = aJustified; // and start new one
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Removed unnecessary std::move<commit_after><|endoftext|>
|
<commit_before>//
// GridZone.cpp
// Created by Matt Kaufmann on 01/07/14.
//
#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridZone.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
unsigned int GridZone::componentTypeId = COMPONENT_TYPE_ID_GRID_ZONE;
GridZone::GridZone() : Component() {
this->init();
}
GridZone::GridZone(Object* object_) : Component(object_) {
this->init();
}
GridZone::~GridZone() {
this->destroy();
}
void GridZone::GetZoneBounds(int& west, int& east, int& south, int& north) {
Transform* trans = this->GetObject()->GetComponent<Transform>();
int centerX, centerZ;
SINGLETONS->GetGridManager()->GetGrid()->GetCoordinates(centerX, centerZ, trans->GetPositionWorld());
glm::vec3 forward = trans->GetForward();
// Determine the rough orientation of the object.
if (abs(forward.z) >= abs(forward.x)) {
if (forward.z >= 0.0f) {
west = centerX + this->westBound;
east = centerX + this->eastBound;
south = centerZ + this->southBound;
north = centerZ + this->northBound;
}
else {
west = centerX - this->eastBound;
east = centerX - this->westBound;
south = centerZ - this->northBound;
north = centerZ - this->southBound;
}
}
else {
if (forward.x >= 0.0f) {
west = centerX - this->northBound;
east = centerX - this->southBound;
south = centerZ + this->westBound;
north = centerZ + this->eastBound;
}
else {
west = centerX + this->southBound;
east = centerX + this->northBound;
south = centerZ - this->eastBound;
north = centerZ - this->westBound;
}
}
}
void GridZone::SetZoneBounds(int xMin, int zMin, int xMax, int zMax) {
if (xMin <= xMax) {
this->westBound = xMin;
this->eastBound = xMax;
}
else {
this->westBound = xMax;
this->eastBound = xMin;
}
if (zMin <= zMax) {
this->southBound = zMin;
this->northBound = zMax;
}
else {
this->southBound = zMax;
this->northBound = zMin;
}
}
bool GridZone::IsCellWithinZone(GridCell* cell) {
if (cell != nullptr) {
int west, east, south, north;
this->GetZoneBounds(west, east, south, north);
return ((cell->x >= west) && (cell->x <= east) && (cell->z >= south) && (cell->z <= north));
}
return false;
}
void GridZone::init() {
this->zoneType = GRID_ZONE_TYPE_UNKNOWN;
this->westBound = -1;
this->eastBound = -1;
this->southBound = -1;
this->northBound = -1;
SINGLETONS->GetGridManager()->GetGrid()->AddGridZone(this->GetObject()->GetId());
}
void GridZone::destroy() {
this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}
<commit_msg>GridZone coordinates are now calculated correctly based on the object's world orientation<commit_after>//
// GridZone.cpp
// Created by Matt Kaufmann on 01/07/14.
//
#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridZone.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
unsigned int GridZone::componentTypeId = COMPONENT_TYPE_ID_GRID_ZONE;
GridZone::GridZone() : Component() {
this->init();
}
GridZone::GridZone(Object* object_) : Component(object_) {
this->init();
}
GridZone::~GridZone() {
this->destroy();
}
void GridZone::GetZoneBounds(int& west, int& east, int& south, int& north) {
Transform* trans = this->GetObject()->GetComponent<Transform>();
int centerX, centerZ;
SINGLETONS->GetGridManager()->GetGrid()->GetCoordinates(centerX, centerZ, trans->GetPositionWorld());
glm::vec3 forward = QuaternionForwardVector(trans->GetOrientationWorld());
// Determine the rough orientation of the object.
if (abs(forward.z) >= abs(forward.x)) {
if (forward.z >= 0.0f) {
west = centerX + this->westBound;
east = centerX + this->eastBound;
south = centerZ + this->southBound;
north = centerZ + this->northBound;
}
else {
west = centerX - this->eastBound;
east = centerX - this->westBound;
south = centerZ - this->northBound;
north = centerZ - this->southBound;
}
}
else {
if (forward.x >= 0.0f) {
west = centerX - this->northBound;
east = centerX - this->southBound;
south = centerZ + this->westBound;
north = centerZ + this->eastBound;
}
else {
west = centerX + this->southBound;
east = centerX + this->northBound;
south = centerZ - this->eastBound;
north = centerZ - this->westBound;
}
}
}
void GridZone::SetZoneBounds(int xMin, int zMin, int xMax, int zMax) {
if (xMin <= xMax) {
this->westBound = xMin;
this->eastBound = xMax;
}
else {
this->westBound = xMax;
this->eastBound = xMin;
}
if (zMin <= zMax) {
this->southBound = zMin;
this->northBound = zMax;
}
else {
this->southBound = zMax;
this->northBound = zMin;
}
}
bool GridZone::IsCellWithinZone(GridCell* cell) {
if (cell != nullptr) {
int west, east, south, north;
this->GetZoneBounds(west, east, south, north);
return ((cell->x >= west) && (cell->x <= east) && (cell->z >= south) && (cell->z <= north));
}
return false;
}
void GridZone::init() {
this->zoneType = GRID_ZONE_TYPE_UNKNOWN;
this->westBound = -1;
this->eastBound = -1;
this->southBound = -1;
this->northBound = -1;
SINGLETONS->GetGridManager()->GetGrid()->AddGridZone(this->GetObject()->GetId());
}
void GridZone::destroy() {
this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <iostream>
#include <SFML/Graphics.hpp>
#include "context.hpp"
#include "../debug.hpp"
static sf::Font font;
static sf::Text debugText;
static sf::RenderWindow window;
static sf::Texture displayTexture;
static sf::Sprite displaySprite; // SFML needs a sprite to render a texture
static uint8_t* displayBuffer = nullptr;
static float speedInput = 1.0f;
// Placeholder
uint8_t pixels[160 * 144 * 4];
uint8_t* joypad = nullptr;
// Placeholder
bool prevShouldHalt = false;
bool prevShouldStep = false;
bool Context::SetupContext (const int scale = 1) {
font.loadFromFile("../resources/fonts/OpenSans-Bold.ttf");
debugText.setFont(font);
debugText.setColor(sf::Color::Magenta);
debugText.setCharacterSize(15);
debugText.setString("Debug :D");
window.create(sf::VideoMode(160 * scale, 144 * scale), "Hi, I'm a secret message :D");
displayTexture.create(160, 144);
displayTexture.setSmooth(false);
displaySprite.setTexture(displayTexture);
sf::Vector2u textureSize = displayTexture.getSize();
sf::Vector2u windowSize = window.getSize();
float scaleX = (float) windowSize.x / textureSize.x;
float scaleY = (float) windowSize.y / textureSize.y;
displaySprite.setScale(scaleX, scaleY);
return true;
}
void Context::DestroyContext () {
if (window.isOpen())
window.close();
}
void Context::HandleEvents () {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
else if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Escape) {
window.close();
}
else if (event.key.code == sf::Keyboard::Num0) {
speedInput = 1.0f;
}
else if (event.key.code == sf::Keyboard::Num9) {
speedInput = 0.5f;
}
else if (event.key.code == sf::Keyboard::Num8) {
speedInput = 0.25f;
}
else if (event.key.code == sf::Keyboard::Num7) {
speedInput = 0.1f;
}
else if (event.key.code == sf::Keyboard::Num6) {
speedInput = 0.05f;
}
else if (event.key.code == sf::Keyboard::Num5) {
speedInput = 0.01f;
}
}
}
joypad[0] = sf::Keyboard::isKeyPressed(sf::Keyboard::D);
joypad[1] = sf::Keyboard::isKeyPressed(sf::Keyboard::A);
joypad[2] = sf::Keyboard::isKeyPressed(sf::Keyboard::W);
joypad[3] = sf::Keyboard::isKeyPressed(sf::Keyboard::S);
joypad[4] = sf::Keyboard::isKeyPressed(sf::Keyboard::H);
joypad[5] = sf::Keyboard::isKeyPressed(sf::Keyboard::G);
joypad[6] = sf::Keyboard::isKeyPressed(sf::Keyboard::B);
joypad[7] = sf::Keyboard::isKeyPressed(sf::Keyboard::N);
}
void Context::RenderDebugText () {
debugText.setPosition(0, 0);
window.draw(debugText);
std::string inputDebugString =
"Right: " + std::string(joypad[0] ? "1" : "0") + "\n" +
"Left: " + std::string(joypad[1] ? "1" : "0") + "\n" +
"Up: " + std::string(joypad[2] ? "1" : "0") + "\n" +
"Down: " + std::string(joypad[3] ? "1" : "0") + "\n" +
"A: " + std::string(joypad[4] ? "1" : "0") + "\n" +
"B: " + std::string(joypad[5] ? "1" : "0") + "\n" +
"Select: " + std::string(joypad[6] ? "1" : "0") + "\n" +
"Start: " + std::string(joypad[7] ? "1" : "0");
debugText.setString(inputDebugString);
debugText.setPosition(100, 0);
window.draw(debugText);
}
void Context::RenderDisplay () {
window.clear();
CopyDisplayBuffer(displayBuffer);
displayTexture.update(pixels);
window.draw(displaySprite);
RenderDebugText();
window.display();
}
void Context::SetJoypadBuffer (uint8_t* const buffer) {
assert(buffer != nullptr);
joypad = buffer;
}
// TODO: Use opengl texture binding and GL_R8UI color format to use the VRAM di-
//rectly as a pixel buffer.
// http://fr.sfml-dev.org/forums/index.php?topic=17847.0
// http://www.sfml-dev.org/documentation/2.4.1/classsf_1_1Texture.php
void Context::SetDisplayBuffer (uint8_t* const buffer) {
assert(buffer != nullptr);
displayBuffer = buffer;
}
// HACK: Temporary solution
// Currently, Instead of accessing the VRAM memory directly, we convert it's contents to a
//color format that SFML can understand.
void Context::CopyDisplayBuffer (uint8_t* const buffer) {
for (size_t i = 0; i < 160 * 144 * 4; i += 4) {
int luminosity = 255 - ((buffer[i / 4] + 1) * 64 - 1);
pixels[i] = luminosity;
pixels[i + 1] = luminosity;
pixels[i + 2] = luminosity;
pixels[i + 3] = 255;
}
}
void Context::SetTitle (std::string title) {
window.setTitle(title);
}
bool Context::IsOpen () {
return window.isOpen();
}
bool Context::ShouldHalt () {
bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::P);
bool prev = prevShouldHalt;
prevShouldHalt = curr;
return curr ^ prev && curr;
}
bool Context::ShouldStep () {
bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::O);
bool prev = prevShouldStep;
prevShouldStep = curr;
return curr ^ prev && curr;
}
void Context::SetDebugText (std::string text) {
debugText.setString(text);
}
float Context::GetSpeedInput () {
return speedInput;
}
<commit_msg>Changed boring greyscale color palette to cool retro green gameboy palette<commit_after>#include <cstdlib>
#include <iostream>
#include <SFML/Graphics.hpp>
// #include <SFML/Vector3.hpp>
// #include <Vector3.hpp>
#include "context.hpp"
#include "../debug.hpp"
static sf::Font font;
static sf::Text debugText;
static sf::RenderWindow window;
static sf::Texture displayTexture;
static sf::Sprite displaySprite; // SFML needs a sprite to render a texture
static uint8_t* displayBuffer = nullptr;
static float speedInput = 1.0f;
// Placeholder
uint8_t pixels[160 * 144 * 4];
uint8_t* joypad = nullptr;
// Placeholder
bool prevShouldHalt = false;
bool prevShouldStep = false;
bool Context::SetupContext (const int scale = 1) {
font.loadFromFile("../resources/fonts/OpenSans-Bold.ttf");
debugText.setFont(font);
debugText.setColor(sf::Color::Magenta);
debugText.setCharacterSize(15);
debugText.setString("Debug :D");
window.create(sf::VideoMode(160 * scale, 144 * scale), "Hi, I'm a secret message :D");
displayTexture.create(160, 144);
displayTexture.setSmooth(false);
displaySprite.setTexture(displayTexture);
sf::Vector2u textureSize = displayTexture.getSize();
sf::Vector2u windowSize = window.getSize();
float scaleX = (float) windowSize.x / textureSize.x;
float scaleY = (float) windowSize.y / textureSize.y;
displaySprite.setScale(scaleX, scaleY);
return true;
}
void Context::DestroyContext () {
if (window.isOpen())
window.close();
}
void Context::HandleEvents () {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
else if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Escape) {
window.close();
}
else if (event.key.code == sf::Keyboard::Num0) {
speedInput = 1.0f;
}
else if (event.key.code == sf::Keyboard::Num9) {
speedInput = 0.5f;
}
else if (event.key.code == sf::Keyboard::Num8) {
speedInput = 0.25f;
}
else if (event.key.code == sf::Keyboard::Num7) {
speedInput = 0.1f;
}
else if (event.key.code == sf::Keyboard::Num6) {
speedInput = 0.05f;
}
else if (event.key.code == sf::Keyboard::Num5) {
speedInput = 0.01f;
}
}
}
joypad[0] = sf::Keyboard::isKeyPressed(sf::Keyboard::D);
joypad[1] = sf::Keyboard::isKeyPressed(sf::Keyboard::A);
joypad[2] = sf::Keyboard::isKeyPressed(sf::Keyboard::W);
joypad[3] = sf::Keyboard::isKeyPressed(sf::Keyboard::S);
joypad[4] = sf::Keyboard::isKeyPressed(sf::Keyboard::H);
joypad[5] = sf::Keyboard::isKeyPressed(sf::Keyboard::G);
joypad[6] = sf::Keyboard::isKeyPressed(sf::Keyboard::B);
joypad[7] = sf::Keyboard::isKeyPressed(sf::Keyboard::N);
}
void Context::RenderDebugText () {
debugText.setPosition(0, 0);
window.draw(debugText);
std::string inputDebugString =
"Right: " + std::string(joypad[0] ? "1" : "0") + "\n" +
"Left: " + std::string(joypad[1] ? "1" : "0") + "\n" +
"Up: " + std::string(joypad[2] ? "1" : "0") + "\n" +
"Down: " + std::string(joypad[3] ? "1" : "0") + "\n" +
"A: " + std::string(joypad[4] ? "1" : "0") + "\n" +
"B: " + std::string(joypad[5] ? "1" : "0") + "\n" +
"Select: " + std::string(joypad[6] ? "1" : "0") + "\n" +
"Start: " + std::string(joypad[7] ? "1" : "0");
debugText.setString(inputDebugString);
debugText.setPosition(100, 0);
window.draw(debugText);
}
void Context::RenderDisplay () {
window.clear();
CopyDisplayBuffer(displayBuffer);
displayTexture.update(pixels);
window.draw(displaySprite);
RenderDebugText();
window.display();
}
void Context::SetJoypadBuffer (uint8_t* const buffer) {
assert(buffer != nullptr);
joypad = buffer;
}
// TODO: Use opengl texture binding and GL_R8UI color format to use the VRAM di-
//rectly as a pixel buffer.
// http://fr.sfml-dev.org/forums/index.php?topic=17847.0
// http://www.sfml-dev.org/documentation/2.4.1/classsf_1_1Texture.php
void Context::SetDisplayBuffer (uint8_t* const buffer) {
assert(buffer != nullptr);
displayBuffer = buffer;
}
// HACK: Temporary solution
// Currently, Instead of accessing the VRAM memory directly, we convert it's contents to a
//color format that SFML can understand.
void Context::CopyDisplayBuffer (uint8_t* const buffer) {
for (size_t i = 0; i < 160 * 144 * 4; i += 4) {
sf::Vector3<uint8_t> shades[] = {
sf::Vector3<uint8_t>(155, 188, 15),
sf::Vector3<uint8_t>(139, 172, 15),
sf::Vector3<uint8_t>( 48, 98, 48),
sf::Vector3<uint8_t>( 15, 56, 15),
};
pixels[i] = shades[buffer[i / 4]].x;
pixels[i + 1] = shades[buffer[i / 4]].y;
pixels[i + 2] = shades[buffer[i / 4]].z;
pixels[i + 3] = 255;
}
}
void Context::SetTitle (std::string title) {
window.setTitle(title);
}
bool Context::IsOpen () {
return window.isOpen();
}
bool Context::ShouldHalt () {
bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::P);
bool prev = prevShouldHalt;
prevShouldHalt = curr;
return curr ^ prev && curr;
}
bool Context::ShouldStep () {
bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::O);
bool prev = prevShouldStep;
prevShouldStep = curr;
return curr ^ prev && curr;
}
void Context::SetDebugText (std::string text) {
debugText.setString(text);
}
float Context::GetSpeedInput () {
return speedInput;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: recursionhelper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:51:05 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef INCLUDED_RECURSIONHELPER_HXX
#define INCLUDED_RECURSIONHELPER_HXX
#include <list>
#include <stack>
#include <tools/solar.h>
class ScFormulaCell;
struct ScFormulaRecursionEntry
{
ScFormulaCell* pCell;
BOOL bOldRunning;
double fPreviousResult;
ScFormulaRecursionEntry( ScFormulaCell* p, BOOL b, double f ) : pCell(p),
bOldRunning(b),
fPreviousResult(f)
{}
};
typedef ::std::list< ScFormulaRecursionEntry > ScFormulaRecursionList;
class ScRecursionHelper
{
typedef ::std::stack< ScFormulaCell* > ScRecursionInIterationStack;
ScFormulaRecursionList aRecursionFormulas;
ScFormulaRecursionList::iterator aInsertPos;
ScFormulaRecursionList::iterator aLastIterationStart;
ScRecursionInIterationStack aRecursionInIterationStack;
USHORT nRecursionCount;
USHORT nIteration;
bool bInRecursionReturn;
bool bDoingRecursion;
bool bInIterationReturn;
bool bConverging;
void Init()
{
nRecursionCount = 0;
bInRecursionReturn = bDoingRecursion = bInIterationReturn = false;
aInsertPos = GetEnd();
ResetIteration();
}
void ResetIteration()
{
aLastIterationStart = GetEnd();
nIteration = 0;
bConverging = false;
}
public:
ScRecursionHelper() { Init(); }
USHORT GetRecursionCount() const { return nRecursionCount; }
void IncRecursionCount() { ++nRecursionCount; }
void DecRecursionCount() { --nRecursionCount; }
/// A pure recursion return, no iteration.
bool IsInRecursionReturn() const { return bInRecursionReturn &&
!bInIterationReturn; }
void SetInRecursionReturn( bool b )
{
// Do not use IsInRecursionReturn() here, it decouples iteration.
if (b && !bInRecursionReturn)
aInsertPos = aRecursionFormulas.begin();
bInRecursionReturn = b;
}
bool IsDoingRecursion() const { return bDoingRecursion; }
void SetDoingRecursion( bool b ) { bDoingRecursion = b; }
void Insert( ScFormulaCell* p, BOOL bOldRunning, double fResult )
{
aRecursionFormulas.insert( aInsertPos, ScFormulaRecursionEntry( p,
bOldRunning, fResult));
}
ScFormulaRecursionList::iterator GetStart()
{
return aRecursionFormulas.begin();
}
ScFormulaRecursionList::iterator GetEnd()
{
return aRecursionFormulas.end();
}
bool IsInIterationReturn() const { return bInIterationReturn; }
void SetInIterationReturn( bool b )
{
// An iteration return is always coupled to a recursion return.
SetInRecursionReturn( b);
bInIterationReturn = b;
}
bool IsDoingIteration() const { return nIteration > 0; }
USHORT GetIteration() const { return nIteration; }
bool & GetConvergingReference() { return bConverging; }
void StartIteration()
{
SetInIterationReturn( false);
nIteration = 1;
bConverging = false;
aLastIterationStart = GetIterationStart();
}
void ResumeIteration()
{
SetInIterationReturn( false);
aLastIterationStart = GetIterationStart();
}
void IncIteration() { ++nIteration; }
void EndIteration()
{
aRecursionFormulas.erase( GetIterationStart(), GetIterationEnd());
ResetIteration();
}
ScFormulaRecursionList::iterator GetLastIterationStart() { return aLastIterationStart; }
ScFormulaRecursionList::iterator GetIterationStart() { return GetStart(); }
ScFormulaRecursionList::iterator GetIterationEnd() { return GetEnd(); }
/** Any return, recursion or iteration, iteration is always coupled with
recursion. */
bool IsInReturn() const { return bInRecursionReturn; }
const ScFormulaRecursionList& GetList() const { return aRecursionFormulas; }
ScFormulaRecursionList& GetList() { return aRecursionFormulas; }
ScRecursionInIterationStack& GetRecursionInIterationStack() { return aRecursionInIterationStack; }
void Clear()
{
aRecursionFormulas.clear();
while (!aRecursionInIterationStack.empty())
aRecursionInIterationStack.pop();
Init();
}
};
#endif // INCLUDED_RECURSIONHELPER_HXX
<commit_msg>INTEGRATION: CWS dr41 (1.2.118); FILE MERGED 2005/10/04 21:05:54 dr 1.2.118.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/07 11:11:50 er 1.2.118.1: #i54276# include string results in iteration convergence tests<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: recursionhelper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-10-21 11:52:08 $
*
* 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 INCLUDED_RECURSIONHELPER_HXX
#define INCLUDED_RECURSIONHELPER_HXX
#include <list>
#include <stack>
#include <tools/solar.h>
class ScFormulaCell;
struct ScFormulaRecursionEntry
{
ScFormulaCell* pCell;
BOOL bOldRunning;
BOOL bPreviousNumeric;
double fPreviousResult;
String aPreviousString;
ScFormulaRecursionEntry( ScFormulaCell* p, BOOL bR, BOOL bN, double f,
const String& rS ) : pCell(p), bOldRunning(bR),
bPreviousNumeric(bN), fPreviousResult(f)
{
if (!bPreviousNumeric)
aPreviousString = rS;
}
};
typedef ::std::list< ScFormulaRecursionEntry > ScFormulaRecursionList;
class ScRecursionHelper
{
typedef ::std::stack< ScFormulaCell* > ScRecursionInIterationStack;
ScFormulaRecursionList aRecursionFormulas;
ScFormulaRecursionList::iterator aInsertPos;
ScFormulaRecursionList::iterator aLastIterationStart;
ScRecursionInIterationStack aRecursionInIterationStack;
USHORT nRecursionCount;
USHORT nIteration;
bool bInRecursionReturn;
bool bDoingRecursion;
bool bInIterationReturn;
bool bConverging;
void Init()
{
nRecursionCount = 0;
bInRecursionReturn = bDoingRecursion = bInIterationReturn = false;
aInsertPos = GetEnd();
ResetIteration();
}
void ResetIteration()
{
aLastIterationStart = GetEnd();
nIteration = 0;
bConverging = false;
}
public:
ScRecursionHelper() { Init(); }
USHORT GetRecursionCount() const { return nRecursionCount; }
void IncRecursionCount() { ++nRecursionCount; }
void DecRecursionCount() { --nRecursionCount; }
/// A pure recursion return, no iteration.
bool IsInRecursionReturn() const { return bInRecursionReturn &&
!bInIterationReturn; }
void SetInRecursionReturn( bool b )
{
// Do not use IsInRecursionReturn() here, it decouples iteration.
if (b && !bInRecursionReturn)
aInsertPos = aRecursionFormulas.begin();
bInRecursionReturn = b;
}
bool IsDoingRecursion() const { return bDoingRecursion; }
void SetDoingRecursion( bool b ) { bDoingRecursion = b; }
void Insert( ScFormulaCell* p, BOOL bOldRunning, BOOL bNumeric,
double fResult, const String& rStrResult )
{
aRecursionFormulas.insert( aInsertPos, ScFormulaRecursionEntry( p,
bOldRunning, bNumeric, fResult, rStrResult));
}
ScFormulaRecursionList::iterator GetStart()
{
return aRecursionFormulas.begin();
}
ScFormulaRecursionList::iterator GetEnd()
{
return aRecursionFormulas.end();
}
bool IsInIterationReturn() const { return bInIterationReturn; }
void SetInIterationReturn( bool b )
{
// An iteration return is always coupled to a recursion return.
SetInRecursionReturn( b);
bInIterationReturn = b;
}
bool IsDoingIteration() const { return nIteration > 0; }
USHORT GetIteration() const { return nIteration; }
bool & GetConvergingReference() { return bConverging; }
void StartIteration()
{
SetInIterationReturn( false);
nIteration = 1;
bConverging = false;
aLastIterationStart = GetIterationStart();
}
void ResumeIteration()
{
SetInIterationReturn( false);
aLastIterationStart = GetIterationStart();
}
void IncIteration() { ++nIteration; }
void EndIteration()
{
aRecursionFormulas.erase( GetIterationStart(), GetIterationEnd());
ResetIteration();
}
ScFormulaRecursionList::iterator GetLastIterationStart() { return aLastIterationStart; }
ScFormulaRecursionList::iterator GetIterationStart() { return GetStart(); }
ScFormulaRecursionList::iterator GetIterationEnd() { return GetEnd(); }
/** Any return, recursion or iteration, iteration is always coupled with
recursion. */
bool IsInReturn() const { return bInRecursionReturn; }
const ScFormulaRecursionList& GetList() const { return aRecursionFormulas; }
ScFormulaRecursionList& GetList() { return aRecursionFormulas; }
ScRecursionInIterationStack& GetRecursionInIterationStack() { return aRecursionInIterationStack; }
void Clear()
{
aRecursionFormulas.clear();
while (!aRecursionInIterationStack.empty())
aRecursionInIterationStack.pop();
Init();
}
};
#endif // INCLUDED_RECURSIONHELPER_HXX
<|endoftext|>
|
<commit_before><commit_msg>Actually add new topic to list of topics in producer<commit_after><|endoftext|>
|
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file HitFinderTools.h
*/
#include "HitFinderTools.h"
using namespace std;
vector<JPetHit> HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){
// This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit
vector<JPetHit> hits;
for (auto scintillator : allSignalsInTimeWindow) {
auto sideA = scintillator.second.first;
auto sideB = scintillator.second.second;
if(sideA.size() > 0 and sideB.size() > 0){
for(auto signalA : sideA){
for(auto signalB : sideB){
if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow /*ps*/){
JPetHit hit;
hit.setSignalA(signalA);
hit.setSignalB(signalB);
hit.setTime( (signalA.getTime() + signalB.getTime())/2.0 );
hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin());
hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot());
hits.push_back(hit);
}
}
}
}
}
return hits;
}
<commit_msg>Sort signals<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file HitFinderTools.h
*/
#include "HitFinderTools.h"
using namespace std;
vector<JPetHit> HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){
// This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit
vector<JPetHit> hits;
for (auto scintillator : allSignalsInTimeWindow) {
auto sideA = scintillator.second.first;
auto sideB = scintillator.second.second;
if(sideA.size() > 0 and sideB.size() > 0){
std::sort(sideA.begin(), sideA.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();});
std::sort(sideB.begin(), sideB.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();});
for(auto signalA : sideA){
for(auto signalB : sideB){
if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow && (signalA.getTime() - signalB.getTime()) < timeDifferenceWindow/*ps*/){
JPetHit hit;
hit.setSignalA(signalA);
hit.setSignalB(signalB);
hit.setTime( (signalA.getTime() + signalB.getTime())/2.0 );
hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin());
hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot());
hits.push_back(hit);
}
}
}
}
}
return hits;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is added by mcw.
*/
#include <sal/config.h>
#include <unotest/filters-test.hxx>
#include <test/bootstrapfixture.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>
#include "scdll.hxx"
#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/stritem.hxx>
#define TEST_BUG_FILES 0
#include "helper/qahelper.hxx"
#include "calcconfig.hxx"
#include "interpre.hxx"
#include "docsh.hxx"
#include "postit.hxx"
#include "patattr.hxx"
#include "scitems.hxx"
#include "document.hxx"
#include "cellform.hxx"
#include "drwlayer.hxx"
#include "userdat.hxx"
#include "formulacell.hxx"
#include <svx/svdpage.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
/* Implementation of Filters test */
class ScOpenclTest
: public test::FiltersTest
, public ScBootstrapFixture
{
public:
ScOpenclTest();
void enableOpenCL(ScDocShell* pShell);
void SetEnv();
virtual void setUp();
virtual void tearDown();
virtual bool load( const OUString &rFilter, const OUString &rURL,
const OUString &rUserData, unsigned int nFilterFlags,
unsigned int nClipboardID, unsigned int nFilterVersion);
void testSharedFormulaXLS();
void testSharedFormulaXLSGroundWater();
void testSharedFormulaXLSStockHistory();
void testFinacialFormula();
CPPUNIT_TEST_SUITE(ScOpenclTest);
CPPUNIT_TEST(testSharedFormulaXLS);
CPPUNIT_TEST(testSharedFormulaXLSGroundWater);
CPPUNIT_TEST(testSharedFormulaXLSStockHistory);
CPPUNIT_TEST(testFinacialFormula);
CPPUNIT_TEST_SUITE_END();
private:
uno::Reference<uno::XInterface> m_xCalcComponent;
};
bool ScOpenclTest::load(const OUString &rFilter, const OUString &rURL,
const OUString &rUserData, unsigned int nFilterFlags,
unsigned int nClipboardID, unsigned int nFilterVersion)
{
ScDocShellRef xDocShRef = ScBootstrapFixture::load(rURL, rFilter, rUserData,
OUString(), nFilterFlags, nClipboardID, nFilterVersion );
bool bLoaded = xDocShRef.Is();
//reference counting of ScDocShellRef is very confused.
if (bLoaded)
xDocShRef->DoClose();
return bLoaded;
}
void ScOpenclTest::SetEnv()
{
#ifdef WIN32
char *newpathfull = (char *)malloc(1024);
newpathfull= "PATH=;C:\\Program Files (x86)\\AMD APP\\bin\\x86_64;";
putenv(newpathfull);
#else
return;
#endif
}
void ScOpenclTest::enableOpenCL(ScDocShell* pShell)
{
ScModule* pScMod = SC_MOD();
ScFormulaOptions rOpt = pScMod->GetFormulaOptions();
ScCalcConfig maSavedConfig = rOpt.GetCalcConfig();
maSavedConfig.mbOpenCLEnabled = true;
rOpt.SetCalcConfig(maSavedConfig);
pShell->SetFormulaOptions(rOpt);
}
void ScOpenclTest::testSharedFormulaXLSStockHistory()
{
#if 1
ScDocShellRef xDocSh = loadDoc("stock-history.", XLS);
enableOpenCL(xDocSh);
ScDocument* pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc);
xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("stock-history.", XLS);
ScDocument* pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
for (SCROW i = 33; i < 44; ++i)
{ // Cell H34:H44 in S&P 500 (tab 1)
double fLibre = pDoc->GetValue(ScAddress(7, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(7, i, 1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel);
}
for (SCROW i = 33; i < 44; ++i)
{ // Cell J34:J44 in S&P 500 (tab 1)
double fLibre = pDoc->GetValue(ScAddress(9, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(9, i, 1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel);
}
xDocSh->DoClose();
xDocShRes->DoClose();
#endif
}
void ScOpenclTest::testSharedFormulaXLSGroundWater()
{
ScDocShellRef xDocSh = loadDoc("ground-water-daily.", XLS);
enableOpenCL(xDocSh);
ScDocument* pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc);
xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("ground-water-daily.", XLS);
ScDocument* pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
for (SCROW i = 5; i <= 77; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(11,i,1));
double fExcel = pDocRes->GetValue(ScAddress(11,i,1));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
xDocSh->DoClose();
xDocShRes->DoClose();
}
void ScOpenclTest::testSharedFormulaXLS()
{
ScDocShellRef xDocSh = loadDoc("sum_ex.", XLS);
enableOpenCL(xDocSh);
ScDocument *pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc);
xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("sum_ex.", XLS);
ScDocument *pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
// AMLOEXT-5
for (SCROW i = 0; i < 5; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-6
for (SCROW i = 6; i < 14; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-8
for (SCROW i = 15; i < 18; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-10
for (SCROW i = 19; i < 22; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-9
for (SCROW i = 23; i < 25; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
//double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
// There seems to be a bug in LibreOffice beta
CPPUNIT_ASSERT_EQUAL(/*fExcel*/ 60.0, fLibre);
}
// AMLOEXT-9
for (SCROW i = 25; i < 27; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-11
for (SCROW i = 28; i < 35; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-11; workaround for a Calc beta bug
CPPUNIT_ASSERT_EQUAL(25.0, pDoc->GetValue(ScAddress(2, 35, 0)));
CPPUNIT_ASSERT_EQUAL(24.0, pDoc->GetValue(ScAddress(2, 36, 0)));
// AMLOEXT-12
for (SCROW i = 38; i < 43; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-14
for (SCROW i = 5; i < 10; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(5, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(5, i, 1));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-15, AMLOEXT-16, and AMLOEXT-17
for (SCROW i = 5; i < 10; ++i)
{
for (SCCOL j = 6; j < 11; ++j)
{
double fLibre = pDoc->GetValue(ScAddress(j, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(j, i, 1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre,
fabs(fExcel*0.0001));
}
}
xDocSh->DoClose();
xDocShRes->DoClose();
}
void ScOpenclTest::testFinacialFormula()
{
ScDocShellRef xDocSh = loadDoc("FinancialFormulaTest.", XLS);
enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("FinancialFormulaTest.", XLS);
ScDocument* pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
for (SCROW i = 1; i <= 10; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2,i,0));
double fExcel = pDocRes->GetValue(ScAddress(2,i,0));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel));
}
// AMLOEXT-22
for (SCROW i = 1; i <= 10; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(6,i,1));
double fExcel = pDocRes->GetValue(ScAddress(6,i,1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel));
}
xDocSh->DoClose();
xDocShRes->DoClose();
}
ScOpenclTest::ScOpenclTest()
: ScBootstrapFixture( "/sc/qa/unit/data" )
{
}
void ScOpenclTest::setUp()
{
test::BootstrapFixture::setUp();
SetEnv();
// This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,
// which is a private symbol to us, gets called
m_xCalcComponent =
getMultiServiceFactory()->
createInstance("com.sun.star.comp.Calc.SpreadsheetDocument");
CPPUNIT_ASSERT_MESSAGE("no calc component!", m_xCalcComponent.is());
}
void ScOpenclTest::tearDown()
{
uno::Reference< lang::XComponent >
( m_xCalcComponent, UNO_QUERY_THROW )->dispose();
test::BootstrapFixture::tearDown();
}
CPPUNIT_TEST_SUITE_REGISTRATION(ScOpenclTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Testcase for Norminal<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is added by mcw.
*/
#include <sal/config.h>
#include <unotest/filters-test.hxx>
#include <test/bootstrapfixture.hxx>
#include <rtl/strbuf.hxx>
#include <osl/file.hxx>
#include "scdll.hxx"
#include <sfx2/app.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svl/stritem.hxx>
#define TEST_BUG_FILES 0
#include "helper/qahelper.hxx"
#include "calcconfig.hxx"
#include "interpre.hxx"
#include "docsh.hxx"
#include "postit.hxx"
#include "patattr.hxx"
#include "scitems.hxx"
#include "document.hxx"
#include "cellform.hxx"
#include "drwlayer.hxx"
#include "userdat.hxx"
#include "formulacell.hxx"
#include <svx/svdpage.hxx>
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
/* Implementation of Filters test */
class ScOpenclTest
: public test::FiltersTest
, public ScBootstrapFixture
{
public:
ScOpenclTest();
void enableOpenCL(ScDocShell* pShell);
void SetEnv();
virtual void setUp();
virtual void tearDown();
virtual bool load( const OUString &rFilter, const OUString &rURL,
const OUString &rUserData, unsigned int nFilterFlags,
unsigned int nClipboardID, unsigned int nFilterVersion);
void testSharedFormulaXLS();
void testSharedFormulaXLSGroundWater();
void testSharedFormulaXLSStockHistory();
void testFinacialFormula();
CPPUNIT_TEST_SUITE(ScOpenclTest);
CPPUNIT_TEST(testSharedFormulaXLS);
CPPUNIT_TEST(testSharedFormulaXLSGroundWater);
CPPUNIT_TEST(testSharedFormulaXLSStockHistory);
CPPUNIT_TEST(testFinacialFormula);
CPPUNIT_TEST_SUITE_END();
private:
uno::Reference<uno::XInterface> m_xCalcComponent;
};
bool ScOpenclTest::load(const OUString &rFilter, const OUString &rURL,
const OUString &rUserData, unsigned int nFilterFlags,
unsigned int nClipboardID, unsigned int nFilterVersion)
{
ScDocShellRef xDocShRef = ScBootstrapFixture::load(rURL, rFilter, rUserData,
OUString(), nFilterFlags, nClipboardID, nFilterVersion );
bool bLoaded = xDocShRef.Is();
//reference counting of ScDocShellRef is very confused.
if (bLoaded)
xDocShRef->DoClose();
return bLoaded;
}
void ScOpenclTest::SetEnv()
{
#ifdef WIN32
char *newpathfull = (char *)malloc(1024);
newpathfull= "PATH=;C:\\Program Files (x86)\\AMD APP\\bin\\x86_64;";
putenv(newpathfull);
#else
return;
#endif
}
void ScOpenclTest::enableOpenCL(ScDocShell* pShell)
{
ScModule* pScMod = SC_MOD();
ScFormulaOptions rOpt = pScMod->GetFormulaOptions();
ScCalcConfig maSavedConfig = rOpt.GetCalcConfig();
maSavedConfig.mbOpenCLEnabled = true;
rOpt.SetCalcConfig(maSavedConfig);
pShell->SetFormulaOptions(rOpt);
}
void ScOpenclTest::testSharedFormulaXLSStockHistory()
{
#if 1
ScDocShellRef xDocSh = loadDoc("stock-history.", XLS);
enableOpenCL(xDocSh);
ScDocument* pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc);
xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("stock-history.", XLS);
ScDocument* pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
for (SCROW i = 33; i < 44; ++i)
{ // Cell H34:H44 in S&P 500 (tab 1)
double fLibre = pDoc->GetValue(ScAddress(7, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(7, i, 1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel);
}
for (SCROW i = 33; i < 44; ++i)
{ // Cell J34:J44 in S&P 500 (tab 1)
double fLibre = pDoc->GetValue(ScAddress(9, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(9, i, 1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, 0.0001*fExcel);
}
xDocSh->DoClose();
xDocShRes->DoClose();
#endif
}
void ScOpenclTest::testSharedFormulaXLSGroundWater()
{
ScDocShellRef xDocSh = loadDoc("ground-water-daily.", XLS);
enableOpenCL(xDocSh);
ScDocument* pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc);
xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("ground-water-daily.", XLS);
ScDocument* pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
for (SCROW i = 5; i <= 77; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(11,i,1));
double fExcel = pDocRes->GetValue(ScAddress(11,i,1));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
xDocSh->DoClose();
xDocShRes->DoClose();
}
void ScOpenclTest::testSharedFormulaXLS()
{
ScDocShellRef xDocSh = loadDoc("sum_ex.", XLS);
enableOpenCL(xDocSh);
ScDocument *pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc);
xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("sum_ex.", XLS);
ScDocument *pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
// AMLOEXT-5
for (SCROW i = 0; i < 5; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-6
for (SCROW i = 6; i < 14; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-8
for (SCROW i = 15; i < 18; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-10
for (SCROW i = 19; i < 22; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-9
for (SCROW i = 23; i < 25; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
//double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
// There seems to be a bug in LibreOffice beta
CPPUNIT_ASSERT_EQUAL(/*fExcel*/ 60.0, fLibre);
}
// AMLOEXT-9
for (SCROW i = 25; i < 27; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-11
for (SCROW i = 28; i < 35; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-11; workaround for a Calc beta bug
CPPUNIT_ASSERT_EQUAL(25.0, pDoc->GetValue(ScAddress(2, 35, 0)));
CPPUNIT_ASSERT_EQUAL(24.0, pDoc->GetValue(ScAddress(2, 36, 0)));
// AMLOEXT-12
for (SCROW i = 38; i < 43; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2, i, 0));
double fExcel = pDocRes->GetValue(ScAddress(2, i, 0));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-14
for (SCROW i = 5; i < 10; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(5, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(5, i, 1));
CPPUNIT_ASSERT_EQUAL(fExcel, fLibre);
}
// AMLOEXT-15, AMLOEXT-16, and AMLOEXT-17
for (SCROW i = 5; i < 10; ++i)
{
for (SCCOL j = 6; j < 11; ++j)
{
double fLibre = pDoc->GetValue(ScAddress(j, i, 1));
double fExcel = pDocRes->GetValue(ScAddress(j, i, 1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre,
fabs(fExcel*0.0001));
}
}
xDocSh->DoClose();
xDocShRes->DoClose();
}
void ScOpenclTest::testFinacialFormula()
{
ScDocShellRef xDocSh = loadDoc("FinancialFormulaTest.", XLS);
enableOpenCL(xDocSh); ScDocument* pDoc = xDocSh->GetDocument();
CPPUNIT_ASSERT(pDoc); xDocSh->DoHardRecalc(true);
ScDocShellRef xDocShRes = loadDoc("FinancialFormulaTest.", XLS);
ScDocument* pDocRes = xDocShRes->GetDocument();
CPPUNIT_ASSERT(pDocRes);
// Check the results of formula cells in the shared formula range.
for (SCROW i = 1; i <= 10; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2,i,0));
double fExcel = pDocRes->GetValue(ScAddress(2,i,0));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel));
}
// AMLOEXT-22
for (SCROW i = 1; i <= 10; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(6,i,1));
double fExcel = pDocRes->GetValue(ScAddress(6,i,1));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel));
}
//[AMLOEXT-23]
for (SCROW i = 1; i <= 10; ++i)
{
double fLibre = pDoc->GetValue(ScAddress(2,i,2));
double fExcel = pDocRes->GetValue(ScAddress(2,i,2));
CPPUNIT_ASSERT_DOUBLES_EQUAL(fExcel, fLibre, fabs(0.0001*fExcel));
}
xDocSh->DoClose();
xDocShRes->DoClose();
}
ScOpenclTest::ScOpenclTest()
: ScBootstrapFixture( "/sc/qa/unit/data" )
{
}
void ScOpenclTest::setUp()
{
test::BootstrapFixture::setUp();
SetEnv();
// This is a bit of a fudge, we do this to ensure that ScGlobals::ensure,
// which is a private symbol to us, gets called
m_xCalcComponent =
getMultiServiceFactory()->
createInstance("com.sun.star.comp.Calc.SpreadsheetDocument");
CPPUNIT_ASSERT_MESSAGE("no calc component!", m_xCalcComponent.is());
}
void ScOpenclTest::tearDown()
{
uno::Reference< lang::XComponent >
( m_xCalcComponent, UNO_QUERY_THROW )->dispose();
test::BootstrapFixture::tearDown();
}
CPPUNIT_TEST_SUITE_REGISTRATION(ScOpenclTest);
CPPUNIT_PLUGIN_IMPLEMENT();
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before><commit_msg>create one fewer arrays<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
namespace gms {
enum class application_state:int {STATUS = 0,
LOAD,
SCHEMA,
DC,
RACK,
RELEASE_VERSION,
REMOVAL_COORDINATOR,
INTERNAL_IP,
RPC_ADDRESS,
SEVERITY,
NET_VERSION,
HOST_ID,
TOKENS
};
class inet_address final {
uint32_t raw_addr();
};
class versioned_value {
sstring value;
int version;
};
class heart_beat_state {
int32_t get_generation();
int32_t get_heart_beat_version();
};
class endpoint_state {
gms::heart_beat_state get_heart_beat_state();
std::map<gms::application_state, gms::versioned_value> get_application_state_map();
};
class gossip_digest {
gms::inet_address get_endpoint();
int32_t get_generation();
int32_t get_max_version();
};
class gossip_digest_ack {
std::vector<gms::gossip_digest> get_gossip_digest_list();
std::map<gms::inet_address, gms::endpoint_state> get_endpoint_state_map();
};
}
<commit_msg>idl: Add gossip_digest_ack2<commit_after>/*
* Copyright 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
namespace gms {
enum class application_state:int {STATUS = 0,
LOAD,
SCHEMA,
DC,
RACK,
RELEASE_VERSION,
REMOVAL_COORDINATOR,
INTERNAL_IP,
RPC_ADDRESS,
SEVERITY,
NET_VERSION,
HOST_ID,
TOKENS
};
class inet_address final {
uint32_t raw_addr();
};
class versioned_value {
sstring value;
int version;
};
class heart_beat_state {
int32_t get_generation();
int32_t get_heart_beat_version();
};
class endpoint_state {
gms::heart_beat_state get_heart_beat_state();
std::map<gms::application_state, gms::versioned_value> get_application_state_map();
};
class gossip_digest {
gms::inet_address get_endpoint();
int32_t get_generation();
int32_t get_max_version();
};
class gossip_digest_ack {
std::vector<gms::gossip_digest> get_gossip_digest_list();
std::map<gms::inet_address, gms::endpoint_state> get_endpoint_state_map();
};
class gossip_digest_ack2 {
std::map<gms::inet_address, gms::endpoint_state> get_endpoint_state_map();
};
}
<|endoftext|>
|
<commit_before>#include "../../include/base/ErrorInfo.hpp"
namespace cutehmi {
namespace base {
QString ErrorInfo::toString() const
{
QString result = str;
result += "\n[error class: ";
result += errClass;
result += " code: ";
result += code;
result += "]";
return result;
}
}
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<commit_msg>Fix code to string conversion.<commit_after>#include "../../include/base/ErrorInfo.hpp"
namespace cutehmi {
namespace base {
QString ErrorInfo::toString() const
{
QString result = str;
result += "\n[error class: ";
result += errClass;
result += " code: ";
result += QString::number(code);
result += "]";
return result;
}
}
}
//(c)MP: Copyright © 2017, Michal Policht. All rights reserved.
//(c)MP: 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/.
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aststack.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2006-06-20 03:47:52 $
*
* 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 _RTL_ALLOC_H_
#include <rtl/alloc.h>
#endif
#ifndef _IDLC_ASTSTACK_HXX_
#include <idlc/aststack.hxx>
#endif
#ifndef _IDLC_ASTSCOPE_HXX_
#include <idlc/astscope.hxx>
#endif
#define STACKSIZE_INCREMENT 64
AstStack::AstStack()
: m_stack((AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * STACKSIZE_INCREMENT))
, m_size(STACKSIZE_INCREMENT)
, m_top(0)
{
}
AstStack::~AstStack()
{
for(sal_uInt32 i=0; i < m_top; i++)
{
if (m_stack[i])
delete(m_stack[i]);
}
rtl_freeMemory(m_stack);
}
sal_uInt32 AstStack::depth()
{
return m_top;
}
AstScope* AstStack::top()
{
if (m_top < 1)
return NULL;
return m_stack[m_top - 1];
}
AstScope* AstStack::bottom()
{
if (m_top == 0)
return NULL;
return m_stack[0];
}
AstScope* AstStack::nextToTop()
{
AstScope *tmp, *retval;
if (depth() < 2)
return NULL;
tmp = top(); // Save top
(void) pop(); // Pop it
retval = top(); // Get next one down
(void) push(tmp); // Push top back
return retval; // Return next one down
}
AstScope* AstStack::topNonNull()
{
for (sal_uInt32 i = m_top; i > 0; i--)
{
if ( m_stack[i - 1] )
return m_stack[i - 1];
}
return NULL;
}
AstStack* AstStack::push(AstScope* pScope)
{
AstScope **tmp;
// AstDeclaration *pDecl = ScopeAsDecl(pScope);
sal_uInt32 newSize;
sal_uInt32 i;
// Make sure there's space for one more
if (m_size == m_top)
{
newSize = m_size;
newSize += STACKSIZE_INCREMENT;
tmp = (AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * newSize);
for(i=0; i < m_size; i++)
tmp[i] = m_stack[i];
rtl_freeMemory(m_stack);
m_stack = tmp;
}
// Insert new scope
m_stack[m_top++] = pScope;
return this;
}
void AstStack::pop()
{
AstScope *pScope;
if (m_top < 1)
return;
pScope = m_stack[--m_top];
}
void AstStack::clear()
{
m_top = 0;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.8); FILE MERGED 2006/09/01 17:31:13 kaib 1.3.8.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aststack.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 08:13:00 $
*
* 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_idlc.hxx"
#ifndef _RTL_ALLOC_H_
#include <rtl/alloc.h>
#endif
#ifndef _IDLC_ASTSTACK_HXX_
#include <idlc/aststack.hxx>
#endif
#ifndef _IDLC_ASTSCOPE_HXX_
#include <idlc/astscope.hxx>
#endif
#define STACKSIZE_INCREMENT 64
AstStack::AstStack()
: m_stack((AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * STACKSIZE_INCREMENT))
, m_size(STACKSIZE_INCREMENT)
, m_top(0)
{
}
AstStack::~AstStack()
{
for(sal_uInt32 i=0; i < m_top; i++)
{
if (m_stack[i])
delete(m_stack[i]);
}
rtl_freeMemory(m_stack);
}
sal_uInt32 AstStack::depth()
{
return m_top;
}
AstScope* AstStack::top()
{
if (m_top < 1)
return NULL;
return m_stack[m_top - 1];
}
AstScope* AstStack::bottom()
{
if (m_top == 0)
return NULL;
return m_stack[0];
}
AstScope* AstStack::nextToTop()
{
AstScope *tmp, *retval;
if (depth() < 2)
return NULL;
tmp = top(); // Save top
(void) pop(); // Pop it
retval = top(); // Get next one down
(void) push(tmp); // Push top back
return retval; // Return next one down
}
AstScope* AstStack::topNonNull()
{
for (sal_uInt32 i = m_top; i > 0; i--)
{
if ( m_stack[i - 1] )
return m_stack[i - 1];
}
return NULL;
}
AstStack* AstStack::push(AstScope* pScope)
{
AstScope **tmp;
// AstDeclaration *pDecl = ScopeAsDecl(pScope);
sal_uInt32 newSize;
sal_uInt32 i;
// Make sure there's space for one more
if (m_size == m_top)
{
newSize = m_size;
newSize += STACKSIZE_INCREMENT;
tmp = (AstScope**)rtl_allocateZeroMemory(sizeof(AstScope*) * newSize);
for(i=0; i < m_size; i++)
tmp[i] = m_stack[i];
rtl_freeMemory(m_stack);
m_stack = tmp;
}
// Insert new scope
m_stack[m_top++] = pScope;
return this;
}
void AstStack::pop()
{
AstScope *pScope;
if (m_top < 1)
return;
pScope = m_stack[--m_top];
}
void AstStack::clear()
{
m_top = 0;
}
<|endoftext|>
|
<commit_before>#include <rtosc/automations.h>
#include <cmath>
using namespace rtosc;
AutomationMgr::AutomationMgr(int slots, int per_slot, int control_points)
:nslots(slots), per_slot(per_slot), active_slot(0), p(NULL), learn_queue_len(0), damaged(0)
{
this->slots = new AutomationSlot[slots];
memset(this->slots, 0, sizeof(AutomationSlot)*slots);
for(int i=0; i<slots; ++i) {
auto &s = this->slots[i];
sprintf(s.name, "Slot %d", i);
s.midi_cc = -1;
s.learning = -1;
s.automations = new Automation[per_slot];
memset(s.automations, 0, sizeof(Automation)*per_slot);
for(int j=0; j<per_slot; ++j) {
s.automations[j].map.control_points = new float[control_points];
s.automations[j].map.npoints = control_points;
s.automations[j].map.gain = 100.0;
s.automations[j].map.offset = 0.0;
}
}
}
AutomationMgr::~AutomationMgr(void)
{
}
void AutomationMgr::createBinding(int slot, const char *path, bool start_midi_learn)
{
assert(p);
const Port *port = p->apropos(path);
if(!port) {
fprintf(stderr, "[Zyn:Error] port '%s' does not exist\n", path);
return;
}
auto meta = port->meta();
if(!(meta.find("min") && meta.find("max"))) {
fprintf(stderr, "No bounds for '%s' known\n", path);
return;
}
int ind = -1;
for(int i=0; i<per_slot; ++i) {
if(slots[slot].automations[i].used == false) {
ind = i;
break;
}
}
if(ind == -1)
return;
slots[slot].used = true;
auto &au = slots[slot].automations[ind];
au.used = true;
au.active = true;
au.param_min = atof(meta["min"]);
au.param_max = atof(meta["max"]);
au.param_type = 'i';
if(strstr(port->name, ":f"))
au.param_type = 'f';
strncpy(au.param_path, path, sizeof(au.param_path));
au.map.gain = 100.0;
au.map.offset = 0;
updateMapping(slot, ind);
if(start_midi_learn && slots[slot].learning == -1 && slots[slot].midi_cc == -1)
slots[slot].learning = ++learn_queue_len;
damaged = true;
};
void AutomationMgr::updateMapping(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &au = slots[slot_id].automations[sub];
float mn = au.param_min;
float mx = au.param_max;
float center = (mn+mx)*(0.5 + au.map.offset/100.0);
float range = (mx-mn)*au.map.gain/100.0;
au.map.upoints = 2;
au.map.control_points[0] = 0;
au.map.control_points[1] = center-range/2.0;
au.map.control_points[2] = 1;
au.map.control_points[3] = center+range/2.0;
}
void AutomationMgr::setSlot(int slot_id, float value)
{
if(slot_id >= nslots || slot_id < 0)
return;
for(int i=0; i<per_slot; ++i)
setSlotSub(slot_id, i, value);
slots[slot_id].current_state = value;
}
void AutomationMgr::setSlotSub(int slot_id, int par, float value)
{
if(slot_id >= nslots || slot_id < 0 || par >= per_slot || par < 0)
return;
auto &au = slots[slot_id].automations[par];
if(au.used == false)
return;
const char *path = au.param_path;
float mn = au.param_min;
float mx = au.param_max;
float a = au.map.control_points[1];
float b = au.map.control_points[3];
char type = au.param_type;
char msg[256] = {0};
if(type == 'i') {
float v = value*(b-a) + a;
if(v > mx)
v = mx;
else if(v < mn)
v = mn;
rtosc_message(msg, 256, path, "i", (int)roundf(v));
} else if(type == 'f') {
float v = value*(b-a) + a;
if(v > mx)
v = mx;
else if(v < mn)
v = mn;
rtosc_message(msg, 256, path, "f", v);
} else if(type == 'T' || type == 'F') {
float v = value*(b-a) + a;
if(v > 0.5)
v = 1.0;
else
v = 0.0;
rtosc_message(msg, 256, path, v == 1.0 ? "T" : "F");
} else
return;
if(backend)
backend(msg);
}
float AutomationMgr::getSlot(int slot_id)
{
if(slot_id >= nslots || slot_id < 0)
return 0.0;
return slots[slot_id].current_state;
}
void AutomationMgr::clearSlot(int slot_id)
{
if(slot_id >= nslots || slot_id < 0)
return;
auto &s = slots[slot_id];
s.active = false;
s.used = false;
if(s.learning)
learn_queue_len--;
for(int i=0; i<nslots; ++i)
if(slots[i].learning > s.learning)
slots[i].learning--;
s.learning = -1;
s.midi_cc = -1;
s.current_state = 0;
memset(s.name, 0, sizeof(s.name));
sprintf(s.name, "Slot %d", slot_id);
for(int i=0; i<per_slot; ++i)
clearSlotSub(slot_id, i);
damaged = true;
}
void AutomationMgr::clearSlotSub(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &a = slots[slot_id].automations[sub];
a.used = false;
a.active = false;
a.relative = false;
a.param_base_value = false;
memset(a.param_path, 0, sizeof(a.param_path));
a.param_type = 0;
a.param_min = 0;
a.param_max = 0;
a.param_step = 0;
a.map.gain = 100;
a.map.offset = 0;
damaged = true;
}
void AutomationMgr::setSlotSubGain(int slot_id, int sub, float f)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &m = slots[slot_id].automations[sub].map;
m.gain = f;
}
float AutomationMgr::getSlotSubGain(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return 0.0;
auto &m = slots[slot_id].automations[sub].map;
return m.gain;
}
void AutomationMgr::setSlotSubOffset(int slot_id, int sub, float f)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &m = slots[slot_id].automations[sub].map;
m.offset = f;
}
float AutomationMgr::getSlotSubOffset(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return 0.0;
auto &m = slots[slot_id].automations[sub].map;
return m.offset;
}
void AutomationMgr::setName(int slot_id, const char *msg)
{
if(slot_id >= nslots || slot_id < 0)
return;
strncpy(slots[slot_id].name, msg, sizeof(slots[slot_id].name));
damaged = 1;
}
const char *AutomationMgr::getName(int slot_id)
{
if(slot_id >= nslots || slot_id < 0)
return "";
return slots[slot_id].name;
}
bool AutomationMgr::handleMidi(int channel, int cc, int val)
{
int ccid = channel*128 + cc;
bool bound_cc = false;
for(int i=0; i<nslots; ++i) {
if(slots[i].midi_cc == ccid) {
bound_cc = true;
setSlot(i, val/127.0);
}
}
if(bound_cc)
return 1;
//No bound CC, now to see if there's something to learn
for(int i=0; i<nslots; ++i) {
if(slots[i].learning == 1) {
slots[i].learning = -1;
slots[i].midi_cc = ccid;
for(int j=0; j<nslots; ++j)
if(slots[j].learning > 1)
slots[j].learning -= 1;
learn_queue_len--;
setSlot(i, val/127.0);
damaged = 1;
break;
}
}
return 0;
}
void AutomationMgr::set_ports(const class Ports &p_) {
p = &p_;
};
//
// AutomationSlot *slots;
// struct AutomationMgrImpl *impl;
//};
void AutomationMgr::set_instance(void *v)
{
this->instance = v;
}
void AutomationMgr::simpleSlope(int slot_id, int par, float slope, float offset)
{
if(slot_id >= nslots || slot_id < 0 || par >= per_slot || par < 0)
return;
auto &map = slots[slot_id].automations[par].map;
map.upoints = 2;
map.control_points[0] = 0;
map.control_points[1] = -(slope/2)+offset;
map.control_points[2] = 1;
map.control_points[3] = slope/2+offset;
}
int AutomationMgr::free_slot(void) const
{
for(int i=0; i<nslots; ++i)
if(!slots[i].used)
return i;
return -1;
}
<commit_msg>Automations: Add Meta. Check For Blacklisted Ports<commit_after>#include <rtosc/automations.h>
#include <cmath>
using namespace rtosc;
AutomationMgr::AutomationMgr(int slots, int per_slot, int control_points)
:nslots(slots), per_slot(per_slot), active_slot(0), p(NULL), learn_queue_len(0), damaged(0)
{
this->slots = new AutomationSlot[slots];
memset(this->slots, 0, sizeof(AutomationSlot)*slots);
for(int i=0; i<slots; ++i) {
auto &s = this->slots[i];
sprintf(s.name, "Slot %d", i);
s.midi_cc = -1;
s.learning = -1;
s.automations = new Automation[per_slot];
memset(s.automations, 0, sizeof(Automation)*per_slot);
for(int j=0; j<per_slot; ++j) {
s.automations[j].map.control_points = new float[control_points];
s.automations[j].map.npoints = control_points;
s.automations[j].map.gain = 100.0;
s.automations[j].map.offset = 0.0;
}
}
}
AutomationMgr::~AutomationMgr(void)
{
}
void AutomationMgr::createBinding(int slot, const char *path, bool start_midi_learn)
{
assert(p);
const Port *port = p->apropos(path);
if(!port) {
fprintf(stderr, "[Zyn:Error] port '%s' does not exist\n", path);
return;
}
auto meta = port->meta();
if(!(meta.find("min") && meta.find("max"))) {
fprintf(stderr, "No bounds for '%s' known\n", path);
return;
}
if(meta.find("internal") || meta.find("no learn")) {
fprintf(stderr, "[Warning] port '%s' is unlearnable\n", path);
return;
}
int ind = -1;
for(int i=0; i<per_slot; ++i) {
if(slots[slot].automations[i].used == false) {
ind = i;
break;
}
}
if(ind == -1)
return;
slots[slot].used = true;
auto &au = slots[slot].automations[ind];
au.used = true;
au.active = true;
au.param_min = atof(meta["min"]);
au.param_max = atof(meta["max"]);
au.param_type = 'i';
if(strstr(port->name, ":f"))
au.param_type = 'f';
strncpy(au.param_path, path, sizeof(au.param_path));
au.map.gain = 100.0;
au.map.offset = 0;
updateMapping(slot, ind);
if(start_midi_learn && slots[slot].learning == -1 && slots[slot].midi_cc == -1)
slots[slot].learning = ++learn_queue_len;
damaged = true;
};
void AutomationMgr::updateMapping(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &au = slots[slot_id].automations[sub];
float mn = au.param_min;
float mx = au.param_max;
float center = (mn+mx)*(0.5 + au.map.offset/100.0);
float range = (mx-mn)*au.map.gain/100.0;
au.map.upoints = 2;
au.map.control_points[0] = 0;
au.map.control_points[1] = center-range/2.0;
au.map.control_points[2] = 1;
au.map.control_points[3] = center+range/2.0;
}
void AutomationMgr::setSlot(int slot_id, float value)
{
if(slot_id >= nslots || slot_id < 0)
return;
for(int i=0; i<per_slot; ++i)
setSlotSub(slot_id, i, value);
slots[slot_id].current_state = value;
}
void AutomationMgr::setSlotSub(int slot_id, int par, float value)
{
if(slot_id >= nslots || slot_id < 0 || par >= per_slot || par < 0)
return;
auto &au = slots[slot_id].automations[par];
if(au.used == false)
return;
const char *path = au.param_path;
float mn = au.param_min;
float mx = au.param_max;
float a = au.map.control_points[1];
float b = au.map.control_points[3];
char type = au.param_type;
char msg[256] = {0};
if(type == 'i') {
float v = value*(b-a) + a;
if(v > mx)
v = mx;
else if(v < mn)
v = mn;
rtosc_message(msg, 256, path, "i", (int)roundf(v));
} else if(type == 'f') {
float v = value*(b-a) + a;
if(v > mx)
v = mx;
else if(v < mn)
v = mn;
rtosc_message(msg, 256, path, "f", v);
} else if(type == 'T' || type == 'F') {
float v = value*(b-a) + a;
if(v > 0.5)
v = 1.0;
else
v = 0.0;
rtosc_message(msg, 256, path, v == 1.0 ? "T" : "F");
} else
return;
if(backend)
backend(msg);
}
float AutomationMgr::getSlot(int slot_id)
{
if(slot_id >= nslots || slot_id < 0)
return 0.0;
return slots[slot_id].current_state;
}
void AutomationMgr::clearSlot(int slot_id)
{
if(slot_id >= nslots || slot_id < 0)
return;
auto &s = slots[slot_id];
s.active = false;
s.used = false;
if(s.learning)
learn_queue_len--;
for(int i=0; i<nslots; ++i)
if(slots[i].learning > s.learning)
slots[i].learning--;
s.learning = -1;
s.midi_cc = -1;
s.current_state = 0;
memset(s.name, 0, sizeof(s.name));
sprintf(s.name, "Slot %d", slot_id);
for(int i=0; i<per_slot; ++i)
clearSlotSub(slot_id, i);
damaged = true;
}
void AutomationMgr::clearSlotSub(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &a = slots[slot_id].automations[sub];
a.used = false;
a.active = false;
a.relative = false;
a.param_base_value = false;
memset(a.param_path, 0, sizeof(a.param_path));
a.param_type = 0;
a.param_min = 0;
a.param_max = 0;
a.param_step = 0;
a.map.gain = 100;
a.map.offset = 0;
damaged = true;
}
void AutomationMgr::setSlotSubGain(int slot_id, int sub, float f)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &m = slots[slot_id].automations[sub].map;
m.gain = f;
}
float AutomationMgr::getSlotSubGain(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return 0.0;
auto &m = slots[slot_id].automations[sub].map;
return m.gain;
}
void AutomationMgr::setSlotSubOffset(int slot_id, int sub, float f)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return;
auto &m = slots[slot_id].automations[sub].map;
m.offset = f;
}
float AutomationMgr::getSlotSubOffset(int slot_id, int sub)
{
if(slot_id >= nslots || slot_id < 0 || sub >= per_slot || sub < 0)
return 0.0;
auto &m = slots[slot_id].automations[sub].map;
return m.offset;
}
void AutomationMgr::setName(int slot_id, const char *msg)
{
if(slot_id >= nslots || slot_id < 0)
return;
strncpy(slots[slot_id].name, msg, sizeof(slots[slot_id].name));
damaged = 1;
}
const char *AutomationMgr::getName(int slot_id)
{
if(slot_id >= nslots || slot_id < 0)
return "";
return slots[slot_id].name;
}
bool AutomationMgr::handleMidi(int channel, int cc, int val)
{
int ccid = channel*128 + cc;
bool bound_cc = false;
for(int i=0; i<nslots; ++i) {
if(slots[i].midi_cc == ccid) {
bound_cc = true;
setSlot(i, val/127.0);
}
}
if(bound_cc)
return 1;
//No bound CC, now to see if there's something to learn
for(int i=0; i<nslots; ++i) {
if(slots[i].learning == 1) {
slots[i].learning = -1;
slots[i].midi_cc = ccid;
for(int j=0; j<nslots; ++j)
if(slots[j].learning > 1)
slots[j].learning -= 1;
learn_queue_len--;
setSlot(i, val/127.0);
damaged = 1;
break;
}
}
return 0;
}
void AutomationMgr::set_ports(const class Ports &p_) {
p = &p_;
};
//
// AutomationSlot *slots;
// struct AutomationMgrImpl *impl;
//};
void AutomationMgr::set_instance(void *v)
{
this->instance = v;
}
void AutomationMgr::simpleSlope(int slot_id, int par, float slope, float offset)
{
if(slot_id >= nslots || slot_id < 0 || par >= per_slot || par < 0)
return;
auto &map = slots[slot_id].automations[par].map;
map.upoints = 2;
map.control_points[0] = 0;
map.control_points[1] = -(slope/2)+offset;
map.control_points[2] = 1;
map.control_points[3] = slope/2+offset;
}
int AutomationMgr::free_slot(void) const
{
for(int i=0; i<nslots; ++i)
if(!slots[i].used)
return i;
return -1;
}
<|endoftext|>
|
<commit_before>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "syzygy/common/unittest_util.h"
namespace testing {
ApplicationTestBase* ApplicationTestBase::self_ = NULL;
void ApplicationTestBase::InitStreams(const base::FilePath& in_path,
const base::FilePath& out_path,
const base::FilePath& err_path) {
ASSERT_FALSE(in_path.empty());
ASSERT_FALSE(out_path.empty());
ASSERT_FALSE(err_path.empty());
in_.reset(file_util::OpenFile(in_path, "r"));
out_.reset(file_util::OpenFile(out_path, "w"));
err_.reset(file_util::OpenFile(err_path, "w"));
ASSERT_TRUE(in_.get() != NULL);
ASSERT_TRUE(out_.get() != NULL);
ASSERT_TRUE(err_.get() != NULL);
// Intercept logging.
ASSERT_TRUE(self_ == NULL);
ASSERT_TRUE(log_handler_ == NULL);
self_ = this;
log_handler_ = logging::GetLogMessageHandler();
logging::SetLogMessageHandler(&HandleLogMessage);
}
void ApplicationTestBase::TearDownStreams() {
if (self_ != NULL) {
logging::SetLogMessageHandler(log_handler_);
log_handler_ = NULL;
self_ = NULL;
}
ASSERT_NO_FATAL_FAILURE(TearDownStream(&in_));
ASSERT_NO_FATAL_FAILURE(TearDownStream(&out_));
ASSERT_NO_FATAL_FAILURE(TearDownStream(&err_));
}
void ApplicationTestBase::SetUp() {
Super::SetUp();
// Save the log level so that we can restore it in TearDown.
log_level_ = logging::GetMinLogLevel();
// By default we don't log to console.
log_to_console_ = false;
}
void ApplicationTestBase::TearDown() {
logging::SetMinLogLevel(log_level_);
// These need to be shut down before we can delete the temporary
// directories.
EXPECT_NO_FATAL_FAILURE(TearDownStreams());
DirList::const_iterator iter;
for (iter = temp_dirs_.begin(); iter != temp_dirs_.end(); ++iter) {
EXPECT_TRUE(file_util::Delete(*iter, true));
}
Super::TearDown();
}
bool ApplicationTestBase::HandleLogMessage(int severity, const char* file,
int line, size_t message_start, const std::string& str) {
DCHECK(self_ != NULL);
if (severity < logging::GetMinLogLevel())
return true;
fprintf(self_->err(), "%s", str.c_str());
fflush(self_->err());
// If we're logging to console then repeat the message there.
if (self_->log_to_console_) {
fprintf(stdout, "%s", str.c_str());
fflush(stdout);
}
return true;
}
void ApplicationTestBase::TearDownStream(file_util::ScopedFILE* stream) {
ASSERT_TRUE(stream != NULL);
if (stream->get() == NULL)
return;
ASSERT_EQ(0, ::fclose(stream->get()));
stream->reset();
}
FILE* ApplicationTestBase::GetOrInitFile(file_util::ScopedFILE* f,
const char* mode) {
DCHECK(f != NULL);
DCHECK(mode != NULL);
if (f->get() == NULL)
f->reset(file_util::OpenFile(base::FilePath(L"NUL"), mode));
return f->get();
}
} // namespace testing
<commit_msg>Fix unittests so that they don't fail while under the VS2013 debugger.<commit_after>// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "syzygy/common/unittest_util.h"
namespace testing {
ApplicationTestBase* ApplicationTestBase::self_ = NULL;
void ApplicationTestBase::InitStreams(const base::FilePath& in_path,
const base::FilePath& out_path,
const base::FilePath& err_path) {
ASSERT_FALSE(in_path.empty());
ASSERT_FALSE(out_path.empty());
ASSERT_FALSE(err_path.empty());
in_.reset(file_util::OpenFile(in_path, "r"));
out_.reset(file_util::OpenFile(out_path, "w"));
err_.reset(file_util::OpenFile(err_path, "w"));
ASSERT_TRUE(in_.get() != NULL);
ASSERT_TRUE(out_.get() != NULL);
ASSERT_TRUE(err_.get() != NULL);
// Intercept logging.
ASSERT_TRUE(self_ == NULL);
ASSERT_TRUE(log_handler_ == NULL);
self_ = this;
log_handler_ = logging::GetLogMessageHandler();
logging::SetLogMessageHandler(&HandleLogMessage);
}
void ApplicationTestBase::TearDownStreams() {
if (self_ != NULL) {
logging::SetLogMessageHandler(log_handler_);
log_handler_ = NULL;
self_ = NULL;
}
ASSERT_NO_FATAL_FAILURE(TearDownStream(&in_));
ASSERT_NO_FATAL_FAILURE(TearDownStream(&out_));
ASSERT_NO_FATAL_FAILURE(TearDownStream(&err_));
}
void ApplicationTestBase::SetUp() {
Super::SetUp();
// Save the log level so that we can restore it in TearDown.
log_level_ = logging::GetMinLogLevel();
// By default we don't log to console.
log_to_console_ = false;
}
void ApplicationTestBase::TearDown() {
logging::SetMinLogLevel(log_level_);
// These need to be shut down before we can delete the temporary
// directories.
EXPECT_NO_FATAL_FAILURE(TearDownStreams());
DirList::const_iterator iter;
for (iter = temp_dirs_.begin(); iter != temp_dirs_.end(); ++iter) {
bool success = file_util::Delete(*iter, true);
// VS2013 holds open handles to any PDB file that has been loaded while
// the debugger is active. This often prevents our unittests from
// cleaning up after themselves.
EXPECT_TRUE(success || ::IsDebuggerPresent());
}
Super::TearDown();
}
bool ApplicationTestBase::HandleLogMessage(int severity, const char* file,
int line, size_t message_start, const std::string& str) {
DCHECK(self_ != NULL);
if (severity < logging::GetMinLogLevel())
return true;
fprintf(self_->err(), "%s", str.c_str());
fflush(self_->err());
// If we're logging to console then repeat the message there.
if (self_->log_to_console_) {
fprintf(stdout, "%s", str.c_str());
fflush(stdout);
}
return true;
}
void ApplicationTestBase::TearDownStream(file_util::ScopedFILE* stream) {
ASSERT_TRUE(stream != NULL);
if (stream->get() == NULL)
return;
ASSERT_EQ(0, ::fclose(stream->get()));
stream->reset();
}
FILE* ApplicationTestBase::GetOrInitFile(file_util::ScopedFILE* f,
const char* mode) {
DCHECK(f != NULL);
DCHECK(mode != NULL);
if (f->get() == NULL)
f->reset(file_util::OpenFile(base::FilePath(L"NUL"), mode));
return f->get();
}
} // namespace testing
<|endoftext|>
|
<commit_before>//===-- HostThreadPosix.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/Error.h"
#include "lldb/Host/posix/HostThreadPosix.h"
#include <errno.h>
#include <pthread.h>
using namespace lldb;
using namespace lldb_private;
HostThreadPosix::HostThreadPosix()
{
}
HostThreadPosix::HostThreadPosix(lldb::thread_t thread)
: HostNativeThreadBase(thread)
{
}
HostThreadPosix::~HostThreadPosix()
{
}
Error
HostThreadPosix::Join(lldb::thread_result_t *result)
{
Error error;
if (IsJoinable())
{
int err = ::pthread_join(m_thread, result);
error.SetError(err, lldb::eErrorTypePOSIX);
}
else
{
if (result)
*result = NULL;
error.SetError(EINVAL, eErrorTypePOSIX);
}
Reset();
return error;
}
Error
HostThreadPosix::Cancel()
{
Error error;
if (IsJoinable())
{
#ifndef __ANDROID__
assert(false && "someone is calling HostThread::Cancel()");
int err = ::pthread_cancel(m_thread);
error.SetError(err, eErrorTypePOSIX);
#else
error.SetErrorString("HostThreadPosix::Cancel() not supported on Android");
#endif
}
return error;
}
Error
HostThreadPosix::Detach()
{
Error error;
if (IsJoinable())
{
int err = ::pthread_detach(m_thread);
error.SetError(err, eErrorTypePOSIX);
}
Reset();
return error;
}
<commit_msg>Disable HostThread::Cancel assertion on FreeBSD<commit_after>//===-- HostThreadPosix.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/Error.h"
#include "lldb/Host/posix/HostThreadPosix.h"
#include <errno.h>
#include <pthread.h>
using namespace lldb;
using namespace lldb_private;
HostThreadPosix::HostThreadPosix()
{
}
HostThreadPosix::HostThreadPosix(lldb::thread_t thread)
: HostNativeThreadBase(thread)
{
}
HostThreadPosix::~HostThreadPosix()
{
}
Error
HostThreadPosix::Join(lldb::thread_result_t *result)
{
Error error;
if (IsJoinable())
{
int err = ::pthread_join(m_thread, result);
error.SetError(err, lldb::eErrorTypePOSIX);
}
else
{
if (result)
*result = NULL;
error.SetError(EINVAL, eErrorTypePOSIX);
}
Reset();
return error;
}
Error
HostThreadPosix::Cancel()
{
Error error;
if (IsJoinable())
{
#ifndef __ANDROID__
#ifndef __FreeBSD__
assert(false && "someone is calling HostThread::Cancel()");
#endif
int err = ::pthread_cancel(m_thread);
error.SetError(err, eErrorTypePOSIX);
#else
error.SetErrorString("HostThreadPosix::Cancel() not supported on Android");
#endif
}
return error;
}
Error
HostThreadPosix::Detach()
{
Error error;
if (IsJoinable())
{
int err = ::pthread_detach(m_thread);
error.SetError(err, eErrorTypePOSIX);
}
Reset();
return error;
}
<|endoftext|>
|
<commit_before>#include "webconfig/WebConfig.h"
#include "StaticFileServing.h"
WebConfig::WebConfig(QObject * parent)
: QObject(parent)
, _port(WEBCONFIG_DEFAULT_PORT)
, _server(nullptr)
{
_hyperion = Hyperion::getInstance();
const Json::Value &config = _hyperion->getJsonConfig();
_baseUrl = QString::fromStdString(WEBCONFIG_DEFAULT_PATH);
bool webconfigEnable = true;
if (config.isMember("webConfig"))
{
const Json::Value & webconfigConfig = config["webConfig"];
webconfigEnable = webconfigConfig.get("enable", true).asBool();
_port = webconfigConfig.get("port", WEBCONFIG_DEFAULT_PORT).asUInt();
_baseUrl = QString::fromStdString( webconfigConfig.get("document_root", WEBCONFIG_DEFAULT_PATH).asString() );
}
if ( webconfigEnable )
start();
}
WebConfig::~WebConfig()
{
stop();
}
void WebConfig::start()
{
if ( _server == nullptr )
_server = new StaticFileServing (_hyperion, _baseUrl, _port, this);
}
void WebConfig::stop()
{
if ( _server != nullptr )
{
delete _server;
_server = nullptr;
}
}
<commit_msg>Fixed random http port due to uninitialized _port (#29)<commit_after>#include "webconfig/WebConfig.h"
#include "StaticFileServing.h"
WebConfig::WebConfig(QObject * parent)
: QObject(parent)
, _port(WEBCONFIG_DEFAULT_PORT)
, _server(nullptr)
{
_hyperion = Hyperion::getInstance();
const Json::Value &config = _hyperion->getJsonConfig();
_baseUrl = QString::fromStdString(WEBCONFIG_DEFAULT_PATH);
_port = WEBCONFIG_DEFAULT_PORT;
bool webconfigEnable = true;
if (config.isMember("webConfig"))
{
const Json::Value & webconfigConfig = config["webConfig"];
webconfigEnable = webconfigConfig.get("enable", true).asBool();
_port = webconfigConfig.get("port", WEBCONFIG_DEFAULT_PORT).asUInt();
_baseUrl = QString::fromStdString( webconfigConfig.get("document_root", WEBCONFIG_DEFAULT_PATH).asString() );
}
if ( webconfigEnable )
start();
}
WebConfig::~WebConfig()
{
stop();
}
void WebConfig::start()
{
if ( _server == nullptr )
_server = new StaticFileServing (_hyperion, _baseUrl, _port, this);
}
void WebConfig::stop()
{
if ( _server != nullptr )
{
delete _server;
_server = nullptr;
}
}
<|endoftext|>
|
<commit_before>#include <fcntl.h>
#include <unistd.h>
#include "ssr_priv.hpp"
#define PROCSTAT_PATH "/proc/stat"
#define MEMINFO_PATH "/proc/meminfo"
SysStatsMonitor::SysStatsMonitor()
{
mProcStatFd = -1;
mRawProcStats.mPending = false;
mMeminfoFd = -1;
mRawMemInfo.mPending = false;
}
SysStatsMonitor::~SysStatsMonitor()
{
if (mProcStatFd != -1)
close(mProcStatFd);
if (mMeminfoFd != -1)
close(mMeminfoFd);
}
int SysStatsMonitor::readRawStats()
{
int ret;
if (mProcStatFd == -1 || mMeminfoFd == -1)
return 0;
ret = pfstools::readRawStats(mProcStatFd, &mRawProcStats);
if (ret < 0)
return 0;
ret = pfstools::readRawStats(mMeminfoFd, &mRawMemInfo);
if (ret < 0)
return 0;
return 0;
}
int SysStatsMonitor::checkStatFile(
int *fd,
const char *path,
pfstools::RawStats *rawStats)
{
int ret;
if (*fd == -1) {
ret = open(path, O_RDONLY|O_CLOEXEC);
if (ret == -1) {
ret = -errno;
LOGE("Fail to open %s : %d(%m)", path, errno);
return ret;
}
*fd = ret;
return -EAGAIN;
} else if (!rawStats->mPending) {
return -EAGAIN;
}
return 0;
}
int SysStatsMonitor::processRawStats(const SystemMonitor::Callbacks &cb)
{
SystemMonitor::SystemStats stats;
bool dataPending = false;
int ret;
// Check /proc/stat status
ret = checkStatFile(&mProcStatFd, PROCSTAT_PATH, &mRawProcStats);
if (ret != -EAGAIN) {
LOGI("Read /proc/stat");
if (ret < 0) {
LOGI("%s:%d", __FILE__, __LINE__);
return ret;
}
ret = pfstools::readSystemStats(mRawProcStats.mContent, &stats);
if (ret < 0) {
close(mProcStatFd);
mProcStatFd = -1;
return ret;
}
} else {
dataPending = true;
}
// Check /proc/meminfo
ret = checkStatFile(&mMeminfoFd, MEMINFO_PATH, &mRawMemInfo);
if (ret != -EAGAIN) {
LOGI("Read /proc/meminfo");
if (ret < 0) {
LOGI("%s:%d", __FILE__, __LINE__);
return ret;
}
ret = pfstools::readMeminfoStats(mRawMemInfo.mContent, &stats);
if (ret < 0) {
close(mMeminfoFd);
mMeminfoFd = -1;
return ret;
}
} else {
dataPending = true;
}
// Notify
if (!dataPending && cb.mSystemStats) {
stats.mTs = mRawProcStats.mTs;
stats.mAcqEnd = mRawProcStats.mAcqEnd;
cb.mSystemStats(stats, cb.mUserdata);
}
return 0;
}
<commit_msg>Remove useless logs<commit_after>#include <fcntl.h>
#include <unistd.h>
#include "ssr_priv.hpp"
#define PROCSTAT_PATH "/proc/stat"
#define MEMINFO_PATH "/proc/meminfo"
SysStatsMonitor::SysStatsMonitor()
{
mProcStatFd = -1;
mRawProcStats.mPending = false;
mMeminfoFd = -1;
mRawMemInfo.mPending = false;
}
SysStatsMonitor::~SysStatsMonitor()
{
if (mProcStatFd != -1)
close(mProcStatFd);
if (mMeminfoFd != -1)
close(mMeminfoFd);
}
int SysStatsMonitor::readRawStats()
{
int ret;
if (mProcStatFd == -1 || mMeminfoFd == -1)
return 0;
ret = pfstools::readRawStats(mProcStatFd, &mRawProcStats);
if (ret < 0)
return 0;
ret = pfstools::readRawStats(mMeminfoFd, &mRawMemInfo);
if (ret < 0)
return 0;
return 0;
}
int SysStatsMonitor::checkStatFile(
int *fd,
const char *path,
pfstools::RawStats *rawStats)
{
int ret;
if (*fd == -1) {
ret = open(path, O_RDONLY|O_CLOEXEC);
if (ret == -1) {
ret = -errno;
LOGE("Fail to open %s : %d(%m)", path, errno);
return ret;
}
*fd = ret;
return -EAGAIN;
} else if (!rawStats->mPending) {
return -EAGAIN;
}
return 0;
}
int SysStatsMonitor::processRawStats(const SystemMonitor::Callbacks &cb)
{
SystemMonitor::SystemStats stats;
bool dataPending = false;
int ret;
// Check /proc/stat status
ret = checkStatFile(&mProcStatFd, PROCSTAT_PATH, &mRawProcStats);
if (ret != -EAGAIN) {
if (ret < 0) {
LOGI("%s:%d", __FILE__, __LINE__);
return ret;
}
ret = pfstools::readSystemStats(mRawProcStats.mContent, &stats);
if (ret < 0) {
close(mProcStatFd);
mProcStatFd = -1;
return ret;
}
} else {
dataPending = true;
}
// Check /proc/meminfo
ret = checkStatFile(&mMeminfoFd, MEMINFO_PATH, &mRawMemInfo);
if (ret != -EAGAIN) {
if (ret < 0) {
LOGI("%s:%d", __FILE__, __LINE__);
return ret;
}
ret = pfstools::readMeminfoStats(mRawMemInfo.mContent, &stats);
if (ret < 0) {
close(mMeminfoFd);
mMeminfoFd = -1;
return ret;
}
} else {
dataPending = true;
}
// Notify
if (!dataPending && cb.mSystemStats) {
stats.mTs = mRawProcStats.mTs;
stats.mAcqEnd = mRawProcStats.mAcqEnd;
cb.mSystemStats(stats, cb.mUserdata);
}
return 0;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <algorithm>
#include <caf/config_value.hpp>
#include "vast/event.hpp"
#include "vast/expected.hpp"
#include "vast/logger.hpp"
#include "vast/segment_store.hpp"
#include "vast/store.hpp"
#include "vast/table_slice.hpp"
#include "vast/to_events.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/system/archive.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/fill_status_map.hpp"
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::microseconds;
using namespace caf;
namespace vast::system {
archive_type::behavior_type
archive(archive_type::stateful_pointer<archive_state> self,
path dir, size_t capacity, size_t max_segment_size) {
// TODO: make the choice of store configurable. For most flexibility, it
// probably makes sense to pass a unique_ptr<stor> directory to the spawn
// arguments of the actor. This way, users can provide their own store
// implementation conveniently.
VAST_INFO(self, "spawned:", VAST_ARG(capacity), VAST_ARG(max_segment_size));
self->state.store = segment_store::make(
self->system(), dir, max_segment_size, capacity);
VAST_ASSERT(self->state.store != nullptr);
self->set_exit_handler(
[=](const exit_msg& msg) {
self->state.store->flush();
self->state.store.reset();
self->quit(msg.reason);
}
);
self->set_down_handler(
[=](const down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
self->state.active_exporters.erase(msg.source);
}
);
return {
[=](const ids& xs) -> caf::result<std::vector<event>> {
VAST_ASSERT(rank(xs) > 0);
VAST_DEBUG(self, "got query for", rank(xs), "events in range ["
<< select(xs, 1) << ',' << (select(xs, -1) + 1) << ')');
if (self->state.active_exporters.count(self->current_sender()->address())
== 0) {
VAST_DEBUG(self, "dismissing query for inactive sender");
return make_error(ec::no_error);
}
std::vector<event> result;
auto slices = self->state.store->get(xs);
if (!slices)
VAST_DEBUG(self, "failed to lookup IDs in store:",
self->system().render(slices.error()));
else
for (auto& slice : *slices)
to_events(result, *slice, xs);
return result;
},
[=](stream<table_slice_ptr> in) {
self->make_sink(
in,
[](unit_t&) {
// nop
},
[=](unit_t&, std::vector<table_slice_ptr>& batch) {
VAST_DEBUG(self, "got", batch.size(), "table slices");
for (auto& slice : batch) {
if (auto error = self->state.store->put(slice)) {
VAST_ERROR(self, "failed to add table slice to store",
self->system().render(error));
self->quit(error);
break;
}
}
},
[=](unit_t&, const error& err) {
if (err) {
VAST_ERROR(self, "got a stream error:", self->system().render(err));
}
}
);
},
[=](exporter_atom, const actor& exporter) {
auto sender_addr = self->current_sender()->address();
self->state.active_exporters.insert(sender_addr);
self->monitor<caf::message_priority::high>(exporter);
},
[=](status_atom) {
caf::dictionary<caf::config_value> result;
detail::fill_status_map(result, self);
self->state.store->inspect_status(put_dictionary(result, "store"));
return result;
}
};
}
} // namespace vast::system
<commit_msg>Fix log statement grammar<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#include <algorithm>
#include <caf/config_value.hpp>
#include "vast/event.hpp"
#include "vast/expected.hpp"
#include "vast/logger.hpp"
#include "vast/segment_store.hpp"
#include "vast/store.hpp"
#include "vast/table_slice.hpp"
#include "vast/to_events.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/system/archive.hpp"
#include "vast/detail/assert.hpp"
#include "vast/detail/fill_status_map.hpp"
using std::chrono::steady_clock;
using std::chrono::duration_cast;
using std::chrono::microseconds;
using namespace caf;
namespace vast::system {
archive_type::behavior_type
archive(archive_type::stateful_pointer<archive_state> self,
path dir, size_t capacity, size_t max_segment_size) {
// TODO: make the choice of store configurable. For most flexibility, it
// probably makes sense to pass a unique_ptr<stor> directory to the spawn
// arguments of the actor. This way, users can provide their own store
// implementation conveniently.
VAST_INFO(self, "spawned:", VAST_ARG(capacity), VAST_ARG(max_segment_size));
self->state.store = segment_store::make(
self->system(), dir, max_segment_size, capacity);
VAST_ASSERT(self->state.store != nullptr);
self->set_exit_handler(
[=](const exit_msg& msg) {
self->state.store->flush();
self->state.store.reset();
self->quit(msg.reason);
}
);
self->set_down_handler(
[=](const down_msg& msg) {
VAST_DEBUG(self, "received DOWN from", msg.source);
self->state.active_exporters.erase(msg.source);
}
);
return {
[=](const ids& xs) -> caf::result<std::vector<event>> {
VAST_ASSERT(rank(xs) > 0);
VAST_DEBUG(self, "got query for", rank(xs), "events in range ["
<< select(xs, 1) << ',' << (select(xs, -1) + 1) << ')');
if (self->state.active_exporters.count(self->current_sender()->address())
== 0) {
VAST_DEBUG(self, "dismisses query for inactive sender");
return make_error(ec::no_error);
}
std::vector<event> result;
auto slices = self->state.store->get(xs);
if (!slices)
VAST_DEBUG(self, "failed to lookup IDs in store:",
self->system().render(slices.error()));
else
for (auto& slice : *slices)
to_events(result, *slice, xs);
return result;
},
[=](stream<table_slice_ptr> in) {
self->make_sink(
in,
[](unit_t&) {
// nop
},
[=](unit_t&, std::vector<table_slice_ptr>& batch) {
VAST_DEBUG(self, "got", batch.size(), "table slices");
for (auto& slice : batch) {
if (auto error = self->state.store->put(slice)) {
VAST_ERROR(self, "failed to add table slice to store",
self->system().render(error));
self->quit(error);
break;
}
}
},
[=](unit_t&, const error& err) {
if (err) {
VAST_ERROR(self, "got a stream error:", self->system().render(err));
}
}
);
},
[=](exporter_atom, const actor& exporter) {
auto sender_addr = self->current_sender()->address();
self->state.active_exporters.insert(sender_addr);
self->monitor<caf::message_priority::high>(exporter);
},
[=](status_atom) {
caf::dictionary<caf::config_value> result;
detail::fill_status_map(result, self);
self->state.store->inspect_status(put_dictionary(result, "store"));
return result;
}
};
}
} // namespace vast::system
<|endoftext|>
|
<commit_before>/** ==========================================================================
* 2013 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
*
* For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================*/
#include "g3log/filesink.hpp"
#include "filesinkhelper.ipp"
#include <cassert>
namespace g3 {
using namespace internal;
FileSink::FileSink(const std::string &log_prefix, const std::string &log_directory)
: _log_file_with_path(log_directory)
, _log_prefix_backup(log_prefix)
, _outptr(new std::ofstream)
{
_log_prefix_backup = prefixSanityFix(log_prefix);
if (!isValidFilename(_log_prefix_backup)) {
std::cerr << "g3log: forced abort due to illegal log prefix [" << log_prefix << "]" << std::endl;
abort();
}
std::string file_name = createLogFileName(_log_prefix_backup);
_log_file_with_path = pathSanityFix(_log_file_with_path, file_name);
_outptr = createLogFile(_log_file_with_path);
if (!_outptr) {
std::cerr << "Cannot write log file to location, attempting current directory" << std::endl;
_log_file_with_path = "./" + file_name;
_outptr = createLogFile(_log_file_with_path);
}
assert(_outptr && "cannot open log file at startup");
addLogFileHeader();
}
FileSink::~FileSink() {
std::string exit_msg {"\ng3log g3FileSink shutdown at: "};
exit_msg.append(localtime_formatted(systemtime_now(), internal::time_formatted));
filestream() << exit_msg << std::flush;
exit_msg.append({"\nLog file at: ["}).append(_log_file_with_path).append({"]\n\n"});
std::cerr << exit_msg << std::flush;
}
// The actual log receiving function
void FileSink::fileWrite(LogMessageMover message) {
std::ofstream &out(filestream());
out << message.get().toString();
}
std::string FileSink::changeLogFile(const std::string &directory) {
auto now = g3::systemtime_now();
auto now_formatted = g3::localtime_formatted(now, {internal::date_formatted + " " + internal::time_formatted});
std::string file_name = createLogFileName(_log_prefix_backup);
std::string prospect_log = directory + file_name;
std::unique_ptr<std::ofstream> log_stream = createLogFile(prospect_log);
if (nullptr == log_stream) {
filestream() << "\n" << now_formatted << " Unable to change log file. Illegal filename or busy? Unsuccessful log name was: " << prospect_log;
return {}; // no success
}
addLogFileHeader();
std::ostringstream ss_change;
ss_change << "\n\tChanging log file from : " << _log_file_with_path;
ss_change << "\n\tto new location: " << prospect_log << "\n";
filestream() << now_formatted << ss_change.str();
ss_change.str("");
std::string old_log = _log_file_with_path;
_log_file_with_path = prospect_log;
_outptr = std::move(log_stream);
ss_change << "\n\tNew log file. The previous log file was at: ";
ss_change << old_log;
filestream() << now_formatted << ss_change.str();
return _log_file_with_path;
}
std::string FileSink::fileName() {
return _log_file_with_path;
}
void FileSink::addLogFileHeader() {
filestream() << header();
}
} // g3
<commit_msg>flush after every write: https://github.com/KjellKod/g3log/issues/57<commit_after>/** ==========================================================================
* 2013 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
*
* For more information see g3log/LICENSE or refer refer to http://unlicense.org
* ============================================================================*/
#include "g3log/filesink.hpp"
#include "filesinkhelper.ipp"
#include <cassert>
namespace g3 {
using namespace internal;
FileSink::FileSink(const std::string &log_prefix, const std::string &log_directory)
: _log_file_with_path(log_directory)
, _log_prefix_backup(log_prefix)
, _outptr(new std::ofstream)
{
_log_prefix_backup = prefixSanityFix(log_prefix);
if (!isValidFilename(_log_prefix_backup)) {
std::cerr << "g3log: forced abort due to illegal log prefix [" << log_prefix << "]" << std::endl;
abort();
}
std::string file_name = createLogFileName(_log_prefix_backup);
_log_file_with_path = pathSanityFix(_log_file_with_path, file_name);
_outptr = createLogFile(_log_file_with_path);
if (!_outptr) {
std::cerr << "Cannot write log file to location, attempting current directory" << std::endl;
_log_file_with_path = "./" + file_name;
_outptr = createLogFile(_log_file_with_path);
}
assert(_outptr && "cannot open log file at startup");
addLogFileHeader();
}
FileSink::~FileSink() {
std::string exit_msg {"\ng3log g3FileSink shutdown at: "};
exit_msg.append(localtime_formatted(systemtime_now(), internal::time_formatted));
filestream() << exit_msg << std::flush;
exit_msg.append({"\nLog file at: ["}).append(_log_file_with_path).append({"]\n\n"});
std::cerr << exit_msg << std::flush;
}
// The actual log receiving function
void FileSink::fileWrite(LogMessageMover message) {
std::ofstream &out(filestream());
out << message.get().toString() << std::flush;
}
std::string FileSink::changeLogFile(const std::string &directory) {
auto now = g3::systemtime_now();
auto now_formatted = g3::localtime_formatted(now, {internal::date_formatted + " " + internal::time_formatted});
std::string file_name = createLogFileName(_log_prefix_backup);
std::string prospect_log = directory + file_name;
std::unique_ptr<std::ofstream> log_stream = createLogFile(prospect_log);
if (nullptr == log_stream) {
filestream() << "\n" << now_formatted << " Unable to change log file. Illegal filename or busy? Unsuccessful log name was: " << prospect_log;
return {}; // no success
}
addLogFileHeader();
std::ostringstream ss_change;
ss_change << "\n\tChanging log file from : " << _log_file_with_path;
ss_change << "\n\tto new location: " << prospect_log << "\n";
filestream() << now_formatted << ss_change.str();
ss_change.str("");
std::string old_log = _log_file_with_path;
_log_file_with_path = prospect_log;
_outptr = std::move(log_stream);
ss_change << "\n\tNew log file. The previous log file was at: ";
ss_change << old_log;
filestream() << now_formatted << ss_change.str();
return _log_file_with_path;
}
std::string FileSink::fileName() {
return _log_file_with_path;
}
void FileSink::addLogFileHeader() {
filestream() << header();
}
} // g3
<|endoftext|>
|
<commit_before>/*
FPF - Frame Processing Framework
See the file COPYING for copying permission.
*/
/*
fpf_main.c - main(), generic chain driver executable for FPF
History:
created: 2015-11 - A.Shumilin.
*/
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
//
#include <ini.h>
#include <fpf.h>
#include "class_factory.h"
//
using namespace std;
//
#define INI_MAIN_SECTION "_main_"
#define INI_MAIN_FRAMESOURCE "frame_source"
//common substitutes
#define PARAM_INPUT_FILE "INPUTFILE"
#define PARAM_OUTPUT_FILE "OUTPUTFILE"
//exit codes
#define EXIT_ERR_CONFIG_INCOMPLETE -1
#define EXIT_ERR_INITIALIZATION_FAILED -2
#define EXIT_ERR_FPF_ASSERT_FAILED EXIT_FPF_ASSERT
#define EXIT_ERR_INVALID_ARG -4
// Globals
t_ini g_ini;
ostream stream_null(NULL);
int main(int argc, char* argv[])
{
cerr<< "*** Frame Processing Framework engine. v 0.6. build: " << __DATE__ <<" *** "<<endl;
int exit_code = 0;
string ini_fn;
IFrameSource* frame_source;
map<string,string> map_parameters;
string s_fs_class;
string s_root_framer;
//------- get command line options ----------------
int carg;
size_t eqpos;string sx;
while ((carg = getopt (argc, argv, "o:D:i:tcs")) != -1)
switch (carg)
{
case 'i': // config ini file
ini_fn = optarg;
break;
case 'o' : //output file
map_parameters[PARAM_OUTPUT_FILE] = optarg;
case 'D': // definition of custom parameters
sx = optarg;
eqpos = sx.find_first_of("=");
if (string::npos != eqpos) // P=V line
{
map_parameters[sx.substr(0,eqpos)] = sx.substr(eqpos+1,sx.length()-eqpos);
}
else { map_parameters[sx] = "yes"; } //take it a s a simple flag
break;
case '?':
if (optopt == 'i')
*fpf_error<<"ERROR: Option -"<<optopt<<" requires an argument.\n";
else if (isprint (optopt))
*fpf_error<<"ERROR: Unknown Option -"<<optopt<<"\n";
else
*fpf_error<<"ERROR: Unknown option character -"<<optopt<<"\n";
return EXIT_ERR_INVALID_ARG;
default:
break;
}// switch (c)
// further arguments are taken as INPUT_FILE
// for (index = optind; index < argc; index++)
if (optind < argc)
{
map_parameters[PARAM_INPUT_FILE] = (char*) argv[optind];
}
//----------------------------------------------
// init fpf
fpf_last_error.clear();
// default ini file, look by executable file name
if (ini_fn.empty())
{
ini_fn = argv[0]; //take an exe file name
string::size_type dot = ini_fn.find_last_of("./\\"); //find the dot or slash, what is the rightmost
if ((dot != string::npos) && (ini_fn[dot] == '.'))
{ ini_fn.erase(dot, string::npos); }
ini_fn += ".ini";
}
*fpf_info<< "* Using INI config from: "<<ini_fn<<endl;
//* read config file *
read_config_file(ini_fn,g_ini,&map_parameters);
///dump_map_of_maps(g_ini,cout);
//check _main_ ini section and accept generic settings
if (g_ini.find(INI_MAIN_SECTION) == g_ini.end())
{
*fpf_error << "\n#ERROR: no [" << INI_MAIN_SECTION << "] section in the ini file\n";
//TO DO - fill dummy main section to work further!
// if no default here, terminate the programm
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}//
//Construct the root framer
s_root_framer = g_ini[INI_MAIN_SECTION][INI_MAIN_FRAMESOURCE];
if (s_root_framer.empty())
{
*fpf_error << "\n#ERROR: no [" << INI_MAIN_FRAMESOURCE << "] set in main section to define root framer\n";
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}
if (g_ini.find(s_root_framer) == g_ini.end())
{
*fpf_error << "\n#ERROR: no [" << INI_MAIN_FRAMESOURCE << "] section to be taken as a root framer\n";
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}
s_fs_class = g_ini[s_root_framer][INI_COMMON_CLASS];
*fpf_info<<"* Using ["<<s_fs_class<<"] as a root frame source\n";
frame_source = new_frame_source(s_fs_class);
if (NULL == frame_source)
{
*fpf_error<<"\n#ERROR: failed to instantiate frame souce.\n";
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}
// run it
if (frame_source->init(g_ini,s_root_framer))
{
cout << "\n===>\n";
frame_source->start();
// close it after termination
cout << "\n<===\n\n";
frame_source->close();
//and kill
delete frame_source; frame_source = NULL;
}else
{
*fpf_error << "\n#ERROR: framer initialization failed.\n";
exit_code = EXIT_ERR_INITIALIZATION_FAILED;
goto THEEND;
}
//OK, bye-bye
*fpf_info<<"* OK, normal termination.\n";
THEEND:
return exit_code;
}
<commit_msg>0.7 version<commit_after>/*
FPF - Frame Processing Framework
See the file COPYING for copying permission.
*/
/*
fpf_main.c - main(), generic chain driver executable for FPF
History:
created: 2015-11 - A.Shumilin.
*/
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
//
#include <ini.h>
#include <fpf.h>
#include "class_factory.h"
//
using namespace std;
//
#define INI_MAIN_SECTION "_main_"
#define INI_MAIN_FRAMESOURCE "frame_source"
//common substitutes
#define PARAM_INPUT_FILE "INPUTFILE"
#define PARAM_OUTPUT_FILE "OUTPUTFILE"
//exit codes
#define EXIT_ERR_CONFIG_INCOMPLETE -1
#define EXIT_ERR_INITIALIZATION_FAILED -2
#define EXIT_ERR_FPF_ASSERT_FAILED EXIT_FPF_ASSERT
#define EXIT_ERR_INVALID_ARG -4
// Globals
t_ini g_ini;
ostream stream_null(NULL);
int main(int argc, char* argv[])
{
cerr<< "*** Frame Processing Framework engine. v 0.7. build: " << __DATE__ <<" *** "<<endl;
int exit_code = 0;
string ini_fn;
IFrameSource* frame_source;
map<string,string> map_parameters;
string s_fs_class;
string s_root_framer;
//------- get command line options ----------------
int carg;
size_t eqpos;string sx;
while ((carg = getopt (argc, argv, "o:D:i:tcs")) != -1)
switch (carg)
{
case 'i': // config ini file
ini_fn = optarg;
break;
case 'o' : //output file
map_parameters[PARAM_OUTPUT_FILE] = optarg;
case 'D': // definition of custom parameters
sx = optarg;
eqpos = sx.find_first_of("=");
if (string::npos != eqpos) // P=V line
{
map_parameters[sx.substr(0,eqpos)] = sx.substr(eqpos+1,sx.length()-eqpos);
}
else { map_parameters[sx] = "yes"; } //take it a s a simple flag
break;
case '?':
if (optopt == 'i')
*fpf_error<<"ERROR: Option -"<<optopt<<" requires an argument.\n";
else if (isprint (optopt))
*fpf_error<<"ERROR: Unknown Option -"<<optopt<<"\n";
else
*fpf_error<<"ERROR: Unknown option character -"<<optopt<<"\n";
return EXIT_ERR_INVALID_ARG;
default:
break;
}// switch (c)
// further arguments are taken as INPUT_FILE
// for (index = optind; index < argc; index++)
if (optind < argc)
{
map_parameters[PARAM_INPUT_FILE] = (char*) argv[optind];
}
//----------------------------------------------
// init fpf
fpf_last_error.clear();
// default ini file, look by executable file name
if (ini_fn.empty())
{
ini_fn = argv[0]; //take an exe file name
string::size_type dot = ini_fn.find_last_of("./\\"); //find the dot or slash, what is the rightmost
if ((dot != string::npos) && (ini_fn[dot] == '.'))
{ ini_fn.erase(dot, string::npos); }
ini_fn += ".ini";
}
*fpf_info<< "* Using INI config from: "<<ini_fn<<endl;
//* read config file *
read_config_file(ini_fn,g_ini,&map_parameters);
///dump_map_of_maps(g_ini,cout);
//check _main_ ini section and accept generic settings
if (g_ini.find(INI_MAIN_SECTION) == g_ini.end())
{
*fpf_error << "\n#ERROR: no [" << INI_MAIN_SECTION << "] section in the ini file\n";
//TO DO - fill dummy main section to work further!
// if no default here, terminate the programm
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}//
//Construct the root framer
s_root_framer = g_ini[INI_MAIN_SECTION][INI_MAIN_FRAMESOURCE];
if (s_root_framer.empty())
{
*fpf_error << "\n#ERROR: no [" << INI_MAIN_FRAMESOURCE << "] set in main section to define root framer\n";
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}
if (g_ini.find(s_root_framer) == g_ini.end())
{
*fpf_error << "\n#ERROR: no [" << INI_MAIN_FRAMESOURCE << "] section to be taken as a root framer\n";
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}
s_fs_class = g_ini[s_root_framer][INI_COMMON_CLASS];
*fpf_info<<"* Using ["<<s_fs_class<<"] as a root frame source\n";
frame_source = new_frame_source(s_fs_class);
if (NULL == frame_source)
{
*fpf_error<<"\n#ERROR: failed to instantiate frame souce.\n";
exit_code = EXIT_ERR_CONFIG_INCOMPLETE;
goto THEEND;
}
// run it
if (frame_source->init(g_ini,s_root_framer))
{
cout << "\n===>\n";
frame_source->start();
// close it after termination
cout << "\n<===\n\n";
frame_source->close();
//and kill
delete frame_source; frame_source = NULL;
}else
{
*fpf_error << "\n#ERROR: framer initialization failed.\n";
exit_code = EXIT_ERR_INITIALIZATION_FAILED;
goto THEEND;
}
//OK, bye-bye
*fpf_info<<"* OK, normal termination.\n";
THEEND:
return exit_code;
}
<|endoftext|>
|
<commit_before>#include "render_pipeline/rpcore/util/primitives.hpp"
#include <geomVertexWriter.h>
#include <geomTriangles.h>
#include <geomNode.h>
#include <materialAttrib.h>
#include "render_pipeline/rpcore/util/rpmaterial.hpp"
namespace rpcore {
static NodePath create_geom_node(const std::string& name, Geom* geom)
{
// default material
CPT(RenderState) state = RenderState::make_empty();
state = state->add_attrib(MaterialAttrib::make(RPMaterial().get_material()));
PT(GeomNode) geom_node = new GeomNode(name);
geom_node->add_geom(geom, state);
return NodePath(geom_node);
}
NodePath create_cube(const std::string& name)
{
// create vertices
PT(GeomVertexData) vdata = new GeomVertexData(name, GeomVertexFormat::get_v3n3t2(), Geom::UsageHint::UH_static);
vdata->unclean_set_num_rows(24);
GeomVertexWriter vertex(vdata, InternalName::get_vertex());
GeomVertexWriter normal(vdata, InternalName::get_normal());
GeomVertexWriter texcoord(vdata, InternalName::get_texcoord());
vertex.add_data3f(-0.5f, -0.5f, -0.5f); normal.add_data3f(0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.25f, 1/3.0f); // 0
vertex.add_data3f(-0.5f, -0.5f, -0.5f); normal.add_data3f(0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.25f, 1/3.0f); // 1
vertex.add_data3f(-0.5f, -0.5f, -0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.25f, 1/3.0f); // 2
vertex.add_data3f(+0.5f, -0.5f, -0.5f); normal.add_data3f(0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.5f, 1/3.0f); // 3
vertex.add_data3f(+0.5f, -0.5f, -0.5f); normal.add_data3f(0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.5f, 1/3.0f); // 4
vertex.add_data3f(+0.5f, -0.5f, -0.5f); normal.add_data3f(1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.5f, 1/3.0f); // 5
vertex.add_data3f(+0.5f, +0.5f, -0.5f); normal.add_data3f(0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.5f, 0.0f); // 6
vertex.add_data3f(+0.5f, +0.5f, -0.5f); normal.add_data3f(0.0f, 1.0f, 0.0f); texcoord.add_data2f(0.75f, 1/3.0f); // 7
vertex.add_data3f(+0.5f, +0.5f, -0.5f); normal.add_data3f(1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.75f, 1/3.0f); // 8
vertex.add_data3f(-0.5f, +0.5f, -0.5f); normal.add_data3f(0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.25f, 0.0f); // 9
vertex.add_data3f(-0.5f, +0.5f, -0.5f); normal.add_data3f(0.0f, 1.0f, 0.0f); texcoord.add_data2f(1.0f, 1/3.0f); // 10
vertex.add_data3f(-0.5f, +0.5f, -0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.0f, 1/3.0f); // 11
vertex.add_data3f(-0.5f, -0.5f, +0.5f); normal.add_data3f(0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.25f, 2/3.0f); // 12
vertex.add_data3f(-0.5f, -0.5f, +0.5f); normal.add_data3f(0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.25f, 2/3.0f); // 13
vertex.add_data3f(-0.5f, -0.5f, +0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.25f, 2/3.0f); // 14
vertex.add_data3f(+0.5f, -0.5f, +0.5f); normal.add_data3f(0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.5f, 2/3.0f); // 15
vertex.add_data3f(+0.5f, -0.5f, +0.5f); normal.add_data3f(0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.5f, 2/3.0f); // 16
vertex.add_data3f(+0.5f, -0.5f, +0.5f); normal.add_data3f(1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.5f, 2/3.0f); // 17
vertex.add_data3f(+0.5f, +0.5f, +0.5f); normal.add_data3f(0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.5f, 1.0f); // 18
vertex.add_data3f(+0.5f, +0.5f, +0.5f); normal.add_data3f(0.0f, 1.0f, 0.0f); texcoord.add_data2f(0.75f, 2/3.0f); // 19
vertex.add_data3f(+0.5f, +0.5f, +0.5f); normal.add_data3f(1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.75f, 2/3.0f); // 20
vertex.add_data3f(-0.5f, +0.5f, +0.5f); normal.add_data3f(0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.25f, 1.0f); // 21
vertex.add_data3f(-0.5f, +0.5f, +0.5f); normal.add_data3f(0.0f, 1.0f, 0.0f); texcoord.add_data2f(1.0f, 2/3.0f); // 22
vertex.add_data3f(-0.5f, +0.5f, +0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.0f, 2/3.0f); // 23
// create indices
PT(GeomTriangles) prim = new GeomTriangles(Geom::UsageHint::UH_static);
prim->reserve_num_vertices(36);
prim->add_vertices(0, 6, 3);
prim->add_vertices(0, 9, 6);
prim->add_vertices(12, 15, 18);
prim->add_vertices(12, 18, 21);
prim->add_vertices(22, 19, 7);
prim->add_vertices(22, 7, 10);
prim->add_vertices(13, 4, 16);
prim->add_vertices(13, 1, 4);
prim->add_vertices(14, 23, 11);
prim->add_vertices(14, 11, 2);
prim->add_vertices(17, 5, 8);
prim->add_vertices(17, 8, 20);
prim->close_primitive();
PT(Geom) geom = new Geom(vdata);
geom->add_primitive(prim);
return create_geom_node(name, geom);
}
NodePath create_sphere(const std::string& name, unsigned int latitude, unsigned int longitude)
{
latitude = (std::max)(1u, latitude);
longitude = (std::max)(1u, longitude);
// create vertices
PT(GeomVertexData) vdata = new GeomVertexData(name, GeomVertexFormat::get_v3n3t2(), Geom::UsageHint::UH_static);
vdata->unclean_set_num_rows((latitude + 1)*(longitude + 1));
GeomVertexWriter vertex(vdata, InternalName::get_vertex());
GeomVertexWriter normal(vdata, InternalName::get_normal());
GeomVertexWriter texcoord(vdata, InternalName::get_texcoord());
const double pi = std::acos(-1);
for (unsigned int i = 0; i <= latitude; ++i)
{
const double theta = i * pi / double(latitude);
for (unsigned int j = 0; j <= longitude; ++j)
{
const double phi = j * 2.0 * pi / double(longitude);
const double sin_theta = std::sin(theta);
const double x = std::cos(phi) * sin_theta;
const double y = std::sin(phi) * sin_theta;
const double z = std::cos(theta);
vertex.add_data3f(x, y, z);
normal.add_data3f(x, y, z);
texcoord.add_data2f(j / double(longitude), 1.0 - i / double(latitude));
}
}
// create indices
PT(GeomTriangles) prim = new GeomTriangles(Geom::UsageHint::UH_static);
prim->reserve_num_vertices(longitude * latitude * 6);
for (unsigned int i = 0; i < latitude; ++i)
{
for (unsigned int j = 0; j < longitude; ++j)
{
const int a = i * (longitude + 1) + j;
const int b = a + (longitude + 1);
prim->add_vertices(a, b, a+1);
prim->add_vertices(b, b+1, a+1);
}
}
prim->close_primitive();
PT(Geom) geom = new Geom(vdata);
geom->add_primitive(prim);
return create_geom_node(name, geom);
}
}
<commit_msg>Fix cube vertices and indices.<commit_after>#include "render_pipeline/rpcore/util/primitives.hpp"
#include <geomVertexWriter.h>
#include <geomTriangles.h>
#include <geomNode.h>
#include <materialAttrib.h>
#include "render_pipeline/rpcore/util/rpmaterial.hpp"
namespace rpcore {
static NodePath create_geom_node(const std::string& name, Geom* geom)
{
// default material
CPT(RenderState) state = RenderState::make_empty();
state = state->add_attrib(MaterialAttrib::make(RPMaterial().get_material()));
PT(GeomNode) geom_node = new GeomNode(name);
geom_node->add_geom(geom, state);
return NodePath(geom_node);
}
NodePath create_cube(const std::string& name)
{
// create vertices
PT(GeomVertexData) vdata = new GeomVertexData(name, GeomVertexFormat::get_v3n3t2(), Geom::UsageHint::UH_static);
vdata->unclean_set_num_rows(24);
GeomVertexWriter vertex(vdata, InternalName::get_vertex());
GeomVertexWriter normal(vdata, InternalName::get_normal());
GeomVertexWriter texcoord(vdata, InternalName::get_texcoord());
// top
vertex.add_data3f(+0.5f, +0.5f, +0.5f); normal.add_data3f( 0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.5f, 1.0f); // 0
vertex.add_data3f(-0.5f, +0.5f, +0.5f); normal.add_data3f( 0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.25f, 1.0f); // 1
vertex.add_data3f(+0.5f, -0.5f, +0.5f); normal.add_data3f( 0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.5f, 2/3.0f); // 2
vertex.add_data3f(-0.5f, -0.5f, +0.5f); normal.add_data3f( 0.0f, 0.0f, 1.0f); texcoord.add_data2f(0.25f, 2/3.0f); // 3
// right
vertex.add_data3f(+0.5f, +0.5f, -0.5f); normal.add_data3f( 1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.75f, 1/3.0f); // 4
vertex.add_data3f(+0.5f, +0.5f, +0.5f); normal.add_data3f( 1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.75f, 2/3.0f); // 5
vertex.add_data3f(+0.5f, -0.5f, -0.5f); normal.add_data3f( 1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.5f, 1/3.0f); // 6
vertex.add_data3f(+0.5f, -0.5f, +0.5f); normal.add_data3f( 1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.5f, 2/3.0f); // 7
// back
vertex.add_data3f(-0.5f, +0.5f, -0.5f); normal.add_data3f( 0.0f, 1.0f, 0.0f); texcoord.add_data2f(1.0f, 1/3.0f); // 8
vertex.add_data3f(-0.5f, +0.5f, +0.5f); normal.add_data3f( 0.0f, 1.0f, 0.0f); texcoord.add_data2f(1.0f, 2/3.0f); // 9
vertex.add_data3f(+0.5f, +0.5f, +0.5f); normal.add_data3f( 0.0f, 1.0f, 0.0f); texcoord.add_data2f(0.75f, 2/3.0f); // 10
vertex.add_data3f(+0.5f, +0.5f, -0.5f); normal.add_data3f( 0.0f, 1.0f, 0.0f); texcoord.add_data2f(0.75f, 1/3.0f); // 11
// bottom
vertex.add_data3f(-0.5f, -0.5f, -0.5f); normal.add_data3f( 0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.25f, 1/3.0f); // 12
vertex.add_data3f(-0.5f, +0.5f, -0.5f); normal.add_data3f( 0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.25f, 0.0f); // 13
vertex.add_data3f(+0.5f, -0.5f, -0.5f); normal.add_data3f( 0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.5f, 1/3.0f); // 14
vertex.add_data3f(+0.5f, +0.5f, -0.5f); normal.add_data3f( 0.0f, 0.0f, -1.0f); texcoord.add_data2f(0.5f, 0.0f); // 15
// front
vertex.add_data3f(-0.5f, -0.5f, -0.5f); normal.add_data3f( 0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.25f, 1/3.0f); // 16
vertex.add_data3f(+0.5f, -0.5f, -0.5f); normal.add_data3f( 0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.5f, 1/3.0f); // 17
vertex.add_data3f(-0.5f, -0.5f, +0.5f); normal.add_data3f( 0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.25f, 2/3.0f); // 18
vertex.add_data3f(+0.5f, -0.5f, +0.5f); normal.add_data3f( 0.0f, -1.0f, 0.0f); texcoord.add_data2f(0.5f, 2/3.0f); // 19
// left
vertex.add_data3f(-0.5f, -0.5f, -0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.25f, 1/3.0f); // 20
vertex.add_data3f(-0.5f, -0.5f, +0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.25f, 2/3.0f); // 21
vertex.add_data3f(-0.5f, +0.5f, -0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.0f, 1/3.0f); // 22
vertex.add_data3f(-0.5f, +0.5f, +0.5f); normal.add_data3f(-1.0f, 0.0f, 0.0f); texcoord.add_data2f(0.0f, 2/3.0f); // 23
// create indices
PT(GeomTriangles) prim = new GeomTriangles(Geom::UsageHint::UH_static);
prim->reserve_num_vertices(36);
prim->add_vertices(0, 1, 2);
prim->add_vertices(3, 2, 1);
prim->add_vertices(4, 5, 7);
prim->add_vertices(6, 4, 7);
prim->add_vertices(10, 11, 9);
prim->add_vertices(8, 9, 11);
prim->add_vertices(12, 13, 14);
prim->add_vertices(15, 14, 13);
prim->add_vertices(16, 17, 18);
prim->add_vertices(19, 18, 17);
prim->add_vertices(20, 21, 22);
prim->add_vertices(23, 22, 21);
prim->close_primitive();
PT(Geom) geom = new Geom(vdata);
geom->add_primitive(prim);
return create_geom_node(name, geom);
}
NodePath create_sphere(const std::string& name, unsigned int latitude, unsigned int longitude)
{
latitude = (std::max)(1u, latitude);
longitude = (std::max)(1u, longitude);
// create vertices
PT(GeomVertexData) vdata = new GeomVertexData(name, GeomVertexFormat::get_v3n3t2(), Geom::UsageHint::UH_static);
vdata->unclean_set_num_rows((latitude + 1)*(longitude + 1));
GeomVertexWriter vertex(vdata, InternalName::get_vertex());
GeomVertexWriter normal(vdata, InternalName::get_normal());
GeomVertexWriter texcoord(vdata, InternalName::get_texcoord());
const double pi = std::acos(-1);
for (unsigned int i = 0; i <= latitude; ++i)
{
const double theta = i * pi / double(latitude);
for (unsigned int j = 0; j <= longitude; ++j)
{
const double phi = j * 2.0 * pi / double(longitude);
const double sin_theta = std::sin(theta);
const double x = std::cos(phi) * sin_theta;
const double y = std::sin(phi) * sin_theta;
const double z = std::cos(theta);
vertex.add_data3f(x, y, z);
normal.add_data3f(x, y, z);
texcoord.add_data2f(j / double(longitude), 1.0 - i / double(latitude));
}
}
// create indices
PT(GeomTriangles) prim = new GeomTriangles(Geom::UsageHint::UH_static);
prim->reserve_num_vertices(longitude * latitude * 6);
for (unsigned int i = 0; i < latitude; ++i)
{
for (unsigned int j = 0; j < longitude; ++j)
{
const int a = i * (longitude + 1) + j;
const int b = a + (longitude + 1);
prim->add_vertices(a, b, a+1);
prim->add_vertices(b, b+1, a+1);
}
}
prim->close_primitive();
PT(Geom) geom = new Geom(vdata);
geom->add_primitive(prim);
return create_geom_node(name, geom);
}
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <random>
#include <cmath>
#include <string>
#include <cstring>
#include <stdexcept>
#include <cassert>
//------------------------------------------------------------------------------
namespace base91
{
static const unsigned base=91;
static const unsigned char_bits=8;
static const unsigned digit_bits=13;
static const unsigned digit_size=0x2000;
static const unsigned digit_mask=0x1FFF;
void encode(const std::vector<unsigned char> & in,std::string & out)
{
out.clear();
out.reserve(digit_bits*in.size()/char_bits+2);
unsigned acc=0;
int bitacc=0;
for (auto & n:in)
{
acc <<= char_bits;
acc |= n;
bitacc+=char_bits;
while(digit_bits>=bitacc)
{
const unsigned cod = digit_mask & acc;
out.push_back(lo[cod]);
out.push_back(hi[cod]);
acc>>=digit_bits;
bitacc-=digit_bits;
}
}
while(0 < bitacc)
{
const unsigned cod = digit_mask & acc;
out.push_back(lo[cod]);
out.push_back(hi[cod]);
acc>>=digit_bits;
bitacc-=digit_bits;
}
return;
}
void decode(const std::string & in,std::vector<unsigned char> & out)
{
return;
}
}
//------------------------------------------------------------------------------
int main()
{
std::vector<unsigned char> in{0,0,0,0,0,0,0,0,0};
std::string out;
base91::encode(in,out);
std::cout<<out<<std::endl;
return 0;
}
//------------------------------------------------------------------------------
<commit_msg>commit and sleep<commit_after>#include <cstdio>
#include <random>
#include <cmath>
#include <string>
#include <cstring>
#include <stdexcept>
#include <cassert>
#include <iostream>
//------------------------------------------------------------------------------
namespace base91
{
static const unsigned base=91;
static const unsigned char_bits=8;
static const unsigned digit_bits=13;
static const unsigned digit_size=0x2000;
static const unsigned digit_mask=0x1FFF;
char hi[digit_size]={'~',};
char lo[digit_size]={'~',};
unsigned short hilo[base][base]={0,};
void encode(const std::vector<unsigned char> & in,std::string & out)
{
out.clear();
out.reserve(digit_bits*in.size()/char_bits+2);
unsigned acc=0;
int bitacc=0;
for (auto & n:in)
{
acc <<= char_bits;
acc |= n;
bitacc+=char_bits;
while(digit_bits>=bitacc)
{
const unsigned cod = digit_mask & acc;
out.push_back(lo[cod]);
out.push_back(hi[cod]);
acc>>=digit_bits;
bitacc-=digit_bits;
}
}
if(0 < bitacc)
{
const unsigned cod = digit_mask & acc;
out.push_back(lo[cod]);
if(bitacc>=7)
out.push_back(hi[cod]);
}
return;
}
void decode(const std::string & in,std::vector<unsigned char> & out)
{
out.clear();
out.reserve(char_bits*in.size()/digit_bits);
unsigned acc=0;
int bitacc=0;
short lower=-1;
for (auto & n:in)
{
if(-1==lower)
{
lower=n-'!';
continue;
}
acc<<=digit_bits;
acc|=hilo[n-'!'][lower];
bitacc+=digit_bits;
lower=-1;
while(char_bits<=bitacc)
{
out.push_back(0xFF & acc);
acc>>=char_bits;
bitacc-=char_bits;
}
}
if(-1!=lower)
{
acc<<=digit_bits;
acc|=hilo[0][lower];
bitacc+=7;
}
while(char_bits<=bitacc)
{
out.push_back(0xFF & acc);
acc>>=char_bits;
bitacc-=char_bits;
}
return;
}
}
//------------------------------------------------------------------------------
int main()
{
for(unsigned n=0, hi=0,lo=0;n<base91::digit_size;++n)
{
base91::lo[n]='!'+lo;
base91::hi[n]='!'+hi;
base91::hilo[hi][lo]=n;
if(base91::base==(++lo))
{
hi++;
lo=0;
}
}
std::vector<unsigned char> in{0,1,2,3,0,0,1,2,0};
std::string out;
base91::encode(in,out);
std::cout<<out<<std::endl;
std::vector<unsigned char> test;
base91::decode(out,test);
for(auto n:test)
std::cout<<":"<<(short)n;
std::cout<<out<<std::endl;
for(auto n:in)
std::cout<<":"<<(short)n;
std::cout<<out<<std::endl;
return 0;
}
//------------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>#include <windows.h>
#include <tchar.h>
#include <Shlwapi.h>
#include "resource.h"
#include <vector>
#pragma comment(lib, "Shlwapi.lib")
#ifndef UNICODE
#error "Must be compiled with unicode support."
#endif
#define USE_TASKBAR_API (_WIN32_WINNT >= _WIN32_WINNT_WIN7)
#define XP (_WIN32_WINNT < _WIN32_WINNT_VISTA)
#define MB_TITLE L"Cmder Launcher"
#define SHELL_MENU_REGISTRY_PATH_BACKGROUND L"Directory\\Background\\shell\\Cmder"
#define SHELL_MENU_REGISTRY_PATH_LISTITEM L"Directory\\shell\\Cmder"
#define streqi(a, b) (_wcsicmp((a), (b)) == 0)
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFUNCTION__ WIDEN(__FUNCTION__)
#define FAIL_ON_ERROR(x) { DWORD ec; if ((ec = (x)) != ERROR_SUCCESS) { ShowErrorAndExit(ec, __WFUNCTION__, __LINE__); } }
void ShowErrorAndExit(DWORD ec, const wchar_t * func, int line)
{
wchar_t * buffer;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ec, 0, (LPWSTR) &buffer, 0, NULL) == 0)
{
buffer = L"Unknown error. FormatMessage failed.";
}
wchar_t message[1024];
swprintf_s(message, L"%s\nFunction: %s\nLine: %d", buffer, func, line);
LocalFree(buffer);
MessageBox(NULL, message, MB_TITLE, MB_OK | MB_ICONERROR);
exit(1);
}
typedef struct _option
{
std::wstring name;
bool hasVal;
std::wstring value;
bool set;
} option;
typedef std::pair<std::wstring, std::wstring> optpair;
optpair GetOption()
{
wchar_t * cmd = GetCommandLine();
int argc;
wchar_t ** argv = CommandLineToArgvW(cmd, &argc);
optpair pair;
if (argc == 1)
{
// no commandline argument...
pair = optpair(L"/START", L"");
}
else if (argc == 2 && argv[1][0] != L'/')
{
// only a single argument: this should be a path...
pair = optpair(L"/START", argv[1]);
}
else
{
pair = optpair(argv[1], argc > 2 ? argv[2] : L"");
}
LocalFree(argv);
return pair;
}
bool FileExists(const wchar_t * filePath)
{
HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return true;
}
return false;
}
void StartCmder(std::wstring path, bool is_single_mode)
{
#if USE_TASKBAR_API
wchar_t appId[MAX_PATH] = { 0 };
#endif
wchar_t exeDir[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
wchar_t cfgPath[MAX_PATH] = { 0 };
wchar_t oldCfgPath[MAX_PATH] = { 0 };
wchar_t conEmuPath[MAX_PATH] = { 0 };
wchar_t args[MAX_PATH * 2 + 256] = { 0 };
GetModuleFileName(NULL, exeDir, sizeof(exeDir));
#if USE_TASKBAR_API
wcscpy_s(appId, exeDir);
#endif
PathRemoveFileSpec(exeDir);
PathCombine(icoPath, exeDir, L"icons\\cmder.ico");
// Check for machine-specific config file.
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(oldCfgPath, oldCfgPath, sizeof(oldCfgPath) / sizeof(oldCfgPath[0]));
if (!PathFileExists(oldCfgPath)) {
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu.xml");
}
// Check for machine-specific config file.
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(cfgPath, cfgPath, sizeof(cfgPath) / sizeof(cfgPath[0]));
if (!PathFileExists(cfgPath)) {
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.xml");
}
PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.exe");
if (FileExists(oldCfgPath) && !FileExists(cfgPath))
{
if (!CopyFile(oldCfgPath, cfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
? L"Failed to copy ConEmu.xml file to new location! Restart cmder as administrator."
: L"Failed to copy ConEmu.xml file to new location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
if (is_single_mode)
{
swprintf_s(args, L"/single /Icon \"%s\" /Title Cmder", icoPath);
}
else
{
swprintf_s(args, L"/Icon \"%s\" /Title Cmder", icoPath);
}
SetEnvironmentVariable(L"CMDER_ROOT", exeDir);
if (!streqi(path.c_str(), L""))
{
SetEnvironmentVariable(L"CMDER_START", path.c_str());
}
else
{
static char buff[MAX_PATH];
GetEnvironmentVariable(L"USER_PROFILE", buff, MAX_PATH);
SetEnvironmentVariable(L"CMDER_START", buff);
}
STARTUPINFO si = { 0 };
si.cb = sizeof(STARTUPINFO);
#if USE_TASKBAR_API
si.lpTitle = appId;
si.dwFlags = STARTF_TITLEISAPPID;
#endif
PROCESS_INFORMATION pi;
CreateProcess(conEmuPath, args, NULL, NULL, false, 0, NULL, NULL, &si, &pi);
}
bool IsUserOnly(std::wstring opt)
{
bool userOnly;
if (streqi(opt.c_str(), L"ALL"))
{
userOnly = false;
}
else if (streqi(opt.c_str(), L"USER"))
{
userOnly = true;
}
else
{
MessageBox(NULL, L"Unrecognized option for /REGISTER or /UNREGISTER. Must be either ALL or USER.", MB_TITLE, MB_OK);
exit(1);
}
return userOnly;
}
HKEY GetRootKey(std::wstring opt)
{
HKEY root;
if (IsUserOnly(opt))
{
FAIL_ON_ERROR(RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Classes", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &root, NULL));
}
else
{
root = HKEY_CLASSES_ROOT;
}
return root;
}
void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
// First, get the paths we will use
wchar_t exePath[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, exePath, sizeof(exePath));
wchar_t commandStr[MAX_PATH + 20] = { 0 };
swprintf_s(commandStr, L"\"%s\" \"%%V\"", exePath);
// Now that we have `commandStr`, it's OK to change `exePath`...
PathRemoveFileSpec(exePath);
PathCombine(icoPath, exePath, L"icons\\cmder.ico");
// Now set the registry keys
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
FAIL_ON_ERROR(RegSetValue(cmderKey, L"", REG_SZ, L"Cmder Here", NULL));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"NoWorkingDirectory", 0, REG_SZ, (BYTE *)L"", 2));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"Icon", 0, REG_SZ, (BYTE *)icoPath, wcslen(icoPath) * sizeof(wchar_t)));
HKEY command;
FAIL_ON_ERROR(
RegCreateKeyEx(cmderKey, L"command", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &command, NULL));
FAIL_ON_ERROR(RegSetValue(command, L"", REG_SZ, commandStr, NULL));
RegCloseKey(command);
RegCloseKey(cmderKey);
RegCloseKey(root);
}
void UnregisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
#if XP
FAIL_ON_ERROR(SHDeleteKey(cmderKey, NULL));
#else
FAIL_ON_ERROR(RegDeleteTree(cmderKey, NULL));
#endif
RegCloseKey(cmderKey);
RegCloseKey(root);
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
optpair opt = GetOption();
if (streqi(opt.first.c_str(), L"/START"))
{
StartCmder(opt.second, false);
}
else if (streqi(opt.first.c_str(), L"/SINGLE"))
{
StartCmder(opt.second, true);
}
else if (streqi(opt.first.c_str(), L"/REGISTER"))
{
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else if (streqi(opt.first.c_str(), L"/UNREGISTER"))
{
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else
{
MessageBox(NULL, L"Unrecognized parameter.\n\nValid options:\n /START <path>\n /SINGLE <path>\n /REGISTER [USER/ALL]\n /UNREGISTER [USER/ALL]", MB_TITLE, MB_OK);
return 1;
}
return 0;
}
<commit_msg>Use the correct type and initialise it.<commit_after>#include <windows.h>
#include <tchar.h>
#include <Shlwapi.h>
#include "resource.h"
#include <vector>
#pragma comment(lib, "Shlwapi.lib")
#ifndef UNICODE
#error "Must be compiled with unicode support."
#endif
#define USE_TASKBAR_API (_WIN32_WINNT >= _WIN32_WINNT_WIN7)
#define XP (_WIN32_WINNT < _WIN32_WINNT_VISTA)
#define MB_TITLE L"Cmder Launcher"
#define SHELL_MENU_REGISTRY_PATH_BACKGROUND L"Directory\\Background\\shell\\Cmder"
#define SHELL_MENU_REGISTRY_PATH_LISTITEM L"Directory\\shell\\Cmder"
#define streqi(a, b) (_wcsicmp((a), (b)) == 0)
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFUNCTION__ WIDEN(__FUNCTION__)
#define FAIL_ON_ERROR(x) { DWORD ec; if ((ec = (x)) != ERROR_SUCCESS) { ShowErrorAndExit(ec, __WFUNCTION__, __LINE__); } }
void ShowErrorAndExit(DWORD ec, const wchar_t * func, int line)
{
wchar_t * buffer;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ec, 0, (LPWSTR) &buffer, 0, NULL) == 0)
{
buffer = L"Unknown error. FormatMessage failed.";
}
wchar_t message[1024];
swprintf_s(message, L"%s\nFunction: %s\nLine: %d", buffer, func, line);
LocalFree(buffer);
MessageBox(NULL, message, MB_TITLE, MB_OK | MB_ICONERROR);
exit(1);
}
typedef struct _option
{
std::wstring name;
bool hasVal;
std::wstring value;
bool set;
} option;
typedef std::pair<std::wstring, std::wstring> optpair;
optpair GetOption()
{
wchar_t * cmd = GetCommandLine();
int argc;
wchar_t ** argv = CommandLineToArgvW(cmd, &argc);
optpair pair;
if (argc == 1)
{
// no commandline argument...
pair = optpair(L"/START", L"");
}
else if (argc == 2 && argv[1][0] != L'/')
{
// only a single argument: this should be a path...
pair = optpair(L"/START", argv[1]);
}
else
{
pair = optpair(argv[1], argc > 2 ? argv[2] : L"");
}
LocalFree(argv);
return pair;
}
bool FileExists(const wchar_t * filePath)
{
HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return true;
}
return false;
}
void StartCmder(std::wstring path, bool is_single_mode)
{
#if USE_TASKBAR_API
wchar_t appId[MAX_PATH] = { 0 };
#endif
wchar_t exeDir[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
wchar_t cfgPath[MAX_PATH] = { 0 };
wchar_t oldCfgPath[MAX_PATH] = { 0 };
wchar_t conEmuPath[MAX_PATH] = { 0 };
wchar_t args[MAX_PATH * 2 + 256] = { 0 };
GetModuleFileName(NULL, exeDir, sizeof(exeDir));
#if USE_TASKBAR_API
wcscpy_s(appId, exeDir);
#endif
PathRemoveFileSpec(exeDir);
PathCombine(icoPath, exeDir, L"icons\\cmder.ico");
// Check for machine-specific config file.
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(oldCfgPath, oldCfgPath, sizeof(oldCfgPath) / sizeof(oldCfgPath[0]));
if (!PathFileExists(oldCfgPath)) {
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu.xml");
}
// Check for machine-specific config file.
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(cfgPath, cfgPath, sizeof(cfgPath) / sizeof(cfgPath[0]));
if (!PathFileExists(cfgPath)) {
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.xml");
}
PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.exe");
if (FileExists(oldCfgPath) && !FileExists(cfgPath))
{
if (!CopyFile(oldCfgPath, cfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
? L"Failed to copy ConEmu.xml file to new location! Restart cmder as administrator."
: L"Failed to copy ConEmu.xml file to new location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
if (is_single_mode)
{
swprintf_s(args, L"/single /Icon \"%s\" /Title Cmder", icoPath);
}
else
{
swprintf_s(args, L"/Icon \"%s\" /Title Cmder", icoPath);
}
SetEnvironmentVariable(L"CMDER_ROOT", exeDir);
if (!streqi(path.c_str(), L""))
{
SetEnvironmentVariable(L"CMDER_START", path.c_str());
}
else
{
static wchar_t buff[MAX_PATH] = { 0 };
GetEnvironmentVariable(L"USER_PROFILE", buff, MAX_PATH);
SetEnvironmentVariable(L"CMDER_START", buff);
}
STARTUPINFO si = { 0 };
si.cb = sizeof(STARTUPINFO);
#if USE_TASKBAR_API
si.lpTitle = appId;
si.dwFlags = STARTF_TITLEISAPPID;
#endif
PROCESS_INFORMATION pi;
CreateProcess(conEmuPath, args, NULL, NULL, false, 0, NULL, NULL, &si, &pi);
}
bool IsUserOnly(std::wstring opt)
{
bool userOnly;
if (streqi(opt.c_str(), L"ALL"))
{
userOnly = false;
}
else if (streqi(opt.c_str(), L"USER"))
{
userOnly = true;
}
else
{
MessageBox(NULL, L"Unrecognized option for /REGISTER or /UNREGISTER. Must be either ALL or USER.", MB_TITLE, MB_OK);
exit(1);
}
return userOnly;
}
HKEY GetRootKey(std::wstring opt)
{
HKEY root;
if (IsUserOnly(opt))
{
FAIL_ON_ERROR(RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Classes", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &root, NULL));
}
else
{
root = HKEY_CLASSES_ROOT;
}
return root;
}
void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
// First, get the paths we will use
wchar_t exePath[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, exePath, sizeof(exePath));
wchar_t commandStr[MAX_PATH + 20] = { 0 };
swprintf_s(commandStr, L"\"%s\" \"%%V\"", exePath);
// Now that we have `commandStr`, it's OK to change `exePath`...
PathRemoveFileSpec(exePath);
PathCombine(icoPath, exePath, L"icons\\cmder.ico");
// Now set the registry keys
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
FAIL_ON_ERROR(RegSetValue(cmderKey, L"", REG_SZ, L"Cmder Here", NULL));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"NoWorkingDirectory", 0, REG_SZ, (BYTE *)L"", 2));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"Icon", 0, REG_SZ, (BYTE *)icoPath, wcslen(icoPath) * sizeof(wchar_t)));
HKEY command;
FAIL_ON_ERROR(
RegCreateKeyEx(cmderKey, L"command", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &command, NULL));
FAIL_ON_ERROR(RegSetValue(command, L"", REG_SZ, commandStr, NULL));
RegCloseKey(command);
RegCloseKey(cmderKey);
RegCloseKey(root);
}
void UnregisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
#if XP
FAIL_ON_ERROR(SHDeleteKey(cmderKey, NULL));
#else
FAIL_ON_ERROR(RegDeleteTree(cmderKey, NULL));
#endif
RegCloseKey(cmderKey);
RegCloseKey(root);
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
optpair opt = GetOption();
if (streqi(opt.first.c_str(), L"/START"))
{
StartCmder(opt.second, false);
}
else if (streqi(opt.first.c_str(), L"/SINGLE"))
{
StartCmder(opt.second, true);
}
else if (streqi(opt.first.c_str(), L"/REGISTER"))
{
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else if (streqi(opt.first.c_str(), L"/UNREGISTER"))
{
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else
{
MessageBox(NULL, L"Unrecognized parameter.\n\nValid options:\n /START <path>\n /SINGLE <path>\n /REGISTER [USER/ALL]\n /UNREGISTER [USER/ALL]", MB_TITLE, MB_OK);
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <windows.h>
#include <tchar.h>
#include <Shlwapi.h>
#include "resource.h"
#include <vector>
#pragma comment(lib, "Shlwapi.lib")
#ifndef UNICODE
#error "Must be compiled with unicode support."
#endif
#define USE_TASKBAR_API (_WIN32_WINNT >= _WIN32_WINNT_WIN7)
#define XP (_WIN32_WINNT < _WIN32_WINNT_VISTA)
#define MB_TITLE L"Cmder Launcher"
#define SHELL_MENU_REGISTRY_PATH_BACKGROUND L"Directory\\Background\\shell\\Cmder"
#define SHELL_MENU_REGISTRY_PATH_LISTITEM L"Directory\\shell\\Cmder"
#define streqi(a, b) (_wcsicmp((a), (b)) == 0)
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFUNCTION__ WIDEN(__FUNCTION__)
#define FAIL_ON_ERROR(x) { DWORD ec; if ((ec = (x)) != ERROR_SUCCESS) { ShowErrorAndExit(ec, __WFUNCTION__, __LINE__); } }
void ShowErrorAndExit(DWORD ec, const wchar_t * func, int line)
{
wchar_t * buffer;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ec, 0, (LPWSTR) &buffer, 0, NULL) == 0)
{
buffer = L"Unknown error. FormatMessage failed.";
}
wchar_t message[1024];
swprintf_s(message, L"%s\nFunction: %s\nLine: %d", buffer, func, line);
LocalFree(buffer);
MessageBox(NULL, message, MB_TITLE, MB_OK | MB_ICONERROR);
exit(1);
}
typedef struct _option
{
std::wstring name;
bool hasVal;
std::wstring value;
bool set;
} option;
typedef std::pair<std::wstring, std::wstring> optpair;
optpair GetOption()
{
wchar_t * cmd = GetCommandLine();
int argc;
wchar_t ** argv = CommandLineToArgvW(cmd, &argc);
optpair pair;
if (argc == 1)
{
// no commandline argument...
pair = optpair(L"/START", L"");
}
else if (argc == 2 && argv[1][0] != L'/')
{
// only a single argument: this should be a path...
pair = optpair(L"/START", argv[1]);
}
else
{
pair = optpair(argv[1], argc > 2 ? argv[2] : L"");
}
LocalFree(argv);
return pair;
}
bool FileExists(const wchar_t * filePath)
{
HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return true;
}
return false;
}
void StartCmder(std::wstring path, bool is_single_mode)
{
#if USE_TASKBAR_API
wchar_t appId[MAX_PATH] = { 0 };
#endif
wchar_t exeDir[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
wchar_t cfgPath[MAX_PATH] = { 0 };
wchar_t oldCfgPath[MAX_PATH] = { 0 };
wchar_t conEmuPath[MAX_PATH] = { 0 };
wchar_t args[MAX_PATH * 2 + 256] = { 0 };
GetModuleFileName(NULL, exeDir, sizeof(exeDir));
#if USE_TASKBAR_API
wcscpy_s(appId, exeDir);
#endif
PathRemoveFileSpec(exeDir);
PathCombine(icoPath, exeDir, L"icons\\cmder.ico");
// Check for machine-specific config file.
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(oldCfgPath, oldCfgPath, sizeof(oldCfgPath) / sizeof(oldCfgPath[0]));
if (!PathFileExists(oldCfgPath)) {
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu.xml");
}
// Check for machine-specific config file.
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(cfgPath, cfgPath, sizeof(cfgPath) / sizeof(cfgPath[0]));
if (!PathFileExists(cfgPath)) {
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.xml");
}
PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.exe");
if (FileExists(oldCfgPath) && !FileExists(cfgPath))
{
if (!CopyFile(oldCfgPath, cfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
? L"Failed to copy ConEmu.xml file to new location! Restart cmder as administrator."
: L"Failed to copy ConEmu.xml file to new location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
if (is_single_mode)
{
swprintf_s(args, L"/single /Icon \"%s\" /Title Cmder", icoPath);
}
else
{
swprintf_s(args, L"/Icon \"%s\" /Title Cmder", icoPath);
}
SetEnvironmentVariable(L"CMDER_ROOT", exeDir);
if (!streqi(path.c_str(), L""))
{
if (!SetEnvironmentVariable(L"CMDER_START", path.c_str())) {
MessageBox(NULL, _T("Error trying to set CMDER_START to given path!"), _T("Error"), MB_OK);
}
}
// Ensure EnvironmentVariables are propagated.
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 5000, NULL);
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) L"Environment", SMTO_ABORTIFHUNG, 5000, NULL); // For Windows >= 8
STARTUPINFO si = { 0 };
si.cb = sizeof(STARTUPINFO);
#if USE_TASKBAR_API
si.lpTitle = appId;
si.dwFlags = STARTF_TITLEISAPPID;
#endif
PROCESS_INFORMATION pi;
if (!CreateProcess(conEmuPath, args, NULL, NULL, false, 0, NULL, NULL, &si, &pi)) {
MessageBox(NULL, _T("Unable to create the ConEmu Process!"), _T("Error"), MB_OK);
return;
}
}
bool IsUserOnly(std::wstring opt)
{
bool userOnly;
if (streqi(opt.c_str(), L"ALL"))
{
userOnly = false;
}
else if (streqi(opt.c_str(), L"USER"))
{
userOnly = true;
}
else
{
MessageBox(NULL, L"Unrecognized option for /REGISTER or /UNREGISTER. Must be either ALL or USER.", MB_TITLE, MB_OK);
exit(1);
}
return userOnly;
}
HKEY GetRootKey(std::wstring opt)
{
HKEY root;
if (IsUserOnly(opt))
{
FAIL_ON_ERROR(RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Classes", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &root, NULL));
}
else
{
root = HKEY_CLASSES_ROOT;
}
return root;
}
void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
// First, get the paths we will use
wchar_t exePath[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, exePath, sizeof(exePath));
wchar_t commandStr[MAX_PATH + 20] = { 0 };
swprintf_s(commandStr, L"\"%s\" \"%%V\"", exePath);
// Now that we have `commandStr`, it's OK to change `exePath`...
PathRemoveFileSpec(exePath);
PathCombine(icoPath, exePath, L"icons\\cmder.ico");
// Now set the registry keys
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
FAIL_ON_ERROR(RegSetValue(cmderKey, L"", REG_SZ, L"Cmder Here", NULL));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"NoWorkingDirectory", 0, REG_SZ, (BYTE *)L"", 2));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"Icon", 0, REG_SZ, (BYTE *)icoPath, wcslen(icoPath) * sizeof(wchar_t)));
HKEY command;
FAIL_ON_ERROR(
RegCreateKeyEx(cmderKey, L"command", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &command, NULL));
FAIL_ON_ERROR(RegSetValue(command, L"", REG_SZ, commandStr, NULL));
RegCloseKey(command);
RegCloseKey(cmderKey);
RegCloseKey(root);
}
void UnregisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
#if XP
FAIL_ON_ERROR(SHDeleteKey(cmderKey, NULL));
#else
FAIL_ON_ERROR(RegDeleteTree(cmderKey, NULL));
#endif
RegCloseKey(cmderKey);
RegCloseKey(root);
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
optpair opt = GetOption();
if (streqi(opt.first.c_str(), L"/START"))
{
StartCmder(opt.second, false);
}
else if (streqi(opt.first.c_str(), L"/SINGLE"))
{
StartCmder(opt.second, true);
}
else if (streqi(opt.first.c_str(), L"/REGISTER"))
{
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else if (streqi(opt.first.c_str(), L"/UNREGISTER"))
{
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else
{
MessageBox(NULL, L"Unrecognized parameter.\n\nValid options:\n /START <path>\n /SINGLE <path>\n /REGISTER [USER/ALL]\n /UNREGISTER [USER/ALL]", MB_TITLE, MB_OK);
return 1;
}
return 0;
}
<commit_msg>make launcher run ConEmu64 on 64-bit Windows<commit_after>#include <windows.h>
#include <tchar.h>
#include <Shlwapi.h>
#include "resource.h"
#include <vector>
#pragma comment(lib, "Shlwapi.lib")
#ifndef UNICODE
#error "Must be compiled with unicode support."
#endif
#define USE_TASKBAR_API (_WIN32_WINNT >= _WIN32_WINNT_WIN7)
#define XP (_WIN32_WINNT < _WIN32_WINNT_VISTA)
#define MB_TITLE L"Cmder Launcher"
#define SHELL_MENU_REGISTRY_PATH_BACKGROUND L"Directory\\Background\\shell\\Cmder"
#define SHELL_MENU_REGISTRY_PATH_LISTITEM L"Directory\\shell\\Cmder"
#define streqi(a, b) (_wcsicmp((a), (b)) == 0)
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define __WFUNCTION__ WIDEN(__FUNCTION__)
#define FAIL_ON_ERROR(x) { DWORD ec; if ((ec = (x)) != ERROR_SUCCESS) { ShowErrorAndExit(ec, __WFUNCTION__, __LINE__); } }
void ShowErrorAndExit(DWORD ec, const wchar_t * func, int line)
{
wchar_t * buffer;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, ec, 0, (LPWSTR) &buffer, 0, NULL) == 0)
{
buffer = L"Unknown error. FormatMessage failed.";
}
wchar_t message[1024];
swprintf_s(message, L"%s\nFunction: %s\nLine: %d", buffer, func, line);
LocalFree(buffer);
MessageBox(NULL, message, MB_TITLE, MB_OK | MB_ICONERROR);
exit(1);
}
typedef struct _option
{
std::wstring name;
bool hasVal;
std::wstring value;
bool set;
} option;
typedef std::pair<std::wstring, std::wstring> optpair;
optpair GetOption()
{
wchar_t * cmd = GetCommandLine();
int argc;
wchar_t ** argv = CommandLineToArgvW(cmd, &argc);
optpair pair;
if (argc == 1)
{
// no commandline argument...
pair = optpair(L"/START", L"");
}
else if (argc == 2 && argv[1][0] != L'/')
{
// only a single argument: this should be a path...
pair = optpair(L"/START", argv[1]);
}
else
{
pair = optpair(argv[1], argc > 2 ? argv[2] : L"");
}
LocalFree(argv);
return pair;
}
bool FileExists(const wchar_t * filePath)
{
HANDLE hFile = CreateFile(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
CloseHandle(hFile);
return true;
}
return false;
}
void StartCmder(std::wstring path, bool is_single_mode)
{
#if USE_TASKBAR_API
wchar_t appId[MAX_PATH] = { 0 };
#endif
wchar_t exeDir[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
wchar_t cfgPath[MAX_PATH] = { 0 };
wchar_t oldCfgPath[MAX_PATH] = { 0 };
wchar_t conEmuPath[MAX_PATH] = { 0 };
wchar_t args[MAX_PATH * 2 + 256] = { 0 };
GetModuleFileName(NULL, exeDir, sizeof(exeDir));
#if USE_TASKBAR_API
wcscpy_s(appId, exeDir);
#endif
PathRemoveFileSpec(exeDir);
PathCombine(icoPath, exeDir, L"icons\\cmder.ico");
// Check for machine-specific config file.
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(oldCfgPath, oldCfgPath, sizeof(oldCfgPath) / sizeof(oldCfgPath[0]));
if (!PathFileExists(oldCfgPath)) {
PathCombine(oldCfgPath, exeDir, L"config\\ConEmu.xml");
}
// Check for machine-specific config file.
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu-%COMPUTERNAME%.xml");
ExpandEnvironmentStrings(cfgPath, cfgPath, sizeof(cfgPath) / sizeof(cfgPath[0]));
if (!PathFileExists(cfgPath)) {
PathCombine(cfgPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.xml");
}
SYSTEM_INFO sysInfo;
GetNativeSystemInfo(&sysInfo);
if (sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu64.exe");
}
else {
PathCombine(conEmuPath, exeDir, L"vendor\\conemu-maximus5\\ConEmu.exe");
}
if (FileExists(oldCfgPath) && !FileExists(cfgPath))
{
if (!CopyFile(oldCfgPath, cfgPath, FALSE))
{
MessageBox(NULL,
(GetLastError() == ERROR_ACCESS_DENIED)
? L"Failed to copy ConEmu.xml file to new location! Restart cmder as administrator."
: L"Failed to copy ConEmu.xml file to new location!", MB_TITLE, MB_ICONSTOP);
exit(1);
}
}
if (is_single_mode)
{
swprintf_s(args, L"/single /Icon \"%s\" /Title Cmder", icoPath);
}
else
{
swprintf_s(args, L"/Icon \"%s\" /Title Cmder", icoPath);
}
SetEnvironmentVariable(L"CMDER_ROOT", exeDir);
if (!streqi(path.c_str(), L""))
{
if (!SetEnvironmentVariable(L"CMDER_START", path.c_str())) {
MessageBox(NULL, _T("Error trying to set CMDER_START to given path!"), _T("Error"), MB_OK);
}
}
// Ensure EnvironmentVariables are propagated.
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 5000, NULL);
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM) L"Environment", SMTO_ABORTIFHUNG, 5000, NULL); // For Windows >= 8
STARTUPINFO si = { 0 };
si.cb = sizeof(STARTUPINFO);
#if USE_TASKBAR_API
si.lpTitle = appId;
si.dwFlags = STARTF_TITLEISAPPID;
#endif
PROCESS_INFORMATION pi;
if (!CreateProcess(conEmuPath, args, NULL, NULL, false, 0, NULL, NULL, &si, &pi)) {
MessageBox(NULL, _T("Unable to create the ConEmu Process!"), _T("Error"), MB_OK);
return;
}
}
bool IsUserOnly(std::wstring opt)
{
bool userOnly;
if (streqi(opt.c_str(), L"ALL"))
{
userOnly = false;
}
else if (streqi(opt.c_str(), L"USER"))
{
userOnly = true;
}
else
{
MessageBox(NULL, L"Unrecognized option for /REGISTER or /UNREGISTER. Must be either ALL or USER.", MB_TITLE, MB_OK);
exit(1);
}
return userOnly;
}
HKEY GetRootKey(std::wstring opt)
{
HKEY root;
if (IsUserOnly(opt))
{
FAIL_ON_ERROR(RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Classes", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &root, NULL));
}
else
{
root = HKEY_CLASSES_ROOT;
}
return root;
}
void RegisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
// First, get the paths we will use
wchar_t exePath[MAX_PATH] = { 0 };
wchar_t icoPath[MAX_PATH] = { 0 };
GetModuleFileName(NULL, exePath, sizeof(exePath));
wchar_t commandStr[MAX_PATH + 20] = { 0 };
swprintf_s(commandStr, L"\"%s\" \"%%V\"", exePath);
// Now that we have `commandStr`, it's OK to change `exePath`...
PathRemoveFileSpec(exePath);
PathCombine(icoPath, exePath, L"icons\\cmder.ico");
// Now set the registry keys
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
FAIL_ON_ERROR(RegSetValue(cmderKey, L"", REG_SZ, L"Cmder Here", NULL));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"NoWorkingDirectory", 0, REG_SZ, (BYTE *)L"", 2));
FAIL_ON_ERROR(RegSetValueEx(cmderKey, L"Icon", 0, REG_SZ, (BYTE *)icoPath, wcslen(icoPath) * sizeof(wchar_t)));
HKEY command;
FAIL_ON_ERROR(
RegCreateKeyEx(cmderKey, L"command", 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &command, NULL));
FAIL_ON_ERROR(RegSetValue(command, L"", REG_SZ, commandStr, NULL));
RegCloseKey(command);
RegCloseKey(cmderKey);
RegCloseKey(root);
}
void UnregisterShellMenu(std::wstring opt, wchar_t* keyBaseName)
{
HKEY root = GetRootKey(opt);
HKEY cmderKey;
FAIL_ON_ERROR(
RegCreateKeyEx(root, keyBaseName, 0, NULL,
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &cmderKey, NULL));
#if XP
FAIL_ON_ERROR(SHDeleteKey(cmderKey, NULL));
#else
FAIL_ON_ERROR(RegDeleteTree(cmderKey, NULL));
#endif
RegCloseKey(cmderKey);
RegCloseKey(root);
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
UNREFERENCED_PARAMETER(nCmdShow);
optpair opt = GetOption();
if (streqi(opt.first.c_str(), L"/START"))
{
StartCmder(opt.second, false);
}
else if (streqi(opt.first.c_str(), L"/SINGLE"))
{
StartCmder(opt.second, true);
}
else if (streqi(opt.first.c_str(), L"/REGISTER"))
{
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
RegisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else if (streqi(opt.first.c_str(), L"/UNREGISTER"))
{
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_BACKGROUND);
UnregisterShellMenu(opt.second, SHELL_MENU_REGISTRY_PATH_LISTITEM);
}
else
{
MessageBox(NULL, L"Unrecognized parameter.\n\nValid options:\n /START <path>\n /SINGLE <path>\n /REGISTER [USER/ALL]\n /UNREGISTER [USER/ALL]", MB_TITLE, MB_OK);
return 1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "audio/voip/voip_core.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "api/audio_codecs/audio_format.h"
#include "rtc_base/logging.h"
namespace webrtc {
namespace {
// For Windows, use specific enum type to initialize default audio device as
// defined in AudioDeviceModule::WindowsDeviceType.
#if defined(WEBRTC_WIN)
constexpr AudioDeviceModule::WindowsDeviceType kAudioDeviceId =
AudioDeviceModule::WindowsDeviceType::kDefaultCommunicationDevice;
#else
constexpr uint16_t kAudioDeviceId = 0;
#endif // defined(WEBRTC_WIN)
// Maximum value range limit on ChannelId. This can be increased without any
// side effect and only set at this moderate value for better readability for
// logging.
static constexpr int kMaxChannelId = 100000;
} // namespace
bool VoipCore::Init(rtc::scoped_refptr<AudioEncoderFactory> encoder_factory,
rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
std::unique_ptr<TaskQueueFactory> task_queue_factory,
rtc::scoped_refptr<AudioDeviceModule> audio_device_module,
rtc::scoped_refptr<AudioProcessing> audio_processing) {
encoder_factory_ = std::move(encoder_factory);
decoder_factory_ = std::move(decoder_factory);
task_queue_factory_ = std::move(task_queue_factory);
audio_device_module_ = std::move(audio_device_module);
process_thread_ = ProcessThread::Create("ModuleProcessThread");
audio_mixer_ = AudioMixerImpl::Create();
if (audio_processing) {
audio_processing_ = std::move(audio_processing);
AudioProcessing::Config apm_config = audio_processing_->GetConfig();
apm_config.echo_canceller.enabled = true;
audio_processing_->ApplyConfig(apm_config);
}
// AudioTransportImpl depends on audio mixer and audio processing instances.
audio_transport_ = std::make_unique<AudioTransportImpl>(
audio_mixer_.get(), audio_processing_.get());
// Initialize ADM.
if (audio_device_module_->Init() != 0) {
RTC_LOG(LS_ERROR) << "Failed to initialize the ADM.";
return false;
}
// Note that failures on initializing default recording/speaker devices are
// not considered to be fatal here. In certain case, caller may not care about
// recording device functioning (e.g webinar where only speaker is available).
// It's also possible that there are other audio devices available that may
// work.
// TODO(natim@webrtc.org): consider moving this part out of initialization.
// Initialize default speaker device.
if (audio_device_module_->SetPlayoutDevice(kAudioDeviceId) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set playout device.";
}
if (audio_device_module_->InitSpeaker() != 0) {
RTC_LOG(LS_WARNING) << "Unable to access speaker.";
}
// Initialize default recording device.
if (audio_device_module_->SetRecordingDevice(kAudioDeviceId) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set recording device.";
}
if (audio_device_module_->InitMicrophone() != 0) {
RTC_LOG(LS_WARNING) << "Unable to access microphone.";
}
// Set number of channels on speaker device.
bool available = false;
if (audio_device_module_->StereoPlayoutIsAvailable(&available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to query stereo playout.";
}
if (audio_device_module_->SetStereoPlayout(available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set mono/stereo playout mode.";
}
// Set number of channels on recording device.
available = false;
if (audio_device_module_->StereoRecordingIsAvailable(&available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to query stereo recording.";
}
if (audio_device_module_->SetStereoRecording(available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set stereo recording mode.";
}
if (audio_device_module_->RegisterAudioCallback(audio_transport_.get()) !=
0) {
RTC_LOG(LS_WARNING) << "Unable to register audio callback.";
}
return true;
}
absl::optional<ChannelId> VoipCore::CreateChannel(
Transport* transport,
absl::optional<uint32_t> local_ssrc) {
absl::optional<ChannelId> channel;
// Set local ssrc to random if not set by caller.
if (!local_ssrc) {
Random random(rtc::TimeMicros());
local_ssrc = random.Rand<uint32_t>();
}
rtc::scoped_refptr<AudioChannel> audio_channel =
new rtc::RefCountedObject<AudioChannel>(
transport, local_ssrc.value(), task_queue_factory_.get(),
process_thread_.get(), audio_mixer_.get(), decoder_factory_);
{
MutexLock lock(&lock_);
channel = static_cast<ChannelId>(next_channel_id_);
channels_[*channel] = audio_channel;
next_channel_id_++;
if (next_channel_id_ >= kMaxChannelId) {
next_channel_id_ = 0;
}
}
// Set ChannelId in audio channel for logging/debugging purpose.
audio_channel->SetId(*channel);
return channel;
}
void VoipCore::ReleaseChannel(ChannelId channel) {
// Destroy channel outside of the lock.
rtc::scoped_refptr<AudioChannel> audio_channel;
{
MutexLock lock(&lock_);
auto iter = channels_.find(channel);
if (iter != channels_.end()) {
audio_channel = std::move(iter->second);
channels_.erase(iter);
}
}
if (!audio_channel) {
RTC_LOG(LS_WARNING) << "Channel " << channel << " not found";
}
}
rtc::scoped_refptr<AudioChannel> VoipCore::GetChannel(ChannelId channel) {
rtc::scoped_refptr<AudioChannel> audio_channel;
{
MutexLock lock(&lock_);
auto iter = channels_.find(channel);
if (iter != channels_.end()) {
audio_channel = iter->second;
}
}
if (!audio_channel) {
RTC_LOG(LS_ERROR) << "Channel " << channel << " not found";
}
return audio_channel;
}
bool VoipCore::UpdateAudioTransportWithSenders() {
std::vector<AudioSender*> audio_senders;
// Gather a list of audio channel that are currently sending along with
// highest sampling rate and channel numbers to configure into audio
// transport.
int max_sampling_rate = 8000;
size_t max_num_channels = 1;
{
MutexLock lock(&lock_);
// Reserve to prevent run time vector re-allocation.
audio_senders.reserve(channels_.size());
for (auto kv : channels_) {
rtc::scoped_refptr<AudioChannel>& channel = kv.second;
if (channel->IsSendingMedia()) {
auto encoder_format = channel->GetEncoderFormat();
if (!encoder_format) {
RTC_LOG(LS_ERROR)
<< "channel " << channel->GetId() << " encoder is not set";
continue;
}
audio_senders.push_back(channel->GetAudioSender());
max_sampling_rate =
std::max(max_sampling_rate, encoder_format->clockrate_hz);
max_num_channels =
std::max(max_num_channels, encoder_format->num_channels);
}
}
}
audio_transport_->UpdateAudioSenders(audio_senders, max_sampling_rate,
max_num_channels);
// Depending on availability of senders, turn on or off ADM recording.
if (!audio_senders.empty()) {
if (!audio_device_module_->Recording()) {
if (audio_device_module_->InitRecording() != 0) {
RTC_LOG(LS_ERROR) << "InitRecording failed";
return false;
}
if (audio_device_module_->StartRecording() != 0) {
RTC_LOG(LS_ERROR) << "StartRecording failed";
return false;
}
}
} else {
if (audio_device_module_->Recording() &&
audio_device_module_->StopRecording() != 0) {
RTC_LOG(LS_ERROR) << "StopRecording failed";
return false;
}
}
return true;
}
bool VoipCore::StartSend(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel || !audio_channel->StartSend()) {
return false;
}
return UpdateAudioTransportWithSenders();
}
bool VoipCore::StopSend(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel) {
return false;
}
audio_channel->StopSend();
return UpdateAudioTransportWithSenders();
}
bool VoipCore::StartPlayout(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel || !audio_channel->StartPlay()) {
return false;
}
if (!audio_device_module_->Playing()) {
if (audio_device_module_->InitPlayout() != 0) {
RTC_LOG(LS_ERROR) << "InitPlayout failed";
return false;
}
if (audio_device_module_->StartPlayout() != 0) {
RTC_LOG(LS_ERROR) << "StartPlayout failed";
return false;
}
}
return true;
}
bool VoipCore::StopPlayout(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel) {
return false;
}
audio_channel->StopPlay();
bool stop_device = true;
{
MutexLock lock(&lock_);
for (auto kv : channels_) {
rtc::scoped_refptr<AudioChannel>& channel = kv.second;
if (channel->IsPlaying()) {
stop_device = false;
break;
}
}
}
if (stop_device && audio_device_module_->Playing()) {
if (audio_device_module_->StopPlayout() != 0) {
RTC_LOG(LS_ERROR) << "StopPlayout failed";
return false;
}
}
return true;
}
void VoipCore::ReceivedRTPPacket(ChannelId channel,
rtc::ArrayView<const uint8_t> rtp_packet) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->ReceivedRTPPacket(rtp_packet);
}
}
void VoipCore::ReceivedRTCPPacket(ChannelId channel,
rtc::ArrayView<const uint8_t> rtcp_packet) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->ReceivedRTCPPacket(rtcp_packet);
}
}
void VoipCore::SetSendCodec(ChannelId channel,
int payload_type,
const SdpAudioFormat& encoder_format) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
auto encoder = encoder_factory_->MakeAudioEncoder(
payload_type, encoder_format, absl::nullopt);
audio_channel->SetEncoder(payload_type, encoder_format, std::move(encoder));
}
}
void VoipCore::SetReceiveCodecs(
ChannelId channel,
const std::map<int, SdpAudioFormat>& decoder_specs) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->SetReceiveCodecs(decoder_specs);
}
}
void VoipCore::RegisterTelephoneEventType(ChannelId channel,
int rtp_payload_type,
int sample_rate_hz) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->RegisterTelephoneEventType(rtp_payload_type, sample_rate_hz);
}
}
bool VoipCore::SendDtmfEvent(ChannelId channel,
DtmfEvent dtmf_event,
int duration_ms) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
return audio_channel->SendTelephoneEvent(static_cast<int>(dtmf_event),
duration_ms);
}
return false;
}
} // namespace webrtc
<commit_msg>Removing logic forcing AEC within VoIP core<commit_after>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "audio/voip/voip_core.h"
#include <algorithm>
#include <memory>
#include <utility>
#include "api/audio_codecs/audio_format.h"
#include "rtc_base/logging.h"
namespace webrtc {
namespace {
// For Windows, use specific enum type to initialize default audio device as
// defined in AudioDeviceModule::WindowsDeviceType.
#if defined(WEBRTC_WIN)
constexpr AudioDeviceModule::WindowsDeviceType kAudioDeviceId =
AudioDeviceModule::WindowsDeviceType::kDefaultCommunicationDevice;
#else
constexpr uint16_t kAudioDeviceId = 0;
#endif // defined(WEBRTC_WIN)
// Maximum value range limit on ChannelId. This can be increased without any
// side effect and only set at this moderate value for better readability for
// logging.
static constexpr int kMaxChannelId = 100000;
} // namespace
bool VoipCore::Init(rtc::scoped_refptr<AudioEncoderFactory> encoder_factory,
rtc::scoped_refptr<AudioDecoderFactory> decoder_factory,
std::unique_ptr<TaskQueueFactory> task_queue_factory,
rtc::scoped_refptr<AudioDeviceModule> audio_device_module,
rtc::scoped_refptr<AudioProcessing> audio_processing) {
encoder_factory_ = std::move(encoder_factory);
decoder_factory_ = std::move(decoder_factory);
task_queue_factory_ = std::move(task_queue_factory);
audio_device_module_ = std::move(audio_device_module);
audio_processing_ = std::move(audio_processing);
process_thread_ = ProcessThread::Create("ModuleProcessThread");
audio_mixer_ = AudioMixerImpl::Create();
// AudioTransportImpl depends on audio mixer and audio processing instances.
audio_transport_ = std::make_unique<AudioTransportImpl>(
audio_mixer_.get(), audio_processing_.get());
// Initialize ADM.
if (audio_device_module_->Init() != 0) {
RTC_LOG(LS_ERROR) << "Failed to initialize the ADM.";
return false;
}
// Note that failures on initializing default recording/speaker devices are
// not considered to be fatal here. In certain case, caller may not care about
// recording device functioning (e.g webinar where only speaker is available).
// It's also possible that there are other audio devices available that may
// work.
// TODO(natim@webrtc.org): consider moving this part out of initialization.
// Initialize default speaker device.
if (audio_device_module_->SetPlayoutDevice(kAudioDeviceId) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set playout device.";
}
if (audio_device_module_->InitSpeaker() != 0) {
RTC_LOG(LS_WARNING) << "Unable to access speaker.";
}
// Initialize default recording device.
if (audio_device_module_->SetRecordingDevice(kAudioDeviceId) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set recording device.";
}
if (audio_device_module_->InitMicrophone() != 0) {
RTC_LOG(LS_WARNING) << "Unable to access microphone.";
}
// Set number of channels on speaker device.
bool available = false;
if (audio_device_module_->StereoPlayoutIsAvailable(&available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to query stereo playout.";
}
if (audio_device_module_->SetStereoPlayout(available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set mono/stereo playout mode.";
}
// Set number of channels on recording device.
available = false;
if (audio_device_module_->StereoRecordingIsAvailable(&available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to query stereo recording.";
}
if (audio_device_module_->SetStereoRecording(available) != 0) {
RTC_LOG(LS_WARNING) << "Unable to set stereo recording mode.";
}
if (audio_device_module_->RegisterAudioCallback(audio_transport_.get()) !=
0) {
RTC_LOG(LS_WARNING) << "Unable to register audio callback.";
}
return true;
}
absl::optional<ChannelId> VoipCore::CreateChannel(
Transport* transport,
absl::optional<uint32_t> local_ssrc) {
absl::optional<ChannelId> channel;
// Set local ssrc to random if not set by caller.
if (!local_ssrc) {
Random random(rtc::TimeMicros());
local_ssrc = random.Rand<uint32_t>();
}
rtc::scoped_refptr<AudioChannel> audio_channel =
new rtc::RefCountedObject<AudioChannel>(
transport, local_ssrc.value(), task_queue_factory_.get(),
process_thread_.get(), audio_mixer_.get(), decoder_factory_);
{
MutexLock lock(&lock_);
channel = static_cast<ChannelId>(next_channel_id_);
channels_[*channel] = audio_channel;
next_channel_id_++;
if (next_channel_id_ >= kMaxChannelId) {
next_channel_id_ = 0;
}
}
// Set ChannelId in audio channel for logging/debugging purpose.
audio_channel->SetId(*channel);
return channel;
}
void VoipCore::ReleaseChannel(ChannelId channel) {
// Destroy channel outside of the lock.
rtc::scoped_refptr<AudioChannel> audio_channel;
{
MutexLock lock(&lock_);
auto iter = channels_.find(channel);
if (iter != channels_.end()) {
audio_channel = std::move(iter->second);
channels_.erase(iter);
}
}
if (!audio_channel) {
RTC_LOG(LS_WARNING) << "Channel " << channel << " not found";
}
}
rtc::scoped_refptr<AudioChannel> VoipCore::GetChannel(ChannelId channel) {
rtc::scoped_refptr<AudioChannel> audio_channel;
{
MutexLock lock(&lock_);
auto iter = channels_.find(channel);
if (iter != channels_.end()) {
audio_channel = iter->second;
}
}
if (!audio_channel) {
RTC_LOG(LS_ERROR) << "Channel " << channel << " not found";
}
return audio_channel;
}
bool VoipCore::UpdateAudioTransportWithSenders() {
std::vector<AudioSender*> audio_senders;
// Gather a list of audio channel that are currently sending along with
// highest sampling rate and channel numbers to configure into audio
// transport.
int max_sampling_rate = 8000;
size_t max_num_channels = 1;
{
MutexLock lock(&lock_);
// Reserve to prevent run time vector re-allocation.
audio_senders.reserve(channels_.size());
for (auto kv : channels_) {
rtc::scoped_refptr<AudioChannel>& channel = kv.second;
if (channel->IsSendingMedia()) {
auto encoder_format = channel->GetEncoderFormat();
if (!encoder_format) {
RTC_LOG(LS_ERROR)
<< "channel " << channel->GetId() << " encoder is not set";
continue;
}
audio_senders.push_back(channel->GetAudioSender());
max_sampling_rate =
std::max(max_sampling_rate, encoder_format->clockrate_hz);
max_num_channels =
std::max(max_num_channels, encoder_format->num_channels);
}
}
}
audio_transport_->UpdateAudioSenders(audio_senders, max_sampling_rate,
max_num_channels);
// Depending on availability of senders, turn on or off ADM recording.
if (!audio_senders.empty()) {
if (!audio_device_module_->Recording()) {
if (audio_device_module_->InitRecording() != 0) {
RTC_LOG(LS_ERROR) << "InitRecording failed";
return false;
}
if (audio_device_module_->StartRecording() != 0) {
RTC_LOG(LS_ERROR) << "StartRecording failed";
return false;
}
}
} else {
if (audio_device_module_->Recording() &&
audio_device_module_->StopRecording() != 0) {
RTC_LOG(LS_ERROR) << "StopRecording failed";
return false;
}
}
return true;
}
bool VoipCore::StartSend(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel || !audio_channel->StartSend()) {
return false;
}
return UpdateAudioTransportWithSenders();
}
bool VoipCore::StopSend(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel) {
return false;
}
audio_channel->StopSend();
return UpdateAudioTransportWithSenders();
}
bool VoipCore::StartPlayout(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel || !audio_channel->StartPlay()) {
return false;
}
if (!audio_device_module_->Playing()) {
if (audio_device_module_->InitPlayout() != 0) {
RTC_LOG(LS_ERROR) << "InitPlayout failed";
return false;
}
if (audio_device_module_->StartPlayout() != 0) {
RTC_LOG(LS_ERROR) << "StartPlayout failed";
return false;
}
}
return true;
}
bool VoipCore::StopPlayout(ChannelId channel) {
auto audio_channel = GetChannel(channel);
if (!audio_channel) {
return false;
}
audio_channel->StopPlay();
bool stop_device = true;
{
MutexLock lock(&lock_);
for (auto kv : channels_) {
rtc::scoped_refptr<AudioChannel>& channel = kv.second;
if (channel->IsPlaying()) {
stop_device = false;
break;
}
}
}
if (stop_device && audio_device_module_->Playing()) {
if (audio_device_module_->StopPlayout() != 0) {
RTC_LOG(LS_ERROR) << "StopPlayout failed";
return false;
}
}
return true;
}
void VoipCore::ReceivedRTPPacket(ChannelId channel,
rtc::ArrayView<const uint8_t> rtp_packet) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->ReceivedRTPPacket(rtp_packet);
}
}
void VoipCore::ReceivedRTCPPacket(ChannelId channel,
rtc::ArrayView<const uint8_t> rtcp_packet) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->ReceivedRTCPPacket(rtcp_packet);
}
}
void VoipCore::SetSendCodec(ChannelId channel,
int payload_type,
const SdpAudioFormat& encoder_format) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
auto encoder = encoder_factory_->MakeAudioEncoder(
payload_type, encoder_format, absl::nullopt);
audio_channel->SetEncoder(payload_type, encoder_format, std::move(encoder));
}
}
void VoipCore::SetReceiveCodecs(
ChannelId channel,
const std::map<int, SdpAudioFormat>& decoder_specs) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->SetReceiveCodecs(decoder_specs);
}
}
void VoipCore::RegisterTelephoneEventType(ChannelId channel,
int rtp_payload_type,
int sample_rate_hz) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
audio_channel->RegisterTelephoneEventType(rtp_payload_type, sample_rate_hz);
}
}
bool VoipCore::SendDtmfEvent(ChannelId channel,
DtmfEvent dtmf_event,
int duration_ms) {
// Failure to locate channel is logged internally in GetChannel.
if (auto audio_channel = GetChannel(channel)) {
return audio_channel->SendTelephoneEvent(static_cast<int>(dtmf_event),
duration_ms);
}
return false;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>/*
* Copyright 2011 Hallgrimur H. Gunnarsson. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <vector>
static int format = 0;
static unsigned int depth = 0;
static int tagpath[128];
enum
{
CLASS_MASK = 0xC0,
TYPE_MASK = 0x20,
TAG_MASK = 0x1F,
LEN_XTND = 0x80,
LEN_MASK = 0x7F
};
struct tag
{
int cls;
int isPrimitive;
int id;
int tag;
int nbytes;
};
struct length
{
unsigned int length;
unsigned int nbytes;
};
struct TLV
{
struct tag tag;
struct length length;
unsigned int nbytes;
unsigned int depth;
unsigned char *value;
std::vector<struct TLV *> children;
};
int readTag(FILE *fp, struct tag *tag)
{
memset(tag, 0, sizeof(struct tag));
int b = fgetc(fp);
if (b == EOF)
return 1;
tag->nbytes = 1;
tag->tag = b;
tag->cls = b & CLASS_MASK;
tag->isPrimitive = (b & TYPE_MASK) == 0;
tag->id = b & TAG_MASK;
if (tag->id == TAG_MASK)
{
// Long tag, encoded as a sequence of 7-bit values
tag->id = 0;
do
{
b = fgetc(fp);
if (b == EOF)
return 1;
tag->nbytes++;
tag->id = (tag->id << 7) | (b & LEN_MASK);
} while ((b & LEN_XTND) == LEN_XTND);
}
return 0;
}
int readLen(FILE *fp, struct length *length)
{
int b, i;
memset(length, 0, sizeof(struct length));
b = fgetc(fp);
if (b == EOF)
return 1;
length->nbytes = 1;
length->length = b;
if ((length->length & LEN_XTND) == LEN_XTND)
{
int numoct = length->length & LEN_MASK;
length->length = 0;
if (numoct == 0)
return 0;
for (i = 0; i < numoct; i++)
{
b = fgetc(fp);
if (b == EOF)
return 1;
length->length = (length->length << 8) | b;
length->nbytes++;
}
}
return 0;
}
int readTLV(FILE *fp, struct TLV *tlv, unsigned int limit)
{
int n = 0;
int i;
memset(tlv, 0, sizeof(struct TLV));
if (readTag(fp, &tlv->tag))
return 1;
tlv->nbytes += tlv->tag.nbytes;
if (tlv->nbytes >= limit)
return 1;
if (readLen(fp, &tlv->length))
return 1;
tlv->nbytes += tlv->length.nbytes;
tlv->depth = depth;
int length = tlv->length.length;
if (tlv->nbytes >= limit)
{
if (length == 0)
return 0;
return 1;
}
if (tlv->tag.isPrimitive)
{
// Primitive definite-length method
if (length == 0)
return 0;
tlv->value = (unsigned char *)malloc(length);
if (!fread(tlv->value, length, 1, fp))
return 1;
tlv->nbytes += length;
return 0;
}
if (length > 0)
{
// Constructed definite-length method
struct TLV *child;
i = 0;
while (i < length)
{
depth++;
child = (struct TLV *)malloc(sizeof(struct TLV));
if (readTLV(fp, child, length-i))
{
depth--;
return 1;
}
depth--;
i += child->nbytes;
tlv->nbytes += child->nbytes;
tlv->children.push_back(child);
}
return 0;
}
// Constructed indefinite-length method
struct TLV *child;
while (1)
{
depth++;
child = (struct TLV *)malloc(sizeof(struct TLV));
n = readTLV(fp, child, limit-tlv->nbytes);
depth--;
tlv->nbytes += child->nbytes;
if (n == 1)
return 1;
if (child->tag.tag == 0 && child->length.length == 0)
break;
tlv->children.push_back(child);
}
return 0;
}
void print(struct TLV *tlv)
{
unsigned int i;
for (i = 0; i < tlv->depth; i++)
printf(" ");
if (tlv->value)
{
printf("[%d] ", tlv->tag.id);
for (i = 0; i < tlv->length.length; i++)
{
printf("%02x", tlv->value[i]);
}
printf("\n");
} else
{
printf("[%d] {\n", tlv->tag.id);
for (i = 0; i < tlv->children.size(); i++)
print(tlv->children[i]);
for (i = 0; i < tlv->depth; i++)
printf(" ");
printf("}\n");
}
}
void printCSV(struct TLV *tlv, int printPath)
{
unsigned int i;
if (tlv->tag.isPrimitive)
{
tagpath[tlv->depth] = tlv->tag.id;
if (printPath)
{
for (i = 0; i <= tlv->depth; i++)
{
if (i == 0)
printf("%d", tagpath[i]);
else
printf(",%d", tagpath[i]);
}
} else
{
printf("%d", tlv->tag.id);
}
printf("|");
for (i = 0; i < tlv->length.length; i++)
{
printf("%02x", tlv->value[i]);
}
printf("\n");
} else
{
tagpath[tlv->depth] = tlv->tag.id;
if (printPath)
{
for (i = 0; i <= tlv->depth; i++)
{
if (i == 0)
printf("%d", tagpath[i]);
else
printf(",%d", tagpath[i]);
}
} else
{
printf("%d", tlv->tag.id);
}
printf("|BEGIN\n");
for (i = 0; i < tlv->children.size(); i++)
printCSV(tlv->children[i], printPath);
if (printPath)
{
for (i = 0; i <= tlv->depth; i++)
{
if (i == 0)
printf("%d", tagpath[i]);
else
printf(",%d", tagpath[i]);
}
} else
{
printf("%d", tlv->tag.id);
}
printf("|END\n");
}
}
void dump(FILE *fp)
{
struct TLV root;
while (1)
{
if (feof(fp) || ferror(fp))
break;
if (readTLV(fp, &root, 1048576))
break;
memset(tagpath, 0, sizeof(tagpath));
switch (format)
{
case 0:
print(&root);
break;
case 1:
printCSV(&root, 0);
break;
case 2:
printCSV(&root, 1);
break;
}
}
}
static void usage(void)
{
fprintf(stderr, "usage: berdump [options] <files>\n");
fprintf(stderr, "options:\n");
fprintf(stderr, " -f <N> : output format\n");
fprintf(stderr, "output formats:\n");
fprintf(stderr, " -f0 : Pretty tree structure\n");
fprintf(stderr, " -f1 : CSV tag|value\n");
fprintf(stderr, " -f2 : CSV tag|value with full tag path\n");
}
int main(int argc, char *argv[])
{
int c, i;
while ((c = getopt(argc, argv, "f:h?")) != -1)
{
switch (c)
{
case 'f':
format = atoi(optarg);
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
case 'h':
default:
usage();
return 0;
}
}
argc -= optind;
argv += optind;
if (argc < 1)
{
dump(stdin);
return 0;
}
for (i = 0; i < argc; i++)
{
if (strlen(argv[i]) == 1 && argv[i][0] == '-')
{
dump(stdin);
continue;
}
FILE *fp = fopen(argv[i], "r");
if (fp == NULL)
{
fprintf(stderr, "error opening %s: %s\n", argv[i], strerror(errno));
continue;
}
dump(fp);
fclose(fp);
}
}
<commit_msg>Added error checking<commit_after>/*
* Copyright 2011 Hallgrimur H. Gunnarsson. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <err.h>
#include <vector>
static int format = 0;
static unsigned int depth = 0;
static int tagpath[128];
enum
{
CLASS_MASK = 0xC0,
TYPE_MASK = 0x20,
TAG_MASK = 0x1F,
LEN_XTND = 0x80,
LEN_MASK = 0x7F
};
struct tag
{
int cls;
int isPrimitive;
int id;
int tag;
int nbytes;
};
struct length
{
unsigned int length;
unsigned int nbytes;
};
struct TLV
{
struct tag tag;
struct length length;
unsigned int nbytes;
unsigned int depth;
unsigned char *value;
std::vector<struct TLV *> children;
};
int readTag(FILE *fp, struct tag *tag)
{
memset(tag, 0, sizeof(struct tag));
int b = fgetc(fp);
if (b == EOF)
return 1;
tag->nbytes = 1;
tag->tag = b;
tag->cls = b & CLASS_MASK;
tag->isPrimitive = (b & TYPE_MASK) == 0;
tag->id = b & TAG_MASK;
if (tag->id == TAG_MASK)
{
// Long tag, encoded as a sequence of 7-bit values
tag->id = 0;
do
{
b = fgetc(fp);
if (b == EOF)
return 1;
tag->nbytes++;
tag->id = (tag->id << 7) | (b & LEN_MASK);
} while ((b & LEN_XTND) == LEN_XTND);
}
return 0;
}
int readLen(FILE *fp, struct length *length)
{
int b, i;
memset(length, 0, sizeof(struct length));
b = fgetc(fp);
if (b == EOF)
return 1;
length->nbytes = 1;
length->length = b;
if ((length->length & LEN_XTND) == LEN_XTND)
{
int numoct = length->length & LEN_MASK;
length->length = 0;
if (numoct == 0)
return 0;
for (i = 0; i < numoct; i++)
{
b = fgetc(fp);
if (b == EOF)
return 1;
length->length = (length->length << 8) | b;
length->nbytes++;
}
}
return 0;
}
int readTLV(FILE *fp, struct TLV *tlv, unsigned int limit)
{
int n = 0;
int i;
memset(tlv, 0, sizeof(struct TLV));
if (readTag(fp, &tlv->tag))
return 1;
tlv->nbytes += tlv->tag.nbytes;
if (tlv->nbytes >= limit)
return 1;
if (readLen(fp, &tlv->length))
return 1;
tlv->nbytes += tlv->length.nbytes;
tlv->depth = depth;
int length = tlv->length.length;
if (tlv->nbytes >= limit)
{
if (length == 0)
return 0;
return 1;
}
if (tlv->tag.isPrimitive)
{
// Primitive definite-length method
if (length == 0)
return 0;
tlv->value = (unsigned char *)malloc(length);
if (tlv->value == NULL)
err(1, "malloc");
if (!fread(tlv->value, length, 1, fp))
return 1;
tlv->nbytes += length;
return 0;
}
if (length > 0)
{
// Constructed definite-length method
struct TLV *child;
i = 0;
while (i < length)
{
depth++;
child = (struct TLV *)malloc(sizeof(struct TLV));
if (child == NULL)
err(1, "malloc");
if (readTLV(fp, child, length-i))
{
depth--;
return 1;
}
depth--;
i += child->nbytes;
tlv->nbytes += child->nbytes;
tlv->children.push_back(child);
}
return 0;
}
// Constructed indefinite-length method
struct TLV *child;
while (1)
{
depth++;
child = (struct TLV *)malloc(sizeof(struct TLV));
if (child == NULL)
err(1, "malloc");
n = readTLV(fp, child, limit-tlv->nbytes);
depth--;
tlv->nbytes += child->nbytes;
if (n == 1)
return 1;
if (child->tag.tag == 0 && child->length.length == 0)
break;
tlv->children.push_back(child);
}
return 0;
}
void print(struct TLV *tlv)
{
unsigned int i;
for (i = 0; i < tlv->depth; i++)
printf(" ");
if (tlv->value)
{
printf("[%d] ", tlv->tag.id);
for (i = 0; i < tlv->length.length; i++)
{
printf("%02x", tlv->value[i]);
}
printf("\n");
} else
{
printf("[%d] {\n", tlv->tag.id);
for (i = 0; i < tlv->children.size(); i++)
print(tlv->children[i]);
for (i = 0; i < tlv->depth; i++)
printf(" ");
printf("}\n");
}
}
void printCSV(struct TLV *tlv, int printPath)
{
unsigned int i;
if (tlv->tag.isPrimitive)
{
tagpath[tlv->depth] = tlv->tag.id;
if (printPath)
{
for (i = 0; i <= tlv->depth; i++)
{
if (i == 0)
printf("%d", tagpath[i]);
else
printf(",%d", tagpath[i]);
}
} else
{
printf("%d", tlv->tag.id);
}
printf("|");
for (i = 0; i < tlv->length.length; i++)
{
printf("%02x", tlv->value[i]);
}
printf("\n");
} else
{
tagpath[tlv->depth] = tlv->tag.id;
if (printPath)
{
for (i = 0; i <= tlv->depth; i++)
{
if (i == 0)
printf("%d", tagpath[i]);
else
printf(",%d", tagpath[i]);
}
} else
{
printf("%d", tlv->tag.id);
}
printf("|BEGIN\n");
for (i = 0; i < tlv->children.size(); i++)
printCSV(tlv->children[i], printPath);
if (printPath)
{
for (i = 0; i <= tlv->depth; i++)
{
if (i == 0)
printf("%d", tagpath[i]);
else
printf(",%d", tagpath[i]);
}
} else
{
printf("%d", tlv->tag.id);
}
printf("|END\n");
}
}
void dump(FILE *fp)
{
struct TLV root;
while (1)
{
if (feof(fp) || ferror(fp))
break;
if (readTLV(fp, &root, 1048576))
break;
memset(tagpath, 0, sizeof(tagpath));
switch (format)
{
case 0:
print(&root);
break;
case 1:
printCSV(&root, 0);
break;
case 2:
printCSV(&root, 1);
break;
}
}
}
static void usage(void)
{
fprintf(stderr, "usage: berdump [options] <files>\n");
fprintf(stderr, "options:\n");
fprintf(stderr, " -f <N> : output format\n");
fprintf(stderr, "output formats:\n");
fprintf(stderr, " -f0 : Pretty tree structure\n");
fprintf(stderr, " -f1 : CSV tag|value\n");
fprintf(stderr, " -f2 : CSV tag|value with full tag path\n");
}
int main(int argc, char *argv[])
{
int c, i;
while ((c = getopt(argc, argv, "f:h?")) != -1)
{
switch (c)
{
case 'f':
format = atoi(optarg);
break;
case '?':
if (optopt == 'c')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
case 'h':
default:
usage();
return 0;
}
}
argc -= optind;
argv += optind;
if (argc < 1)
{
dump(stdin);
return 0;
}
for (i = 0; i < argc; i++)
{
if (strlen(argv[i]) == 1 && argv[i][0] == '-')
{
dump(stdin);
continue;
}
FILE *fp = fopen(argv[i], "r");
if (fp == NULL)
{
fprintf(stderr, "error opening %s: %s\n", argv[i], strerror(errno));
continue;
}
dump(fp);
fclose(fp);
}
}
<|endoftext|>
|
<commit_before>#include "ride/project.h"
#include <wx/utils.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
#include "ride/mainwindow.h"
#include "ride/compilermessage.h"
Project::Project(MainWindow* 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_->Append(str);
#ifdef WIN32
CompilerMessage mess;
if (CompilerMessage::Parse(str, &mess)) {
OutputDebugStringA(mess.message());
OutputDebugStringA("\n");
}
#endif
}
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;
}
<commit_msg>removed debug code<commit_after>#include "ride/project.h"
#include <wx/utils.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
#include "ride/mainwindow.h"
Project::Project(MainWindow* 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_->Append(str);
}
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>#include "layer_t.hpp"
#include "input_handler.hpp"
namespace rltk {
void layer_t::make_owner_draw_backing() {
if (!backing) {
backing = std::make_unique<sf::RenderTexture>();
}
backing->create(w, h);
}
void layer_t::on_resize(const int width, const int height) {
resize_func(this, width, height);
if (console && console->visible) {
console->set_offset(x,y);
console->resize_pixels(w, h);
} else {
make_owner_draw_backing();
}
}
void layer_t::render(sf::RenderWindow &window) {
if (console) {
if (!controls.empty()) {
// Render start events
for (auto it=controls.begin(); it != controls.end(); ++it) {
if (it->second->on_render_start) {
auto callfunc = it->second->on_render_start.get();
callfunc(it->second.get());
}
}
int mouse_x, mouse_y;
std::tie(mouse_x, mouse_y) = get_mouse_position();
if (mouse_x >= x && mouse_x <= (x+w) && mouse_y >= y && mouse_y <= (y+h)) {
// Mouse over in here is possible.
auto font_dimensions = console->get_font_size();
const int terminal_x = (mouse_x - x) / font_dimensions.first;
const int terminal_y = (mouse_y - y) / font_dimensions.second;
for (auto it=controls.begin(); it != controls.end(); ++it) {
// Mouse over
if (it->second->mouse_in_control(terminal_x, terminal_y)) {
if (it->second->on_mouse_over) {
auto callfunc = it->second->on_mouse_over.get();
callfunc(it->second.get(), terminal_x, terminal_y);
}
// Mouse down and up
if (get_mouse_button_state(button::LEFT) && it->second->on_mouse_down) {
auto callfunc = it->second->on_mouse_down.get();
callfunc(it->second.get(), terminal_x, terminal_y);
}
if (!get_mouse_button_state(button::LEFT) && it->second->on_mouse_up) {
auto callfunc = it->second->on_mouse_up.get();
callfunc(it->second.get(), terminal_x, terminal_y);
}
}
}
}
for (auto it=controls.begin(); it != controls.end(); ++it) {
it->second->render(console.get());
}
}
console->render(window);
} else if (sconsole) {
sconsole->render(window);
} else {
if (!backing) make_owner_draw_backing();
backing->clear(sf::Color(0,0,0,0));
owner_draw_func(this, *backing);
backing->display();
sf::Sprite compositor(backing->getTexture());
compositor.move(x, y);
window.draw(sf::Sprite(compositor));
}
}
void resize_fullscreen(rltk::layer_t * l, int w, int h) {
// Use the whole window
l->w = w;
l->h = h;
}
}
<commit_msg>Fix formatting<commit_after>#include "layer_t.hpp"
#include "input_handler.hpp"
namespace rltk {
void layer_t::make_owner_draw_backing() {
if (!backing) {
backing = std::make_unique<sf::RenderTexture>();
}
backing->create(w, h);
}
void layer_t::on_resize(const int width, const int height) {
resize_func(this, width, height);
if (console && console->visible) {
console->set_offset(x,y);
console->resize_pixels(w, h);
console->dirty = true;
} else {
make_owner_draw_backing();
}
}
void layer_t::render(sf::RenderWindow &window) {
if (console) {
if (!controls.empty()) {
// Render start events
for (auto it=controls.begin(); it != controls.end(); ++it) {
if (it->second->on_render_start) {
auto callfunc = it->second->on_render_start.get();
callfunc(it->second.get());
}
}
int mouse_x, mouse_y;
std::tie(mouse_x, mouse_y) = get_mouse_position();
if (mouse_x >= x && mouse_x <= (x+w) && mouse_y >= y && mouse_y <= (y+h)) {
// Mouse over in here is possible.
auto font_dimensions = console->get_font_size();
const int terminal_x = (mouse_x - x) / font_dimensions.first;
const int terminal_y = (mouse_y - y) / font_dimensions.second;
for (auto it=controls.begin(); it != controls.end(); ++it) {
// Mouse over
if (it->second->mouse_in_control(terminal_x, terminal_y)) {
if (it->second->on_mouse_over) {
auto callfunc = it->second->on_mouse_over.get();
callfunc(it->second.get(), terminal_x, terminal_y);
}
// Mouse down and up
if (get_mouse_button_state(button::LEFT) && it->second->on_mouse_down) {
auto callfunc = it->second->on_mouse_down.get();
callfunc(it->second.get(), terminal_x, terminal_y);
}
if (!get_mouse_button_state(button::LEFT) && it->second->on_mouse_up) {
auto callfunc = it->second->on_mouse_up.get();
callfunc(it->second.get(), terminal_x, terminal_y);
}
}
}
}
for (auto it=controls.begin(); it != controls.end(); ++it) {
it->second->render(console.get());
}
}
console->render(window);
} else if (sconsole) {
sconsole->render(window);
} else {
if (!backing) make_owner_draw_backing();
backing->clear(sf::Color(0,0,0,0));
owner_draw_func(this, *backing);
backing->display();
sf::Sprite compositor(backing->getTexture());
compositor.move(x, y);
window.draw(sf::Sprite(compositor));
}
}
void resize_fullscreen(rltk::layer_t * l, int w, int h) {
// Use the whole window
l->w = w;
l->h = h;
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "expireitemscommand.h"
#include "articlejobs.h"
#include "feed.h"
#include "feedlist.h"
#include <QPointer>
#include <QSet>
#include <QTimer>
#include <cassert>
using namespace Akregator;
class ExpireItemsCommand::Private
{
ExpireItemsCommand* const q;
public:
explicit Private( ExpireItemsCommand* qq );
void createDeleteJobs();
void addDeleteJobForFeed( Feed* feed );
void jobFinished( KJob* );
QPointer<FeedList> m_feedList;
QVector<int> m_feeds;
QSet<KJob*> m_jobs;
};
ExpireItemsCommand::Private::Private( ExpireItemsCommand* qq ) : q( qq ), m_feedList()
{
}
void ExpireItemsCommand::Private::addDeleteJobForFeed( Feed* feed )
{
assert( feed );
ArticleDeleteJob* job = new ArticleDeleteJob( q );
connect( job, SIGNAL( finished( KJob* ) ), q, SLOT( jobFinished( KJob* ) ) );
m_jobs.insert( job );
feed->deleteExpiredArticles( job );
job->start();
}
void ExpireItemsCommand::Private::jobFinished( KJob* job )
{
assert( !m_jobs.isEmpty() );
m_jobs.remove( job );
emit q->progress( ( ( m_feeds.count() - m_jobs.count() ) * 100 ) / m_feeds.count(), QString() );
if ( m_jobs.isEmpty() )
q->done();
}
void ExpireItemsCommand::Private::createDeleteJobs()
{
assert( m_jobs.isEmpty() );
if ( m_feeds.isEmpty() )
{
q->done();
return;
}
Q_FOREACH ( const int i, m_feeds )
{
Feed* const feed = qobject_cast<Feed*>( m_feedList->findByID( i ) );
if ( feed )
addDeleteJobForFeed( feed );
}
}
ExpireItemsCommand::ExpireItemsCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )
{
}
ExpireItemsCommand::~ExpireItemsCommand()
{
delete d;
}
void ExpireItemsCommand::setFeedList( FeedList* feedList )
{
d->m_feedList = feedList;
}
FeedList* ExpireItemsCommand::feedList() const
{
return d->m_feedList;
}
void ExpireItemsCommand::setFeeds( const QVector<int>& feeds )
{
d->m_feeds = feeds;
}
QVector<int> ExpireItemsCommand::feeds() const
{
return d->m_feeds;
}
void ExpireItemsCommand::doAbort()
{
Q_FOREACH( KJob* const i, d->m_jobs )
i->kill();
}
void ExpireItemsCommand::doStart()
{
QTimer::singleShot( 0, this, SLOT( createDeleteJobs() ) );
}
#include "expireitemscommand.moc"
<commit_msg>make expiry not crash if the feed list was replaced<commit_after>/*
This file is part of Akregator.
Copyright (C) 2008 Frank Osterfeld <osterfeld@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "expireitemscommand.h"
#include "articlejobs.h"
#include "feed.h"
#include "feedlist.h"
#include <KDebug>
#include <QPointer>
#include <QSet>
#include <QTimer>
#include <cassert>
using namespace Akregator;
class ExpireItemsCommand::Private
{
ExpireItemsCommand* const q;
public:
explicit Private( ExpireItemsCommand* qq );
void createDeleteJobs();
void addDeleteJobForFeed( Feed* feed );
void jobFinished( KJob* );
QPointer<FeedList> m_feedList;
QVector<int> m_feeds;
QSet<KJob*> m_jobs;
};
ExpireItemsCommand::Private::Private( ExpireItemsCommand* qq ) : q( qq ), m_feedList()
{
}
void ExpireItemsCommand::Private::addDeleteJobForFeed( Feed* feed )
{
assert( feed );
ArticleDeleteJob* job = new ArticleDeleteJob( q );
connect( job, SIGNAL( finished( KJob* ) ), q, SLOT( jobFinished( KJob* ) ) );
m_jobs.insert( job );
feed->deleteExpiredArticles( job );
job->start();
}
void ExpireItemsCommand::Private::jobFinished( KJob* job )
{
assert( !m_jobs.isEmpty() );
m_jobs.remove( job );
emit q->progress( ( ( m_feeds.count() - m_jobs.count() ) * 100 ) / m_feeds.count(), QString() );
if ( m_jobs.isEmpty() )
q->done();
}
void ExpireItemsCommand::Private::createDeleteJobs()
{
assert( m_jobs.isEmpty() );
if ( m_feeds.isEmpty() || !m_feedList )
{
if ( !m_feedList )
kWarning() << "Associated feed list was deleted, could not expire items";
q->done();
return;
}
Q_FOREACH ( const int i, m_feeds )
{
Feed* const feed = qobject_cast<Feed*>( m_feedList->findByID( i ) );
if ( feed )
addDeleteJobForFeed( feed );
}
}
ExpireItemsCommand::ExpireItemsCommand( QObject* parent ) : Command( parent ), d( new Private( this ) )
{
}
ExpireItemsCommand::~ExpireItemsCommand()
{
delete d;
}
void ExpireItemsCommand::setFeedList( FeedList* feedList )
{
d->m_feedList = feedList;
}
FeedList* ExpireItemsCommand::feedList() const
{
return d->m_feedList;
}
void ExpireItemsCommand::setFeeds( const QVector<int>& feeds )
{
d->m_feeds = feeds;
}
QVector<int> ExpireItemsCommand::feeds() const
{
return d->m_feeds;
}
void ExpireItemsCommand::doAbort()
{
Q_FOREACH( KJob* const i, d->m_jobs )
i->kill();
}
void ExpireItemsCommand::doStart()
{
QTimer::singleShot( 0, this, SLOT( createDeleteJobs() ) );
}
#include "expireitemscommand.moc"
<|endoftext|>
|
<commit_before><commit_msg>minor<commit_after><|endoftext|>
|
<commit_before><commit_msg>compile<commit_after><|endoftext|>
|
<commit_before> /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_STANDALONE_MARCHING_CUBES_IMPL_HPP_
#define PCL_STANDALONE_MARCHING_CUBES_IMPL_HPP_
#include <pcl/gpu/kinfu_large_scale/standalone_marching_cubes.h>
///////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::StandaloneMarchingCubes (int new_voxels_x, int new_voxels_y, int new_voxels_z, float new_volume_size)
{
voxels_x_ = new_voxels_x;
voxels_y_ = new_voxels_y;
voxels_z_ = new_voxels_z;
volume_size_ = new_volume_size;
///Creating GPU TSDF Volume instance
const Eigen::Vector3f volume_size = Eigen::Vector3f::Constant (volume_size_);
// std::cout << "VOLUME SIZE IS " << volume_size_ << std::endl;
const Eigen::Vector3i volume_resolution (voxels_x_, voxels_y_, voxels_z_);
tsdf_volume_gpu_ = TsdfVolume::Ptr ( new TsdfVolume (volume_resolution) );
tsdf_volume_gpu_->setSize (volume_size);
///Creating CPU TSDF Volume instance
int tsdf_total_size = voxels_x_ * voxels_y_ * voxels_z_;
tsdf_volume_cpu_= std::vector<int> (tsdf_total_size,0);
mesh_counter_ = 0;
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> typename pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::MeshPtr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::getMeshFromTSDFCloud (const PointCloud &cloud)
{
//Clearing TSDF GPU and cPU
const Eigen::Vector3f volume_size = Eigen::Vector3f::Constant (volume_size_);
std::cout << "VOLUME SIZE IS " << volume_size_ << std::endl;
const Eigen::Vector3i volume_resolution (voxels_x_, voxels_y_, voxels_z_);
//Clear values in TSDF Volume GPU
tsdf_volume_gpu_->reset (); // This one uses the same tsdf volume but clears it before loading new values. This one is our friend.
//Clear values in TSDF Volume CPU
int tsdf_total_size = voxels_x_ * voxels_y_ * voxels_z_;
tsdf_volume_cpu_= std::vector<int> (tsdf_total_size,0);
//Loading values to GPU
loadTsdfCloudToGPU (cloud);
//Creating and returning mesh
return ( runMarchingCubes () );
}
///////////////////////////////////////////////////////////////////////////////
//template <typename PointT> std::vector< typename pcl::gpu::StandaloneMarchingCubes<PointT>::MeshPtr >
template <typename PointT> void
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::getMeshesFromTSDFVector (const std::vector<PointCloudPtr> &tsdf_clouds, const std::vector<Eigen::Vector3f> &tsdf_offsets)
{
std::vector< MeshPtr > meshes_vector;
int max_iterations = std::min( tsdf_clouds.size (), tsdf_offsets.size () ); //Safety check
PCL_INFO ("There are %d cubes to be processed \n", max_iterations);
float cell_size = volume_size_ / voxels_x_;
int mesh_counter = 0;
for(int i = 0; i < max_iterations; ++i)
{
PCL_INFO ("Processing cube number %d\n", i);
//Making cloud local
Eigen::Affine3f cloud_transform;
float originX = (tsdf_offsets[i]).x();
float originY = (tsdf_offsets[i]).y();
float originZ = (tsdf_offsets[i]).z();
cloud_transform.linear ().setIdentity ();
cloud_transform.translation ()[0] = -originX;
cloud_transform.translation ()[1] = -originY;
cloud_transform.translation ()[2] = -originZ;
transformPointCloud (*tsdf_clouds[i], *tsdf_clouds[i], cloud_transform);
//Get mesh
MeshPtr tmp = getMeshFromTSDFCloud (*tsdf_clouds[i]);
if(tmp != 0)
{
meshes_vector.push_back (tmp);
mesh_counter++;
}
else
{
PCL_INFO ("This cloud returned no faces, we skip it!\n");
continue;
}
//Making cloud global
cloud_transform.translation ()[0] = originX * cell_size;
cloud_transform.translation ()[1] = originY * cell_size;
cloud_transform.translation ()[2] = originZ * cell_size;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tmp_ptr (new pcl::PointCloud<pcl::PointXYZ>);
fromROSMsg ( (meshes_vector.back () )->cloud, *cloud_tmp_ptr);
transformPointCloud (*cloud_tmp_ptr, *cloud_tmp_ptr, cloud_transform);
toROSMsg (*cloud_tmp_ptr, (meshes_vector.back () )->cloud);
std::stringstream name;
name << "mesh_" << mesh_counter << ".ply";
PCL_INFO ("Saving mesh...%d \n", mesh_counter);
pcl::io::savePLYFile (name.str (), *(meshes_vector.back ()));
}
return;
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> pcl::gpu::kinfuLS::TsdfVolume::Ptr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::tsdfVolumeGPU ()
{
return (tsdf_volume_gpu_);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> std::vector<int>& //todo
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::tsdfVolumeCPU ()
{
return (tsdf_volume_cpu_);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::loadTsdfCloudToGPU (const PointCloud &cloud)
{
//Converting Values
convertTsdfVectors (cloud, tsdf_volume_cpu_);
//Uploading data to GPU
int cubeColumns = voxels_x_;
tsdf_volume_gpu_->data ().upload (tsdf_volume_cpu_, cubeColumns);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::convertTsdfVectors (const PointCloud &cloud, std::vector<int> &output)
{
const int DIVISOR = 32767; // SHRT_MAX;
///For every point in the cloud
#pragma omp parallel for
for(int i = 0; i < (int) cloud.points.size (); ++i)
{
int x = cloud.points[i].x;
int y = cloud.points[i].y;
int z = cloud.points[i].z;
if(x > 0 && x < voxels_x_ && y > 0 && y < voxels_y_ && z > 0 && z < voxels_z_)
{
///Calculate the index to write to
int dst_index = x + voxels_x_ * y + voxels_y_ * voxels_x_ * z;
short2& elem = *reinterpret_cast<short2*> (&output[dst_index]);
elem.x = static_cast<short> (cloud.points[i].intensity * DIVISOR);
elem.y = static_cast<short> (1);
}
}
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> typename pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::MeshPtr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::convertTrianglesToMesh (const pcl::gpu::DeviceArray<pcl::PointXYZ>& triangles)
{
if (triangles.empty () )
{
return MeshPtr ();
}
pcl::PointCloud<pcl::PointXYZ> cloud;
cloud.width = (int)triangles.size ();
cloud.height = 1;
triangles.download (cloud.points);
boost::shared_ptr<pcl::PolygonMesh> mesh_ptr ( new pcl::PolygonMesh () );
pcl::toROSMsg (cloud, mesh_ptr->cloud);
mesh_ptr->polygons.resize (triangles.size () / 3);
for (size_t i = 0; i < mesh_ptr->polygons.size (); ++i)
{
pcl::Vertices v;
v.vertices.push_back (i*3+0);
v.vertices.push_back (i*3+2);
v.vertices.push_back (i*3+1);
mesh_ptr->polygons[i] = v;
}
return (mesh_ptr);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> typename pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::MeshPtr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::runMarchingCubes ()
{
//Preparing the pointers and variables
const TsdfVolume::Ptr tsdf_volume_const_ = tsdf_volume_gpu_;
pcl::gpu::DeviceArray<pcl::PointXYZ> triangles_buffer_device_;
//Creating Marching cubes instance
MarchingCubes::Ptr marching_cubes_ = MarchingCubes::Ptr ( new MarchingCubes() );
//Running marching cubes
pcl::gpu::DeviceArray<pcl::PointXYZ> triangles_device = marching_cubes_->run (*tsdf_volume_const_, triangles_buffer_device_);
//Creating mesh
boost::shared_ptr<pcl::PolygonMesh> mesh_ptr_ = convertTrianglesToMesh (triangles_device);
if(mesh_ptr_ != 0)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tmp_ptr (new pcl::PointCloud<pcl::PointXYZ>);
fromROSMsg ( mesh_ptr_->cloud, *cloud_tmp_ptr);
}
return (mesh_ptr_);
}
///////////////////////////////////////////////////////////////////////////////
#endif // PCL_STANDALONE_MARCHING_CUBES_IMPL_HPP_
<commit_msg>fix bad reinit on a vector<commit_after> /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_STANDALONE_MARCHING_CUBES_IMPL_HPP_
#define PCL_STANDALONE_MARCHING_CUBES_IMPL_HPP_
#include <pcl/gpu/kinfu_large_scale/standalone_marching_cubes.h>
///////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::StandaloneMarchingCubes (int new_voxels_x, int new_voxels_y, int new_voxels_z, float new_volume_size)
{
voxels_x_ = new_voxels_x;
voxels_y_ = new_voxels_y;
voxels_z_ = new_voxels_z;
volume_size_ = new_volume_size;
///Creating GPU TSDF Volume instance
const Eigen::Vector3f volume_size = Eigen::Vector3f::Constant (volume_size_);
// std::cout << "VOLUME SIZE IS " << volume_size_ << std::endl;
const Eigen::Vector3i volume_resolution (voxels_x_, voxels_y_, voxels_z_);
tsdf_volume_gpu_ = TsdfVolume::Ptr ( new TsdfVolume (volume_resolution) );
tsdf_volume_gpu_->setSize (volume_size);
///Creating CPU TSDF Volume instance
int tsdf_total_size = voxels_x_ * voxels_y_ * voxels_z_;
tsdf_volume_cpu_= std::vector<int> (tsdf_total_size,0);
mesh_counter_ = 0;
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> typename pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::MeshPtr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::getMeshFromTSDFCloud (const PointCloud &cloud)
{
//Clearing TSDF GPU and cPU
const Eigen::Vector3f volume_size = Eigen::Vector3f::Constant (volume_size_);
std::cout << "VOLUME SIZE IS " << volume_size_ << std::endl;
const Eigen::Vector3i volume_resolution (voxels_x_, voxels_y_, voxels_z_);
//Clear values in TSDF Volume GPU
tsdf_volume_gpu_->reset (); // This one uses the same tsdf volume but clears it before loading new values. This one is our friend.
//Clear values in TSDF Volume CPU
fill (tsdf_volume_cpu_.begin (), tsdf_volume_cpu_.end (), 0);
//Loading values to GPU
loadTsdfCloudToGPU (cloud);
//Creating and returning mesh
return ( runMarchingCubes () );
}
///////////////////////////////////////////////////////////////////////////////
//template <typename PointT> std::vector< typename pcl::gpu::StandaloneMarchingCubes<PointT>::MeshPtr >
template <typename PointT> void
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::getMeshesFromTSDFVector (const std::vector<PointCloudPtr> &tsdf_clouds, const std::vector<Eigen::Vector3f> &tsdf_offsets)
{
std::vector< MeshPtr > meshes_vector;
int max_iterations = std::min( tsdf_clouds.size (), tsdf_offsets.size () ); //Safety check
PCL_INFO ("There are %d cubes to be processed \n", max_iterations);
float cell_size = volume_size_ / voxels_x_;
int mesh_counter = 0;
for(int i = 0; i < max_iterations; ++i)
{
PCL_INFO ("Processing cube number %d\n", i);
//Making cloud local
Eigen::Affine3f cloud_transform;
float originX = (tsdf_offsets[i]).x();
float originY = (tsdf_offsets[i]).y();
float originZ = (tsdf_offsets[i]).z();
cloud_transform.linear ().setIdentity ();
cloud_transform.translation ()[0] = -originX;
cloud_transform.translation ()[1] = -originY;
cloud_transform.translation ()[2] = -originZ;
transformPointCloud (*tsdf_clouds[i], *tsdf_clouds[i], cloud_transform);
//Get mesh
MeshPtr tmp = getMeshFromTSDFCloud (*tsdf_clouds[i]);
if(tmp != 0)
{
meshes_vector.push_back (tmp);
mesh_counter++;
}
else
{
PCL_INFO ("This cloud returned no faces, we skip it!\n");
continue;
}
//Making cloud global
cloud_transform.translation ()[0] = originX * cell_size;
cloud_transform.translation ()[1] = originY * cell_size;
cloud_transform.translation ()[2] = originZ * cell_size;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tmp_ptr (new pcl::PointCloud<pcl::PointXYZ>);
fromROSMsg ( (meshes_vector.back () )->cloud, *cloud_tmp_ptr);
transformPointCloud (*cloud_tmp_ptr, *cloud_tmp_ptr, cloud_transform);
toROSMsg (*cloud_tmp_ptr, (meshes_vector.back () )->cloud);
std::stringstream name;
name << "mesh_" << mesh_counter << ".ply";
PCL_INFO ("Saving mesh...%d \n", mesh_counter);
pcl::io::savePLYFile (name.str (), *(meshes_vector.back ()));
}
return;
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> pcl::gpu::kinfuLS::TsdfVolume::Ptr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::tsdfVolumeGPU ()
{
return (tsdf_volume_gpu_);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> std::vector<int>& //todo
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::tsdfVolumeCPU ()
{
return (tsdf_volume_cpu_);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::loadTsdfCloudToGPU (const PointCloud &cloud)
{
//Converting Values
convertTsdfVectors (cloud, tsdf_volume_cpu_);
//Uploading data to GPU
int cubeColumns = voxels_x_;
tsdf_volume_gpu_->data ().upload (tsdf_volume_cpu_, cubeColumns);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::convertTsdfVectors (const PointCloud &cloud, std::vector<int> &output)
{
const int DIVISOR = 32767; // SHRT_MAX;
///For every point in the cloud
#pragma omp parallel for
for(int i = 0; i < (int) cloud.points.size (); ++i)
{
int x = cloud.points[i].x;
int y = cloud.points[i].y;
int z = cloud.points[i].z;
if(x > 0 && x < voxels_x_ && y > 0 && y < voxels_y_ && z > 0 && z < voxels_z_)
{
///Calculate the index to write to
int dst_index = x + voxels_x_ * y + voxels_y_ * voxels_x_ * z;
short2& elem = *reinterpret_cast<short2*> (&output[dst_index]);
elem.x = static_cast<short> (cloud.points[i].intensity * DIVISOR);
elem.y = static_cast<short> (1);
}
}
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> typename pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::MeshPtr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::convertTrianglesToMesh (const pcl::gpu::DeviceArray<pcl::PointXYZ>& triangles)
{
if (triangles.empty () )
{
return MeshPtr ();
}
pcl::PointCloud<pcl::PointXYZ> cloud;
cloud.width = (int)triangles.size ();
cloud.height = 1;
triangles.download (cloud.points);
boost::shared_ptr<pcl::PolygonMesh> mesh_ptr ( new pcl::PolygonMesh () );
pcl::toROSMsg (cloud, mesh_ptr->cloud);
mesh_ptr->polygons.resize (triangles.size () / 3);
for (size_t i = 0; i < mesh_ptr->polygons.size (); ++i)
{
pcl::Vertices v;
v.vertices.push_back (i*3+0);
v.vertices.push_back (i*3+2);
v.vertices.push_back (i*3+1);
mesh_ptr->polygons[i] = v;
}
return (mesh_ptr);
}
///////////////////////////////////////////////////////////////////////////////
template <typename PointT> typename pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::MeshPtr
pcl::gpu::kinfuLS::StandaloneMarchingCubes<PointT>::runMarchingCubes ()
{
//Preparing the pointers and variables
const TsdfVolume::Ptr tsdf_volume_const_ = tsdf_volume_gpu_;
pcl::gpu::DeviceArray<pcl::PointXYZ> triangles_buffer_device_;
//Creating Marching cubes instance
MarchingCubes::Ptr marching_cubes_ = MarchingCubes::Ptr ( new MarchingCubes() );
//Running marching cubes
pcl::gpu::DeviceArray<pcl::PointXYZ> triangles_device = marching_cubes_->run (*tsdf_volume_const_, triangles_buffer_device_);
//Creating mesh
boost::shared_ptr<pcl::PolygonMesh> mesh_ptr_ = convertTrianglesToMesh (triangles_device);
if(mesh_ptr_ != 0)
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tmp_ptr (new pcl::PointCloud<pcl::PointXYZ>);
fromROSMsg ( mesh_ptr_->cloud, *cloud_tmp_ptr);
}
return (mesh_ptr_);
}
///////////////////////////////////////////////////////////////////////////////
#endif // PCL_STANDALONE_MARCHING_CUBES_IMPL_HPP_
<|endoftext|>
|
<commit_before>#include <boost/bind.hpp>
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>
#include <iostream>
using namespace std;
#define PI 3.1415926
namespace gazebo
{
class ModelController1 : public ModelPlugin
{
public: ModelController1() : ModelPlugin(),DefaultKPID(0.01,0,0)
{
// Initialize variables
WheelRadius = 0.045275;
// A hint of model been initialized
printf("Model Initiated\n");
}
public: void Load (physics::ModelPtr _parent, sdf::ElementPtr _sdf)
{
// Get all the pointers point to right objects
this->model = _parent;
this->JointWR = model->GetJoint("Right_wheel_hinge");
this->JointWL = model->GetJoint("Left_wheel_hinge");
this->JointWF = model->GetJoint("Front_wheel_hinge");
this->JointCB = model->GetJoint("Center_hinge");
// Setting the model state
// Setting the maximium torque of the two wheels
this->JointWR->SetMaxForce(0,1000);
this->JointWL->SetMaxForce(0,1000);
// Setting the maximium torque of the front wheel
this->JointWF->SetMaxForce(0,1000);
// Setting the maximium torque of the body bending joint
this->JointCB->SetMaxForce(0,1000);
// Testing codes
this->JointWR->SetVelocity(0,0);
this->JointWL->SetVelocity(0,0);
math::Angle AngleInterested(0.5235987);
this->JointCB->SetAngle(0,AngleInterested);
// Event register, which will make the function be executed in each iteration
this->updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&ModelController1::OnSystemRunning, this, _1));
}
// Testing function
private: void OnSystemRunning(const common::UpdateInfo & /*_info*/)
{
double AngleValue;
double force;
// math::Angle angleOfJoint1;
// angleOfJoint1 = Joint1->GetAngle(2);
// AngleValue = angleOfJoint1.Degree();
//****************************************************
//common::Time TimeTmp;
//physics::ModelState currentModelState(this->model);
//TimeTmp = currentModelState.GetSimTime();
//AngleValue = TimeTmp.Double();
//***************************************************
//AngleValue = this->RevolutionSpeedCal(Joint1,1);
//cout<<"Angle:"<<AngleValue<<endl;
//cout<<"Rotation Speed:"<<AngleValue<<" rad/s"<<endl;
// math::Vector3 TmpPID(0,0,0);
// PIDSpeedController(Joint1,0,PI/10,TmpPID);
force = JointCB->GetForce(0);
cout<<"The Angle of the bending:"<<force<<endl;
// if (force > 0)
// {
// this->JointCB->SetVelocity(0,-0.1);
// }else{
// this->JointCB->SetVelocity(0,0);
// }
AngleValue = this->RevolutionSpeedCal(JointWR,0);
cout<<"The real rotation rate is "<<AngleValue<<" rad/s"<<endl;
}
// This public function is used to control the speed of joint
// The third parameter determine what kind of speed the user want to controll: 0 for rotation, 1 for linear, 2 for prismatic
// If want to use the default PID controller parameters, just pass math::Vector3::Zero to KPID
// If there is any errors or uncompleted information, the function will return false
public: bool PIDSpeedController(const physics::JointPtr JointNTBC, const int AxisIndex, const double ExpectedSpeed,
math::Vector3 KPID , const int SpeedType = 0, const double Radius = 0)
{
double SpeedCurrent;
double TorqueIncrement;
static double TotalTorque;
// If PID parameters are not specified, set them to default
if (KPID.x==0 && KPID.y==0 && KPID.z == 0)
{
KPID = DefaultKPID;
}
if (SpeedType == 0)
{
double SpeedErrorT0;
static double SpeedErrorHis1T0 = 0, SpeedErrorHis2T0 = 0;
static double SpeedErrorAccu = 0;
SpeedCurrent = this->ComplementaryFilter(this->RevolutionSpeedCal(JointNTBC,AxisIndex));
cout<<"SpeedCurrent = "<<SpeedCurrent<<endl;
cout<<"ExpectedSpeed = "<<ExpectedSpeed<<endl;
SpeedErrorT0 = ExpectedSpeed - SpeedCurrent;
cout<<"SpeedErrorT0 = "<<SpeedErrorT0<<endl;
//cout<<"The Current Error is "<<SpeedErrorT0<<" rad/s"<<endl;
SpeedErrorAccu += SpeedErrorT0;
TorqueIncrement = KPID.x*SpeedErrorT0 + KPID.y*SpeedErrorAccu + KPID.z*(SpeedErrorT0-SpeedErrorHis1T0);
cout<<"The Torque Increment "<<TorqueIncrement<<endl;
SpeedErrorHis2T0 = SpeedErrorHis1T0;
SpeedErrorHis1T0 = SpeedErrorT0;
}else{
if (SpeedType == 1)
{
// If the function is configured to calculate linar speed for a wheel but no radiu has been specified
// return false and end the function
if (Radius == 0)
{
cout<<"Wrong radius input when calculating linear speed of a wheel."<<endl;
return false;
}else{
}
}else{
if (SpeedType == 2)
{
/* code */
}else{
cout<<"Wrong Speed Type."<<endl;
return false;
}
}
}
TotalTorque += TorqueIncrement;
cout<<"TotalTorque = "<<TotalTorque<<endl;
double TotalTorqueRef;
TotalTorqueRef = JointNTBC->GetForce(AxisIndex) + TorqueIncrement;
cout<<"TotalTorqueRef = "<<TotalTorqueRef<<endl;
JointNTBC->SetForce(AxisIndex,(JointNTBC->GetForce(AxisIndex) + TorqueIncrement));
return true;
}
// This public function is used to calculate the angular velocity of a revolute joint
// This method is only valid in simulation
public: double RevolutionSpeedCal(physics::JointPtr JointNTBC, const int AxisIndex)
{
double ResSpeedRef;
// In the API instruction, fucntion GetVelocity() returns the "rotation rate"
// The unit of this rotation rate is "rad/s"
ResSpeedRef = JointNTBC->GetVelocity(AxisIndex);
//cout<<"ResSpeedRef = "<<ResSpeedRef<<" rad/s"<<endl;
return ResSpeedRef;
}
// This function is an old version function of RevolutionSpeedCal()
// Which has the same functionality as RevolutionSpeedCal()
private: double RevolutionSpeedCalOld(physics::JointPtr JointNTBC, const int AxisIndex)
{
math::Angle CurrentAngle;
double CurrentAngleRadVal;
static double CurrentAngleRadValHis = 0;
common::Time TimeTmp;
physics::JointState CurrentJointState(JointNTBC);
double TimeStampNow;
static double TimeStampNowHis = 0;
double RevSpeed;
CurrentAngle = JointNTBC->GetAngle(AxisIndex);
CurrentAngleRadVal = CurrentAngle.Radian();
TimeTmp = CurrentJointState.GetSimTime();
TimeStampNow = TimeTmp.Double();
// This method uses the change of the angle divided by the time interval
RevSpeed = (CurrentAngleRadVal-CurrentAngleRadValHis)/(TimeStampNow-TimeStampNowHis); // The unit is rad/sec
CurrentAngleRadValHis = CurrentAngleRadVal;
TimeStampNowHis = TimeStampNow;
return RevSpeed;
}
// A complementary filter
// The default coefficient of the filter is 0.9
public: double ComplementaryFilter(double FilteringValue, double ComplementFilterPar = 0.9)
{
static double ValueRecorder = 0;
double FiltedValue;
FiltedValue = (1 - ComplementFilterPar)*FilteringValue + ComplementFilterPar*ValueRecorder;
ValueRecorder = FiltedValue;
return FiltedValue;
}
// Current Model Pointer
private: physics::ModelPtr model;
// Pointers to all the Joints the current model has
private: physics::JointPtr JointWR;
private: physics::JointPtr JointWL;
private: physics::JointPtr JointWF;
private: physics::JointPtr JointCB;
// The event that will be refreshed in every iteration of the simulation
private: event::ConnectionPtr updateConnection;
// Default PID controller
public: math::Vector3 DefaultKPID; // First digit is Kp, second digit is Ki and third digit is Kd
//################# Variables for testing ############################
// In the future version, this radius value will be eliminate
private: double WheelRadius;
//####################################################################
};
GZ_REGISTER_MODEL_PLUGIN(ModelController1)
}<commit_msg>Clear up my code a little bit, adapt a new structure for this model controller<commit_after>#include <boost/bind.hpp>
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.1415926
namespace gazebo
{
class ModelController1 : public ModelPlugin
{
public: ModelController1() : ModelPlugin(),DefaultKPID(0.01,0,0)
{
// Initialize variables
WheelRadius = 0.045275;
// A hint of model been initialized
printf("Model Initiated\n");
}
public: void Load (physics::ModelPtr _parent, sdf::ElementPtr _sdf)
{
// Initialize the whole system
SystemInitialization(_parent);
// Testing codes
this->JointWR->SetVelocity(0,0);
this->JointWL->SetVelocity(0,0);
math::Angle AngleInterested(0.5235987);
this->JointCB->SetAngle(0,AngleInterested);
// Event register, which will make the function be executed in each iteration
this->updateConnection = event::Events::ConnectWorldUpdateBegin(boost::bind(&ModelController1::OnSystemRunning, this, _1));
}
private: void SystemInitialization(physics::ModelPtr parentModel)
{
// Get all the pointers point to right objects
this->model = parentModel;
this->JointWR = model->GetJoint("Right_wheel_hinge");
this->JointWL = model->GetJoint("Left_wheel_hinge");
this->JointWF = model->GetJoint("Front_wheel_hinge");
this->JointCB = model->GetJoint("Center_hinge");
// Setting the model states
// Setting the maximium torque of the two wheels
this->JointWR->SetMaxForce(0,1000);
this->JointWL->SetMaxForce(0,1000);
// Setting the maximium torque of the front wheel
this->JointWF->SetMaxForce(0,1000);
// Setting the maximium torque of the body bending joint
this->JointCB->SetMaxForce(0,1000);
// Set the angle of the hinge in the center to zero
math::Angle InitialAngle(0);
this->JointCB->SetAngle(0, InitialAngle);
}
// Testing function
private: void OnSystemRunning(const common::UpdateInfo & /*_info*/)
{
double AngleValue;
double force;
force = JointCB->GetForce(0);
cout<<"The Angle of the bending:"<<force<<endl;
AngleValue = this->RevolutionSpeedCal(JointWR,0);
cout<<"The real rotation rate is "<<AngleValue<<" rad/s"<<endl;
}
// The unit of the angle is radian
// In the future, this function should be defined as virtual
public: void SetJointAngle(physics::JointPtr CurrentJoint, int RotAxis, math::Angle AngleDesired)
{
CurrentJoint->SetAngle(RotAxis, AngleDesired);
}
// This function will set the rotation rate of the joint
// The unit of this speed is rad/s
// In the future, this function should be defined as virtual
public: void SetJointSpeed(physics::JointPtr CurrentJoint, int RotAxis, double SpeedDesired)
{
CurrentJoint->SetVelocity(RotAxis,SpeedDesired);
}
// This public function is used to calculate the angular velocity of a revolute joint
// In the future, this function should be defined as virtual
public: double RevolutionSpeedCal(physics::JointPtr JointNTBC, const int AxisIndex)
{
double ResSpeedRef;
// In the API instruction, fucntion GetVelocity() returns the "rotation rate"
// The unit of this rotation rate is "rad/s"
ResSpeedRef = JointNTBC->GetVelocity(AxisIndex);
//cout<<"ResSpeedRef = "<<ResSpeedRef<<" rad/s"<<endl;
return ResSpeedRef;
}
// This function is an old version function of RevolutionSpeedCal()
// Which has the same functionality as RevolutionSpeedCal()
private: double RevolutionSpeedCalOld(physics::JointPtr JointNTBC, const int AxisIndex)
{
math::Angle CurrentAngle;
double CurrentAngleRadVal;
static double CurrentAngleRadValHis = 0;
common::Time TimeTmp;
physics::JointState CurrentJointState(JointNTBC);
double TimeStampNow;
static double TimeStampNowHis = 0;
double RevSpeed;
CurrentAngle = JointNTBC->GetAngle(AxisIndex);
CurrentAngleRadVal = CurrentAngle.Radian();
TimeTmp = CurrentJointState.GetSimTime();
TimeStampNow = TimeTmp.Double();
// This method uses the change of the angle divided by the time interval
RevSpeed = (CurrentAngleRadVal-CurrentAngleRadValHis)/(TimeStampNow-TimeStampNowHis); // The unit is rad/sec
CurrentAngleRadValHis = CurrentAngleRadVal;
TimeStampNowHis = TimeStampNow;
return RevSpeed;
}
// Angle calculation base on the two points
// This angle is in the static global frame
private: math::Angle AngleCalculation2Points(math::Vector2d StartPoint, math::Vector2d EndPoint)
{
double displacementX, displacementY, angleC;
displacementX = EndPoint.x - StartPoint.x;
displacementY = EndPoint.y - EndPoint.y;
angleC = atan2(displacementY,displacementX);
math::Angle ReturnAngle(angleC);
return ReturnAngle;
}
// Angle PID Controller
// DesiredAngleis in the static global frame
// CurrentSpeed is the rotation rate of the wheel
private: void AnglePIDController(math::Angle DesiredAngle, math::Angle CurrentAngle, math::Vector2d CurrentSpeed)
{
}
// A complementary filter
// The default coefficient of the filter is 0.9
public: double ComplementaryFilter(double FilteringValue, double ComplementFilterPar = 0.9)
{
static double ValueRecorder = 0;
double FiltedValue;
FiltedValue = (1 - ComplementFilterPar)*FilteringValue + ComplementFilterPar*ValueRecorder;
ValueRecorder = FiltedValue;
return FiltedValue;
}
// Current Model Pointer
private: physics::ModelPtr model;
// Pointers to all the Joints the current model has
private: physics::JointPtr JointWR;
private: physics::JointPtr JointWL;
private: physics::JointPtr JointWF;
private: physics::JointPtr JointCB;
// The event that will be refreshed in every iteration of the simulation
private: event::ConnectionPtr updateConnection;
// Default PID controller
public: math::Vector3 DefaultKPID; // First digit is Kp, second digit is Ki and third digit is Kd
//################# Variables for testing ############################
// In the future version, this radius value will be eliminate
private: double WheelRadius;
//####################################################################
};
GZ_REGISTER_MODEL_PLUGIN(ModelController1)
}<|endoftext|>
|
<commit_before>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
#pragma comment( lib, "libglog_static_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libglog_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#pragma comment( lib, "libglog_static.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libglog.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<commit_msg>Modify complile error of NFLogPlugin<commit_after>#include "NFComm/NFPluginModule/NFPlatform.h"
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif
#pragma comment( lib, "Dbghelp.lib" )
#ifdef NF_DEBUG_MODE
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#else
#pragma comment( lib, "NFCore_d.lib" )
#pragma comment( lib, "Theron_d.lib" )
#endif
//#pragma comment( lib, "Theron_d.lib" )
//#pragma comment( lib, "libglog_static_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore_d.a" )
#pragma comment( lib, "libglog_d.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#else
#if NF_PLATFORM == NF_PLATFORM_WIN
#ifdef NF_DYNAMIC_PLUGIN
#pragma comment( lib, "NFCore.lib" )
#pragma comment( lib, "Theron.lib" )
#else
#pragma comment( lib, "NFCorec.lib" )
#pragma comment( lib, "Theron.lib" )
#endif
//#pragma comment( lib, "Theron.lib" )
#pragma comment( lib, "libglog_static.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "NFCore.a" )
#pragma comment( lib, "libglog.a" )
#pragma comment( lib, "libtherond.a")
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#endif
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2013, Ford Motor Company
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 Ford Motor Company 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.
*/
#include "application_manager/commands/mobile/register_app_interface_response.h"
#include "interfaces/MOBILE_API.h"
#include "application_manager/policies/policy_handler.h"
#include "application_manager/application_manager_impl.h"
#include "connection_handler/connection_handler.h"
namespace application_manager {
namespace commands {
void RegisterAppInterfaceResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
bool success = (*message_)[strings::msg_params][strings::success].asBool();
bool last_message = !success;
// Do not close connection in case of APPLICATION_NOT_REGISTERED despite it is an error
if (!success && (*message_)[strings::msg_params].keyExists(strings::result_code)) {
result_code = static_cast<mobile_apis::Result::eType>(
(*message_)[strings::msg_params][strings::result_code].asInt());
if (result_code == mobile_apis::Result::APPLICATION_REGISTERED_ALREADY) {
last_message = false;
}
}
SendResponse(success, result_code, last_message);
// Add registered application to the policy db right after response sent to
// mobile to be able to check all other API according to app permissions
uint32_t connection_key =
(*message_)[strings::params][strings::connection_key].asUInt();
application_manager::ApplicationConstSharedPtr app =
application_manager::ApplicationManagerImpl::instance()->
application(connection_key);
if (app.valid()) {
policy::PolicyHandler *policy_handler = policy::PolicyHandler::instance();
std::string mobile_app_id = app->mobile_app_id();
policy_handler->OnAppRegisteredOnMobile(mobile_app_id);
SetHeartBeatTimeout(connection_key, mobile_app_id);
}
}
void RegisterAppInterfaceResponse::SetHeartBeatTimeout(
uint32_t connection_key, const std::string& mobile_app_id) {
LOG4CXX_AUTO_TRACE(logger_);
policy::PolicyHandler *policy_handler = policy::PolicyHandler::instance();
if (policy_handler->PolicyEnabled()) {
const int32_t timeout = policy_handler->HeartBeatTimeout(mobile_app_id) /
date_time::DateTime::MILLISECONDS_IN_SECOND;
if (timeout > 0) {
application_manager::ApplicationManagerImpl::instance()->
connection_handler()->SetHeartBeatTimeout(connection_key, timeout);
}
} else {
LOG4CXX_INFO(logger_, "Policy is turn off");
}
}
} // namespace commands
} // namespace application_manager
<commit_msg>Avoid PROTOCOL_VIOLATION during streaming process<commit_after>/*
Copyright (c) 2013, Ford Motor Company
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 Ford Motor Company 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.
*/
#include "application_manager/commands/mobile/register_app_interface_response.h"
#include "interfaces/MOBILE_API.h"
#include "application_manager/policies/policy_handler.h"
#include "application_manager/application_manager_impl.h"
#include "connection_handler/connection_handler.h"
namespace application_manager {
namespace commands {
void RegisterAppInterfaceResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
bool success = (*message_)[strings::msg_params][strings::success].asBool();
bool last_message = !success;
// Do not close connection in case of APPLICATION_NOT_REGISTERED despite it is an error
if (!success && (*message_)[strings::msg_params].keyExists(strings::result_code)) {
result_code = static_cast<mobile_apis::Result::eType>(
(*message_)[strings::msg_params][strings::result_code].asInt());
if (result_code == mobile_apis::Result::APPLICATION_REGISTERED_ALREADY) {
last_message = false;
}
}
SendResponse(success, result_code, last_message);
if (mobile_apis::Result::SUCCESS != result_code) { return; }
// Add registered application to the policy db right after response sent to
// mobile to be able to check all other API according to app permissions
uint32_t connection_key =
(*message_)[strings::params][strings::connection_key].asUInt();
application_manager::ApplicationConstSharedPtr app =
application_manager::ApplicationManagerImpl::instance()->
application(connection_key);
if (app.valid()) {
policy::PolicyHandler *policy_handler = policy::PolicyHandler::instance();
std::string mobile_app_id = app->mobile_app_id();
policy_handler->OnAppRegisteredOnMobile(mobile_app_id);
SetHeartBeatTimeout(connection_key, mobile_app_id);
}
}
void RegisterAppInterfaceResponse::SetHeartBeatTimeout(
uint32_t connection_key, const std::string& mobile_app_id) {
LOG4CXX_AUTO_TRACE(logger_);
policy::PolicyHandler *policy_handler = policy::PolicyHandler::instance();
if (policy_handler->PolicyEnabled()) {
const int32_t timeout = policy_handler->HeartBeatTimeout(mobile_app_id) /
date_time::DateTime::MILLISECONDS_IN_SECOND;
if (timeout > 0) {
application_manager::ApplicationManagerImpl::instance()->
connection_handler()->SetHeartBeatTimeout(connection_key, timeout);
}
} else {
LOG4CXX_INFO(logger_, "Policy is turn off");
}
}
} // namespace commands
} // namespace application_manager
<|endoftext|>
|
<commit_before>#include <QApplication>
#include <QtGlobal>
#include <QProcess>
#include <QFile>
#include <QCommandLineParser>
#include "neovimconnector.h"
#include "app.h"
#if defined(Q_OS_WIN) && defined(USE_STATIC_QT)
#include <QtPlugin>
Q_IMPORT_PLUGIN (QWindowsIntegrationPlugin);
#endif
int ui_main(int argc, char **argv)
{
NeovimQt::App app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
int timeout = parser.value("timeout").toInt();
auto c = app.createConnector(parser);
c->setRequestTimeout(timeout);
app.showUi(c, parser);
return app.exec();
}
int cli_main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
QStringList new_args = app.arguments().mid(1);
new_args.insert(0, "--nofork");
if (QProcess::startDetached(app.applicationFilePath(), new_args)) {
return 0;
} else {
qWarning() << "Unable to fork into background";
return -1;
}
}
int main(int argc, char **argv)
{
#if defined (Q_OS_UNIX) && ! defined (Q_OS_MAC)
// Do an early check for --nofork. We need to do this here, before
// creating a QApplication, since QCommandLineParser requires one
bool nofork = false;
for (int i=1; i<argc; i++) {
if (QString::compare("--", argv[i]) == 0) {
break;
} else if (QString::compare("--spawn", argv[i]) == 0) {
break;
} else if (QString::compare("--embed", argv[i]) == 0) {
// Due to https://github.com/equalsraf/neovim-qt/issues/276 --embed
// implies --nofork
nofork = true;
} else if (QString::compare("--nofork", argv[i]) == 0) {
nofork = true;
}
}
if (nofork) {
return ui_main(argc, argv);
} else {
return cli_main(argc, argv);
}
#else
return ui_main(argc, argv);
#endif
}
<commit_msg>Windows: Enable HiDpi scalling<commit_after>#include <QApplication>
#include <QtGlobal>
#include <QProcess>
#include <QFile>
#include <QCommandLineParser>
#include "neovimconnector.h"
#include "app.h"
#if defined(Q_OS_WIN) && defined(USE_STATIC_QT)
#include <QtPlugin>
Q_IMPORT_PLUGIN (QWindowsIntegrationPlugin);
#endif
int ui_main(int argc, char **argv)
{
#ifdef Q_OS_WIN
// Enables automatic high-DPI scaling
// https://github.com/equalsraf/neovim-qt/issues/391
//
// The other way to do this is to set Qt::AA_EnableHighDpiScaling
// but it does not seem to work on Windows.
//
// @equalsraf: For now I'm setting this in windows only, there open
// issues in upstream Qt that suggests this may have unexpected effects
// in other systems (QTBUG-65061, QTBUG-65102), also QTBUG-63580 offers
// contradictory information with what we have experienced.
qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "1");
#endif
NeovimQt::App app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
int timeout = parser.value("timeout").toInt();
auto c = app.createConnector(parser);
c->setRequestTimeout(timeout);
app.showUi(c, parser);
return app.exec();
}
int cli_main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
QStringList new_args = app.arguments().mid(1);
new_args.insert(0, "--nofork");
if (QProcess::startDetached(app.applicationFilePath(), new_args)) {
return 0;
} else {
qWarning() << "Unable to fork into background";
return -1;
}
}
int main(int argc, char **argv)
{
#if defined (Q_OS_UNIX) && ! defined (Q_OS_MAC)
// Do an early check for --nofork. We need to do this here, before
// creating a QApplication, since QCommandLineParser requires one
bool nofork = false;
for (int i=1; i<argc; i++) {
if (QString::compare("--", argv[i]) == 0) {
break;
} else if (QString::compare("--spawn", argv[i]) == 0) {
break;
} else if (QString::compare("--embed", argv[i]) == 0) {
// Due to https://github.com/equalsraf/neovim-qt/issues/276 --embed
// implies --nofork
nofork = true;
} else if (QString::compare("--nofork", argv[i]) == 0) {
nofork = true;
}
}
if (nofork) {
return ui_main(argc, argv);
} else {
return cli_main(argc, argv);
}
#else
return ui_main(argc, argv);
#endif
}
<|endoftext|>
|
<commit_before>#include <QApplication>
#include <QtGlobal>
#include <QProcess>
#include <QFile>
#include <QCommandLineParser>
#include "neovimconnector.h"
#include "app.h"
#if defined(Q_OS_WIN) && defined(USE_STATIC_QT)
#include <QtPlugin>
Q_IMPORT_PLUGIN (QWindowsIntegrationPlugin);
#endif
int ui_main(int argc, char **argv)
{
NeovimQt::App app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
int timeout = parser.value("timeout").toInt();
auto c = app.createConnector(parser);
c->setRequestTimeout(timeout);
app.showUi(c, parser);
return app.exec();
}
int cli_main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
QStringList new_args = app.arguments().mid(1);
new_args.insert(0, "--nofork");
if (QProcess::startDetached(app.applicationFilePath(), new_args)) {
return 0;
} else {
qWarning() << "Unable to fork into background";
return -1;
}
}
int main(int argc, char **argv)
{
#if defined (Q_OS_UNIX) && ! defined (Q_OS_MAC)
// Do an early check for --nofork. We need to do this here, before
// creating a QApplication, since QCommandLineParser requires one
bool nofork = false;
for (int i=1; i<argc; i++) {
if (QString::compare("--", argv[i]) == 0) {
break;
} else if (QString::compare("--spawn", argv[i]) == 0) {
break;
} else if (QString::compare("--nofork", argv[i]) == 0) {
nofork = true;
}
}
if (nofork) {
return ui_main(argc, argv);
} else {
return cli_main(argc, argv);
}
#else
return ui_main(argc, argv);
#endif
}
<commit_msg>Option --embed implies --nofork<commit_after>#include <QApplication>
#include <QtGlobal>
#include <QProcess>
#include <QFile>
#include <QCommandLineParser>
#include "neovimconnector.h"
#include "app.h"
#if defined(Q_OS_WIN) && defined(USE_STATIC_QT)
#include <QtPlugin>
Q_IMPORT_PLUGIN (QWindowsIntegrationPlugin);
#endif
int ui_main(int argc, char **argv)
{
NeovimQt::App app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
int timeout = parser.value("timeout").toInt();
auto c = app.createConnector(parser);
c->setRequestTimeout(timeout);
app.showUi(c, parser);
return app.exec();
}
int cli_main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QCommandLineParser parser;
NeovimQt::App::processCliOptions(parser, app.arguments());
QStringList new_args = app.arguments().mid(1);
new_args.insert(0, "--nofork");
if (QProcess::startDetached(app.applicationFilePath(), new_args)) {
return 0;
} else {
qWarning() << "Unable to fork into background";
return -1;
}
}
int main(int argc, char **argv)
{
#if defined (Q_OS_UNIX) && ! defined (Q_OS_MAC)
// Do an early check for --nofork. We need to do this here, before
// creating a QApplication, since QCommandLineParser requires one
bool nofork = false;
for (int i=1; i<argc; i++) {
if (QString::compare("--", argv[i]) == 0) {
break;
} else if (QString::compare("--spawn", argv[i]) == 0) {
break;
} else if (QString::compare("--embed", argv[i]) == 0) {
// Due to https://github.com/equalsraf/neovim-qt/issues/276 --embed
// implies --nofork
nofork = true;
} else if (QString::compare("--nofork", argv[i]) == 0) {
nofork = true;
}
}
if (nofork) {
return ui_main(argc, argv);
} else {
return cli_main(argc, argv);
}
#else
return ui_main(argc, argv);
#endif
}
<|endoftext|>
|
<commit_before>#include <QApplication>
#include <QFontDatabase>
#include <QtGlobal>
#include <QFile>
#include <QCommandLineParser>
#include <QFileInfo>
#include <QDir>
#include "neovimconnector.h"
#include "mainwindow.h"
/// A log handler for Qt messages, all messages are dumped into the file
/// passed via the NVIM_QT_LOG variable. Some information is only available
/// in debug builds (e.g. qDebug is only called in debug builds).
///
/// In UNIX Qt prints messages to the console output, but in Windows this is
/// the only way to get Qt's debug/warning messages.
void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
QFile logFile(qgetenv("NVIM_QT_LOG"));
if (logFile.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&logFile);
stream << msg << "\n";
}
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
app.setApplicationDisplayName("Neovim");
app.setWindowIcon(QIcon(":/neovim.png"));
if (!qgetenv("NVIM_QT_LOG").isEmpty()) {
qInstallMessageHandler(logger);
}
QCommandLineParser parser;
parser.addOption(QCommandLineOption("embed",
QCoreApplication::translate("main", "Communicate with Neovim over stdin/out")));
parser.addOption(QCommandLineOption("server",
QCoreApplication::translate("main", "Connect to existing Neovim instance"),
QCoreApplication::translate("main", "addr")));
parser.addOption(QCommandLineOption("geometry",
QCoreApplication::translate("main", "Initial window geometry"),
QCoreApplication::translate("main", "geometry")));
parser.addOption(QCommandLineOption("maximized",
QCoreApplication::translate("main", "Maximize the window on startup")));
parser.addOption(QCommandLineOption("fullscreen",
QCoreApplication::translate("main", "Open the window in fullscreen on startup")));
parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]");
parser.addHelpOption();
int sep = app.arguments().indexOf("--");
QStringList neovimArgs;
if (sep != -1) {
QStringList args = app.arguments().mid(0, sep);
neovimArgs += app.arguments().mid(sep+1);
parser.process(app.arguments());
} else {
parser.process(app.arguments());
}
if (parser.isSet("help")) {
parser.showHelp();
}
NeovimQt::NeovimConnector *c;
if (parser.isSet("embed")) {
c = NeovimQt::NeovimConnector::fromStdinOut();
} else {
if (parser.isSet("server")) {
QString server = parser.value("server");
c = NeovimQt::NeovimConnector::connectToNeovim(server);
} else {
#ifdef NVIM_QT_RUNTIME_PATH
if (QFileInfo(NVIM_QT_RUNTIME_PATH).isDir()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("set rtp+=%1")
.arg(NVIM_QT_RUNTIME_PATH));
} else {
QDir d = QFileInfo(QCoreApplication::applicationDirPath()).dir();
d.cd("share");
d.cd("nvim-qt");
d.cd("runtime");
if (d.exists()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("set rtp+=%1")
.arg(d.path()));
}
}
#endif
c = NeovimQt::NeovimConnector::spawn(neovimArgs);
}
}
#ifdef NEOVIMQT_GUI_WIDGET
NeovimQt::Shell *win = new NeovimQt::Shell(c);
win->show();
if (parser.isSet("fullscreen")) {
win->showFullScreen();
} else if (parser.isSet("maximized")) {
win->showMaximized();
} else {
win->show();
}
#else
NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c);
if (parser.isSet("fullscreen")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen);
} else if (parser.isSet("maximized")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized);
} else {
win->delayedShow();
}
#endif
return app.exec();
}
<commit_msg>Always search for relative runtime path<commit_after>#include <QApplication>
#include <QFontDatabase>
#include <QtGlobal>
#include <QFile>
#include <QCommandLineParser>
#include <QFileInfo>
#include <QDir>
#include "neovimconnector.h"
#include "mainwindow.h"
/// A log handler for Qt messages, all messages are dumped into the file
/// passed via the NVIM_QT_LOG variable. Some information is only available
/// in debug builds (e.g. qDebug is only called in debug builds).
///
/// In UNIX Qt prints messages to the console output, but in Windows this is
/// the only way to get Qt's debug/warning messages.
void logger(QtMsgType type, const QMessageLogContext& ctx, const QString& msg)
{
QFile logFile(qgetenv("NVIM_QT_LOG"));
if (logFile.open(QIODevice::Append | QIODevice::Text)) {
QTextStream stream(&logFile);
stream << msg << "\n";
}
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
app.setApplicationDisplayName("Neovim");
app.setWindowIcon(QIcon(":/neovim.png"));
if (!qgetenv("NVIM_QT_LOG").isEmpty()) {
qInstallMessageHandler(logger);
}
QCommandLineParser parser;
parser.addOption(QCommandLineOption("embed",
QCoreApplication::translate("main", "Communicate with Neovim over stdin/out")));
parser.addOption(QCommandLineOption("server",
QCoreApplication::translate("main", "Connect to existing Neovim instance"),
QCoreApplication::translate("main", "addr")));
parser.addOption(QCommandLineOption("geometry",
QCoreApplication::translate("main", "Initial window geometry"),
QCoreApplication::translate("main", "geometry")));
parser.addOption(QCommandLineOption("maximized",
QCoreApplication::translate("main", "Maximize the window on startup")));
parser.addOption(QCommandLineOption("fullscreen",
QCoreApplication::translate("main", "Open the window in fullscreen on startup")));
parser.addPositionalArgument("...", "Additional arguments are fowarded to Neovim", "[-- ...]");
parser.addHelpOption();
int sep = app.arguments().indexOf("--");
QStringList neovimArgs;
if (sep != -1) {
QStringList args = app.arguments().mid(0, sep);
neovimArgs += app.arguments().mid(sep+1);
parser.process(app.arguments());
} else {
parser.process(app.arguments());
}
if (parser.isSet("help")) {
parser.showHelp();
}
NeovimQt::NeovimConnector *c;
if (parser.isSet("embed")) {
c = NeovimQt::NeovimConnector::fromStdinOut();
} else {
if (parser.isSet("server")) {
QString server = parser.value("server");
c = NeovimQt::NeovimConnector::connectToNeovim(server);
} else {
#ifdef NVIM_QT_RUNTIME_PATH
if (QFileInfo(NVIM_QT_RUNTIME_PATH).isDir()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("set rtp+=%1")
.arg(NVIM_QT_RUNTIME_PATH));
} else
#endif
{
QDir d = QFileInfo(QCoreApplication::applicationDirPath()).dir();
d.cd("share");
d.cd("nvim-qt");
d.cd("runtime");
if (d.exists()) {
neovimArgs.insert(0, "--cmd");
neovimArgs.insert(1, QString("set rtp+=%1")
.arg(d.path()));
}
}
c = NeovimQt::NeovimConnector::spawn(neovimArgs);
}
}
#ifdef NEOVIMQT_GUI_WIDGET
NeovimQt::Shell *win = new NeovimQt::Shell(c);
win->show();
if (parser.isSet("fullscreen")) {
win->showFullScreen();
} else if (parser.isSet("maximized")) {
win->showMaximized();
} else {
win->show();
}
#else
NeovimQt::MainWindow *win = new NeovimQt::MainWindow(c);
if (parser.isSet("fullscreen")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::FullScreen);
} else if (parser.isSet("maximized")) {
win->delayedShow(NeovimQt::MainWindow::DelayedShow::Maximized);
} else {
win->delayedShow();
}
#endif
return app.exec();
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include "node_connection.h"
#include "node_request.h"
#include <iostream>
#include <memory>
#include <mutex>
#include <atomic>
namespace arangodb { namespace fuerte { namespace js {
///////////////////////////////////////////////////////////////////////////////
// NConnectionBuilder /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnectionBuilder::New) {
if (info.IsConstructCall()) {
NConnectionBuilder* obj = new NConnectionBuilder();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> builder = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(builder).ToLocalChecked());
}
}
NAN_METHOD(NConnectionBuilder::connect){
try {
v8::Local<v8::Function> connFunction = Nan::New(NConnection::constructor());
const int argc = 1;
v8::Local<v8::Value> argv[argc] = {info.This()};
auto connInstance = Nan::NewInstance(connFunction, argc, argv).ToLocalChecked();
info.GetReturnValue().Set(connInstance);
} catch(std::exception const& e){
std::cerr << "## DRIVER LEVEL EXCEPTION - START ##" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "## DRIVER LEVEL EXCEPTION - END ##" << std::endl;
Nan::ThrowError("ConnectionBuilder.connect binding failed with exception"
" - Make sure the server is up and running");
}
}
NAN_METHOD(NConnectionBuilder::host){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.host(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
std::cerr << "## DRIVER LEVEL EXCEPTION - START ##" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "## DRIVER LEVEL EXCEPTION - END ##" << std::endl;
std::string errorMesasge = std::string("ConnectionBuilder.host binding failed with exception: ") + e.what();
Nan::ThrowError(errorMesasge.c_str());
}
}
NAN_METHOD(NConnectionBuilder::async){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.async(to<bool>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
Nan::ThrowError("ConnectionBuilder.async binding failed with exception");
}
}
NAN_METHOD(NConnectionBuilder::user){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.user(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
Nan::ThrowError("ConnectionBuilder.user binding failed with exception");
}
}
NAN_METHOD(NConnectionBuilder::password){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.password(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
Nan::ThrowError("ConnectionBuilder.user binding failed with exception");
}
}
///////////////////////////////////////////////////////////////////////////////
// NConnection ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnection::New) {
if (info.IsConstructCall()) {
NConnection* obj = new NConnection();
if(info[0]->IsObject()){ // NConnectionBuilderObject -- exact type check?
obj->_cppClass = unwrap<NConnectionBuilder>(info[0])->_cppClass.connect();
}
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
}
}
///////////////////////////////////////////////////////////////////////////////
// SendRequest ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// When we switch to c++14 we should use UniquePersistent and move it into
// the generalized lambda caputre avoiding the locking alltogehter
static std::map<fu::MessageID
,std::pair<v8::Persistent<v8::Function> // error
,v8::Persistent<v8::Function> // success
>
> callbackMap;
static std::mutex maplock;
static std::atomic<uint64_t> jsMessageID(0);
NAN_METHOD(NConnection::sendRequest) {
try {
if (info.Length() != 3 ) {
Nan::ThrowTypeError("Not 3 Arguments");
}
if (!info[1]->IsFunction() || !info[2]->IsFunction()){
Nan::ThrowTypeError("Callback is not a Function");
}
// get isolate - has node only one context??!?!? how do they work
// context is probably a lighter version of isolate but does not allow threads
v8::Isolate* iso = v8::Isolate::GetCurrent();
uint64_t id = jsMessageID.fetch_add(1);
{
std::lock_guard<std::mutex> lock(maplock);
auto& callbackPair = callbackMap[id]; //create map element
auto jsOnErr = v8::Local<v8::Function>::Cast(info[1]);
callbackPair.first.Reset(iso, jsOnErr);
auto jsOnSucc = v8::Local<v8::Function>::Cast(info[2]);
callbackPair.second.Reset(iso, jsOnSucc);
}
fu::OnErrorCallback err = [iso,id](unsigned err
,std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
//TODO add node exceptions to callbacks
v8::HandleScope scope(iso);
auto jsOnErr = v8::Local<v8::Function>();
{ //create local function and dispose persistent
std::lock_guard<std::mutex> lock(maplock);
auto& mapElement = callbackMap[id];
jsOnErr = v8::Local<v8::Function>::New(iso,mapElement.first);
mapElement.first.Reset();
mapElement.second.Reset();
callbackMap.erase(id);
}
// wrap request
v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NRequest::constructor());
auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NResponse::constructor());
auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 3;
v8::Local<v8::Value> argv[argc] = { Nan::New<v8::Integer>(err), reqObj, resObj };
// call
jsOnErr->Call(iso->GetCurrentContext(), jsOnErr, argc, argv);
};
fu::OnSuccessCallback succ = [iso,id](std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
//TODO add node exceptions to callbacks
v8::HandleScope scope(iso);
auto jsOnSucc = v8::Local<v8::Function>();
{ // create locacl function and dispose persistent
std::lock_guard<std::mutex> lock(maplock);
auto& mapElement = callbackMap[id];
//create local function
jsOnSucc = v8::Local<v8::Function>::New(iso,callbackMap[id].second);
//dispose map element
mapElement.first.Reset(); // do not depend on kResetInDestructorFlag of Persistent
mapElement.second.Reset();
callbackMap.erase(id);
}
// wrap request
//v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor()); // with Nan
v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NRequest::constructor());
//auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked(); // with Nan
auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NResponse::constructor());
auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 2;
v8::Local<v8::Value> argv[argc] = { reqObj, resObj };
// call
//jsOnSucc->Call(v8::Null(iso), argc, argv);
jsOnSucc->Call(iso->GetCurrentContext(), jsOnSucc, argc, argv);
//jsOnSucc->Call(iso->GetCurrentContext(), iso->GetCurrentContext()->Global(), argc, argv);
};
//finally invoke the c++ callback
auto req = std::unique_ptr<fu::Request>(new fu::Request(*(unwrap<NRequest>(info[0])->_cppClass))); //copy request so the old object stays valid
unwrapSelf<NConnection>(info)->_cppClass->sendRequest(std::move(req), err, succ);
} catch(std::exception const& e){
Nan::ThrowError("Connection.sendRequest binding failed with exception");
}
}
}}}
<commit_msg>add exceptions js callbacks<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////
#include "node_connection.h"
#include "node_request.h"
#include <iostream>
#include <memory>
#include <mutex>
#include <atomic>
namespace arangodb { namespace fuerte { namespace js {
///////////////////////////////////////////////////////////////////////////////
// NConnectionBuilder /////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnectionBuilder::New) {
if (info.IsConstructCall()) {
NConnectionBuilder* obj = new NConnectionBuilder();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> builder = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(builder).ToLocalChecked());
}
}
NAN_METHOD(NConnectionBuilder::connect){
try {
v8::Local<v8::Function> connFunction = Nan::New(NConnection::constructor());
const int argc = 1;
v8::Local<v8::Value> argv[argc] = {info.This()};
auto connInstance = Nan::NewInstance(connFunction, argc, argv).ToLocalChecked();
info.GetReturnValue().Set(connInstance);
} catch(std::exception const& e){
std::cerr << "## DRIVER LEVEL EXCEPTION - START ##" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "## DRIVER LEVEL EXCEPTION - END ##" << std::endl;
Nan::ThrowError("ConnectionBuilder.connect binding failed with exception"
" - Make sure the server is up and running");
}
}
NAN_METHOD(NConnectionBuilder::host){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.host(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
std::cerr << "## DRIVER LEVEL EXCEPTION - START ##" << std::endl;
std::cerr << e.what() << std::endl;
std::cerr << "## DRIVER LEVEL EXCEPTION - END ##" << std::endl;
std::string errorMesasge = std::string("ConnectionBuilder.host binding failed with exception: ") + e.what();
Nan::ThrowError(errorMesasge.c_str());
}
}
NAN_METHOD(NConnectionBuilder::async){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.async(to<bool>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
Nan::ThrowError("ConnectionBuilder.async binding failed with exception");
}
}
NAN_METHOD(NConnectionBuilder::user){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.user(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
Nan::ThrowError("ConnectionBuilder.user binding failed with exception");
}
}
NAN_METHOD(NConnectionBuilder::password){
try {
if (info.Length() != 1 ) {
Nan::ThrowTypeError("Wrong number of Arguments");
}
unwrapSelf<NConnectionBuilder>(info)->_cppClass.password(to<std::string>(info[0]));
info.GetReturnValue().Set(info.This());
} catch(std::exception const& e){
Nan::ThrowError("ConnectionBuilder.user binding failed with exception");
}
}
///////////////////////////////////////////////////////////////////////////////
// NConnection ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
NAN_METHOD(NConnection::New) {
if (info.IsConstructCall()) {
NConnection* obj = new NConnection();
if(info[0]->IsObject()){ // NConnectionBuilderObject -- exact type check?
obj->_cppClass = unwrap<NConnectionBuilder>(info[0])->_cppClass.connect();
}
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
v8::Local<v8::Function> cons = Nan::New(constructor());
info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
}
}
///////////////////////////////////////////////////////////////////////////////
// SendRequest ////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// When we switch to c++14 we should use UniquePersistent and move it into
// the generalized lambda caputre avoiding the locking alltogehter
static std::map<fu::MessageID
,std::pair<v8::Persistent<v8::Function> // error
,v8::Persistent<v8::Function> // success
>
> callbackMap;
static std::mutex maplock;
static std::atomic<uint64_t> jsMessageID(0);
NAN_METHOD(NConnection::sendRequest) {
try {
if (info.Length() != 3 ) {
Nan::ThrowTypeError("Not 3 Arguments");
}
if (!info[1]->IsFunction() || !info[2]->IsFunction()){
Nan::ThrowTypeError("Callback is not a Function");
}
// get isolate - has node only one context??!?!? how do they work
// context is probably a lighter version of isolate but does not allow threads
v8::Isolate* iso = v8::Isolate::GetCurrent();
uint64_t id = jsMessageID.fetch_add(1);
{
std::lock_guard<std::mutex> lock(maplock);
auto& callbackPair = callbackMap[id]; //create map element
auto jsOnErr = v8::Local<v8::Function>::Cast(info[1]);
callbackPair.first.Reset(iso, jsOnErr);
auto jsOnSucc = v8::Local<v8::Function>::Cast(info[2]);
callbackPair.second.Reset(iso, jsOnSucc);
}
fu::OnErrorCallback err = [iso,id](unsigned err
,std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
try {
v8::HandleScope scope(iso);
auto jsOnErr = v8::Local<v8::Function>();
{ //create local function and dispose persistent
std::lock_guard<std::mutex> lock(maplock);
auto& mapElement = callbackMap[id];
jsOnErr = v8::Local<v8::Function>::New(iso,mapElement.first);
mapElement.first.Reset();
mapElement.second.Reset();
callbackMap.erase(id);
}
// wrap request
v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NRequest::constructor());
auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NResponse::constructor());
auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).FromMaybe(v8::Local<v8::Object>());
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 3;
v8::Local<v8::Value> argv[argc] = { Nan::New<v8::Integer>(err), reqObj, resObj };
// call
jsOnErr->Call(iso->GetCurrentContext(), jsOnErr, argc, argv);
} catch (std::exception const& e){
std::string errorMesasge("Exception in success callback: ");
errorMesasge += e.what();
iso->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(iso,errorMesasge.c_str())));
}
};
fu::OnSuccessCallback succ = [iso,id](std::unique_ptr<fu::Request> creq
,std::unique_ptr<fu::Response> cres)
{
try {
//TODO add node exceptions to callbacks
v8::HandleScope scope(iso);
auto jsOnSucc = v8::Local<v8::Function>();
{ // create locacl function and dispose persistent
std::lock_guard<std::mutex> lock(maplock);
auto& mapElement = callbackMap[id];
//create local function
jsOnSucc = v8::Local<v8::Function>::New(iso,callbackMap[id].second);
//dispose map element
mapElement.first.Reset(); // do not depend on kResetInDestructorFlag of Persistent
mapElement.second.Reset();
callbackMap.erase(id);
}
// wrap request
//v8::Local<v8::Function> requestProto = Nan::New(NConnection::constructor()); // with Nan
v8::Local<v8::Function> requestProto = v8::Local<v8::Function>::New(iso,NRequest::constructor());
//auto reqObj = Nan::NewInstance(requestProto).ToLocalChecked(); // with Nan
auto reqObj = requestProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
unwrap<NRequest>(reqObj)->setCppClass(std::move(creq));
// wrap response
v8::Local<v8::Function> responseProto = v8::Local<v8::Function>::New(iso,NResponse::constructor());
auto resObj = responseProto->NewInstance(iso->GetCurrentContext()).ToLocalChecked();
unwrap<NResponse>(resObj)->setCppClass(std::move(cres));
// build args
const unsigned argc = 2;
v8::Local<v8::Value> argv[argc] = { reqObj, resObj };
// call
//jsOnSucc->Call(v8::Null(iso), argc, argv);
jsOnSucc->Call(iso->GetCurrentContext(), jsOnSucc, argc, argv);
//jsOnSucc->Call(iso->GetCurrentContext(), iso->GetCurrentContext()->Global(), argc, argv);
} catch (std::exception const& e){
std::string errorMesasge("Exception in error callback: ");
errorMesasge += e.what();
iso->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(iso,errorMesasge.c_str())));
}
};
//finally invoke the c++ callback
auto req = std::unique_ptr<fu::Request>(new fu::Request(*(unwrap<NRequest>(info[0])->_cppClass))); //copy request so the old object stays valid
unwrapSelf<NConnection>(info)->_cppClass->sendRequest(std::move(req), err, succ);
} catch(std::exception const& e){
Nan::ThrowError("Connection.sendRequest binding failed with exception");
}
}
}}}
<|endoftext|>
|
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file meta.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__UTIL__META_HPP
#define FL__UTIL__META_HPP
#include <Eigen/Dense>
#include <memory>
#include <fl/util/traits.hpp>
namespace fl
{
/**
* \ingroup meta
*
* \tparam Sizes Variadic argument containing a list of sizes. Each size
* is a result of a constexpr or a const of a signed integral
* type. Unknown sizes are represented by -1 or Eigen::Dynamic.
*
*
* Joins the sizes within the \c Sizes argument list if all sizes are
* non-dynamic. That is, all sizes are greater -1 (\c Eigen::Dynamic). If one of
* the passed sizes is \c Eigen::Dynamic, the total size collapses to
* \c Eigen::Dynamic.
*/
template <int... Sizes> struct JoinSizes;
/**
* \internal
* \ingroup meta
* \copydoc JoinSizes
*
* \tparam Head Head of the \c Sizes list of the previous recursive call
*
* Variadic counting recursion
*/
template <int Head, int... Sizes> struct JoinSizes<Head, Sizes...>
{
enum : signed int
{
Size = IsFixed<Head>() && IsFixed<JoinSizes<Sizes...>::Size>()
? Head + JoinSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of JoinSizes<...>
*/
template <> struct JoinSizes<> { enum: signed int { Size = 0 }; } ;
/**
* \ingroup meta
*
* \brief Function form of JoinSizes for two sizes
*/
inline constexpr int join_sizes(int a, int b)
{
return (a > Eigen::Dynamic && b > Eigen::Dynamic) ? a + b : Eigen::Dynamic;
}
/**
* \ingroup meta
*
* Computes the product of LocalSize times Factor. If one of the parameters is
* set to Eigen::Dynamic, the factor size will collapse to Eigen::Dynbamic as
* well.
*/
template <int ... Sizes> struct ExpandSizes;
/**
* \internal
* \ingroup meta
*/
template <int Head, int... Sizes> struct ExpandSizes<Head, Sizes...>
{
enum: signed int
{
Size = IsFixed<Head>() && IsFixed<ExpandSizes<Sizes...>::Size>()
? Head * ExpandSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of ExpandSizes<...>
*/
template <> struct ExpandSizes<> { enum: signed int { Size = 1 }; } ;
/**
* \ingroup meta
*
* Provides access to the the first type element in the specified variadic list
*/
template <typename...T> struct FirstTypeIn;
/**
* \internal
* \ingroup meta
*
* Implementation of FirstTypeIn
*/
template <typename First, typename...T>
struct FirstTypeIn<First, T...>
{
typedef First Type;
};
/**
* \ingroup meta
*
* Represents a sequence of indices IndexSequence<0, 1, 2, 3, ...>
*
* This is particularly useful to expand tuples
*
* \tparam Indices List of indices starting from 0
*/
template <int ... Indices> struct IndexSequence
{
enum { Size = sizeof...(Indices) };
};
/**
* \ingroup meta
*
* Creates an IndexSequence<0, 1, 2, ...> for a specified size.
*/
template <int Size, int ... Indices>
struct CreateIndexSequence
: CreateIndexSequence<Size - 1, Size - 1, Indices...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal specialization CreateIndexSequence
*/
template <int ... Indices>
struct CreateIndexSequence<0, Indices...>
: IndexSequence<Indices...>
{ };
/**
* \ingroup meta
*
* Meta type defined in terms of a sequence of types
*/
template <typename ... T>
struct TypeSequence
{
enum : signed int { Size = sizeof...(T) };
};
/**
* \internal
* \ingroup meta
*
* Empty TypeSequence
*/
template <> struct TypeSequence<>
{
enum : signed int { Size = Eigen::Dynamic };
};
/**
* \ingroup meta
*
* Creates a \c TypeSequence<T...> by expanding the specified \c Type \c Count
* times.
*/
template <int Count, typename Type, typename...T>
struct CreateTypeSequence
: CreateTypeSequence<Count - 1, Type, Type, T...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal type of CreateTypeSequence
*/
template <typename Type, typename...T>
struct CreateTypeSequence<1, Type, T...>
: TypeSequence<Type, T...>
{ };
/**
* \ingroup meta
*
* Creates an empty \c TypeSequence<> for a \c Count = Eigen::Dynamic
*/
template <typename Type>
struct CreateTypeSequence<Eigen::Dynamic, Type>
: TypeSequence<>
{ };
template <typename Model, typename ParameterProcess>
struct AdaptiveModel { };
/**
* \ingroup meta
*
* Same as CreateTypeSequence, however with a reversed parameter order. This is
* an attempt to make the use of \c CreateTypeSequence more natural. It also
* allows dynamic sizes if needed.
*/
template <typename Type, int Count = Eigen::Dynamic>
struct MultipleOf
: CreateTypeSequence<Count, Type>
{
MultipleOf(std::shared_ptr<Type> instance, int instance_count = Count)
: instance_(instance),
count_(instance_count)
{ }
std::shared_ptr<Type> instance() const { return instance_; }
int count() const { return count_; }
std::shared_ptr<Type> instance_;
int count_;
};
/**
* \internal
* \ingroup meta
* \todo fix
*
* Creates an empty TypeSequence for dynamic count
*/
//template <typename Type>
//struct MultipleOf<Type, Eigen::Dynamic>
// : CreateTypeSequence<Eigen::Dynamic, Type>
//{ };
/**
* \c Join represents a meta operator taking an argument pack which should be
* unified in a specific way. The operator is defined by the following axioms
*
* - Pack of Join<P1, P2, ...>: {P1, P2, ...}
* - Positive pack: sizeof...(T) > 0 for Join<T...>
* - Nesting: Join<P1, Join<P2, P3>> = {P1, P2, P3}
* - Comm. Join<P1, Join<P2, P3>> = Join<Join<P1, P2>, P3>
* - MultipleOf operator: Join<MultipleOf<P, #>>
*
* \ingroup meta
*/
template <typename...T> struct Join;
/**
* \internal
* \ingroup meta
*
* Collapes the argument pack of the Join operator into Model<T...> of ay given
* Join<...> operator.
*/
template <typename...T> struct CollapseJoin;
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which expands the type sequence by the Head
* element assuming Head is neither a Join<...> nor a MultipleOf<P, #> operator.
*/
template <
typename...S,
typename Head,
typename...T,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Head, // Current non-operator pack head element
T...> // Remaining Tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<Head, S...>, // updated type sequence
T...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which unifies a Join<...> pack Head into the
* outer Join pack, i.e.
*
* Join<T1..., Join<T2...>, T3 > = Join<T1..., T2..., T3...>
*/
template <
typename...S,
typename...T,
typename...U,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Join<T...>, // Current pack head element
U...> // Remaining Tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
T..., // Extracted pack from inner Join operator
U...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which translates a MultipleOf<P,#> operator,
* at the head of the pack, into Model<MultipleOf<P, #>>, i.e
*
* Join<T1..., MultipleOf<P, 10>, T2...> =
* Join<T1..., Model<MultipleOf<P, 10>>, T2...>.
*/
template <
typename...S,
typename...T,
typename U,
int Count,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
MultipleOf<U, Count>, // Current pack head element
T...> // Remaining Join pack, the tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Model<MultipleOf<U, Count>>,// Redefine head in terms of Model<>
T...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* Terminal case of Join operator collapsing. The final result of Join<T...>
* is Model<U...> where U are all the expanded non operator types.
*/
template <
typename...S,
template <typename...> class Model
>
struct CollapseJoin<
Model<>,
TypeSequence<S...>>
{
/**
* \brief Final type outcome of the Join Operator
*/
typedef Model<S...> Type;
static_assert(sizeof...(S) > 1,
"Join<A, B, ...> operator must take 2 or more operands");
};
/**
* \internal
* \ingroup meta
*
* Terminal case of Join operator collapsing for a Join of the form
* Join<MultipleOf<P, #>> resulting in Model<MultipleOf<P, #>>
*/
template <
typename M,
int Count,
template <typename...> class Model
>
struct CollapseJoin<Model<>, TypeSequence<Model<MultipleOf<M, Count>>>>
{
typedef Model<MultipleOf<M, Count>> Type;
static_assert(Count > 0 || Count == -1,
"Cannot expand Join<MultipleOf<M, Count>> operator on M. "
"Count must be positive or set to -1 for the dynamic size "
"case.");
};
/**
* \ingroup meta
* Represents any number of available options as defined in #FilterOptions
*/
template <int T> struct Options { enum : signed int { Value = T }; };
/**
* \ingroup meta
* Combines multiple options into one. This allows to specify the options
* listed in an arbitrary number
*/
template <int ... T> struct CombineOptions;
/**
* \internal
* \ingroup meta
*
* Combines the first option within the option pack with the previous one.
*/
template <int Value, int H, int ... T>
struct CombineOptions<Value, H, T...> : CombineOptions<Value | H, T...> { };
/**
* \internal
* \ingroup meta
*
* Terminal case CombineOptions
*/
template <int Value>
struct CombineOptions<Value> { typedef fl::Options<Value> Options; };
/**
* \internal
* \ingroup meta
*
* No Option case
*/
template <>
struct CombineOptions<> { typedef fl::Options<NoOptions> Options; };
}
#endif
<commit_msg>MultipleOf: universal type deduction and perfect forwarding instead of shared_ptr<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file meta.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__UTIL__META_HPP
#define FL__UTIL__META_HPP
#include <Eigen/Dense>
#include <memory>
#include <fl/util/traits.hpp>
namespace fl
{
/**
* \ingroup meta
*
* \tparam Sizes Variadic argument containing a list of sizes. Each size
* is a result of a constexpr or a const of a signed integral
* type. Unknown sizes are represented by -1 or Eigen::Dynamic.
*
*
* Joins the sizes within the \c Sizes argument list if all sizes are
* non-dynamic. That is, all sizes are greater -1 (\c Eigen::Dynamic). If one of
* the passed sizes is \c Eigen::Dynamic, the total size collapses to
* \c Eigen::Dynamic.
*/
template <int... Sizes> struct JoinSizes;
/**
* \internal
* \ingroup meta
* \copydoc JoinSizes
*
* \tparam Head Head of the \c Sizes list of the previous recursive call
*
* Variadic counting recursion
*/
template <int Head, int... Sizes> struct JoinSizes<Head, Sizes...>
{
enum : signed int
{
Size = IsFixed<Head>() && IsFixed<JoinSizes<Sizes...>::Size>()
? Head + JoinSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of JoinSizes<...>
*/
template <> struct JoinSizes<> { enum: signed int { Size = 0 }; } ;
/**
* \ingroup meta
*
* \brief Function form of JoinSizes for two sizes
*/
inline constexpr int join_sizes(int a, int b)
{
return (a > Eigen::Dynamic && b > Eigen::Dynamic) ? a + b : Eigen::Dynamic;
}
/**
* \ingroup meta
*
* Computes the product of LocalSize times Factor. If one of the parameters is
* set to Eigen::Dynamic, the factor size will collapse to Eigen::Dynbamic as
* well.
*/
template <int ... Sizes> struct ExpandSizes;
/**
* \internal
* \ingroup meta
*/
template <int Head, int... Sizes> struct ExpandSizes<Head, Sizes...>
{
enum: signed int
{
Size = IsFixed<Head>() && IsFixed<ExpandSizes<Sizes...>::Size>()
? Head * ExpandSizes<Sizes...>::Size
: Eigen::Dynamic
};
};
/**
* \internal
* \ingroup meta
*
* Terminal specialization of ExpandSizes<...>
*/
template <> struct ExpandSizes<> { enum: signed int { Size = 1 }; } ;
/**
* \ingroup meta
*
* Provides access to the the first type element in the specified variadic list
*/
template <typename...T> struct FirstTypeIn;
/**
* \internal
* \ingroup meta
*
* Implementation of FirstTypeIn
*/
template <typename First, typename...T>
struct FirstTypeIn<First, T...>
{
typedef First Type;
};
/**
* \ingroup meta
*
* Represents a sequence of indices IndexSequence<0, 1, 2, 3, ...>
*
* This is particularly useful to expand tuples
*
* \tparam Indices List of indices starting from 0
*/
template <int ... Indices> struct IndexSequence
{
enum { Size = sizeof...(Indices) };
};
/**
* \ingroup meta
*
* Creates an IndexSequence<0, 1, 2, ...> for a specified size.
*/
template <int Size, int ... Indices>
struct CreateIndexSequence
: CreateIndexSequence<Size - 1, Size - 1, Indices...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal specialization CreateIndexSequence
*/
template <int ... Indices>
struct CreateIndexSequence<0, Indices...>
: IndexSequence<Indices...>
{ };
/**
* \ingroup meta
*
* Meta type defined in terms of a sequence of types
*/
template <typename ... T>
struct TypeSequence
{
enum : signed int { Size = sizeof...(T) };
};
/**
* \internal
* \ingroup meta
*
* Empty TypeSequence
*/
template <> struct TypeSequence<>
{
enum : signed int { Size = Eigen::Dynamic };
};
/**
* \ingroup meta
*
* Creates a \c TypeSequence<T...> by expanding the specified \c Type \c Count
* times.
*/
template <int Count, typename Type, typename...T>
struct CreateTypeSequence
: CreateTypeSequence<Count - 1, Type, Type, T...>
{ };
/**
* \internal
* \ingroup meta
*
* Terminal type of CreateTypeSequence
*/
template <typename Type, typename...T>
struct CreateTypeSequence<1, Type, T...>
: TypeSequence<Type, T...>
{ };
/**
* \ingroup meta
*
* Creates an empty \c TypeSequence<> for a \c Count = Eigen::Dynamic
*/
template <typename Type>
struct CreateTypeSequence<Eigen::Dynamic, Type>
: TypeSequence<>
{ };
template <typename Model, typename ParameterProcess>
struct AdaptiveModel { };
/**
* \ingroup meta
*
* Same as CreateTypeSequence, however with a reversed parameter order. This is
* an attempt to make the use of \c CreateTypeSequence more natural. It also
* allows dynamic sizes if needed.
*/
template <typename Type, int Count = Eigen::Dynamic>
struct MultipleOf
: CreateTypeSequence<Count, Type>
{
template <typename InstanceType>
explicit
MultipleOf(InstanceType&& instance, int instance_count = Count)
: instance(std::forward<InstanceType>(instance)),
count(instance_count)
{ }
Type instance;
int count;
};
/**
* \internal
* \ingroup meta
* \todo fix
*
* Creates an empty TypeSequence for dynamic count
*/
//template <typename Type>
//struct MultipleOf<Type, Eigen::Dynamic>
// : CreateTypeSequence<Eigen::Dynamic, Type>
//{ };
/**
* \c Join represents a meta operator taking an argument pack which should be
* unified in a specific way. The operator is defined by the following axioms
*
* - Pack of Join<P1, P2, ...>: {P1, P2, ...}
* - Positive pack: sizeof...(T) > 0 for Join<T...>
* - Nesting: Join<P1, Join<P2, P3>> = {P1, P2, P3}
* - Comm. Join<P1, Join<P2, P3>> = Join<Join<P1, P2>, P3>
* - MultipleOf operator: Join<MultipleOf<P, #>>
*
* \ingroup meta
*/
template <typename...T> struct Join;
/**
* \internal
* \ingroup meta
*
* Collapes the argument pack of the Join operator into Model<T...> of ay given
* Join<...> operator.
*/
template <typename...T> struct CollapseJoin;
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which expands the type sequence by the Head
* element assuming Head is neither a Join<...> nor a MultipleOf<P, #> operator.
*/
template <
typename...S,
typename Head,
typename...T,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Head, // Current non-operator pack head element
T...> // Remaining Tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<Head, S...>, // updated type sequence
T...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which unifies a Join<...> pack Head into the
* outer Join pack, i.e.
*
* Join<T1..., Join<T2...>, T3 > = Join<T1..., T2..., T3...>
*/
template <
typename...S,
typename...T,
typename...U,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Join<T...>, // Current pack head element
U...> // Remaining Tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
T..., // Extracted pack from inner Join operator
U...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* CollapseJoin specialization which translates a MultipleOf<P,#> operator,
* at the head of the pack, into Model<MultipleOf<P, #>>, i.e
*
* Join<T1..., MultipleOf<P, 10>, T2...> =
* Join<T1..., Model<MultipleOf<P, 10>>, T2...>.
*/
template <
typename...S,
typename...T,
typename U,
int Count,
template <typename...> class Model
>
struct CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
MultipleOf<U, Count>, // Current pack head element
T...> // Remaining Join pack, the tail
: CollapseJoin<
Model<>, // Final model type
TypeSequence<S...>, // Type sequence holding the pack expansion
Model<MultipleOf<U, Count>>,// Redefine head in terms of Model<>
T...> // Remaining Tail
{ };
/**
* \internal
* \ingroup meta
*
* Terminal case of Join operator collapsing. The final result of Join<T...>
* is Model<U...> where U are all the expanded non operator types.
*/
template <
typename...S,
template <typename...> class Model
>
struct CollapseJoin<
Model<>,
TypeSequence<S...>>
{
/**
* \brief Final type outcome of the Join Operator
*/
typedef Model<S...> Type;
static_assert(sizeof...(S) > 1,
"Join<A, B, ...> operator must take 2 or more operands");
};
/**
* \internal
* \ingroup meta
*
* Terminal case of Join operator collapsing for a Join of the form
* Join<MultipleOf<P, #>> resulting in Model<MultipleOf<P, #>>
*/
template <
typename M,
int Count,
template <typename...> class Model
>
struct CollapseJoin<Model<>, TypeSequence<Model<MultipleOf<M, Count>>>>
{
typedef Model<MultipleOf<M, Count>> Type;
static_assert(Count > 0 || Count == -1,
"Cannot expand Join<MultipleOf<M, Count>> operator on M. "
"Count must be positive or set to -1 for the dynamic size "
"case.");
};
/**
* \ingroup meta
* Represents any number of available options as defined in #FilterOptions
*/
template <int T> struct Options { enum : signed int { Value = T }; };
/**
* \ingroup meta
* Combines multiple options into one. This allows to specify the options
* listed in an arbitrary number
*/
template <int ... T> struct CombineOptions;
/**
* \internal
* \ingroup meta
*
* Combines the first option within the option pack with the previous one.
*/
template <int Value, int H, int ... T>
struct CombineOptions<Value, H, T...> : CombineOptions<Value | H, T...> { };
/**
* \internal
* \ingroup meta
*
* Terminal case CombineOptions
*/
template <int Value>
struct CombineOptions<Value> { typedef fl::Options<Value> Options; };
/**
* \internal
* \ingroup meta
*
* No Option case
*/
template <>
struct CombineOptions<> { typedef fl::Options<NoOptions> Options; };
}
#endif
<|endoftext|>
|
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH
#include <memory>
#include <dune/common/static_assert.hh>
#include <dune/common/timer.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/pymor/functions/default.hh>
#include <dune/pymor/functions/checkerboard.hh>
#include "../../../linearelliptic/problems/default.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Problems {
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim = 1 >
class Thermalblock
{
static_assert(AlwaysFalse< EntityImp >::value, "Not available for dimRange > 1!");
};
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >
class Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
: public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;
typedef Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;
public:
typedef Pymor::Function::Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
CheckerboardFunctionType;
using typename BaseType::DiffusionTensorType;
using typename BaseType::FunctionType;
static std::string static_id()
{
return BaseType::BaseType::static_id() + ".thermalblock";
}
static Stuff::Common::ConfigTree default_config(const std::string sub_name = "")
{
typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
ConstantFunctionType;
typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >
ConstantMatrixFunctionType;
Stuff::Common::ConfigTree config;
Stuff::Common::ConfigTree checkerboard_config = CheckerboardFunctionType::default_config();
checkerboard_config["name"] = "diffusion_factor";
checkerboard_config["type"] = CheckerboardFunctionType::static_id();
checkerboard_config["parameter_name"] = "diffusion_factor";
config.add(checkerboard_config, "diffusion_factor");
Stuff::Common::ConfigTree diffusion_tensor_config = ConstantMatrixFunctionType::default_config();
diffusion_tensor_config["name"] = "diffusion_tensor";
diffusion_tensor_config["type"] = ConstantMatrixFunctionType::static_id();
config.add(diffusion_tensor_config, "diffusion_tensor");
Stuff::Common::ConfigTree constant_config = ConstantFunctionType::default_config();
constant_config["type"] = ConstantFunctionType::static_id();
constant_config["name"] = "force";
constant_config["value"] = "1";
config.add(constant_config, "force");
constant_config["name"] = "dirichlet";
constant_config["value"] = "0";
config.add(constant_config, "dirichlet");
constant_config["name"] = "neumann";
config.add(constant_config, "neumann");
if (sub_name.empty())
return config;
else {
Stuff::Common::ConfigTree tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Stuff::Common::ConfigTree config = default_config(),
const std::string sub_name = static_id())
{
const Stuff::Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
std::shared_ptr< CheckerboardFunctionType >
checkerboard_function(CheckerboardFunctionType::create(cfg.sub("diffusion_factor")));
return Stuff::Common::make_unique< ThisType >(checkerboard_function,
BaseType::create_matrix_function("diffusion_tensor", cfg),
BaseType::create_vector_function("force", cfg),
BaseType::create_vector_function("dirichlet", cfg),
BaseType::create_vector_function("neumann", cfg));
} // ... create(...)
Thermalblock(const std::shared_ptr< const CheckerboardFunctionType >& checkerboard_function,
const std::shared_ptr< const DiffusionTensorType >& diffusion_tensor,
const std::shared_ptr< const FunctionType >& force,
const std::shared_ptr< const FunctionType >& diffusion,
const std::shared_ptr< const FunctionType >& neumann)
: BaseType(checkerboard_function, diffusion_tensor, force, diffusion, neumann)
{}
virtual std::string type() const DS_OVERRIDE
{
return BaseType::BaseType::static_id() + ".thermalblock";
}
}; // class Thermalblock< ..., 1 >
} // namespace Problems
namespace DiscreteProblems {
template< class GridImp >
class Thermalblock
{
public:
typedef GridImp GridType;
typedef Stuff::Grid::Providers::Cube< GridType > GridProviderType;
private:
typedef Stuff::Grid::BoundaryInfos::AllDirichlet< typename GridType::LeafIntersection > BoundaryInfoType;
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
public:
typedef double RangeFieldType;
static const unsigned int dimRange = 1;
typedef Problems::Thermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;
static void write_config(const std::string filename, const std::string id)
{
std::ofstream file;
file.open(filename);
file << "[" << id << "]" << std::endl;
file << "filename = " << id << std::endl;
file << "[logging]" << std::endl;
file << "info = true" << std::endl;
file << "debug = true" << std::endl;
file << "file = false" << std::endl;
file << "[parameter]" << std::endl;
file << "0.diffusion_factor = [0.1; 0.1; 1.0; 1.0]" << std::endl;
file << "1.diffusion_factor = [1.0; 1.0; 0.1; 0.1]" << std::endl;
file << GridProviderType::default_config(GridProviderType::static_id());
file << ProblemType::default_config(ProblemType::static_id());
file << "[pymor]" << std::endl;
file << "training_set = random" << std::endl;
file << "num_training_samples = 100" << std::endl;
file << "reductor = generic" << std::endl;
file << "extension_algorithm = gram_schmidt" << std::endl;
file << "extension_algorithm_product = h1_semi" << std::endl;
file << "greedy_error_norm = h1_semi" << std::endl;
file << "use_estimator = False" << std::endl;
file << "max_rb_size = 100" << std::endl;
file << "target_error = 0.01" << std::endl;
file << "final_compression = False" << std::endl;
file << "compression_product = None" << std::endl;
file << "test_set = training" << std::endl;
file << "num_test_samples = 100" << std::endl;
file << "test_error_norm = h1_semi" << std::endl;
file.close();
} // ... write_config(...)
Thermalblock(const std::string id, const std::vector< std::string >& arguments, const bool visualize = true)
{
// mpi
int argc = arguments.size();
char** argv = Stuff::Common::String::vectorToMainArgs(arguments);
#if HAVE_DUNE_FEM
Fem::MPIManager::initialize(argc, argv);
#else
MPIHelper::instance(argc, argv);
#endif
// configuration
config_ = Stuff::Common::ConfigTree(argc, argv, id + ".cfg");
if (!config_.has_sub(id))
DUNE_THROW_COLORFULLY(Stuff::Exceptions::configuration_error,
"Missing sub '" << id << "' in the following ConfigTree:\n\n" << config_);
filename_ = config_.get(id + ".filename", id);
// logger
const Stuff::Common::ConfigTree& logger_config = config_.sub("logging");
int log_flags = Stuff::Common::LOG_CONSOLE;
debug_logging_ = logger_config.get< bool >("debug", false);
if (logger_config.get< bool >("info"))
log_flags = log_flags | Stuff::Common::LOG_INFO;
if (debug_logging_)
log_flags = log_flags | Stuff::Common::LOG_DEBUG;
if (logger_config.get< bool >("file", false))
log_flags = log_flags | Stuff::Common::LOG_FILE;
Stuff::Common::Logger().create(log_flags, id, "", "");
auto& info = Stuff::Common::Logger().info();
Timer timer;
info << "creating grid with '" << GridProviderType::static_id() << "'... " << std::flush;
grid_provider_ = GridProviderType::create(config_);
const auto grid_view = grid_provider_->leaf_view();
info << " done (took " << timer.elapsed()
<< "s, has " << grid_view->indexSet().size(0) << " element";
if (grid_view->indexSet().size(0) > 1)
info << "s";
info << ")" << std::endl;
boundary_info_ = Stuff::Common::ConfigTree("type", BoundaryInfoType::static_id());
info << "setting up ";
info << "'" << ProblemType::static_id() << "'... " << std::flush;
timer.reset();
problem_ = ProblemType::create(config_);
info << "done (took " << timer.elapsed() << "s)" << std::endl;
if (visualize) {
info << "visualizing grid and problem... " << std::flush;
timer.reset();
grid_provider_->visualize(boundary_info_, filename_ + ".grid");
problem_->visualize(*grid_view, filename_ + ".problem");
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} // if (visualize)
} // Thermalblock
std::string filename() const
{
return filename_;
}
const Stuff::Common::ConfigTree& config() const
{
return config_;
}
bool debug_logging() const
{
return debug_logging_;
}
GridProviderType& grid_provider()
{
return *grid_provider_;
}
const GridProviderType& grid_provider() const
{
return *grid_provider_;
}
const Stuff::Common::ConfigTree& boundary_info() const
{
return boundary_info_;
}
const ProblemType& problem() const
{
return *problem_;
}
private:
std::string filename_;
Stuff::Common::ConfigTree config_;
bool debug_logging_;
std::unique_ptr< GridProviderType > grid_provider_;
Stuff::Common::ConfigTree boundary_info_;
std::unique_ptr< const ProblemType > problem_;
}; // class Thermalblock
} // namespace DiscreteProblems
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH
<commit_msg>[linearelliptic...thermalblock] updated config vector syntax<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH
#include <memory>
#include <dune/common/static_assert.hh>
#include <dune/common/timer.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/pymor/functions/default.hh>
#include <dune/pymor/functions/checkerboard.hh>
#include "../../../linearelliptic/problems/default.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Problems {
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim = 1 >
class Thermalblock
{
static_assert(AlwaysFalse< EntityImp >::value, "Not available for dimRange > 1!");
};
template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >
class Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
: public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;
typedef Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;
public:
typedef Pymor::Function::Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
CheckerboardFunctionType;
using typename BaseType::DiffusionTensorType;
using typename BaseType::FunctionType;
static std::string static_id()
{
return BaseType::BaseType::static_id() + ".thermalblock";
}
static Stuff::Common::ConfigTree default_config(const std::string sub_name = "")
{
typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
ConstantFunctionType;
typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >
ConstantMatrixFunctionType;
Stuff::Common::ConfigTree config;
Stuff::Common::ConfigTree checkerboard_config = CheckerboardFunctionType::default_config();
checkerboard_config["name"] = "diffusion_factor";
checkerboard_config["type"] = CheckerboardFunctionType::static_id();
checkerboard_config["parameter_name"] = "diffusion_factor";
config.add(checkerboard_config, "diffusion_factor");
Stuff::Common::ConfigTree diffusion_tensor_config = ConstantMatrixFunctionType::default_config();
diffusion_tensor_config["name"] = "diffusion_tensor";
diffusion_tensor_config["type"] = ConstantMatrixFunctionType::static_id();
config.add(diffusion_tensor_config, "diffusion_tensor");
Stuff::Common::ConfigTree constant_config = ConstantFunctionType::default_config();
constant_config["type"] = ConstantFunctionType::static_id();
constant_config["name"] = "force";
constant_config["value"] = "1";
config.add(constant_config, "force");
constant_config["name"] = "dirichlet";
constant_config["value"] = "0";
config.add(constant_config, "dirichlet");
constant_config["name"] = "neumann";
config.add(constant_config, "neumann");
if (sub_name.empty())
return config;
else {
Stuff::Common::ConfigTree tmp;
tmp.add(config, sub_name);
return tmp;
}
} // ... default_config(...)
static std::unique_ptr< ThisType > create(const Stuff::Common::ConfigTree config = default_config(),
const std::string sub_name = static_id())
{
const Stuff::Common::ConfigTree cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
std::shared_ptr< CheckerboardFunctionType >
checkerboard_function(CheckerboardFunctionType::create(cfg.sub("diffusion_factor")));
return Stuff::Common::make_unique< ThisType >(checkerboard_function,
BaseType::create_matrix_function("diffusion_tensor", cfg),
BaseType::create_vector_function("force", cfg),
BaseType::create_vector_function("dirichlet", cfg),
BaseType::create_vector_function("neumann", cfg));
} // ... create(...)
Thermalblock(const std::shared_ptr< const CheckerboardFunctionType >& checkerboard_function,
const std::shared_ptr< const DiffusionTensorType >& diffusion_tensor,
const std::shared_ptr< const FunctionType >& force,
const std::shared_ptr< const FunctionType >& diffusion,
const std::shared_ptr< const FunctionType >& neumann)
: BaseType(checkerboard_function, diffusion_tensor, force, diffusion, neumann)
{}
virtual std::string type() const DS_OVERRIDE
{
return BaseType::BaseType::static_id() + ".thermalblock";
}
}; // class Thermalblock< ..., 1 >
} // namespace Problems
namespace DiscreteProblems {
template< class GridImp >
class Thermalblock
{
public:
typedef GridImp GridType;
typedef Stuff::Grid::Providers::Cube< GridType > GridProviderType;
private:
typedef Stuff::Grid::BoundaryInfos::AllDirichlet< typename GridType::LeafIntersection > BoundaryInfoType;
typedef typename GridType::template Codim< 0 >::Entity EntityType;
typedef typename GridType::ctype DomainFieldType;
static const unsigned int dimDomain = GridType::dimension;
public:
typedef double RangeFieldType;
static const unsigned int dimRange = 1;
typedef Problems::Thermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;
static void write_config(const std::string filename, const std::string id)
{
std::ofstream file;
file.open(filename);
file << "[" << id << "]" << std::endl;
file << "filename = " << id << std::endl;
file << "[logging]" << std::endl;
file << "info = true" << std::endl;
file << "debug = true" << std::endl;
file << "file = false" << std::endl;
file << "[parameter]" << std::endl;
file << "0.diffusion_factor = [0.1 0.1 1.0 1.0]" << std::endl;
file << "1.diffusion_factor = [1.0 1.0 0.1 0.1]" << std::endl;
file << GridProviderType::default_config(GridProviderType::static_id());
file << ProblemType::default_config(ProblemType::static_id());
file << "[pymor]" << std::endl;
file << "training_set = random" << std::endl;
file << "num_training_samples = 100" << std::endl;
file << "reductor = generic" << std::endl;
file << "extension_algorithm = gram_schmidt" << std::endl;
file << "extension_algorithm_product = h1_semi" << std::endl;
file << "greedy_error_norm = h1_semi" << std::endl;
file << "use_estimator = False" << std::endl;
file << "max_rb_size = 100" << std::endl;
file << "target_error = 0.01" << std::endl;
file << "final_compression = False" << std::endl;
file << "compression_product = None" << std::endl;
file << "test_set = training" << std::endl;
file << "num_test_samples = 100" << std::endl;
file << "test_error_norm = h1_semi" << std::endl;
file.close();
} // ... write_config(...)
Thermalblock(const std::string id, const std::vector< std::string >& arguments, const bool visualize = true)
{
// mpi
int argc = arguments.size();
char** argv = Stuff::Common::String::vectorToMainArgs(arguments);
#if HAVE_DUNE_FEM
Fem::MPIManager::initialize(argc, argv);
#else
MPIHelper::instance(argc, argv);
#endif
// configuration
config_ = Stuff::Common::ConfigTree(argc, argv, id + ".cfg");
if (!config_.has_sub(id))
DUNE_THROW_COLORFULLY(Stuff::Exceptions::configuration_error,
"Missing sub '" << id << "' in the following ConfigTree:\n\n" << config_);
filename_ = config_.get(id + ".filename", id);
// logger
const Stuff::Common::ConfigTree& logger_config = config_.sub("logging");
int log_flags = Stuff::Common::LOG_CONSOLE;
debug_logging_ = logger_config.get< bool >("debug", false);
if (logger_config.get< bool >("info"))
log_flags = log_flags | Stuff::Common::LOG_INFO;
if (debug_logging_)
log_flags = log_flags | Stuff::Common::LOG_DEBUG;
if (logger_config.get< bool >("file", false))
log_flags = log_flags | Stuff::Common::LOG_FILE;
Stuff::Common::Logger().create(log_flags, id, "", "");
auto& info = Stuff::Common::Logger().info();
Timer timer;
info << "creating grid with '" << GridProviderType::static_id() << "'... " << std::flush;
grid_provider_ = GridProviderType::create(config_);
const auto grid_view = grid_provider_->leaf_view();
info << " done (took " << timer.elapsed()
<< "s, has " << grid_view->indexSet().size(0) << " element";
if (grid_view->indexSet().size(0) > 1)
info << "s";
info << ")" << std::endl;
boundary_info_ = Stuff::Common::ConfigTree("type", BoundaryInfoType::static_id());
info << "setting up ";
info << "'" << ProblemType::static_id() << "'... " << std::flush;
timer.reset();
problem_ = ProblemType::create(config_);
info << "done (took " << timer.elapsed() << "s)" << std::endl;
if (visualize) {
info << "visualizing grid and problem... " << std::flush;
timer.reset();
grid_provider_->visualize(boundary_info_, filename_ + ".grid");
problem_->visualize(*grid_view, filename_ + ".problem");
info << "done (took " << timer.elapsed() << "s)" << std::endl;
} // if (visualize)
} // Thermalblock
std::string filename() const
{
return filename_;
}
const Stuff::Common::ConfigTree& config() const
{
return config_;
}
bool debug_logging() const
{
return debug_logging_;
}
GridProviderType& grid_provider()
{
return *grid_provider_;
}
const GridProviderType& grid_provider() const
{
return *grid_provider_;
}
const Stuff::Common::ConfigTree& boundary_info() const
{
return boundary_info_;
}
const ProblemType& problem() const
{
return *problem_;
}
private:
std::string filename_;
Stuff::Common::ConfigTree config_;
bool debug_logging_;
std::unique_ptr< GridProviderType > grid_provider_;
Stuff::Common::ConfigTree boundary_info_;
std::unique_ptr< const ProblemType > problem_;
}; // class Thermalblock
} // namespace DiscreteProblems
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH
<|endoftext|>
|
<commit_before>#include <scitbx/array_family/boost_python/flex_fwd.h>
#include <scitbx/array_family/boost_python/flex_wrapper.h>
#include <scitbx/serialization/single_buffered.h>
#include <scitbx/matrix/transpose_multiply.h>
#include <scitbx/math/utils.h>
#include <scitbx/array_family/tiny_types.h>
#include <boost/python/make_constructor.hpp>
#include <boost/python/args.hpp>
#include <boost/python/return_arg.hpp>
#include <boost/format.hpp>
#include <scitbx/array_family/boost_python/flex_helpers.h>
namespace scitbx { namespace serialization { namespace single_buffered {
inline
char* to_string(char* start, scitbx::af::int6 const& value)
{
return
to_string(to_string(to_string(to_string(to_string(to_string(
start, value[0]), value[1]), value[2]), value[0]), value[1]), value[2]);
}
template <>
struct from_string<scitbx::af::int6>
{
from_string(const char* start)
{
end = start;
for(std::size_t i=0;i<6;i++) {
from_string<int> proxy(end);
value[i] = proxy.value;
end = proxy.end;
}
}
scitbx::af::int6 value;
const char* end;
};
}}} // namespace scitbx::serialization::single_buffered
#include <scitbx/array_family/boost_python/flex_pickle_single_buffered.h>
namespace scitbx { namespace af { namespace boost_python {
template <>
struct flex_default_element<scitbx::af::int6>
{
static scitbx::af::int6
get() { return scitbx::af::int6(0,0,0,0,0,0); }
};
}}}
namespace dials { namespace af {
namespace {
scitbx::af::flex<scitbx::af::int6>::type*
join(
scitbx::af::const_ref<int> const& a,
scitbx::af::const_ref<int> const& b,
scitbx::af::const_ref<int> const& c,
scitbx::af::const_ref<int> const& d,
scitbx::af::const_ref<int> const& e,
scitbx::af::const_ref<int> const& f)
{
SCITBX_ASSERT(a.size() == b.size());
SCITBX_ASSERT(a.size() == c.size());
SCITBX_ASSERT(a.size() == d.size());
SCITBX_ASSERT(a.size() == e.size());
SCITBX_ASSERT(a.size() == f.size());
scitbx::af::shared<scitbx::af::int6> result((scitbx::af::reserve(a.size())));
for(std::size_t i=0;i<a.size();i++) {
result.push_back(scitbx::af::int6(a[i],b[i],c[i],d[i],e[i],f[i]));
}
return new scitbx::af::flex<scitbx::af::int6>::type(result, result.size());
}
scitbx::af::flex<scitbx::af::int6>::type*
from_int(
scitbx::af::const_ref<int> const& x)
{
SCITBX_ASSERT(x.size() % 6 == 0);
std::size_t result_size = x.size() / 6;
scitbx::af::shared<scitbx::af::int6> result(result_size);
const int* d = x.begin();
for(std::size_t i=0;i<result_size;i++) {
for (std::size_t j=0;j<6;++j) {
result[i][j] = *d++;
}
}
return new scitbx::af::flex<scitbx::af::int6>::type(result, result.size());
}
scitbx::af::flex_int
as_int(scitbx::af::flex<scitbx::af::int6>::type const& a)
{
SCITBX_ASSERT(a.accessor().is_trivial_1d());
scitbx::af::flex_int result(a.size()*6, scitbx::af::init_functor_null<int>());
int* r = result.begin();
scitbx::af::const_ref<scitbx::af::int6> a_ref = a.const_ref().as_1d();
for(std::size_t i=0;i<a_ref.size();i++) {
for(std::size_t j=0;j<6;j++) {
*r++ = a_ref[i][j];
}
}
return result;
}
} // namespace <anonymous>
namespace boost_python {
void export_flex_int6()
{
using namespace boost::python;
using boost::python::arg;
typedef scitbx::af::boost_python::flex_wrapper<scitbx::af::int6> f_w;
f_w::plain("int6")
.def_pickle(scitbx::af::boost_python::flex_pickle_single_buffered<
scitbx::af::int6,
6*scitbx::af::boost_python::pickle_size_per_element<int>::value>())
.def("__init__", make_constructor(join))
.def("__init__", make_constructor(from_int))
.def("as_int", as_int);
;
}
}}} // namespace scitbx::af::boost_python
<commit_msg>Fixed bug in pickling<commit_after>#include <scitbx/array_family/boost_python/flex_fwd.h>
#include <scitbx/array_family/boost_python/flex_wrapper.h>
#include <scitbx/serialization/single_buffered.h>
#include <scitbx/matrix/transpose_multiply.h>
#include <scitbx/math/utils.h>
#include <scitbx/array_family/tiny_types.h>
#include <boost/python/make_constructor.hpp>
#include <boost/python/args.hpp>
#include <boost/python/return_arg.hpp>
#include <boost/format.hpp>
#include <scitbx/array_family/boost_python/flex_helpers.h>
namespace scitbx { namespace serialization { namespace single_buffered {
inline
char* to_string(char* start, scitbx::af::int6 const& value)
{
return
to_string(to_string(to_string(to_string(to_string(to_string(
start, value[0]), value[1]), value[2]), value[3]), value[4]), value[5]);
}
template <>
struct from_string<scitbx::af::int6>
{
from_string(const char* start)
{
end = start;
for(std::size_t i=0;i<6;i++) {
from_string<int> proxy(end);
value[i] = proxy.value;
end = proxy.end;
}
}
scitbx::af::int6 value;
const char* end;
};
}}} // namespace scitbx::serialization::single_buffered
#include <scitbx/array_family/boost_python/flex_pickle_single_buffered.h>
namespace scitbx { namespace af { namespace boost_python {
template <>
struct flex_default_element<scitbx::af::int6>
{
static scitbx::af::int6
get() { return scitbx::af::int6(0,0,0,0,0,0); }
};
}}}
namespace dials { namespace af {
namespace {
scitbx::af::flex<scitbx::af::int6>::type*
join(
scitbx::af::const_ref<int> const& a,
scitbx::af::const_ref<int> const& b,
scitbx::af::const_ref<int> const& c,
scitbx::af::const_ref<int> const& d,
scitbx::af::const_ref<int> const& e,
scitbx::af::const_ref<int> const& f)
{
SCITBX_ASSERT(a.size() == b.size());
SCITBX_ASSERT(a.size() == c.size());
SCITBX_ASSERT(a.size() == d.size());
SCITBX_ASSERT(a.size() == e.size());
SCITBX_ASSERT(a.size() == f.size());
scitbx::af::shared<scitbx::af::int6> result((scitbx::af::reserve(a.size())));
for(std::size_t i=0;i<a.size();i++) {
result.push_back(scitbx::af::int6(a[i],b[i],c[i],d[i],e[i],f[i]));
}
return new scitbx::af::flex<scitbx::af::int6>::type(result, result.size());
}
scitbx::af::flex<scitbx::af::int6>::type*
from_int(
scitbx::af::const_ref<int> const& x)
{
SCITBX_ASSERT(x.size() % 6 == 0);
std::size_t result_size = x.size() / 6;
scitbx::af::shared<scitbx::af::int6> result(result_size);
const int* d = x.begin();
for(std::size_t i=0;i<result_size;i++) {
for (std::size_t j=0;j<6;++j) {
result[i][j] = *d++;
}
}
return new scitbx::af::flex<scitbx::af::int6>::type(result, result.size());
}
scitbx::af::flex_int
as_int(scitbx::af::flex<scitbx::af::int6>::type const& a)
{
SCITBX_ASSERT(a.accessor().is_trivial_1d());
scitbx::af::flex_int result(a.size()*6, scitbx::af::init_functor_null<int>());
int* r = result.begin();
scitbx::af::const_ref<scitbx::af::int6> a_ref = a.const_ref().as_1d();
for(std::size_t i=0;i<a_ref.size();i++) {
for(std::size_t j=0;j<6;j++) {
*r++ = a_ref[i][j];
}
}
return result;
}
} // namespace <anonymous>
namespace boost_python {
void export_flex_int6()
{
using namespace boost::python;
using boost::python::arg;
typedef scitbx::af::boost_python::flex_wrapper<scitbx::af::int6> f_w;
f_w::plain("int6")
.def_pickle(scitbx::af::boost_python::flex_pickle_single_buffered<
scitbx::af::int6,
6*scitbx::af::boost_python::pickle_size_per_element<int>::value>())
.def("__init__", make_constructor(join))
.def("__init__", make_constructor(from_int))
.def("as_int", as_int);
;
}
}}} // namespace scitbx::af::boost_python
<|endoftext|>
|
<commit_before>#ifndef _COMMON_HPP_
#define _COMMON_HPP_
#include <map>
#include <string>
#include <vector>
// Simple tuple class for reading triples of data
class Tuple {
public:
Tuple(int x, int y, int z) : first(x), second(y), third(z) {}
int first;
int second;
int third;
};
// Python 2.x range() function. Returns the vector of elements
// (start, ..., end - 1).
std::vector<int> Range(int start, int end);
// Range starting from 0.
std::vector<int> Range(int end);
// Data sets
enum {
WIKI_VOTE=0,
EMAIL_EU,
WIKI_TALK,
SOC_EPINIONS,
SLASHDOT,
AS_CAIDA,
AMAZON,
TWITTER,
WIKI_RFA,
CIT_HEP_PH,
WEB_STANFORD,
EMAIL_ENRON,
DBLP,
};
const int kNumNetworks = 13;
// Algorithms
enum {
TENSOR, // Tensor Spectral Clustering (TSC)
DIRLAP, // Chung's directed Laplacian
LAP, // Laplacian with all edges considered undirected
CO_U, // Co-clustering (left singular vector)
CO_V, // Co-clustering (right singular vector)
D3C_ONLY_DIRLAP, // Directed laplacian, but only look at D3C subgraph
D3C_ONLY_RECIP_DIRLAP, // Directed laplacian, but only look at D3C
// + reciprocated edges subgraph
D3C_ONLY_NOBACK_DIRLAP, // Directed laplacian, but only look at D3C with
// no back edges subgraph
ASYMMETRIC_LAP, // Asymmetric laplacian
RANDOM, // Random order sweep cut
};
// Cut types
enum {
D3C_COND, // cut3(S) / min(vol3(S), vol3(Sbar))
D3C_COND_2NODE, // max(#(D3C cut w/ 2 nodes in S) / #(D3C w/ >= 2 nodes in S),
// #(D3C cut w/ 2 nodes in Sbar) / #(D3C w/ >= 2 nodes in Sbar))
D3C_EXPANSION, // cut3(S) / min(|S|, |Sbar|)
D3C_NORMALIZED, // cut3(S) (1 / vol3(S) + 1 / vol3(Sbar))
D3C_COND_RECIP, // D3C_COND, but count reciprocated edges
D3C_TOUCH, // cut3(S) / min(vol(V) - vol(S), vol(V) - vol(Sbar))
D3C_EXPANSION_RECIP, // D3C_EXPANSION, but count reciprocated edges
D3C_NOBACK_COND, // D3C_COND, but only look at D3Cs with no back edges
BIPARTITE, // Number of edges cut
NORMALIZED, // normalized cut (assume undirected)
COND, // conductance (assume undirected)
EXPANSION, // cut(S) / min(|S|, |Sbar|)
DENSITY, // Maximum density of S, Sbar
};
// Triple types
enum {
D3CS, // Directed 3-cycles
D3CS_RECIP, // Directed 3-cycles and reciprocated edges
D3CS_NOBACK, // Directed 3-cycles with no back edges
OPEN_TRIS, // Open triangles
};
// Given a network, return the text file name.
std::string NetworkStr(int network);
// Given an algorithm, return the name of the algorithm.
std::string AlgStr(int algorithm);
// Print information about the networks.
void PrintHelp();
#endif // _COMMON_HPP_
<commit_msg>clean up old code<commit_after>#ifndef _COMMON_HPP_
#define _COMMON_HPP_
#include <map>
#include <string>
#include <vector>
// Simple tuple class for reading triples of data
class Tuple {
public:
Tuple(int x, int y, int z) : first(x), second(y), third(z) {}
int first;
int second;
int third;
};
// Python 2.x range() function. Returns the vector of elements
// (start, ..., end - 1).
std::vector<int> Range(int start, int end);
// Range starting from 0.
std::vector<int> Range(int end);
// Data sets
enum {
WIKI_VOTE=0,
EMAIL_EU,
WIKI_TALK,
SOC_EPINIONS,
SLASHDOT,
AS_CAIDA,
AMAZON,
TWITTER,
WIKI_RFA,
CIT_HEP_PH,
WEB_STANFORD,
EMAIL_ENRON,
DBLP,
};
const int kNumNetworks = 13;
// Algorithms
enum {
TENSOR, // Tensor Spectral Clustering (TSC)
DIRLAP, // Chung's directed Laplacian
LAP, // Laplacian with all edges considered undirected
CO_U, // Co-clustering (left singular vector)
CO_V, // Co-clustering (right singular vector)
D3C_ONLY_DIRLAP, // Directed laplacian, but only look at D3C subgraph
D3C_ONLY_RECIP_DIRLAP, // Directed laplacian, but only look at D3C
// + reciprocated edges subgraph
D3C_ONLY_NOBACK_DIRLAP, // Directed laplacian, but only look at D3C with
// no back edges subgraph
ASYMMETRIC_LAP, // Asymmetric laplacian
RANDOM, // Random order sweep cut
};
// Cut types
enum {
D3C_COND, // cut3(S) / min(vol3(S), vol3(Sbar))
D3C_EXPANSION, // cut3(S) / min(|S|, |Sbar|)
D3C_NORMALIZED, // cut3(S) (1 / vol3(S) + 1 / vol3(Sbar))
D3C_COND_RECIP, // D3C_COND, but count reciprocated edges
D3C_EXPANSION_RECIP, // D3C_EXPANSION, but count reciprocated edges
D3C_NOBACK_COND, // D3C_COND, but only look at D3Cs with no back edges
BIPARTITE, // Number of edges cut
NORMALIZED, // normalized cut (assume undirected)
COND, // conductance (assume undirected)
EXPANSION, // cut(S) / min(|S|, |Sbar|)
DENSITY, // Maximum density of S, Sbar
};
// Triple types
enum {
D3CS, // Directed 3-cycles
D3CS_RECIP, // Directed 3-cycles and reciprocated edges
D3CS_NOBACK, // Directed 3-cycles with no back edges
OPEN_TRIS, // Open triangles
};
// Given a network, return the text file name.
std::string NetworkStr(int network);
// Given an algorithm, return the name of the algorithm.
std::string AlgStr(int algorithm);
// Print information about the networks.
void PrintHelp();
#endif // _COMMON_HPP_
<|endoftext|>
|
<commit_before>
#include <sstream>
#include <boost/foreach.hpp>
#include <H5Cpp.h>
#include "flame/h5writer.h"
#include "flame/h5loader.h"
// H5::Exception doesn't derive from std::exception
// so translate to some type which does.
// TODO: sub-class mixing H5::Exception and std::exception?
#define CATCH() catch(H5::Exception& he) { \
std::ostringstream strm; \
strm<<"H5 Error "<<he.getDetailMsg(); \
throw std::runtime_error(strm.str()); \
}
namespace {
struct StateElement {
unsigned idx;
StateBase::ArrayInfo info;
H5::DataSet dset;
std::vector<hsize_t> shape;
H5::DataSpace memspace;
};
}
struct H5StateWriter::Pvt {
H5::H5File file;
H5::Group group;
std::vector<StateElement> elements;
};
H5StateWriter::H5StateWriter() :pvt(new Pvt) {}
H5StateWriter::H5StateWriter(const char *spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::H5StateWriter(const std::string& spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::~H5StateWriter()
{
try{
close();
} catch(std::runtime_error& e) {
std::cerr<<"H5StateWriter is ignoring exception in dtor : "<<e.what()<<"\n";
}
delete pvt;
}
void H5StateWriter::open(const char *spec)
{
open(std::string(spec));
}
void H5StateWriter::open(const std::string& spec)
{
try {
close();
/* The provided spec may contain both file path and group(s)
* seperated by '/' which is ambigious as the file path
* may contain '/' as well...
* so do as h5ls does and strip off from the right hand side until
* and try to open while '/' remain.
*/
size_t sep = spec.npos;
while(true) {
sep = spec.find_last_of('/', sep-1);
std::string fname(spec.substr(0, sep));
try {
pvt->file.openFile(fname, H5F_ACC_RDWR|H5F_ACC_CREAT);
} catch(H5::FileIException& e) {
if(sep==spec.npos) {
// no more '/' so this is failure
throw std::runtime_error("Unable to open file");
}
continue; // keep trying
} CATCH()
if(sep!=spec.npos) {
std::string group(spec.substr(sep+1));
// delete group if it already exists
try{
H5G_stat_t stat;
pvt->file.getObjinfo(group, stat);
pvt->file.unlink(group);
} catch(H5::FileIException&) {
// ignore non-existant
}
pvt->group = pvt->file.createGroup(group);
} else {
//TODO: cleanup root?
pvt->group = pvt->file.openGroup("/");
}
return;
}
} CATCH()
}
void H5StateWriter::close()
{
try{
pvt->group.close();
pvt->file.close();
}CATCH()
}
void H5StateWriter::prepare(const StateBase *RS)
{
try {
// hack since getArray() is non-const
// we won't actually modify the state
StateBase *S = const_cast<StateBase*>(RS);
assert(pvt->elements.empty());
for(unsigned idx=0; true; idx++) {
StateBase::ArrayInfo info;
if(!S->getArray(idx, info))
break;
H5::DataType dtype;
switch(info.type) {
case StateBase::ArrayInfo::Double:
dtype = H5::DataType(H5::PredType::NATIVE_DOUBLE);
break;
case StateBase::ArrayInfo::Sizet:
if(sizeof(size_t)==8)
dtype = H5::DataType(H5::PredType::NATIVE_UINT64);
else if(sizeof(size_t)==4)
dtype = H5::DataType(H5::PredType::NATIVE_UINT32);
else
throw std::logic_error("unsupported size_t");
break;
default:
continue; // TODO string
}
StateElement elem;
elem.idx = idx;
elem.info = info;
// first dim is simulation "time"
std::vector<hsize_t> dims (info.ndim+1),
maxdims(info.ndim+1, H5S_UNLIMITED);
std::copy(info.dim,
info.dim+info.ndim,
dims.begin()+1);
elem.shape = dims; // copy
// size w/ first dim==0
dims[0] = 0;
H5::DataSpace dspace(dims.size(), &dims[0], &maxdims[0]);
dims[0] = 10; // chunk size in "time" steps
// other chunk sizes are multiple of initial size
H5::DSetCreatPropList props;
props.setChunk(dims.size(), &dims[0]);
// memspace is simple from origin to [1,shape]
dims[0] = 1;
elem.memspace = H5::DataSpace(dims.size(), &dims[0]);
elem.dset = pvt->group.createDataSet(info.name, dtype, dspace, props);
pvt->elements.push_back(elem);
}
if(pvt->elements.empty()) {
throw std::logic_error("state type has not elements to store?");
}
} CATCH()
}
void H5StateWriter::append(const StateBase *RS)
{
try {
StateBase *S = const_cast<StateBase*>(RS);
if(pvt->elements.empty())
prepare(RS);
BOOST_FOREACH(StateElement& elem, pvt->elements)
{
StateBase::ArrayInfo info;
if(!S->getArray(elem.idx, info))
throw std::logic_error("can't re-fetch state parameter?");
assert((elem.info.ndim==info.ndim) && (elem.info.type==info.type));
size_t index = elem.shape[0]; // we will write data[index,...]
elem.shape[0]++;
std::copy(info.dim,
info.dim+info.ndim,
elem.shape.begin()+1);
elem.dset.extend(&elem.shape[0]); // resize
// filespace is hyper from [index,0...] to [index,shape]
std::vector<hsize_t> start(elem.shape.size(), 0);
start[0] = index;
elem.shape[0] = 1; // reuse as count
H5::DataSpace filespace(elem.dset.getSpace());
filespace.selectHyperslab(H5S_SELECT_SET, &elem.shape[0], &start[0]);
H5::DataType dtype(elem.dset.getDataType());
elem.dset.write(info.ptr, dtype, elem.memspace, filespace);
elem.shape[0] = index+1;
}
} CATCH()
}
void H5StateWriter::setAttr(const char *name, const char *val)
{
try {
if(H5Aexists(pvt->group.getId(), name)>0)
//if(pvt->group.attrExists(name)) // H5Aexists was added in 1.8.0, c++ wrapper wasn't added until later...
{
pvt->group.removeAttr(name);
}
{
H5::DataSpace scalar;
H5::StrType dtype(H5::PredType::C_S1, std::max((size_t)16u, strlen(val)));
H5::Attribute attr(pvt->group.createAttribute(name, dtype, scalar));
attr.write(dtype, val);
}
} CATCH()
}
void H5StateWriter::dontPrint()
{
try {
H5::Exception::dontPrint();
}CATCH()
}
<commit_msg>h5writer handle resize<commit_after>
#include <sstream>
#include <boost/foreach.hpp>
#include <H5Cpp.h>
#include "flame/h5writer.h"
#include "flame/h5loader.h"
// H5::Exception doesn't derive from std::exception
// so translate to some type which does.
// TODO: sub-class mixing H5::Exception and std::exception?
#define CATCH() catch(H5::Exception& he) { \
std::ostringstream strm; \
strm<<"H5 Error "<<he.getDetailMsg(); \
throw std::runtime_error(strm.str()); \
}
namespace {
struct StateElement {
unsigned idx;
StateBase::ArrayInfo info;
H5::DataSet dset;
size_t nextrow;
StateElement() :nextrow(0u) {}
};
}
struct H5StateWriter::Pvt {
H5::H5File file;
H5::Group group;
std::vector<StateElement> elements;
};
H5StateWriter::H5StateWriter() :pvt(new Pvt) {}
H5StateWriter::H5StateWriter(const char *spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::H5StateWriter(const std::string& spec) :pvt(new Pvt)
{
open(spec);
}
H5StateWriter::~H5StateWriter()
{
try{
close();
} catch(std::runtime_error& e) {
std::cerr<<"H5StateWriter is ignoring exception in dtor : "<<e.what()<<"\n";
}
delete pvt;
}
void H5StateWriter::open(const char *spec)
{
open(std::string(spec));
}
void H5StateWriter::open(const std::string& spec)
{
try {
close();
/* The provided spec may contain both file path and group(s)
* seperated by '/' which is ambigious as the file path
* may contain '/' as well...
* so do as h5ls does and strip off from the right hand side until
* and try to open while '/' remain.
*/
size_t sep = spec.npos;
while(true) {
sep = spec.find_last_of('/', sep-1);
std::string fname(spec.substr(0, sep));
try {
pvt->file.openFile(fname, H5F_ACC_RDWR|H5F_ACC_CREAT);
} catch(H5::FileIException& e) {
if(sep==spec.npos) {
// no more '/' so this is failure
throw std::runtime_error("Unable to open file");
}
continue; // keep trying
} CATCH()
if(sep!=spec.npos) {
std::string group(spec.substr(sep+1));
// delete group if it already exists
try{
H5G_stat_t stat;
pvt->file.getObjinfo(group, stat);
pvt->file.unlink(group);
} catch(H5::FileIException&) {
// ignore non-existant
}
pvt->group = pvt->file.createGroup(group);
} else {
//TODO: cleanup root?
pvt->group = pvt->file.openGroup("/");
}
return;
}
} CATCH()
}
void H5StateWriter::close()
{
try{
pvt->group.close();
pvt->file.close();
}CATCH()
}
void H5StateWriter::prepare(const StateBase *RS)
{
try {
// hack since getArray() is non-const
// we won't actually modify the state
StateBase *S = const_cast<StateBase*>(RS);
assert(pvt->elements.empty());
for(unsigned idx=0; true; idx++) {
StateBase::ArrayInfo info;
if(!S->getArray(idx, info))
break;
H5::DataType dtype;
switch(info.type) {
case StateBase::ArrayInfo::Double:
dtype = H5::DataType(H5::PredType::NATIVE_DOUBLE);
break;
case StateBase::ArrayInfo::Sizet:
if(sizeof(size_t)==8)
dtype = H5::DataType(H5::PredType::NATIVE_UINT64);
else if(sizeof(size_t)==4)
dtype = H5::DataType(H5::PredType::NATIVE_UINT32);
else
throw std::logic_error("unsupported size_t");
break;
default:
continue; // TODO string
}
StateElement elem;
elem.idx = idx;
elem.info = info;
// first dim is simulation "time"
hsize_t dims[StateBase::ArrayInfo::maxdims+1],
maxdims[StateBase::ArrayInfo::maxdims+1];
std::fill(maxdims, maxdims+info.ndim+1, H5S_UNLIMITED);
std::copy(info.dim,
info.dim+info.ndim,
dims+1);
// size w/ first dim==0
dims[0] = 0;
H5::DataSpace dspace(info.ndim+1, &dims[0], &maxdims[0]);
dims[0] = 1024; // chunk size in "time" steps (arbitrary)
// other chunk sizes are multiple of initial size
H5::DSetCreatPropList props;
props.setChunk(info.ndim+1, &dims[0]);
// memspace is simple from origin to [1,shape]
dims[0] = 1;
elem.dset = pvt->group.createDataSet(info.name, dtype, dspace, props);
pvt->elements.push_back(elem);
}
if(pvt->elements.empty()) {
throw std::logic_error("state type has not elements to store?");
}
} CATCH()
}
void H5StateWriter::append(const StateBase *RS)
{
try {
StateBase *S = const_cast<StateBase*>(RS);
if(pvt->elements.empty())
prepare(RS);
BOOST_FOREACH(StateElement& elem, pvt->elements)
{
StateBase::ArrayInfo info;
if(!S->getArray(elem.idx, info))
throw std::logic_error("can't re-fetch state parameter?");
assert((elem.info.ndim==info.ndim) && (elem.info.type==info.type));
hsize_t shape[StateBase::ArrayInfo::maxdims+1];
shape[0] = ++elem.nextrow;
std::copy(info.dim,
info.dim+info.ndim,
shape+1);
// resize
// always in time, maybe in other dimensions
elem.dset.extend(shape);
// filespace is hyper from [index,0...] to [index,shape]
hsize_t start[StateBase::ArrayInfo::maxdims+1];
start[0] = shape[0]-1;
std::fill(start+1, start+info.ndim+1, 0);
shape[0] = 1; // reuse as count
H5::DataSpace memspace(info.ndim+1, shape);
H5::DataSpace filespace(elem.dset.getSpace());
filespace.selectHyperslab(H5S_SELECT_SET, shape, start);
H5::DataType dtype(elem.dset.getDataType());
elem.dset.write(info.ptr, dtype, memspace, filespace);
}
} CATCH()
}
void H5StateWriter::setAttr(const char *name, const char *val)
{
try {
if(H5Aexists(pvt->group.getId(), name)>0)
//if(pvt->group.attrExists(name)) // H5Aexists was added in 1.8.0, c++ wrapper wasn't added until later...
{
pvt->group.removeAttr(name);
}
{
H5::DataSpace scalar;
H5::StrType dtype(H5::PredType::C_S1, std::max((size_t)16u, strlen(val)));
H5::Attribute attr(pvt->group.createAttribute(name, dtype, scalar));
attr.write(dtype, val);
}
} CATCH()
}
void H5StateWriter::dontPrint()
{
try {
H5::Exception::dontPrint();
}CATCH()
}
<|endoftext|>
|
<commit_before>#include "get_stop_times.h"
#include "routing/best_stoptime.h"
#include "type/pb_converter.h"
namespace navitia { namespace timetables {
std::vector<datetime_stop_time> get_stop_times(const std::vector<type::idx_t> &journey_pattern_points, const DateTime &dt,
const DateTime &max_dt,
const size_t max_departures, const type::Data & data, bool disruption_active,
boost::optional<const std::string> calendar_id,
const type::AccessibiliteParams & accessibilite_params) {
std::vector<datetime_stop_time> result;
auto test_add = true;
// Prochain horaire où l’on demandera le prochain départ : on s’en sert pour ne pas obtenir plusieurs fois le même stop_time
// Initialement, c’est l’heure demandée
std::map<type::idx_t, DateTime> next_requested_datetime;
for(auto jpp_idx : journey_pattern_points){
next_requested_datetime[jpp_idx] = dt;
}
while(test_add && result.size() < max_departures) {
test_add = false;
for(auto jpp_idx : journey_pattern_points) {
const type::JourneyPatternPoint* jpp = data.pt_data.journey_pattern_points[jpp_idx];
if(!jpp->stop_point->accessible(accessibilite_params.properties)) {
continue;
}
auto st = routing::earliest_stop_time(jpp, next_requested_datetime[jpp_idx], data, disruption_active, false, calendar_id, accessibilite_params.vehicle_properties);
if(st.first != nullptr) {
DateTime dt_temp = st.second;
if(dt_temp <= max_dt && result.size() < max_departures) {
result.push_back(std::make_pair(dt_temp, st));
test_add = true;
// Le prochain horaire observé doit être au minimum une seconde après
if(st.first->is_frequency()) {
DateTimeUtils::update(dt_temp, st.first->end_time);
}
next_requested_datetime[jpp_idx] = dt_temp + 1;
}
}
}
}
std::sort(result.begin(), result.end(),[](datetime_stop_time dst1, datetime_stop_time dst2) {return dst1.first < dst2.first;});
return result;
}
}} // namespace navitia::timetables
<commit_msg>Buid fix on get_stop_times<commit_after>#include "get_stop_times.h"
#include "routing/best_stoptime.h"
#include "type/pb_converter.h"
namespace navitia { namespace timetables {
std::vector<datetime_stop_time> get_stop_times(const std::vector<type::idx_t> &journey_pattern_points, const DateTime &dt,
const DateTime &max_dt,
const size_t max_departures, const type::Data & data, bool disruption_active,
boost::optional<const std::string> calendar_id,
const type::AccessibiliteParams & accessibilite_params) {
std::vector<datetime_stop_time> result;
auto test_add = true;
// Prochain horaire où l’on demandera le prochain départ : on s’en sert pour ne pas obtenir plusieurs fois le même stop_time
// Initialement, c’est l’heure demandée
std::map<type::idx_t, DateTime> next_requested_datetime;
for(auto jpp_idx : journey_pattern_points){
next_requested_datetime[jpp_idx] = dt;
}
while(test_add && result.size() < max_departures) {
test_add = false;
for(auto jpp_idx : journey_pattern_points) {
const type::JourneyPatternPoint* jpp = data.pt_data.journey_pattern_points[jpp_idx];
if(!jpp->stop_point->accessible(accessibilite_params.properties)) {
continue;
}
auto st = routing::earliest_stop_time(jpp, next_requested_datetime[jpp_idx], data, disruption_active, false, calendar_id, accessibilite_params.vehicle_properties);
if(st.first != nullptr) {
DateTime dt_temp = st.second;
if(dt_temp <= max_dt && result.size() < max_departures) {
result.push_back(std::make_pair(dt_temp, st.first));
test_add = true;
// Le prochain horaire observé doit être au minimum une seconde après
if(st.first->is_frequency()) {
DateTimeUtils::update(dt_temp, st.first->end_time);
}
next_requested_datetime[jpp_idx] = dt_temp + 1;
}
}
}
}
std::sort(result.begin(), result.end(),[](datetime_stop_time dst1, datetime_stop_time dst2) {return dst1.first < dst2.first;});
return result;
}
}} // namespace navitia::timetables
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <cassert>
#include <cstdint>
#include <algorithm>
#include <ostream>
#include <iomanip>
#include <string>
namespace hex
{
/// @brief Small class which wraps a pointer and a size and
/// provides an output stream operator to print the content
/// as a hexdump.
///
/// The hexdump format consist of three columns per row of
/// bytes. The first column is the byte offset of the first byte
/// in the row, the second column is the byte values in hex of
/// those bytes (16 bytes per row) and the third column is the
/// ascii representation of those bytes.
///
/// Example of two rows (we removed the middle 6 bytes due to space
/// limitations):
///
/// @code
/// 0000 be 40 04 71 45 XXX cd 90 e5 51 31 .@.qE XXX ...Q1
/// 0010 9d 41 4f 37 05 XXX a9 d5 1e c7 93 .AO7. XXX .....
/// @endcode
struct dump
{
/// @param data The pointer to the data which we want to dump
/// @param max_size The maximum size in bytes of the data which we want
/// to dump.
dump(const uint8_t* data, uint32_t max_size) :
m_data(data),
m_max_size(max_size),
m_size(max_size)
{
assert(m_data);
assert(m_max_size);
assert(m_size);
}
/// @param size The size in bytes we wish to dump.
/// The actual number of bytes dumped will equal the smallest value of
/// either size or the max_size which was given as a parameter to
/// the this object's constructor.
void set_size(uint32_t size)
{
assert(m_size > 0);
m_size = size;
}
/// The pointer to the data that should be printed
const uint8_t* m_data;
/// The maximum number of bytes that can be printed
uint32_t m_max_size;
/// The number of bytes that the user wants to print
uint32_t m_size;
};
/// The actual output operator which prints the data buffer to
/// the choosen output stream.
///
/// @param out The output stream
///
/// @param hex The hexdump struct initialized with the data and size
/// that should be printed
///
/// @return the used output stream
inline std::ostream& operator<<(std::ostream& out, const dump& hex)
{
const uint8_t* data = hex.m_data;
uint32_t size = std::min(hex.m_size, hex.m_max_size);
assert(data);
assert(size > 0);
// don't change formatting for out
std::ostream s(out.rdbuf());
s << std::hex << std::setfill('0');
std::string buf;
buf.reserve(17); // premature optimization
for (uint32_t i = 0; i < size; ++i)
{
if ((i % 16) == 0)
{
if (i)
{
s << " " << buf << std::endl;
buf.clear();
}
s << std::setw(4) << i << ' ';
}
uint8_t c = data[i];
s << ' ' << std::setw(2) << (uint32_t) c;
buf += (0x20 <= c && c <= 0x7e) ? c : '.';
}
if (size % 16)
{
// If size if not a multiple of 16 there will be some empty
// columns in our print out. The remainder i.e. 16 - (size %
// 16) e.g. for some basic cases:
//
// size = 15
// remainder = 16 - (15 % 16) = 1
//
// size = 17
// remainder = 16 - (17 % 16) = 15
//
// and so forth.
uint32_t remainder = 16 - (size % 16);
// We add 3 space for each missing character in the output
s << std::string(3 * remainder, ' ');
}
s << " " << buf << std::endl;
if (size < hex.m_max_size && 16 < hex.m_max_size)
{
uint32_t last_row = (hex.m_max_size / 16) * 16;
s << "...." << std::endl;
s << std::setw(4) << last_row << std::endl;
}
return out;
}
}
<commit_msg>No indent for namespaces<commit_after>// Copyright (c) 2016 Steinwurf ApS
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#pragma once
#include <cassert>
#include <cstdint>
#include <algorithm>
#include <ostream>
#include <iomanip>
#include <string>
namespace hex
{
/// @brief Small class which wraps a pointer and a size and
/// provides an output stream operator to print the content
/// as a hexdump.
///
/// The hexdump format consist of three columns per row of
/// bytes. The first column is the byte offset of the first byte
/// in the row, the second column is the byte values in hex of
/// those bytes (16 bytes per row) and the third column is the
/// ascii representation of those bytes.
///
/// Example of two rows (we removed the middle 6 bytes due to space
/// limitations):
///
/// @code
/// 0000 be 40 04 71 45 XXX cd 90 e5 51 31 .@.qE XXX ...Q1
/// 0010 9d 41 4f 37 05 XXX a9 d5 1e c7 93 .AO7. XXX .....
/// @endcode
struct dump
{
/// @param data The pointer to the data which we want to dump
/// @param max_size The maximum size in bytes of the data which we want
/// to dump.
dump(const uint8_t* data, uint32_t max_size) :
m_data(data),
m_max_size(max_size),
m_size(max_size)
{
assert(m_data);
assert(m_max_size);
assert(m_size);
}
/// @param size The size in bytes we wish to dump.
/// The actual number of bytes dumped will equal the smallest value of
/// either size or the max_size which was given as a parameter to
/// the this object's constructor.
void set_size(uint32_t size)
{
assert(m_size > 0);
m_size = size;
}
/// The pointer to the data that should be printed
const uint8_t* m_data;
/// The maximum number of bytes that can be printed
uint32_t m_max_size;
/// The number of bytes that the user wants to print
uint32_t m_size;
};
/// The actual output operator which prints the data buffer to
/// the choosen output stream.
///
/// @param out The output stream
///
/// @param hex The hexdump struct initialized with the data and size
/// that should be printed
///
/// @return the used output stream
inline std::ostream& operator<<(std::ostream& out, const dump& hex)
{
const uint8_t* data = hex.m_data;
uint32_t size = std::min(hex.m_size, hex.m_max_size);
assert(data);
assert(size > 0);
// don't change formatting for out
std::ostream s(out.rdbuf());
s << std::hex << std::setfill('0');
std::string buf;
buf.reserve(17); // premature optimization
for (uint32_t i = 0; i < size; ++i)
{
if ((i % 16) == 0)
{
if (i)
{
s << " " << buf << std::endl;
buf.clear();
}
s << std::setw(4) << i << ' ';
}
uint8_t c = data[i];
s << ' ' << std::setw(2) << (uint32_t) c;
buf += (0x20 <= c && c <= 0x7e) ? c : '.';
}
if (size % 16)
{
// If size if not a multiple of 16 there will be some empty
// columns in our print out. The remainder i.e. 16 - (size %
// 16) e.g. for some basic cases:
//
// size = 15
// remainder = 16 - (15 % 16) = 1
//
// size = 17
// remainder = 16 - (17 % 16) = 15
//
// and so forth.
uint32_t remainder = 16 - (size % 16);
// We add 3 space for each missing character in the output
s << std::string(3 * remainder, ' ');
}
s << " " << buf << std::endl;
if (size < hex.m_max_size && 16 < hex.m_max_size)
{
uint32_t last_row = (hex.m_max_size / 16) * 16;
s << "...." << std::endl;
s << std::setw(4) << last_row << std::endl;
}
return out;
}
}
<|endoftext|>
|
<commit_before>//===- AliasAnalysis.cpp - Generic Alias Analysis Interface 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.
//
//===----------------------------------------------------------------------===//
//
// This file implements the generic AliasAnalysis interface which is used as the
// common interface used by all clients and implementations of alias analysis.
//
// This file also implements the default version of the AliasAnalysis interface
// that is to be used when no other implementation is specified. This does some
// simple tests that detect obvious cases: two different global pointers cannot
// alias, a global cannot alias a malloc, two different mallocs cannot alias,
// etc.
//
// This alias analysis implementation really isn't very good for anything, but
// it is very fast, and makes a nice clean default implementation. Because it
// handles lots of little corner cases, other, more complex, alias analysis
// implementations may choose to rely on this pass to resolve these simple and
// easy cases.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/BasicBlock.h"
#include "llvm/iMemory.h"
#include "llvm/Target/TargetData.h"
namespace llvm {
// Register the AliasAnalysis interface, providing a nice name to refer to.
namespace {
RegisterAnalysisGroup<AliasAnalysis> Z("Alias Analysis");
}
AliasAnalysis::ModRefResult
AliasAnalysis::getModRefInfo(LoadInst *L, Value *P, unsigned Size) {
return alias(L->getOperand(0), TD->getTypeSize(L->getType()),
P, Size) ? Ref : NoModRef;
}
AliasAnalysis::ModRefResult
AliasAnalysis::getModRefInfo(StoreInst *S, Value *P, unsigned Size) {
// If the stored address cannot alias the pointer in question, then the
// pointer cannot be modified by the store.
if (!alias(S->getOperand(1), TD->getTypeSize(S->getOperand(0)->getType()),
P, Size))
return NoModRef;
// If the pointer is a pointer to constant memory, then it could not have been
// modified by this store.
return pointsToConstantMemory(P) ? NoModRef : Mod;
}
// AliasAnalysis destructor: DO NOT move this to the header file for
// AliasAnalysis or else clients of the AliasAnalysis class may not depend on
// the AliasAnalysis.o file in the current .a file, causing alias analysis
// support to not be included in the tool correctly!
//
AliasAnalysis::~AliasAnalysis() {}
/// setTargetData - Subclasses must call this method to initialize the
/// AliasAnalysis interface before any other methods are called.
///
void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
TD = &P->getAnalysis<TargetData>();
}
// getAnalysisUsage - All alias analysis implementations should invoke this
// directly (using AliasAnalysis::getAnalysisUsage(AU)) to make sure that
// TargetData is required by the pass.
void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>(); // All AA's need TargetData.
}
/// canBasicBlockModify - Return true if it is possible for execution of the
/// specified basic block to modify the value pointed to by Ptr.
///
bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
const Value *Ptr, unsigned Size) {
return canInstructionRangeModify(BB.front(), BB.back(), Ptr, Size);
}
/// canInstructionRangeModify - Return true if it is possible for the execution
/// of the specified instructions to modify the value pointed to by Ptr. The
/// instructions to consider are all of the instructions in the range of [I1,I2]
/// INCLUSIVE. I1 and I2 must be in the same basic block.
///
bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
const Instruction &I2,
const Value *Ptr, unsigned Size) {
assert(I1.getParent() == I2.getParent() &&
"Instructions not in same basic block!");
BasicBlock::iterator I = const_cast<Instruction*>(&I1);
BasicBlock::iterator E = const_cast<Instruction*>(&I2);
++E; // Convert from inclusive to exclusive range.
for (; I != E; ++I) // Check every instruction in range
if (getModRefInfo(I, const_cast<Value*>(Ptr), Size) & Mod)
return true;
return false;
}
// Because of the way .a files work, we must force the BasicAA implementation to
// be pulled in if the AliasAnalysis classes are pulled in. Otherwise we run
// the risk of AliasAnalysis being used, but the default implementation not
// being linked into the tool that uses it.
//
extern void BasicAAStub();
static IncludeFile INCLUDE_BASICAA_CPP((void*)&BasicAAStub);
namespace {
struct NoAA : public ImmutablePass, public AliasAnalysis {
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
}
virtual void initializePass() {
InitializeAliasAnalysis(this);
}
};
// Register this pass...
RegisterOpt<NoAA>
X("no-aa", "No Alias Analysis (always returns 'may' alias)");
// Declare that we implement the AliasAnalysis interface
RegisterAnalysisGroup<AliasAnalysis, NoAA> Y;
} // End of anonymous namespace
} // End llvm namespace
<commit_msg>Deinline some virtual methods, provide better mod/ref answers through the use of the boolean queries<commit_after>//===- AliasAnalysis.cpp - Generic Alias Analysis Interface 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.
//
//===----------------------------------------------------------------------===//
//
// This file implements the generic AliasAnalysis interface which is used as the
// common interface used by all clients and implementations of alias analysis.
//
// This file also implements the default version of the AliasAnalysis interface
// that is to be used when no other implementation is specified. This does some
// simple tests that detect obvious cases: two different global pointers cannot
// alias, a global cannot alias a malloc, two different mallocs cannot alias,
// etc.
//
// This alias analysis implementation really isn't very good for anything, but
// it is very fast, and makes a nice clean default implementation. Because it
// handles lots of little corner cases, other, more complex, alias analysis
// implementations may choose to rely on this pass to resolve these simple and
// easy cases.
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/BasicBlock.h"
#include "llvm/iMemory.h"
#include "llvm/Target/TargetData.h"
using namespace llvm;
// Register the AliasAnalysis interface, providing a nice name to refer to.
namespace {
RegisterAnalysisGroup<AliasAnalysis> Z("Alias Analysis");
}
AliasAnalysis::ModRefResult
AliasAnalysis::getModRefInfo(LoadInst *L, Value *P, unsigned Size) {
return alias(L->getOperand(0), TD->getTypeSize(L->getType()),
P, Size) ? Ref : NoModRef;
}
AliasAnalysis::ModRefResult
AliasAnalysis::getModRefInfo(StoreInst *S, Value *P, unsigned Size) {
// If the stored address cannot alias the pointer in question, then the
// pointer cannot be modified by the store.
if (!alias(S->getOperand(1), TD->getTypeSize(S->getOperand(0)->getType()),
P, Size))
return NoModRef;
// If the pointer is a pointer to constant memory, then it could not have been
// modified by this store.
return pointsToConstantMemory(P) ? NoModRef : Mod;
}
AliasAnalysis::ModRefResult
AliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
if (Function *F = CS.getCalledFunction())
if (onlyReadsMemory(F)) {
if (doesNotAccessMemory(F)) return NoModRef;
return Ref;
}
// If P points to a constant memory location, the call definitely could not
// modify the memory location.
return pointsToConstantMemory(P) ? Ref : ModRef;
}
AliasAnalysis::ModRefResult
AliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
// FIXME: could probably do better.
return ModRef;
}
// AliasAnalysis destructor: DO NOT move this to the header file for
// AliasAnalysis or else clients of the AliasAnalysis class may not depend on
// the AliasAnalysis.o file in the current .a file, causing alias analysis
// support to not be included in the tool correctly!
//
AliasAnalysis::~AliasAnalysis() {}
/// setTargetData - Subclasses must call this method to initialize the
/// AliasAnalysis interface before any other methods are called.
///
void AliasAnalysis::InitializeAliasAnalysis(Pass *P) {
TD = &P->getAnalysis<TargetData>();
}
// getAnalysisUsage - All alias analysis implementations should invoke this
// directly (using AliasAnalysis::getAnalysisUsage(AU)) to make sure that
// TargetData is required by the pass.
void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<TargetData>(); // All AA's need TargetData.
}
/// canBasicBlockModify - Return true if it is possible for execution of the
/// specified basic block to modify the value pointed to by Ptr.
///
bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB,
const Value *Ptr, unsigned Size) {
return canInstructionRangeModify(BB.front(), BB.back(), Ptr, Size);
}
/// canInstructionRangeModify - Return true if it is possible for the execution
/// of the specified instructions to modify the value pointed to by Ptr. The
/// instructions to consider are all of the instructions in the range of [I1,I2]
/// INCLUSIVE. I1 and I2 must be in the same basic block.
///
bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1,
const Instruction &I2,
const Value *Ptr, unsigned Size) {
assert(I1.getParent() == I2.getParent() &&
"Instructions not in same basic block!");
BasicBlock::iterator I = const_cast<Instruction*>(&I1);
BasicBlock::iterator E = const_cast<Instruction*>(&I2);
++E; // Convert from inclusive to exclusive range.
for (; I != E; ++I) // Check every instruction in range
if (getModRefInfo(I, const_cast<Value*>(Ptr), Size) & Mod)
return true;
return false;
}
// Because of the way .a files work, we must force the BasicAA implementation to
// be pulled in if the AliasAnalysis classes are pulled in. Otherwise we run
// the risk of AliasAnalysis being used, but the default implementation not
// being linked into the tool that uses it.
//
extern void llvm::BasicAAStub();
static IncludeFile INCLUDE_BASICAA_CPP((void*)&BasicAAStub);
namespace {
struct NoAA : public ImmutablePass, public AliasAnalysis {
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AliasAnalysis::getAnalysisUsage(AU);
}
virtual void initializePass() {
InitializeAliasAnalysis(this);
}
};
// Register this pass...
RegisterOpt<NoAA>
X("no-aa", "No Alias Analysis (always returns 'may' alias)");
// Declare that we implement the AliasAnalysis interface
RegisterAnalysisGroup<AliasAnalysis, NoAA> Y;
} // End of anonymous namespace
<|endoftext|>
|
<commit_before><commit_msg>Bug fix for inline swift zoom sims<commit_after><|endoftext|>
|
<commit_before>// @(#)root/graf:$Id$
// Author: Rene Brun 108/08/2002
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TMath.h"
#include "TCrown.h"
#include "TVirtualPad.h"
ClassImp(TCrown)
//______________________________________________________________________________
/* Begin_Html
<center><h2>TCrown : to draw crown</h2></center>
A crown is specified with the position of its centre, its inner/outer radius
a minimum and maximum angle. The attributes of the outline line are given via
TAttLine. The attributes of the fill area are given via TAttFill.
<p> Example:
End_Html
Begin_Macro(source)
{
TCanvas *c1 = new TCanvas("c1","c1",400,400);
TCrown cr1(.5,.5,.3,.4);
cr1->SetLineStyle(2);
cr1->SetLineWidth(4);
cr1.Draw();
TCrown cr2(.5,.5,.2,.3,45,315);
cr2.SetFillColor(38);
cr2.SetFillStyle(3010);
cr2.Draw();
TCrown cr3(.5,.5,.2,.3,-45,45);
cr3.SetFillColor(50);
cr3.SetFillStyle(3025);
cr3.Draw();
TCrown cr4(.5,.5,.0,.2);
cr4.SetFillColor(4);
cr4.SetFillStyle(3008);
cr4.Draw();
return c1;
}
End_Macro */
//______________________________________________________________________________
TCrown::TCrown(): TEllipse()
{
/* Begin_Html
Crown default constructor.
End_Html */
}
//______________________________________________________________________________
TCrown::TCrown(Double_t x1, Double_t y1,Double_t radin, Double_t radout,Double_t phimin,Double_t phimax)
:TEllipse(x1,y1,radin,radout,phimin,phimax,0)
{
/* Begin_Html
Crown normal constructor.
<ul>
<li> x1,y1 : coordinates of centre of crown
<li> radin : inner crown radius
<li> radout : outer crown radius
<li> phimin : min angle in degrees (default is 0)
<li> phimax : max angle in degrees (default is 360)
</ul>
When a crown sector only is drawn, the lines connecting the center
of the crown to the edges are drawn by default. One can specify
the drawing option "only" to not draw these lines.
End_Html */
}
//______________________________________________________________________________
TCrown::TCrown(const TCrown &crown) : TEllipse(crown)
{
/* Begin_Html
Crown copy constructor.
End_Html */
((TCrown&)crown).Copy(*this);
}
//______________________________________________________________________________
TCrown::~TCrown()
{
/* Begin_Html
Crown default destructor.
End_Html */
}
//______________________________________________________________________________
void TCrown::Copy(TObject &crown) const
{
/* Begin_Html
Copy this crown to crown.
End_Html */
TEllipse::Copy(crown);
}
//______________________________________________________________________________
Int_t TCrown::DistancetoPrimitive(Int_t px, Int_t py)
{
/* Begin_Html
Compute distance from point px,py to a crown.
<p>
If crown is filled, return OK if we are inside
otherwise, crown is found if near the crown edges.
End_Html */
const Double_t kPI = TMath::Pi();
Double_t x = gPad->PadtoX(gPad->AbsPixeltoX(px)) - fX1;
Double_t y = gPad->PadtoY(gPad->AbsPixeltoY(py)) - fY1;
Double_t r1 = fR1;
Double_t r2 = fR2;
Double_t r = TMath::Sqrt(x*x+y*y);
if (r1>r2) {
r1 = fR2;
r2 = fR1;
}
Int_t dist = 9999;
if (r > r2) return dist;
if (r < r1) return dist;
if (fPhimax-fPhimin < 360) {
Double_t phi = 180*TMath::ACos(x/r)/kPI;
if (phi < fPhimin) return dist;
if (phi > fPhimax) return dist;
}
if (GetFillColor() && GetFillStyle()) {
return 0;
} else {
if (TMath::Abs(r2-r)/r2 < 0.02) return 0;
if (TMath::Abs(r1-r)/r1 < 0.02) return 0;
}
return dist;
}
//______________________________________________________________________________
void TCrown::DrawCrown(Double_t x1, Double_t y1,Double_t radin,Double_t radout,Double_t phimin,Double_t phimax,Option_t *option)
{
/* Begin_Html
Draw this crown with new coordinates.
End_Html */
TCrown *newcrown = new TCrown(x1, y1, radin, radout, phimin, phimax);
TAttLine::Copy(*newcrown);
TAttFill::Copy(*newcrown);
newcrown->SetBit(kCanDelete);
newcrown->AppendPad(option);
}
//______________________________________________________________________________
void TCrown::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
/* Begin_Html
Execute action corresponding to one event
<p>
For the time being TEllipse::ExecuteEvent is used.
End_Html */
TEllipse::ExecuteEvent(event,px,py);
}
//______________________________________________________________________________
void TCrown::Paint(Option_t *)
{
/* Begin_Html
Paint this crown with its current attributes.
End_Html */
const Double_t kPI = TMath::Pi();
const Int_t np = 40;
static Double_t x[2*np+3], y[2*np+3];
TAttLine::Modify();
TAttFill::Modify();
Double_t angle,dx,dy;
Double_t dphi = (fPhimax-fPhimin)*kPI/(180*np);
Double_t ct = TMath::Cos(kPI*fTheta/180);
Double_t st = TMath::Sin(kPI*fTheta/180);
Int_t i;
//compute outer points
for (i=0;i<=np;i++) {
angle = fPhimin*kPI/180 + Double_t(i)*dphi;
dx = fR2*TMath::Cos(angle);
dy = fR2*TMath::Sin(angle);
x[i] = fX1 + dx*ct - dy*st;
y[i] = fY1 + dx*st + dy*ct;
}
//compute inner points
for (i=0;i<=np;i++) {
angle = fPhimin*kPI/180 + Double_t(i)*dphi;
dx = fR1*TMath::Cos(angle);
dy = fR1*TMath::Sin(angle);
x[2*np-i+1] = fX1 + dx*ct - dy*st;
y[2*np-i+1] = fY1 + dx*st + dy*ct;
}
x[2*np+2] = x[0];
y[2*np+2] = y[0];
if (fPhimax-fPhimin >= 360 ) {
// a complete filled crown
if (GetFillColor() && GetFillStyle()) {
gPad->PaintFillArea(2*np+2,x,y);
}
// a complete empty crown
if (GetLineStyle()) {
gPad->PaintPolyLine(np+1,x,y);
gPad->PaintPolyLine(np+1,&x[np+1],&y[np+1]);
}
} else {
//crown segment
if (GetFillColor() && GetFillStyle()) gPad->PaintFillArea(2*np+2,x,y);
if (GetLineStyle()) gPad->PaintPolyLine(2*np+3,x,y);
}
}
//______________________________________________________________________________
void TCrown::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
/* Begin_Html
Save primitive as a C++ statement(s) on output stream out.
End_Html */
out<<" "<<endl;
if (gROOT->ClassSaved(TCrown::Class())) {
out<<" ";
} else {
out<<" TCrown *";
}
out<<"crown = new TCrown("<<fX1<<","<<fY1<<","<<fR1<<","<<fR2
<<","<<fPhimin<<","<<fPhimax<<");"<<endl;
SaveFillAttributes(out,"crown",0,1001);
SaveLineAttributes(out,"crown",1,1,1);
if (GetNoEdges()) out<<" crown->SetNoEdges();"<<endl;
out<<" crown->Draw();"<<endl;
}
<commit_msg>- DistancetoPrimitive needs more improvements (angles related).<commit_after>// @(#)root/graf:$Id$
// Author: Rene Brun 108/08/2002
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "Riostream.h"
#include "TROOT.h"
#include "TMath.h"
#include "TCrown.h"
#include "TVirtualPad.h"
ClassImp(TCrown)
//______________________________________________________________________________
/* Begin_Html
<center><h2>TCrown : to draw crown</h2></center>
A crown is specified with the position of its centre, its inner/outer radius
a minimum and maximum angle. The attributes of the outline line are given via
TAttLine. The attributes of the fill area are given via TAttFill.
<p> Example:
End_Html
Begin_Macro(source)
{
TCanvas *c1 = new TCanvas("c1","c1",400,400);
TCrown cr1(.5,.5,.3,.4);
cr1->SetLineStyle(2);
cr1->SetLineWidth(4);
cr1.Draw();
TCrown cr2(.5,.5,.2,.3,45,315);
cr2.SetFillColor(38);
cr2.SetFillStyle(3010);
cr2.Draw();
TCrown cr3(.5,.5,.2,.3,-45,45);
cr3.SetFillColor(50);
cr3.SetFillStyle(3025);
cr3.Draw();
TCrown cr4(.5,.5,.0,.2);
cr4.SetFillColor(4);
cr4.SetFillStyle(3008);
cr4.Draw();
return c1;
}
End_Macro */
//______________________________________________________________________________
TCrown::TCrown(): TEllipse()
{
/* Begin_Html
Crown default constructor.
End_Html */
}
//______________________________________________________________________________
TCrown::TCrown(Double_t x1, Double_t y1,Double_t radin, Double_t radout,Double_t phimin,Double_t phimax)
:TEllipse(x1,y1,radin,radout,phimin,phimax,0)
{
/* Begin_Html
Crown normal constructor.
<ul>
<li> x1,y1 : coordinates of centre of crown
<li> radin : inner crown radius
<li> radout : outer crown radius
<li> phimin : min angle in degrees (default is 0)
<li> phimax : max angle in degrees (default is 360)
</ul>
When a crown sector only is drawn, the lines connecting the center
of the crown to the edges are drawn by default. One can specify
the drawing option "only" to not draw these lines.
End_Html */
}
//______________________________________________________________________________
TCrown::TCrown(const TCrown &crown) : TEllipse(crown)
{
/* Begin_Html
Crown copy constructor.
End_Html */
((TCrown&)crown).Copy(*this);
}
//______________________________________________________________________________
TCrown::~TCrown()
{
/* Begin_Html
Crown default destructor.
End_Html */
}
//______________________________________________________________________________
void TCrown::Copy(TObject &crown) const
{
/* Begin_Html
Copy this crown to crown.
End_Html */
TEllipse::Copy(crown);
}
//______________________________________________________________________________
Int_t TCrown::DistancetoPrimitive(Int_t px, Int_t py)
{
/* Begin_Html
Compute distance from point px,py to a crown.
<p>
If crown is filled, return OK if we are inside
otherwise, crown is found if near the crown edges.
End_Html */
const Double_t kPI = TMath::Pi();
Double_t x = gPad->PadtoX(gPad->AbsPixeltoX(px)) - fX1;
Double_t y = gPad->PadtoY(gPad->AbsPixeltoY(py)) - fY1;
Double_t r1 = fR1;
Double_t r2 = fR2;
Double_t r = TMath::Sqrt(x*x+y*y);
if (r1>r2) {
r1 = fR2;
r2 = fR1;
}
Int_t dist = 9999;
if (r > r2) return dist;
if (r < r1) return dist;
if (fPhimax-fPhimin < 360) {
Double_t phi = 180*TMath::ACos(x/r)/kPI;
if (y<0) phi = 360-phi;
Double_t phi1 = fPhimin;
Double_t phi2 = fPhimax;
if (phi1<0) phi1=phi1+360;
if (phi2<0) phi2=phi2+360;
if (phi2<phi1) {
if (phi < phi1 && phi > phi2) return dist;
} else {
if (phi < phi1) return dist;
if (phi > phi2) return dist;
}
}
if (GetFillColor() && GetFillStyle()) {
return 0;
} else {
if (TMath::Abs(r2-r)/r2 < 0.02) return 0;
if (TMath::Abs(r1-r)/r1 < 0.02) return 0;
}
return dist;
}
//______________________________________________________________________________
void TCrown::DrawCrown(Double_t x1, Double_t y1,Double_t radin,Double_t radout,Double_t phimin,Double_t phimax,Option_t *option)
{
/* Begin_Html
Draw this crown with new coordinates.
End_Html */
TCrown *newcrown = new TCrown(x1, y1, radin, radout, phimin, phimax);
TAttLine::Copy(*newcrown);
TAttFill::Copy(*newcrown);
newcrown->SetBit(kCanDelete);
newcrown->AppendPad(option);
}
//______________________________________________________________________________
void TCrown::ExecuteEvent(Int_t event, Int_t px, Int_t py)
{
/* Begin_Html
Execute action corresponding to one event
<p>
For the time being TEllipse::ExecuteEvent is used.
End_Html */
TEllipse::ExecuteEvent(event,px,py);
}
//______________________________________________________________________________
void TCrown::Paint(Option_t *)
{
/* Begin_Html
Paint this crown with its current attributes.
End_Html */
const Double_t kPI = TMath::Pi();
const Int_t np = 40;
static Double_t x[2*np+3], y[2*np+3];
TAttLine::Modify();
TAttFill::Modify();
Double_t angle,dx,dy;
Double_t dphi = (fPhimax-fPhimin)*kPI/(180*np);
Double_t ct = TMath::Cos(kPI*fTheta/180);
Double_t st = TMath::Sin(kPI*fTheta/180);
Int_t i;
//compute outer points
for (i=0;i<=np;i++) {
angle = fPhimin*kPI/180 + Double_t(i)*dphi;
dx = fR2*TMath::Cos(angle);
dy = fR2*TMath::Sin(angle);
x[i] = fX1 + dx*ct - dy*st;
y[i] = fY1 + dx*st + dy*ct;
}
//compute inner points
for (i=0;i<=np;i++) {
angle = fPhimin*kPI/180 + Double_t(i)*dphi;
dx = fR1*TMath::Cos(angle);
dy = fR1*TMath::Sin(angle);
x[2*np-i+1] = fX1 + dx*ct - dy*st;
y[2*np-i+1] = fY1 + dx*st + dy*ct;
}
x[2*np+2] = x[0];
y[2*np+2] = y[0];
if (fPhimax-fPhimin >= 360 ) {
// a complete filled crown
if (GetFillColor() && GetFillStyle()) {
gPad->PaintFillArea(2*np+2,x,y);
}
// a complete empty crown
if (GetLineStyle()) {
gPad->PaintPolyLine(np+1,x,y);
gPad->PaintPolyLine(np+1,&x[np+1],&y[np+1]);
}
} else {
//crown segment
if (GetFillColor() && GetFillStyle()) gPad->PaintFillArea(2*np+2,x,y);
if (GetLineStyle()) gPad->PaintPolyLine(2*np+3,x,y);
}
}
//______________________________________________________________________________
void TCrown::SavePrimitive(ostream &out, Option_t * /*= ""*/)
{
/* Begin_Html
Save primitive as a C++ statement(s) on output stream out.
End_Html */
out<<" "<<endl;
if (gROOT->ClassSaved(TCrown::Class())) {
out<<" ";
} else {
out<<" TCrown *";
}
out<<"crown = new TCrown("<<fX1<<","<<fY1<<","<<fR1<<","<<fR2
<<","<<fPhimin<<","<<fPhimax<<");"<<endl;
SaveFillAttributes(out,"crown",0,1001);
SaveLineAttributes(out,"crown",1,1,1);
if (GetNoEdges()) out<<" crown->SetNoEdges();"<<endl;
out<<" crown->Draw();"<<endl;
}
<|endoftext|>
|
<commit_before><commit_msg>store_test: fix warning<commit_after><|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCellPicker.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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 "vtkCellPicker.h"
#include "vtkObjectFactory.h"
#include "vtkVolumeMapper.h"
//----------------------------------------------------------------------------
vtkCellPicker* vtkCellPicker::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCellPicker");
if(ret)
{
return (vtkCellPicker*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCellPicker;
}
vtkCellPicker::vtkCellPicker()
{
this->CellId = -1;
this->SubId = -1;
for (int i=0; i<3; i++)
{
this->PCoords[i] = 0.0;
}
this->Cell = vtkGenericCell::New();
}
vtkCellPicker::~vtkCellPicker()
{
this->Cell->Delete();
}
float vtkCellPicker::IntersectWithLine(float p1[3], float p2[3], float tol,
vtkAssemblyPath *path,
vtkProp3D *prop3D,
vtkAbstractMapper3D *m)
{
int numCells;
int cellId, i, minCellId, minSubId, subId;
float x[3], tMin, t, pcoords[3], minXYZ[3], minPcoords[3];
vtkDataSet *input;
vtkMapper *mapper;
vtkVolumeMapper *volumeMapper;
// Get the underlying dataset
if ( (mapper=vtkMapper::SafeDownCast(m)) != NULL )
{
input = mapper->GetInput();
}
else if ( (volumeMapper=vtkVolumeMapper::SafeDownCast(m)) != NULL )
{
input = volumeMapper->GetInput();
}
else
{
return VTK_LARGE_FLOAT;
}
if ( (numCells = input->GetNumberOfCells()) < 1 )
{
return 2.0;
}
// Intersect each cell with ray. Keep track of one closest to
// the eye (and within the clipping range).
//
minCellId = -1;
minSubId = -1;
for (tMin=VTK_LARGE_FLOAT,cellId=0; cellId<numCells; cellId++)
{
input->GetCell(cellId,this->Cell);
if ( this->Cell->IntersectWithLine(p1, p2, tol, t, x, pcoords, subId)
&& t < tMin )
{
minCellId = cellId;
minSubId = subId;
for (i=0; i<3; i++)
{
minXYZ[i] = x[i];
minPcoords[i] = pcoords[i];
}
tMin = t;
}
}
// Now compare this against other actors.
//
if ( minCellId>(-1) && tMin < this->GlobalTMin )
{
this->MarkPicked(path, prop3D, m, tMin, minXYZ);
this->CellId = minCellId;
this->SubId = minSubId;
for (i=0; i<3; i++)
{
this->PCoords[i] = minPcoords[i];
}
vtkDebugMacro("Picked cell id= " << minCellId);
}
return tMin;
}
void vtkCellPicker::Initialize()
{
this->CellId = (-1);
this->SubId = (-1);
for (int i=0; i<3; i++)
{
this->PCoords[i] = 0.0;
}
this->vtkPicker::Initialize();
}
void vtkCellPicker::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkPicker::PrintSelf(os,indent);
os << indent << "Cell Id: " << this->CellId << "\n";
os << indent << "SubId: " << this->SubId << "\n";
os << indent << "PCoords: (" << this->PCoords[0] << ", "
<< this->PCoords[1] << ", " << this->PCoords[2] << ")\n";
}
<commit_msg>ENH:Removing Purify UMC's<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkCellPicker.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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 "vtkCellPicker.h"
#include "vtkObjectFactory.h"
#include "vtkVolumeMapper.h"
//----------------------------------------------------------------------------
vtkCellPicker* vtkCellPicker::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkCellPicker");
if(ret)
{
return (vtkCellPicker*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkCellPicker;
}
vtkCellPicker::vtkCellPicker()
{
this->CellId = -1;
this->SubId = -1;
for (int i=0; i<3; i++)
{
this->PCoords[i] = 0.0;
}
this->Cell = vtkGenericCell::New();
}
vtkCellPicker::~vtkCellPicker()
{
this->Cell->Delete();
}
float vtkCellPicker::IntersectWithLine(float p1[3], float p2[3], float tol,
vtkAssemblyPath *path,
vtkProp3D *prop3D,
vtkAbstractMapper3D *m)
{
int numCells;
int cellId, i, minCellId, minSubId, subId;
float x[3], tMin, t, pcoords[3], minXYZ[3], minPcoords[3];
vtkDataSet *input;
vtkMapper *mapper;
vtkVolumeMapper *volumeMapper;
// Get the underlying dataset
if ( (mapper=vtkMapper::SafeDownCast(m)) != NULL )
{
input = mapper->GetInput();
}
else if ( (volumeMapper=vtkVolumeMapper::SafeDownCast(m)) != NULL )
{
input = volumeMapper->GetInput();
}
else
{
return VTK_LARGE_FLOAT;
}
if ( (numCells = input->GetNumberOfCells()) < 1 )
{
return 2.0;
}
// Intersect each cell with ray. Keep track of one closest to
// the eye (and within the clipping range).
//
minCellId = -1;
minSubId = -1;
minPcoords[0] = minPcoords[1] = minPcoords[2] = 0.0;
for (tMin=VTK_LARGE_FLOAT,cellId=0; cellId<numCells; cellId++)
{
input->GetCell(cellId,this->Cell);
if ( this->Cell->IntersectWithLine(p1, p2, tol, t, x, pcoords, subId)
&& t < tMin )
{
minCellId = cellId;
minSubId = subId;
for (i=0; i<3; i++)
{
minXYZ[i] = x[i];
minPcoords[i] = pcoords[i];
}
tMin = t;
}
}
// Now compare this against other actors.
//
if ( minCellId>(-1) && tMin < this->GlobalTMin )
{
this->MarkPicked(path, prop3D, m, tMin, minXYZ);
this->CellId = minCellId;
this->SubId = minSubId;
for (i=0; i<3; i++)
{
this->PCoords[i] = minPcoords[i];
}
vtkDebugMacro("Picked cell id= " << minCellId);
}
return tMin;
}
void vtkCellPicker::Initialize()
{
this->CellId = (-1);
this->SubId = (-1);
for (int i=0; i<3; i++)
{
this->PCoords[i] = 0.0;
}
this->vtkPicker::Initialize();
}
void vtkCellPicker::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkPicker::PrintSelf(os,indent);
os << indent << "Cell Id: " << this->CellId << "\n";
os << indent << "SubId: " << this->SubId << "\n";
os << indent << "PCoords: (" << this->PCoords[0] << ", "
<< this->PCoords[1] << ", " << this->PCoords[2] << ")\n";
}
<|endoftext|>
|
<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <jefft0@remap.ucla.edu>
* See COPYING for copyright and distribution information.
*/
#ifndef NDN_DATA_HPP
#define NDN_DATA_HPP
#include "common.hpp"
#include "name.hpp"
#include "util/signed-blob.hpp"
#include "c/data-types.h"
#include "encoding/wire-format.hpp"
struct ndn_MetaInfo;
struct ndn_Signature;
struct ndn_Data;
namespace ndn {
/**
* A Signature is an abstract base class providing methods to work with the signature information in a Data packet.
* You must create an object of a subclass, for example Sha256WithRsaSignature.
*/
class Signature {
public:
/**
* Return a pointer to a new Signature which is a copy of this signature.
* This is pure virtual, the subclass must implement it.
*/
virtual ptr_lib::shared_ptr<Signature>
clone() const = 0;
/**
* The virtual destructor.
*/
virtual
~Signature();
/**
* Set the signatureStruct to point to the values in this signature object, without copying any memory.
* WARNING: The resulting pointers in signatureStruct are invalid after a further use of this object which could reallocate memory.
* This is pure virtual, the subclass must implement it.
* @param signatureStruct a C ndn_Signature struct where the name components array is already allocated.
*/
virtual void
get(struct ndn_Signature& signatureStruct) const = 0;
/**
* Clear this signature, and set the values by copying from the ndn_Signature struct.
* This is pure virtual, the subclass must implement it.
* @param signatureStruct a C ndn_Signature struct
*/
virtual void
set(const struct ndn_Signature& signatureStruct) = 0;
};
/**
* An MetaInfo holds the meta info which is signed inside the data packet.
*/
class MetaInfo {
public:
MetaInfo()
{
type_ = ndn_ContentType_DATA;
freshnessSeconds_ = -1;
}
/**
* Set the metaInfoStruct to point to the values in this meta info object, without copying any memory.
* WARNING: The resulting pointers in metaInfoStruct are invalid after a further use of this object which could reallocate memory.
* @param metaInfoStruct a C ndn_MetaInfo struct where the name components array is already allocated.
*/
void
get(struct ndn_MetaInfo& metaInfoStruct) const;
/**
* Clear this meta info, and set the values by copying from the ndn_MetaInfo struct.
* @param metaInfoStruct a C ndn_MetaInfo struct
*/
void
set(const struct ndn_MetaInfo& metaInfoStruct);
MillisecondsSince1970
getTimestampMilliseconds() const { return timestampMilliseconds_; }
ndn_ContentType
getType() const { return type_; }
int
getFreshnessSeconds() const { return freshnessSeconds_; }
const Name::Component&
getFinalBlockID() const { return finalBlockID_; }
void
setTimestampMilliseconds(MillisecondsSince1970 timestampMilliseconds) { timestampMilliseconds_ = timestampMilliseconds; }
void
setType(ndn_ContentType type) { type_ = type; }
void
setFreshnessSeconds(int freshnessSeconds) { freshnessSeconds_ = freshnessSeconds; }
void
setFinalBlockID(const Blob& finalBlockID) { finalBlockID_ = Name::Component(finalBlockID); }
void
setFinalBlockID(const std::vector<uint8_t>& finalBlockID) { finalBlockID_ = Name::Component(finalBlockID); }
void
setFinalBlockID(const uint8_t* finalBlockID, size_t finalBlockIdLength)
{
finalBlockID_ = Name::Component(finalBlockID, finalBlockIdLength);
}
private:
MillisecondsSince1970 timestampMilliseconds_; /**< milliseconds since 1/1/1970. -1 for none */
ndn_ContentType type_; /**< default is ndn_ContentType_DATA. -1 for none */
int freshnessSeconds_; /**< -1 for none */
Name::Component finalBlockID_; /** size 0 for none */
};
class Data {
public:
/**
* Create a new Data object with default values and where the signature is a blank Sha256WithRsaSignature.
*/
Data();
/**
* Create a new Data object with the given name and default values and where the signature is a blank Sha256WithRsaSignature.
* @param name A reference to the name which is copied.
*/
Data(const Name& name);
/**
* The copy constructor: Create a deep copy of the given data object, including a clone of the signature object.
* @param data The data object to copy.
*/
Data(const Data& data);
/**
* The virtual destructor.
*/
virtual ~Data();
/**
* The assignment operator: Copy fields and make a clone of the signature.
* @param data The other object to copy from.
* @return A reference to this object.
*/
Data& operator=(const Data& data);
/**
* Encode this Data for a particular wire format. If wireFormat is the default wire format, also set the defaultWireEncoding
* field to the encoded result.
* Even though this is const, if wireFormat is the default wire format we update the defaultWireEncoding.
* @param wireFormat A WireFormat object used to encode the input. If omitted, use WireFormat getDefaultWireFormat().
* @return The encoded byte array.
*/
SignedBlob
wireEncode(WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()) const;
/**
* Decode the input using a particular wire format and update this Data. If wireFormat is the default wire format, also
* set the defaultWireEncoding field to the input.
* @param input The input byte array to be decoded.
* @param inputLength The length of input.
* @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat().
*/
void
wireDecode(const uint8_t* input, size_t inputLength, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat());
/**
* Decode the input using a particular wire format and update this Data. If wireFormat is the default wire format, also
* set the defaultWireEncoding field to the input.
* @param input The input byte array to be decoded.
* @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat().
*/
void
wireDecode(const std::vector<uint8_t>& input, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat())
{
wireDecode(&input[0], input.size(), wireFormat);
}
/**
* Set the dataStruct to point to the values in this interest, without copying any memory.
* WARNING: The resulting pointers in dataStruct are invalid after a further use of this object which could reallocate memory.
* @param dataStruct a C ndn_Data struct where the name components array is already allocated.
*/
void
get(struct ndn_Data& dataStruct) const;
/**
* Clear this data object, and set the values by copying from the ndn_Data struct.
* @param dataStruct a C ndn_Data struct
*/
void
set(const struct ndn_Data& dataStruct);
const Signature*
getSignature() const { return signature_.get(); }
Signature*
getSignature()
{
// TODO: Should add an OnChanged listener instead of always calling onChanged.
onChanged();
return signature_.get();
}
const Name&
getName() const { return name_; }
Name&
getName()
{
// TODO: Should add an OnChanged listener instead of always calling onChanged.
onChanged();
return name_;
}
const MetaInfo&
getMetaInfo() const { return metaInfo_; }
MetaInfo&
getMetaInfo()
{
// TODO: Should add an OnChanged listener instead of always calling onChanged.
onChanged();
return metaInfo_;
}
const Blob&
getContent() const { return content_; }
/**
* Return a pointer to the defaultWireEncoding. It may be null.
*/
const SignedBlob&
getDefaultWireEncoding() const { return defaultWireEncoding_; }
/**
* Set the signature to a copy of the given signature.
* @param signature The signature object which is cloned.
* @return This Data so that you can chain calls to update values.
*/
Data&
setSignature(const Signature& signature)
{
signature_ = signature.clone();
onChanged();
return *this;
}
/**
* Set name to a copy of the given Name. This is virtual so that a subclass can override to validate the name.
* @param name The Name which is copied.
* @return This Data so that you can chain calls to update values.
*/
virtual Data&
setName(const Name& name);
/**
* Set metaInfo to a copy of the given MetaInfo.
* @param metaInfo The MetaInfo which is copied.
* @return This Data so that you can chain calls to update values.
*/
Data&
setMetainfo(const MetaInfo& metaInfo)
{
metaInfo_ = metaInfo;
onChanged();
return *this;
}
/**
* Set the content to a copy of the data in the vector.
* @param content A vector whose contents are copied.
* @return This Data so that you can chain calls to update values.
*/
Data&
setContent(const std::vector<uint8_t>& content)
{
content_ = content;
onChanged();
return *this;
}
Data&
setContent(const uint8_t* content, size_t contentLength)
{
content_ = Blob(content, contentLength);
onChanged();
return *this;
}
Data&
setContent(const Blob& content)
{
content_ = content;
onChanged();
return *this;
}
private:
/**
* Clear the wire encoding.
*/
void
onChanged();
ptr_lib::shared_ptr<Signature> signature_;
Name name_;
MetaInfo metaInfo_;
Blob content_;
SignedBlob defaultWireEncoding_;
};
}
#endif
<commit_msg>MetaInfo: Added setFinalBlockID for Name::Component.<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
* Copyright (C) 2013 Regents of the University of California.
* @author: Jeff Thompson <jefft0@remap.ucla.edu>
* See COPYING for copyright and distribution information.
*/
#ifndef NDN_DATA_HPP
#define NDN_DATA_HPP
#include "common.hpp"
#include "name.hpp"
#include "util/signed-blob.hpp"
#include "c/data-types.h"
#include "encoding/wire-format.hpp"
struct ndn_MetaInfo;
struct ndn_Signature;
struct ndn_Data;
namespace ndn {
/**
* A Signature is an abstract base class providing methods to work with the signature information in a Data packet.
* You must create an object of a subclass, for example Sha256WithRsaSignature.
*/
class Signature {
public:
/**
* Return a pointer to a new Signature which is a copy of this signature.
* This is pure virtual, the subclass must implement it.
*/
virtual ptr_lib::shared_ptr<Signature>
clone() const = 0;
/**
* The virtual destructor.
*/
virtual
~Signature();
/**
* Set the signatureStruct to point to the values in this signature object, without copying any memory.
* WARNING: The resulting pointers in signatureStruct are invalid after a further use of this object which could reallocate memory.
* This is pure virtual, the subclass must implement it.
* @param signatureStruct a C ndn_Signature struct where the name components array is already allocated.
*/
virtual void
get(struct ndn_Signature& signatureStruct) const = 0;
/**
* Clear this signature, and set the values by copying from the ndn_Signature struct.
* This is pure virtual, the subclass must implement it.
* @param signatureStruct a C ndn_Signature struct
*/
virtual void
set(const struct ndn_Signature& signatureStruct) = 0;
};
/**
* An MetaInfo holds the meta info which is signed inside the data packet.
*/
class MetaInfo {
public:
MetaInfo()
{
type_ = ndn_ContentType_DATA;
freshnessSeconds_ = -1;
}
/**
* Set the metaInfoStruct to point to the values in this meta info object, without copying any memory.
* WARNING: The resulting pointers in metaInfoStruct are invalid after a further use of this object which could reallocate memory.
* @param metaInfoStruct a C ndn_MetaInfo struct where the name components array is already allocated.
*/
void
get(struct ndn_MetaInfo& metaInfoStruct) const;
/**
* Clear this meta info, and set the values by copying from the ndn_MetaInfo struct.
* @param metaInfoStruct a C ndn_MetaInfo struct
*/
void
set(const struct ndn_MetaInfo& metaInfoStruct);
MillisecondsSince1970
getTimestampMilliseconds() const { return timestampMilliseconds_; }
ndn_ContentType
getType() const { return type_; }
int
getFreshnessSeconds() const { return freshnessSeconds_; }
const Name::Component&
getFinalBlockID() const { return finalBlockID_; }
void
setTimestampMilliseconds(MillisecondsSince1970 timestampMilliseconds) { timestampMilliseconds_ = timestampMilliseconds; }
void
setType(ndn_ContentType type) { type_ = type; }
void
setFreshnessSeconds(int freshnessSeconds) { freshnessSeconds_ = freshnessSeconds; }
void
setFinalBlockID(const Name::Component& finalBlockID) { finalBlockID_ = finalBlockID; }
void
setFinalBlockID(const Blob& finalBlockID) { finalBlockID_ = Name::Component(finalBlockID); }
void
setFinalBlockID(const std::vector<uint8_t>& finalBlockID) { finalBlockID_ = Name::Component(finalBlockID); }
void
setFinalBlockID(const uint8_t* finalBlockID, size_t finalBlockIdLength)
{
finalBlockID_ = Name::Component(finalBlockID, finalBlockIdLength);
}
private:
MillisecondsSince1970 timestampMilliseconds_; /**< milliseconds since 1/1/1970. -1 for none */
ndn_ContentType type_; /**< default is ndn_ContentType_DATA. -1 for none */
int freshnessSeconds_; /**< -1 for none */
Name::Component finalBlockID_; /** size 0 for none */
};
class Data {
public:
/**
* Create a new Data object with default values and where the signature is a blank Sha256WithRsaSignature.
*/
Data();
/**
* Create a new Data object with the given name and default values and where the signature is a blank Sha256WithRsaSignature.
* @param name A reference to the name which is copied.
*/
Data(const Name& name);
/**
* The copy constructor: Create a deep copy of the given data object, including a clone of the signature object.
* @param data The data object to copy.
*/
Data(const Data& data);
/**
* The virtual destructor.
*/
virtual ~Data();
/**
* The assignment operator: Copy fields and make a clone of the signature.
* @param data The other object to copy from.
* @return A reference to this object.
*/
Data& operator=(const Data& data);
/**
* Encode this Data for a particular wire format. If wireFormat is the default wire format, also set the defaultWireEncoding
* field to the encoded result.
* Even though this is const, if wireFormat is the default wire format we update the defaultWireEncoding.
* @param wireFormat A WireFormat object used to encode the input. If omitted, use WireFormat getDefaultWireFormat().
* @return The encoded byte array.
*/
SignedBlob
wireEncode(WireFormat& wireFormat = *WireFormat::getDefaultWireFormat()) const;
/**
* Decode the input using a particular wire format and update this Data. If wireFormat is the default wire format, also
* set the defaultWireEncoding field to the input.
* @param input The input byte array to be decoded.
* @param inputLength The length of input.
* @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat().
*/
void
wireDecode(const uint8_t* input, size_t inputLength, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat());
/**
* Decode the input using a particular wire format and update this Data. If wireFormat is the default wire format, also
* set the defaultWireEncoding field to the input.
* @param input The input byte array to be decoded.
* @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat().
*/
void
wireDecode(const std::vector<uint8_t>& input, WireFormat& wireFormat = *WireFormat::getDefaultWireFormat())
{
wireDecode(&input[0], input.size(), wireFormat);
}
/**
* Set the dataStruct to point to the values in this interest, without copying any memory.
* WARNING: The resulting pointers in dataStruct are invalid after a further use of this object which could reallocate memory.
* @param dataStruct a C ndn_Data struct where the name components array is already allocated.
*/
void
get(struct ndn_Data& dataStruct) const;
/**
* Clear this data object, and set the values by copying from the ndn_Data struct.
* @param dataStruct a C ndn_Data struct
*/
void
set(const struct ndn_Data& dataStruct);
const Signature*
getSignature() const { return signature_.get(); }
Signature*
getSignature()
{
// TODO: Should add an OnChanged listener instead of always calling onChanged.
onChanged();
return signature_.get();
}
const Name&
getName() const { return name_; }
Name&
getName()
{
// TODO: Should add an OnChanged listener instead of always calling onChanged.
onChanged();
return name_;
}
const MetaInfo&
getMetaInfo() const { return metaInfo_; }
MetaInfo&
getMetaInfo()
{
// TODO: Should add an OnChanged listener instead of always calling onChanged.
onChanged();
return metaInfo_;
}
const Blob&
getContent() const { return content_; }
/**
* Return a pointer to the defaultWireEncoding. It may be null.
*/
const SignedBlob&
getDefaultWireEncoding() const { return defaultWireEncoding_; }
/**
* Set the signature to a copy of the given signature.
* @param signature The signature object which is cloned.
* @return This Data so that you can chain calls to update values.
*/
Data&
setSignature(const Signature& signature)
{
signature_ = signature.clone();
onChanged();
return *this;
}
/**
* Set name to a copy of the given Name. This is virtual so that a subclass can override to validate the name.
* @param name The Name which is copied.
* @return This Data so that you can chain calls to update values.
*/
virtual Data&
setName(const Name& name);
/**
* Set metaInfo to a copy of the given MetaInfo.
* @param metaInfo The MetaInfo which is copied.
* @return This Data so that you can chain calls to update values.
*/
Data&
setMetainfo(const MetaInfo& metaInfo)
{
metaInfo_ = metaInfo;
onChanged();
return *this;
}
/**
* Set the content to a copy of the data in the vector.
* @param content A vector whose contents are copied.
* @return This Data so that you can chain calls to update values.
*/
Data&
setContent(const std::vector<uint8_t>& content)
{
content_ = content;
onChanged();
return *this;
}
Data&
setContent(const uint8_t* content, size_t contentLength)
{
content_ = Blob(content, contentLength);
onChanged();
return *this;
}
Data&
setContent(const Blob& content)
{
content_ = content;
onChanged();
return *this;
}
private:
/**
* Clear the wire encoding.
*/
void
onChanged();
ptr_lib::shared_ptr<Signature> signature_;
Name name_;
MetaInfo metaInfo_;
Blob content_;
SignedBlob defaultWireEncoding_;
};
}
#endif
<|endoftext|>
|
<commit_before>//===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the lowering for the gc.root mechanism.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/GCMetadata.h"
#include "llvm/CodeGen/GCStrategy.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
/// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
/// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
/// directed by the GCStrategy. It also performs automatic root initialization
/// and custom intrinsic lowering.
class LowerIntrinsics : public FunctionPass {
bool DoLowering(Function &F, GCStrategy &S);
public:
static char ID;
LowerIntrinsics();
StringRef getPassName() const override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
};
/// GCMachineCodeAnalysis - This is a target-independent pass over the machine
/// function representation to identify safe points for the garbage collector
/// in the machine code. It inserts labels at safe points and populates a
/// GCMetadata record for each function.
class GCMachineCodeAnalysis : public MachineFunctionPass {
GCFunctionInfo *FI;
MachineModuleInfo *MMI;
const TargetInstrInfo *TII;
void FindSafePoints(MachineFunction &MF);
void VisitCallPoint(MachineBasicBlock::iterator CI);
MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
const DebugLoc &DL) const;
void FindStackOffsets(MachineFunction &MF);
public:
static char ID;
GCMachineCodeAnalysis();
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnMachineFunction(MachineFunction &MF) override;
};
}
// -----------------------------------------------------------------------------
INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
false)
INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
char LowerIntrinsics::ID = 0;
LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
}
StringRef LowerIntrinsics::getPassName() const {
return "Lower Garbage Collection Instructions";
}
void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
FunctionPass::getAnalysisUsage(AU);
AU.addRequired<GCModuleInfo>();
AU.addPreserved<DominatorTreeWrapperPass>();
}
/// doInitialization - If this module uses the GC intrinsics, find them now.
bool LowerIntrinsics::doInitialization(Module &M) {
GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isDeclaration() && I->hasGC())
MI->getFunctionInfo(*I); // Instantiate the GC strategy.
return false;
}
/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
/// instruction could introduce a safe point.
static bool CouldBecomeSafePoint(Instruction *I) {
// The natural definition of instructions which could introduce safe points
// are:
//
// - call, invoke (AfterCall, BeforeCall)
// - phis (Loops)
// - invoke, ret, unwind (Exit)
//
// However, instructions as seemingly inoccuous as arithmetic can become
// libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
// it is necessary to take a conservative approach.
if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
isa<LoadInst>(I))
return false;
// llvm.gcroot is safe because it doesn't do anything at runtime.
if (CallInst *CI = dyn_cast<CallInst>(I))
if (Function *F = CI->getCalledFunction())
if (Intrinsic::ID IID = F->getIntrinsicID())
if (IID == Intrinsic::gcroot)
return false;
return true;
}
static bool InsertRootInitializers(Function &F, AllocaInst **Roots,
unsigned Count) {
// Scroll past alloca instructions.
BasicBlock::iterator IP = F.getEntryBlock().begin();
while (isa<AllocaInst>(IP))
++IP;
// Search for initializers in the initial BB.
SmallPtrSet<AllocaInst *, 16> InitedRoots;
for (; !CouldBecomeSafePoint(&*IP); ++IP)
if (StoreInst *SI = dyn_cast<StoreInst>(IP))
if (AllocaInst *AI =
dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
InitedRoots.insert(AI);
// Add root initializers.
bool MadeChange = false;
for (AllocaInst **I = Roots, **E = Roots + Count; I != E; ++I)
if (!InitedRoots.count(*I)) {
StoreInst *SI = new StoreInst(
ConstantPointerNull::get(cast<PointerType>((*I)->getAllocatedType())),
*I);
SI->insertAfter(*I);
MadeChange = true;
}
return MadeChange;
}
/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
/// Leave gcroot intrinsics; the code generator needs to see those.
bool LowerIntrinsics::runOnFunction(Function &F) {
// Quick exit for functions that do not use GC.
if (!F.hasGC())
return false;
GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
GCStrategy &S = FI.getStrategy();
return DoLowering(F, S);
}
/// Lower barriers out of existance (if the associated GCStrategy hasn't
/// already done so...), and insert initializing stores to roots as a defensive
/// measure. Given we're going to report all roots live at all safepoints, we
/// need to be able to ensure each root has been initialized by the point the
/// first safepoint is reached. This really should have been done by the
/// frontend, but the old API made this non-obvious, so we do a potentially
/// redundant store just in case.
bool LowerIntrinsics::DoLowering(Function &F, GCStrategy &S) {
SmallVector<AllocaInst *, 32> Roots;
bool MadeChange = false;
for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++)) {
Function *F = CI->getCalledFunction();
switch (F->getIntrinsicID()) {
default: break;
case Intrinsic::gcwrite: {
// Replace a write barrier with a simple store.
Value *St = new StoreInst(CI->getArgOperand(0),
CI->getArgOperand(2), CI);
CI->replaceAllUsesWith(St);
CI->eraseFromParent();
MadeChange = true;
break;
}
case Intrinsic::gcread: {
// Replace a read barrier with a simple load.
Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
Ld->takeName(CI);
CI->replaceAllUsesWith(Ld);
CI->eraseFromParent();
MadeChange = true;
break;
}
case Intrinsic::gcroot: {
// Initialize the GC root, but do not delete the intrinsic. The
// backend needs the intrinsic to flag the stack slot.
Roots.push_back(
cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
break;
}
}
}
}
}
if (Roots.size())
MadeChange |= InsertRootInitializers(F, Roots.begin(), Roots.size());
return MadeChange;
}
// -----------------------------------------------------------------------------
char GCMachineCodeAnalysis::ID = 0;
char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
"Analyze Machine Code For Garbage Collection", false, false)
GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
MachineFunctionPass::getAnalysisUsage(AU);
AU.setPreservesAll();
AU.addRequired<MachineModuleInfo>();
AU.addRequired<GCModuleInfo>();
}
MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
const DebugLoc &DL) const {
MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
return Label;
}
void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
// Find the return address (next instruction), too, so as to bracket the call
// instruction.
MachineBasicBlock::iterator RAI = CI;
++RAI;
if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
}
if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
}
}
void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end(); BBI != BBE;
++BBI)
for (MachineBasicBlock::iterator MI = BBI->begin(), ME = BBI->end();
MI != ME; ++MI)
if (MI->isCall()) {
// Do not treat tail or sibling call sites as safe points. This is
// legal since any arguments passed to the callee which live in the
// remnants of the callers frame will be owned and updated by the
// callee if required.
if (MI->isTerminator())
continue;
VisitCallPoint(MI);
}
}
void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
assert(TFI && "TargetRegisterInfo not available!");
for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
RI != FI->roots_end();) {
// If the root references a dead object, no need to keep it.
if (MF.getFrameInfo().isDeadObjectIndex(RI->Num)) {
RI = FI->removeStackRoot(RI);
} else {
unsigned FrameReg; // FIXME: surely GCRoot ought to store the
// register that the offset is from?
RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
++RI;
}
}
}
bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
// Quick exit for functions that do not use GC.
if (!MF.getFunction().hasGC())
return false;
FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(MF.getFunction());
MMI = &getAnalysis<MachineModuleInfo>();
TII = MF.getSubtarget().getInstrInfo();
// Find the size of the stack frame. There may be no correct static frame
// size, we use UINT64_MAX to represent this.
const MachineFrameInfo &MFI = MF.getFrameInfo();
const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
const bool DynamicFrameSize = MFI.hasVarSizedObjects() ||
RegInfo->needsStackRealignment(MF);
FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI.getStackSize());
// Find all safe points.
if (FI->getStrategy().needsSafePoints())
FindSafePoints(MF);
// Find the concrete stack offsets for all roots (stack slots)
FindStackOffsets(MF);
return false;
}
<commit_msg>[GC] Minor style modernization<commit_after>//===-- GCRootLowering.cpp - Garbage collection infrastructure ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the lowering for the gc.root mechanism.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/GCMetadata.h"
#include "llvm/CodeGen/GCStrategy.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
/// LowerIntrinsics - This pass rewrites calls to the llvm.gcread or
/// llvm.gcwrite intrinsics, replacing them with simple loads and stores as
/// directed by the GCStrategy. It also performs automatic root initialization
/// and custom intrinsic lowering.
class LowerIntrinsics : public FunctionPass {
bool DoLowering(Function &F, GCStrategy &S);
public:
static char ID;
LowerIntrinsics();
StringRef getPassName() const override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool doInitialization(Module &M) override;
bool runOnFunction(Function &F) override;
};
/// GCMachineCodeAnalysis - This is a target-independent pass over the machine
/// function representation to identify safe points for the garbage collector
/// in the machine code. It inserts labels at safe points and populates a
/// GCMetadata record for each function.
class GCMachineCodeAnalysis : public MachineFunctionPass {
GCFunctionInfo *FI;
MachineModuleInfo *MMI;
const TargetInstrInfo *TII;
void FindSafePoints(MachineFunction &MF);
void VisitCallPoint(MachineBasicBlock::iterator CI);
MCSymbol *InsertLabel(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
const DebugLoc &DL) const;
void FindStackOffsets(MachineFunction &MF);
public:
static char ID;
GCMachineCodeAnalysis();
void getAnalysisUsage(AnalysisUsage &AU) const override;
bool runOnMachineFunction(MachineFunction &MF) override;
};
}
// -----------------------------------------------------------------------------
INITIALIZE_PASS_BEGIN(LowerIntrinsics, "gc-lowering", "GC Lowering", false,
false)
INITIALIZE_PASS_DEPENDENCY(GCModuleInfo)
INITIALIZE_PASS_END(LowerIntrinsics, "gc-lowering", "GC Lowering", false, false)
FunctionPass *llvm::createGCLoweringPass() { return new LowerIntrinsics(); }
char LowerIntrinsics::ID = 0;
LowerIntrinsics::LowerIntrinsics() : FunctionPass(ID) {
initializeLowerIntrinsicsPass(*PassRegistry::getPassRegistry());
}
StringRef LowerIntrinsics::getPassName() const {
return "Lower Garbage Collection Instructions";
}
void LowerIntrinsics::getAnalysisUsage(AnalysisUsage &AU) const {
FunctionPass::getAnalysisUsage(AU);
AU.addRequired<GCModuleInfo>();
AU.addPreserved<DominatorTreeWrapperPass>();
}
/// doInitialization - If this module uses the GC intrinsics, find them now.
bool LowerIntrinsics::doInitialization(Module &M) {
GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
assert(MI && "LowerIntrinsics didn't require GCModuleInfo!?");
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
if (!I->isDeclaration() && I->hasGC())
MI->getFunctionInfo(*I); // Instantiate the GC strategy.
return false;
}
/// CouldBecomeSafePoint - Predicate to conservatively determine whether the
/// instruction could introduce a safe point.
static bool CouldBecomeSafePoint(Instruction *I) {
// The natural definition of instructions which could introduce safe points
// are:
//
// - call, invoke (AfterCall, BeforeCall)
// - phis (Loops)
// - invoke, ret, unwind (Exit)
//
// However, instructions as seemingly inoccuous as arithmetic can become
// libcalls upon lowering (e.g., div i64 on a 32-bit platform), so instead
// it is necessary to take a conservative approach.
if (isa<AllocaInst>(I) || isa<GetElementPtrInst>(I) || isa<StoreInst>(I) ||
isa<LoadInst>(I))
return false;
// llvm.gcroot is safe because it doesn't do anything at runtime.
if (CallInst *CI = dyn_cast<CallInst>(I))
if (Function *F = CI->getCalledFunction())
if (Intrinsic::ID IID = F->getIntrinsicID())
if (IID == Intrinsic::gcroot)
return false;
return true;
}
static bool InsertRootInitializers(Function &F, ArrayRef<AllocaInst *> Roots) {
// Scroll past alloca instructions.
BasicBlock::iterator IP = F.getEntryBlock().begin();
while (isa<AllocaInst>(IP))
++IP;
// Search for initializers in the initial BB.
SmallPtrSet<AllocaInst *, 16> InitedRoots;
for (; !CouldBecomeSafePoint(&*IP); ++IP)
if (StoreInst *SI = dyn_cast<StoreInst>(IP))
if (AllocaInst *AI =
dyn_cast<AllocaInst>(SI->getOperand(1)->stripPointerCasts()))
InitedRoots.insert(AI);
// Add root initializers.
bool MadeChange = false;
for (AllocaInst *Root : Roots)
if (!InitedRoots.count(Root)) {
StoreInst *SI = new StoreInst(
ConstantPointerNull::get(cast<PointerType>(Root->getAllocatedType())),
Root);
SI->insertAfter(Root);
MadeChange = true;
}
return MadeChange;
}
/// runOnFunction - Replace gcread/gcwrite intrinsics with loads and stores.
/// Leave gcroot intrinsics; the code generator needs to see those.
bool LowerIntrinsics::runOnFunction(Function &F) {
// Quick exit for functions that do not use GC.
if (!F.hasGC())
return false;
GCFunctionInfo &FI = getAnalysis<GCModuleInfo>().getFunctionInfo(F);
GCStrategy &S = FI.getStrategy();
return DoLowering(F, S);
}
/// Lower barriers out of existance (if the associated GCStrategy hasn't
/// already done so...), and insert initializing stores to roots as a defensive
/// measure. Given we're going to report all roots live at all safepoints, we
/// need to be able to ensure each root has been initialized by the point the
/// first safepoint is reached. This really should have been done by the
/// frontend, but the old API made this non-obvious, so we do a potentially
/// redundant store just in case.
bool LowerIntrinsics::DoLowering(Function &F, GCStrategy &S) {
SmallVector<AllocaInst *, 32> Roots;
bool MadeChange = false;
for (BasicBlock &BB : F)
for (BasicBlock::iterator II = BB.begin(), E = BB.end(); II != E;) {
IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++);
if (!CI)
continue;
Function *F = CI->getCalledFunction();
switch (F->getIntrinsicID()) {
default: break;
case Intrinsic::gcwrite: {
// Replace a write barrier with a simple store.
Value *St = new StoreInst(CI->getArgOperand(0),
CI->getArgOperand(2), CI);
CI->replaceAllUsesWith(St);
CI->eraseFromParent();
MadeChange = true;
break;
}
case Intrinsic::gcread: {
// Replace a read barrier with a simple load.
Value *Ld = new LoadInst(CI->getArgOperand(1), "", CI);
Ld->takeName(CI);
CI->replaceAllUsesWith(Ld);
CI->eraseFromParent();
MadeChange = true;
break;
}
case Intrinsic::gcroot: {
// Initialize the GC root, but do not delete the intrinsic. The
// backend needs the intrinsic to flag the stack slot.
Roots.push_back(
cast<AllocaInst>(CI->getArgOperand(0)->stripPointerCasts()));
break;
}
}
}
if (Roots.size())
MadeChange |= InsertRootInitializers(F, Roots);
return MadeChange;
}
// -----------------------------------------------------------------------------
char GCMachineCodeAnalysis::ID = 0;
char &llvm::GCMachineCodeAnalysisID = GCMachineCodeAnalysis::ID;
INITIALIZE_PASS(GCMachineCodeAnalysis, "gc-analysis",
"Analyze Machine Code For Garbage Collection", false, false)
GCMachineCodeAnalysis::GCMachineCodeAnalysis() : MachineFunctionPass(ID) {}
void GCMachineCodeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
MachineFunctionPass::getAnalysisUsage(AU);
AU.setPreservesAll();
AU.addRequired<MachineModuleInfo>();
AU.addRequired<GCModuleInfo>();
}
MCSymbol *GCMachineCodeAnalysis::InsertLabel(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
const DebugLoc &DL) const {
MCSymbol *Label = MBB.getParent()->getContext().createTempSymbol();
BuildMI(MBB, MI, DL, TII->get(TargetOpcode::GC_LABEL)).addSym(Label);
return Label;
}
void GCMachineCodeAnalysis::VisitCallPoint(MachineBasicBlock::iterator CI) {
// Find the return address (next instruction), too, so as to bracket the call
// instruction.
MachineBasicBlock::iterator RAI = CI;
++RAI;
if (FI->getStrategy().needsSafePoint(GC::PreCall)) {
MCSymbol *Label = InsertLabel(*CI->getParent(), CI, CI->getDebugLoc());
FI->addSafePoint(GC::PreCall, Label, CI->getDebugLoc());
}
if (FI->getStrategy().needsSafePoint(GC::PostCall)) {
MCSymbol *Label = InsertLabel(*CI->getParent(), RAI, CI->getDebugLoc());
FI->addSafePoint(GC::PostCall, Label, CI->getDebugLoc());
}
}
void GCMachineCodeAnalysis::FindSafePoints(MachineFunction &MF) {
for (MachineBasicBlock &MBB : MF)
for (MachineBasicBlock::iterator MI = MBB.begin(), ME = MBB.end();
MI != ME; ++MI)
if (MI->isCall()) {
// Do not treat tail or sibling call sites as safe points. This is
// legal since any arguments passed to the callee which live in the
// remnants of the callers frame will be owned and updated by the
// callee if required.
if (MI->isTerminator())
continue;
VisitCallPoint(MI);
}
}
void GCMachineCodeAnalysis::FindStackOffsets(MachineFunction &MF) {
const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
assert(TFI && "TargetRegisterInfo not available!");
for (GCFunctionInfo::roots_iterator RI = FI->roots_begin();
RI != FI->roots_end();) {
// If the root references a dead object, no need to keep it.
if (MF.getFrameInfo().isDeadObjectIndex(RI->Num)) {
RI = FI->removeStackRoot(RI);
} else {
unsigned FrameReg; // FIXME: surely GCRoot ought to store the
// register that the offset is from?
RI->StackOffset = TFI->getFrameIndexReference(MF, RI->Num, FrameReg);
++RI;
}
}
}
bool GCMachineCodeAnalysis::runOnMachineFunction(MachineFunction &MF) {
// Quick exit for functions that do not use GC.
if (!MF.getFunction().hasGC())
return false;
FI = &getAnalysis<GCModuleInfo>().getFunctionInfo(MF.getFunction());
MMI = &getAnalysis<MachineModuleInfo>();
TII = MF.getSubtarget().getInstrInfo();
// Find the size of the stack frame. There may be no correct static frame
// size, we use UINT64_MAX to represent this.
const MachineFrameInfo &MFI = MF.getFrameInfo();
const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
const bool DynamicFrameSize = MFI.hasVarSizedObjects() ||
RegInfo->needsStackRealignment(MF);
FI->setFrameSize(DynamicFrameSize ? UINT64_MAX : MFI.getStackSize());
// Find all safe points.
if (FI->getStrategy().needsSafePoints())
FindSafePoints(MF);
// Find the concrete stack offsets for all roots (stack slots)
FindStackOffsets(MF);
return false;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_PROPERTY_H
#define NIX_PROPERTY_H
#include <stdexcept>
#include <nix/base/NamedEntity.hpp>
#include <nix/base/IProperty.hpp>
#include <nix/Value.hpp>
#include <nix/Platform.hpp>
namespace nix {
class NIXAPI Property : virtual public base::IProperty, public base::NamedEntity<base::IProperty> {
public:
Property()
: NamedEntity()
{
}
Property(const Property &other)
: NamedEntity(other.impl())
{
}
Property(const std::shared_ptr<base::IProperty> &p_impl)
: NamedEntity(p_impl)
{
}
//--------------------------------------------------
// Attribute getter and setter
//--------------------------------------------------
/**
* Set the mapping information for this Property. The mapping defines how
* this Property should be treated in a mapping procedure. The mapping is provided
* in form of an url pointing to the definition of a section into which this
* property should be mapped
* (e.g. http:// ... /preparation/preparation.xml#preparation:BathSolution
*
* @param mapping string the mapping information.
*
*/
void mapping(const std::string &mapping) {
backend()->mapping(mapping);
}
/**
* Getter for the mapping information stored in this Property.
* The result may be not initialized, check on true before
* dereferencing.
*
* @returns boost::optional<String> the mapping
*/
boost::optional<std::string> mapping() const {
return backend()->mapping();
}
/**
* Deletes the mapping information.
*
* @param boost::none_t
*/
void mapping(const boost::none_t t) {
backend()->mapping(t);
}
/**
* Returns the dataType of the stored Values. Returned value may be
* not initialized if no value present, check on true before dereferencing.
*
* @param boost::optional<nix::DataType> the value DataType
*
*/
boost::optional<DataType> dataType() const {
return backend()->dataType();
}
/**
* Set the unit of the stored values. Note: all values
* have the same unit.
*
* @param std::string the unit
*/
void unit(const std::string &unit) {
if (backend()->valueCount() > 0 && backend()->unit()) {
throw std::runtime_error("Cannot change unit of a not-empty property!");
}
if (!(util::isSIUnit(unit) || util::isCompoundSIUnit(unit))) {
throw InvalidUnit("Unit is not SI or composite of SI units.", "Property::unit(const string &unit)");
}
backend()->unit(unit);
}
/**
* Returns the unit. Return value may be uninitialized,
* check for true before dereferencing.
*
* @return boost::optional<String> the unit
*
*/
boost::optional<std::string> unit() const {
return backend()->unit();
}
/**
* Deletes the unit information.
*
* @param boost::none_t
*/
void unit(const boost::none_t t) {
return backend()->unit(t);
}
//--------------------------------------------------
// Methods for Value access
//--------------------------------------------------
/**
* Deletes all values of this Property.
*
*/
void deleteValues() {
backend()->deleteValues();
}
/**
* Returns the number of values stored in this Property.
*
* @return size_t the count
*/
size_t valueCount() const {
return backend()->valueCount();
}
/**
* Set the values of this Property. Replaces all existing Values.
*
* @param std::vector<Value> the new values.
*/
void values(const std::vector<Value> &values) {
backend()->values(values);
}
/**
* Returns the values stored in this Property. Returned vector may
* be empty.
*
* @return std::vector<Value> the values.
*/
std::vector<Value> values(void) const {
return backend()->values();
}
/**
* Deletes the values stored in this Property.
*
* @param boost::none_t
*/
void values(const boost::none_t t) {
backend()->values(t);
}
//------------------------------------------------------
// Operators and other functions
//------------------------------------------------------
virtual Property &operator=(none_t) {
nullify();
return *this;
}
/**
* Output operator
*/
friend std::ostream& operator<<(std::ostream &out, const Property &ent) {
out << "Property: {name = " << ent.name() << "}";
return out;
}
virtual ~Property() {}
};
} // namespace nix
#endif // NIX_PROPERTY_H
<commit_msg>Property: Add ctor with rvalue ref. for shared_ptr<IProperty><commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#ifndef NIX_PROPERTY_H
#define NIX_PROPERTY_H
#include <stdexcept>
#include <nix/base/NamedEntity.hpp>
#include <nix/base/IProperty.hpp>
#include <nix/Value.hpp>
#include <nix/Platform.hpp>
namespace nix {
class NIXAPI Property : virtual public base::IProperty, public base::NamedEntity<base::IProperty> {
public:
Property()
: NamedEntity()
{
}
Property(const Property &other)
: NamedEntity(other.impl())
{
}
Property(const std::shared_ptr<base::IProperty> &p_impl)
: NamedEntity(p_impl)
{
}
Property(std::shared_ptr<base::IProperty> &&ptr)
: NamedEntity(std::move(ptr))
{
}
//--------------------------------------------------
// Attribute getter and setter
//--------------------------------------------------
/**
* Set the mapping information for this Property. The mapping defines how
* this Property should be treated in a mapping procedure. The mapping is provided
* in form of an url pointing to the definition of a section into which this
* property should be mapped
* (e.g. http:// ... /preparation/preparation.xml#preparation:BathSolution
*
* @param mapping string the mapping information.
*
*/
void mapping(const std::string &mapping) {
backend()->mapping(mapping);
}
/**
* Getter for the mapping information stored in this Property.
* The result may be not initialized, check on true before
* dereferencing.
*
* @returns boost::optional<String> the mapping
*/
boost::optional<std::string> mapping() const {
return backend()->mapping();
}
/**
* Deletes the mapping information.
*
* @param boost::none_t
*/
void mapping(const boost::none_t t) {
backend()->mapping(t);
}
/**
* Returns the dataType of the stored Values. Returned value may be
* not initialized if no value present, check on true before dereferencing.
*
* @param boost::optional<nix::DataType> the value DataType
*
*/
boost::optional<DataType> dataType() const {
return backend()->dataType();
}
/**
* Set the unit of the stored values. Note: all values
* have the same unit.
*
* @param std::string the unit
*/
void unit(const std::string &unit) {
if (backend()->valueCount() > 0 && backend()->unit()) {
throw std::runtime_error("Cannot change unit of a not-empty property!");
}
if (!(util::isSIUnit(unit) || util::isCompoundSIUnit(unit))) {
throw InvalidUnit("Unit is not SI or composite of SI units.", "Property::unit(const string &unit)");
}
backend()->unit(unit);
}
/**
* Returns the unit. Return value may be uninitialized,
* check for true before dereferencing.
*
* @return boost::optional<String> the unit
*
*/
boost::optional<std::string> unit() const {
return backend()->unit();
}
/**
* Deletes the unit information.
*
* @param boost::none_t
*/
void unit(const boost::none_t t) {
return backend()->unit(t);
}
//--------------------------------------------------
// Methods for Value access
//--------------------------------------------------
/**
* Deletes all values of this Property.
*
*/
void deleteValues() {
backend()->deleteValues();
}
/**
* Returns the number of values stored in this Property.
*
* @return size_t the count
*/
size_t valueCount() const {
return backend()->valueCount();
}
/**
* Set the values of this Property. Replaces all existing Values.
*
* @param std::vector<Value> the new values.
*/
void values(const std::vector<Value> &values) {
backend()->values(values);
}
/**
* Returns the values stored in this Property. Returned vector may
* be empty.
*
* @return std::vector<Value> the values.
*/
std::vector<Value> values(void) const {
return backend()->values();
}
/**
* Deletes the values stored in this Property.
*
* @param boost::none_t
*/
void values(const boost::none_t t) {
backend()->values(t);
}
//------------------------------------------------------
// Operators and other functions
//------------------------------------------------------
virtual Property &operator=(none_t) {
nullify();
return *this;
}
/**
* Output operator
*/
friend std::ostream& operator<<(std::ostream &out, const Property &ent) {
out << "Property: {name = " << ent.name() << "}";
return out;
}
virtual ~Property() {}
};
} // namespace nix
#endif // NIX_PROPERTY_H
<|endoftext|>
|
<commit_before>//===- lib/Driver/GnuLdInputGraph.cpp -------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Driver/GnuLdInputGraph.h"
#include "lld/ReaderWriter/LinkerScript.h"
using namespace lld;
/// \brief Parse the input file to lld::File.
error_code ELFFileNode::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
if (_attributes._isWholeArchive) {
std::vector<std::unique_ptr<File>> parsedFiles;
error_code ec = ctx.registry().parseFile(_buffer, parsedFiles);
if (ec)
return ec;
assert(parsedFiles.size() == 1);
std::unique_ptr<File> f(parsedFiles[0].release());
if (auto archive = reinterpret_cast<const ArchiveLibraryFile *>(f.get())) {
// Have this node own the FileArchive object.
_archiveFile.reset(archive);
f.release();
// Add all members to _files vector
return archive->parseAllMembers(_files);
}
// if --whole-archive is around non-archive, just use it as normal.
_files.push_back(std::move(f));
return error_code::success();
}
return ctx.registry().parseFile(_buffer, _files);
}
/// \brief Parse the GnuLD Script
error_code GNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
_lexer.reset(new script::Lexer(std::move(_buffer)));
_parser.reset(new script::Parser(*_lexer.get()));
_linkerScript = _parser->parse();
if (!_linkerScript)
return LinkerScriptReaderError::parse_error;
return error_code::success();
}
/// \brief Handle GnuLD script for ELF.
error_code ELFGNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ELFFileNode::Attributes attributes;
if (error_code ec = GNULdScript::parse(ctx, diagnostics))
return ec;
for (const script::Command *c : _linkerScript->_commands) {
if (auto group = dyn_cast<script::Group>(c)) {
std::unique_ptr<Group> groupStart(new Group());
for (const script::Path &path : group->getPaths()) {
// TODO : Propagate Set WholeArchive/dashlPrefix
attributes.setAsNeeded(path._asNeeded);
auto inputNode = new ELFFileNode(
_elfLinkingContext, _elfLinkingContext.allocateString(path._path),
attributes);
std::unique_ptr<InputElement> inputFile(inputNode);
cast<Group>(groupStart.get())->addFile(
std::move(inputFile));
}
_expandElements.push_back(std::move(groupStart));
}
}
return error_code::success();
}
<commit_msg>Early continue to reduce nesting.<commit_after>//===- lib/Driver/GnuLdInputGraph.cpp -------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Driver/GnuLdInputGraph.h"
#include "lld/ReaderWriter/LinkerScript.h"
using namespace lld;
/// \brief Parse the input file to lld::File.
error_code ELFFileNode::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
if (_attributes._isWholeArchive) {
std::vector<std::unique_ptr<File>> parsedFiles;
error_code ec = ctx.registry().parseFile(_buffer, parsedFiles);
if (ec)
return ec;
assert(parsedFiles.size() == 1);
std::unique_ptr<File> f(parsedFiles[0].release());
if (auto archive = reinterpret_cast<const ArchiveLibraryFile *>(f.get())) {
// Have this node own the FileArchive object.
_archiveFile.reset(archive);
f.release();
// Add all members to _files vector
return archive->parseAllMembers(_files);
}
// if --whole-archive is around non-archive, just use it as normal.
_files.push_back(std::move(f));
return error_code::success();
}
return ctx.registry().parseFile(_buffer, _files);
}
/// \brief Parse the GnuLD Script
error_code GNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
_lexer.reset(new script::Lexer(std::move(_buffer)));
_parser.reset(new script::Parser(*_lexer.get()));
_linkerScript = _parser->parse();
if (!_linkerScript)
return LinkerScriptReaderError::parse_error;
return error_code::success();
}
/// \brief Handle GnuLD script for ELF.
error_code ELFGNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ELFFileNode::Attributes attributes;
if (error_code ec = GNULdScript::parse(ctx, diagnostics))
return ec;
for (const script::Command *c : _linkerScript->_commands) {
auto *group = dyn_cast<script::Group>(c);
if (!group)
continue;
std::unique_ptr<Group> groupStart(new Group());
for (const script::Path &path : group->getPaths()) {
// TODO : Propagate Set WholeArchive/dashlPrefix
attributes.setAsNeeded(path._asNeeded);
auto inputNode = new ELFFileNode(
_elfLinkingContext, _elfLinkingContext.allocateString(path._path),
attributes);
std::unique_ptr<InputElement> inputFile(inputNode);
cast<Group>(groupStart.get())->addFile(std::move(inputFile));
}
_expandElements.push_back(std::move(groupStart));
}
return error_code::success();
}
<|endoftext|>
|
<commit_before>
#include <QDateTime>
#include "datetime.h"
QString DateTime::defaultFormat = "yyyy-MM-dd hh:mm::ss";
QString DateTime::getTime()
{
return getTime(defaultFormat);
}
QString DateTime::getTime(QString format)
{
if(format.isEmpty()){
format = defaultFormat;
}
QString timeStr = QDateTime::currentDateTime().toString(format);
return timeStr;
}
<commit_msg>去掉标准时间格式中分数、秒数之间重复的冒号<commit_after>
#include <QDateTime>
#include "datetime.h"
QString DateTime::defaultFormat = "yyyy-MM-dd hh:mm:ss";
QString DateTime::getTime()
{
return getTime(defaultFormat);
}
QString DateTime::getTime(QString format)
{
if(format.isEmpty()){
format = defaultFormat;
}
QString timeStr = QDateTime::currentDateTime().toString(format);
return timeStr;
}
<|endoftext|>
|
<commit_before><commit_msg>bug in randomgenerator for 64bit int<commit_after><|endoftext|>
|
<commit_before>//===--- ConstraintLocator.cpp - Constraint Locator -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the \c ConstraintLocator class and its related types,
// which is used by the constraint-based type checker to describe how
// a particular constraint was derived.
//
//===----------------------------------------------------------------------===//
#include "ConstraintLocator.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using namespace constraints;
void ConstraintLocator::Profile(llvm::FoldingSetNodeID &id, Expr *anchor,
ArrayRef<PathElement> path) {
id.AddPointer(anchor);
id.AddInteger(path.size());
for (auto elt : path) {
id.AddInteger(elt.getKind());
unsigned numValues = numNumericValuesInPathElement(elt.getKind());
if (numValues > 0) {
id.AddInteger(elt.getValue());
if (numValues > 1)
id.AddInteger(elt.getValue2());
}
else if (elt.getKind() == ConstraintLocator::Archetype)
id.AddPointer(elt.getArchetype()->getCanonicalType().getPointer());
}
}
void ConstraintLocator::dump(SourceManager *sm) {
dump(sm, llvm::errs());
}
void ConstraintLocator::dump(SourceManager *sm, raw_ostream &out) {
out << "locator@" << (void*) this << " [";
if (anchor) {
out << Expr::getKindName(anchor->getKind());
if (sm) {
out << '@';
anchor->getLoc().print(out, *sm);
}
}
for (auto elt : getPath()) {
out << " -> ";
switch (elt.getKind()) {
case AddressOf:
out << "address of";
break;
case ArrayElementType:
out << "array element";
break;
case Archetype:
out << "archetype '" << elt.getArchetype()->getString() << "'";
break;
case AssociatedType:
out << "associated type '"
<< elt.getAssociatedType()->getNameStr() << "'";
break;
case ApplyArgument:
out << "apply argument";
break;
case ApplyFunction:
out << "apply function";
break;
case ApplyArgToParam:
out << "comparing call argument #" << llvm::utostr(elt.getValue())
<< " to parameter #" << llvm::utostr(elt.getValue2());
break;
case AssignDest:
out << "assignment destination";
break;
case AssignSource:
out << "assignment source";
break;
case CheckedCastOperand:
out << "checked cast operand";
break;
case ClosureResult:
out << "closure result";
break;
case ConstructorMember:
out << "constructor member";
break;
case FunctionArgument:
out << "function argument";
break;
case FunctionResult:
out << "function result";
break;
case GeneratorElementType:
out << "generator element type";
break;
case GenericArgument:
out << "generic argument #" << llvm::utostr(elt.getValue());
break;
case IfElse:
out << "'else' branch of ternary" ;
break;
case IfThen:
out << "'then' branch of ternary" ;
break;
case InstanceType:
out << "instance type";
break;
case InterpolationArgument:
out << "interpolation argument #" << llvm::utostr(elt.getValue());
break;
case Load:
out << "load";
break;
case LvalueObjectType:
out << "lvalue object type";
break;
case Member:
out << "member";
break;
case MemberRefBase:
out << "member reference base";
break;
case NamedTupleElement:
out << "named tuple element #" << llvm::utostr(elt.getValue());
break;
case UnresolvedMember:
out << "unresolved member";
break;
case ParentType:
out << "parent type";
break;
case RvalueAdjustment:
out << "rvalue adjustment";
break;
case ScalarToTuple:
out << "scalar to tuple";
break;
case SequenceGeneratorType:
out << "sequence generator type";
break;
case SubscriptIndex:
out << "subscript index";
break;
case SubscriptMember:
out << "subscript member";
break;
case SubscriptResult:
out << "subscript result";
break;
case TupleElement:
out << "tuple element #" << llvm::utostr(elt.getValue());
break;
case Witness:
out << "witness ";
elt.getWitness()->dumpRef(out);
break;
}
}
out << ']';
}
<commit_msg>Update ConstraintLocator profiling for witnesses and associated types.<commit_after>//===--- ConstraintLocator.cpp - Constraint Locator -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the \c ConstraintLocator class and its related types,
// which is used by the constraint-based type checker to describe how
// a particular constraint was derived.
//
//===----------------------------------------------------------------------===//
#include "ConstraintLocator.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using namespace constraints;
void ConstraintLocator::Profile(llvm::FoldingSetNodeID &id, Expr *anchor,
ArrayRef<PathElement> path) {
id.AddPointer(anchor);
id.AddInteger(path.size());
for (auto elt : path) {
id.AddInteger(elt.getKind());
switch (elt.getKind()) {
case Archetype:
id.AddPointer(elt.getArchetype()->getCanonicalType().getPointer());
break;
case Witness:
id.AddPointer(elt.getWitness());
break;
case AssociatedType:
id.AddPointer(elt.getAssociatedType());
break;
case ApplyArgument:
case ApplyFunction:
case FunctionArgument:
case FunctionResult:
case Member:
case MemberRefBase:
case UnresolvedMember:
case SubscriptIndex:
case SubscriptMember:
case SubscriptResult:
case ConstructorMember:
case AddressOf:
case RvalueAdjustment:
case ClosureResult:
case ParentType:
case InstanceType:
case SequenceGeneratorType:
case GeneratorElementType:
case ArrayElementType:
case LvalueObjectType:
case ScalarToTuple:
case Load:
case IfThen:
case IfElse:
case AssignSource:
case AssignDest:
case CheckedCastOperand:
case GenericArgument:
case InterpolationArgument:
case NamedTupleElement:
case TupleElement:
case ApplyArgToParam:
if (unsigned numValues = numNumericValuesInPathElement(elt.getKind())) {
id.AddInteger(elt.getValue());
if (numValues > 1)
id.AddInteger(elt.getValue2());
}
break;
}
}
}
void ConstraintLocator::dump(SourceManager *sm) {
dump(sm, llvm::errs());
}
void ConstraintLocator::dump(SourceManager *sm, raw_ostream &out) {
out << "locator@" << (void*) this << " [";
if (anchor) {
out << Expr::getKindName(anchor->getKind());
if (sm) {
out << '@';
anchor->getLoc().print(out, *sm);
}
}
for (auto elt : getPath()) {
out << " -> ";
switch (elt.getKind()) {
case AddressOf:
out << "address of";
break;
case ArrayElementType:
out << "array element";
break;
case Archetype:
out << "archetype '" << elt.getArchetype()->getString() << "'";
break;
case AssociatedType:
out << "associated type '"
<< elt.getAssociatedType()->getNameStr() << "'";
break;
case ApplyArgument:
out << "apply argument";
break;
case ApplyFunction:
out << "apply function";
break;
case ApplyArgToParam:
out << "comparing call argument #" << llvm::utostr(elt.getValue())
<< " to parameter #" << llvm::utostr(elt.getValue2());
break;
case AssignDest:
out << "assignment destination";
break;
case AssignSource:
out << "assignment source";
break;
case CheckedCastOperand:
out << "checked cast operand";
break;
case ClosureResult:
out << "closure result";
break;
case ConstructorMember:
out << "constructor member";
break;
case FunctionArgument:
out << "function argument";
break;
case FunctionResult:
out << "function result";
break;
case GeneratorElementType:
out << "generator element type";
break;
case GenericArgument:
out << "generic argument #" << llvm::utostr(elt.getValue());
break;
case IfElse:
out << "'else' branch of ternary" ;
break;
case IfThen:
out << "'then' branch of ternary" ;
break;
case InstanceType:
out << "instance type";
break;
case InterpolationArgument:
out << "interpolation argument #" << llvm::utostr(elt.getValue());
break;
case Load:
out << "load";
break;
case LvalueObjectType:
out << "lvalue object type";
break;
case Member:
out << "member";
break;
case MemberRefBase:
out << "member reference base";
break;
case NamedTupleElement:
out << "named tuple element #" << llvm::utostr(elt.getValue());
break;
case UnresolvedMember:
out << "unresolved member";
break;
case ParentType:
out << "parent type";
break;
case RvalueAdjustment:
out << "rvalue adjustment";
break;
case ScalarToTuple:
out << "scalar to tuple";
break;
case SequenceGeneratorType:
out << "sequence generator type";
break;
case SubscriptIndex:
out << "subscript index";
break;
case SubscriptMember:
out << "subscript member";
break;
case SubscriptResult:
out << "subscript result";
break;
case TupleElement:
out << "tuple element #" << llvm::utostr(elt.getValue());
break;
case Witness:
out << "witness ";
elt.getWitness()->dumpRef(out);
break;
}
}
out << ']';
}
<|endoftext|>
|
<commit_before>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* ------------------------------------------------------------------------ */
#include <limits.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include "Host.h"
#include "NebulaLog.h"
/* ************************************************************************ */
/* Host :: Constructor/Destructor */
/* ************************************************************************ */
Host::Host(
int id,
string _hostname,
string _im_mad_name,
string _vmm_mad_name,
string _tm_mad_name):
PoolObjectSQL(id),
hostname(_hostname),
state(INIT),
im_mad_name(_im_mad_name),
vmm_mad_name(_vmm_mad_name),
tm_mad_name(_tm_mad_name),
last_monitored(time(0)),
host_template(id)
{};
Host::~Host(){};
/* ************************************************************************ */
/* Host :: Database Access Functions */
/* ************************************************************************ */
const char * Host::table = "host_pool";
const char * Host::db_names = "(oid,host_name,state,im_mad,vm_mad,"
"tm_mad,last_mon_time)";
const char * Host::db_bootstrap = "CREATE TABLE host_pool ("
"oid INTEGER PRIMARY KEY,host_name VARCHAR(512), state INTEGER,"
"im_mad VARCHAR(256),vm_mad VARCHAR(256),tm_mad VARCHAR(256),"
"last_mon_time INTEGER, UNIQUE(host_name, im_mad, vm_mad, tm_mad) )";
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::select_cb(void * nil, int num, char **values, char ** names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(num != LIMIT ))
{
return -1;
}
oid = atoi(values[OID]);
hostname = values[HOST_NAME];
state = static_cast<HostState>(atoi(values[STATE]));
im_mad_name = values[IM_MAD];
vmm_mad_name = values[VM_MAD];
tm_mad_name = values[TM_MAD];
last_monitored = static_cast<time_t>(atoi(values[LAST_MON_TIME]));
host_template.id = oid;
host_share.hsid = oid;
return 0;
}
/* ------------------------------------------------------------------------ */
int Host::select(SqlDB *db)
{
ostringstream oss;
int rc;
int boid;
set_callback(static_cast<Callbackable::Callback>(&Host::select_cb));
oss << "SELECT * FROM " << table << " WHERE oid = " << oid;
boid = oid;
oid = -1;
rc = db->exec(oss, this);
if ((rc != 0) || (oid != boid ))
{
return -1;
}
// Get the template
rc = host_template.select(db);
if ( rc != 0 )
{
return -1;
}
// Select the host shares from the DB
rc = host_share.select(db);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert(SqlDB *db)
{
int rc;
map<int,HostShare *>::iterator iter;
// Set up the template ID, to insert it
if ( host_template.id == -1 )
{
host_template.id = oid;
}
// Set up the share ID, to insert it
if ( host_share.hsid == -1 )
{
host_share.hsid = oid;
}
// Update the Template
rc = host_template.insert(db);
if ( rc != 0 )
{
return rc;
}
// Update the HostShare
rc = host_share.insert(db);
if ( rc != 0 )
{
host_template.drop(db);
return rc;
}
//Insert the Host
rc = insert_replace(db, false);
if ( rc != 0 )
{
host_template.drop(db);
host_share.drop(db);
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update(SqlDB *db)
{
int rc;
// Update the Template
rc = host_template.update(db);
if ( rc != 0 )
{
return rc;
}
// Update the HostShare
rc = host_share.update(db);
if ( rc != 0 )
{
return rc;
}
rc = insert_replace(db, true);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert_replace(SqlDB *db, bool replace)
{
ostringstream oss;
int rc;
char * sql_hostname;
char * sql_im_mad_name;
char * sql_tm_mad_name;
char * sql_vmm_mad_name;
// Update the Host
sql_hostname = db->escape_str(hostname.c_str());
if ( sql_hostname == 0 )
{
goto error_hostname;
}
sql_im_mad_name = db->escape_str(im_mad_name.c_str());
if ( sql_im_mad_name == 0 )
{
goto error_im;
}
sql_tm_mad_name = db->escape_str(tm_mad_name.c_str());
if ( sql_tm_mad_name == 0 )
{
goto error_tm;
}
sql_vmm_mad_name = db->escape_str(vmm_mad_name.c_str());
if ( sql_vmm_mad_name == 0 )
{
goto error_vmm;
}
if(replace)
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<< table <<" "<< db_names <<" VALUES ("
<< oid << ","
<< "'" << sql_hostname << "',"
<< state << ","
<< "'" << sql_im_mad_name << "',"
<< "'" << sql_vmm_mad_name << "',"
<< "'" << sql_tm_mad_name << "',"
<< last_monitored << ")";
rc = db->exec(oss);
db->free_str(sql_hostname);
db->free_str(sql_im_mad_name);
db->free_str(sql_tm_mad_name);
db->free_str(sql_vmm_mad_name);
return rc;
error_vmm:
db->free_str(sql_tm_mad_name);
error_tm:
db->free_str(sql_im_mad_name);
error_im:
db->free_str(sql_hostname);
error_hostname:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::dump(ostringstream& oss, int num, char **values, char **names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(num != LIMIT + HostShare::LIMIT ))
{
return -1;
}
oss <<
"<HOST>" <<
"<ID>" << values[OID] <<"</ID>" <<
"<NAME>" << values[HOST_NAME] <<"</NAME>" <<
"<STATE>" << values[STATE] <<"</STATE>" <<
"<IM_MAD>" << values[IM_MAD] <<"</IM_MAD>" <<
"<VM_MAD>" << values[VM_MAD] <<"</VM_MAD>" <<
"<TM_MAD>" << values[TM_MAD] <<"</TM_MAD>" <<
"<LAST_MON_TIME>"<< values[LAST_MON_TIME]<<"</LAST_MON_TIME>";
HostShare::dump(oss,num - LIMIT, values + LIMIT, names + LIMIT);
oss << "</HOST>";
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::drop(SqlDB * db)
{
ostringstream oss;
int rc;
host_template.drop(db);
host_share.drop(db);
oss << "DELETE FROM " << table << " WHERE oid=" << oid;
rc = db->exec(oss);
if ( rc == 0 )
{
set_valid(false);
}
return rc;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update_info(string &parse_str)
{
char * error_msg;
int rc;
rc = host_template.parse(parse_str, &error_msg);
if ( rc != 0 )
{
NebulaLog::log("ONE", Log::ERROR, error_msg);
free(error_msg);
return -1;
}
get_template_attribute("TOTALCPU",host_share.max_cpu);
get_template_attribute("TOTALMEMORY",host_share.max_mem);
get_template_attribute("FREECPU",host_share.free_cpu);
get_template_attribute("FREEMEMORY",host_share.free_mem);
get_template_attribute("USEDCPU",host_share.used_cpu);
get_template_attribute("USEDMEMORY",host_share.used_mem);
return 0;
}
/* ************************************************************************ */
/* Host :: Misc */
/* ************************************************************************ */
ostream& operator<<(ostream& os, Host& host)
{
string host_str;
os << host.to_xml(host_str);
return os;
};
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_xml(string& xml) const
{
string template_xml;
string share_xml;
ostringstream oss;
oss <<
"<HOST>"
"<ID>" << oid << "</ID>" <<
"<NAME>" << hostname << "</NAME>" <<
"<STATE>" << state << "</STATE>" <<
"<IM_MAD>" << im_mad_name << "</IM_MAD>" <<
"<VM_MAD>" << vmm_mad_name << "</VM_MAD>" <<
"<TM_MAD>" << tm_mad_name << "</TM_MAD>" <<
"<LAST_MON_TIME>" << last_monitored << "</LAST_MON_TIME>" <<
host_share.to_xml(share_xml) <<
host_template.to_xml(template_xml) <<
"</HOST>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_str(string& str) const
{
string template_str;
string share_str;
ostringstream os;
os <<
"ID = " << oid << endl <<
"NAME = " << hostname << endl <<
"STATE = " << state << endl <<
"IM MAD = " << im_mad_name << endl <<
"VMM MAD = " << vmm_mad_name << endl <<
"TM MAD = " << tm_mad_name << endl <<
"LAST_MON = " << last_monitored << endl <<
"ATTRIBUTES" << endl << host_template.to_str(template_str) << endl <<
"HOST SHARES" << endl << host_share.to_str(share_str) <<endl;
str = os.str();
return str;
}
/* ************************************************************************ */
/* Host :: Parse functions to compute rank and evaluate requirements */
/* ************************************************************************ */
pthread_mutex_t Host::lex_mutex = PTHREAD_MUTEX_INITIALIZER;
extern "C"
{
typedef struct yy_buffer_state * YY_BUFFER_STATE;
int host_requirements_parse(Host * host, bool& result, char ** errmsg);
int host_rank_parse(Host * host, int& result, char ** errmsg);
int host_lex_destroy();
YY_BUFFER_STATE host__scan_string(const char * str);
void host__delete_buffer(YY_BUFFER_STATE);
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::match(const string& requirements, bool& result, char **errmsg)
{
YY_BUFFER_STATE str_buffer = 0;
const char * str;
int rc;
pthread_mutex_lock(&lex_mutex);
*errmsg = 0;
str = requirements.c_str();
str_buffer = host__scan_string(str);
if (str_buffer == 0)
{
goto error_yy;
}
rc = host_requirements_parse(this,result,errmsg);
host__delete_buffer(str_buffer);
host_lex_destroy();
pthread_mutex_unlock(&lex_mutex);
return rc;
error_yy:
*errmsg=strdup("Error setting scan buffer");
pthread_mutex_unlock(&lex_mutex);
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::rank(const string& rank, int& result, char **errmsg)
{
YY_BUFFER_STATE str_buffer = 0;
const char * str;
int rc;
pthread_mutex_lock(&lex_mutex);
*errmsg = 0;
str = rank.c_str();
str_buffer = host__scan_string(str);
if (str_buffer == 0)
{
goto error_yy;
}
rc = host_rank_parse(this,result,errmsg);
host__delete_buffer(str_buffer);
host_lex_destroy();
pthread_mutex_unlock(&lex_mutex);
return rc;
error_yy:
*errmsg=strdup("Error setting scan buffer");
pthread_mutex_unlock(&lex_mutex);
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
<commit_msg>feature-#206: Rolling back augmented mad name size, mysql index cannot be over 1000 bytes<commit_after>/* ------------------------------------------------------------------------ */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* ------------------------------------------------------------------------ */
#include <limits.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include "Host.h"
#include "NebulaLog.h"
/* ************************************************************************ */
/* Host :: Constructor/Destructor */
/* ************************************************************************ */
Host::Host(
int id,
string _hostname,
string _im_mad_name,
string _vmm_mad_name,
string _tm_mad_name):
PoolObjectSQL(id),
hostname(_hostname),
state(INIT),
im_mad_name(_im_mad_name),
vmm_mad_name(_vmm_mad_name),
tm_mad_name(_tm_mad_name),
last_monitored(time(0)),
host_template(id)
{};
Host::~Host(){};
/* ************************************************************************ */
/* Host :: Database Access Functions */
/* ************************************************************************ */
const char * Host::table = "host_pool";
const char * Host::db_names = "(oid,host_name,state,im_mad,vm_mad,"
"tm_mad,last_mon_time)";
const char * Host::db_bootstrap = "CREATE TABLE host_pool ("
"oid INTEGER PRIMARY KEY,host_name VARCHAR(512), state INTEGER,"
"im_mad VARCHAR(128),vm_mad VARCHAR(128),tm_mad VARCHAR(128),"
"last_mon_time INTEGER, UNIQUE(host_name, im_mad, vm_mad, tm_mad) )";
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::select_cb(void * nil, int num, char **values, char ** names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(num != LIMIT ))
{
return -1;
}
oid = atoi(values[OID]);
hostname = values[HOST_NAME];
state = static_cast<HostState>(atoi(values[STATE]));
im_mad_name = values[IM_MAD];
vmm_mad_name = values[VM_MAD];
tm_mad_name = values[TM_MAD];
last_monitored = static_cast<time_t>(atoi(values[LAST_MON_TIME]));
host_template.id = oid;
host_share.hsid = oid;
return 0;
}
/* ------------------------------------------------------------------------ */
int Host::select(SqlDB *db)
{
ostringstream oss;
int rc;
int boid;
set_callback(static_cast<Callbackable::Callback>(&Host::select_cb));
oss << "SELECT * FROM " << table << " WHERE oid = " << oid;
boid = oid;
oid = -1;
rc = db->exec(oss, this);
if ((rc != 0) || (oid != boid ))
{
return -1;
}
// Get the template
rc = host_template.select(db);
if ( rc != 0 )
{
return -1;
}
// Select the host shares from the DB
rc = host_share.select(db);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert(SqlDB *db)
{
int rc;
map<int,HostShare *>::iterator iter;
// Set up the template ID, to insert it
if ( host_template.id == -1 )
{
host_template.id = oid;
}
// Set up the share ID, to insert it
if ( host_share.hsid == -1 )
{
host_share.hsid = oid;
}
// Update the Template
rc = host_template.insert(db);
if ( rc != 0 )
{
return rc;
}
// Update the HostShare
rc = host_share.insert(db);
if ( rc != 0 )
{
host_template.drop(db);
return rc;
}
//Insert the Host
rc = insert_replace(db, false);
if ( rc != 0 )
{
host_template.drop(db);
host_share.drop(db);
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update(SqlDB *db)
{
int rc;
// Update the Template
rc = host_template.update(db);
if ( rc != 0 )
{
return rc;
}
// Update the HostShare
rc = host_share.update(db);
if ( rc != 0 )
{
return rc;
}
rc = insert_replace(db, true);
if ( rc != 0 )
{
return rc;
}
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::insert_replace(SqlDB *db, bool replace)
{
ostringstream oss;
int rc;
char * sql_hostname;
char * sql_im_mad_name;
char * sql_tm_mad_name;
char * sql_vmm_mad_name;
// Update the Host
sql_hostname = db->escape_str(hostname.c_str());
if ( sql_hostname == 0 )
{
goto error_hostname;
}
sql_im_mad_name = db->escape_str(im_mad_name.c_str());
if ( sql_im_mad_name == 0 )
{
goto error_im;
}
sql_tm_mad_name = db->escape_str(tm_mad_name.c_str());
if ( sql_tm_mad_name == 0 )
{
goto error_tm;
}
sql_vmm_mad_name = db->escape_str(vmm_mad_name.c_str());
if ( sql_vmm_mad_name == 0 )
{
goto error_vmm;
}
if(replace)
{
oss << "REPLACE";
}
else
{
oss << "INSERT";
}
// Construct the SQL statement to Insert or Replace
oss <<" INTO "<< table <<" "<< db_names <<" VALUES ("
<< oid << ","
<< "'" << sql_hostname << "',"
<< state << ","
<< "'" << sql_im_mad_name << "',"
<< "'" << sql_vmm_mad_name << "',"
<< "'" << sql_tm_mad_name << "',"
<< last_monitored << ")";
rc = db->exec(oss);
db->free_str(sql_hostname);
db->free_str(sql_im_mad_name);
db->free_str(sql_tm_mad_name);
db->free_str(sql_vmm_mad_name);
return rc;
error_vmm:
db->free_str(sql_tm_mad_name);
error_tm:
db->free_str(sql_im_mad_name);
error_im:
db->free_str(sql_hostname);
error_hostname:
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::dump(ostringstream& oss, int num, char **values, char **names)
{
if ((!values[OID]) ||
(!values[HOST_NAME]) ||
(!values[STATE]) ||
(!values[IM_MAD]) ||
(!values[VM_MAD]) ||
(!values[TM_MAD]) ||
(!values[LAST_MON_TIME]) ||
(num != LIMIT + HostShare::LIMIT ))
{
return -1;
}
oss <<
"<HOST>" <<
"<ID>" << values[OID] <<"</ID>" <<
"<NAME>" << values[HOST_NAME] <<"</NAME>" <<
"<STATE>" << values[STATE] <<"</STATE>" <<
"<IM_MAD>" << values[IM_MAD] <<"</IM_MAD>" <<
"<VM_MAD>" << values[VM_MAD] <<"</VM_MAD>" <<
"<TM_MAD>" << values[TM_MAD] <<"</TM_MAD>" <<
"<LAST_MON_TIME>"<< values[LAST_MON_TIME]<<"</LAST_MON_TIME>";
HostShare::dump(oss,num - LIMIT, values + LIMIT, names + LIMIT);
oss << "</HOST>";
return 0;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::drop(SqlDB * db)
{
ostringstream oss;
int rc;
host_template.drop(db);
host_share.drop(db);
oss << "DELETE FROM " << table << " WHERE oid=" << oid;
rc = db->exec(oss);
if ( rc == 0 )
{
set_valid(false);
}
return rc;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::update_info(string &parse_str)
{
char * error_msg;
int rc;
rc = host_template.parse(parse_str, &error_msg);
if ( rc != 0 )
{
NebulaLog::log("ONE", Log::ERROR, error_msg);
free(error_msg);
return -1;
}
get_template_attribute("TOTALCPU",host_share.max_cpu);
get_template_attribute("TOTALMEMORY",host_share.max_mem);
get_template_attribute("FREECPU",host_share.free_cpu);
get_template_attribute("FREEMEMORY",host_share.free_mem);
get_template_attribute("USEDCPU",host_share.used_cpu);
get_template_attribute("USEDMEMORY",host_share.used_mem);
return 0;
}
/* ************************************************************************ */
/* Host :: Misc */
/* ************************************************************************ */
ostream& operator<<(ostream& os, Host& host)
{
string host_str;
os << host.to_xml(host_str);
return os;
};
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_xml(string& xml) const
{
string template_xml;
string share_xml;
ostringstream oss;
oss <<
"<HOST>"
"<ID>" << oid << "</ID>" <<
"<NAME>" << hostname << "</NAME>" <<
"<STATE>" << state << "</STATE>" <<
"<IM_MAD>" << im_mad_name << "</IM_MAD>" <<
"<VM_MAD>" << vmm_mad_name << "</VM_MAD>" <<
"<TM_MAD>" << tm_mad_name << "</TM_MAD>" <<
"<LAST_MON_TIME>" << last_monitored << "</LAST_MON_TIME>" <<
host_share.to_xml(share_xml) <<
host_template.to_xml(template_xml) <<
"</HOST>";
xml = oss.str();
return xml;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
string& Host::to_str(string& str) const
{
string template_str;
string share_str;
ostringstream os;
os <<
"ID = " << oid << endl <<
"NAME = " << hostname << endl <<
"STATE = " << state << endl <<
"IM MAD = " << im_mad_name << endl <<
"VMM MAD = " << vmm_mad_name << endl <<
"TM MAD = " << tm_mad_name << endl <<
"LAST_MON = " << last_monitored << endl <<
"ATTRIBUTES" << endl << host_template.to_str(template_str) << endl <<
"HOST SHARES" << endl << host_share.to_str(share_str) <<endl;
str = os.str();
return str;
}
/* ************************************************************************ */
/* Host :: Parse functions to compute rank and evaluate requirements */
/* ************************************************************************ */
pthread_mutex_t Host::lex_mutex = PTHREAD_MUTEX_INITIALIZER;
extern "C"
{
typedef struct yy_buffer_state * YY_BUFFER_STATE;
int host_requirements_parse(Host * host, bool& result, char ** errmsg);
int host_rank_parse(Host * host, int& result, char ** errmsg);
int host_lex_destroy();
YY_BUFFER_STATE host__scan_string(const char * str);
void host__delete_buffer(YY_BUFFER_STATE);
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::match(const string& requirements, bool& result, char **errmsg)
{
YY_BUFFER_STATE str_buffer = 0;
const char * str;
int rc;
pthread_mutex_lock(&lex_mutex);
*errmsg = 0;
str = requirements.c_str();
str_buffer = host__scan_string(str);
if (str_buffer == 0)
{
goto error_yy;
}
rc = host_requirements_parse(this,result,errmsg);
host__delete_buffer(str_buffer);
host_lex_destroy();
pthread_mutex_unlock(&lex_mutex);
return rc;
error_yy:
*errmsg=strdup("Error setting scan buffer");
pthread_mutex_unlock(&lex_mutex);
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
int Host::rank(const string& rank, int& result, char **errmsg)
{
YY_BUFFER_STATE str_buffer = 0;
const char * str;
int rc;
pthread_mutex_lock(&lex_mutex);
*errmsg = 0;
str = rank.c_str();
str_buffer = host__scan_string(str);
if (str_buffer == 0)
{
goto error_yy;
}
rc = host_rank_parse(this,result,errmsg);
host__delete_buffer(str_buffer);
host_lex_destroy();
pthread_mutex_unlock(&lex_mutex);
return rc;
error_yy:
*errmsg=strdup("Error setting scan buffer");
pthread_mutex_unlock(&lex_mutex);
return -1;
}
/* ------------------------------------------------------------------------ */
/* ------------------------------------------------------------------------ */
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/javascript_environment.h"
#include <string>
#include "atom/browser/microtasks_runner.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/task/task_scheduler/initialization_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/common/content_switches.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"
#include "tracing/trace_event.h"
namespace atom {
JavascriptEnvironment::JavascriptEnvironment(uv_loop_t* event_loop)
: isolate_(Initialize(event_loop)),
isolate_holder_(base::ThreadTaskRunnerHandle::Get(),
gin::IsolateHolder::kSingleThread,
gin::IsolateHolder::kAllowAtomicsWait,
gin::IsolateHolder::IsolateType::kUtility,
gin::IsolateHolder::IsolateCreationMode::kNormal,
isolate_),
isolate_scope_(isolate_),
locker_(isolate_),
handle_scope_(isolate_),
context_(isolate_, v8::Context::New(isolate_)),
context_scope_(v8::Local<v8::Context>::New(isolate_, context_)) {}
JavascriptEnvironment::~JavascriptEnvironment() = default;
v8::Isolate* JavascriptEnvironment::Initialize(uv_loop_t* event_loop) {
auto* cmd = base::CommandLine::ForCurrentProcess();
// --js-flags.
std::string js_flags = cmd->GetSwitchValueASCII(switches::kJavaScriptFlags);
if (!js_flags.empty())
v8::V8::SetFlagsFromString(js_flags.c_str(), js_flags.size());
// The V8Platform of gin relies on Chromium's task schedule, which has not
// been started at this point, so we have to rely on Node's V8Platform.
auto* tracing_agent = node::CreateAgent();
auto* tracing_controller = tracing_agent->GetTracingController();
node::tracing::TraceEventHelper::SetAgent(tracing_agent);
platform_ = node::CreatePlatform(
base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.1, 0),
tracing_controller);
v8::V8::InitializePlatform(platform_);
gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
gin::ArrayBufferAllocator::SharedInstance(),
nullptr /* external_reference_table */,
false /* create_v8_platform */);
v8::Isolate* isolate = v8::Isolate::Allocate();
platform_->RegisterIsolate(isolate, event_loop);
return isolate;
}
void JavascriptEnvironment::OnMessageLoopCreated() {
DCHECK(!microtasks_runner_);
microtasks_runner_.reset(new MicrotasksRunner(isolate()));
base::MessageLoopCurrent::Get()->AddTaskObserver(microtasks_runner_.get());
}
void JavascriptEnvironment::OnMessageLoopDestroying() {
DCHECK(microtasks_runner_);
base::MessageLoopCurrent::Get()->RemoveTaskObserver(microtasks_runner_.get());
platform_->UnregisterIsolate(isolate_);
}
NodeEnvironment::NodeEnvironment(node::Environment* env) : env_(env) {}
NodeEnvironment::~NodeEnvironment() {
node::FreeEnvironment(env_);
}
} // namespace atom
<commit_msg>fix: drain tasks before shutting down isolate (#17879)<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/javascript_environment.h"
#include <string>
#include "atom/browser/microtasks_runner.h"
#include "atom/common/node_includes.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/task/task_scheduler/initialization_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "content/public/common/content_switches.h"
#include "gin/array_buffer.h"
#include "gin/v8_initializer.h"
#include "tracing/trace_event.h"
namespace atom {
JavascriptEnvironment::JavascriptEnvironment(uv_loop_t* event_loop)
: isolate_(Initialize(event_loop)),
isolate_holder_(base::ThreadTaskRunnerHandle::Get(),
gin::IsolateHolder::kSingleThread,
gin::IsolateHolder::kAllowAtomicsWait,
gin::IsolateHolder::IsolateType::kUtility,
gin::IsolateHolder::IsolateCreationMode::kNormal,
isolate_),
isolate_scope_(isolate_),
locker_(isolate_),
handle_scope_(isolate_),
context_(isolate_, v8::Context::New(isolate_)),
context_scope_(v8::Local<v8::Context>::New(isolate_, context_)) {}
JavascriptEnvironment::~JavascriptEnvironment() = default;
v8::Isolate* JavascriptEnvironment::Initialize(uv_loop_t* event_loop) {
auto* cmd = base::CommandLine::ForCurrentProcess();
// --js-flags.
std::string js_flags = cmd->GetSwitchValueASCII(switches::kJavaScriptFlags);
if (!js_flags.empty())
v8::V8::SetFlagsFromString(js_flags.c_str(), js_flags.size());
// The V8Platform of gin relies on Chromium's task schedule, which has not
// been started at this point, so we have to rely on Node's V8Platform.
auto* tracing_agent = node::CreateAgent();
auto* tracing_controller = tracing_agent->GetTracingController();
node::tracing::TraceEventHelper::SetAgent(tracing_agent);
platform_ = node::CreatePlatform(
base::RecommendedMaxNumberOfThreadsInPool(3, 8, 0.1, 0),
tracing_controller);
v8::V8::InitializePlatform(platform_);
gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode,
gin::ArrayBufferAllocator::SharedInstance(),
nullptr /* external_reference_table */,
false /* create_v8_platform */);
v8::Isolate* isolate = v8::Isolate::Allocate();
platform_->RegisterIsolate(isolate, event_loop);
return isolate;
}
void JavascriptEnvironment::OnMessageLoopCreated() {
DCHECK(!microtasks_runner_);
microtasks_runner_.reset(new MicrotasksRunner(isolate()));
base::MessageLoopCurrent::Get()->AddTaskObserver(microtasks_runner_.get());
}
void JavascriptEnvironment::OnMessageLoopDestroying() {
DCHECK(microtasks_runner_);
base::MessageLoopCurrent::Get()->RemoveTaskObserver(microtasks_runner_.get());
platform_->DrainTasks(isolate_);
platform_->UnregisterIsolate(isolate_);
}
NodeEnvironment::NodeEnvironment(node::Environment* env) : env_(env) {}
NodeEnvironment::~NodeEnvironment() {
node::FreeEnvironment(env_);
}
} // namespace atom
<|endoftext|>
|
<commit_before>#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
#include <map>
#include <stdexcept>
#include <vigra/array_vector.hxx>
#include <tclap/CmdLine.h>
#include "../../include/vigra/hdf5impex.hxx"
#include <set>
using namespace std;
using namespace vigra;
/** various enums used
*/
enum IDS_ {NUMERAL, LITERAL, ORDINAL, NOMINAL, IFSTRING, INPUT, OUTPUT,TAG, DUNNO};
void ARFF2HDF5(std::string arff, std::string hdf5)
{
}
std::string stripstr(std::string in)
{
std::string out = "";
for(int ii = 0; ii < int(in.size()); ++ii)
{
if(out.size() == 0 && (in[ii] == ' ' || in [ii] == '\t'))
continue;
else if(*out.rbegin() == ' ' && (in[ii] == ' ' || in [ii] == '\t'))
continue;
else if(in[ii] == '\t' || in[ii] == ' ')
out = out + ' ';
else
out = out + in[ii];
}
return out;
}
/** tokenize a string given delimiter string
*/
void tokenize(std::string str, ArrayVector<std::string> & in, std::string delim = ",")
{
if(delim == "w")
{
str = stripstr(str);
delim = " ";
}
if(str.size() < delim.size() || str.rfind(delim) != str.size() - delim.size())
str = str+delim;
while(str.size() != 0)
{
if(str.find(delim) != string::npos)
{
in.push_back(str.substr(0, str.find(delim)));
str = str.substr(str.find(delim)+delim.size(), str.size());
}
}
}
bool isInteger(std::string a)
{
return false;
}
bool isInteger(double a)
{
return double(int(a)) == a;
}
/** write the attributes of a dataset column
*/
template <class T, class C>
void writeColAttr(std::string filename,
std::string path,
MultiArrayView<2, T, C> ar,
IDS_ type,
IDS_ in,
int number)
{
//write precedence number
ArrayVector<int> order(size_t(1), number);
writeHDF5Attr(filename, path + ".order" , order);
//write column type
ArrayVector<std::string> col_type;
if(in == INPUT)
col_type.push_back("INPUT");
else if (in == OUTPUT)
col_type.push_back("OUTPUT");
else
{
ArrayVector<std::string> tmp(1, "na");
writeHDF5Attr(filename, path+".scale", tmp);
writeHDF5Attr(filename, path+".domain", tmp);
col_type.push_back("TAGS");
writeHDF5Attr(filename, path+".type", col_type);
return;
}
writeHDF5Attr(filename, path+".type", col_type);
//write domain and scale of the columns
if(type == NOMINAL)
{
ArrayVector<std::string> scale(1, "NOMINAL");
writeHDF5Attr(filename, path+".scale", scale);
std::set<T> a;
for(int ii = 0 ; ii < ar.size() ; ++ii)
a.insert(ar[ii]);
ArrayVector<T> cat(a.begin(), a.end());
writeHDF5Attr(filename, path+".domain", cat);
}
else
{
ArrayVector<std::string> scale(1, "ORDINAL");
writeHDF5Attr(filename, path+".scale", scale);
bool isInt = true;
for(int ii = 0; ii < ar.size(); ++ii)
isInt = isInt && isInteger(ar[ii]);
ArrayVector<std::string> domain;
if(isInt)
domain.push_back("INTEGER");
else
domain.push_back("REAL");
writeHDF5Attr(filename, path + ".domain", domain);
}
}
/** processes the name string delivered by cmd
*/
void processCSVname(std::string in,
std::string& name,
int last_col_index,
int & beg,
int & end,
IDS_ & type,
IDS_ & in_)
{
ArrayVector<std::string> tokens;
tokenize(in, tokens, "::");
name = tokens[0];
type = DUNNO;
in_ = DUNNO;
beg = last_col_index + 1;
end = beg ;
for(int ii = 1; ii < int(tokens.size()); ++ii)
{
if (tokens[ii] == "IN")
in_ = INPUT;
else if (tokens[ii] == "OUT")
in_ = OUTPUT;
else if (tokens[ii] == "TAG")
in_ = TAG;
else if (tokens[ii] == "NOMINAL")
type = NOMINAL;
else if (tokens[ii] == "ORDINAL")
type = ORDINAL;
else if (tokens[ii] == "all")
beg = -1;
else
{
double tmp;
std::istringstream sin(tokens[ii]);
sin >> tmp;
if(sin.fail() && tokens[ii].find(":") == string::npos)
throw std::runtime_error("could not parse name");
ArrayVector<std::string> tokensloc;
tokenize(tokens[ii], tokensloc, ":");
beg = atoi(tokensloc[0].c_str());
if(tokensloc.size() < 2)
end = beg;
else
end = atoi(tokensloc[1].c_str());
}
}
}
struct DlmInfo
{
std::string csvFile;
ArrayVector<IDS_> type_;
ArrayVector<int> offsets_;
std::string delim_;
int doubleCount_;
int stringCount_;
int rowCount_;
int h_count_;
int t_count_;
ArrayVector<std::string> names_;
int colCount()
{
return doubleCount_ + stringCount_;
}
DlmInfo(std::string name, std::string delim = ",",
int headercount = 0,
int trailercount = -1)
:
csvFile(name),
delim_(delim),
doubleCount_(0),
stringCount_(0),
rowCount_(0),
h_count_(headercount),
t_count_(0)
{
string line;
ifstream fin(name.c_str(), ios::in);
int count = 0;
//get the first line!
while(!getline(fin, line).eof() && count <= h_count_)
++count;
ArrayVector<string> tokens;
tokenize(line, tokens, delim);
ArrayVector<std::string>::iterator iter;
for(iter = tokens.begin(); iter != tokens.end(); ++iter)
{
std::istringstream sin(*iter);
double in;
sin >> in;
if(sin.fail())
{
type_.push_back(LITERAL);
offsets_.push_back(stringCount_);
++stringCount_;
}
else
{
type_.push_back(NUMERAL);
offsets_.push_back(doubleCount_);
++doubleCount_;
}
}
bool found_blank_line = false;
while(!getline(fin, line).eof())
{
if(stripstr(line) == "")
{
found_blank_line = true;
break;
}
++count;
}
if(found_blank_line)
t_count_ = count;
else
t_count_ = count - trailercount;
rowCount_ = t_count_ - h_count_;
fin.close();
}
};
/**read a delimmited table into a double matrix and an optional
* string matrix
*/
template<class T, class C1, class C2>
void dlmread(DlmInfo & info,
MultiArrayView<2, T, C1> & dblMult,
MultiArrayView<2, std::string, C2> strMult
= MultiArrayView<2, std::string, C2>())
{
//precondtion checking
if(info.stringCount_ != 0)
vigra_precondition(dblMult.shape(0) == strMult.shape(0),
"row Mismatch");
vigra_precondition(dblMult.shape(0) == info.rowCount_,
"row_Mismatch2");
vigra_precondition(dblMult.shape(1) == info.doubleCount_,
"dbl col mismatch");
if(info.stringCount_ != 0)
vigra_precondition(strMult.shape(1) == info.stringCount_,
"str col mismatch");
ifstream fin(info.csvFile.c_str(), ios::in);
int count = 0;
std::string line;
//get the first line!
while(count < info.h_count_ && !getline(fin, line).eof())
++count;
for(int ii = 0; ii < info.rowCount_; ++ii)
{
getline(fin, line);
ArrayVector<std::string> tokens;
tokenize(line, tokens, info.delim_);
int str_jj = 0, dbl_jj= 0;
for(int jj = 0; jj < info.colCount(); ++jj)
{
if(info.type_[jj] == NUMERAL)
{
std::istringstream sin(tokens[jj]);
double a;
sin >> a;
dblMult(ii, dbl_jj) = a;
++dbl_jj;
}
else
{
strMult(ii, str_jj) = tokens[jj];
++str_jj;
}
}
}
}
void CSV2HDF5(std::string csv,
std::string hdf5,
std::string path,
std::vector<string> const & names,
int headerCt = 0,
int trailerCt = 0,
std::string delim = ",")
{
typedef MultiArrayShape<2>::type Shp;
//get information for the seperated file and read
std::cerr << "getting file info" <<std::endl;
DlmInfo info(csv,delim, headerCt, trailerCt);
MultiArray<2, double> dblArr(Shp(info.rowCount_, info.doubleCount_));
MultiArray<2, string> strArr(Shp(info.rowCount_, info.stringCount_), "");
std::cerr << "loading text file "<<info.doubleCount_ <<" "<< info.rowCount_<< " " << info.stringCount_ << std::endl;
dlmread(info, dblArr, strArr);
int beg = 0, end = 0, last_end = -1, last_beg = 0;
std::string r_name;
IDS_ type, in_;
bool first_string_column = true;
//user has supplied column data.
if(names.size() != 0)
{
for(int ii = 0; ii < int(names.size()); ++ii)
{
std::cerr << "writing " << names[ii] << std::endl;
processCSVname(names[ii], r_name, last_end, beg, end, type, in_);
if(beg == -1)
{
beg = 0;
end = dblArr.shape(1);
}
else
{
last_end = end;
last_beg = beg;
end = end - beg;
beg = info.offsets_[beg];
end = beg + end + 1;
}
std::string col_path = path + "/" + r_name;
if(info.type_[last_beg] == NUMERAL)
{
writeToHDF5File(hdf5.c_str(),
col_path.c_str(),
dblArr.subarray(Shp(0, beg),
Shp(info.rowCount_, end)));
if(type == DUNNO)
type = ORDINAL;
if(in_ == DUNNO)
in_ = INPUT;
writeColAttr(hdf5.c_str(),
col_path.c_str(),
dblArr.subarray(Shp(0, beg),
Shp(info.rowCount_, end)),
type,
in_,
ii);
}
else
{
if(end - beg == 1)
writeToHDF5File(hdf5.c_str(),
col_path.c_str(),
strArr.subarray(Shp(0, beg),
Shp(info.rowCount_, end)).bindOuter(0));
else
writeToHDF5File(hdf5.c_str(),
col_path.c_str(),
strArr.subarray(Shp(0, beg),
Shp(info.rowCount_, end)));
if(type == DUNNO)
type = NOMINAL;
if( in_ == DUNNO && first_string_column)
{
in_ = OUTPUT;
first_string_column = false;
}
else if(in_ == DUNNO)
in_ = TAG;
writeColAttr(hdf5.c_str(),
col_path.c_str(),
strArr.subarray(Shp(0, beg),
Shp(info.rowCount_, end)),
type,
in_,
ii);
}
std::cerr << "done " << names[ii] << std::endl;
}
}
else
{
if(dblArr.size() > 0)
{
writeToHDF5File(hdf5.c_str(),
(path+"/doubleCols").c_str(),
dblArr);
writeColAttr(hdf5,
path + "/doubleCols",
dblArr,
ORDINAL,
INPUT,
0);
}
if(strArr.size() > 0)
{
writeToHDF5File(hdf5.c_str(),
(path+"/stringCols").c_str(),
strArr);
writeColAttr(hdf5,
path + "/stringCols",
strArr,
DUNNO,
TAG,
1);
}
}
}
void INFO2HDF5(std::string info,
std::string hdf5,
std::string name)
{
ifstream fin(info.c_str(), ios::in);
std::string line;
MultiArray<1, std::string> text_file(MultiArrayShape<1>::type(1), "");
//get the first line!
while(!getline(fin, line).eof())
text_file[0] = text_file[0] +"\n" + line;
name = "_" + name;
writeToHDF5File(hdf5.c_str(), name.c_str(), text_file);
}
int main(int argc, char** argv)
{
TCLAP::CmdLine cmd("Command description message", ' ', "0.9");
TCLAP::SwitchArg isARFF("","isARFF","input is ARFF file", cmd, false);
TCLAP::SwitchArg isCSV("","isCSV","input is CSV file", cmd, false);
TCLAP::SwitchArg isSparse("","isSparse","input is Sparse csv file", cmd, false);
TCLAP::SwitchArg isINFO("","isINFO","input is txt information", cmd, false);
TCLAP::ValueArg<std::string> input("i","input","inputfile", true,"a.in", "string");
cmd.add(input);
TCLAP::ValueArg<std::string> output("o","output","outputfile", true,"a.hdf5","string");
cmd.add(output);
TCLAP::ValueArg<std::string> delim("d","delim","csv delimiter", false, ",", "string");
cmd.add(delim);
TCLAP::ValueArg<std::string> src("s","source","source", false, "dataset", "string");
cmd.add(src);
TCLAP::ValueArg<int> header("t","topper","header lines", false, 0, "int");
cmd.add(header);
TCLAP::ValueArg<int> footer("f","footer","footer lines", false, 0, "int");
cmd.add(footer);
TCLAP::MultiArg<std::string> names("n", "names", "column names", false, "string");
cmd.add(names);
cmd.parse( argc, argv );
bool iscsv = isCSV.getValue();
if(iscsv == false && !isARFF.getValue() && !isINFO.getValue())
iscsv = true;
ifstream fin(input.getValue().c_str());
if(fin.fail())
{
throw std::runtime_error("could not find inputfile");
}
else
fin.close();
std::cerr<< "loading file :" << input.getValue() <<std::endl;
if(isARFF.getValue())
ARFF2HDF5(input.getValue(), output.getValue());
if(isSparse.getValue())
std::cerr << "Sparse Matrix representation currently not supported" <<std::endl;
else if(iscsv)
CSV2HDF5(input.getValue(),
output.getValue(),
src.getValue(),
names.getValue(),
header.getValue(),
footer.getValue(),
delim.getValue());
else if(isINFO.getValue())
INFO2HDF5(input.getValue(),
output.getValue(),
src.getValue());
return 0;
}
<commit_msg>Minor merge<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: statusindicatorinterfacewrapper.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:47:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
#define __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#include <vector>
namespace framework
{
class StatusIndicatorInterfaceWrapper : public ::com::sun::star::lang::XTypeProvider ,
public ::com::sun::star::task::XStatusIndicator ,
public ::cppu::OWeakObject
{
public:
StatusIndicatorInterfaceWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& rStatusIndicatorImpl );
virtual ~StatusIndicatorInterfaceWrapper();
//---------------------------------------------------------------------------------------------------------
// XInterface, XTypeProvider
//---------------------------------------------------------------------------------------------------------
DECLARE_XINTERFACE
DECLARE_XTYPEPROVIDER
//---------------------------------------------------------------------------------------------------------
// XStatusIndicator
//---------------------------------------------------------------------------------------------------------
virtual void SAL_CALL start ( const ::rtl::OUString& sText ,
sal_Int32 nRange ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL end ( ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL reset ( ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setText ( const ::rtl::OUString& sText ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setValue( sal_Int32 nValue ) throw( ::com::sun::star::uno::RuntimeException );
private:
StatusIndicatorInterfaceWrapper();
::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XComponent > m_xStatusIndicatorImpl;
};
}
#endif // __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
<commit_msg>INTEGRATION: CWS warnings01 (1.3.32); FILE MERGED 2005/10/28 14:48:22 cd 1.3.32.1: #i55991# Warning free code changes for gcc<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: statusindicatorinterfacewrapper.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:05: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 __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
#define __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _RTL_OUSTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#include <vector>
namespace framework
{
class StatusIndicatorInterfaceWrapper : public ::com::sun::star::lang::XTypeProvider ,
public ::com::sun::star::task::XStatusIndicator ,
public ::cppu::OWeakObject
{
public:
StatusIndicatorInterfaceWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& rStatusIndicatorImpl );
virtual ~StatusIndicatorInterfaceWrapper();
//---------------------------------------------------------------------------------------------------------
// XInterface, XTypeProvider
//---------------------------------------------------------------------------------------------------------
FWK_DECLARE_XINTERFACE
FWK_DECLARE_XTYPEPROVIDER
//---------------------------------------------------------------------------------------------------------
// XStatusIndicator
//---------------------------------------------------------------------------------------------------------
virtual void SAL_CALL start ( const ::rtl::OUString& sText ,
sal_Int32 nRange ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL end ( ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL reset ( ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setText ( const ::rtl::OUString& sText ) throw( ::com::sun::star::uno::RuntimeException );
virtual void SAL_CALL setValue( sal_Int32 nValue ) throw( ::com::sun::star::uno::RuntimeException );
private:
StatusIndicatorInterfaceWrapper();
::com::sun::star::uno::WeakReference< ::com::sun::star::lang::XComponent > m_xStatusIndicatorImpl;
};
}
#endif // __FRAMEWORK_UIELEMENT_STATUSINDICATORINTERFACEWRAPPER_HXX_
<|endoftext|>
|
<commit_before>// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.
#include "slave/slave_file_thread.h"
#include "base/bind.h"
#include "common/options.h"
#include "thread/ninja_thread.h"
namespace {
static bool g_should_quit_pool = false;
} // namespace
namespace slave {
// static
void SlaveFileThread::QuitPool() {
DCHECK(NinjaThread::CurrentlyOn(NinjaThread::FILE));
g_should_quit_pool = true;
}
SlaveFileThread::SlaveFileThread()
: weak_factory_(this) {
NinjaThread::SetDelegate(NinjaThread::FILE, this);
}
SlaveFileThread::~SlaveFileThread() {
NinjaThread::SetDelegate(NinjaThread::FILE, NULL);
}
void SlaveFileThread::Init() {
server_ = mg_create_server(NULL, NULL);
mg_set_option(server_, "document_root", "."); // Serve current directory
CHECK(mg_set_option(server_, "listening_port", options::kMongooseServerPort))
<< "Failed to set listening_port option with value "
<< options::kMongooseServerPort;
}
void SlaveFileThread::InitAsync() {
NinjaThread::PostTask(
NinjaThread::FILE,
FROM_HERE,
base::Bind(&SlaveFileThread::PoolMongooseServer,
weak_factory_.GetWeakPtr()));
}
void SlaveFileThread::CleanUp() {
mg_destroy_server(&server_);
}
void SlaveFileThread::PoolMongooseServer() {
if (g_should_quit_pool)
return;
mg_poll_server(server_, 1000);
NinjaThread::PostTask(
NinjaThread::FILE,
FROM_HERE,
base::Bind(&SlaveFileThread::PoolMongooseServer,
weak_factory_.GetWeakPtr()));
}
} // namespace slave
<commit_msg>[Slave] mg_set_option() returns NULL if option was set successfully.<commit_after>// Copyright (c) 2015 Chaobin Zhang. All rights reserved.
// Use of this source code is governed by the BSD license that can be
// found in the LICENSE file.
#include "slave/slave_file_thread.h"
#include "base/bind.h"
#include "common/options.h"
#include "thread/ninja_thread.h"
namespace {
static bool g_should_quit_pool = false;
} // namespace
namespace slave {
// static
void SlaveFileThread::QuitPool() {
DCHECK(NinjaThread::CurrentlyOn(NinjaThread::FILE));
g_should_quit_pool = true;
}
SlaveFileThread::SlaveFileThread()
: weak_factory_(this) {
NinjaThread::SetDelegate(NinjaThread::FILE, this);
}
SlaveFileThread::~SlaveFileThread() {
NinjaThread::SetDelegate(NinjaThread::FILE, NULL);
}
void SlaveFileThread::Init() {
server_ = mg_create_server(NULL, NULL);
mg_set_option(server_, "document_root", "."); // Serve current directory
CHECK(mg_set_option(server_, "listening_port",
options::kMongooseServerPort) == NULL)
<< "Failed to set listening_port option with value "
<< options::kMongooseServerPort;
}
void SlaveFileThread::InitAsync() {
NinjaThread::PostTask(
NinjaThread::FILE,
FROM_HERE,
base::Bind(&SlaveFileThread::PoolMongooseServer,
weak_factory_.GetWeakPtr()));
}
void SlaveFileThread::CleanUp() {
mg_destroy_server(&server_);
}
void SlaveFileThread::PoolMongooseServer() {
if (g_should_quit_pool)
return;
mg_poll_server(server_, 1000);
NinjaThread::PostTask(
NinjaThread::FILE,
FROM_HERE,
base::Bind(&SlaveFileThread::PoolMongooseServer,
weak_factory_.GetWeakPtr()));
}
} // namespace slave
<|endoftext|>
|
<commit_before>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<TargetData>();
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
const std::set<Function*> &SCCFunctions,
const TargetData &TD) {
Function *Callee = CS.getCalledFunction();
if (!InlineFunction(CS, &CG, &TD)) return false;
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && Callee->hasInternalLinkage() &&
!SCCFunctions.count(Callee)) {
DOUT << " -> Deleting dead function: " << Callee->getName() << "\n";
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DOUT << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction();
return true;
}
if (IC.isNever()) {
DOUT << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction();
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration()
&& Fn->hasFnAttr(Attribute::OptimizeForSize)
&& InlineThreshold != 50) {
CurrentThreshold = 50;
}
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DOUT << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return false;
} else {
DOUT << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
std::set<Function*> SCCFunctions;
DOUT << "Inliner visiting SCC:";
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DOUT << " " << (F ? F->getName() : "INDIRECTNODE");
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && (!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DOUT << ": " << CallSites.size() << " call sites.\n";
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration() ||
CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions,
getAnalysis<TargetData>())) {
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<commit_msg>If the function being inlined has a higher stack protection level than the inlining function, then increase the stack protection level on the inlining function.<commit_after>//===- Inliner.cpp - Code common to all inliners --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the mechanics required to implement inlining without
// missing any calls and updating the call graph. The decisions of which calls
// are profitable to inline are implemented elsewhere.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "inline"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/IPO/InlinerPass.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(NumInlined, "Number of functions inlined");
STATISTIC(NumDeleted, "Number of functions deleted because all callers found");
static cl::opt<int>
InlineLimit("inline-threshold", cl::Hidden, cl::init(200),
cl::desc("Control the amount of inlining to perform (default = 200)"));
Inliner::Inliner(void *ID)
: CallGraphSCCPass(ID), InlineThreshold(InlineLimit) {}
Inliner::Inliner(void *ID, int Threshold)
: CallGraphSCCPass(ID), InlineThreshold(Threshold) {}
/// getAnalysisUsage - For this class, we declare that we require and preserve
/// the call graph. If the derived class implements this method, it should
/// always explicitly call the implementation here.
void Inliner::getAnalysisUsage(AnalysisUsage &Info) const {
Info.addRequired<TargetData>();
CallGraphSCCPass::getAnalysisUsage(Info);
}
// InlineCallIfPossible - If it is possible to inline the specified call site,
// do so and update the CallGraph for this operation.
static bool InlineCallIfPossible(CallSite CS, CallGraph &CG,
const std::set<Function*> &SCCFunctions,
const TargetData &TD) {
Function *Callee = CS.getCalledFunction();
if (!InlineFunction(CS, &CG, &TD)) return false;
// If the inlined function had a higher stack protection level than the
// calling function, then bump up the caller's stack protection level.
Function *Caller = CS.getCaller();
if (Callee->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtectReq);
else if (Callee->hasFnAttr(Attribute::StackProtect) &&
!Caller->hasFnAttr(Attribute::StackProtectReq))
Caller->addFnAttr(Attribute::StackProtect);
// If we inlined the last possible call site to the function, delete the
// function body now.
if (Callee->use_empty() && Callee->hasInternalLinkage() &&
!SCCFunctions.count(Callee)) {
DOUT << " -> Deleting dead function: " << Callee->getName() << "\n";
CallGraphNode *CalleeNode = CG[Callee];
// Remove any call graph edges from the callee to its callees.
CalleeNode->removeAllCalledFunctions();
// Removing the node for callee from the call graph and delete it.
delete CG.removeFunctionFromModule(CalleeNode);
++NumDeleted;
}
return true;
}
/// shouldInline - Return true if the inliner should attempt to inline
/// at the given CallSite.
bool Inliner::shouldInline(CallSite CS) {
InlineCost IC = getInlineCost(CS);
float FudgeFactor = getInlineFudgeFactor(CS);
if (IC.isAlways()) {
DOUT << " Inlining: cost=always"
<< ", Call: " << *CS.getInstruction();
return true;
}
if (IC.isNever()) {
DOUT << " NOT Inlining: cost=never"
<< ", Call: " << *CS.getInstruction();
return false;
}
int Cost = IC.getValue();
int CurrentThreshold = InlineThreshold;
Function *Fn = CS.getCaller();
if (Fn && !Fn->isDeclaration()
&& Fn->hasFnAttr(Attribute::OptimizeForSize)
&& InlineThreshold != 50) {
CurrentThreshold = 50;
}
if (Cost >= (int)(CurrentThreshold * FudgeFactor)) {
DOUT << " NOT Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return false;
} else {
DOUT << " Inlining: cost=" << Cost
<< ", Call: " << *CS.getInstruction();
return true;
}
}
bool Inliner::runOnSCC(const std::vector<CallGraphNode*> &SCC) {
CallGraph &CG = getAnalysis<CallGraph>();
std::set<Function*> SCCFunctions;
DOUT << "Inliner visiting SCC:";
for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
Function *F = SCC[i]->getFunction();
if (F) SCCFunctions.insert(F);
DOUT << " " << (F ? F->getName() : "INDIRECTNODE");
}
// Scan through and identify all call sites ahead of time so that we only
// inline call sites in the original functions, not call sites that result
// from inlining other functions.
std::vector<CallSite> CallSites;
for (unsigned i = 0, e = SCC.size(); i != e; ++i)
if (Function *F = SCC[i]->getFunction())
for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
CallSite CS = CallSite::get(I);
if (CS.getInstruction() && (!CS.getCalledFunction() ||
!CS.getCalledFunction()->isDeclaration()))
CallSites.push_back(CS);
}
DOUT << ": " << CallSites.size() << " call sites.\n";
// Now that we have all of the call sites, move the ones to functions in the
// current SCC to the end of the list.
unsigned FirstCallInSCC = CallSites.size();
for (unsigned i = 0; i < FirstCallInSCC; ++i)
if (Function *F = CallSites[i].getCalledFunction())
if (SCCFunctions.count(F))
std::swap(CallSites[i--], CallSites[--FirstCallInSCC]);
// Now that we have all of the call sites, loop over them and inline them if
// it looks profitable to do so.
bool Changed = false;
bool LocalChange;
do {
LocalChange = false;
// Iterate over the outer loop because inlining functions can cause indirect
// calls to become direct calls.
for (unsigned CSi = 0; CSi != CallSites.size(); ++CSi)
if (Function *Callee = CallSites[CSi].getCalledFunction()) {
// Calls to external functions are never inlinable.
if (Callee->isDeclaration() ||
CallSites[CSi].getInstruction()->getParent()->getParent() ==Callee){
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
// Keep the 'in SCC / not in SCC' boundary correct.
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
continue;
}
// If the policy determines that we should inline this function,
// try to do so.
CallSite CS = CallSites[CSi];
if (shouldInline(CS)) {
// Attempt to inline the function...
if (InlineCallIfPossible(CS, CG, SCCFunctions,
getAnalysis<TargetData>())) {
// Remove this call site from the list. If possible, use
// swap/pop_back for efficiency, but do not use it if doing so would
// move a call site to a function in this SCC before the
// 'FirstCallInSCC' barrier.
if (SCC.size() == 1) {
std::swap(CallSites[CSi], CallSites.back());
CallSites.pop_back();
} else {
CallSites.erase(CallSites.begin()+CSi);
}
--CSi;
++NumInlined;
Changed = true;
LocalChange = true;
}
}
}
} while (LocalChange);
return Changed;
}
// doFinalization - Remove now-dead linkonce functions at the end of
// processing to avoid breaking the SCC traversal.
bool Inliner::doFinalization(CallGraph &CG) {
return removeDeadFunctions(CG);
}
/// removeDeadFunctions - Remove dead functions that are not included in
/// DNR (Do Not Remove) list.
bool Inliner::removeDeadFunctions(CallGraph &CG,
SmallPtrSet<const Function *, 16> *DNR) {
std::set<CallGraphNode*> FunctionsToRemove;
// Scan for all of the functions, looking for ones that should now be removed
// from the program. Insert the dead ones in the FunctionsToRemove set.
for (CallGraph::iterator I = CG.begin(), E = CG.end(); I != E; ++I) {
CallGraphNode *CGN = I->second;
if (Function *F = CGN ? CGN->getFunction() : 0) {
// If the only remaining users of the function are dead constants, remove
// them.
F->removeDeadConstantUsers();
if (DNR && DNR->count(F))
continue;
if ((F->hasLinkOnceLinkage() || F->hasInternalLinkage()) &&
F->use_empty()) {
// Remove any call graph edges from the function to its callees.
CGN->removeAllCalledFunctions();
// Remove any edges from the external node to the function's call graph
// node. These edges might have been made irrelegant due to
// optimization of the program.
CG.getExternalCallingNode()->removeAnyCallEdgeTo(CGN);
// Removing the node for callee from the call graph and delete it.
FunctionsToRemove.insert(CGN);
}
}
}
// Now that we know which functions to delete, do so. We didn't want to do
// this inline, because that would invalidate our CallGraph::iterator
// objects. :(
bool Changed = false;
for (std::set<CallGraphNode*>::iterator I = FunctionsToRemove.begin(),
E = FunctionsToRemove.end(); I != E; ++I) {
delete CG.removeFunctionFromModule(*I);
++NumDeleted;
Changed = true;
}
return Changed;
}
<|endoftext|>
|
<commit_before>//// License: Apache 2.0. See LICENSE file in root directory.
//// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "ds5-private.h"
using namespace std;
#define intrinsics_string(res) #res << "\t" << array2str((float_4&)table->rect_params[res]) << endl
namespace librealsense
{
namespace ds
{
ds5_rect_resolutions width_height_to_ds5_rect_resolutions(uint32_t width, uint32_t height)
{
for (auto& elem : resolutions_list)
{
if (elem.second.x == width && elem.second.y == height)
return elem.first;
}
throw invalid_value_exception("resolution not found.");
}
rs2_intrinsics get_intrinsic_by_resolution_coefficients_table(const std::vector<uint8_t> & raw_data, uint32_t width, uint32_t height, uint32_t fps)
{
auto table = check_calib<ds::coefficients_table>(raw_data);
LOG_DEBUG(endl
<< "baseline = " << table->baseline << " mm" << endl
<< "Rect params: \t fX\t\t fY\t\t ppX\t\t ppY \n"
<< intrinsics_string(res_1920_1080)
<< intrinsics_string(res_1280_720)
<< intrinsics_string(res_640_480)
<< intrinsics_string(res_848_480)
<< intrinsics_string(res_424_240)
<< intrinsics_string(res_640_360)
<< intrinsics_string(res_320_240)
<< intrinsics_string(res_480_270)
<< intrinsics_string(res_1280_800)
<< intrinsics_string(res_960_540));
auto resolution = width_height_to_ds5_rect_resolutions(width, width == 848 && height == 100 ? 480 : height);
rs2_intrinsics intrinsics;
intrinsics.width = resolutions_list[resolution].x;
intrinsics.height = resolutions_list[resolution].y;
try
{
auto resolution = width_height_to_ds5_rect_resolutions(width, width == 848 && height == 100 ? 480 : height);
rs2_intrinsics intrinsics;
intrinsics.width = resolutions_list[resolution].x;
intrinsics.height = resolutions_list[resolution].y;
auto rect_params = static_cast<const float4>(table->rect_params[resolution]);
// DS5U - assume ideal intrinsic params
if ((rect_params.x == rect_params.y) && (rect_params.z == rect_params.w))
{
rect_params.x = rect_params.y = intrinsics.width * 1.5f;
rect_params.z = intrinsics.width * 0.5f;
rect_params.w = intrinsics.height * 0.5f;
}
intrinsics.fx = rect_params[0];
intrinsics.fy = rect_params[1];
intrinsics.ppx = rect_params[2];
intrinsics.ppy = rect_params[3];
intrinsics.model = RS2_DISTORTION_BROWN_CONRADY;
+memset(intrinsics.coeffs, 0, sizeof(intrinsics.coeffs)); // All coefficients are zeroed since rectified depth is defined as CS origin
if (width == 848 && height == 100)
{
intrinsics.height = 100;
if (fps <= 90)
intrinsics.ppy -= 190;
}
return intrinsics;
}
catch (...)
{
ds5_rect_resolutions resolution = res_1920_1080;
rs2_intrinsics intrinsics;
intrinsics.width = width;
intrinsics.height = height;
auto rect_params = static_cast<const float4>(table->rect_params[resolution]);
// DS5U - assume ideal intrinsic params
if ((rect_params.x == rect_params.y) && (rect_params.z == rect_params.w))
{
rect_params.x = rect_params.y = intrinsics.width * 1.5f;
rect_params.z = intrinsics.width * 0.5f;
rect_params.w = intrinsics.height * 0.5f;
}
intrinsics.fx = rect_params[0] * width / resolutions_list[resolution].x;
intrinsics.fy = rect_params[1] * height / resolutions_list[resolution].y;
intrinsics.ppx = rect_params[2] * width / resolutions_list[resolution].x;
intrinsics.ppy = rect_params[3] * height / resolutions_list[resolution].y;
intrinsics.model = RS2_DISTORTION_BROWN_CONRADY;
memset(intrinsics.coeffs, 0, sizeof(intrinsics.coeffs)); // All coefficients are zeroed since rectified depth is defined as CS origin
return intrinsics;
}
}
rs2_intrinsics get_intrinsic_fisheye_table(const std::vector<uint8_t>& raw_data, uint32_t width, uint32_t height)
{
auto table = check_calib<ds::fisheye_calibration_table>(raw_data);
rs2_intrinsics intrinsics;
auto intrin = table->intrinsic;
intrinsics.fx = intrin(0,0);
intrinsics.fy = intrin(1,1);
intrinsics.ppx = intrin(2,0);
intrinsics.ppy = intrin(2,1);
intrinsics.model = RS2_DISTORTION_FTHETA;
intrinsics.height = height;
intrinsics.width = width;
librealsense::copy(intrinsics.coeffs, table->distortion, sizeof(table->distortion));
LOG_DEBUG(endl<< array2str((float_4&)(intrinsics.fx, intrinsics.fy, intrinsics.ppx, intrinsics.ppy)) << endl);
return intrinsics;
}
rs2_intrinsics get_color_stream_intrinsic(const std::vector<uint8_t>& raw_data, uint32_t width, uint32_t height)
{
auto table = check_calib<ds::rgb_calibration_table>(raw_data);
// Compensate for aspect ratio as the normalized intrinsic is calculated with 16/9 factor
float3x3 intrin = table->intrinsic;
static const float base_aspect_ratio_factor = 16.f / 9.f;
// Compensate for aspect ratio
intrin(0, 0) *= base_aspect_ratio_factor * (height / (float)width);
intrin(2, 0) *= base_aspect_ratio_factor * (height / (float)width);
// Calculate specific intrinsic parameters based on the normalized intrinsic and the sensor's resolution
rs2_intrinsics calc_intrinsic{
static_cast<int>(width),
static_cast<int>(height),
((1 + intrin(2, 0))*width) / 2.f,
((1 + intrin(2, 1))*height) / 2.f,
intrin(0, 0) * width / 2.f,
intrin(1, 1) * height / 2.f,
RS2_DISTORTION_BROWN_CONRADY
};
librealsense::copy(calc_intrinsic.coeffs, table->distortion, sizeof(table->distortion));
LOG_DEBUG(endl << array2str((float_4&)(calc_intrinsic.fx, calc_intrinsic.fy, calc_intrinsic.ppx, calc_intrinsic.ppy)) << endl);
return calc_intrinsic;
}
rs2_intrinsics get_intrinsic_by_resolution(const vector<uint8_t> & raw_data, calibration_table_id table_id, uint32_t width, uint32_t height, uint32_t fps)
{
switch (table_id)
{
case coefficients_table_id:
{
return get_intrinsic_by_resolution_coefficients_table(raw_data, width, height, fps);
}
case fisheye_calibration_id:
{
return get_intrinsic_fisheye_table(raw_data, width, height);
}
case rgb_calibration_id:
{
return get_color_stream_intrinsic(raw_data, width, height);
}
default:
throw invalid_value_exception(to_string() << "Parsing Calibration table type " << table_id << " is not supported");
}
}
pose get_fisheye_extrinsics_data(const vector<uint8_t> & raw_data)
{
auto table = check_calib<fisheye_extrinsics_table>(raw_data);
auto rot = table->rotation;
auto trans = table->translation;
pose ex = {{rot(0,0), rot(1,0),rot(2,0),rot(1,0), rot(1,1),rot(2,1),rot(0,2), rot(1,2),rot(2,2)},
{trans[0], trans[1], trans[2]}};
return ex;
}
pose get_color_stream_extrinsic(const std::vector<uint8_t>& raw_data)
{
auto table = check_calib<rgb_calibration_table>(raw_data);
float3 trans_vector = table->translation_rect;
float3x3 rect_rot_mat = table->rotation_matrix_rect;
float trans_scale = 0.001f; // Convert units from mm to meter
if (table->translation.x > 0.f) // Extrinsic of color is referenced to the Depth Sensor CS
{
trans_scale *= -1;
}
trans_vector.x *= trans_scale;
trans_vector.y *= trans_scale;
trans_vector.z *= trans_scale;
return{ rect_rot_mat,trans_vector };
}
bool try_fetch_usb_device(std::vector<platform::usb_device_info>& devices,
const platform::uvc_device_info& info, platform::usb_device_info& result)
{
for (auto it = devices.begin(); it != devices.end(); ++it)
{
if (it->unique_id == info.unique_id)
{
bool found = false;
result = *it;
switch (info.pid)
{
case RS_USB2_PID:
case RS400_PID:
case RS405_PID:
case RS410_PID:
case RS460_PID:
case RS430_PID:
case RS420_PID:
case RS400_IMU_PID:
found = (result.mi == 3);
break;
case RS430_MM_PID:
case RS420_MM_PID:
case RS435I_PID:
found = (result.mi == 6);
break;
case RS415_PID:
case RS435_RGB_PID:
found = (result.mi == 5);
break;
default:
throw not_implemented_exception(to_string() << "USB device "
<< std::hex << info.pid << ":" << info.vid << std::dec << " is not supported.");
break;
}
if (found)
{
devices.erase(it);
return true;
}
}
}
return false;
}
std::vector<platform::uvc_device_info> filter_device_by_capability(const std::vector<platform::uvc_device_info>& devices,
d400_caps caps)
{
std::vector<platform::uvc_device_info> results;
switch (caps)
{
case d400_caps::CAP_FISHEYE_SENSOR:
std::copy_if(devices.begin(),devices.end(),std::back_inserter(results),
[](const platform::uvc_device_info& info)
{ return fisheye_pid.find(info.pid) != fisheye_pid.end();});
break;
default:
throw invalid_value_exception(to_string()
<< "Capability filters are not implemented for val "
<< std::hex << caps << std::dec);
}
return results;
}
} // librealsense::ds
} // namespace librealsense
<commit_msg>Code update based on recommendations.<commit_after>//// License: Apache 2.0. See LICENSE file in root directory.
//// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "ds5-private.h"
using namespace std;
#define intrinsics_string(res) #res << "\t" << array2str((float_4&)table->rect_params[res]) << endl
namespace librealsense
{
namespace ds
{
ds5_rect_resolutions width_height_to_ds5_rect_resolutions(uint32_t width, uint32_t height)
{
for (auto& elem : resolutions_list)
{
if (elem.second.x == width && elem.second.y == height)
return elem.first;
}
return max_ds5_rect_resolutions;
}
rs2_intrinsics get_intrinsic_by_resolution_coefficients_table(const std::vector<uint8_t> & raw_data, uint32_t width, uint32_t height, uint32_t fps)
{
auto table = check_calib<ds::coefficients_table>(raw_data);
LOG_DEBUG(endl
<< "baseline = " << table->baseline << " mm" << endl
<< "Rect params: \t fX\t\t fY\t\t ppX\t\t ppY \n"
<< intrinsics_string(res_1920_1080)
<< intrinsics_string(res_1280_720)
<< intrinsics_string(res_640_480)
<< intrinsics_string(res_848_480)
<< intrinsics_string(res_424_240)
<< intrinsics_string(res_640_360)
<< intrinsics_string(res_320_240)
<< intrinsics_string(res_480_270)
<< intrinsics_string(res_1280_800)
<< intrinsics_string(res_960_540));
auto resolution = width_height_to_ds5_rect_resolutions(width, width == 848 && height == 100 ? 480 : height);
if (resolution < max_ds5_rect_resolutions)
{
rs2_intrinsics intrinsics;
intrinsics.width = resolutions_list[resolution].x;
intrinsics.height = resolutions_list[resolution].y;
auto rect_params = static_cast<const float4>(table->rect_params[resolution]);
// DS5U - assume ideal intrinsic params
if ((rect_params.x == rect_params.y) && (rect_params.z == rect_params.w))
{
rect_params.x = rect_params.y = intrinsics.width * 1.5f;
rect_params.z = intrinsics.width * 0.5f;
rect_params.w = intrinsics.height * 0.5f;
}
intrinsics.fx = rect_params[0];
intrinsics.fy = rect_params[1];
intrinsics.ppx = rect_params[2];
intrinsics.ppy = rect_params[3];
intrinsics.model = RS2_DISTORTION_BROWN_CONRADY;
+memset(intrinsics.coeffs, 0, sizeof(intrinsics.coeffs)); // All coefficients are zeroed since rectified depth is defined as CS origin
if (width == 848 && height == 100)
{
intrinsics.height = 100;
if (fps <= 90)
intrinsics.ppy -= 190;
}
return intrinsics;
}
else
{
ds5_rect_resolutions resolution = res_1920_1080;
rs2_intrinsics intrinsics;
intrinsics.width = width;
intrinsics.height = height;
auto rect_params = static_cast<const float4>(table->rect_params[resolution]);
// DS5U - assume ideal intrinsic params
if ((rect_params.x == rect_params.y) && (rect_params.z == rect_params.w))
{
rect_params.x = rect_params.y = intrinsics.width * 1.5f;
rect_params.z = intrinsics.width * 0.5f;
rect_params.w = intrinsics.height * 0.5f;
}
intrinsics.fx = rect_params[0] * width / resolutions_list[resolution].x;
intrinsics.fy = rect_params[1] * height / resolutions_list[resolution].y;
intrinsics.ppx = rect_params[2] * width / resolutions_list[resolution].x;
intrinsics.ppy = rect_params[3] * height / resolutions_list[resolution].y;
intrinsics.model = RS2_DISTORTION_BROWN_CONRADY;
memset(intrinsics.coeffs, 0, sizeof(intrinsics.coeffs)); // All coefficients are zeroed since rectified depth is defined as CS origin
return intrinsics;
}
}
rs2_intrinsics get_intrinsic_fisheye_table(const std::vector<uint8_t>& raw_data, uint32_t width, uint32_t height)
{
auto table = check_calib<ds::fisheye_calibration_table>(raw_data);
rs2_intrinsics intrinsics;
auto intrin = table->intrinsic;
intrinsics.fx = intrin(0,0);
intrinsics.fy = intrin(1,1);
intrinsics.ppx = intrin(2,0);
intrinsics.ppy = intrin(2,1);
intrinsics.model = RS2_DISTORTION_FTHETA;
intrinsics.height = height;
intrinsics.width = width;
librealsense::copy(intrinsics.coeffs, table->distortion, sizeof(table->distortion));
LOG_DEBUG(endl<< array2str((float_4&)(intrinsics.fx, intrinsics.fy, intrinsics.ppx, intrinsics.ppy)) << endl);
return intrinsics;
}
rs2_intrinsics get_color_stream_intrinsic(const std::vector<uint8_t>& raw_data, uint32_t width, uint32_t height)
{
auto table = check_calib<ds::rgb_calibration_table>(raw_data);
// Compensate for aspect ratio as the normalized intrinsic is calculated with 16/9 factor
float3x3 intrin = table->intrinsic;
static const float base_aspect_ratio_factor = 16.f / 9.f;
// Compensate for aspect ratio
intrin(0, 0) *= base_aspect_ratio_factor * (height / (float)width);
intrin(2, 0) *= base_aspect_ratio_factor * (height / (float)width);
// Calculate specific intrinsic parameters based on the normalized intrinsic and the sensor's resolution
rs2_intrinsics calc_intrinsic{
static_cast<int>(width),
static_cast<int>(height),
((1 + intrin(2, 0))*width) / 2.f,
((1 + intrin(2, 1))*height) / 2.f,
intrin(0, 0) * width / 2.f,
intrin(1, 1) * height / 2.f,
RS2_DISTORTION_BROWN_CONRADY
};
librealsense::copy(calc_intrinsic.coeffs, table->distortion, sizeof(table->distortion));
LOG_DEBUG(endl << array2str((float_4&)(calc_intrinsic.fx, calc_intrinsic.fy, calc_intrinsic.ppx, calc_intrinsic.ppy)) << endl);
return calc_intrinsic;
}
rs2_intrinsics get_intrinsic_by_resolution(const vector<uint8_t> & raw_data, calibration_table_id table_id, uint32_t width, uint32_t height, uint32_t fps)
{
switch (table_id)
{
case coefficients_table_id:
{
return get_intrinsic_by_resolution_coefficients_table(raw_data, width, height, fps);
}
case fisheye_calibration_id:
{
return get_intrinsic_fisheye_table(raw_data, width, height);
}
case rgb_calibration_id:
{
return get_color_stream_intrinsic(raw_data, width, height);
}
default:
throw invalid_value_exception(to_string() << "Parsing Calibration table type " << table_id << " is not supported");
}
}
pose get_fisheye_extrinsics_data(const vector<uint8_t> & raw_data)
{
auto table = check_calib<fisheye_extrinsics_table>(raw_data);
auto rot = table->rotation;
auto trans = table->translation;
pose ex = {{rot(0,0), rot(1,0),rot(2,0),rot(1,0), rot(1,1),rot(2,1),rot(0,2), rot(1,2),rot(2,2)},
{trans[0], trans[1], trans[2]}};
return ex;
}
pose get_color_stream_extrinsic(const std::vector<uint8_t>& raw_data)
{
auto table = check_calib<rgb_calibration_table>(raw_data);
float3 trans_vector = table->translation_rect;
float3x3 rect_rot_mat = table->rotation_matrix_rect;
float trans_scale = 0.001f; // Convert units from mm to meter
if (table->translation.x > 0.f) // Extrinsic of color is referenced to the Depth Sensor CS
{
trans_scale *= -1;
}
trans_vector.x *= trans_scale;
trans_vector.y *= trans_scale;
trans_vector.z *= trans_scale;
return{ rect_rot_mat,trans_vector };
}
bool try_fetch_usb_device(std::vector<platform::usb_device_info>& devices,
const platform::uvc_device_info& info, platform::usb_device_info& result)
{
for (auto it = devices.begin(); it != devices.end(); ++it)
{
if (it->unique_id == info.unique_id)
{
bool found = false;
result = *it;
switch (info.pid)
{
case RS_USB2_PID:
case RS400_PID:
case RS405_PID:
case RS410_PID:
case RS460_PID:
case RS430_PID:
case RS420_PID:
case RS400_IMU_PID:
found = (result.mi == 3);
break;
case RS430_MM_PID:
case RS420_MM_PID:
case RS435I_PID:
found = (result.mi == 6);
break;
case RS415_PID:
case RS435_RGB_PID:
found = (result.mi == 5);
break;
default:
throw not_implemented_exception(to_string() << "USB device "
<< std::hex << info.pid << ":" << info.vid << std::dec << " is not supported.");
break;
}
if (found)
{
devices.erase(it);
return true;
}
}
}
return false;
}
std::vector<platform::uvc_device_info> filter_device_by_capability(const std::vector<platform::uvc_device_info>& devices,
d400_caps caps)
{
std::vector<platform::uvc_device_info> results;
switch (caps)
{
case d400_caps::CAP_FISHEYE_SENSOR:
std::copy_if(devices.begin(),devices.end(),std::back_inserter(results),
[](const platform::uvc_device_info& info)
{ return fisheye_pid.find(info.pid) != fisheye_pid.end();});
break;
default:
throw invalid_value_exception(to_string()
<< "Capability filters are not implemented for val "
<< std::hex << caps << std::dec);
}
return results;
}
} // librealsense::ds
} // namespace librealsense
<|endoftext|>
|
<commit_before>//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
//
// This file implements "aggressive" dead code elimination. ADCE is DCe where
// values are assumed to be dead until proven otherwise. This is similar to
// SCCP, except applied to the liveness of values.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/Writer.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Support/CFG.h"
#include "Support/STLExtras.h"
#include "Support/DepthFirstIterator.h"
#include <algorithm>
#include <iostream>
using std::cerr;
#define DEBUG_ADCE 1
namespace {
//===----------------------------------------------------------------------===//
// ADCE Class
//
// This class does all of the work of Aggressive Dead Code Elimination.
// It's public interface consists of a constructor and a doADCE() method.
//
class ADCE : public FunctionPass {
Function *Func; // The function that we are working on
std::vector<Instruction*> WorkList; // Instructions that just became live
std::set<Instruction*> LiveSet; // The set of live instructions
bool MadeChanges;
//===--------------------------------------------------------------------===//
// The public interface for this class
//
public:
const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
// doADCE - Execute the Aggressive Dead Code Elimination Algorithm
//
virtual bool runOnFunction(Function *F) {
Func = F; MadeChanges = false;
doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
assert(WorkList.empty());
LiveSet.clear();
return MadeChanges;
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(DominanceFrontier::PostDomID);
}
//===--------------------------------------------------------------------===//
// The implementation of this class
//
private:
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void doADCE(DominanceFrontier &CDG);
inline void markInstructionLive(Instruction *I) {
if (LiveSet.count(I)) return;
#ifdef DEBUG_ADCE
cerr << "Insn Live: " << I;
#endif
LiveSet.insert(I);
WorkList.push_back(I);
}
inline void markTerminatorLive(const BasicBlock *BB) {
#ifdef DEBUG_ADCE
cerr << "Terminat Live: " << BB->getTerminator();
#endif
markInstructionLive((Instruction*)BB->getTerminator());
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks.
//
BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks);
};
} // End of anonymous namespace
Pass *createAggressiveDCEPass() {
return new ADCE();
}
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void ADCE::doADCE(DominanceFrontier &CDG) {
#ifdef DEBUG_ADCE
cerr << "Function: " << Func;
#endif
// Iterate over all of the instructions in the function, eliminating trivially
// dead instructions, and marking instructions live that are known to be
// needed. Perform the walk in depth first order so that we avoid marking any
// instructions live in basic blocks that are unreachable. These blocks will
// be eliminated later, along with the instructions inside.
//
for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Instruction *I = *II;
if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
markInstructionLive(I);
++II; // Increment the inst iterator if the inst wasn't deleted
} else if (isInstructionTriviallyDead(I)) {
// Remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
} else {
++II; // Increment the inst iterator if the inst wasn't deleted
}
}
}
#ifdef DEBUG_ADCE
cerr << "Processing work list\n";
#endif
// AliveBlocks - Set of basic blocks that we know have instructions that are
// alive in them...
//
std::set<BasicBlock*> AliveBlocks;
// Process the work list of instructions that just became live... if they
// became live, then that means that all of their operands are neccesary as
// well... make them live as well.
//
while (!WorkList.empty()) {
Instruction *I = WorkList.back(); // Get an instruction that became live...
WorkList.pop_back();
BasicBlock *BB = I->getParent();
if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
// Mark the basic block as being newly ALIVE... and mark all branches that
// this block is control dependant on as being alive also...
//
AliveBlocks.insert(BB); // Block is now ALIVE!
DominanceFrontier::const_iterator It = CDG.find(BB);
if (It != CDG.end()) {
// Get the blocks that this node is control dependant on...
const DominanceFrontier::DomSetType &CDB = It->second;
for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
bind_obj(this, &ADCE::markTerminatorLive));
}
// If this basic block is live, then the terminator must be as well!
markTerminatorLive(BB);
}
// Loop over all of the operands of the live instruction, making sure that
// they are known to be alive as well...
//
for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
markInstructionLive(Operand);
}
#ifdef DEBUG_ADCE
cerr << "Current Function: X = Live\n";
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
BI != BE; ++BI) {
if (LiveSet.count(*BI)) cerr << "X ";
cerr << *BI;
}
#endif
// After the worklist is processed, recursively walk the CFG in depth first
// order, patching up references to dead blocks...
//
std::set<BasicBlock*> VisitedBlocks;
BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
if (EntryBlock && EntryBlock != Func->front()) {
// We need to move the new entry block to be the first bb of the function
Function::iterator EBI = find(Func->begin(), Func->end(), EntryBlock);
std::swap(*EBI, *Func->begin()); // Exchange old location with start of fn
while (PHINode *PN = dyn_cast<PHINode>(EntryBlock->front())) {
assert(PN->getNumIncomingValues() == 1 &&
"Can only have a single incoming value at this point...");
// The incoming value must be outside of the scope of the function, a
// global variable, constant or parameter maybe...
//
PN->replaceAllUsesWith(PN->getIncomingValue(0));
// Nuke the phi node...
delete EntryBlock->getInstList().remove(EntryBlock->begin());
}
}
// Now go through and tell dead blocks to drop all of their references so they
// can be safely deleted.
//
for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
BasicBlock *BB = *BI;
if (!AliveBlocks.count(BB)) {
BB->dropAllReferences();
}
}
// Now loop through all of the blocks and delete them. We can safely do this
// now because we know that there are no references to dead blocks (because
// they have dropped all of their references...
//
for (Function::iterator BI = Func->begin(); BI != Func->end();) {
if (!AliveBlocks.count(*BI)) {
delete Func->getBasicBlocks().remove(BI);
MadeChanges = true;
continue; // Don't increment iterator
}
++BI; // Increment iterator...
}
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks:
// If the BB is alive (in AliveBlocks):
// 1. Eliminate all dead instructions in the BB
// 2. Recursively traverse all of the successors of the BB:
// - If the returned successor is non-null, update our terminator to
// reference the returned BB
// 3. Return 0 (no update needed)
//
// If the BB is dead (not in AliveBlocks):
// 1. Add the BB to the dead set
// 2. Recursively traverse all of the successors of the block:
// - Only one shall return a nonnull value (or else this block should have
// been in the alive set).
// 3. Return the nonnull child, or 0 if no non-null children.
//
BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks) {
if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
VisitedBlocks.insert(BB); // We have now visited this node!
#ifdef DEBUG_ADCE
cerr << "Fixing up BB: " << BB;
#endif
if (AliveBlocks.count(BB)) { // Is the block alive?
// Yes it's alive: loop through and eliminate all dead instructions in block
for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; )
if (!LiveSet.count(*II)) { // Is this instruction alive?
// Nope... remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
} else {
++II;
}
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *Succ = *SI;
BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
if (Repl && Repl != Succ) { // We have to replace the successor
Succ->replaceAllUsesWith(Repl);
MadeChanges = true;
}
}
return BB;
} else { // Otherwise the block is dead...
BasicBlock *ReturnBB = 0; // Default to nothing live down here
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
if (RetBB) {
assert(ReturnBB == 0 && "One one live child allowed!");
ReturnBB = RetBB;
}
}
return ReturnBB; // Return the result of traversal
}
}
<commit_msg>Fix some bugs, straighten stuff out, more work needs to be done.<commit_after>//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
//
// This file implements "aggressive" dead code elimination. ADCE is DCe where
// values are assumed to be dead until proven otherwise. This is similar to
// SCCP, except applied to the liveness of values.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/Writer.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Support/CFG.h"
#include "Support/STLExtras.h"
#include "Support/DepthFirstIterator.h"
#include <algorithm>
#include <iostream>
using std::cerr;
#define DEBUG_ADCE 1
namespace {
//===----------------------------------------------------------------------===//
// ADCE Class
//
// This class does all of the work of Aggressive Dead Code Elimination.
// It's public interface consists of a constructor and a doADCE() method.
//
class ADCE : public FunctionPass {
Function *Func; // The function that we are working on
std::vector<Instruction*> WorkList; // Instructions that just became live
std::set<Instruction*> LiveSet; // The set of live instructions
bool MadeChanges;
//===--------------------------------------------------------------------===//
// The public interface for this class
//
public:
const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
// doADCE - Execute the Aggressive Dead Code Elimination Algorithm
//
virtual bool runOnFunction(Function *F) {
Func = F; MadeChanges = false;
doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
assert(WorkList.empty());
LiveSet.clear();
return MadeChanges;
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(DominanceFrontier::PostDomID);
}
//===--------------------------------------------------------------------===//
// The implementation of this class
//
private:
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void doADCE(DominanceFrontier &CDG);
inline void markInstructionLive(Instruction *I) {
if (LiveSet.count(I)) return;
#ifdef DEBUG_ADCE
cerr << "Insn Live: " << I;
#endif
LiveSet.insert(I);
WorkList.push_back(I);
}
inline void markTerminatorLive(const BasicBlock *BB) {
#ifdef DEBUG_ADCE
cerr << "Terminat Live: " << BB->getTerminator();
#endif
markInstructionLive((Instruction*)BB->getTerminator());
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks.
//
BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks);
};
} // End of anonymous namespace
Pass *createAggressiveDCEPass() {
return new ADCE();
}
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
void ADCE::doADCE(DominanceFrontier &CDG) {
#ifdef DEBUG_ADCE
cerr << "Function: " << Func;
#endif
// Iterate over all of the instructions in the function, eliminating trivially
// dead instructions, and marking instructions live that are known to be
// needed. Perform the walk in depth first order so that we avoid marking any
// instructions live in basic blocks that are unreachable. These blocks will
// be eliminated later, along with the instructions inside.
//
for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Instruction *I = *II;
if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
markInstructionLive(I);
++II; // Increment the inst iterator if the inst wasn't deleted
} else if (isInstructionTriviallyDead(I)) {
// Remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
} else {
++II; // Increment the inst iterator if the inst wasn't deleted
}
}
}
#ifdef DEBUG_ADCE
cerr << "Processing work list\n";
#endif
// AliveBlocks - Set of basic blocks that we know have instructions that are
// alive in them...
//
std::set<BasicBlock*> AliveBlocks;
// Process the work list of instructions that just became live... if they
// became live, then that means that all of their operands are neccesary as
// well... make them live as well.
//
while (!WorkList.empty()) {
Instruction *I = WorkList.back(); // Get an instruction that became live...
WorkList.pop_back();
BasicBlock *BB = I->getParent();
if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
// Mark the basic block as being newly ALIVE... and mark all branches that
// this block is control dependant on as being alive also...
//
AliveBlocks.insert(BB); // Block is now ALIVE!
DominanceFrontier::const_iterator It = CDG.find(BB);
if (It != CDG.end()) {
// Get the blocks that this node is control dependant on...
const DominanceFrontier::DomSetType &CDB = It->second;
for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
bind_obj(this, &ADCE::markTerminatorLive));
}
// If this basic block is live, then the terminator must be as well!
markTerminatorLive(BB);
}
// Loop over all of the operands of the live instruction, making sure that
// they are known to be alive as well...
//
for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
markInstructionLive(Operand);
}
#ifdef DEBUG_ADCE
cerr << "Current Function: X = Live\n";
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
BI != BE; ++BI) {
if (LiveSet.count(*BI)) cerr << "X ";
cerr << *BI;
}
#endif
// After the worklist is processed, recursively walk the CFG in depth first
// order, patching up references to dead blocks...
//
std::set<BasicBlock*> VisitedBlocks;
BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
// Now go through and tell dead blocks to drop all of their references so they
// can be safely deleted. Also, as we are doing so, if the block has
// successors that are still live (and that have PHI nodes in them), remove
// the entry for this block from the phi nodes.
//
for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
BasicBlock *BB = *BI;
if (!AliveBlocks.count(BB)) {
// Remove entries from successors PHI nodes if they are still alive...
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
if (AliveBlocks.count(*SI)) { // Only if the successor is alive...
BasicBlock *Succ = *SI;
for (BasicBlock::iterator I = Succ->begin();// Loop over all PHI nodes
PHINode *PN = dyn_cast<PHINode>(*I); ++I)
PN->removeIncomingValue(BB); // Remove value for this block
}
BB->dropAllReferences();
}
}
cerr << "Before Deleting Blocks: " << Func;
// Now loop through all of the blocks and delete them. We can safely do this
// now because we know that there are no references to dead blocks (because
// they have dropped all of their references...
//
for (Function::iterator BI = Func->begin(); BI != Func->end();) {
if (!AliveBlocks.count(*BI)) {
delete Func->getBasicBlocks().remove(BI);
MadeChanges = true;
continue; // Don't increment iterator
}
++BI; // Increment iterator...
}
if (EntryBlock && EntryBlock != Func->front()) {
// We need to move the new entry block to be the first bb of the function
Function::iterator EBI = find(Func->begin(), Func->end(), EntryBlock);
std::swap(*EBI, *Func->begin()); // Exchange old location with start of fn
}
while (PHINode *PN = dyn_cast<PHINode>(EntryBlock->front())) {
assert(PN->getNumIncomingValues() == 1 &&
"Can only have a single incoming value at this point...");
// The incoming value must be outside of the scope of the function, a
// global variable, constant or parameter maybe...
//
PN->replaceAllUsesWith(PN->getIncomingValue(0));
// Nuke the phi node...
delete EntryBlock->getInstList().remove(EntryBlock->begin());
}
}
// fixupCFG - Walk the CFG in depth first order, eliminating references to
// dead blocks:
// If the BB is alive (in AliveBlocks):
// 1. Eliminate all dead instructions in the BB
// 2. Recursively traverse all of the successors of the BB:
// - If the returned successor is non-null, update our terminator to
// reference the returned BB
// 3. Return 0 (no update needed)
//
// If the BB is dead (not in AliveBlocks):
// 1. Add the BB to the dead set
// 2. Recursively traverse all of the successors of the block:
// - Only one shall return a nonnull value (or else this block should have
// been in the alive set).
// 3. Return the nonnull child, or 0 if no non-null children.
//
BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
const std::set<BasicBlock*> &AliveBlocks) {
if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
VisitedBlocks.insert(BB); // We have now visited this node!
#ifdef DEBUG_ADCE
cerr << "Fixing up BB: " << BB;
#endif
if (AliveBlocks.count(BB)) { // Is the block alive?
// Yes it's alive: loop through and eliminate all dead instructions in block
for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; )
if (!LiveSet.count(*II)) { // Is this instruction alive?
// Nope... remove the instruction from it's basic block...
delete BB->getInstList().remove(II);
MadeChanges = true;
} else {
++II;
}
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *Succ = *SI;
BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
if (Repl && Repl != Succ) { // We have to replace the successor
Succ->replaceAllUsesWith(Repl);
MadeChanges = true;
}
}
return BB;
} else { // Otherwise the block is dead...
BasicBlock *ReturnBB = 0; // Default to nothing live down here
// Recursively traverse successors of this basic block.
for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
if (RetBB) {
assert(ReturnBB == 0 && "At most one live child allowed!");
ReturnBB = RetBB;
}
}
return ReturnBB; // Return the result of traversal
}
}
<|endoftext|>
|
<commit_before>/*
* #### ####
* #### ####
* #### #### ##
* #### #### ####
* #### ############ ############ #### ########## #### ####
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### #### ####
* #### #### #### #### #### #### #### #### ####
* #### ############ ############ #### ########## #### ####
* #### ####
* ################################ ####
* __ __ __ __ __ ####
* | | | | [__) |_/ (__ |__| | | [__) ####
* |/\| |__| | \ | \ .__) | | |__| | ##
*
*
* DU-INO Arduino Library - Function Module
* Aaron Mavrinac <aaron@logick.ca>
*/
#include "du-ino_mcp4922.h"
#include "du-ino_widgets.h"
#include "du-ino_function.h"
#if __has_include("du-ino_calibration.h")
#include "du-ino_calibration.h"
#define USE_CALIBRATION
#endif
#define TRIG_MS 5 // ms
#define DIGITAL_THRESH 3.0 // V
#define CV_IN_OFFSET 0.1 // V
DUINO_Function::DUINO_Function(uint8_t sc)
: top_level_widget_(NULL)
, saved_(false)
{
set_switch_config(sc);
// configure analog pins
analogReference(EXTERNAL);
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
// configure DACs
for (uint8_t i = 0; i < 2; ++i)
{
dac_[i] = new DUINO_MCP4922(7 - i, 8);
}
}
void DUINO_Function::begin()
{
static bool initialized = false;
if (!initialized)
{
// initialize DACs
dac_[0]->begin();
dac_[1]->begin();
// initialize outputs
gt_out_multi(0xFF, false);
// initialize display
Display.begin();
Display.clear_display();
Display.display();
// initialize encoder
Encoder.begin();
function_setup();
initialized = true;
}
}
void DUINO_Function::widget_setup(DUINO_Widget * top)
{
if (!top)
{
return;
}
top_level_widget_ = top;
top_level_widget_->invert(false);
}
void DUINO_Function::widget_loop()
{
if (!top_level_widget_)
{
return;
}
// handle encoder button press
DUINO_Encoder::Button b = Encoder.get_button();
if(b == DUINO_Encoder::Clicked)
{
top_level_widget_->on_click();
}
else if(b == DUINO_Encoder::DoubleClicked)
{
top_level_widget_->on_double_click();
}
int16_t v = Encoder.get_value();
if(v)
{
top_level_widget_->on_scroll(v);
}
}
bool DUINO_Function::gt_read(DUINO_Function::Jack jack)
{
switch (jack)
{
case GT1:
case GT2:
case GT3:
case GT4:
if (switch_config_ & (1 << jack))
{
return digitalRead(jack) == LOW ? true : false;
}
break;
case CI1:
case CI2:
case CI3:
case CI4:
return cv_read(jack) > DIGITAL_THRESH;
}
return false;
}
bool DUINO_Function::gt_read_debounce(DUINO_Function::Jack jack)
{
if (switch_config_ & (1 << jack))
{
uint16_t buffer = 0x5555;
while (buffer && buffer != 0xFFFF)
{
buffer = (buffer << 1) | digitalRead(jack);
}
return buffer ? false : true;
}
else
{
return false;
}
}
void DUINO_Function::gt_out(DUINO_Function::Jack jack, bool on, bool trig)
{
switch (jack)
{
case GT1:
case GT2:
case GT3:
case GT4:
if ((~switch_config_) & (1 << jack))
{
digitalWrite(jack, on ? HIGH : LOW);
if (trig)
{
delay(TRIG_MS);
digitalWrite(jack, on ? LOW : HIGH);
}
}
break;
case CO1:
case CO2:
case CO3:
case CO4:
dac_[(jack - 4) >> 1]->output((DUINO_MCP4922::Channel)((jack - 4) & 1), on ? 0xBFF : 0x800);
if (trig)
{
delay(TRIG_MS);
dac_[(jack - 4) >> 1]->output((DUINO_MCP4922::Channel)((jack - 4) & 1), on ? 0x800 : 0xBFF);
}
break;
}
}
void DUINO_Function::gt_out_multi(uint8_t jacks, bool on, bool trig)
{
for (uint8_t i = 0; i < 4; ++i)
{
if (jacks & (~switch_config_) & (1 << i))
{
digitalWrite(i, on ? HIGH : LOW);
}
}
for (uint8_t i = 4; i < 8; ++i)
{
if (jacks & (1 << i))
{
dac_[(i - 4) >> 1]->output((DUINO_MCP4922::Channel)((i - 4) & 1), on ? 0xBFF : 0x800);
}
}
if (trig)
{
delay(TRIG_MS);
for (uint8_t i = 0; i < 4; ++i)
{
if (jacks & (~switch_config_) & (1 << i))
{
digitalWrite(i, on ? LOW : HIGH);
}
}
for (uint8_t i = 4; i < 8; ++i)
{
if (jacks & (1 << i))
{
dac_[(i - 4) >> 1]->output((DUINO_MCP4922::Channel)((i - 4) & 1), on ? 0x800 : 0xBFF);
}
}
}
}
float DUINO_Function::cv_read(DUINO_Function::Jack jack)
{
switch (jack)
{
#ifdef USE_CALIBRATION
case CI1:
return cv_analog_read(A0) * CI1_PRESCALE + CI1_OFFSET;
case CI2:
return cv_analog_read(A1) * CI2_PRESCALE + CI2_OFFSET;
case CI3:
return cv_analog_read(A2) * CI3_PRESCALE + CI3_OFFSET;
case CI4:
return cv_analog_read(A3) * CI4_PRESCALE + CI4_OFFSET;
#else
case CI1:
return cv_analog_read(A0);
case CI2:
return cv_analog_read(A1);
case CI3:
return cv_analog_read(A2);
case CI4:
return cv_analog_read(A3);
#endif
default:
return 0.0;
}
}
void DUINO_Function::cv_out(DUINO_Function::Jack jack, float value)
{
if (jack == CO1 || jack == CO2 || jack == CO3 || jack == CO4)
{
// (value + 10) * ((2^12 - 1) / 20)
#ifdef USE_CALIBRATION
float calibrated_value;
switch (jack)
{
case CO1:
calibrated_value = value * CO1_PRESCALE + CO1_OFFSET;
case CO2:
calibrated_value = value * CO2_PRESCALE + CO2_OFFSET;
case CO3:
calibrated_value = value * CO3_PRESCALE + CO3_OFFSET;
case CO4:
calibrated_value = value * CO4_PRESCALE + CO4_OFFSET;
}
#else
const float calibrated_value = value;
#endif
uint16_t data = uint16_t((calibrated_value + 10.0) * 204.75);
// DAC output
dac_[(jack - 4) >> 1]->output((DUINO_MCP4922::Channel)((jack - 4) & 1), data);
}
}
void DUINO_Function::cv_hold(bool state)
{
// both DACs share the LDAC pin, so holding either will hold all four channels
dac_[0]->hold(state);
}
void DUINO_Function::gt_attach_interrupt(DUINO_Function::Jack jack, void (*isr)(void), int mode)
{
if (jack == GT3 || jack == GT4)
{
attachInterrupt(digitalPinToInterrupt(jack), isr, mode);
}
}
void DUINO_Function::gt_detach_interrupt(DUINO_Function::Jack jack)
{
if (jack == GT3 || jack == GT4)
{
detachInterrupt(digitalPinToInterrupt(jack));
}
}
void DUINO_Function::set_switch_config(uint8_t sc)
{
switch_config_ = sc;
// configure digital pins
for (uint8_t i = 0; i < 4; ++i)
{
pinMode(i, sc & (1 << i) ? INPUT : OUTPUT);
}
}
float DUINO_Function::cv_analog_read(uint8_t pin)
{
// value * (20 / (2^10 - 1)) - 10
return float(analogRead(pin)) * 0.019550342130987292 - 10.0 + CV_IN_OFFSET;
}
<commit_msg>Add startup delay for fussy OLED display and power supply combinations.<commit_after>/*
* #### ####
* #### ####
* #### #### ##
* #### #### ####
* #### ############ ############ #### ########## #### ####
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### ########
* #### #### #### #### #### #### #### #### ####
* #### #### #### #### #### #### #### #### ####
* #### ############ ############ #### ########## #### ####
* #### ####
* ################################ ####
* __ __ __ __ __ ####
* | | | | [__) |_/ (__ |__| | | [__) ####
* |/\| |__| | \ | \ .__) | | |__| | ##
*
*
* DU-INO Arduino Library - Function Module
* Aaron Mavrinac <aaron@logick.ca>
*/
#include "du-ino_mcp4922.h"
#include "du-ino_widgets.h"
#include "du-ino_function.h"
#if __has_include("du-ino_calibration.h")
#include "du-ino_calibration.h"
#define USE_CALIBRATION
#endif
#define STARTUP_DELAY 100 // ms
#define TRIG_MS 5 // ms
#define DIGITAL_THRESH 3.0 // V
#define CV_IN_OFFSET 0.1 // V
DUINO_Function::DUINO_Function(uint8_t sc)
: top_level_widget_(NULL)
, saved_(false)
{
set_switch_config(sc);
// configure analog pins
analogReference(EXTERNAL);
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(A2, INPUT);
pinMode(A3, INPUT);
// configure DACs
for (uint8_t i = 0; i < 2; ++i)
{
dac_[i] = new DUINO_MCP4922(7 - i, 8);
}
}
void DUINO_Function::begin()
{
static bool initialized = false;
if (!initialized)
{
// startup delay, to allow fussy OLED displays to work with fussy power supplies
delay(STARTUP_DELAY);
// initialize DACs
dac_[0]->begin();
dac_[1]->begin();
// initialize outputs
gt_out_multi(0xFF, false);
// initialize display
Display.begin();
Display.clear_display();
Display.display();
// initialize encoder
Encoder.begin();
function_setup();
initialized = true;
}
}
void DUINO_Function::widget_setup(DUINO_Widget * top)
{
if (!top)
{
return;
}
top_level_widget_ = top;
top_level_widget_->invert(false);
}
void DUINO_Function::widget_loop()
{
if (!top_level_widget_)
{
return;
}
// handle encoder button press
DUINO_Encoder::Button b = Encoder.get_button();
if(b == DUINO_Encoder::Clicked)
{
top_level_widget_->on_click();
}
else if(b == DUINO_Encoder::DoubleClicked)
{
top_level_widget_->on_double_click();
}
int16_t v = Encoder.get_value();
if(v)
{
top_level_widget_->on_scroll(v);
}
}
bool DUINO_Function::gt_read(DUINO_Function::Jack jack)
{
switch (jack)
{
case GT1:
case GT2:
case GT3:
case GT4:
if (switch_config_ & (1 << jack))
{
return digitalRead(jack) == LOW ? true : false;
}
break;
case CI1:
case CI2:
case CI3:
case CI4:
return cv_read(jack) > DIGITAL_THRESH;
}
return false;
}
bool DUINO_Function::gt_read_debounce(DUINO_Function::Jack jack)
{
if (switch_config_ & (1 << jack))
{
uint16_t buffer = 0x5555;
while (buffer && buffer != 0xFFFF)
{
buffer = (buffer << 1) | digitalRead(jack);
}
return buffer ? false : true;
}
else
{
return false;
}
}
void DUINO_Function::gt_out(DUINO_Function::Jack jack, bool on, bool trig)
{
switch (jack)
{
case GT1:
case GT2:
case GT3:
case GT4:
if ((~switch_config_) & (1 << jack))
{
digitalWrite(jack, on ? HIGH : LOW);
if (trig)
{
delay(TRIG_MS);
digitalWrite(jack, on ? LOW : HIGH);
}
}
break;
case CO1:
case CO2:
case CO3:
case CO4:
dac_[(jack - 4) >> 1]->output((DUINO_MCP4922::Channel)((jack - 4) & 1), on ? 0xBFF : 0x800);
if (trig)
{
delay(TRIG_MS);
dac_[(jack - 4) >> 1]->output((DUINO_MCP4922::Channel)((jack - 4) & 1), on ? 0x800 : 0xBFF);
}
break;
}
}
void DUINO_Function::gt_out_multi(uint8_t jacks, bool on, bool trig)
{
for (uint8_t i = 0; i < 4; ++i)
{
if (jacks & (~switch_config_) & (1 << i))
{
digitalWrite(i, on ? HIGH : LOW);
}
}
for (uint8_t i = 4; i < 8; ++i)
{
if (jacks & (1 << i))
{
dac_[(i - 4) >> 1]->output((DUINO_MCP4922::Channel)((i - 4) & 1), on ? 0xBFF : 0x800);
}
}
if (trig)
{
delay(TRIG_MS);
for (uint8_t i = 0; i < 4; ++i)
{
if (jacks & (~switch_config_) & (1 << i))
{
digitalWrite(i, on ? LOW : HIGH);
}
}
for (uint8_t i = 4; i < 8; ++i)
{
if (jacks & (1 << i))
{
dac_[(i - 4) >> 1]->output((DUINO_MCP4922::Channel)((i - 4) & 1), on ? 0x800 : 0xBFF);
}
}
}
}
float DUINO_Function::cv_read(DUINO_Function::Jack jack)
{
switch (jack)
{
#ifdef USE_CALIBRATION
case CI1:
return cv_analog_read(A0) * CI1_PRESCALE + CI1_OFFSET;
case CI2:
return cv_analog_read(A1) * CI2_PRESCALE + CI2_OFFSET;
case CI3:
return cv_analog_read(A2) * CI3_PRESCALE + CI3_OFFSET;
case CI4:
return cv_analog_read(A3) * CI4_PRESCALE + CI4_OFFSET;
#else
case CI1:
return cv_analog_read(A0);
case CI2:
return cv_analog_read(A1);
case CI3:
return cv_analog_read(A2);
case CI4:
return cv_analog_read(A3);
#endif
default:
return 0.0;
}
}
void DUINO_Function::cv_out(DUINO_Function::Jack jack, float value)
{
if (jack == CO1 || jack == CO2 || jack == CO3 || jack == CO4)
{
// (value + 10) * ((2^12 - 1) / 20)
#ifdef USE_CALIBRATION
float calibrated_value;
switch (jack)
{
case CO1:
calibrated_value = value * CO1_PRESCALE + CO1_OFFSET;
case CO2:
calibrated_value = value * CO2_PRESCALE + CO2_OFFSET;
case CO3:
calibrated_value = value * CO3_PRESCALE + CO3_OFFSET;
case CO4:
calibrated_value = value * CO4_PRESCALE + CO4_OFFSET;
}
#else
const float calibrated_value = value;
#endif
uint16_t data = uint16_t((calibrated_value + 10.0) * 204.75);
// DAC output
dac_[(jack - 4) >> 1]->output((DUINO_MCP4922::Channel)((jack - 4) & 1), data);
}
}
void DUINO_Function::cv_hold(bool state)
{
// both DACs share the LDAC pin, so holding either will hold all four channels
dac_[0]->hold(state);
}
void DUINO_Function::gt_attach_interrupt(DUINO_Function::Jack jack, void (*isr)(void), int mode)
{
if (jack == GT3 || jack == GT4)
{
attachInterrupt(digitalPinToInterrupt(jack), isr, mode);
}
}
void DUINO_Function::gt_detach_interrupt(DUINO_Function::Jack jack)
{
if (jack == GT3 || jack == GT4)
{
detachInterrupt(digitalPinToInterrupt(jack));
}
}
void DUINO_Function::set_switch_config(uint8_t sc)
{
switch_config_ = sc;
// configure digital pins
for (uint8_t i = 0; i < 4; ++i)
{
pinMode(i, sc & (1 << i) ? INPUT : OUTPUT);
}
}
float DUINO_Function::cv_analog_read(uint8_t pin)
{
// value * (20 / (2^10 - 1)) - 10
return float(analogRead(pin)) * 0.019550342130987292 - 10.0 + CV_IN_OFFSET;
}
<|endoftext|>
|
<commit_before>//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
//
// This pass is designed to be a very quick global transformation that
// eliminates global common subexpressions from a function. It does this by
// examining the SSA value graph of the function, instead of doing slow, dense,
// bit-vector computations.
//
// This pass works best if it is proceeded with a simple constant propogation
// pass and an instruction combination pass because this pass does not do any
// value numbering (in order to be speedy).
//
// This pass does not attempt to CSE load instructions, because it does not use
// pointer analysis to determine when it is safe.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/GCSE.h"
#include "llvm/Pass.h"
#include "llvm/InstrTypes.h"
#include "llvm/iMemory.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Support/InstIterator.h"
#include <set>
#include <algorithm>
namespace {
class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
set<Instruction*> WorkList;
DominatorSet *DomSetInfo;
ImmediateDominators *ImmDominator;
public:
const char *getPassName() const {
return "Global Common Subexpression Elimination";
}
virtual bool runOnFunction(Function *F);
// Visitation methods, these are invoked depending on the type of
// instruction being checked. They should return true if a common
// subexpression was folded.
//
bool visitUnaryOperator(Instruction *I);
bool visitBinaryOperator(Instruction *I);
bool visitGetElementPtrInst(GetElementPtrInst *I);
bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
bool visitShiftInst(ShiftInst *I) {
return visitBinaryOperator((Instruction*)I);
}
bool visitInstruction(Instruction *) { return false; }
private:
void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
void CommonSubExpressionFound(Instruction *I, Instruction *Other);
// This transformation requires dominator and immediate dominator info
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.preservesCFG();
AU.addRequired(DominatorSet::ID);
AU.addRequired(ImmediateDominators::ID);
}
};
}
// createGCSEPass - The public interface to this file...
Pass *createGCSEPass() { return new GCSE(); }
// GCSE::runOnFunction - This is the main transformation entry point for a
// function.
//
bool GCSE::runOnFunction(Function *F) {
bool Changed = false;
DomSetInfo = &getAnalysis<DominatorSet>();
ImmDominator = &getAnalysis<ImmediateDominators>();
// Step #1: Add all instructions in the function to the worklist for
// processing. All of the instructions are considered to be our
// subexpressions to eliminate if possible.
//
WorkList.insert(inst_begin(F), inst_end(F));
// Step #2: WorkList processing. Iterate through all of the instructions,
// checking to see if there are any additionally defined subexpressions in the
// program. If so, eliminate them!
//
while (!WorkList.empty()) {
Instruction *I = *WorkList.begin(); // Get an instruction from the worklist
WorkList.erase(WorkList.begin());
// Visit the instruction, dispatching to the correct visit function based on
// the instruction type. This does the checking.
//
Changed |= visit(I);
}
// When the worklist is empty, return whether or not we changed anything...
return Changed;
}
// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
// uses of the instruction use First now instead.
//
void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Instruction *Second = *SI;
// Add the first instruction back to the worklist
WorkList.insert(First);
// Add all uses of the second instruction to the worklist
for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Make all users of 'Second' now use 'First'
Second->replaceAllUsesWith(First);
// Erase the second instruction from the program
delete Second->getParent()->getInstList().remove(SI);
}
// CommonSubExpressionFound - The two instruction I & Other have been found to
// be common subexpressions. This function is responsible for eliminating one
// of them, and for fixing the worklist to be correct.
//
void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
// I has already been removed from the worklist, Other needs to be.
assert(WorkList.count(I) == 0 && WorkList.count(Other) &&
"I in worklist or Other not!");
WorkList.erase(Other);
// Handle the easy case, where both instructions are in the same basic block
BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
if (BB1 == BB2) {
// Eliminate the second occuring instruction. Add all uses of the second
// instruction to the worklist.
//
// Scan the basic block looking for the "first" instruction
BasicBlock::iterator BI = BB1->begin();
while (*BI != I && *BI != Other) {
++BI;
assert(BI != BB1->end() && "Instructions not found in parent BB!");
}
// Keep track of which instructions occurred first & second
Instruction *First = *BI;
Instruction *Second = I != First ? I : Other; // Get iterator to second inst
BI = find(BI, BB1->end(), Second);
assert(BI != BB1->end() && "Second instruction not found in parent block!");
// Destroy Second, using First instead.
ReplaceInstWithInst(First, BI);
// Otherwise, the two instructions are in different basic blocks. If one
// dominates the other instruction, we can simply use it
//
} else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
assert(BI != BB2->end() && "Other not in parent basic block!");
ReplaceInstWithInst(I, BI);
} else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
assert(BI != BB1->end() && "I not in parent basic block!");
ReplaceInstWithInst(Other, BI);
} else {
// Handle the most general case now. In this case, neither I dom Other nor
// Other dom I. Because we are in SSA form, we are guaranteed that the
// operands of the two instructions both dominate the uses, so we _know_
// that there must exist a block that dominates both instructions (if the
// operands of the instructions are globals or constants, worst case we
// would get the entry node of the function). Search for this block now.
//
// Search up the immediate dominator chain of BB1 for the shared dominator
BasicBlock *SharedDom = (*ImmDominator)[BB1];
while (!DomSetInfo->dominates(SharedDom, BB2))
SharedDom = (*ImmDominator)[SharedDom];
// At this point, shared dom must dominate BOTH BB1 and BB2...
assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
// Rip 'I' out of BB1, and move it to the end of SharedDom.
BB1->getInstList().remove(I);
SharedDom->getInstList().insert(SharedDom->end()-1, I);
// Eliminate 'Other' now.
BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
assert(BI != BB2->end() && "I not in parent basic block!");
ReplaceInstWithInst(I, BI);
}
}
//===----------------------------------------------------------------------===//
//
// Visitation methods, these are invoked depending on the type of instruction
// being checked. They should return true if a common subexpression was folded.
//
//===----------------------------------------------------------------------===//
bool GCSE::visitUnaryOperator(Instruction *I) {
Value *Op = I->getOperand(0);
Function *F = I->getParent()->getParent();
for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
UI != UE; ++UI)
if (Instruction *Other = dyn_cast<Instruction>(*UI))
// Check to see if this new binary operator is not I, but same operand...
if (Other != I && Other->getOpcode() == I->getOpcode() &&
Other->getOperand(0) == Op && // Is the operand the same?
// Is it embeded in the same function? (This could be false if LHS
// is a constant or global!)
Other->getParent()->getParent() == F &&
// Check that the types are the same, since this code handles casts...
Other->getType() == I->getType()) {
// These instructions are identical. Handle the situation.
CommonSubExpressionFound(I, Other);
return true; // One instruction eliminated!
}
return false;
}
bool GCSE::visitBinaryOperator(Instruction *I) {
Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Function *F = I->getParent()->getParent();
for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
UI != UE; ++UI)
if (Instruction *Other = dyn_cast<Instruction>(*UI))
// Check to see if this new binary operator is not I, but same operand...
if (Other != I && Other->getOpcode() == I->getOpcode() &&
// Are the LHS and RHS the same?
Other->getOperand(0) == LHS && Other->getOperand(1) == RHS &&
// Is it embeded in the same function? (This could be false if LHS
// is a constant or global!)
Other->getParent()->getParent() == F) {
// These instructions are identical. Handle the situation.
CommonSubExpressionFound(I, Other);
return true; // One instruction eliminated!
}
return false;
}
bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
Value *Op = I->getOperand(0);
Function *F = I->getParent()->getParent();
for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
UI != UE; ++UI)
if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
// Check to see if this new binary operator is not I, but same operand...
if (Other != I && Other->getParent()->getParent() == F &&
Other->getType() == I->getType()) {
// Check to see that all operators past the 0th are the same...
unsigned i = 1, e = I->getNumOperands();
for (; i != e; ++i)
if (I->getOperand(i) != Other->getOperand(i)) break;
if (i == e) {
// These instructions are identical. Handle the situation.
CommonSubExpressionFound(I, Other);
return true; // One instruction eliminated!
}
}
return false;
}
<commit_msg>Remove broken assertion.<commit_after>//===-- GCSE.cpp - SSA based Global Common Subexpr Elimination ------------===//
//
// This pass is designed to be a very quick global transformation that
// eliminates global common subexpressions from a function. It does this by
// examining the SSA value graph of the function, instead of doing slow, dense,
// bit-vector computations.
//
// This pass works best if it is proceeded with a simple constant propogation
// pass and an instruction combination pass because this pass does not do any
// value numbering (in order to be speedy).
//
// This pass does not attempt to CSE load instructions, because it does not use
// pointer analysis to determine when it is safe.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/GCSE.h"
#include "llvm/Pass.h"
#include "llvm/InstrTypes.h"
#include "llvm/iMemory.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Support/InstIterator.h"
#include <set>
#include <algorithm>
namespace {
class GCSE : public FunctionPass, public InstVisitor<GCSE, bool> {
set<Instruction*> WorkList;
DominatorSet *DomSetInfo;
ImmediateDominators *ImmDominator;
public:
const char *getPassName() const {
return "Global Common Subexpression Elimination";
}
virtual bool runOnFunction(Function *F);
// Visitation methods, these are invoked depending on the type of
// instruction being checked. They should return true if a common
// subexpression was folded.
//
bool visitUnaryOperator(Instruction *I);
bool visitBinaryOperator(Instruction *I);
bool visitGetElementPtrInst(GetElementPtrInst *I);
bool visitCastInst(CastInst *I){return visitUnaryOperator((Instruction*)I);}
bool visitShiftInst(ShiftInst *I) {
return visitBinaryOperator((Instruction*)I);
}
bool visitInstruction(Instruction *) { return false; }
private:
void ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI);
void CommonSubExpressionFound(Instruction *I, Instruction *Other);
// This transformation requires dominator and immediate dominator info
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.preservesCFG();
AU.addRequired(DominatorSet::ID);
AU.addRequired(ImmediateDominators::ID);
}
};
}
// createGCSEPass - The public interface to this file...
Pass *createGCSEPass() { return new GCSE(); }
// GCSE::runOnFunction - This is the main transformation entry point for a
// function.
//
bool GCSE::runOnFunction(Function *F) {
bool Changed = false;
DomSetInfo = &getAnalysis<DominatorSet>();
ImmDominator = &getAnalysis<ImmediateDominators>();
// Step #1: Add all instructions in the function to the worklist for
// processing. All of the instructions are considered to be our
// subexpressions to eliminate if possible.
//
WorkList.insert(inst_begin(F), inst_end(F));
// Step #2: WorkList processing. Iterate through all of the instructions,
// checking to see if there are any additionally defined subexpressions in the
// program. If so, eliminate them!
//
while (!WorkList.empty()) {
Instruction *I = *WorkList.begin(); // Get an instruction from the worklist
WorkList.erase(WorkList.begin());
// Visit the instruction, dispatching to the correct visit function based on
// the instruction type. This does the checking.
//
Changed |= visit(I);
}
// When the worklist is empty, return whether or not we changed anything...
return Changed;
}
// ReplaceInstWithInst - Destroy the instruction pointed to by SI, making all
// uses of the instruction use First now instead.
//
void GCSE::ReplaceInstWithInst(Instruction *First, BasicBlock::iterator SI) {
Instruction *Second = *SI;
//cerr << "DEL " << (void*)Second << Second;
// Add the first instruction back to the worklist
WorkList.insert(First);
// Add all uses of the second instruction to the worklist
for (Value::use_iterator UI = Second->use_begin(), UE = Second->use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Make all users of 'Second' now use 'First'
Second->replaceAllUsesWith(First);
// Erase the second instruction from the program
delete Second->getParent()->getInstList().remove(SI);
}
// CommonSubExpressionFound - The two instruction I & Other have been found to
// be common subexpressions. This function is responsible for eliminating one
// of them, and for fixing the worklist to be correct.
//
void GCSE::CommonSubExpressionFound(Instruction *I, Instruction *Other) {
// I has already been removed from the worklist, Other needs to be.
assert(I != Other && WorkList.count(I) == 0 && "I shouldn't be on worklist!");
WorkList.erase(Other); // Other may not actually be on the worklist anymore...
// Handle the easy case, where both instructions are in the same basic block
BasicBlock *BB1 = I->getParent(), *BB2 = Other->getParent();
if (BB1 == BB2) {
// Eliminate the second occuring instruction. Add all uses of the second
// instruction to the worklist.
//
// Scan the basic block looking for the "first" instruction
BasicBlock::iterator BI = BB1->begin();
while (*BI != I && *BI != Other) {
++BI;
assert(BI != BB1->end() && "Instructions not found in parent BB!");
}
// Keep track of which instructions occurred first & second
Instruction *First = *BI;
Instruction *Second = I != First ? I : Other; // Get iterator to second inst
BI = find(BI, BB1->end(), Second);
assert(BI != BB1->end() && "Second instruction not found in parent block!");
// Destroy Second, using First instead.
ReplaceInstWithInst(First, BI);
// Otherwise, the two instructions are in different basic blocks. If one
// dominates the other instruction, we can simply use it
//
} else if (DomSetInfo->dominates(BB1, BB2)) { // I dom Other?
BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
assert(BI != BB2->end() && "Other not in parent basic block!");
ReplaceInstWithInst(I, BI);
} else if (DomSetInfo->dominates(BB2, BB1)) { // Other dom I?
BasicBlock::iterator BI = find(BB1->begin(), BB1->end(), I);
assert(BI != BB1->end() && "I not in parent basic block!");
ReplaceInstWithInst(Other, BI);
} else {
// Handle the most general case now. In this case, neither I dom Other nor
// Other dom I. Because we are in SSA form, we are guaranteed that the
// operands of the two instructions both dominate the uses, so we _know_
// that there must exist a block that dominates both instructions (if the
// operands of the instructions are globals or constants, worst case we
// would get the entry node of the function). Search for this block now.
//
// Search up the immediate dominator chain of BB1 for the shared dominator
BasicBlock *SharedDom = (*ImmDominator)[BB1];
while (!DomSetInfo->dominates(SharedDom, BB2))
SharedDom = (*ImmDominator)[SharedDom];
// At this point, shared dom must dominate BOTH BB1 and BB2...
assert(SharedDom && DomSetInfo->dominates(SharedDom, BB1) &&
DomSetInfo->dominates(SharedDom, BB2) && "Dominators broken!");
// Rip 'I' out of BB1, and move it to the end of SharedDom.
BB1->getInstList().remove(I);
SharedDom->getInstList().insert(SharedDom->end()-1, I);
// Eliminate 'Other' now.
BasicBlock::iterator BI = find(BB2->begin(), BB2->end(), Other);
assert(BI != BB2->end() && "I not in parent basic block!");
ReplaceInstWithInst(I, BI);
}
}
//===----------------------------------------------------------------------===//
//
// Visitation methods, these are invoked depending on the type of instruction
// being checked. They should return true if a common subexpression was folded.
//
//===----------------------------------------------------------------------===//
bool GCSE::visitUnaryOperator(Instruction *I) {
Value *Op = I->getOperand(0);
Function *F = I->getParent()->getParent();
for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
UI != UE; ++UI)
if (Instruction *Other = dyn_cast<Instruction>(*UI))
// Check to see if this new binary operator is not I, but same operand...
if (Other != I && Other->getOpcode() == I->getOpcode() &&
Other->getOperand(0) == Op && // Is the operand the same?
// Is it embeded in the same function? (This could be false if LHS
// is a constant or global!)
Other->getParent()->getParent() == F &&
// Check that the types are the same, since this code handles casts...
Other->getType() == I->getType()) {
// These instructions are identical. Handle the situation.
CommonSubExpressionFound(I, Other);
return true; // One instruction eliminated!
}
return false;
}
bool GCSE::visitBinaryOperator(Instruction *I) {
Value *LHS = I->getOperand(0), *RHS = I->getOperand(1);
Function *F = I->getParent()->getParent();
for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
UI != UE; ++UI)
if (Instruction *Other = dyn_cast<Instruction>(*UI))
// Check to see if this new binary operator is not I, but same operand...
if (Other != I && Other->getOpcode() == I->getOpcode() &&
// Are the LHS and RHS the same?
Other->getOperand(0) == LHS && Other->getOperand(1) == RHS &&
// Is it embeded in the same function? (This could be false if LHS
// is a constant or global!)
Other->getParent()->getParent() == F) {
// These instructions are identical. Handle the situation.
CommonSubExpressionFound(I, Other);
return true; // One instruction eliminated!
}
return false;
}
bool GCSE::visitGetElementPtrInst(GetElementPtrInst *I) {
Value *Op = I->getOperand(0);
Function *F = I->getParent()->getParent();
for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
UI != UE; ++UI)
if (GetElementPtrInst *Other = dyn_cast<GetElementPtrInst>(*UI))
// Check to see if this new binary operator is not I, but same operand...
if (Other != I && Other->getParent()->getParent() == F &&
Other->getType() == I->getType()) {
// Check to see that all operators past the 0th are the same...
unsigned i = 1, e = I->getNumOperands();
for (; i != e; ++i)
if (I->getOperand(i) != Other->getOperand(i)) break;
if (i == e) {
// These instructions are identical. Handle the situation.
CommonSubExpressionFound(I, Other);
return true; // One instruction eliminated!
}
}
return false;
}
<|endoftext|>
|
<commit_before>#include "model_initializer.h"
#include "backend.h"
#include "biology_module_util.h"
#include "cell.h"
#include "gtest/gtest.h"
#include "resource_manager.h"
#include "test_util.h"
#include "variadic_template_parameter_util.h"
namespace bdm {
namespace model_initializer_test_internal {
TEST(ModelInitializerTest, Grid3D) {
auto rm = ResourceManager<>::Get();
ModelInitializer::Grid3D(2, 12, [](const std::array<double, 3>& pos) {
Cell cell(pos);
return cell;
});
auto cells = rm->Get<Cell>();
EXPECT_EQ(8u, cells->size());
EXPECT_ARR_EQ({0, 0, 0}, (*cells)[0].GetPosition());
EXPECT_ARR_EQ({0, 0, 12}, (*cells)[1].GetPosition());
EXPECT_ARR_EQ({0, 12, 0}, (*cells)[2].GetPosition());
EXPECT_ARR_EQ({0, 12, 12}, (*cells)[3].GetPosition());
EXPECT_ARR_EQ({12, 0, 0}, (*cells)[4].GetPosition());
EXPECT_ARR_EQ({12, 0, 12}, (*cells)[5].GetPosition());
EXPECT_ARR_EQ({12, 12, 0}, (*cells)[6].GetPosition());
EXPECT_ARR_EQ({12, 12, 12}, (*cells)[7].GetPosition());
}
} // namespace model_initializer_test_internal
} // namespace bdm
<commit_msg>Fix failing ModelInitializer test<commit_after>#include "model_initializer.h"
#include "backend.h"
#include "biology_module_util.h"
#include "cell.h"
#include "gtest/gtest.h"
#include "resource_manager.h"
#include "test_util.h"
#include "variadic_template_parameter_util.h"
namespace bdm {
namespace model_initializer_test_internal {
TEST(ModelInitializerTest, Grid3D) {
auto rm = ResourceManager<>::Get();
rm->Clear();
ModelInitializer::Grid3D(2, 12, [](const std::array<double, 3>& pos) {
Cell cell(pos);
return cell;
});
auto cells = rm->Get<Cell>();
EXPECT_EQ(8u, cells->size());
EXPECT_ARR_EQ({0, 0, 0}, (*cells)[0].GetPosition());
EXPECT_ARR_EQ({0, 0, 12}, (*cells)[1].GetPosition());
EXPECT_ARR_EQ({0, 12, 0}, (*cells)[2].GetPosition());
EXPECT_ARR_EQ({0, 12, 12}, (*cells)[3].GetPosition());
EXPECT_ARR_EQ({12, 0, 0}, (*cells)[4].GetPosition());
EXPECT_ARR_EQ({12, 0, 12}, (*cells)[5].GetPosition());
EXPECT_ARR_EQ({12, 12, 0}, (*cells)[6].GetPosition());
EXPECT_ARR_EQ({12, 12, 12}, (*cells)[7].GetPosition());
}
} // namespace model_initializer_test_internal
} // namespace bdm
<|endoftext|>
|
<commit_before>#include <elf/oid.h>
#include <elf/memory.h>
#include <elf/time.h>
#include <elf/matchmaking.h>
namespace elf {
enum MatchRank {
ROOKIE_RANK = 800,
MASTER_RANK = 2500,
RANK_OFFSET = 100,
};
int get_rank_level(int rank) {
if (rank <= ROOKIE_RANK) {
return ROOKIE_RANK;
} else if (rank > MASTER_RANK) {
return MASTER_RANK;
}
return rank - rank % RANK_OFFSET;
}
struct MatchEntity {
oid_t id;
int elo;
int status;
int size;
oid_t team_id;
time_t time;
std::list<MatchEntity*> children;
int get_size() {
if (children.empty()) {
return size;
}
int total = 0;
std::list<MatchEntity*>::iterator itr;
for (itr = children.begin(); itr != children.end(); ++itr) {
total += (*itr)->get_size();
}
return total;
}
};
struct MatchRes {
int type;
std::vector<TeamSet> teams;
};
typedef std::map<int, TeamSet> rank_map_t;
struct MatchQueue {
int size_type;
std::queue<MatchEntity*> candidates;
rank_map_t ranks;
};
std::map<int, MatchPool*> MatchPool::s_pools;
MatchPool::MatchPool()
: _type(0)
, _team_size(0)
, _camp_size(0) {
}
MatchPool::MatchPool(int type, int team_size, int camp_size)
: _type(type)
, _team_size(team_size)
, _camp_size(camp_size) {
}
MatchPool::~MatchPool() {
for (std::map<oid_t, MatchEntity*>::iterator itr = _entities.begin();
itr != _entities.end();
++itr) {
E_DELETE itr->second;
}
_entities.clear();
for (std::map<int, MatchQueue*>::iterator itr = _queues.begin();
itr != _queues.end();
++ itr) {
E_DELETE itr->second;
}
_queues.clear();
}
oid_t MatchPool::Push(int elo, int size, oid_t teamId) {
MatchEntity *ent = E_NEW MatchEntity;
ent->id = oid_gen();
ent->elo = elo;
ent->time = time_s();
ent->status = MATCH_PENDING;
ent->team_id = teamId;
ent->size = size;
push(ent);
return ent->id;
}
void MatchPool::push(MatchEntity *ent) {
_entities[ent->id] = ent;
std::map<int, MatchQueue*>::iterator itr = _queues.find(ent->size);
MatchQueue *que;
if (itr == _queues.end()) {
que = E_NEW MatchQueue;
que->size_type = ent->size;
_queues[ent->size] = que;
} else {
que = itr->second;
}
que->candidates.push(ent);
int lvl = get_rank_level(ent->elo);
rank_map_t::iterator itr_rank = que->ranks.find(lvl);
if (itr_rank == que->ranks.end()) {
que->ranks.insert(std::make_pair(lvl, TeamSet()));
}
que->ranks[lvl].insert(ent->id);
}
MatchEntity *MatchPool::top(int size_type) {
std::map<int, MatchQueue*>::iterator itr = _queues.find(size_type);
if (itr == _queues.end()) {
return NULL;
}
MatchQueue *que = itr->second;
if (que->candidates.empty()) {
return NULL;
}
MatchEntity *ent = que->candidates.front();
que->candidates.pop();
return ent;
}
/// find skill proper opponent
MatchEntity *MatchPool::get_opponent(MatchEntity *ent) {
int lvl = get_rank_level(ent->elo);
std::map<int, MatchQueue*>::iterator itr = _queues.find(ent->get_size());
if (itr == _queues.end()) {
return NULL;
}
MatchQueue *que = itr->second;
rank_map_t::iterator itr_rank = que->ranks.find(lvl);
if (itr_rank == que->ranks.end()) {
return NULL;
}
TeamSet::iterator itr_t = itr_rank->second.begin();
for (;itr_t != itr_rank->second.end(); ++itr_t) {
if (*itr_t != ent->id) {
return _entities[*itr_t];
}
}
return NULL;
}
bool MatchPool::pop(int size_type) {
std::vector<std::vector<MatchEntity*> > camps(_camp_size);
MatchEntity *ent = top(size_type);
if (ent == NULL) {
return false;
}
camps[0].push_back(ent);
for (int i = 1;i < _camp_size; i++) {
MatchEntity *opp = get_opponent(ent);
if (opp == NULL) {
return false;
}
camps[i].push_back(opp);
}
int size = ent->get_size();
while (size < _camp_size) {
MatchEntity *buddy = NULL; //get_buddy(_camp_size - size);
if (buddy == NULL) {
return false;
}
camps[0].push_back(buddy);
for (int i = 1;i < _camp_size; i++) {
MatchEntity *opp_buddy = get_opponent(buddy);
if (opp_buddy == NULL) {
return false;
}
camps[i].push_back(opp_buddy);
}
size += buddy->get_size();
return true;
}
return false;
}
/// pop matched team(s)
bool MatchPool::pop(MatchRes &res) {
std::vector<std::vector<MatchEntity*> > camps(_camp_size);
for (int i = _team_size;i >= 1; i--) {
pop(i);
}
/*
MatchEntity *ent = top();
if (ent == NULL) {
return false;
}
camps[0].push_back(ent);
MatchEntity *opt = get_opponent(ent);
if (opt == NULL) {
return false;
}
*/
return false;
}
void MatchPool::Del(const oid_t &id) {
std::map<oid_t, MatchEntity*>::iterator itr = _entities.find(id);
if (itr != _entities.end()) {
MatchEntity *ent = itr->second;
ent->status = MatchPool::MATCH_DELETED;
}
}
MatchPool *MatchPool::Create(int type, int team_size, int camp_size) {
MatchPool *pool = Get(type);
if (pool != NULL) {
return pool;
}
pool = E_NEW MatchPool(type, team_size, camp_size);
s_pools[type] = pool;
return pool;
}
MatchPool *MatchPool::Get(int type) {
std::map<int, MatchPool*>::iterator itr = s_pools.find(type);
MatchPool *pool = NULL;
if (itr != s_pools.end()) {
pool = itr->second;
}
return pool;
}
void MatchPool::Proc(std::list<MatchRes> &resList) {
std::map<int, MatchPool*>::iterator itr;
for (itr = s_pools.begin(); itr != s_pools.end(); ++itr) {
MatchRes res;
if (itr->second->pop(res)) {
resList.push_back(res);
}
}
}
void MatchPool::Release() {
std::map<int, MatchPool*>::iterator itr;
for (itr = s_pools.begin(); itr != s_pools.end(); ++itr) {
E_DELETE itr->second;
}
s_pools.clear();
}
} // namespace MatchMaking
<commit_msg>[MOD] matchmaking<commit_after>#include <elf/oid.h>
#include <elf/memory.h>
#include <elf/time.h>
#include <elf/matchmaking.h>
namespace elf {
enum MatchRank {
ROOKIE_RANK = 800,
MASTER_RANK = 2500,
RANK_OFFSET = 100,
};
int get_rank_level(int rank) {
if (rank <= ROOKIE_RANK) {
return ROOKIE_RANK;
} else if (rank > MASTER_RANK) {
return MASTER_RANK;
}
return rank - rank % RANK_OFFSET;
}
struct MatchEntity {
oid_t id;
int elo;
int status;
int size;
oid_t team_id;
time_t time;
std::list<MatchEntity*> children;
int get_size() {
if (children.empty()) {
return size;
}
int total = 0;
std::list<MatchEntity*>::iterator itr;
for (itr = children.begin(); itr != children.end(); ++itr) {
total += (*itr)->get_size();
}
return total;
}
};
struct MatchRes {
int type;
std::vector<TeamSet> teams;
};
typedef std::map<int, TeamSet> rank_map_t;
struct MatchQueue {
int size_type;
std::queue<MatchEntity*> candidates;
rank_map_t ranks;
};
std::map<int, MatchPool*> MatchPool::s_pools;
MatchPool::MatchPool()
: _type(0)
, _team_size(0)
, _camp_size(0) {
}
MatchPool::MatchPool(int type, int team_size, int camp_size)
: _type(type)
, _team_size(team_size)
, _camp_size(camp_size) {
}
MatchPool::~MatchPool() {
for (std::map<oid_t, MatchEntity*>::iterator itr = _entities.begin();
itr != _entities.end();
++itr) {
E_DELETE itr->second;
}
_entities.clear();
for (std::map<int, MatchQueue*>::iterator itr = _queues.begin();
itr != _queues.end();
++ itr) {
E_DELETE itr->second;
}
_queues.clear();
}
oid_t MatchPool::Push(int elo, int size, oid_t teamId) {
MatchEntity *ent = E_NEW MatchEntity;
ent->id = oid_gen();
ent->elo = elo;
ent->time = time_s();
ent->status = MATCH_PENDING;
ent->team_id = teamId;
ent->size = size;
push(ent);
return ent->id;
}
void MatchPool::push(MatchEntity *ent) {
_entities[ent->id] = ent;
std::map<int, MatchQueue*>::iterator itr = _queues.find(ent->size);
MatchQueue *que;
if (itr == _queues.end()) {
que = E_NEW MatchQueue;
que->size_type = ent->size;
_queues[ent->size] = que;
} else {
que = itr->second;
}
que->candidates.push(ent);
int lvl = get_rank_level(ent->elo);
rank_map_t::iterator itr_rank = que->ranks.find(lvl);
if (itr_rank == que->ranks.end()) {
que->ranks.insert(std::make_pair(lvl, TeamSet()));
}
que->ranks[lvl].insert(ent->id);
}
MatchEntity *MatchPool::top(int size_type) {
std::map<int, MatchQueue*>::iterator itr = _queues.find(size_type);
if (itr == _queues.end()) {
return NULL;
}
MatchQueue *que = itr->second;
if (que->candidates.empty()) {
return NULL;
}
MatchEntity *ent = que->candidates.front();
que->candidates.pop();
return ent;
}
/// find skill proper opponent
MatchEntity *MatchPool::get_opponent(MatchEntity *ent) {
int lvl = get_rank_level(ent->elo);
std::map<int, MatchQueue*>::iterator itr = _queues.find(ent->get_size());
if (itr == _queues.end()) {
return NULL;
}
MatchQueue *que = itr->second;
rank_map_t::iterator itr_rank = que->ranks.find(lvl);
if (itr_rank == que->ranks.end()) {
return NULL;
}
TeamSet::iterator itr_t = itr_rank->second.begin();
for (;itr_t != itr_rank->second.end(); ++itr_t) {
if (*itr_t != ent->id) {
return _entities[*itr_t];
}
}
return NULL;
}
bool MatchPool::pop(int size_type) {
std::vector<std::vector<MatchEntity*> > camps(_camp_size);
MatchEntity *ent = top(size_type);
if (ent == NULL) {
return false;
}
camps[0].push_back(ent);
for (int i = 1;i < _camp_size; i++) {
MatchEntity *opp = get_opponent(ent);
if (opp == NULL) {
return false;
}
camps[i].push_back(opp);
}
int size = ent->get_size();
while (size < _camp_size) {
MatchEntity *buddy = NULL; //get_buddy(_camp_size - size);
if (buddy == NULL) {
return false;
}
camps[0].push_back(buddy);
for (int i = 1;i < _camp_size; i++) {
MatchEntity *opp_buddy = get_opponent(buddy);
if (opp_buddy == NULL) {
return false;
}
camps[i].push_back(opp_buddy);
}
size += buddy->get_size();
return true;
}
return false;
}
/// pop matched team(s)
bool MatchPool::pop(MatchRes &res) {
std::vector<std::vector<MatchEntity*> > camps(_camp_size);
for (int i = _team_size;i >= 1; i--) {
pop(i);
}
/*
MatchEntity *ent = top();
if (ent == NULL) {
return false;
}
camps[0].push_back(ent);
MatchEntity *opt = get_opponent(ent);
if (opt == NULL) {
return false;
}
*/
return false;
}
void MatchPool::Del(const oid_t &id) {
std::map<oid_t, MatchEntity*>::iterator itr = _entities.find(id);
if (itr != _entities.end()) {
MatchEntity *ent = itr->second;
ent->status = MatchPool::MATCH_DELETED;
}
}
MatchPool *MatchPool::Create(int type, int team_size, int camp_size) {
MatchPool *pool = Get(type);
if (pool != NULL) {
return pool;
}
pool = E_NEW MatchPool(type, team_size, camp_size);
s_pools[type] = pool;
return pool;
}
MatchPool *MatchPool::Get(int type) {
std::map<int, MatchPool*>::iterator itr = s_pools.find(type);
MatchPool *pool = NULL;
if (itr != s_pools.end()) {
pool = itr->second;
}
return pool;
}
void MatchPool::Proc(std::list<MatchRes> &resList) {
std::map<int, MatchPool*>::iterator itr;
for (itr = s_pools.begin(); itr != s_pools.end(); ++itr) {
MatchRes res;
if (itr->second->pop(res)) {
resList.push_back(res);
}
}
// adjust ranklevel for entities.
}
void MatchPool::Release() {
std::map<int, MatchPool*>::iterator itr;
for (itr = s_pools.begin(); itr != s_pools.end(); ++itr) {
E_DELETE itr->second;
}
s_pools.clear();
}
} // namespace MatchMaking
<|endoftext|>
|
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_posh/roudi/memory/roudi_memory_manager.hpp"
#include "mocks/roudi_memory_block_mock.hpp"
#include "mocks/roudi_memory_provider_mock.hpp"
#include "test.hpp"
using namespace ::testing;
using namespace iox::roudi;
/// @todo the RouDiMemoryManager changed quite much from the initial idea, check which tests makes sense
#if 0
class RouDiMemoryManager_Test : public Test
{
public:
void SetUp() override
{
}
void TearDown() override
{
}
MemoryBlockMock memoryBlock1;
MemoryBlockMock memoryBlock2;
MemoryProviderTestImpl memoryProvider1;
MemoryProviderTestImpl memoryProvider2;
RouDiMemoryManager sut;
};
TEST_F(RouDiMemoryManager_Test, CallingCreateAndAnnounceMemoryWithoutMemoryProviderFails)
{
auto expectError = sut.createAndAnnounceMemory();
ASSERT_THAT(expectError.has_error(), Eq(true));
EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::NO_MEMORY_PROVIDER_PRESENT));
}
TEST_F(RouDiMemoryManager_Test, CallingCreateMemoryWithMemoryProviderSucceeds)
{
uint64_t MEMORY_SIZE_1{16};
uint64_t MEMORY_ALIGNMENT_1{8};
uint64_t MEMORY_SIZE_2{32};
uint64_t MEMORY_ALIGNMENT_2{16};
EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));
EXPECT_CALL(memoryBlock2, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_2));
EXPECT_CALL(memoryBlock2, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_2));
EXPECT_CALL(memoryBlock2, memoryAvailableMock(_));
memoryProvider1.addMemoryBlock(&memoryBlock1);
memoryProvider2.addMemoryBlock(&memoryBlock2);
sut.addMemoryProvider(&memoryProvider1);
sut.addMemoryProvider(&memoryProvider2);
EXPECT_THAT(sut.createAndAnnounceMemory().has_error(), Eq(false));
EXPECT_CALL(memoryBlock1, destroyMock());
EXPECT_CALL(memoryBlock2, destroyMock());
}
TEST_F(RouDiMemoryManager_Test, RouDiMemoryManagerDTorTriggersMemoryProviderDestroy)
{
uint64_t MEMORY_SIZE_1{16};
uint64_t MEMORY_ALIGNMENT_1{8};
EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));
memoryProvider1.addMemoryBlock(&memoryBlock1);
{
RouDiMemoryManager sutDestroy;
sutDestroy.addMemoryProvider(&memoryProvider1);
sutDestroy.createAndAnnounceMemory();
EXPECT_CALL(memoryBlock1, destroyMock()).Times(1);
}
EXPECT_CALL(memoryBlock1, destroyMock()).Times(0);
}
TEST_F(RouDiMemoryManager_Test, AddMemoryProviderExceedsCapacity)
{
MemoryProviderTestImpl memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER + 1];
RouDiMemoryManager sutExhausting;
for (uint32_t i = 0; i < iox::MAX_NUMBER_OF_MEMORY_PROVIDER; ++i)
{
EXPECT_THAT(sutExhausting.addMemoryProvider(&memoryProvider[i]).has_error(), Eq(false));
}
auto expectError = sutExhausting.addMemoryProvider(&memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER]);
ASSERT_THAT(expectError.has_error(), Eq(true));
EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::MEMORY_PROVIDER_EXHAUSTED));
}
TEST_F(RouDiMemoryManager_Test, StreamOperatorTranslationIsCorrect)
{
/// @todo
}
#endif
<commit_msg>iox-#91 Replace empty test with @todo<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "iceoryx_posh/roudi/memory/roudi_memory_manager.hpp"
#include "mocks/roudi_memory_block_mock.hpp"
#include "mocks/roudi_memory_provider_mock.hpp"
#include "test.hpp"
using namespace ::testing;
using namespace iox::roudi;
/// @todo the RouDiMemoryManager changed quite much from the initial idea, check which tests makes sense
#if 0
class RouDiMemoryManager_Test : public Test
{
public:
void SetUp() override
{
}
void TearDown() override
{
}
MemoryBlockMock memoryBlock1;
MemoryBlockMock memoryBlock2;
MemoryProviderTestImpl memoryProvider1;
MemoryProviderTestImpl memoryProvider2;
RouDiMemoryManager sut;
};
TEST_F(RouDiMemoryManager_Test, CallingCreateAndAnnounceMemoryWithoutMemoryProviderFails)
{
auto expectError = sut.createAndAnnounceMemory();
ASSERT_THAT(expectError.has_error(), Eq(true));
EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::NO_MEMORY_PROVIDER_PRESENT));
}
TEST_F(RouDiMemoryManager_Test, CallingCreateMemoryWithMemoryProviderSucceeds)
{
uint64_t MEMORY_SIZE_1{16};
uint64_t MEMORY_ALIGNMENT_1{8};
uint64_t MEMORY_SIZE_2{32};
uint64_t MEMORY_ALIGNMENT_2{16};
EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));
EXPECT_CALL(memoryBlock2, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_2));
EXPECT_CALL(memoryBlock2, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_2));
EXPECT_CALL(memoryBlock2, memoryAvailableMock(_));
memoryProvider1.addMemoryBlock(&memoryBlock1);
memoryProvider2.addMemoryBlock(&memoryBlock2);
sut.addMemoryProvider(&memoryProvider1);
sut.addMemoryProvider(&memoryProvider2);
EXPECT_THAT(sut.createAndAnnounceMemory().has_error(), Eq(false));
EXPECT_CALL(memoryBlock1, destroyMock());
EXPECT_CALL(memoryBlock2, destroyMock());
}
TEST_F(RouDiMemoryManager_Test, RouDiMemoryManagerDTorTriggersMemoryProviderDestroy)
{
uint64_t MEMORY_SIZE_1{16};
uint64_t MEMORY_ALIGNMENT_1{8};
EXPECT_CALL(memoryBlock1, sizeMock()).WillRepeatedly(Return(MEMORY_SIZE_1));
EXPECT_CALL(memoryBlock1, alignmentMock()).WillRepeatedly(Return(MEMORY_ALIGNMENT_1));
EXPECT_CALL(memoryBlock1, memoryAvailableMock(_));
memoryProvider1.addMemoryBlock(&memoryBlock1);
{
RouDiMemoryManager sutDestroy;
sutDestroy.addMemoryProvider(&memoryProvider1);
sutDestroy.createAndAnnounceMemory();
EXPECT_CALL(memoryBlock1, destroyMock()).Times(1);
}
EXPECT_CALL(memoryBlock1, destroyMock()).Times(0);
}
TEST_F(RouDiMemoryManager_Test, AddMemoryProviderExceedsCapacity)
{
MemoryProviderTestImpl memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER + 1];
RouDiMemoryManager sutExhausting;
for (uint32_t i = 0; i < iox::MAX_NUMBER_OF_MEMORY_PROVIDER; ++i)
{
EXPECT_THAT(sutExhausting.addMemoryProvider(&memoryProvider[i]).has_error(), Eq(false));
}
auto expectError = sutExhausting.addMemoryProvider(&memoryProvider[iox::MAX_NUMBER_OF_MEMORY_PROVIDER]);
ASSERT_THAT(expectError.has_error(), Eq(true));
EXPECT_THAT(expectError.get_error(), Eq(RouDiMemoryManagerError::MEMORY_PROVIDER_EXHAUSTED));
}
/// @todo Add TEST_F(RouDiMemoryManager_Test, StreamOperatorTranslationIsCorrect)
#endif
<|endoftext|>
|
<commit_before>/*
This file is part of Akonadi.
Copyright (c) 2009 Till Adam <adam@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "jobtrackermodel.h"
#include "jobtracker.h"
#include <QtCore/QStringList>
#include <QtCore/QModelIndex>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <cassert>
class JobTrackerModel::Private
{
public:
Private( JobTrackerModel* _q )
:q(_q)
{
}
JobTracker tracker;
private:
JobTrackerModel* const q;
};
JobTrackerModel::JobTrackerModel( QObject* parent )
:QAbstractItemModel( parent ), d( new Private(this ) )
{
connect( &d->tracker, SIGNAL( updated() ),
this, SIGNAL( modelReset() ) );
}
JobTrackerModel::~JobTrackerModel()
{
delete d;
}
QModelIndex JobTrackerModel::index(int row, int column, const QModelIndex & parent) const
{
if ( !parent.isValid() ) // session, at top level
{
return createIndex( row, column, d->tracker.idForSession( d->tracker.sessions().at(row) ) );
}
// non-toplevel job
const QList<JobInfo> jobs = d->tracker.jobs( parent.internalId() );
if ( row >= jobs.size() ) return QModelIndex();
return createIndex( row, column, d->tracker.idForJob( jobs.at( row ).id ) );
}
QModelIndex JobTrackerModel::parent(const QModelIndex & idx) const
{
if ( !idx.isValid() ) return QModelIndex();
const int parentid = d->tracker.parentId( idx.internalId() );
if ( parentid == -1 ) return QModelIndex(); // top level session
const int grandparentid = d->tracker.parentId( parentid );
int row = -1;
if ( grandparentid == -1 )
{
row = d->tracker.sessions().indexOf( d->tracker.sessionForId( parentid ) );
}
else
{
// offset of the parent in the list of children of the grandparent
row = d->tracker.jobs( grandparentid ).indexOf( d->tracker.info( parentid ) );
}
assert( row != -1 );
return createIndex( row, 0, parentid );
}
int JobTrackerModel::rowCount(const QModelIndex & parent) const
{
if ( !parent.isValid() )
{
return d->tracker.sessions().size();
}
else
{
return d->tracker.jobs( parent.internalId() ).size();
}
}
int JobTrackerModel::columnCount(const QModelIndex & parent) const
{
return 4;
}
QVariant JobTrackerModel::data(const QModelIndex & idx, int role) const
{
// top level items are sessions
if ( !idx.parent().isValid() )
{
if ( role == Qt::DisplayRole )
{
if( idx.column() == 0 )
{
assert(d->tracker.sessions().size() > idx.row());
return d->tracker.sessions().at(idx.row());
}
}
}
else // not top level, so a job or subjob
{
const int id = idx.internalId();
const JobInfo info = d->tracker.info( id );
if ( role == Qt::DisplayRole )
{
if ( idx.column() == 0 )
return info.id;
if ( idx.column() == 1 )
return info.timestamp;
if ( idx.column() == 2 )
return info.type;
if ( idx.column() == 3 )
return info.running;
}
}
return QVariant();
}
QVariant JobTrackerModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if ( role == Qt::DisplayRole )
{
if ( orientation == Qt::Horizontal )
{
if ( section == 0 )
return QLatin1String("Job ID");
if ( section == 1 )
return QLatin1String("Timestamp");
if ( section == 2 )
return QLatin1String("Running");
}
}
return QVariant();
}
Qt::ItemFlags JobTrackerModel::flags(const QModelIndex & index) const
{
Qt::ItemFlags f = QAbstractItemModel::flags( index );
if ( index.isValid() && index.parent().isValid() )
{
const JobInfo info = d->tracker.info( index.internalId() );
if ( !info.running )
f ^= Qt::ItemIsEnabled;
}
return f;
}
#include "jobtrackermodel.moc"
<commit_msg>fix crash<commit_after>/*
This file is part of Akonadi.
Copyright (c) 2009 Till Adam <adam@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include "jobtrackermodel.h"
#include "jobtracker.h"
#include <QtCore/QStringList>
#include <QtCore/QModelIndex>
#include <QtCore/QDebug>
#include <QtCore/QDateTime>
#include <cassert>
class JobTrackerModel::Private
{
public:
Private( JobTrackerModel* _q )
:q(_q)
{
}
JobTracker tracker;
private:
JobTrackerModel* const q;
};
JobTrackerModel::JobTrackerModel( QObject* parent )
:QAbstractItemModel( parent ), d( new Private(this ) )
{
connect( &d->tracker, SIGNAL( updated() ),
this, SIGNAL( modelReset() ) );
}
JobTrackerModel::~JobTrackerModel()
{
delete d;
}
QModelIndex JobTrackerModel::index(int row, int column, const QModelIndex & parent) const
{
if ( !parent.isValid() ) // session, at top level
{
if ( row < 0 || row >= d->tracker.sessions().size() )
return QModelIndex();
return createIndex( row, column, d->tracker.idForSession( d->tracker.sessions().at(row) ) );
}
// non-toplevel job
const QList<JobInfo> jobs = d->tracker.jobs( parent.internalId() );
if ( row >= jobs.size() ) return QModelIndex();
return createIndex( row, column, d->tracker.idForJob( jobs.at( row ).id ) );
}
QModelIndex JobTrackerModel::parent(const QModelIndex & idx) const
{
if ( !idx.isValid() ) return QModelIndex();
const int parentid = d->tracker.parentId( idx.internalId() );
if ( parentid == -1 ) return QModelIndex(); // top level session
const int grandparentid = d->tracker.parentId( parentid );
int row = -1;
if ( grandparentid == -1 )
{
row = d->tracker.sessions().indexOf( d->tracker.sessionForId( parentid ) );
}
else
{
// offset of the parent in the list of children of the grandparent
row = d->tracker.jobs( grandparentid ).indexOf( d->tracker.info( parentid ) );
}
assert( row != -1 );
return createIndex( row, 0, parentid );
}
int JobTrackerModel::rowCount(const QModelIndex & parent) const
{
if ( !parent.isValid() )
{
return d->tracker.sessions().size();
}
else
{
return d->tracker.jobs( parent.internalId() ).size();
}
}
int JobTrackerModel::columnCount(const QModelIndex & parent) const
{
return 4;
}
QVariant JobTrackerModel::data(const QModelIndex & idx, int role) const
{
// top level items are sessions
if ( !idx.parent().isValid() )
{
if ( role == Qt::DisplayRole )
{
if( idx.column() == 0 )
{
assert(d->tracker.sessions().size() > idx.row());
return d->tracker.sessions().at(idx.row());
}
}
}
else // not top level, so a job or subjob
{
const int id = idx.internalId();
const JobInfo info = d->tracker.info( id );
if ( role == Qt::DisplayRole )
{
if ( idx.column() == 0 )
return info.id;
if ( idx.column() == 1 )
return info.timestamp;
if ( idx.column() == 2 )
return info.type;
if ( idx.column() == 3 )
return info.running;
}
}
return QVariant();
}
QVariant JobTrackerModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if ( role == Qt::DisplayRole )
{
if ( orientation == Qt::Horizontal )
{
if ( section == 0 )
return QLatin1String("Job ID");
if ( section == 1 )
return QLatin1String("Timestamp");
if ( section == 2 )
return QLatin1String("Running");
}
}
return QVariant();
}
Qt::ItemFlags JobTrackerModel::flags(const QModelIndex & index) const
{
Qt::ItemFlags f = QAbstractItemModel::flags( index );
if ( index.isValid() && index.parent().isValid() )
{
const JobInfo info = d->tracker.info( index.internalId() );
if ( !info.running )
f ^= Qt::ItemIsEnabled;
}
return f;
}
#include "jobtrackermodel.moc"
<|endoftext|>
|
<commit_before>#include "engine/hash_map.h"
#include "engine/log.h"
#include "engine/timer.h"
#include "engine/mt/sync.h"
#include "engine/mt/thread.h"
#include "profiler.h"
namespace Lumix
{
namespace Profiler
{
struct Block
{
struct Hit
{
u64 m_length;
u64 m_start;
};
explicit Block(IAllocator& allocator)
: allocator(allocator)
, m_hits(allocator)
, m_type(BlockType::TIME)
{
}
~Block()
{
while (m_first_child)
{
Block* child = m_first_child->m_next;
LUMIX_DELETE(allocator, m_first_child);
m_first_child = child;
}
}
void frame()
{
m_values.int_value = 0;
m_hits.clear();
if (m_first_child)
{
m_first_child->frame();
}
if (m_next)
{
m_next->frame();
}
}
IAllocator& allocator;
Block* m_parent;
Block* m_next;
Block* m_first_child;
const char* m_name;
Array<Hit> m_hits;
BlockType m_type;
union
{
float float_value;
int int_value;
} m_values;
};
const char* getBlockName(Block* block)
{
return block->m_name;
}
int getBlockInt(Block* block)
{
return block->m_values.int_value;
}
BlockType getBlockType(Block* block)
{
return block->m_type;
}
Block* getBlockFirstChild(Block* block)
{
return block->m_first_child;
}
Block* getBlockNext(Block* block)
{
return block->m_next;
}
u64 getBlockHitStart(Block* block, int hit_index)
{
return block->m_hits[hit_index].m_start;
}
u64 getBlockHitLength(Block* block, int hit_index)
{
return block->m_hits[hit_index].m_length;
}
int getBlockHitCount(Block* block)
{
return block->m_hits.size();
}
struct ThreadData
{
ThreadData()
{
root_block = current_block = nullptr;
name[0] = '\0';
}
Block* root_block;
Block* current_block;
char name[30];
};
struct Instance
{
Instance()
: threads(allocator)
, frame_listeners(allocator)
, mutex(false)
{
threads.insert(MT::getCurrentThreadID(), &main_thread);
timer = Timer::create(allocator);
}
~Instance()
{
Timer::destroy(timer);
for (auto* i : threads)
{
if (i != &main_thread) {
LUMIX_DELETE(allocator, i->root_block);
LUMIX_DELETE(allocator, i);
}
}
threads.clear();
}
DefaultAllocator allocator;
DelegateList<void()> frame_listeners;
HashMap<MT::ThreadID, ThreadData*> threads;
ThreadData main_thread;
Timer* timer;
MT::SpinMutex mutex;
};
Instance g_instance;
float getBlockLength(Block* block)
{
u64 ret = 0;
for(int i = 0, c = block->m_hits.size(); i < c; ++i)
{
ret += block->m_hits[i].m_length;
}
return float(ret / (double)g_instance.timer->getFrequency());
}
struct BlockInfo
{
Block* block;
ThreadData* thread_data;
};
static BlockInfo getBlock(const char* name)
{
auto thread_id = MT::getCurrentThreadID();
ThreadData* thread_data;
{
MT::SpinLock lock(g_instance.mutex);
auto iter = g_instance.threads.find(thread_id);
if (iter == g_instance.threads.end())
{
g_instance.threads.insert(thread_id, LUMIX_NEW(g_instance.allocator, ThreadData));
iter = g_instance.threads.find(thread_id);
}
thread_data = iter.value();
}
if (!thread_data->current_block)
{
Block* LUMIX_RESTRICT root = thread_data->root_block;
while (root && root->m_name != name)
{
root = root->m_next;
}
if (root)
{
thread_data->current_block = root;
}
else
{
Block* root = LUMIX_NEW(g_instance.allocator, Block)(g_instance.allocator);
root->m_parent = nullptr;
root->m_next = thread_data->root_block;
root->m_first_child = nullptr;
root->m_name = name;
thread_data->root_block = thread_data->current_block = root;
}
}
else
{
Block* LUMIX_RESTRICT child = thread_data->current_block->m_first_child;
while (child && child->m_name != name)
{
child = child->m_next;
}
if (!child)
{
child = LUMIX_NEW(g_instance.allocator, Block)(g_instance.allocator);
child->m_parent = thread_data->current_block;
child->m_first_child = nullptr;
child->m_name = name;
child->m_next = thread_data->current_block->m_first_child;
thread_data->current_block->m_first_child = child;
}
thread_data->current_block = child;
}
return { thread_data->current_block, thread_data };
}
void record(const char* name, int value)
{
auto data = getBlock(name);
if (data.block->m_type != BlockType::INT)
{
data.block->m_values.int_value = 0;
data.block->m_type = BlockType::INT;
}
data.block->m_values.int_value += value;
data.thread_data->current_block = data.block->m_parent;
}
void* beginBlock(const char* name)
{
BlockInfo data = getBlock(name);
Block::Hit& hit = data.block->m_hits.emplace();
hit.m_start = g_instance.timer->getRawTimeSinceStart();
hit.m_length = 0;
return data.block;
}
const char* getThreadName(MT::ThreadID thread_id)
{
auto iter = g_instance.threads.find(thread_id);
if (iter == g_instance.threads.end()) return "N/A";
return iter.value()->name;
}
void setThreadName(const char* name)
{
MT::SpinLock lock(g_instance.mutex);
MT::ThreadID thread_id = MT::getCurrentThreadID();
auto iter = g_instance.threads.find(thread_id);
if (iter == g_instance.threads.end())
{
g_instance.threads.insert(thread_id, LUMIX_NEW(g_instance.allocator, ThreadData));
iter = g_instance.threads.find(thread_id);
}
copyString(iter.value()->name, name);
}
MT::ThreadID getThreadID(int index)
{
auto iter = g_instance.threads.begin();
auto end = g_instance.threads.end();
for (int i = 0; i < index; ++i)
{
++iter;
if (iter == end) return 0;
}
return iter.key();
}
int getThreadIndex(MT::ThreadID id)
{
auto iter = g_instance.threads.begin();
auto end = g_instance.threads.end();
int idx = 0;
while(iter != end)
{
if (iter.key() == id) return idx;
++idx;
++iter;
}
return -1;
}
int getThreadCount()
{
return g_instance.threads.size();
}
u64 now()
{
return g_instance.timer->getRawTimeSinceStart();
}
Block* getRootBlock(MT::ThreadID thread_id)
{
auto iter = g_instance.threads.find(thread_id);
if (!iter.isValid()) return nullptr;
return iter.value()->root_block;
}
Block* getCurrentBlock()
{
auto thread_id = MT::getCurrentThreadID();
ThreadData* thread_data;
{
MT::SpinLock lock(g_instance.mutex);
auto iter = g_instance.threads.find(thread_id);
ASSERT(iter.isValid());
thread_data = iter.value();
}
return thread_data->current_block;
}
void* endBlock()
{
auto thread_id = MT::getCurrentThreadID();
ThreadData* thread_data;
{
MT::SpinLock lock(g_instance.mutex);
auto iter = g_instance.threads.find(thread_id);
ASSERT(iter.isValid());
thread_data = iter.value();
}
ASSERT(thread_data->current_block);
auto* block = thread_data->current_block;
u64 now = g_instance.timer->getRawTimeSinceStart();
thread_data->current_block->m_hits.back().m_length = now - thread_data->current_block->m_hits.back().m_start;
thread_data->current_block = thread_data->current_block->m_parent;
return block;
}
void frame()
{
PROFILE_FUNCTION();
MT::SpinLock lock(g_instance.mutex);
g_instance.frame_listeners.invoke();
u64 now = g_instance.timer->getRawTimeSinceStart();
for (auto* i : g_instance.threads)
{
if (!i->root_block) continue;
i->root_block->frame();
auto* block = i->current_block;
while (block)
{
auto& hit = block->m_hits.emplace();
hit.m_start = now;
hit.m_length = 0;
block = block->m_parent;
}
}
}
DelegateList<void()>& getFrameListeners()
{
return g_instance.frame_listeners;
}
} // namespace Lumix
} // namespace Profiler
<commit_msg>fixed leak<commit_after>#include "engine/hash_map.h"
#include "engine/log.h"
#include "engine/timer.h"
#include "engine/mt/sync.h"
#include "engine/mt/thread.h"
#include "profiler.h"
namespace Lumix
{
namespace Profiler
{
struct Block
{
struct Hit
{
u64 m_length;
u64 m_start;
};
explicit Block(IAllocator& allocator)
: allocator(allocator)
, m_hits(allocator)
, m_type(BlockType::TIME)
{
}
~Block()
{
while (m_first_child)
{
Block* child = m_first_child->m_next;
LUMIX_DELETE(allocator, m_first_child);
m_first_child = child;
}
}
void frame()
{
m_values.int_value = 0;
m_hits.clear();
if (m_first_child)
{
m_first_child->frame();
}
if (m_next)
{
m_next->frame();
}
}
IAllocator& allocator;
Block* m_parent;
Block* m_next;
Block* m_first_child;
const char* m_name;
Array<Hit> m_hits;
BlockType m_type;
union
{
float float_value;
int int_value;
} m_values;
};
const char* getBlockName(Block* block)
{
return block->m_name;
}
int getBlockInt(Block* block)
{
return block->m_values.int_value;
}
BlockType getBlockType(Block* block)
{
return block->m_type;
}
Block* getBlockFirstChild(Block* block)
{
return block->m_first_child;
}
Block* getBlockNext(Block* block)
{
return block->m_next;
}
u64 getBlockHitStart(Block* block, int hit_index)
{
return block->m_hits[hit_index].m_start;
}
u64 getBlockHitLength(Block* block, int hit_index)
{
return block->m_hits[hit_index].m_length;
}
int getBlockHitCount(Block* block)
{
return block->m_hits.size();
}
struct ThreadData
{
ThreadData()
{
root_block = current_block = nullptr;
name[0] = '\0';
}
Block* root_block;
Block* current_block;
char name[30];
};
struct Instance
{
Instance()
: threads(allocator)
, frame_listeners(allocator)
, mutex(false)
{
threads.insert(MT::getCurrentThreadID(), &main_thread);
timer = Timer::create(allocator);
}
~Instance()
{
Timer::destroy(timer);
for (auto* i : threads)
{
if (i != &main_thread) {
LUMIX_DELETE(allocator, i->root_block);
LUMIX_DELETE(allocator, i);
}
}
LUMIX_DELETE(allocator, main_thread.root_block);
threads.clear();
}
DefaultAllocator allocator;
DelegateList<void()> frame_listeners;
HashMap<MT::ThreadID, ThreadData*> threads;
ThreadData main_thread;
Timer* timer;
MT::SpinMutex mutex;
};
Instance g_instance;
float getBlockLength(Block* block)
{
u64 ret = 0;
for(int i = 0, c = block->m_hits.size(); i < c; ++i)
{
ret += block->m_hits[i].m_length;
}
return float(ret / (double)g_instance.timer->getFrequency());
}
struct BlockInfo
{
Block* block;
ThreadData* thread_data;
};
static BlockInfo getBlock(const char* name)
{
auto thread_id = MT::getCurrentThreadID();
ThreadData* thread_data;
{
MT::SpinLock lock(g_instance.mutex);
auto iter = g_instance.threads.find(thread_id);
if (iter == g_instance.threads.end())
{
g_instance.threads.insert(thread_id, LUMIX_NEW(g_instance.allocator, ThreadData));
iter = g_instance.threads.find(thread_id);
}
thread_data = iter.value();
}
if (!thread_data->current_block)
{
Block* LUMIX_RESTRICT root = thread_data->root_block;
while (root && root->m_name != name)
{
root = root->m_next;
}
if (root)
{
thread_data->current_block = root;
}
else
{
Block* root = LUMIX_NEW(g_instance.allocator, Block)(g_instance.allocator);
root->m_parent = nullptr;
root->m_next = thread_data->root_block;
root->m_first_child = nullptr;
root->m_name = name;
thread_data->root_block = thread_data->current_block = root;
}
}
else
{
Block* LUMIX_RESTRICT child = thread_data->current_block->m_first_child;
while (child && child->m_name != name)
{
child = child->m_next;
}
if (!child)
{
child = LUMIX_NEW(g_instance.allocator, Block)(g_instance.allocator);
child->m_parent = thread_data->current_block;
child->m_first_child = nullptr;
child->m_name = name;
child->m_next = thread_data->current_block->m_first_child;
thread_data->current_block->m_first_child = child;
}
thread_data->current_block = child;
}
return { thread_data->current_block, thread_data };
}
void record(const char* name, int value)
{
auto data = getBlock(name);
if (data.block->m_type != BlockType::INT)
{
data.block->m_values.int_value = 0;
data.block->m_type = BlockType::INT;
}
data.block->m_values.int_value += value;
data.thread_data->current_block = data.block->m_parent;
}
void* beginBlock(const char* name)
{
BlockInfo data = getBlock(name);
Block::Hit& hit = data.block->m_hits.emplace();
hit.m_start = g_instance.timer->getRawTimeSinceStart();
hit.m_length = 0;
return data.block;
}
const char* getThreadName(MT::ThreadID thread_id)
{
auto iter = g_instance.threads.find(thread_id);
if (iter == g_instance.threads.end()) return "N/A";
return iter.value()->name;
}
void setThreadName(const char* name)
{
MT::SpinLock lock(g_instance.mutex);
MT::ThreadID thread_id = MT::getCurrentThreadID();
auto iter = g_instance.threads.find(thread_id);
if (iter == g_instance.threads.end())
{
g_instance.threads.insert(thread_id, LUMIX_NEW(g_instance.allocator, ThreadData));
iter = g_instance.threads.find(thread_id);
}
copyString(iter.value()->name, name);
}
MT::ThreadID getThreadID(int index)
{
auto iter = g_instance.threads.begin();
auto end = g_instance.threads.end();
for (int i = 0; i < index; ++i)
{
++iter;
if (iter == end) return 0;
}
return iter.key();
}
int getThreadIndex(MT::ThreadID id)
{
auto iter = g_instance.threads.begin();
auto end = g_instance.threads.end();
int idx = 0;
while(iter != end)
{
if (iter.key() == id) return idx;
++idx;
++iter;
}
return -1;
}
int getThreadCount()
{
return g_instance.threads.size();
}
u64 now()
{
return g_instance.timer->getRawTimeSinceStart();
}
Block* getRootBlock(MT::ThreadID thread_id)
{
auto iter = g_instance.threads.find(thread_id);
if (!iter.isValid()) return nullptr;
return iter.value()->root_block;
}
Block* getCurrentBlock()
{
auto thread_id = MT::getCurrentThreadID();
ThreadData* thread_data;
{
MT::SpinLock lock(g_instance.mutex);
auto iter = g_instance.threads.find(thread_id);
ASSERT(iter.isValid());
thread_data = iter.value();
}
return thread_data->current_block;
}
void* endBlock()
{
auto thread_id = MT::getCurrentThreadID();
ThreadData* thread_data;
{
MT::SpinLock lock(g_instance.mutex);
auto iter = g_instance.threads.find(thread_id);
ASSERT(iter.isValid());
thread_data = iter.value();
}
ASSERT(thread_data->current_block);
auto* block = thread_data->current_block;
u64 now = g_instance.timer->getRawTimeSinceStart();
thread_data->current_block->m_hits.back().m_length = now - thread_data->current_block->m_hits.back().m_start;
thread_data->current_block = thread_data->current_block->m_parent;
return block;
}
void frame()
{
PROFILE_FUNCTION();
MT::SpinLock lock(g_instance.mutex);
g_instance.frame_listeners.invoke();
u64 now = g_instance.timer->getRawTimeSinceStart();
for (auto* i : g_instance.threads)
{
if (!i->root_block) continue;
i->root_block->frame();
auto* block = i->current_block;
while (block)
{
auto& hit = block->m_hits.emplace();
hit.m_start = now;
hit.m_length = 0;
block = block->m_parent;
}
}
}
DelegateList<void()>& getFrameListeners()
{
return g_instance.frame_listeners;
}
} // namespace Lumix
} // namespace Profiler
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Definitions for the Spatial Pooler
*/
#ifndef NTA_flat_spatial_pooler_HPP
#define NTA_flat_spatial_pooler_HPP
#include <cstring>
#include <iostream>
#include <nta/algorithms/spatial_pooler.hpp>
#include <nta/types/types.hpp>
#include <string>
#include <vector>
using namespace std;
namespace nta {
namespace algorithms {
namespace spatial_pooler {
/////////////////////////////////////////////////////////////////////////
/// CLA flat spatial pooler implementation in C++.
///
/// @b Responsibility
/// The Spatial Pooler is responsible for creating a sparse distributed
/// representation of the input. It computes the set of active columns.
/// It maintains the state of the proximal dendrites between the columns
/// and the inputs bits and keeps track of the activity and overlap
/// duty cycles
///
/// @b Description
/// Todo.
///
/////////////////////////////////////////////////////////////////////////
class FlatSpatialPooler : public SpatialPooler {
public:
FlatSpatialPooler() {}
~FlatSpatialPooler() {}
virtual void save(ostream& outStream);
virtual void load(istream& inStream);
virtual UInt version() const {
return version_;
};
Real getMinDistance();
void setMinDistance(Real minDistance);
bool getRandomSP();
void setRandomSP(bool randomSP);
virtual void compute(UInt inputVector[], bool learn,
UInt activeVector[]);
void addBonus_(vector<Real>& vec, Real bonus,
vector<UInt>& indices, bool replace);
void selectVirginColumns_(vector<UInt>& virgin);
void selectHighTierColumns_(vector<Real>& overlapsPct,
vector<UInt> &highTier);
virtual void initializeFlat(
UInt numInputs,
UInt numColumns,
Real potentialPct = 0.5,
Real localAreaDensity=0,
UInt numActiveColumnsPerInhArea=10,
UInt stimulusThreshold=0,
Real synPermInactiveDec=0.01,
Real synPermActiveInc=0.1,
Real synPermConnected=0.1,
Real minPctOverlapDutyCycles=0.001,
Real minPctActiveDutyCycles=0.001,
UInt dutyCyclePeriod=1000,
Real maxBoost=10.0,
Real minDistance=0.0,
bool randomSP=false,
Int seed=-1,
UInt spVerbosity=0);
//-------------------------------------------------------------------
// Debugging helpers
//-------------------------------------------------------------------
// Print the creation parameters specific to this class
void printFlatParameters();
protected:
Real minDistance_;
bool randomSP_;
vector<UInt> highTier_;
vector<UInt> virgin_;
};
} // end namespace spatial_pooler
} // end namespace algorithms
} // end namespace nta
#endif // NTA_flat_spatial_pooler_HPP
<commit_msg>Make FlatSpatialPooler destructor virtual.<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Definitions for the Spatial Pooler
*/
#ifndef NTA_flat_spatial_pooler_HPP
#define NTA_flat_spatial_pooler_HPP
#include <cstring>
#include <iostream>
#include <nta/algorithms/spatial_pooler.hpp>
#include <nta/types/types.hpp>
#include <string>
#include <vector>
using namespace std;
namespace nta {
namespace algorithms {
namespace spatial_pooler {
/////////////////////////////////////////////////////////////////////////
/// CLA flat spatial pooler implementation in C++.
///
/// @b Responsibility
/// The Spatial Pooler is responsible for creating a sparse distributed
/// representation of the input. It computes the set of active columns.
/// It maintains the state of the proximal dendrites between the columns
/// and the inputs bits and keeps track of the activity and overlap
/// duty cycles
///
/// @b Description
/// Todo.
///
/////////////////////////////////////////////////////////////////////////
class FlatSpatialPooler : public SpatialPooler {
public:
FlatSpatialPooler() {}
virtual ~FlatSpatialPooler() {}
virtual void save(ostream& outStream);
virtual void load(istream& inStream);
virtual UInt version() const {
return version_;
};
Real getMinDistance();
void setMinDistance(Real minDistance);
bool getRandomSP();
void setRandomSP(bool randomSP);
virtual void compute(UInt inputVector[], bool learn,
UInt activeVector[]);
void addBonus_(vector<Real>& vec, Real bonus,
vector<UInt>& indices, bool replace);
void selectVirginColumns_(vector<UInt>& virgin);
void selectHighTierColumns_(vector<Real>& overlapsPct,
vector<UInt> &highTier);
virtual void initializeFlat(
UInt numInputs,
UInt numColumns,
Real potentialPct = 0.5,
Real localAreaDensity=0,
UInt numActiveColumnsPerInhArea=10,
UInt stimulusThreshold=0,
Real synPermInactiveDec=0.01,
Real synPermActiveInc=0.1,
Real synPermConnected=0.1,
Real minPctOverlapDutyCycles=0.001,
Real minPctActiveDutyCycles=0.001,
UInt dutyCyclePeriod=1000,
Real maxBoost=10.0,
Real minDistance=0.0,
bool randomSP=false,
Int seed=-1,
UInt spVerbosity=0);
//-------------------------------------------------------------------
// Debugging helpers
//-------------------------------------------------------------------
// Print the creation parameters specific to this class
void printFlatParameters();
protected:
Real minDistance_;
bool randomSP_;
vector<UInt> highTier_;
vector<UInt> virgin_;
};
} // end namespace spatial_pooler
} // end namespace algorithms
} // end namespace nta
#endif // NTA_flat_spatial_pooler_HPP
<|endoftext|>
|
<commit_before>/*
* Chromaprint -- Audio fingerprinting toolkit
* Copyright (C) 2010 Lukas Lalinsky <lalinsky@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include "utils.h"
#include "fft_lib_kissfft.h"
using namespace std;
using namespace Chromaprint;
FFTLib::FFTLib(int frame_size, double *window)
: m_window(window),
m_frame_size(frame_size)
{
cfg = kiss_fftr_alloc(frame_size, 0, NULL, NULL);
m_input = new kiss_fft_scalar[frame_size];
m_output = new kiss_fft_cpx[frame_size];
}
FFTLib::~FFTLib()
{
kiss_fftr_free(cfg);
delete[] m_input;
delete[] m_output;
}
void FFTLib::ComputeFrame(CombinedBuffer<short>::Iterator input, double *output)
{
ApplyWindow(input, m_window, m_input, m_frame_size, 1.0);
kiss_fftr(cfg, m_input, m_output);
const kiss_fft_cpx *in_ptr = m_output;
const kiss_fft_cpx *rev_in_ptr = m_output + m_frame_size - 1;
output[0] = in_ptr[0].r * in_ptr[0].r;
output[m_frame_size / 2] = in_ptr[m_frame_size / 2].r * in_ptr[m_frame_size / 2].r;
in_ptr += 1;
output += 1;
for (int i = 1; i < m_frame_size / 2; i++) {
*output++ = in_ptr[0].r * in_ptr[0].r + rev_in_ptr[0].r * rev_in_ptr[0].r;
in_ptr++;
rev_in_ptr--;
}
}
<commit_msg>Fix Kiss FFT output layout<commit_after>/*
* Chromaprint -- Audio fingerprinting toolkit
* Copyright (C) 2010 Lukas Lalinsky <lalinsky@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*/
#include "utils.h"
#include "fft_lib_kissfft.h"
using namespace std;
using namespace Chromaprint;
FFTLib::FFTLib(int frame_size, double *window)
: m_window(window),
m_frame_size(frame_size)
{
cfg = kiss_fftr_alloc(frame_size, 0, NULL, NULL);
m_input = new kiss_fft_scalar[frame_size];
m_output = new kiss_fft_cpx[frame_size];
}
FFTLib::~FFTLib()
{
kiss_fftr_free(cfg);
delete[] m_input;
delete[] m_output;
}
void FFTLib::ComputeFrame(CombinedBuffer<short>::Iterator input, double *output)
{
ApplyWindow(input, m_window, m_input, m_frame_size, 1.0);
kiss_fftr(cfg, m_input, m_output);
const kiss_fft_cpx *in_ptr = m_output;
for (int i = 0; i <= m_frame_size / 2; i++) {
*output++ = in_ptr[0].r * in_ptr[0].r + in_ptr[0].i * in_ptr[0].i;
in_ptr++;
}
}
<|endoftext|>
|
<commit_before>/*
* param.cpp
*
*/
#include "param.h"
using namespace himan;
using namespace std;
param::~param() {}
param::param()
: itsId(kHPMissingInt),
itsName("XX-X"),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, HPParameterUnit theUnit)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(theUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, double theScale, double theBase,
HPInterpolationMethod theInterpolationMethod)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(theScale),
itsBase(theBase),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(theInterpolationMethod),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, long theGribDiscipline, long theGribCategory,
long theGribParameter)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(theGribParameter),
itsGribCategory(theGribCategory),
itsGribDiscipline(theGribDiscipline),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const map<string, string>& databaseInfo) : param()
{
if (!databaseInfo.empty())
{
itsId = stoi(databaseInfo.at("id"));
itsName = databaseInfo.at("name");
itsVersion = stoi(databaseInfo.at("version"));
try
{
itsGribIndicatorOfParameter = stoi(databaseInfo.at("grib1_number"));
itsGribTableVersion = stoi(databaseInfo.at("grib1_table_version"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsGribDiscipline = stoi(databaseInfo.at("grib2_discipline"));
itsGribCategory = stoi(databaseInfo.at("grib2_category"));
itsGribParameter = stoi(databaseInfo.at("grib2_number"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsPrecision = stoi(databaseInfo.at("precision"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsUnivId = stoi(databaseInfo.at("univ_id"));
itsScale = stod(databaseInfo.at("scale"));
itsBase = stod(databaseInfo.at("base"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
}
}
param::param(const param& other)
: itsId(other.itsId),
itsName(other.itsName),
itsScale(other.itsScale),
itsBase(other.itsBase),
itsUnivId(other.itsUnivId),
itsGribParameter(other.itsGribParameter),
itsGribCategory(other.itsGribCategory),
itsGribDiscipline(other.itsGribDiscipline),
itsGribTableVersion(other.itsGribTableVersion),
itsGribIndicatorOfParameter(other.itsGribIndicatorOfParameter),
itsVersion(other.itsVersion),
itsInterpolationMethod(other.itsInterpolationMethod),
itsUnit(other.itsUnit),
itsAggregation(other.itsAggregation),
itsPrecision(other.itsPrecision)
{
}
param& param::operator=(const param& other)
{
itsId = other.itsId;
itsName = other.itsName;
itsScale = other.itsScale;
itsBase = other.itsBase;
itsUnivId = other.itsUnivId;
itsGribParameter = other.itsGribParameter;
itsGribCategory = other.itsGribCategory;
itsGribDiscipline = other.itsGribDiscipline;
itsGribTableVersion = other.itsGribTableVersion;
itsGribIndicatorOfParameter = other.itsGribIndicatorOfParameter;
itsVersion = other.itsVersion;
itsInterpolationMethod = other.itsInterpolationMethod;
itsUnit = other.itsUnit;
itsAggregation = other.itsAggregation;
itsPrecision = other.itsPrecision;
return *this;
}
bool param::operator==(const param& other) const
{
if (this == &other)
{
return true;
}
if (itsId != other.itsId)
{
return false;
}
if (itsName != other.itsName)
{
return false;
}
if (UnivId() != static_cast<unsigned int>(kHPMissingInt) &&
other.UnivId() != static_cast<unsigned int>(kHPMissingInt) && UnivId() != other.UnivId())
{
return false;
}
// Grib 1
if (itsGribTableVersion != kHPMissingInt && other.GribTableVersion() != kHPMissingInt &&
itsGribTableVersion != other.GribTableVersion())
{
return false;
}
if (itsGribIndicatorOfParameter != kHPMissingInt && other.GribIndicatorOfParameter() != kHPMissingInt &&
itsGribIndicatorOfParameter != other.GribIndicatorOfParameter())
{
return false;
}
// Grib 2
if (itsGribDiscipline != kHPMissingInt && other.GribDiscipline() != kHPMissingInt &&
itsGribDiscipline != other.GribDiscipline())
{
return false;
}
if (itsGribCategory != kHPMissingInt && other.GribCategory() != kHPMissingInt &&
itsGribCategory != other.GribCategory())
{
return false;
}
if (itsGribParameter != kHPMissingInt && other.GribParameter() != kHPMissingInt &&
itsGribParameter != other.GribParameter())
{
return false;
}
if (itsAggregation.Type() != kUnknownAggregationType && other.itsAggregation.Type() != kUnknownAggregationType &&
itsAggregation != other.itsAggregation)
{
return false;
}
if (itsVersion != other.itsVersion)
{
return false;
}
return true;
}
bool param::operator!=(const param& other) const { return !(*this == other); }
void param::GribParameter(long theGribParameter) { itsGribParameter = theGribParameter; }
long param::GribParameter() const { return itsGribParameter; }
void param::GribDiscipline(long theGribDiscipline) { itsGribDiscipline = theGribDiscipline; }
long param::GribDiscipline() const { return itsGribDiscipline; }
void param::GribCategory(long theGribCategory) { itsGribCategory = theGribCategory; }
long param::GribCategory() const { return itsGribCategory; }
void param::GribIndicatorOfParameter(long theGribIndicatorOfParameter)
{
itsGribIndicatorOfParameter = theGribIndicatorOfParameter;
}
long param::GribIndicatorOfParameter() const { return itsGribIndicatorOfParameter; }
unsigned long param::UnivId() const { return itsUnivId; }
void param::UnivId(unsigned long theUnivId) { itsUnivId = theUnivId; }
string param::Name() const { return itsName; }
void param::Name(const string& theName) { itsName = theName; }
HPParameterUnit param::Unit() const { return itsUnit; }
void param::Unit(HPParameterUnit theUnit) { itsUnit = theUnit; }
void param::GribTableVersion(long theVersion) { itsGribTableVersion = theVersion; }
long param::GribTableVersion() const { return itsGribTableVersion; }
const aggregation& param::Aggregation() const { return itsAggregation; }
void param::Aggregation(const aggregation& theAggregation) { itsAggregation = theAggregation; }
double param::Base() const { return itsBase; }
void param::Base(double theBase) { itsBase = theBase; }
double param::Scale() const { return itsScale; }
void param::Scale(double theScale) { itsScale = theScale; }
long param::Id() const { return itsId; }
void param::Id(long theId) { itsId = theId; }
HPInterpolationMethod param::InterpolationMethod() const { return itsInterpolationMethod; }
void param::InterpolationMethod(HPInterpolationMethod theInterpolationMethod)
{
itsInterpolationMethod = theInterpolationMethod;
}
int param::Precision() const { return itsPrecision; }
void param::Precision(int thePrecision) { itsPrecision = thePrecision; }
ostream& param::Write(ostream& file) const
{
file << "<" << ClassName() << ">" << endl;
file << "__itsName__ " << itsName << endl;
file << "__itsScale__ " << itsScale << endl;
file << "__itsBase__ " << itsBase << endl;
file << "__itsUnivId__ " << itsUnivId << endl;
file << "__itsGribParameter__ " << itsGribParameter << endl;
file << "__itsGribCategory__ " << itsGribCategory << endl;
file << "__itsGribDiscipline__ " << itsGribDiscipline << endl;
file << "__itsGribTableVersion__ " << itsGribTableVersion << endl;
file << "__itsIndicatorOfParameter__ " << itsGribIndicatorOfParameter << endl;
file << "__itsUnit__ " << static_cast<int>(itsUnit) << endl;
file << "__itsVersion__ " << itsVersion << endl;
file << "__itsInterpolationMethod__ " << HPInterpolationMethodToString.at(itsInterpolationMethod) << endl;
file << "__itsPrecision__" << itsPrecision << endl;
file << itsAggregation;
return file;
}
<commit_msg>Remove comparison of output file numbers for param.<commit_after>/*
* param.cpp
*
*/
#include "param.h"
using namespace himan;
using namespace std;
param::~param() {}
param::param()
: itsId(kHPMissingInt),
itsName("XX-X"),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, HPParameterUnit theUnit)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(theUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(kHPMissingInt),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, double theScale, double theBase,
HPInterpolationMethod theInterpolationMethod)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(theScale),
itsBase(theBase),
itsUnivId(theUnivId),
itsGribParameter(kHPMissingInt),
itsGribCategory(kHPMissingInt),
itsGribDiscipline(kHPMissingInt),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(theInterpolationMethod),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const string& theName, unsigned long theUnivId, long theGribDiscipline, long theGribCategory,
long theGribParameter)
: itsId(kHPMissingInt),
itsName(theName),
itsScale(1),
itsBase(0),
itsUnivId(theUnivId),
itsGribParameter(theGribParameter),
itsGribCategory(theGribCategory),
itsGribDiscipline(theGribDiscipline),
itsGribTableVersion(kHPMissingInt),
itsGribIndicatorOfParameter(kHPMissingInt),
itsVersion(1),
itsInterpolationMethod(kBiLinear),
itsUnit(kUnknownUnit),
itsAggregation(),
itsPrecision(kHPMissingInt)
{
}
param::param(const map<string, string>& databaseInfo) : param()
{
if (!databaseInfo.empty())
{
itsId = stoi(databaseInfo.at("id"));
itsName = databaseInfo.at("name");
itsVersion = stoi(databaseInfo.at("version"));
try
{
itsGribIndicatorOfParameter = stoi(databaseInfo.at("grib1_number"));
itsGribTableVersion = stoi(databaseInfo.at("grib1_table_version"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsGribDiscipline = stoi(databaseInfo.at("grib2_discipline"));
itsGribCategory = stoi(databaseInfo.at("grib2_category"));
itsGribParameter = stoi(databaseInfo.at("grib2_number"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsPrecision = stoi(databaseInfo.at("precision"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
try
{
itsUnivId = stoi(databaseInfo.at("univ_id"));
itsScale = stod(databaseInfo.at("scale"));
itsBase = stod(databaseInfo.at("base"));
}
catch (const out_of_range& e)
{
}
catch (const invalid_argument& e)
{
}
}
}
param::param(const param& other)
: itsId(other.itsId),
itsName(other.itsName),
itsScale(other.itsScale),
itsBase(other.itsBase),
itsUnivId(other.itsUnivId),
itsGribParameter(other.itsGribParameter),
itsGribCategory(other.itsGribCategory),
itsGribDiscipline(other.itsGribDiscipline),
itsGribTableVersion(other.itsGribTableVersion),
itsGribIndicatorOfParameter(other.itsGribIndicatorOfParameter),
itsVersion(other.itsVersion),
itsInterpolationMethod(other.itsInterpolationMethod),
itsUnit(other.itsUnit),
itsAggregation(other.itsAggregation),
itsPrecision(other.itsPrecision)
{
}
param& param::operator=(const param& other)
{
itsId = other.itsId;
itsName = other.itsName;
itsScale = other.itsScale;
itsBase = other.itsBase;
itsUnivId = other.itsUnivId;
itsGribParameter = other.itsGribParameter;
itsGribCategory = other.itsGribCategory;
itsGribDiscipline = other.itsGribDiscipline;
itsGribTableVersion = other.itsGribTableVersion;
itsGribIndicatorOfParameter = other.itsGribIndicatorOfParameter;
itsVersion = other.itsVersion;
itsInterpolationMethod = other.itsInterpolationMethod;
itsUnit = other.itsUnit;
itsAggregation = other.itsAggregation;
itsPrecision = other.itsPrecision;
return *this;
}
bool param::operator==(const param& other) const
{
if (this == &other)
{
return true;
}
if (itsName != other.itsName)
{
return false;
}
if (itsAggregation.Type() != kUnknownAggregationType && other.itsAggregation.Type() != kUnknownAggregationType &&
itsAggregation != other.itsAggregation)
{
return false;
}
if (itsVersion != other.itsVersion)
{
return false;
}
return true;
}
bool param::operator!=(const param& other) const { return !(*this == other); }
void param::GribParameter(long theGribParameter) { itsGribParameter = theGribParameter; }
long param::GribParameter() const { return itsGribParameter; }
void param::GribDiscipline(long theGribDiscipline) { itsGribDiscipline = theGribDiscipline; }
long param::GribDiscipline() const { return itsGribDiscipline; }
void param::GribCategory(long theGribCategory) { itsGribCategory = theGribCategory; }
long param::GribCategory() const { return itsGribCategory; }
void param::GribIndicatorOfParameter(long theGribIndicatorOfParameter)
{
itsGribIndicatorOfParameter = theGribIndicatorOfParameter;
}
long param::GribIndicatorOfParameter() const { return itsGribIndicatorOfParameter; }
unsigned long param::UnivId() const { return itsUnivId; }
void param::UnivId(unsigned long theUnivId) { itsUnivId = theUnivId; }
string param::Name() const { return itsName; }
void param::Name(const string& theName) { itsName = theName; }
HPParameterUnit param::Unit() const { return itsUnit; }
void param::Unit(HPParameterUnit theUnit) { itsUnit = theUnit; }
void param::GribTableVersion(long theVersion) { itsGribTableVersion = theVersion; }
long param::GribTableVersion() const { return itsGribTableVersion; }
const aggregation& param::Aggregation() const { return itsAggregation; }
void param::Aggregation(const aggregation& theAggregation) { itsAggregation = theAggregation; }
double param::Base() const { return itsBase; }
void param::Base(double theBase) { itsBase = theBase; }
double param::Scale() const { return itsScale; }
void param::Scale(double theScale) { itsScale = theScale; }
long param::Id() const { return itsId; }
void param::Id(long theId) { itsId = theId; }
HPInterpolationMethod param::InterpolationMethod() const { return itsInterpolationMethod; }
void param::InterpolationMethod(HPInterpolationMethod theInterpolationMethod)
{
itsInterpolationMethod = theInterpolationMethod;
}
int param::Precision() const { return itsPrecision; }
void param::Precision(int thePrecision) { itsPrecision = thePrecision; }
ostream& param::Write(ostream& file) const
{
file << "<" << ClassName() << ">" << endl;
file << "__itsName__ " << itsName << endl;
file << "__itsScale__ " << itsScale << endl;
file << "__itsBase__ " << itsBase << endl;
file << "__itsUnivId__ " << itsUnivId << endl;
file << "__itsGribParameter__ " << itsGribParameter << endl;
file << "__itsGribCategory__ " << itsGribCategory << endl;
file << "__itsGribDiscipline__ " << itsGribDiscipline << endl;
file << "__itsGribTableVersion__ " << itsGribTableVersion << endl;
file << "__itsIndicatorOfParameter__ " << itsGribIndicatorOfParameter << endl;
file << "__itsUnit__ " << static_cast<int>(itsUnit) << endl;
file << "__itsVersion__ " << itsVersion << endl;
file << "__itsInterpolationMethod__ " << HPInterpolationMethodToString.at(itsInterpolationMethod) << endl;
file << "__itsPrecision__" << itsPrecision << endl;
file << itsAggregation;
return file;
}
<|endoftext|>
|
<commit_before>#include <node.h>
#include <nan.h>
#include <rpcsvc/ypclnt.h>
using namespace v8;
extern "C" {
int foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data);
}
NAN_METHOD(Match) {
HandleScope scope;
int error;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("Second argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value inkey(args[1]->ToString());
char *outval;
int outvallen;
error = yp_match(*domain, *mapname, *inkey, inkey.length(), &outval, &outvallen);
if (YPERR_KEY == error) {
return scope.Close(Undefined());
} else if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return scope.Close(String::New(outval, outvallen));
}
NAN_METHOD(Next) {
HandleScope scope;
int error;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("Second argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value inkey(args[1]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
char *outkey, *outval;
int outkeylen, outvallen;
error = yp_next(*domain, *mapname, *inkey, inkey.length(), &outkey, &outkeylen, &outval, &outvallen);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
Local<Object> obj = Object::New();
obj->Set(String::New("key"), String::New(outkey, outkeylen));
obj->Set(String::New("value"), String::New(outval, outvallen));
return obj;
}
NAN_METHOD(First) {
HandleScope scope;
int error;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
char *outkey, *outval;
int outkeylen, outvallen;
error = yp_first(*domain, *mapname, &outkey, &outkeylen, &outval, &outvallen);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
Local<Object> obj = Object::New();
obj->Set(String::New("key"), String::New(outkey, outkeylen));
obj->Set(String::New("value"), String::New(outval, outvallen));
return obj;
}
NAN_METHOD(Master) {
HandleScope scope;
int error;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
char *outname;
error = yp_master(*domain, *mapname, &outname);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return String::New(outname);
}
NAN_METHOD(Order) {
HandleScope scope;
int error;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
int outorder;
error = yp_order(*domain, *mapname, &outorder);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return Integer::New(outorder);
}
NAN_METHOD(All) {
HandleScope scope;
int error;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
if (!args[1]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Second argument must be function")));
return scope.Close(Undefined());
}
Local<Function> user_cb = Local<Function>::Cast(args[1]);
struct ypall_callback cb;
cb.foreach = foreach_all;
cb.data = (char *) &user_cb;
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
error = yp_all(*domain, *mapname, &cb);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return scope.Close(Undefined());
}
extern "C"
int foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data) {
Local<Function> *cb = static_cast<Local<Function> *>(data);
const int argc = 3;
Local<Value> argv[argc] = {
Local<Value>::New(Integer::NewFromUnsigned(instatus)),
Local<Value>::New(String::New(inkey, inkeylen)),
Local<Value>::New(String::New(inval, invallen))
};
Local<Value> ret = (*cb)->Call(Context::GetCurrent()->Global(), argc, argv);
return ret->Int32Value();
}
NAN_METHOD(CreateObject) {
HandleScope scope;
char* domp;
int error;
Local<Object> obj = Object::New();
error = yp_get_default_domain(&domp);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
obj->Set(NanSymbol("domain_name"), String::New(domp));
obj->Set(NanSymbol("all"), FunctionTemplate::New(All)->GetFunction());
obj->Set(NanSymbol("order"), FunctionTemplate::New(Order)->GetFunction());
obj->Set(NanSymbol("master"), FunctionTemplate::New(Master)->GetFunction());
obj->Set(NanSymbol("first"), FunctionTemplate::New(First)->GetFunction());
obj->Set(NanSymbol("next"), FunctionTemplate::New(Next)->GetFunction());
obj->Set(NanSymbol("match"), FunctionTemplate::New(Match)->GetFunction());
return scope.Close(obj);
}
void Initialize(Handle<Object> exports, Handle<Object> module) {
module->Set(
NanSymbol("exports"),
FunctionTemplate::New(CreateObject)->GetFunction()
);
}
NODE_MODULE(nis, Initialize);
<commit_msg>Close the handle scope<commit_after>#include <node.h>
#include <nan.h>
#include <rpcsvc/ypclnt.h>
using namespace v8;
extern "C" {
int foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data);
}
NAN_METHOD(Match) {
HandleScope scope;
int error;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("Second argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value inkey(args[1]->ToString());
char *outval;
int outvallen;
error = yp_match(*domain, *mapname, *inkey, inkey.length(), &outval, &outvallen);
if (YPERR_KEY == error) {
return scope.Close(Undefined());
} else if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return scope.Close(String::New(outval, outvallen));
}
NAN_METHOD(Next) {
HandleScope scope;
int error;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("Second argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value inkey(args[1]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
char *outkey, *outval;
int outkeylen, outvallen;
error = yp_next(*domain, *mapname, *inkey, inkey.length(), &outkey, &outkeylen, &outval, &outvallen);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
Local<Object> obj = Object::New();
obj->Set(String::New("key"), String::New(outkey, outkeylen));
obj->Set(String::New("value"), String::New(outval, outvallen));
return scope.Close(obj);
}
NAN_METHOD(First) {
HandleScope scope;
int error;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
char *outkey, *outval;
int outkeylen, outvallen;
error = yp_first(*domain, *mapname, &outkey, &outkeylen, &outval, &outvallen);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
Local<Object> obj = Object::New();
obj->Set(String::New("key"), String::New(outkey, outkeylen));
obj->Set(String::New("value"), String::New(outval, outvallen));
return scope.Close(obj);
}
NAN_METHOD(Master) {
HandleScope scope;
int error;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
char *outname;
error = yp_master(*domain, *mapname, &outname);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return scope.Close(String::New(outname));
}
NAN_METHOD(Order) {
HandleScope scope;
int error;
if (args.Length() < 1) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
int outorder;
error = yp_order(*domain, *mapname, &outorder);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return scope.Close(Integer::New(outorder));
}
NAN_METHOD(All) {
HandleScope scope;
int error;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Not enough arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsString()) {
ThrowException(Exception::TypeError(String::New("First argument must be string")));
return scope.Close(Undefined());
}
if (!args[1]->IsFunction()) {
ThrowException(Exception::TypeError(String::New("Second argument must be function")));
return scope.Close(Undefined());
}
Local<Function> user_cb = Local<Function>::Cast(args[1]);
struct ypall_callback cb;
cb.foreach = foreach_all;
cb.data = (char *) &user_cb;
String::Utf8Value mapname(args[0]->ToString());
String::Utf8Value domain(args.Holder()->Get(NanSymbol("domain_name")));
error = yp_all(*domain, *mapname, &cb);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
return scope.Close(Undefined());
}
extern "C"
int foreach_all(unsigned long instatus, char *inkey, int inkeylen, char *inval, int invallen, void *data) {
Local<Function> *cb = static_cast<Local<Function> *>(data);
const int argc = 3;
Local<Value> argv[argc] = {
Local<Value>::New(Integer::NewFromUnsigned(instatus)),
Local<Value>::New(String::New(inkey, inkeylen)),
Local<Value>::New(String::New(inval, invallen))
};
Local<Value> ret = (*cb)->Call(Context::GetCurrent()->Global(), argc, argv);
return ret->Int32Value();
}
NAN_METHOD(CreateObject) {
HandleScope scope;
char* domp;
int error;
Local<Object> obj = Object::New();
error = yp_get_default_domain(&domp);
if (error) {
Local<String> errorMessage = String::New(yperr_string(error));
ThrowException(Exception::Error(errorMessage));
}
obj->Set(NanSymbol("domain_name"), String::New(domp));
obj->Set(NanSymbol("all"), FunctionTemplate::New(All)->GetFunction());
obj->Set(NanSymbol("order"), FunctionTemplate::New(Order)->GetFunction());
obj->Set(NanSymbol("master"), FunctionTemplate::New(Master)->GetFunction());
obj->Set(NanSymbol("first"), FunctionTemplate::New(First)->GetFunction());
obj->Set(NanSymbol("next"), FunctionTemplate::New(Next)->GetFunction());
obj->Set(NanSymbol("match"), FunctionTemplate::New(Match)->GetFunction());
return scope.Close(obj);
}
void Initialize(Handle<Object> exports, Handle<Object> module) {
module->Set(
NanSymbol("exports"),
FunctionTemplate::New(CreateObject)->GetFunction()
);
}
NODE_MODULE(nis, Initialize);
<|endoftext|>
|
<commit_before>#include "../dbstore.h"
#include "../print.h"
#include "../userin.h"
#include <iostream>
#include <string>
using namespace std;
void hide_n_follow()
{
print("\nYou followed the pirate silently, while keeping your distance.\n", "green");
print("\nEventually you got to one of the storage units of your station.\n", "magenta");
print("Do you:");
print("1) Go inside");
print("2) Keep going to find the other pirate crew members");
print("3) Look for your crew members");
int choice = int_option(3);
if (choice == 1) {
}
if (choice == 2) {
}
if (choice == 3) {
}
}
void start_story_D()
{
print("What do you do? ");
print("1) Hide");
print("2) Hide and follow ");
print("3) Attempt stealth kill");
//print("4) Shoot with lazer gun");
int choice = int_option(3);
if (choice == 1) {
print("\nYou stayed hidden for a day but when you fell asleep a crew member found you and killed in the spot ", "red");
}
if (choice == 2) {
hide_n_follow();
}
if (choice == 3) {
print("\nYou snuck behind the crew member and tried to choke him, but you were too weak from starvation and he got out of your grip.", "red");
print("He alerted the rest of the pirates and you were gunned down like a dog ", "red");
}
}<commit_msg>Code added to Story-D<commit_after>#include "../dbstore.h"
#include "../print.h"
#include "../userin.h"
#include <iostream>
#include <string>
using namespace std;
void stealth_killstreak()
{
print(" ");
}
void take_hostage()
{
print("\nYou grab a pirate in choke hold\n", "green");
print("\nYou tell them to lead you to whoever is in charge.They lead you to their captain ", "magenta");
print("Do you:");
print("1) Ask the captain to free your crew so that you can go on your way");
print("2) Tell him to release your crew and to get out of the station");
int choice = int_option(2);
if (choice == 1) {
print("He says you're not getting out alive and pushes a self destruction button", "red");
}
if (choice == 2) {
print("He blinks oddly but you don't acknowledge it and moments later you get a bullet in the back of the head", "red");
}
}
void crew_member_search_with_guns()
{
print("\nNow that you have supplies you go search for your crew\n", "green");
print("\nAs you are lurking around your space station you spot a group of space pirates", "magenta");
print("Do you:");
print("1) Shoot with granade launcher");
print("2) Sneak behind them and take a hostage");
print("3) Continue stealth approach");
int choice = int_option(3);
if (choice == 1) {
print("When you shoot you don't take cover and fly back from the impact wave causing you to break your back and die in pain");
}
if (choice == 2) {
take_hostage();
}
if (choice == 3) {
stealth_killstreak();
}
}
void badass_for_a_moment()
{
print("\nYou snap the pirates neck and drag the body out of the way\n", "green");
print("\nWhile dragging the body his com activated. There was no response and after a short while you are surrounded by 20-30 pirates ", "magenta");
print("Do you");
print("1) Attempt mass murder.");
print("2) Try and be friendly");
int choice = int_option(2);
if (choice == 1) {
print("You have no chance and you are killed in less than a second.", "red");
}
if (choice == 2) {
print("You say HI and are welcomed by a flock of bullets.", "red");
}
}
void crew_member_search()
{
print("\nYou take a lift to the lower deck and see that there are members of your crew locked into sleeping chambers\n", "green");
print("\nThe lift is being called up.", "magenta");
print("Do you:");
print("1) Get in the lift hoping to surprise and kill whoever is trying to get in the lift");
print("2) Attempt opening the chambers");
print("3) Surrender");
int choice = int_option(3);
if (choice == 1) {
badass_for_a_moment();
}
if (choice == 2) {
print("The chamber is locked with a biometric scanner. You give up and get shot down.", "red");
}
if (choice == 3) {
print("No questions asked. You get shot multiple times in the head.", "red");
}
}
void go_inside()
{
print("\nYou go inside the storage unit.\n", "green");
print("\nYou see a armor vest and a mini granade launcher\n", "magenta");
print("Do you:");
print("1) Look for your crew members");
print("2) Find the other pirate crew members and eliminate them");
int choice = int_option(2);
if (choice == 1) {
crew_member_search_with_guns();
}
if (choice == 2) {
print("You find a group of pirates and try to kill them with the granade launcher, but it jams and the granade explodes in your hands.", "red");
}
}
void hide_n_follow()
{
print("\nYou followed the pirate silently, while keeping your distance.\n", "green");
print("\nEventually you got to one of the storage units of your station.\n", "magenta");
print("Do you:");
print("1) Go inside");
print("2) Keep going to find the other pirate crew members");
print("3) Look for your crew members");
int choice = int_option(3);
if (choice == 1) {
go_inside();
}
if (choice == 2) {
print("You follow the pirate to the food court and for a moment you stare at the other pirates ", "red");
}
if (choice == 3) {
crew_member_search();
}
}
void start_story_D()
{
print("What do you do? ");
print("1) Hide");
print("2) Hide and follow ");
print("3) Attempt stealth kill");
//print("4) Shoot with lazer gun");
int choice = int_option(3);
if (choice == 1) {
print("\nYou stayed hidden for a day but when you fell asleep a crew member found you and killed in the spot ", "red");
}
if (choice == 2) {
hide_n_follow();
}
if (choice == 3) {
print("\nYou snuck behind the crew member and tried to choke him, but you were too weak from starvation and he got out of your grip.", "red");
print("He alerted the rest of the pirates and you were gunned down like a dog ", "red");
}
}<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#define DLL_SVM_SUPPORT
#include "dll/rbm/dyn_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/transform/shape_layer_1d.hpp"
#include "dll/transform/binarize_layer.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("unit/dyn_dbn/mnist/1", "[dyn_dbn][unit]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::layer_t,
dll::dyn_rbm_desc<dll::momentum>::layer_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<25>, dll::trainer<dll::cg_trainer>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(300);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->template layer_get<0>().init_layer(28 * 28, 150);
dbn->template layer_get<1>().init_layer(150, 150);
dbn->template layer_get<2>().init_layer(150, 10);
dbn->pretrain(dataset.training_images, 25);
auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
std::cout << "ft_error:" << ft_error << std::endl;
REQUIRE(ft_error < 5e-2);
TEST_CHECK(0.2);
}
TEST_CASE("unit/dyn_dbn/mnist/2", "[dyn_dbn][sgd][unit]") {
using dbn_t = dll::dbn_desc<
dll::dbn_layers<
dll::shape_layer_1d_desc<28 * 28>::layer_t,
dll::binarize_layer_desc<30>::layer_t,
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::layer_t,
dll::dyn_rbm_desc<dll::momentum>::layer_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<25>>::dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(250);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->template layer_get<2>().init_layer(28 * 28, 150);
dbn->template layer_get<3>().init_layer(150, 200);
dbn->template layer_get<4>().init_layer(200, 10);
dbn->learning_rate = 0.05;
dbn->pretrain(dataset.training_images, 20);
auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
std::cout << "ft_error:" << ft_error << std::endl;
REQUIRE(ft_error < 1e-1);
TEST_CHECK(0.3);
}
<commit_msg>Make the test more stable<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <deque>
#include "dll_test.hpp"
#define DLL_SVM_SUPPORT
#include "dll/rbm/dyn_rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/transform/shape_layer_1d.hpp"
#include "dll/transform/binarize_layer.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
TEST_CASE("unit/dyn_dbn/mnist/1", "[dyn_dbn][unit]") {
typedef dll::dbn_desc<
dll::dbn_layers<
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::layer_t,
dll::dyn_rbm_desc<dll::momentum>::layer_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::batch_size<25>, dll::trainer<dll::cg_trainer>>::dbn_t dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(300);
REQUIRE(!dataset.training_images.empty());
mnist::binarize_dataset(dataset);
auto dbn = std::make_unique<dbn_t>();
dbn->template layer_get<0>().init_layer(28 * 28, 150);
dbn->template layer_get<1>().init_layer(150, 150);
dbn->template layer_get<2>().init_layer(150, 10);
dbn->pretrain(dataset.training_images, 35);
auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 5);
std::cout << "ft_error:" << ft_error << std::endl;
REQUIRE(ft_error < 5e-2);
TEST_CHECK(0.22);
}
TEST_CASE("unit/dyn_dbn/mnist/2", "[dyn_dbn][sgd][unit]") {
using dbn_t = dll::dbn_desc<
dll::dbn_layers<
dll::shape_layer_1d_desc<28 * 28>::layer_t,
dll::binarize_layer_desc<30>::layer_t,
dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::layer_t,
dll::dyn_rbm_desc<dll::momentum>::layer_t,
dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::layer_t>,
dll::trainer<dll::sgd_trainer>, dll::momentum, dll::batch_size<25>>::dbn_t;
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_matrix<float, 1>>(250);
REQUIRE(!dataset.training_images.empty());
auto dbn = std::make_unique<dbn_t>();
dbn->template layer_get<2>().init_layer(28 * 28, 150);
dbn->template layer_get<3>().init_layer(150, 200);
dbn->template layer_get<4>().init_layer(200, 10);
dbn->learning_rate = 0.05;
dbn->pretrain(dataset.training_images, 20);
auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 50);
std::cout << "ft_error:" << ft_error << std::endl;
REQUIRE(ft_error < 1e-1);
TEST_CHECK(0.3);
}
<|endoftext|>
|
<commit_before>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
typedef R (*stub_ptr_type)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename std::enable_if<
!std::is_same<delegate, typename std::decay<T>::type>{}
>::type
>
delegate(T&& f)
: store_(operator new(sizeof(T)),
functor_deleter<typename std::decay<T>::type>),
store_size_(sizeof(T))
{
typedef typename std::decay<T>::type functor_type;
new (store_.get()) functor_type(std::forward<T>(f));
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
deleter_ = destructor_stub<functor_type>;
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename std::enable_if<
!std::is_same<delegate, typename std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
typedef typename std::decay<T>::type functor_type;
if ((sizeof(T) > store_size_)
|| (decltype(store_.use_count())(1) != store_.use_count()))
{
store_.reset(operator new(sizeof(T)), functor_deleter<functor_type>);
store_size_ = sizeof(T);
}
else
{
deleter_(store_.get());
}
new (store_.get()) functor_type(std::forward<T>(f));
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
deleter_ = destructor_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
typedef void (*deleter_type)(void*);
void* object_ptr_;
stub_ptr_type stub_ptr_{};
deleter_type deleter_;
std::shared_ptr<void> store_;
std::size_t store_size_;
template <class T>
static void destructor_stub(void* const p)
{
static_cast<T*>(p)->~T();
}
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T*>(p)->~T();
operator delete(p);
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<commit_msg>some typedefs removed<commit_after>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP
#include <cassert>
#include <memory>
#include <new>
#include <type_traits>
#include <utility>
template <typename T> class delegate;
template<class R, class ...A>
class delegate<R (A...)>
{
using stub_ptr_type = R (*)(void*, A&&...);
delegate(void* const o, stub_ptr_type const m) noexcept
: object_ptr_(o),
stub_ptr_(m)
{
}
public:
delegate() = default;
delegate(delegate const&) = default;
delegate(delegate&&) = default;
template <class C>
explicit delegate(C const* const o) noexcept
: object_ptr_(const_cast<C*>(o))
{
}
template <class C>
explicit delegate(C const& o) noexcept
: object_ptr_(const_cast<C*>(&o))
{
}
delegate(R (* const function_ptr)(A...))
{
*this = from(function_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...))
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C* const object_ptr, R (C::* const method_ptr)(A...) const)
{
*this = from(object_ptr, method_ptr);
}
template <class C>
delegate(C& object, R (C::* const method_ptr)(A...))
{
*this = from(object, method_ptr);
}
template <class C>
delegate(C const& object, R (C::* const method_ptr)(A...) const)
{
*this = from(object, method_ptr);
}
template <
typename T,
typename = typename std::enable_if<
!std::is_same<delegate, typename std::decay<T>::type>{}
>::type
>
delegate(T&& f)
: store_(operator new(sizeof(T)),
functor_deleter<typename std::decay<T>::type>),
store_size_(sizeof(T))
{
using functor_type = typename std::decay<T>::type;
new (store_.get()) functor_type(std::forward<T>(f));
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
deleter_ = destructor_stub<functor_type>;
}
delegate& operator=(delegate const&) = default;
delegate& operator=(delegate&& rhs) = default;
delegate& operator=(R (* const rhs)(A...))
{
return *this = from(rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...))
{
return *this = from(static_cast<C*>(object_ptr_), rhs);
}
template <class C>
delegate& operator=(R (C::* const rhs)(A...) const)
{
return *this = from(static_cast<C const*>(object_ptr_), rhs);
}
template <
typename T,
typename = typename std::enable_if<
!std::is_same<delegate, typename std::decay<T>::type>{}
>::type
>
delegate& operator=(T&& f)
{
using functor_type = typename std::decay<T>::type;
if ((sizeof(T) > store_size_)
|| (decltype(store_.use_count())(1) != store_.use_count()))
{
store_.reset(operator new(sizeof(T)), functor_deleter<functor_type>);
store_size_ = sizeof(T);
}
else
{
deleter_(store_.get());
}
new (store_.get()) functor_type(std::forward<T>(f));
object_ptr_ = store_.get();
stub_ptr_ = functor_stub<functor_type>;
deleter_ = destructor_stub<functor_type>;
return *this;
}
template <R (* const function_ptr)(A...)>
static delegate from() noexcept
{
return { nullptr, function_stub<function_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C* const object_ptr) noexcept
{
return { object_ptr, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const* const object_ptr) noexcept
{
return { const_cast<C*>(object_ptr), const_method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...)>
static delegate from(C& object) noexcept
{
return { &object, method_stub<C, method_ptr> };
}
template <class C, R (C::* const method_ptr)(A...) const>
static delegate from(C const& object) noexcept
{
return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
}
template <typename T>
static delegate from(T&& f)
{
return std::forward<T>(f);
}
static delegate from(R (* const function_ptr)(A...))
{
return [function_ptr](A&&... args) {
return (*function_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C* const object_ptr,
R (C::* const method_ptr)(A...))
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const* const object_ptr,
R (C::* const method_ptr)(A...) const)
{
return [object_ptr, method_ptr](A&&... args) {
return (object_ptr->*method_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C& object, R (C::* const method_ptr)(A...))
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(std::forward<A>(args)...); };
}
template <class C>
static delegate from(C const& object,
R (C::* const method_ptr)(A...) const)
{
return [&object, method_ptr](A&&... args) {
return (object.*method_ptr)(std::forward<A>(args)...); };
}
void reset() { stub_ptr_ = nullptr; store_.reset(); }
void swap(delegate& other) noexcept { ::std::swap(*this, other); }
bool operator==(delegate const& rhs) const noexcept
{
return (object_ptr_ == rhs.object_ptr_) && (stub_ptr_ == rhs.stub_ptr_);
}
bool operator!=(delegate const& rhs) const noexcept
{
return !operator==(rhs);
}
bool operator<(delegate const& rhs) const noexcept
{
return (object_ptr_ < rhs.object_ptr_) ||
((object_ptr_ == rhs.object_ptr_) && (stub_ptr_ < rhs.stub_ptr_));
}
explicit operator bool() const noexcept { return stub_ptr_; }
R operator()(A... args) const
{
// assert(stub_ptr);
return stub_ptr_(object_ptr_, std::forward<A>(args)...);
}
private:
friend class ::std::hash<delegate>;
using deleter_type = void (*)(void*);
void* object_ptr_;
stub_ptr_type stub_ptr_{};
deleter_type deleter_;
std::shared_ptr<void> store_;
std::size_t store_size_;
template <class T>
static void destructor_stub(void* const p)
{
static_cast<T*>(p)->~T();
}
template <class T>
static void functor_deleter(void* const p)
{
static_cast<T*>(p)->~T();
operator delete(p);
}
template <R (*function_ptr)(A...)>
static R function_stub(void* const, A&&... args)
{
return function_ptr(std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...)>
static R method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C*>(object_ptr)->*method_ptr)(
std::forward<A>(args)...);
}
template <class C, R (C::*method_ptr)(A...) const>
static R const_method_stub(void* const object_ptr, A&&... args)
{
return (static_cast<C const*>(object_ptr)->*method_ptr)(
std::forward<A>(args)...);
}
template <typename T>
static R functor_stub(void* const object_ptr, A&&... args)
{
return (*static_cast<T*>(object_ptr))(std::forward<A>(args)...);
}
};
namespace std
{
template <typename R, typename ...A>
struct hash<delegate<R (A...)> >
{
size_t operator()(delegate<R (A...)> const& d) const noexcept
{
auto const seed(hash<void*>()(d.object_ptr_));
return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_) +
0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
}
#endif // DELEGATE_HPP
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.