<commit_before>#include "stdafx.h"
#include "include/cef_runnable.h"
#include "ScriptCore.h"
#include "ScriptException.h"

namespace CefSharp
{
    bool ScriptCore::TryGetMainFrame(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame>& frame)
    {
        if (browser != nullptr)
        {
            frame = browser->GetMainFrame();
            return frame != nullptr;
        }
        else
        {
            return false;
        }
    }

    void ScriptCore::UIT_Execute(CefRefPtr<CefBrowser> browser, CefString script)
    {
        CefRefPtr<CefFrame> mainFrame;
        if (TryGetMainFrame(browser, mainFrame))
        {
            mainFrame->ExecuteJavaScript(script, "about:blank", 0);
        }
    }

    void ScriptCore::UIT_Evaluate(CefRefPtr<CefBrowser> browser, CefString script)
    {
        CefRefPtr<CefFrame> mainFrame;
        if (TryGetMainFrame(browser, mainFrame))
        {
            CefRefPtr<CefV8Context> context = mainFrame->GetV8Context();

            if (context.get() && context->Enter())
            {
                CefRefPtr<CefV8Value> global = context->GetGlobal();
                CefRefPtr<CefV8Value> eval = global->GetValue("eval");
                CefRefPtr<CefV8Value> arg = CefV8Value::CreateString(script);
                CefRefPtr<CefV8Value> result;
                CefRefPtr<CefV8Exception> exception;

                CefV8ValueList args;
                args.push_back(arg);

                result = eval->ExecuteFunctionWithContext(context, global, args);

                if (result == nullptr)
                {
                    // XXX
                    _exceptionMessage = "Error";
                }
                else
                {
                    try
                    {
                        _result = convertFromCef(result);
                    }
                    catch (Exception^ ex)
                    {
                        _exceptionMessage = ex->Message;
                    }
                }

                context->Exit();
            }
        }
        else
        {
            _exceptionMessage = "Failed to obtain reference to main frame";
        }

        SetEvent(_event);
    }

    void ScriptCore::Execute(CefRefPtr<CefBrowser> browser, CefString script)
    {
        if (CefCurrentlyOn(TID_UI))
        {
            UIT_Execute(browser, script);
        }
        else
        {
            CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Execute,
                browser, script));
        }
    }

    gcroot<Object^> ScriptCore::Evaluate(CefRefPtr<CefBrowser> browser, CefString script, double timeout)
    {
        AutoLock lock_scope(this);
        _result = nullptr;
        _exceptionMessage = nullptr;

        if (CefCurrentlyOn(TID_UI))
        {
            UIT_Evaluate(browser, script);
        }
        else
        {
            CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Evaluate,
                browser, script));
        }

        switch (WaitForSingleObject(_event, timeout))
        {
        case WAIT_TIMEOUT:
            throw gcnew ScriptException("Script timed out");
        case WAIT_ABANDONED:
        case WAIT_FAILED:
            throw gcnew ScriptException("Script error");
        }

        if (_exceptionMessage)
        {
            throw gcnew ScriptException(_exceptionMessage);
        }
        else
        {
            return _result;
        }
    }
}<commit_msg>ScriptCore::UIT_EvaluateScript: use CefV8Context::Eval()<commit_after>#include "stdafx.h"
#include "include/cef_runnable.h"
#include "ScriptCore.h"
#include "ScriptException.h"

namespace CefSharp
{
    bool ScriptCore::TryGetMainFrame(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame>& frame)
    {
        if (browser != nullptr)
        {
            frame = browser->GetMainFrame();
            return frame != nullptr;
        }
        else
        {
            return false;
        }
    }

    void ScriptCore::UIT_Execute(CefRefPtr<CefBrowser> browser, CefString script)
    {
        CefRefPtr<CefFrame> mainFrame;
        if (TryGetMainFrame(browser, mainFrame))
        {
            mainFrame->ExecuteJavaScript(script, "about:blank", 0);
        }
    }

    void ScriptCore::UIT_Evaluate(CefRefPtr<CefBrowser> browser, CefString script)
    {
        CefRefPtr<CefFrame> mainFrame;
        if (TryGetMainFrame(browser, mainFrame))
        {
            CefRefPtr<CefV8Context> context = mainFrame->GetV8Context();

            if (context.get() && context->Enter())
            {
                CefRefPtr<CefV8Value> result;
                CefRefPtr<CefV8Exception> exception;

                bool success = context->Eval(script, result, exception);
                if (success)
                {
                   try
                    {
                        _result = convertFromCef(result);
                    }
                    catch (Exception^ ex)
                    {
                        _exceptionMessage = ex->Message;
                    }
                }
                else if (exception.get())
                {
                    _exceptionMessage = toClr(exception->GetMessage());
                }
                else
                {
                    _exceptionMessage = "Failed to evaluate script";
                }

                context->Exit();
            }
        }
        else
        {
            _exceptionMessage = "Failed to obtain reference to main frame";
        }

        SetEvent(_event);
    }

    void ScriptCore::Execute(CefRefPtr<CefBrowser> browser, CefString script)
    {
        if (CefCurrentlyOn(TID_UI))
        {
            UIT_Execute(browser, script);
        }
        else
        {
            CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Execute,
                browser, script));
        }
    }

    gcroot<Object^> ScriptCore::Evaluate(CefRefPtr<CefBrowser> browser, CefString script, double timeout)
    {
        AutoLock lock_scope(this);
        _result = nullptr;
        _exceptionMessage = nullptr;

        if (CefCurrentlyOn(TID_UI))
        {
            UIT_Evaluate(browser, script);
        }
        else
        {
            CefPostTask(TID_UI, NewCefRunnableMethod(this, &ScriptCore::UIT_Evaluate,
                browser, script));
        }

        switch (WaitForSingleObject(_event, timeout))
        {
        case WAIT_TIMEOUT:
            throw gcnew ScriptException("Script timed out");
        case WAIT_ABANDONED:
        case WAIT_FAILED:
            throw gcnew ScriptException("Script error");
        }

        if (_exceptionMessage)
        {
            throw gcnew ScriptException(_exceptionMessage);
        }
        else
        {
            return _result;
        }
    }
}<|endoftext|>


<commit_before>#include <Cpp/Events.hpp>
#include <gtest/gtest.h>

class Sender
{
public:
	void fire() { somethingHappened_.fire(); }
	Cpp::EventRef<> somethingHappened() { return somethingHappened_; }
private:
	Cpp::Event<> somethingHappened_;
};

class Reciever
{
public:
	Reciever() : val_() {}

	void increment() { ++val_; }
	void decrement() { --val_; }
	int value() const { return val_; }
	void setValue(int v) { val_ = v; }
private:
	int val_;
};

class SenderEx : public Sender
{
public:
	SenderEx() : stage_() {}

	int stage() const { return stage_; }

	void runStage()
	{
		if(!stage_) stage_ = 1;
		else stage_ *= 2;
		fire();
	}
private:
	int stage_;
};

class RecieverEx
{
public:
	RecieverEx()
		: sender_()
		, scope_()
		, val_()
	{}

	int value() const { return val_; }

	void connect(SenderEx * sender, Cpp::ConnectionScope * scope)
	{
		sender_ = sender;
		scope_ = scope;
		scope->connect(sender->somethingHappened(), this, &RecieverEx::work);
	}

	void work()
	{
		++val_;

		int stage = sender_->stage();
		if(stage < 4)
		{
			RecieverEx * next = this + stage;
			next->connect(sender_, scope_);
		}
	}
private:
	SenderEx * sender_;
	Cpp::ConnectionScope * scope_;
	int val_;
};

////////////////////////////////////////////////////////////////////////////////
// This test checks basic connection management
TEST(Test_ConnectDisconnect, ManualConnectDisconnect)
{
	Sender sender;
	Reciever r1, r2;
	Cpp::ConnectionScope scope;

	ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());
	sender.fire();
	ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());

	scope.connect(sender.somethingHappened(), &r1, &Reciever::increment);
	sender.fire();	// +1-0 +0-0
	ASSERT_EQ(1, r1.value()); ASSERT_EQ(0, r2.value());
	sender.fire();	// +1-0 +0-0
	ASSERT_EQ(2, r1.value()); ASSERT_EQ(0, r2.value());

	scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
	sender.fire();	// +1-0 +1-0
	ASSERT_EQ(3, r1.value()); ASSERT_EQ(1, r2.value());

	scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
	sender.fire();	// +1-1 +1-0
	ASSERT_EQ(3, r1.value()); ASSERT_EQ(2, r2.value());

	scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
	sender.fire();	// +1-2 +1-0
	ASSERT_EQ(2, r1.value()); ASSERT_EQ(3, r2.value());

	scope.connect(sender.somethingHappened(), &r2, &Reciever::decrement);
	sender.fire();	// +1-2 +1-1
	ASSERT_EQ(1, r1.value()); ASSERT_EQ(3, r2.value());

	scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
	sender.fire();	// +1-2 +2-1
	ASSERT_EQ(0, r1.value()); ASSERT_EQ(4, r2.value());

	sender.somethingHappened().disconnectAll(&r2, &Reciever::decrement);
	sender.fire();	// +1-2 +2-0
	ASSERT_EQ(-1, r1.value()); ASSERT_EQ(6, r2.value());

	sender.somethingHappened().disconnectOne(&r1, &Reciever::decrement);
	sender.fire();	// +1-1 +2-0
	ASSERT_EQ(-1, r1.value()); ASSERT_EQ(8, r2.value());

	sender.somethingHappened().disconnectAll(&r1, &Reciever::increment);
	sender.fire();	// +0-1 +2-0
	ASSERT_EQ(-2, r1.value()); ASSERT_EQ(10, r2.value());

	sender.somethingHappened().disconnectOne(&r2, &Reciever::increment);
	sender.fire();	// +0-1 +1-0
	ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());

	sender.somethingHappened().disconnectAll();
	sender.fire();	// +0-0 +0-0
	ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());
}

////////////////////////////////////////////////////////////////////////////////
// This test checks automatic disconnection
TEST(Test_ConnectDisconnect, AutomaticDisconnect)
{
	Cpp::ConnectionScope scope0;
	Reciever r0;
	{
		Sender sender;

		sender.fire();
		{
			Reciever r1;
			{
				Cpp::ConnectionScope scope1;
				scope1.connect(sender.somethingHappened(), &r1, &Reciever::increment);
				ASSERT_EQ(0, r1.value());
				sender.fire();
				ASSERT_EQ(1, r1.value());
			}
			sender.fire();
			ASSERT_EQ(1, r1.value());
			{
				Cpp::ConnectionScope scope2;
				scope2.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
				ASSERT_EQ(1, r1.value());
				sender.fire();
				ASSERT_EQ(0, r1.value());
			}
			sender.fire();
			ASSERT_EQ(0, r1.value());

			{
				scope0.connect(sender.somethingHappened(), &r0, &Reciever::setValue, 5);
				sender.fire();
				ASSERT_EQ(5, r0.value());
				r0.setValue(-1);
				sender.fire();
				ASSERT_EQ(5, r0.value());
			}
		}
		r0.setValue(-1);
		sender.fire();
		ASSERT_EQ(5, r0.value());
		ASSERT_NE(0, scope0.connectionCount());
	}
	ASSERT_EQ(0, scope0.connectionCount());
}

////////////////////////////////////////////////////////////////////////////////
// This test ensures that adding connections inside delegate works fine.
TEST(Test_ConnectDisconnect, ConnectFromDelegate)
{
	RecieverEx rcv[8];
	Cpp::ConnectionScope scope;
	SenderEx sender;

	rcv[0].connect(&sender, &scope);

	ASSERT_EQ(0, rcv[0].value());
	ASSERT_EQ(0, rcv[1].value());
	ASSERT_EQ(0, rcv[2].value());
	ASSERT_EQ(0, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(1, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(1, rcv[0].value());
	ASSERT_EQ(0, rcv[1].value());
	ASSERT_EQ(0, rcv[2].value());
	ASSERT_EQ(0, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(2, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(2, rcv[0].value());
	ASSERT_EQ(1, rcv[1].value());
	ASSERT_EQ(0, rcv[2].value());
	ASSERT_EQ(0, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(4, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(3, rcv[0].value());
	ASSERT_EQ(2, rcv[1].value());
	ASSERT_EQ(1, rcv[2].value());
	ASSERT_EQ(1, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(8, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(4, rcv[0].value());
	ASSERT_EQ(3, rcv[1].value());
	ASSERT_EQ(2, rcv[2].value());
	ASSERT_EQ(2, rcv[3].value());
	ASSERT_EQ(1, rcv[4].value());
	ASSERT_EQ(1, rcv[5].value());
	ASSERT_EQ(1, rcv[6].value());
	ASSERT_EQ(1, rcv[7].value());
	ASSERT_EQ(8, sender.somethingHappened().connectionCount());
}
<commit_msg>-: Fixed: Bug in Test_ConnectDisconnect.ConnectFromDelegate<commit_after>#include <Cpp/Events.hpp>
#include <gtest/gtest.h>

class Sender
{
public:
	void fire() { somethingHappened_.fire(); }
	Cpp::EventRef<> somethingHappened() { return somethingHappened_; }
private:
	Cpp::Event<> somethingHappened_;
};

class Reciever
{
public:
	Reciever() : val_() {}

	void increment() { ++val_; }
	void decrement() { --val_; }
	int value() const { return val_; }
	void setValue(int v) { val_ = v; }
private:
	int val_;
};

class SenderEx : public Sender
{
public:
	SenderEx()
	{
		stageNo_ = 0; // 1 2 3 4 ...
		stageStep_ = 1; // 2 4 8 16 ...
	}

	int stageNo() const { return stageNo_; }
	int stageStep() const { return stageStep_; }

	void runStage()
	{
		fire();
		++stageNo_;
		stageStep_ *= 2;
	}
private:
	int stageNo_;
	int stageStep_;
};

template<int ArraySize> class RecieverEx
{
public:
	RecieverEx()
		: sender_()
		, scope_()
		, index_(-1)
		, val_()
	{}

	int index() const { return index_; }
	int value() const { return val_; }

	void connect(int ind, SenderEx * sender, Cpp::ConnectionScope * scope)
	{
		index_ = ind;
		sender_ = sender;
		scope_ = scope;
		scope->connect(sender->somethingHappened(), this, &RecieverEx<ArraySize>::work);
	}

	void work()
	{
		++val_;

		int step = sender_->stageStep();
		int nextIndex = index_ + step;
		if(nextIndex < ArraySize)
		{
			RecieverEx<ArraySize> * next = this + step;
			next->connect(nextIndex, sender_, scope_);
		}
	}
private:
	SenderEx * sender_;
	Cpp::ConnectionScope * scope_;
	int index_;
	int val_;
};

////////////////////////////////////////////////////////////////////////////////
// This test checks basic connection management
TEST(Test_ConnectDisconnect, ManualConnectDisconnect)
{
	Sender sender;
	Reciever r1, r2;
	Cpp::ConnectionScope scope;

	ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());
	sender.fire();
	ASSERT_EQ(0, r1.value()); ASSERT_EQ(0, r2.value());

	scope.connect(sender.somethingHappened(), &r1, &Reciever::increment);
	sender.fire();	// +1-0 +0-0
	ASSERT_EQ(1, r1.value()); ASSERT_EQ(0, r2.value());
	sender.fire();	// +1-0 +0-0
	ASSERT_EQ(2, r1.value()); ASSERT_EQ(0, r2.value());

	scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
	sender.fire();	// +1-0 +1-0
	ASSERT_EQ(3, r1.value()); ASSERT_EQ(1, r2.value());

	scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
	sender.fire();	// +1-1 +1-0
	ASSERT_EQ(3, r1.value()); ASSERT_EQ(2, r2.value());

	scope.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
	sender.fire();	// +1-2 +1-0
	ASSERT_EQ(2, r1.value()); ASSERT_EQ(3, r2.value());

	scope.connect(sender.somethingHappened(), &r2, &Reciever::decrement);
	sender.fire();	// +1-2 +1-1
	ASSERT_EQ(1, r1.value()); ASSERT_EQ(3, r2.value());

	scope.connect(sender.somethingHappened(), &r2, &Reciever::increment);
	sender.fire();	// +1-2 +2-1
	ASSERT_EQ(0, r1.value()); ASSERT_EQ(4, r2.value());

	sender.somethingHappened().disconnectAll(&r2, &Reciever::decrement);
	sender.fire();	// +1-2 +2-0
	ASSERT_EQ(-1, r1.value()); ASSERT_EQ(6, r2.value());

	sender.somethingHappened().disconnectOne(&r1, &Reciever::decrement);
	sender.fire();	// +1-1 +2-0
	ASSERT_EQ(-1, r1.value()); ASSERT_EQ(8, r2.value());

	sender.somethingHappened().disconnectAll(&r1, &Reciever::increment);
	sender.fire();	// +0-1 +2-0
	ASSERT_EQ(-2, r1.value()); ASSERT_EQ(10, r2.value());

	sender.somethingHappened().disconnectOne(&r2, &Reciever::increment);
	sender.fire();	// +0-1 +1-0
	ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());

	sender.somethingHappened().disconnectAll();
	sender.fire();	// +0-0 +0-0
	ASSERT_EQ(-3, r1.value()); ASSERT_EQ(11, r2.value());
}

////////////////////////////////////////////////////////////////////////////////
// This test checks automatic disconnection
TEST(Test_ConnectDisconnect, AutomaticDisconnect)
{
	Cpp::ConnectionScope scope0;
	Reciever r0;
	{
		Sender sender;

		sender.fire();
		{
			Reciever r1;
			{
				Cpp::ConnectionScope scope1;
				scope1.connect(sender.somethingHappened(), &r1, &Reciever::increment);
				ASSERT_EQ(0, r1.value());
				sender.fire();
				ASSERT_EQ(1, r1.value());
			}
			sender.fire();
			ASSERT_EQ(1, r1.value());
			{
				Cpp::ConnectionScope scope2;
				scope2.connect(sender.somethingHappened(), &r1, &Reciever::decrement);
				ASSERT_EQ(1, r1.value());
				sender.fire();
				ASSERT_EQ(0, r1.value());
			}
			sender.fire();
			ASSERT_EQ(0, r1.value());

			{
				scope0.connect(sender.somethingHappened(), &r0, &Reciever::setValue, 5);
				sender.fire();
				ASSERT_EQ(5, r0.value());
				r0.setValue(-1);
				sender.fire();
				ASSERT_EQ(5, r0.value());
			}
		}
		r0.setValue(-1);
		sender.fire();
		ASSERT_EQ(5, r0.value());
		ASSERT_NE(0, scope0.connectionCount());
	}
	ASSERT_EQ(0, scope0.connectionCount());
}

////////////////////////////////////////////////////////////////////////////////
// This test ensures that adding connections inside delegate works fine.
TEST(Test_ConnectDisconnect, ConnectFromDelegate)
{
	RecieverEx<8> rcv[8];
	Cpp::ConnectionScope scope;
	SenderEx sender;

	rcv[0].connect(0, &sender, &scope);

	ASSERT_EQ(0, rcv[0].value());
	ASSERT_EQ(0, rcv[1].value());
	ASSERT_EQ(0, rcv[2].value());
	ASSERT_EQ(0, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(1, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(1, rcv[0].value());
	ASSERT_EQ(0, rcv[1].value());
	ASSERT_EQ(0, rcv[2].value());
	ASSERT_EQ(0, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(2, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(2, rcv[0].value());
	ASSERT_EQ(1, rcv[1].value());
	ASSERT_EQ(0, rcv[2].value());
	ASSERT_EQ(0, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(4, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(3, rcv[0].value());
	ASSERT_EQ(2, rcv[1].value());
	ASSERT_EQ(1, rcv[2].value());
	ASSERT_EQ(1, rcv[3].value());
	ASSERT_EQ(0, rcv[4].value());
	ASSERT_EQ(0, rcv[5].value());
	ASSERT_EQ(0, rcv[6].value());
	ASSERT_EQ(0, rcv[7].value());
	ASSERT_EQ(8, sender.somethingHappened().connectionCount());

	sender.runStage();
	ASSERT_EQ(4, rcv[0].value());
	ASSERT_EQ(3, rcv[1].value());
	ASSERT_EQ(2, rcv[2].value());
	ASSERT_EQ(2, rcv[3].value());
	ASSERT_EQ(1, rcv[4].value());
	ASSERT_EQ(1, rcv[5].value());
	ASSERT_EQ(1, rcv[6].value());
	ASSERT_EQ(1, rcv[7].value());
	ASSERT_EQ(8, sender.somethingHappened().connectionCount());
}
<|endoftext|>


<commit_before># include <Siv3D.hpp>

void Main()
{
	//const Texture texture(L"example/siv3d-kun.png");

	while (System::Update())
	{
		Texture texture(L"example/siv3d-kun.png");
	}
}
<commit_msg>v0.1.2 リリース準備<commit_after>
# include <Siv3D.hpp>

void Main()
{
	Graphics::SetBackground(Palette::White);

	double t = 0.0;

	while (System::Update())
	{
		Window::SetTitle(Profiler::FPS(), L"FPS");

		t += System::DeltaTime();

		for (auto i : step(36))
		{
			const double angle = i * 10_deg + t * 30_deg;

			const Vec2 pos = Circular(200, angle) + Window::Center();

			RectF(25).setCenter(pos).rotated(angle).draw(HSV(i * 10));
		}

		Circle(Cursor::Pos(), 40).draw(ColorF(1.0, 0.0, 0.0, 0.5));
	}
}
<|endoftext|>


<commit_before>#include "em.h"

EM::EM(std::function<long double(std::tuple<T...>)> q_function, std::function<std::tuple<T...>(std::tuple<T...>)> m_function, std::tuple<T...> theta) : q_function(q_function), m_function(m_function), likelihood(0), theta(theta){
}

long double EM::likelihood_diff(long double previous, long double current){
	if (current < previous){
		throw std::runtime_error("likelihood went down. previous value: " + std::to_string(previous) ", current value: " + std::to_string(current));
	} else {
		return current - previous;
	}
}

std::vector EM::start(long double stop){
	do{
		long double currentlike = q_function(theta);
		std::clog << "Theta: " << theta << "likelihood: " << currentlike << std::endl;
		long double difference = likelihood_diff(likelihood, currentlike);
		likelihood = currentlike;
		theta = m_function(theta);
	} while (difference < stop);
	return theta;
}

long double EM::get_likelihood(){
	return likelihood;
}

<commit_msg>make function generic<commit_after>#include "em.h"

EM::EM(std::function<long double(std::tuple<T...>)> q_function, std::function<std::tuple<T...>(std::tuple<T...>)> m_function, std::tuple<T...> theta) : q_function(q_function), m_function(m_function), likelihood(0), theta(theta){
}

long double EM::likelihood_diff(long double previous, long double current){
	if (current < previous){
		throw std::runtime_error("likelihood went down. previous value: " + std::to_string(previous) ", current value: " + std::to_string(current));
	} else {
		return current - previous;
	}
}

std::tuple<T...> EM::start(long double stop){
	do{
		long double currentlike = q_function(theta);
		std::clog << "Theta: " << theta << "likelihood: " << currentlike << std::endl;
		long double difference = likelihood_diff(likelihood, currentlike);
		likelihood = currentlike;
		theta = m_function(theta);
	} while (difference < stop);
	return theta;
}

long double EM::get_likelihood(){
	return likelihood;
}

<|endoftext|>


<commit_before>#if !defined(_TSXX_SYSTEM_HPP_)
#define _TSXX_SYSTEM_HPP_

#include <map>

#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>

#include <tsxx/exceptions.hpp>

#define LOG(x) (std::clog << __FILE__ << ":" << __LINE__ << ": " << (x) << std::endl)
#define FIXME() LOG("FIXME")
#define TODO() LOG("TODO")
#define XXX() LOG("XXX")

namespace tsxx
{
namespace system
{

class
file_descriptor
: private boost::noncopyable
{
public:
	file_descriptor(int fd = -1);
	~file_descriptor();

	int get_value() const;
	void close();
	bool is_valid();

private:
	int fd;

};
typedef boost::shared_ptr<file_descriptor> file_descriptor_ptr;

class
memory_region
: private boost::noncopyable
{
public:
	memory_region(file_descriptor_ptr fd);
	~memory_region();

	bool map(std::size_t len, off_t offset);
	void unmap();

	void *get_pointer();

private:
	file_descriptor_ptr fd;
	void *pointer;
	std::size_t length;

};
typedef boost::shared_ptr<memory_region> memory_region_ptr;

// CopyableMemoryRegion
class
memory_region_window
{
public:
	memory_region_window(memory_region_ptr reg, off_t off);

	void *get_pointer();

private:
	memory_region_ptr region;
	off_t offset;

};

class
memory
: private boost::noncopyable // XXX check if this is really needed
{
public:
	memory();

	std::size_t get_region_size() const;

	bool is_opened();
	bool open();
	void try_close();

	memory_region_window get_region(off_t address);

private:
	file_descriptor_ptr fd;
	std::map<off_t, memory_region_ptr> memory_regions;
	std::size_t region_size;

};

// TODO Calibrate this function.
/**
 * @warning This function hasn't been calibrated yet.
 */
inline void
nssleep(unsigned int ns)
{
	volatile unsigned int loop = ns * 3;
	asm volatile (
		"1:\n"
		"subs %1, %1, #1;\n"
		"bne 1b;\n"
		: "=r" ((loop)) : "r" ((loop))
	);
}

}
}

#endif // !defined(_TSXX_SYSTEM_HPP_)
<commit_msg>Incremented delay in "nssleep".<commit_after>#if !defined(_TSXX_SYSTEM_HPP_)
#define _TSXX_SYSTEM_HPP_

#include <map>

#include <boost/shared_ptr.hpp>
#include <boost/noncopyable.hpp>

#include <tsxx/exceptions.hpp>

#define LOG(x) (std::clog << __FILE__ << ":" << __LINE__ << ": " << (x) << std::endl)
#define FIXME() LOG("FIXME")
#define TODO() LOG("TODO")
#define XXX() LOG("XXX")

namespace tsxx
{
namespace system
{

class
file_descriptor
: private boost::noncopyable
{
public:
	file_descriptor(int fd = -1);
	~file_descriptor();

	int get_value() const;
	void close();
	bool is_valid();

private:
	int fd;

};
typedef boost::shared_ptr<file_descriptor> file_descriptor_ptr;

class
memory_region
: private boost::noncopyable
{
public:
	memory_region(file_descriptor_ptr fd);
	~memory_region();

	bool map(std::size_t len, off_t offset);
	void unmap();

	void *get_pointer();

private:
	file_descriptor_ptr fd;
	void *pointer;
	std::size_t length;

};
typedef boost::shared_ptr<memory_region> memory_region_ptr;

class
memory_region_window
{
public:
	memory_region_window(memory_region_ptr reg, off_t off);

	void *get_pointer();

private:
	memory_region_ptr region;
	off_t offset;

};

class
memory
: private boost::noncopyable // XXX check if this is really needed
{
public:
	memory();

	std::size_t get_region_size() const;

	bool is_opened();
	bool open();
	void try_close();

	memory_region_window get_region(off_t address);

private:
	file_descriptor_ptr fd;
	std::map<off_t, memory_region_ptr> memory_regions;
	std::size_t region_size;

};

// TODO Calibrate this function.
/**
 * @warning This function hasn't been calibrated yet.
 */
inline void
nssleep(unsigned int ns)
{
	volatile unsigned int loop = ns * 5;
	asm volatile (
		"1:\n"
		"subs %1, %1, #1;\n"
		"bne 1b;\n"
		: "=r" ((loop)) : "r" ((loop))
	);
}

}
}

#endif // !defined(_TSXX_SYSTEM_HPP_)
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
/// \file  bitmap.cpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Bitmap index suitable for indexing up to 64 or 4096 values on a
/// 64bit platform with fast iteration between adjacent items.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2009-12-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2009 Serge Aleynikov <saleyn@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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/

#ifndef _UTXX_BITMAP_HPP_
#define _UTXX_BITMAP_HPP_

#include <boost/assert.hpp>
#include <utxx/meta.hpp>
#include <utxx/atomic.hpp>
#include <utxx/detail/bit_count.hpp>
#include <sstream>
#include <stdio.h>

namespace utxx {

template <int N, typename T = unsigned long>
class bitmap_low {
    T m_data;

    void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
    typedef T value_type;

    bitmap_low() : m_data(0) {
        BOOST_STATIC_ASSERT(1 <= N && N <= sizeof(long)*8);
    }

    static const unsigned int max  = N - 1;
    static const unsigned int cend = N;

    T               value()  const { return m_data; }
    unsigned int    end()    const { return cend; }
    bool            empty()  const { return m_data == 0; }
    void            clear()        { m_data = 0; }

    void set(unsigned int i)   { valid(i); m_data |= 1ul << i; }
    void clear(unsigned int i) { valid(i); m_data ^= m_data & (1ul << i); }
    bool is_set(unsigned int i) const { valid(i); return m_data & (1ul << i); }
    int  first() const { return m_data ? atomic::bit_scan_forward(m_data) : end(); }
    int  last()  const { return m_data ? atomic::bit_scan_reverse(m_data) : end(); }
    int  count() const { return bitcount(m_data); }

    bool operator[] (unsigned int i) const { return is_set(i); }
    void operator=  (const bitmap_low<N>& rhs) { m_data = rhs.value(); }

    /// @param <i> is the bit to search from in the forward direction.
    ///            Valid range [0 ... max-1].
    /// @return position of next enabled bit or <end()> if not found.
    int next(unsigned int i) const {
        T val = m_data >> ++i;
        return val && i <= max ? atomic::bit_scan_forward(val)+i : end();
    }

    /// @param <i> is the bit to search from in the reverse direction.
    ///            Valid range [1 ... max].
    /// @return position of previous enabled bit or <end()> if not found.
    int prev(unsigned int i) const {
        BOOST_ASSERT(i <= max);
        T val = m_data & ((1ul << i)-1);
        return val && i >= 0 ? atomic::bit_scan_reverse(val) : end();
    }

    std::ostream& print(std::ostream& out) const {
        std::stringstream s;
        for(int i=max+1; i > 0; --i) {
            if (i != max+1 && i%8 == 0) s << '-';
            s << (is_set(i-1) ? '1' : '0');
        }
        return out << s.str();
    }
};

template <int N, typename T = unsigned long>
class bitmap_high: protected bitmap_low<sizeof(long)*8, T> {
    typedef bitmap_low<sizeof(long)*8, T> base;
public:
    // the following static members are made public just for testing
    static const int s_lo_dim  = base::max + 1;
    static const int s_hi_sft  = log<s_lo_dim, 2>::value;
    static const int s_lo_mask = base::max;
    static const int s_hi_dim  = N / (sizeof(long)*8) +
                               ((N & (N - 1)) == 0 ? 0 : 1);
private:
    base m_data[s_hi_dim];

    void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
    bitmap_high() {
        BOOST_STATIC_ASSERT(sizeof(long)*8 < N && N <= sizeof(long)*sizeof(long)*64);
    }

    static const unsigned int   max = N - 1;
    unsigned int                end()   const { return max+1; }
    bool                        empty() const { return base::value() == 0; }

    void clear() {
        for (int i=0; i < s_hi_dim; ++i) m_data[i].clear();
        base::clear();
    }

    void set(unsigned int i) {
        valid(i);
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        m_data[hi].set(lo);
        base::set(m_data[hi].value() ? hi : 0);
    }

    void clear(unsigned int i) {
        valid(i);
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        m_data[hi].clear(lo);
        if (!m_data[hi].value())
            base::clear(hi);
    }

    bool operator[] (unsigned int i) const { return is_set(i); }
    void operator=  (const bitmap_high<N>& rhs) {
       for (int i=0; i < s_hi_dim; ++i) m_data[i] = rhs.value();
       this->base::operator= (rhs.base::value());
    }

    bool is_set(unsigned int i) const {
        valid(i);
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        return base::is_set(hi) && m_data[hi].is_set(lo);
    }
    int first()  const {
        int hi=base::first();
        return base::value() ? (hi<<s_hi_sft | m_data[hi].first()):end();
    }
    int last()   const {
        int hi=base::last();
        return base::value() ? (hi<<s_hi_sft | m_data[hi].last() ):end();
    }
    int count() const {
        int sum = 0;
        for (unsigned int i = base::first(); i != base::end(); i = base::next(i)) {
            sum += bitcount(m_data[i].value());
        }
        return sum;
    }
    int next(unsigned int i) const {
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        if (lo < base::max) {
            lo = m_data[hi].next(lo);
            if (lo != base::end()) return (hi << s_hi_sft | lo);
        }
        if (hi == base::max) return end();
        hi = base::next(hi);
        return hi == base::end() ? end() : (hi << s_hi_sft | m_data[hi].first());
    }
    int prev(unsigned int i) const {
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        if (lo > 0) {
            lo = m_data[hi].prev(lo);
            if (lo != base::end()) return (hi << s_hi_sft | lo);
        }
        if (hi == 0) return end();
        hi = base::prev(hi);
        return m_data[hi].value() ? (hi << s_hi_sft | m_data[hi].last()) : end();
    }

    std::ostream& print(std::ostream& out, const char* sep = "\n") const {
        std::stringstream s;
        for(int i=s_hi_dim-1; i >= 0; --i) {
            char buf[9];
            if (i != s_lo_dim-1 && (i+1)%8 != 0 && i != s_hi_dim-1) s << '-';
            if ((i+1)%8 == 0 || (s_hi_dim < 8 && i == (s_hi_dim-1))) {
                sprintf(buf, "%s%02d: ", sep, i+1);
                s << buf;
            }
            sprintf(buf, "%016lx", m_data[i].value());
            s << buf;
        }
        return out << s.str();
    }
};

typedef bitmap_low<16>    bitmap16;
typedef bitmap_low<32>    bitmap32;
typedef
    boost::mpl::if_c<sizeof(long)==8,
                     bitmap_low<48>,
                     bitmap_high<48> >::type bitmap48;
typedef
    boost::mpl::if_c<sizeof(long)==8,
                     bitmap_low<64>,
                     bitmap_high<64> >::type bitmap64;
typedef bitmap_high<128>  bitmap128;
typedef bitmap_high<256>  bitmap256;
typedef bitmap_high<512>  bitmap512;
typedef bitmap_high<1024> bitmap1024;
typedef bitmap_high<4096> bitmap4096;

} // namespace utxx

#endif // _HPCL_BITMAP_HPP_

<commit_msg>Add fill method<commit_after>//----------------------------------------------------------------------------
/// \file  bitmap.cpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief Bitmap index suitable for indexing up to 64 or 4096 values on a
/// 64bit platform with fast iteration between adjacent items.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com>
// Created: 2009-12-21
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (C) 2009 Serge Aleynikov <saleyn@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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/

#ifndef _UTXX_BITMAP_HPP_
#define _UTXX_BITMAP_HPP_

#include <boost/assert.hpp>
#include <utxx/meta.hpp>
#include <utxx/atomic.hpp>
#include <utxx/detail/bit_count.hpp>
#include <sstream>
#include <stdio.h>

namespace utxx {

template <int N, typename T = unsigned long>
class bitmap_low {
    T m_data;

    void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
    typedef T value_type;

    bitmap_low() : m_data(0) {
        BOOST_STATIC_ASSERT(1 <= N && N <= sizeof(long)*8);
    }

    static const unsigned int max  = N - 1;
    static const unsigned int cend = N;

    T               value()  const { return m_data; }
    unsigned int    end()    const { return cend; }
    bool            empty()  const { return m_data == 0; }
    void            clear()        { m_data = 0; }

    void fill()                    { m_data = uint64_t(-1); }
    void set(unsigned int i)       { valid(i); m_data |= 1ul << i; }
    void clear(unsigned int i)     { valid(i); m_data ^= m_data & (1ul << i); }
    bool is_set(unsigned int i) const { valid(i); return m_data & (1ul << i); }
    int  first() const { return m_data ? atomic::bit_scan_forward(m_data) : end(); }
    int  last()  const { return m_data ? atomic::bit_scan_reverse(m_data) : end(); }
    int  count() const { return bitcount(m_data); }

    bool operator[] (unsigned int i) const { return is_set(i); }
    void operator=  (const bitmap_low<N>& rhs) { m_data = rhs.value(); }

    /// @param <i> is the bit to search from in the forward direction.
    ///            Valid range [0 ... max-1].
    /// @return position of next enabled bit or <end()> if not found.
    int next(unsigned int i) const {
        T val = m_data >> ++i;
        return val && i <= max ? atomic::bit_scan_forward(val)+i : end();
    }

    /// @param <i> is the bit to search from in the reverse direction.
    ///            Valid range [1 ... max].
    /// @return position of previous enabled bit or <end()> if not found.
    int prev(unsigned int i) const {
        BOOST_ASSERT(i <= max);
        T val = m_data & ((1ul << i)-1);
        return val && i >= 0 ? atomic::bit_scan_reverse(val) : end();
    }

    std::ostream& print(std::ostream& out) const {
        std::stringstream s;
        for(int i=max+1; i > 0; --i) {
            if (i != max+1 && i%8 == 0) s << '-';
            s << (is_set(i-1) ? '1' : '0');
        }
        return out << s.str();
    }
};

template <int N, typename T = unsigned long>
class bitmap_high: protected bitmap_low<sizeof(long)*8, T> {
    typedef bitmap_low<sizeof(long)*8, T> base;
public:
    // the following static members are made public just for testing
    static const int s_lo_dim  = base::max + 1;
    static const int s_hi_sft  = log<s_lo_dim, 2>::value;
    static const int s_lo_mask = base::max;
    static const int s_hi_dim  = N / (sizeof(long)*8) +
                               ((N & (N - 1)) == 0 ? 0 : 1);
private:
    base m_data[s_hi_dim];

    void valid(unsigned int i) const { BOOST_ASSERT(i <= max); }
public:
    bitmap_high() {
        BOOST_STATIC_ASSERT(sizeof(long)*8 < N && N <= sizeof(long)*sizeof(long)*64);
    }

    static const unsigned int   max = N - 1;
    unsigned int                end()   const { return max+1; }
    bool                        empty() const { return base::value() == 0; }

    void fill() {
        for (int i=0; i < s_hi_dim; ++i) m_data[i].fill();
        base::fill();
    }

    void clear() {
        for (int i=0; i < s_hi_dim; ++i) m_data[i].clear();
        base::clear();
    }

    void set(unsigned int i) {
        valid(i);
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        m_data[hi].set(lo);
        base::set(m_data[hi].value() ? hi : 0);
    }

    void clear(unsigned int i) {
        valid(i);
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        m_data[hi].clear(lo);
        if (!m_data[hi].value())
            base::clear(hi);
    }

    bool operator[] (unsigned int i) const { return is_set(i); }
    void operator=  (const bitmap_high<N>& rhs) {
       for (int i=0; i < s_hi_dim; ++i) m_data[i] = rhs.value();
       this->base::operator= (rhs.base::value());
    }

    bool is_set(unsigned int i) const {
        valid(i);
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        return base::is_set(hi) && m_data[hi].is_set(lo);
    }
    int first()  const {
        int hi=base::first();
        return base::value() ? (hi<<s_hi_sft | m_data[hi].first()):end();
    }
    int last()   const {
        int hi=base::last();
        return base::value() ? (hi<<s_hi_sft | m_data[hi].last() ):end();
    }
    int count() const {
        int sum = 0;
        for (unsigned int i = base::first(); i != base::end(); i = base::next(i)) {
            sum += bitcount(m_data[i].value());
        }
        return sum;
    }
    int next(unsigned int i) const {
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        if (lo < base::max) {
            lo = m_data[hi].next(lo);
            if (lo != base::end()) return (hi << s_hi_sft | lo);
        }
        if (hi == base::max) return end();
        hi = base::next(hi);
        return hi == base::end() ? end() : (hi << s_hi_sft | m_data[hi].first());
    }
    int prev(unsigned int i) const {
        unsigned int hi = i>>s_hi_sft, lo = i&s_lo_mask;
        if (lo > 0) {
            lo = m_data[hi].prev(lo);
            if (lo != base::end()) return (hi << s_hi_sft | lo);
        }
        if (hi == 0) return end();
        hi = base::prev(hi);
        return m_data[hi].value() ? (hi << s_hi_sft | m_data[hi].last()) : end();
    }

    std::ostream& print(std::ostream& out, const char* sep = "\n") const {
        std::stringstream s;
        for(int i=s_hi_dim-1; i >= 0; --i) {
            char buf[9];
            if (i != s_lo_dim-1 && (i+1)%8 != 0 && i != s_hi_dim-1) s << '-';
            if ((i+1)%8 == 0 || (s_hi_dim < 8 && i == (s_hi_dim-1))) {
                sprintf(buf, "%s%02d: ", sep, i+1);
                s << buf;
            }
            sprintf(buf, "%016lx", m_data[i].value());
            s << buf;
        }
        return out << s.str();
    }
};

typedef bitmap_low<16>    bitmap16;
typedef bitmap_low<32>    bitmap32;
typedef
    boost::mpl::if_c<sizeof(long)==8,
                     bitmap_low<48>,
                     bitmap_high<48> >::type bitmap48;
typedef
    boost::mpl::if_c<sizeof(long)==8,
                     bitmap_low<64>,
                     bitmap_high<64> >::type bitmap64;
typedef bitmap_high<128>  bitmap128;
typedef bitmap_high<256>  bitmap256;
typedef bitmap_high<512>  bitmap512;
typedef bitmap_high<1024> bitmap1024;
typedef bitmap_high<4096> bitmap4096;

} // namespace utxx

#endif // _HPCL_BITMAP_HPP_

<|endoftext|>


<commit_before>#include "module_pressuresensor.h"
#include "pressure_form.h"
#include <Module_UID/module_uid.h>

#define REGISTER_CALIB 00 // 8 bytes
#define REGISTER_PRESSURE_RAW 8
#define REGISTER_TEMP_RAW 10
#define REGISTER_PRESSURE 12
#define REGISTER_TEMP 14
#define REGISTER_STATUS 17
#define REGISTER_COUNTER 20

// indicates problem between i2c-spi bridge and pressure sensor
#define STATUS_MAGIC_VALUE 0x55
#define CALIB_MAGIC_VALUE 224

// pressure range. everything outside this range will be regarded as
// a meassurement error
#define PRESSURE_MIN 900
#define PRESSURE_MAX 3000

Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid)
    : RobotModule(id)
{
    this->uid=uid;

    setDefaultValue("i2cAddress", 0x50);
    setDefaultValue("frequency", 1);

    connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData()));

    reset();
}

Module_PressureSensor::~Module_PressureSensor()
{
}

void Module_PressureSensor::terminate()
{
    RobotModule::terminate();
    timer.stop();
}

void Module_PressureSensor::reset()
{
    RobotModule::reset();

    int freq = 1000/getSettings().value("frequency").toInt();
    if (freq>0)
        timer.start(freq);
    else
        timer.stop();

    if (!getSettings().value("enabled").toBool())
        return;

    readCalibWords();

}

void Module_PressureSensor::refreshData()
{
    if (!getSettings().value("enabled").toBool())
        return;

    readPressure();
    readTemperature();
    readCounter();
    readRawRegisters();
    calc();

    if (getHealthStatus().isHealthOk()) {
        emit dataChanged(this);
        emit newDepthData(getDepth());
    }
}

void Module_PressureSensor::calc()
{
    short D1 = data["pressureRaw"].toInt();
    short D2 = data["tempRaw"].toInt();
    short C1 = data["C1"].toInt();
    short C2 = data["C2"].toInt();
    short C3 = data["C3"].toInt();
    short C4 = data["C4"].toInt();
    short C5 = data["C5"].toInt();
    short C6 = data["C6"].toInt();

    int UT1, dT, OFF, SENS, P;
    short int dT2;

    // Calculate calibration temperature
    UT1 = 8*C5+10000;

    // Calculate actual temperature
    dT = D2 - UT1;

    // Second-order temperature compensation
    if (dT < 0)
            dT2 = dT - (dT/128*dT/128)/2;
    else
            dT2 = dT - (dT/128*dT/128)/8;
    data["tempSW"] = 200+dT2*(C6+100)/2048;

    // Calculate temperature compensated pressure
    OFF = C2+((C4-250)*dT)/4096+10000;

    SENS = C1/2 + ((C3+200)*dT)/8192 + 3000;

    // Temperature compensated pressure in mbar
    P = (SENS*(D1-OFF))/4096+1000;

    data["pressureSW"] = P;
}

void Module_PressureSensor::readPressure()
{
    unsigned char readBuffer[2];

    if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    // this is the pressure in mBar
    uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["pressure"] =  pressure;

    // 100 mBar == ca. 1m wassersäule - druck an der luft
    data["depth"] =  ((float)pressure-getSettings().value("airPressure").toFloat())/100;

    if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) {
        setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense.");
    }

}

void Module_PressureSensor::readCounter()
{
    unsigned char readBuffer[1];

    if (!readRegister(REGISTER_COUNTER, 1, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    data["counter"] =  readBuffer[0];
}

void Module_PressureSensor::readCalibWords()
{
    unsigned char readBuffer[8];
    if (!readRegister(0, 8, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    uint16_t pressure_CalibrationWords[4];
    for(int i=0;i<4;i++) {

        // this is the temperature in 10/degree celsius
        uint16_t c = (int)readBuffer[i] << 8 | (int)readBuffer[i+1];

        data["calib"+i] = c;
        pressure_CalibrationWords[i]=c;
    }

    data["C1"] = ((pressure_CalibrationWords[0] & 0xFFF8) >> 3);
    data["C2"] = ((pressure_CalibrationWords[0] & 0x0007) << 10) + ((pressure_CalibrationWords[1] & 0xFFC0) >> 6);
    data["C3"] = ((pressure_CalibrationWords[2] & 0xFFC0) >> 6);
    data["C4"] = ((pressure_CalibrationWords[3] & 0xFF80) >> 7);
    data["C5"] = ((pressure_CalibrationWords[1] & 0x003F) << 6) + ((pressure_CalibrationWords[2] & 0x003F));
    data["C6"] = (pressure_CalibrationWords[3] & 0x007F);

}

void Module_PressureSensor::readRawRegisters()
{

    unsigned char readBuffer[2];
    if (!readRegister(REGISTER_TEMP_RAW, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["tempRaw"] = temp;

    if (!readRegister(REGISTER_PRESSURE_RAW, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["pressureRaw"] = pressure;
}

void Module_PressureSensor::readTemperature()
{

    unsigned char readBuffer[2];
    if (!readRegister(REGISTER_TEMP, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    // this is the temperature in 10/degree celsius
    uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["temperature"] = ((float)temp)/10;
}

float Module_PressureSensor::getDepth()
{
    float p = data["pressure"].toFloat();
    if (p > 900 && p <= 2000) {
        return data["depth"].toFloat();
    } else {
        setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense.");
        return 0;
    }

}

float Module_PressureSensor::getTemperature()
{
    return data["temperature"].toFloat();
}

QList<RobotModule*> Module_PressureSensor::getDependencies()
{
    QList<RobotModule*> ret;
    ret.append(uid);
    return ret;
}

QWidget* Module_PressureSensor::createView(QWidget* parent)
{
    return new Pressure_Form(this, parent);
}

void Module_PressureSensor::doHealthCheck()
{
    if (!getSettings().value("enabled").toBool())
        return;

    unsigned char readBuffer[1];

    if (!readRegister(REGISTER_STATUS, 1, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }
    if (readBuffer[0] != STATUS_MAGIC_VALUE) {
        setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0]));
        return;
    }

    setHealthToOk();
}

bool Module_PressureSensor::readRegister2(unsigned char reg, int size, unsigned char *ret_buf)
{
    unsigned char address = getSettings().value("i2cAddress").toInt();

    if (!uid->I2C_Write(address, &reg, 1)) {
        setHealthToSick("UID reported error.");
        return false;
    }
    if (!uid->I2C_Read(address, size, ret_buf)) {
        setHealthToSick("UID reported error.");
        return false;
    }
    return true;
}

bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf)
{
    unsigned char address = getSettings().value("i2cAddress").toInt();

    if (!uid->I2C_ReadRegisters(address, reg, size, ret_buf)) {
        setHealthToSick("UID reported error.");
        return false;
    }
    return true;
}
<commit_msg>- read out new calib words at each reset on the pressure controller - ui fix<commit_after>#include "module_pressuresensor.h"
#include "pressure_form.h"
#include <Module_UID/module_uid.h>

#define REGISTER_CALIB 00 // 8 bytes
#define REGISTER_PRESSURE_RAW 8
#define REGISTER_TEMP_RAW 10
#define REGISTER_PRESSURE 12
#define REGISTER_TEMP 14
#define REGISTER_STATUS 17
#define REGISTER_COUNTER 20

// indicates problem between i2c-spi bridge and pressure sensor
#define STATUS_MAGIC_VALUE 0x55
#define CALIB_MAGIC_VALUE 224

// pressure range. everything outside this range will be regarded as
// a meassurement error
#define PRESSURE_MIN 900
#define PRESSURE_MAX 3000

Module_PressureSensor::Module_PressureSensor(QString id, Module_UID *uid)
    : RobotModule(id)
{
    this->uid=uid;

    setDefaultValue("i2cAddress", 0x50);
    setDefaultValue("frequency", 1);

    connect(&timer,SIGNAL(timeout()), this, SLOT(refreshData()));

    reset();
}

Module_PressureSensor::~Module_PressureSensor()
{
}

void Module_PressureSensor::terminate()
{
    RobotModule::terminate();
    timer.stop();
}

void Module_PressureSensor::reset()
{
    RobotModule::reset();

    int freq = 1000/getSettings().value("frequency").toInt();
    if (freq>0)
        timer.start(freq);
    else
        timer.stop();

    if (!getSettings().value("enabled").toBool())
        return;

    readCalibWords();

}

void Module_PressureSensor::refreshData()
{
    if (!getSettings().value("enabled").toBool())
        return;

    readPressure();
    readTemperature();
    readCounter();
    readRawRegisters();
    calc();

    if (getHealthStatus().isHealthOk()) {
        emit dataChanged(this);
        emit newDepthData(getDepth());
    }
}

void Module_PressureSensor::calc()
{
    short D1 = data["pressureRaw"].toInt();
    short D2 = data["tempRaw"].toInt();
    short C1 = data["C1"].toInt();
    short C2 = data["C2"].toInt();
    short C3 = data["C3"].toInt();
    short C4 = data["C4"].toInt();
    short C5 = data["C5"].toInt();
    short C6 = data["C6"].toInt();

    int UT1, dT, OFF, SENS, P;
    short int dT2;

    // Calculate calibration temperature
    UT1 = 8*C5+10000;

    // Calculate actual temperature
    dT = D2 - UT1;

    // Second-order temperature compensation
    if (dT < 0)
            dT2 = dT - (dT/128*dT/128)/2;
    else
            dT2 = dT - (dT/128*dT/128)/8;
    data["tempSW"] = 200+dT2*(C6+100)/2048;

    // Calculate temperature compensated pressure
    OFF = C2+((C4-250)*dT)/4096+10000;

    SENS = C1/2 + ((C3+200)*dT)/8192 + 3000;

    // Temperature compensated pressure in mbar
    P = (SENS*(D1-OFF))/4096+1000;

    data["pressureSW"] = P;
}

void Module_PressureSensor::readPressure()
{
    unsigned char readBuffer[2];

    if (!readRegister(REGISTER_PRESSURE, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    // this is the pressure in mBar
    uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["pressure"] =  pressure;

    // 100 mBar == ca. 1m wassersäule - druck an der luft
    data["depth"] =  ((float)pressure-getSettings().value("airPressure").toFloat())/100;

    if (pressure < PRESSURE_MIN || pressure > PRESSURE_MAX) {
        setHealthToSick("Pressure of "+QString::number(pressure) + " doesn't make sense.");
    }

}

void Module_PressureSensor::readCounter()
{
    unsigned char readBuffer[1];

    if (!readRegister(REGISTER_COUNTER, 1, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    data["counter"] =  readBuffer[0];
}

void Module_PressureSensor::readCalibWords()
{
    unsigned char address = getSettings().value("i2cAddress").toInt();
    unsigned char cmd[] = { 0x12 };
    if (!uid->I2C_Write(address, cmd, 1)) {
        setHealthToSick("could not reread calib  words.");
        sleep(100);
        return;
    }
    sleep(100);

    unsigned char readBuffer[8];
    if (!readRegister(0, 8, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    uint16_t pressure_CalibrationWords[4];
    for(int i=0;i<4;i++) {

        // this is the temperature in 10/degree celsius
        uint16_t c = (int)readBuffer[2*i] << 8 | (int)readBuffer[2*i+1];

        data["calib "+QString::number(i)] = "0x"+QString::number(c,16);
        pressure_CalibrationWords[i]=c;
    }

    data["C1"] = ((pressure_CalibrationWords[0] & 0xFFF8) >> 3);
    data["C2"] = ((pressure_CalibrationWords[0] & 0x0007) << 10) + ((pressure_CalibrationWords[1] & 0xFFC0) >> 6);
    data["C3"] = ((pressure_CalibrationWords[2] & 0xFFC0) >> 6);
    data["C4"] = ((pressure_CalibrationWords[3] & 0xFF80) >> 7);
    data["C5"] = ((pressure_CalibrationWords[1] & 0x003F) << 6) + ((pressure_CalibrationWords[2] & 0x003F));
    data["C6"] = (pressure_CalibrationWords[3] & 0x007F);

}

void Module_PressureSensor::readRawRegisters()
{

    unsigned char readBuffer[2];
    if (!readRegister(REGISTER_TEMP_RAW, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["tempRaw"] = temp;

    if (!readRegister(REGISTER_PRESSURE_RAW, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    uint16_t pressure = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["pressureRaw"] = pressure;
}

void Module_PressureSensor::readTemperature()
{

    unsigned char readBuffer[2];
    if (!readRegister(REGISTER_TEMP, 2, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }

    // this is the temperature in 10/degree celsius
    uint16_t temp = (int)readBuffer[0] << 8 | (int)readBuffer[1];

    data["temperature"] = ((float)temp)/10;
}

float Module_PressureSensor::getDepth()
{
    float p = data["pressure"].toFloat();
    if (p > 900 && p <= 2000) {
        return data["depth"].toFloat();
    } else {
        setHealthToSick("Pressure of "+QString::number(p) + " doesn't make sense.");
        return 0;
    }

}

float Module_PressureSensor::getTemperature()
{
    return data["temperature"].toFloat();
}

QList<RobotModule*> Module_PressureSensor::getDependencies()
{
    QList<RobotModule*> ret;
    ret.append(uid);
    return ret;
}

QWidget* Module_PressureSensor::createView(QWidget* parent)
{
    return new Pressure_Form(this, parent);
}

void Module_PressureSensor::doHealthCheck()
{
    if (!getSettings().value("enabled").toBool())
        return;

    unsigned char readBuffer[1];

    if (!readRegister(REGISTER_STATUS, 1, readBuffer)) {
        setHealthToSick("UID reported error.");
        return;
    }
    if (readBuffer[0] != STATUS_MAGIC_VALUE) {
        setHealthToSick("Status register doesn't match magic value: is="+QString::number(readBuffer[0]));
        return;
    }

    setHealthToOk();
}

bool Module_PressureSensor::readRegister2(unsigned char reg, int size, unsigned char *ret_buf)
{
    unsigned char address = getSettings().value("i2cAddress").toInt();

    if (!uid->I2C_Write(address, &reg, 1)) {
        setHealthToSick("UID reported error.");
        return false;
    }
    if (!uid->I2C_Read(address, size, ret_buf)) {
        setHealthToSick("UID reported error.");
        return false;
    }
    return true;
}

bool Module_PressureSensor::readRegister(unsigned char reg, int size, unsigned char *ret_buf)
{
    unsigned char address = getSettings().value("i2cAddress").toInt();

    if (!uid->I2C_ReadRegisters(address, reg, size, ret_buf)) {
        setHealthToSick("UID reported error.");
        return false;
    }
    return true;
}
<|endoftext|>


<commit_before>#include "itkBSplineControlPointImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkN3MRIBiasFieldCorrectionImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkShrinkImageFilter.h"

template <unsigned int ImageDimension>
int N3BiasFieldCorrection( int argc, char *argv[] )
{
  typedef float RealType;

  typedef itk::Image<RealType, ImageDimension> ImageType;
  typedef itk::Image<unsigned char, ImageDimension> MaskImageType;

  typedef itk::ImageFileReader<ImageType> ReaderType;
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[2] );
  reader->Update();

  typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkerType;
  typename ShrinkerType::Pointer shrinker = ShrinkerType::New();
  shrinker->SetInput( reader->GetOutput() );
  shrinker->SetShrinkFactors( 1 );

  typename MaskImageType::Pointer maskImage = NULL;

  if( argc > 5 )
    {
    typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
    typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
    maskreader->SetFileName( argv[5] );

    try
      {
      maskreader->Update();
      maskImage = maskreader->GetOutput();
      }
    catch(...)
      {
      std::cout << "Mask file not read.  Generating mask file using otsu"
        << " thresholding." << std::endl;
      }
    }
  if( !maskImage )
    {
    typedef itk::OtsuThresholdImageFilter<ImageType, MaskImageType>
      ThresholderType;
    typename ThresholderType::Pointer otsu = ThresholderType::New();
    otsu->SetInput( reader->GetOutput() );
    otsu->SetNumberOfHistogramBins( 200 );
    otsu->SetInsideValue( 0 );
    otsu->SetOutsideValue( 1 );
    otsu->Update();

    maskImage = otsu->GetOutput();
    }
  typedef itk::ShrinkImageFilter<MaskImageType, MaskImageType> MaskShrinkerType;
  typename MaskShrinkerType::Pointer maskshrinker = MaskShrinkerType::New();
  maskshrinker->SetInput( maskImage );
  maskshrinker->SetShrinkFactors( 1 );

  if( argc > 4 )
    {
    shrinker->SetShrinkFactors( atoi( argv[4] ) );
    maskshrinker->SetShrinkFactors( atoi( argv[4] ) );
    }
  shrinker->Update();
  maskshrinker->Update();

  typedef itk::N3MRIBiasFieldCorrectionImageFilter<ImageType, MaskImageType,
    ImageType> CorrecterType;
  typename CorrecterType::Pointer correcter = CorrecterType::New();
  correcter->SetInput( shrinker->GetOutput() );
  correcter->SetMaskImage( maskshrinker->GetOutput() );

  if( argc > 6 )
    {
    correcter->SetMaximumNumberOfIterations( atoi( argv[6] ) );
    }
  if( argc > 7 )
    {
    correcter->SetNumberOfFittingLevels( atoi( argv[7] ) );
    }

  try
    {
    correcter->Update();
    }
  catch(...)
    {
    std::cerr << "Exception caught." << std::endl;
    return EXIT_FAILURE;
    }

//  correcter->Print( std::cout, 3 );

  /**
   * Reconstruct the bias field at full image resolution.  Divide
   * the original input image by the bias field to get the final
   * corrected image.
   */
  typedef itk::BSplineControlPointImageFilter<typename
    CorrecterType::BiasFieldControlPointLatticeType, typename
    CorrecterType::ScalarImageType> BSplinerType;
  typename BSplinerType::Pointer bspliner = BSplinerType::New();
  bspliner->SetInput( correcter->GetBiasFieldControlPointLattice() );
  bspliner->SetSplineOrder( correcter->GetSplineOrder() );
  bspliner->SetSize(
    reader->GetOutput()->GetLargestPossibleRegion().GetSize() );
  bspliner->SetOrigin( reader->GetOutput()->GetOrigin() );
  bspliner->SetDirection( reader->GetOutput()->GetDirection() );
  bspliner->SetSpacing( reader->GetOutput()->GetSpacing() );
  bspliner->Update();

  typename ImageType::Pointer logField = ImageType::New();
  logField->SetOrigin( bspliner->GetOutput()->GetOrigin() );
  logField->SetSpacing( bspliner->GetOutput()->GetSpacing() );
  logField->SetRegions(
    bspliner->GetOutput()->GetLargestPossibleRegion().GetSize() );
  logField->SetDirection( bspliner->GetOutput()->GetDirection() );
  logField->Allocate();

  itk::ImageRegionIterator<typename CorrecterType::ScalarImageType> ItB(
    bspliner->GetOutput(),
    bspliner->GetOutput()->GetLargestPossibleRegion() );
  itk::ImageRegionIterator<ImageType> ItF( logField,
    logField->GetLargestPossibleRegion() );
  for( ItB.GoToBegin(), ItF.GoToBegin(); !ItB.IsAtEnd(); ++ItB, ++ItF )
    {
    ItF.Set( ItB.Get()[0] );
    }

  typedef itk::ExpImageFilter<ImageType, ImageType> ExpFilterType;
  typename ExpFilterType::Pointer expFilter = ExpFilterType::New();
  expFilter->SetInput( logField );
  expFilter->Update();

  typedef itk::DivideImageFilter<ImageType, ImageType, ImageType> DividerType;
  typename DividerType::Pointer divider = DividerType::New();
  divider->SetInput1( reader->GetOutput() );
  divider->SetInput2( expFilter->GetOutput() );
  divider->Update();

  typedef itk::ImageFileWriter<ImageType> WriterType;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[3] );
  writer->SetInput( divider->GetOutput() );
  writer->Update();

  if( argc > 8 )
    {
    typedef itk::ImageFileWriter<ImageType> WriterType;
    typename WriterType::Pointer writer = WriterType::New();
    writer->SetFileName( argv[8] );
    writer->SetInput( expFilter->GetOutput() );
    writer->Update();
    }

  return EXIT_SUCCESS;
}

int main( int argc, char *argv[] )
{
  if ( argc < 4 )
    {
    std::cerr << "Usage: " << argv[0] << " imageDimension inputImage "
     << "outputImage [shrinkFactor] [maskImage] [numberOfIterations] "
     << "[numberOfFittingLevels] [outputBiasField] " << std::endl;
    exit( EXIT_FAILURE );
    }

  switch( atoi( argv[1] ) )
   {
   case 2:
     N3BiasFieldCorrection<2>( argc, argv );
     break;
   case 3:
     N3BiasFieldCorrection<3>( argc, argv );
     break;
   default:
      std::cerr << "Unsupported dimension" << std::endl;
      exit( EXIT_FAILURE );
   }
}

<commit_msg>STYLE:  Changed N3 portion to accommodate recent (small) change to itkN3BiasFieldCorrectionImageFilter<commit_after>#include "itkBSplineControlPointImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkN3MRIBiasFieldCorrectionImageFilter.h"
#include "itkOtsuThresholdImageFilter.h"
#include "itkShrinkImageFilter.h"

template <unsigned int ImageDimension>
int N3BiasFieldCorrection( int argc, char *argv[] )
{
  typedef float RealType;

  typedef itk::Image<RealType, ImageDimension> ImageType;
  typedef itk::Image<unsigned char, ImageDimension> MaskImageType;

  typedef itk::ImageFileReader<ImageType> ReaderType;
  typename ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( argv[2] );
  reader->Update();

  typedef itk::ShrinkImageFilter<ImageType, ImageType> ShrinkerType;
  typename ShrinkerType::Pointer shrinker = ShrinkerType::New();
  shrinker->SetInput( reader->GetOutput() );
  shrinker->SetShrinkFactors( 1 );

  typename MaskImageType::Pointer maskImage = NULL;

  if( argc > 5 )
    {
    typedef itk::ImageFileReader<MaskImageType> MaskReaderType;
    typename MaskReaderType::Pointer maskreader = MaskReaderType::New();
    maskreader->SetFileName( argv[5] );

    try
      {
      maskreader->Update();
      maskImage = maskreader->GetOutput();
      }
    catch(...)
      {
      std::cout << "Mask file not read.  Generating mask file using otsu"
        << " thresholding." << std::endl;
      }
    }
  if( !maskImage )
    {
    typedef itk::OtsuThresholdImageFilter<ImageType, MaskImageType>
      ThresholderType;
    typename ThresholderType::Pointer otsu = ThresholderType::New();
    otsu->SetInput( reader->GetOutput() );
    otsu->SetNumberOfHistogramBins( 200 );
    otsu->SetInsideValue( 0 );
    otsu->SetOutsideValue( 1 );
    otsu->Update();

    maskImage = otsu->GetOutput();
    }
  typedef itk::ShrinkImageFilter<MaskImageType, MaskImageType> MaskShrinkerType;
  typename MaskShrinkerType::Pointer maskshrinker = MaskShrinkerType::New();
  maskshrinker->SetInput( maskImage );
  maskshrinker->SetShrinkFactors( 1 );

  if( argc > 4 )
    {
    shrinker->SetShrinkFactors( atoi( argv[4] ) );
    maskshrinker->SetShrinkFactors( atoi( argv[4] ) );
    }
  shrinker->Update();
  maskshrinker->Update();

  typedef itk::N3MRIBiasFieldCorrectionImageFilter<ImageType, MaskImageType,
    ImageType> CorrecterType;
  typename CorrecterType::Pointer correcter = CorrecterType::New();
  correcter->SetInput( shrinker->GetOutput() );
  correcter->SetMaskImage( maskshrinker->GetOutput() );

  if( argc > 6 )
    {
    correcter->SetMaximumNumberOfIterations( atoi( argv[6] ) );
    }
  if( argc > 7 )
    {
    correcter->SetNumberOfFittingLevels( atoi( argv[7] ) );
    }

  try
    {
    correcter->Update();
    }
  catch(...)
    {
    std::cerr << "Exception caught." << std::endl;
    return EXIT_FAILURE;
    }

//  correcter->Print( std::cout, 3 );

  /**
   * Reconstruct the bias field at full image resolution.  Divide
   * the original input image by the bias field to get the final
   * corrected image.
   */
  typedef itk::BSplineControlPointImageFilter<typename
    CorrecterType::BiasFieldControlPointLatticeType, typename
    CorrecterType::ScalarImageType> BSplinerType;
  typename BSplinerType::Pointer bspliner = BSplinerType::New();
  bspliner->SetInput( correcter->GetLogBiasFieldControlPointLattice() );
  bspliner->SetSplineOrder( correcter->GetSplineOrder() );
  bspliner->SetSize(
    reader->GetOutput()->GetLargestPossibleRegion().GetSize() );
  bspliner->SetOrigin( reader->GetOutput()->GetOrigin() );
  bspliner->SetDirection( reader->GetOutput()->GetDirection() );
  bspliner->SetSpacing( reader->GetOutput()->GetSpacing() );
  bspliner->Update();

  typename ImageType::Pointer logField = ImageType::New();
  logField->SetOrigin( bspliner->GetOutput()->GetOrigin() );
  logField->SetSpacing( bspliner->GetOutput()->GetSpacing() );
  logField->SetRegions(
    bspliner->GetOutput()->GetLargestPossibleRegion().GetSize() );
  logField->SetDirection( bspliner->GetOutput()->GetDirection() );
  logField->Allocate();

  itk::ImageRegionIterator<typename CorrecterType::ScalarImageType> ItB(
    bspliner->GetOutput(),
    bspliner->GetOutput()->GetLargestPossibleRegion() );
  itk::ImageRegionIterator<ImageType> ItF( logField,
    logField->GetLargestPossibleRegion() );
  for( ItB.GoToBegin(), ItF.GoToBegin(); !ItB.IsAtEnd(); ++ItB, ++ItF )
    {
    ItF.Set( ItB.Get()[0] );
    }

  typedef itk::ExpImageFilter<ImageType, ImageType> ExpFilterType;
  typename ExpFilterType::Pointer expFilter = ExpFilterType::New();
  expFilter->SetInput( logField );
  expFilter->Update();

  typedef itk::DivideImageFilter<ImageType, ImageType, ImageType> DividerType;
  typename DividerType::Pointer divider = DividerType::New();
  divider->SetInput1( reader->GetOutput() );
  divider->SetInput2( expFilter->GetOutput() );
  divider->Update();

  typedef itk::ImageFileWriter<ImageType> WriterType;
  typename WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[3] );
  writer->SetInput( divider->GetOutput() );
  writer->Update();

  if( argc > 8 )
    {
    typedef itk::ImageFileWriter<ImageType> WriterType;
    typename WriterType::Pointer writer = WriterType::New();
    writer->SetFileName( argv[8] );
    writer->SetInput( expFilter->GetOutput() );
    writer->Update();
    }

  return EXIT_SUCCESS;
}

int main( int argc, char *argv[] )
{
  if ( argc < 4 )
    {
    std::cerr << "Usage: " << argv[0] << " imageDimension inputImage "
     << "outputImage [shrinkFactor] [maskImage] [numberOfIterations] "
     << "[numberOfFittingLevels] [outputBiasField] " << std::endl;
    exit( EXIT_FAILURE );
    }

  switch( atoi( argv[1] ) )
   {
   case 2:
     N3BiasFieldCorrection<2>( argc, argv );
     break;
   case 3:
     N3BiasFieldCorrection<3>( argc, argv );
     break;
   default:
      std::cerr << "Unsupported dimension" << std::endl;
      exit( EXIT_FAILURE );
   }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QApplication>
#include <QDBusConnection>
#include <QDBusError>
#include <QDBusInterface>
#include <QDeclarativeEngine>
#include <QDeclarativeView>
#include <QGraphicsItem>
#include <QDeclarativeContext>
#include <QDeclarativeNetworkAccessManagerFactory>
#include <QDesktopWidget>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QGLFormat>
#include <QLibraryInfo>
#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QNetworkProxy>
#include <QResizeEvent>
#include <QSettings>
#include <QTimer>
#include <QTextStream>
#include <QTranslator>
#include <QVariant>
#include <QX11Info>
#include <MGConfItem>
#include <QInputContext>

#include "launcherwindow.h"
#include "launcheratoms.h"
#include "launcherapp.h"

#include "meegoqmllauncher.h"

#include <QX11Info>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <unistd.h>

class NetworkAccessManagerFactory : public QDeclarativeNetworkAccessManagerFactory
{
public:
    virtual QNetworkAccessManager *create(QObject *parent);
};

QNetworkAccessManager *NetworkAccessManagerFactory::create(QObject *parent)
{
    QUrl httpProxy(getenv("http_proxy"));
    QNetworkAccessManager *nam = new QNetworkAccessManager(parent);
    if (!httpProxy.isEmpty())
    {
        QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy,
                            httpProxy.host(),
                            httpProxy.port());
        nam->setProxy(proxy);
    }

    QNetworkDiskCache *cache = new QNetworkDiskCache();
    cache->setCacheDirectory(QDir::homePath() + "/.cache/" + qApp->applicationName());
    nam->setCache(cache);

    return nam;
}

LauncherWindow::LauncherWindow(bool fullscreen, int width, int height, bool opengl, bool doSetSource, QWidget *parent) :
    QDeclarativeView(parent),
    m_inhibitScreenSaver(false),
    m_useOpenGl(opengl),
    m_usingGl(false)
{
    LauncherApp *app = static_cast<LauncherApp *>(qApp);

    setAttribute(Qt::WA_OpaquePaintEvent);
    setAttribute(Qt::WA_NoSystemBackground);

    engine()->setNetworkAccessManagerFactory(new NetworkAccessManagerFactory);
    connect(engine(), SIGNAL(quit()), qApp, SLOT(closeAllWindows()));

    connect((const QObject*)qApp->inputContext(), SIGNAL(inputMethodAreaChanged(QRect)),
            this, SLOT(handleInputMethodAreaChanged(QRect)));
    connect(qApp, SIGNAL(dismissKeyboard()), this, SLOT(dismissKeyboard()));

    QDeclarativeContext *context = rootContext();

    context->setContextProperty("qApp", qApp);
    context->setContextProperty("mainWindow", this);
    context->setContextProperty("theme_name", MGConfItem("/meego/ux/theme").value().toString());
    foreach (QString key, app->themeConfig->allKeys())
    {
        if (key.contains("Size") || key.contains("Padding") ||
            key.contains("Width") ||key.contains("Height") ||
            key.contains("Margin") || key.contains("Thickness"))
        {
            context->setContextProperty("theme_" + key, app->themeConfig->value(key).toInt());
        }
        else if (key.contains("Opacity"))
        {
            context->setContextProperty("theme_" + key, app->themeConfig->value(key).toDouble());
        }
        else
        {
            context->setContextProperty("theme_" + key, app->themeConfig->value(key));
        }
    }

    loadCommonTranslators();
    connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadCommonTranslators()));

    // Qt will search each translator for a string translation, starting with
    // the last translator installed working back to the first translator.
    // The first translation found wins.
    app->installTranslator(&qtTranslator);     // General Qt translations
    app->installTranslator(&commonTranslator); // Common Components translations
    app->installTranslator(&mediaTranslator);  // Common Media translations

    if (app->applicationName() != MeeGoQMLLauncher::preinitialisedAppName)
    {
        init(fullscreen, width, height, opengl, doSetSource);
    }
}

LauncherWindow::~LauncherWindow()
{
}

void LauncherWindow::init(bool fullscreen, int width, int height,
                          bool opengl, bool doSetSource)
{
    m_useOpenGl = opengl;

    LauncherApp *app = static_cast<LauncherApp *>(qApp);

    setWindowTitle(app->applicationName());
    setWindowIconText(app->applicationName());

    int screenWidth;
    int screenHeight;
    if (fullscreen)
    {
        screenWidth = qApp->desktop()->rect().width();
        screenHeight = qApp->desktop()->rect().height();
        setWindowFlags(Qt::FramelessWindowHint);
    }
    else
    {
        screenWidth = width;
        screenHeight = height;
    }

    QDeclarativeContext *context = rootContext();
    context->setContextProperty("screenWidth", screenWidth);
    context->setContextProperty("screenHeight", screenHeight);

    if (doSetSource) {
        sharePath = QString("/usr/share/") + app->applicationName() + "/";
        if (!QFile::exists(sharePath + "main.qml"))
        {
            qFatal("%s does not exist!", sharePath.toUtf8().data());
        }
    }

    loadAppTranslators();
    connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadAppTranslators()));
    app->installTranslator(&appTranslator);    // App specific translations

    // Switch to GL rendering if it's available
    switchToGLRendering();

    if (doSetSource)
    {
        setSource(QUrl(sharePath + "main.qml"));
    }

    setGeometry(QRect(0, 0, screenWidth, screenHeight));

    connect(app, SIGNAL(foregroundWindowChanged()), this, SLOT(updateOrientationSensorOn()));
}

void LauncherWindow::keyPressEvent ( QKeyEvent * event )
{
    if ((event->modifiers() & Qt::ControlModifier) && event->key() == Qt::Key_R)
    {
        QGraphicsObject* window = rootObject();
        if (window)
        {
            QVariant orientation = window->property("orientation");
            if(orientation.isValid())
            {
                int orient = orientation.toInt();
                orient = ((orient + 1) % 4);
                orientation.setValue(orient);
                window->setProperty("orientation", orientation);
                return;
            }
        }
    }

    QDeclarativeView::keyPressEvent(event);
}

void LauncherWindow::loadCommonTranslators()
{
    qtTranslator.load("qt_" + QLocale::system().name() + ".qm",
                      QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    commonTranslator.load("meegolabs-ux-components_" + QLocale::system().name() + ".qm",
                          QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    mediaTranslator.load("meego-ux-media-qml_" + QLocale::system().name() + ".qm",
                         QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}

void LauncherWindow::loadAppTranslators()
{
    LauncherApp *app = static_cast<LauncherApp *>(qApp);

    appTranslator.load(app->applicationName() + "_" + QLocale::system().name() + ".qm",
                       QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}

void LauncherWindow::triggerSystemUIMenu()
{
    QDBusInterface iface("com.nokia.systemui","/statusindicatormenu","com.meego.core.MStatusIndicatorMenu");
    if(iface.isValid()) iface.call("open");
}

void LauncherWindow::goHome()
{
    setWindowState(windowState() ^ Qt::WindowMinimized);
}

// Called by LauncherApplication when it wants to dismiss the
// keyboard.  hideOnFocusOut() is a slot on MInputContext, that seems
// to be required, it doesn't get it right if you just drop the focus
// (bug in MInputContext?)
void LauncherWindow::dismissKeyboard()
{
    if(scene() && scene()->focusItem())
    {
        if (QMetaObject::invokeMethod(qApp->inputContext(), "hideOnFocusOut"))
        {
            scene()->focusItem()->clearFocus();
        }
    }
}

void LauncherWindow::forwardCall(const QStringList& parameters)
{
    m_call = parameters;
    emit call(parameters);
    emit callChanged();
}

void LauncherWindow::setActualOrientation(int orientation)
{
    m_actualOrientation = orientation;

    if (!winId())
    {
        return;
    }

    Atom orientationAtom = XInternAtom(QX11Info::display(), "_MEEGO_ORIENTATION", false);
    XChangeProperty(QX11Info::display(), winId(), orientationAtom, XA_CARDINAL, 32,
                    PropModeReplace, (unsigned char*)&m_actualOrientation, 1);
}

bool LauncherWindow::event (QEvent * event)
{
    if (event->type() == QEvent::Show)
    {
        setActualOrientation(m_actualOrientation);
    }
    return QWidget::event(event);
}

void LauncherWindow::setInhibitScreenSaver(bool inhibit)
{
    m_inhibitScreenSaver = inhibit;

    Atom inhibitAtom = XInternAtom(QX11Info::display(), "_MEEGO_INHIBIT_SCREENSAVER", false);
    if (inhibit)
    {
        XChangeProperty(QX11Info::display(), winId(), inhibitAtom, XA_CARDINAL, 32,
                        PropModeReplace, (unsigned char*)&m_inhibitScreenSaver, 1);
    }
    else
    {
        XDeleteProperty(QX11Info::display(), winId(), inhibitAtom);
    }
}

void LauncherWindow::updateOrientationSensorOn()
{
    LauncherApp *app = static_cast<LauncherApp *>(qApp);
    app->setOrientationSensorOn(app->getForegroundWindow() == winId());
}

void LauncherWindow::switchToGLRendering()
{
    if (m_usingGl || !m_useOpenGl)
        return;

    //go once around event loop to avoid crash in egl
    QTimer::singleShot(0, this, SLOT(doSwitchToGLRendering()));
}

void LauncherWindow::switchToSoftwareRendering()
{
    // no need to change viewport unnecessarily
    if (!m_usingGl)
        return;

    setViewport(0);

    // each time we create a new viewport widget, we must redo our optimisations
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    viewport()->setAttribute(Qt::WA_NoSystemBackground);
    m_usingGl = false;
}

void LauncherWindow::doSwitchToGLRendering()
{
    QGLFormat format = QGLFormat::defaultFormat();
    format.setSampleBuffers(false);
    setViewport(new QGLWidget(format));

    // each time we create a new viewport widget, we must redo our optimisations
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    viewport()->setAttribute(Qt::WA_NoSystemBackground);
    m_usingGl = true;
}
<commit_msg>Stop crashing in chroot, call setAttribute via viewport()<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include <QApplication>
#include <QDBusConnection>
#include <QDBusError>
#include <QDBusInterface>
#include <QDeclarativeEngine>
#include <QDeclarativeView>
#include <QGraphicsItem>
#include <QDeclarativeContext>
#include <QDeclarativeNetworkAccessManagerFactory>
#include <QDesktopWidget>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QGLFormat>
#include <QLibraryInfo>
#include <QNetworkAccessManager>
#include <QNetworkDiskCache>
#include <QNetworkProxy>
#include <QResizeEvent>
#include <QSettings>
#include <QTimer>
#include <QTextStream>
#include <QTranslator>
#include <QVariant>
#include <QX11Info>
#include <MGConfItem>
#include <QInputContext>

#include "launcherwindow.h"
#include "launcheratoms.h"
#include "launcherapp.h"

#include "meegoqmllauncher.h"

#include <QX11Info>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <unistd.h>

class NetworkAccessManagerFactory : public QDeclarativeNetworkAccessManagerFactory
{
public:
    virtual QNetworkAccessManager *create(QObject *parent);
};

QNetworkAccessManager *NetworkAccessManagerFactory::create(QObject *parent)
{
    QUrl httpProxy(getenv("http_proxy"));
    QNetworkAccessManager *nam = new QNetworkAccessManager(parent);
    if (!httpProxy.isEmpty())
    {
        QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy,
                            httpProxy.host(),
                            httpProxy.port());
        nam->setProxy(proxy);
    }

    QNetworkDiskCache *cache = new QNetworkDiskCache();
    cache->setCacheDirectory(QDir::homePath() + "/.cache/" + qApp->applicationName());
    nam->setCache(cache);

    return nam;
}

LauncherWindow::LauncherWindow(bool fullscreen, int width, int height, bool opengl, bool doSetSource, QWidget *parent) :
    QDeclarativeView(parent),
    m_inhibitScreenSaver(false),
    m_useOpenGl(opengl),
    m_usingGl(false)
{
    LauncherApp *app = static_cast<LauncherApp *>(qApp);

    viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    viewport()->setAttribute(Qt::WA_NoSystemBackground);

    engine()->setNetworkAccessManagerFactory(new NetworkAccessManagerFactory);
    connect(engine(), SIGNAL(quit()), qApp, SLOT(closeAllWindows()));

    connect((const QObject*)qApp->inputContext(), SIGNAL(inputMethodAreaChanged(QRect)),
            this, SLOT(handleInputMethodAreaChanged(QRect)));
    connect(qApp, SIGNAL(dismissKeyboard()), this, SLOT(dismissKeyboard()));

    QDeclarativeContext *context = rootContext();

    context->setContextProperty("qApp", qApp);
    context->setContextProperty("mainWindow", this);
    context->setContextProperty("theme_name", MGConfItem("/meego/ux/theme").value().toString());
    foreach (QString key, app->themeConfig->allKeys())
    {
        if (key.contains("Size") || key.contains("Padding") ||
            key.contains("Width") ||key.contains("Height") ||
            key.contains("Margin") || key.contains("Thickness"))
        {
            context->setContextProperty("theme_" + key, app->themeConfig->value(key).toInt());
        }
        else if (key.contains("Opacity"))
        {
            context->setContextProperty("theme_" + key, app->themeConfig->value(key).toDouble());
        }
        else
        {
            context->setContextProperty("theme_" + key, app->themeConfig->value(key));
        }
    }

    loadCommonTranslators();
    connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadCommonTranslators()));

    // Qt will search each translator for a string translation, starting with
    // the last translator installed working back to the first translator.
    // The first translation found wins.
    app->installTranslator(&qtTranslator);     // General Qt translations
    app->installTranslator(&commonTranslator); // Common Components translations
    app->installTranslator(&mediaTranslator);  // Common Media translations

    if (app->applicationName() != MeeGoQMLLauncher::preinitialisedAppName)
    {
        init(fullscreen, width, height, opengl, doSetSource);
    }
}

LauncherWindow::~LauncherWindow()
{
}

void LauncherWindow::init(bool fullscreen, int width, int height,
                          bool opengl, bool doSetSource)
{
    m_useOpenGl = opengl;

    LauncherApp *app = static_cast<LauncherApp *>(qApp);

    setWindowTitle(app->applicationName());
    setWindowIconText(app->applicationName());

    int screenWidth;
    int screenHeight;
    if (fullscreen)
    {
        screenWidth = qApp->desktop()->rect().width();
        screenHeight = qApp->desktop()->rect().height();
        setWindowFlags(Qt::FramelessWindowHint);
    }
    else
    {
        screenWidth = width;
        screenHeight = height;
    }

    QDeclarativeContext *context = rootContext();
    context->setContextProperty("screenWidth", screenWidth);
    context->setContextProperty("screenHeight", screenHeight);

    if (doSetSource) {
        sharePath = QString("/usr/share/") + app->applicationName() + "/";
        if (!QFile::exists(sharePath + "main.qml"))
        {
            qFatal("%s does not exist!", sharePath.toUtf8().data());
        }
    }

    loadAppTranslators();
    connect(app, SIGNAL(localeSettingsChanged()), this, SLOT(loadAppTranslators()));
    app->installTranslator(&appTranslator);    // App specific translations

    // Switch to GL rendering if it's available
    switchToGLRendering();

    if (doSetSource)
    {
        setSource(QUrl(sharePath + "main.qml"));
    }

    setGeometry(QRect(0, 0, screenWidth, screenHeight));

    connect(app, SIGNAL(foregroundWindowChanged()), this, SLOT(updateOrientationSensorOn()));
}

void LauncherWindow::keyPressEvent ( QKeyEvent * event )
{
    if ((event->modifiers() & Qt::ControlModifier) && event->key() == Qt::Key_R)
    {
        QGraphicsObject* window = rootObject();
        if (window)
        {
            QVariant orientation = window->property("orientation");
            if(orientation.isValid())
            {
                int orient = orientation.toInt();
                orient = ((orient + 1) % 4);
                orientation.setValue(orient);
                window->setProperty("orientation", orientation);
                return;
            }
        }
    }

    QDeclarativeView::keyPressEvent(event);
}

void LauncherWindow::loadCommonTranslators()
{
    qtTranslator.load("qt_" + QLocale::system().name() + ".qm",
                      QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    commonTranslator.load("meegolabs-ux-components_" + QLocale::system().name() + ".qm",
                          QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    mediaTranslator.load("meego-ux-media-qml_" + QLocale::system().name() + ".qm",
                         QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}

void LauncherWindow::loadAppTranslators()
{
    LauncherApp *app = static_cast<LauncherApp *>(qApp);

    appTranslator.load(app->applicationName() + "_" + QLocale::system().name() + ".qm",
                       QLibraryInfo::location(QLibraryInfo::TranslationsPath));
}

void LauncherWindow::triggerSystemUIMenu()
{
    QDBusInterface iface("com.nokia.systemui","/statusindicatormenu","com.meego.core.MStatusIndicatorMenu");
    if(iface.isValid()) iface.call("open");
}

void LauncherWindow::goHome()
{
    setWindowState(windowState() ^ Qt::WindowMinimized);
}

// Called by LauncherApplication when it wants to dismiss the
// keyboard.  hideOnFocusOut() is a slot on MInputContext, that seems
// to be required, it doesn't get it right if you just drop the focus
// (bug in MInputContext?)
void LauncherWindow::dismissKeyboard()
{
    if(scene() && scene()->focusItem())
    {
        if (QMetaObject::invokeMethod(qApp->inputContext(), "hideOnFocusOut"))
        {
            scene()->focusItem()->clearFocus();
        }
    }
}

void LauncherWindow::forwardCall(const QStringList& parameters)
{
    m_call = parameters;
    emit call(parameters);
    emit callChanged();
}

void LauncherWindow::setActualOrientation(int orientation)
{
    m_actualOrientation = orientation;

    if (!winId())
    {
        return;
    }

    Atom orientationAtom = XInternAtom(QX11Info::display(), "_MEEGO_ORIENTATION", false);
    XChangeProperty(QX11Info::display(), winId(), orientationAtom, XA_CARDINAL, 32,
                    PropModeReplace, (unsigned char*)&m_actualOrientation, 1);
}

bool LauncherWindow::event (QEvent * event)
{
    if (event->type() == QEvent::Show)
    {
        setActualOrientation(m_actualOrientation);
    }
    return QWidget::event(event);
}

void LauncherWindow::setInhibitScreenSaver(bool inhibit)
{
    m_inhibitScreenSaver = inhibit;

    Atom inhibitAtom = XInternAtom(QX11Info::display(), "_MEEGO_INHIBIT_SCREENSAVER", false);
    if (inhibit)
    {
        XChangeProperty(QX11Info::display(), winId(), inhibitAtom, XA_CARDINAL, 32,
                        PropModeReplace, (unsigned char*)&m_inhibitScreenSaver, 1);
    }
    else
    {
        XDeleteProperty(QX11Info::display(), winId(), inhibitAtom);
    }
}

void LauncherWindow::updateOrientationSensorOn()
{
    LauncherApp *app = static_cast<LauncherApp *>(qApp);
    app->setOrientationSensorOn(app->getForegroundWindow() == winId());
}

void LauncherWindow::switchToGLRendering()
{
    if (m_usingGl || !m_useOpenGl)
        return;

    //go once around event loop to avoid crash in egl
    QTimer::singleShot(0, this, SLOT(doSwitchToGLRendering()));
}

void LauncherWindow::switchToSoftwareRendering()
{
    // no need to change viewport unnecessarily
    if (!m_usingGl)
        return;

    setViewport(0);

    // each time we create a new viewport widget, we must redo our optimisations
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    viewport()->setAttribute(Qt::WA_NoSystemBackground);
    m_usingGl = false;
}

void LauncherWindow::doSwitchToGLRendering()
{
    QGLFormat format = QGLFormat::defaultFormat();
    format.setSampleBuffers(false);
    setViewport(new QGLWidget(format));

    // each time we create a new viewport widget, we must redo our optimisations
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    viewport()->setAttribute(Qt::WA_NoSystemBackground);
    m_usingGl = true;
}
<|endoftext|>