<commit_before>#include "qhotkey.h"
#include "qhotkey_p.h"
#include <QDebug>
#include <QX11Info>
#include <QThreadStorage>
#include <QTimer>
#include <X11/Xlib.h>
#include <xcb/xcb.h>

//compability to pre Qt 5.8
#ifndef Q_FALLTHROUGH
#define Q_FALLTHROUGH() (void)0
#endif

class QHotkeyPrivateX11 : public QHotkeyPrivate
{
public:
	// QAbstractNativeEventFilter interface
	bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE;

protected:
	// QHotkeyPrivate interface
	quint32 nativeKeycode(Qt::Key keycode, bool &ok) Q_DECL_OVERRIDE;
	quint32 nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) Q_DECL_OVERRIDE;
	QString getX11String(Qt::Key keycode);
	bool registerShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE;
	bool unregisterShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE;

private:
	static const QVector<quint32> specialModifiers;
	static const quint32 validModsMask;
	QTimer *releaseTimer = nullptr;
	xcb_key_press_event_t prevHandledEvent;
	xcb_key_press_event_t prevEvent;

	static QString formatX11Error(Display *display, int errorCode);

	class HotkeyErrorHandler {
	public:
		HotkeyErrorHandler();
		~HotkeyErrorHandler();

		static bool hasError;
		static QString errorString;

	private:
		XErrorHandler prevHandler;

		static int handleError(Display *display, XErrorEvent *error);
	};
};
NATIVE_INSTANCE(QHotkeyPrivateX11)

bool QHotkeyPrivate::isPlatformSupported()
{
	return QX11Info::isPlatformX11();
}

const QVector<quint32> QHotkeyPrivateX11::specialModifiers = {0, Mod2Mask, LockMask, (Mod2Mask | LockMask)};
const quint32 QHotkeyPrivateX11::validModsMask = ShiftMask | ControlMask | Mod1Mask | Mod4Mask;

bool QHotkeyPrivateX11::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
	Q_UNUSED(eventType)
	Q_UNUSED(result)

	xcb_generic_event_t *genericEvent = static_cast<xcb_generic_event_t *>(message);
	if (genericEvent->response_type == XCB_KEY_PRESS) {
		xcb_key_press_event_t keyEvent = *static_cast<xcb_key_press_event_t *>(message);
		this->prevEvent = keyEvent;
		if (this->prevHandledEvent.response_type == XCB_KEY_RELEASE) {
			if(this->prevHandledEvent.time == keyEvent.time) return false;
		}
		this->activateShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask});
	} else if (genericEvent->response_type == XCB_KEY_RELEASE) {
		xcb_key_release_event_t keyEvent = *static_cast<xcb_key_release_event_t *>(message);
		this->prevEvent = keyEvent;
		QTimer *timer = new QTimer(this);
		timer->setSingleShot(true);
		timer->setInterval(50);
		connect(timer, &QTimer::timeout, this, [this, keyEvent, timer] {
			if(this->prevEvent.time == keyEvent.time && this->prevEvent.response_type == keyEvent.response_type && this->prevEvent.detail == keyEvent.detail){
				this->releaseShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask});
			}
			delete timer;
		});
		timer->start();
		this->releaseTimer = timer;
		this->prevHandledEvent = keyEvent;
	}

	return false;
}

QString QHotkeyPrivateX11::getX11String(Qt::Key keycode)
{
	switch(keycode){

		case Qt::Key_MediaLast :
		case Qt::Key_MediaPrevious :
			return "XF86AudioPrev";
		case Qt::Key_MediaNext :
			return "XF86AudioNext";
		case Qt::Key_MediaPause :
		case Qt::Key_MediaPlay :
		case Qt::Key_MediaTogglePlayPause :
			return "XF86AudioPlay";
		case Qt::Key_MediaRecord :
			return "XF86AudioRecord";
		case Qt::Key_MediaStop :
			return "XF86AudioStop";
		default :
			return QKeySequence(keycode).toString(QKeySequence::NativeText);
	}
}

quint32 QHotkeyPrivateX11::nativeKeycode(Qt::Key keycode, bool &ok)
{
	QString keyString = getX11String(keycode);

	KeySym keysym = XStringToKeysym(keyString.toLatin1().constData());
	if (keysym == NoSymbol) {
		//not found -> just use the key
		if(keycode <= 0xFFFF)
			keysym = keycode;
		else
			return 0;
	}

	if(QX11Info::isPlatformX11()) {
		auto res = XKeysymToKeycode(QX11Info::display(), keysym);
		if(res != 0)
			ok = true;
		return res;
	} else
		return 0;
}

quint32 QHotkeyPrivateX11::nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok)
{
	quint32 nMods = 0;
	if (modifiers & Qt::ShiftModifier)
		nMods |= ShiftMask;
	if (modifiers & Qt::ControlModifier)
		nMods |= ControlMask;
	if (modifiers & Qt::AltModifier)
		nMods |= Mod1Mask;
	if (modifiers & Qt::MetaModifier)
		nMods |= Mod4Mask;
	ok = true;
	return nMods;
}

bool QHotkeyPrivateX11::registerShortcut(QHotkey::NativeShortcut shortcut)
{
	Display *display = QX11Info::display();
	if(!display)
		return false;

	HotkeyErrorHandler errorHandler;
	for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) {
		XGrabKey(display,
				 shortcut.key,
				 shortcut.modifier | specialMod,
				 DefaultRootWindow(display),
				 True,
				 GrabModeAsync,
				 GrabModeAsync);
	}
	XSync(display, False);

	if(errorHandler.hasError) {
		error = errorHandler.errorString;
		this->unregisterShortcut(shortcut);
		return false;
	} else
		return true;
}

bool QHotkeyPrivateX11::unregisterShortcut(QHotkey::NativeShortcut shortcut)
{
	Display *display = QX11Info::display();
	if(!display)
		return false;

	HotkeyErrorHandler errorHandler;
	for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) {
		XUngrabKey(display,
				   shortcut.key,
				   shortcut.modifier | specialMod,
				   DefaultRootWindow(display));
	}
	XSync(display, False);

	if(errorHandler.hasError) {
		error = errorHandler.errorString;
		return false;
	} else
		return true;
}

QString QHotkeyPrivateX11::formatX11Error(Display *display, int errorCode)
{
	char errStr[256];
	XGetErrorText(display, errorCode, errStr, 256);
	return QString::fromLatin1(errStr);
}

// ---------- QHotkeyPrivateX11::HotkeyErrorHandler implementation ----------

bool QHotkeyPrivateX11::HotkeyErrorHandler::hasError = false;
QString QHotkeyPrivateX11::HotkeyErrorHandler::errorString;

QHotkeyPrivateX11::HotkeyErrorHandler::HotkeyErrorHandler()
{
	prevHandler = XSetErrorHandler(&HotkeyErrorHandler::handleError);
}

QHotkeyPrivateX11::HotkeyErrorHandler::~HotkeyErrorHandler()
{
	XSetErrorHandler(prevHandler);
	hasError = false;
	errorString.clear();
}

int QHotkeyPrivateX11::HotkeyErrorHandler::handleError(Display *display, XErrorEvent *error)
{
	switch (error->error_code) {
	case BadAccess:
	case BadValue:
	case BadWindow:
		if (error->request_code == 33 || //grab key
			error->request_code == 34) {// ungrab key
			hasError = true;
			errorString = QHotkeyPrivateX11::formatX11Error(display, error->error_code);
			return 1;
		}
		Q_FALLTHROUGH();
		// fall through
	default:
		return 0;
	}
}
<commit_msg>fix SIGSEGV on wayland<commit_after>#include "qhotkey.h"
#include "qhotkey_p.h"
#include <QDebug>
#include <QX11Info>
#include <QThreadStorage>
#include <QTimer>
#include <X11/Xlib.h>
#include <xcb/xcb.h>

//compability to pre Qt 5.8
#ifndef Q_FALLTHROUGH
#define Q_FALLTHROUGH() (void)0
#endif

class QHotkeyPrivateX11 : public QHotkeyPrivate
{
public:
	// QAbstractNativeEventFilter interface
	bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE;

protected:
	// QHotkeyPrivate interface
	quint32 nativeKeycode(Qt::Key keycode, bool &ok) Q_DECL_OVERRIDE;
	quint32 nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) Q_DECL_OVERRIDE;
	QString getX11String(Qt::Key keycode);
	bool registerShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE;
	bool unregisterShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE;

private:
	static const QVector<quint32> specialModifiers;
	static const quint32 validModsMask;
	QTimer *releaseTimer = nullptr;
	xcb_key_press_event_t prevHandledEvent;
	xcb_key_press_event_t prevEvent;

	static QString formatX11Error(Display *display, int errorCode);

	class HotkeyErrorHandler {
	public:
		HotkeyErrorHandler();
		~HotkeyErrorHandler();

		static bool hasError;
		static QString errorString;

	private:
		XErrorHandler prevHandler;

		static int handleError(Display *display, XErrorEvent *error);
	};
};
NATIVE_INSTANCE(QHotkeyPrivateX11)

bool QHotkeyPrivate::isPlatformSupported()
{
	return QX11Info::isPlatformX11();
}

const QVector<quint32> QHotkeyPrivateX11::specialModifiers = {0, Mod2Mask, LockMask, (Mod2Mask | LockMask)};
const quint32 QHotkeyPrivateX11::validModsMask = ShiftMask | ControlMask | Mod1Mask | Mod4Mask;

bool QHotkeyPrivateX11::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
	Q_UNUSED(eventType)
	Q_UNUSED(result)

	xcb_generic_event_t *genericEvent = static_cast<xcb_generic_event_t *>(message);
	if (genericEvent->response_type == XCB_KEY_PRESS) {
		xcb_key_press_event_t keyEvent = *static_cast<xcb_key_press_event_t *>(message);
		this->prevEvent = keyEvent;
		if (this->prevHandledEvent.response_type == XCB_KEY_RELEASE) {
			if(this->prevHandledEvent.time == keyEvent.time) return false;
		}
		this->activateShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask});
	} else if (genericEvent->response_type == XCB_KEY_RELEASE) {
		xcb_key_release_event_t keyEvent = *static_cast<xcb_key_release_event_t *>(message);
		this->prevEvent = keyEvent;
		QTimer *timer = new QTimer(this);
		timer->setSingleShot(true);
		timer->setInterval(50);
		connect(timer, &QTimer::timeout, this, [this, keyEvent, timer] {
			if(this->prevEvent.time == keyEvent.time && this->prevEvent.response_type == keyEvent.response_type && this->prevEvent.detail == keyEvent.detail){
				this->releaseShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask});
			}
			delete timer;
		});
		timer->start();
		this->releaseTimer = timer;
		this->prevHandledEvent = keyEvent;
	}

	return false;
}

QString QHotkeyPrivateX11::getX11String(Qt::Key keycode)
{
	switch(keycode){

		case Qt::Key_MediaLast :
		case Qt::Key_MediaPrevious :
			return "XF86AudioPrev";
		case Qt::Key_MediaNext :
			return "XF86AudioNext";
		case Qt::Key_MediaPause :
		case Qt::Key_MediaPlay :
		case Qt::Key_MediaTogglePlayPause :
			return "XF86AudioPlay";
		case Qt::Key_MediaRecord :
			return "XF86AudioRecord";
		case Qt::Key_MediaStop :
			return "XF86AudioStop";
		default :
			return QKeySequence(keycode).toString(QKeySequence::NativeText);
	}
}

quint32 QHotkeyPrivateX11::nativeKeycode(Qt::Key keycode, bool &ok)
{
	QString keyString = getX11String(keycode);

	KeySym keysym = XStringToKeysym(keyString.toLatin1().constData());
	if (keysym == NoSymbol) {
		//not found -> just use the key
		if(keycode <= 0xFFFF)
			keysym = keycode;
		else
			return 0;
	}

	if(QX11Info::isPlatformX11()) {
		auto res = XKeysymToKeycode(QX11Info::display(), keysym);
		if(res != 0)
			ok = true;
		return res;
	} else
		return 0;
}

quint32 QHotkeyPrivateX11::nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok)
{
	quint32 nMods = 0;
	if (modifiers & Qt::ShiftModifier)
		nMods |= ShiftMask;
	if (modifiers & Qt::ControlModifier)
		nMods |= ControlMask;
	if (modifiers & Qt::AltModifier)
		nMods |= Mod1Mask;
	if (modifiers & Qt::MetaModifier)
		nMods |= Mod4Mask;
	ok = true;
	return nMods;
}

bool QHotkeyPrivateX11::registerShortcut(QHotkey::NativeShortcut shortcut)
{
	Display *display = QX11Info::display();
	if(!display || !QX11Info::isPlatformX11())
		return false;

	HotkeyErrorHandler errorHandler;
	for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) {
		XGrabKey(display,
				 shortcut.key,
				 shortcut.modifier | specialMod,
				 DefaultRootWindow(display),
				 True,
				 GrabModeAsync,
				 GrabModeAsync);
	}
	XSync(display, False);

	if(errorHandler.hasError) {
		error = errorHandler.errorString;
		this->unregisterShortcut(shortcut);
		return false;
	} else
		return true;
}

bool QHotkeyPrivateX11::unregisterShortcut(QHotkey::NativeShortcut shortcut)
{
	Display *display = QX11Info::display();
	if(!display)
		return false;

	HotkeyErrorHandler errorHandler;
	for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers) {
		XUngrabKey(display,
				   shortcut.key,
				   shortcut.modifier | specialMod,
				   DefaultRootWindow(display));
	}
	XSync(display, False);

	if(errorHandler.hasError) {
		error = errorHandler.errorString;
		return false;
	} else
		return true;
}

QString QHotkeyPrivateX11::formatX11Error(Display *display, int errorCode)
{
	char errStr[256];
	XGetErrorText(display, errorCode, errStr, 256);
	return QString::fromLatin1(errStr);
}

// ---------- QHotkeyPrivateX11::HotkeyErrorHandler implementation ----------

bool QHotkeyPrivateX11::HotkeyErrorHandler::hasError = false;
QString QHotkeyPrivateX11::HotkeyErrorHandler::errorString;

QHotkeyPrivateX11::HotkeyErrorHandler::HotkeyErrorHandler()
{
	prevHandler = XSetErrorHandler(&HotkeyErrorHandler::handleError);
}

QHotkeyPrivateX11::HotkeyErrorHandler::~HotkeyErrorHandler()
{
	XSetErrorHandler(prevHandler);
	hasError = false;
	errorString.clear();
}

int QHotkeyPrivateX11::HotkeyErrorHandler::handleError(Display *display, XErrorEvent *error)
{
	switch (error->error_code) {
	case BadAccess:
	case BadValue:
	case BadWindow:
		if (error->request_code == 33 || //grab key
			error->request_code == 34) {// ungrab key
			hasError = true;
			errorString = QHotkeyPrivateX11::formatX11Error(display, error->error_code);
			return 1;
		}
		Q_FALLTHROUGH();
		// fall through
	default:
		return 0;
	}
}
<|endoftext|>


<commit_before><commit_msg>comienzo read/write<commit_after><|endoftext|>


<commit_before>/** This source adapted from https://github.com/kmicklas/variadic-static_variant
 *
 * Copyright (C) 2013 Kenneth Micklas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **/
#pragma once
#include <stdexcept>
#include <typeinfo>
#include <fc/exception/exception.hpp>
#include <boost/core/typeinfo.hpp>

namespace fc {

// Implementation details, the user should not import this:
namespace impl {

template<int N, typename... Ts>
struct storage_ops;

template<typename X, typename... Ts>
struct position;

template<int Pos, typename... Ts>
struct type_at;

template<typename... Ts>
struct type_info;

template<typename StaticVariant>
struct copy_construct
{
   typedef void result_type;
   StaticVariant& sv;
   copy_construct( StaticVariant& s ):sv(s){}
   template<typename T>
   void operator()( const T& v )const
   {
      sv.init(v);
   }
};

template<typename StaticVariant>
struct move_construct
{
   typedef void result_type;
   StaticVariant& sv;
   move_construct( StaticVariant& s ):sv(s){}
   template<typename T>
   void operator()( T& v )const
   {
      sv.init( std::move(v) );
   }
};

template<int N, typename T, typename... Ts>
struct storage_ops<N, T&, Ts...> {
    static void del(int n, void *data) {}
    static void con(int n, void *data) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, visitor& v) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, const visitor& v) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, visitor& v) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, const visitor& v) {}
};

template<int N, typename T, typename... Ts>
struct storage_ops<N, T, Ts...> {
    static void del(int n, void *data) {
        if(n == N) reinterpret_cast<T*>(data)->~T();
        else storage_ops<N + 1, Ts...>::del(n, data);
    }
    static void con(int n, void *data) {
        if(n == N) new(reinterpret_cast<T*>(data)) T();
        else storage_ops<N + 1, Ts...>::con(n, data);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, visitor& v) {
        if(n == N) return v(*reinterpret_cast<T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, const visitor& v) {
        if(n == N) return v(*reinterpret_cast<T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, visitor& v) {
        if(n == N) return v(*reinterpret_cast<const T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, const visitor& v) {
        if(n == N) return v(*reinterpret_cast<const T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }
};

template<int N>
struct storage_ops<N> {
    static void del(int n, void *data) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid.");
    }
    static void con(int n, void *data) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, const visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, const visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
};

template<typename X>
struct position<X> {
    static const int pos = -1;
};

template<typename X, typename... Ts>
struct position<X, X, Ts...> {
    static const int pos = 0;
};

template<typename X, typename T, typename... Ts>
struct position<X, T, Ts...> {
    static const int pos = position<X, Ts...>::pos != -1 ? position<X, Ts...>::pos + 1 : -1;
};

template<typename T, typename... Ts>
struct type_at<0, T, Ts...> {
   using type = T;
};

template<int Pos, typename T, typename... Ts>
struct type_at<Pos, T, Ts...> {
   using type = typename type_at<Pos - 1, Ts...>::type;
};

template<typename T, typename... Ts>
struct type_info<T&, Ts...> {
    static const bool no_reference_types = false;
    static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates;
    static const size_t size = type_info<Ts...>::size > sizeof(T&) ? type_info<Ts...>::size : sizeof(T&);
    static const size_t count = 1 + type_info<Ts...>::count;
};

template<typename T, typename... Ts>
struct type_info<T, Ts...> {
    static const bool no_reference_types = type_info<Ts...>::no_reference_types;
    static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates;
    static const size_t size = type_info<Ts...>::size > sizeof(T) ? type_info<Ts...>::size : sizeof(T&);
    static const size_t count = 1 + type_info<Ts...>::count;
};

template<>
struct type_info<> {
    static const bool no_reference_types = true;
    static const bool no_duplicates = true;
    static const size_t count = 0;
    static const size_t size = 0;
};

} // namespace impl

template<typename... Types>
class static_variant {
    static_assert(impl::type_info<Types...>::no_reference_types, "Reference types are not permitted in static_variant.");
    static_assert(impl::type_info<Types...>::no_duplicates, "static_variant type arguments contain duplicate types.");

    alignas(__int128) char storage[impl::type_info<Types...>::size];
    int _tag;

    template<typename X>
    void init(const X& x) {
        _tag = impl::position<X, Types...>::pos;
        new(storage) X(x);
    }

    template<typename X>
    void init(X&& x) {
        _tag = impl::position<X, Types...>::pos;
        new(storage) X( std::move(x) );
    }

    template<typename StaticVariant>
    friend struct impl::copy_construct;
    template<typename StaticVariant>
    friend struct impl::move_construct;
public:
    template<typename X>
    struct tag
    {
       static_assert(
         impl::position<X, Types...>::pos != -1,
         "Type not in static_variant."
       );
       static const int value = impl::position<X, Types...>::pos;
    };
    static_variant()
    {
       _tag = 0;
       impl::storage_ops<0, Types...>::con(0, storage);
    }

    template<typename... Other>
    static_variant( const static_variant<Other...>& cpy )
    {
       cpy.visit( impl::copy_construct<static_variant>(*this) );
    }
    static_variant( const static_variant& cpy )
    {
       cpy.visit( impl::copy_construct<static_variant>(*this) );
    }

    static_variant( static_variant&& mv )
    {
       mv.visit( impl::move_construct<static_variant>(*this) );
    }

    template<typename X>
    static_variant(const X& v) {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        init(v);
    }
    ~static_variant() {
       impl::storage_ops<0, Types...>::del(_tag, storage);
    }

    template<typename X>
    static_variant& operator=(const X& v) {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        this->~static_variant();
        init(v);
        return *this;
    }
    static_variant& operator=( const static_variant& v )
    {
       if( this == &v ) return *this;
       this->~static_variant();
       v.visit( impl::copy_construct<static_variant>(*this) );
       return *this;
    }
    static_variant& operator=( static_variant&& v )
    {
       if( this == &v ) return *this;
       this->~static_variant();
       v.visit( impl::move_construct<static_variant>(*this) );
       return *this;
    }
    friend bool operator == ( const static_variant& a, const static_variant& b )
    {
       return a.which() == b.which();
    }
    friend bool operator < ( const static_variant& a, const static_variant& b )
    {
       return a.which() < b.which();
    }

    template<typename X>
    X& get() {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        if(_tag == impl::position<X, Types...>::pos) {
            void* tmp(storage);
            return *reinterpret_cast<X*>(tmp);
        } else {
            FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) );
           //     std::string("static_variant does not contain value of type ") + typeid(X).name()
           // );
        }
    }
    template<typename X>
    const X& get() const {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        if(_tag == impl::position<X, Types...>::pos) {
            const void* tmp(storage);
            return *reinterpret_cast<const X*>(tmp);
        } else {
            FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) );
        }
    }
    template<typename visitor>
    typename visitor::result_type visit(visitor& v) {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    template<typename visitor>
    typename visitor::result_type visit(const visitor& v) {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    template<typename visitor>
    typename visitor::result_type visit(visitor& v)const {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    template<typename visitor>
    typename visitor::result_type visit(const visitor& v)const {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    static int count() { return impl::type_info<Types...>::count; }
    void set_which( int w ) {
      FC_ASSERT( w < count() );
      this->~static_variant();
      _tag = w;
      impl::storage_ops<0, Types...>::con(_tag, storage);
    }

    int which() const {return _tag;}

    template<typename X>
    bool contains() const { return which() == tag<X>::value; }

    template<typename X>
    static constexpr int position() { return impl::position<X, Types...>::pos; }

    template<int Pos, std::enable_if_t<Pos < impl::type_info<Types...>::size,int> = 1>
    using type_at = typename impl::type_at<Pos, Types...>::type;
};

template<typename Result>
struct visitor {
    typedef Result result_type;
};

   struct from_static_variant
   {
      variant& var;
      from_static_variant( variant& dv ):var(dv){}

      typedef void result_type;
      template<typename T> void operator()( const T& v )const
      {
         to_variant( v, var );
      }
   };

   struct to_static_variant
   {
      const variant& var;
      to_static_variant( const variant& dv ):var(dv){}

      typedef void result_type;
      template<typename T> void operator()( T& v )const
      {
         from_variant( var, v );
      }
   };

   template<typename... T> void to_variant( const fc::static_variant<T...>& s, fc::variant& v )
   {
      variant tmp;
      variants vars(2);
      vars[0] = s.which();
      s.visit( from_static_variant(vars[1]) );
      v = std::move(vars);
   }
   template<typename... T> void from_variant( const fc::variant& v, fc::static_variant<T...>& s )
   {
      auto ar = v.get_array();
      if( ar.size() < 2 ) return;
      s.set_which( ar[0].as_uint64() );
      s.visit( to_static_variant(ar[1]) );
   }

  template<typename... T> struct get_typename { static const char* name()   { return BOOST_CORE_TYPEID(static_variant<T...>).name();   } };
} // namespace fc
<commit_msg>more correct alignas #1853<commit_after>/** This source adapted from https://github.com/kmicklas/variadic-static_variant
 *
 * Copyright (C) 2013 Kenneth Micklas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **/
#pragma once
#include <stdexcept>
#include <typeinfo>
#include <fc/exception/exception.hpp>
#include <boost/core/typeinfo.hpp>

namespace fc {

// Implementation details, the user should not import this:
namespace impl {

template<int N, typename... Ts>
struct storage_ops;

template<typename X, typename... Ts>
struct position;

template<int Pos, typename... Ts>
struct type_at;

template<typename... Ts>
struct type_info;

template<typename StaticVariant>
struct copy_construct
{
   typedef void result_type;
   StaticVariant& sv;
   copy_construct( StaticVariant& s ):sv(s){}
   template<typename T>
   void operator()( const T& v )const
   {
      sv.init(v);
   }
};

template<typename StaticVariant>
struct move_construct
{
   typedef void result_type;
   StaticVariant& sv;
   move_construct( StaticVariant& s ):sv(s){}
   template<typename T>
   void operator()( T& v )const
   {
      sv.init( std::move(v) );
   }
};

template<int N, typename T, typename... Ts>
struct storage_ops<N, T&, Ts...> {
    static void del(int n, void *data) {}
    static void con(int n, void *data) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, visitor& v) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, const visitor& v) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, visitor& v) {}

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, const visitor& v) {}
};

template<int N, typename T, typename... Ts>
struct storage_ops<N, T, Ts...> {
    static void del(int n, void *data) {
        if(n == N) reinterpret_cast<T*>(data)->~T();
        else storage_ops<N + 1, Ts...>::del(n, data);
    }
    static void con(int n, void *data) {
        if(n == N) new(reinterpret_cast<T*>(data)) T();
        else storage_ops<N + 1, Ts...>::con(n, data);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, visitor& v) {
        if(n == N) return v(*reinterpret_cast<T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, const visitor& v) {
        if(n == N) return v(*reinterpret_cast<T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, visitor& v) {
        if(n == N) return v(*reinterpret_cast<const T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, const visitor& v) {
        if(n == N) return v(*reinterpret_cast<const T*>(data));
        else return storage_ops<N + 1, Ts...>::apply(n, data, v);
    }
};

template<int N>
struct storage_ops<N> {
    static void del(int n, void *data) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid.");
    }
    static void con(int n, void *data) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }

    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
    template<typename visitor>
    static typename visitor::result_type apply(int n, void *data, const visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
    template<typename visitor>
    static typename visitor::result_type apply(int n, const void *data, const visitor& v) {
       FC_THROW_EXCEPTION( fc::assert_exception, "Internal error: static_variant tag is invalid." );
    }
};

template<typename X>
struct position<X> {
    static const int pos = -1;
};

template<typename X, typename... Ts>
struct position<X, X, Ts...> {
    static const int pos = 0;
};

template<typename X, typename T, typename... Ts>
struct position<X, T, Ts...> {
    static const int pos = position<X, Ts...>::pos != -1 ? position<X, Ts...>::pos + 1 : -1;
};

template<typename T, typename... Ts>
struct type_at<0, T, Ts...> {
   using type = T;
};

template<int Pos, typename T, typename... Ts>
struct type_at<Pos, T, Ts...> {
   using type = typename type_at<Pos - 1, Ts...>::type;
};

template<typename T, typename... Ts>
struct type_info<T&, Ts...> {
    static const bool no_reference_types = false;
    static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates;
    static const size_t size = type_info<Ts...>::size > sizeof(T&) ? type_info<Ts...>::size : sizeof(T&);
    static const size_t count = 1 + type_info<Ts...>::count;
};

template<typename T, typename... Ts>
struct type_info<T, Ts...> {
    static const bool no_reference_types = type_info<Ts...>::no_reference_types;
    static const bool no_duplicates = position<T, Ts...>::pos == -1 && type_info<Ts...>::no_duplicates;
    static const size_t size = type_info<Ts...>::size > sizeof(T) ? type_info<Ts...>::size : sizeof(T&);
    static const size_t count = 1 + type_info<Ts...>::count;
};

template<>
struct type_info<> {
    static const bool no_reference_types = true;
    static const bool no_duplicates = true;
    static const size_t count = 0;
    static const size_t size = 0;
};

} // namespace impl

template<typename... Types>
class static_variant {
    static_assert(impl::type_info<Types...>::no_reference_types, "Reference types are not permitted in static_variant.");
    static_assert(impl::type_info<Types...>::no_duplicates, "static_variant type arguments contain duplicate types.");

    alignas(Types...) char storage[impl::type_info<Types...>::size];
    int _tag;

    template<typename X>
    void init(const X& x) {
        _tag = impl::position<X, Types...>::pos;
        new(storage) X(x);
    }

    template<typename X>
    void init(X&& x) {
        _tag = impl::position<X, Types...>::pos;
        new(storage) X( std::move(x) );
    }

    template<typename StaticVariant>
    friend struct impl::copy_construct;
    template<typename StaticVariant>
    friend struct impl::move_construct;
public:
    template<typename X>
    struct tag
    {
       static_assert(
         impl::position<X, Types...>::pos != -1,
         "Type not in static_variant."
       );
       static const int value = impl::position<X, Types...>::pos;
    };
    static_variant()
    {
       _tag = 0;
       impl::storage_ops<0, Types...>::con(0, storage);
    }

    template<typename... Other>
    static_variant( const static_variant<Other...>& cpy )
    {
       cpy.visit( impl::copy_construct<static_variant>(*this) );
    }
    static_variant( const static_variant& cpy )
    {
       cpy.visit( impl::copy_construct<static_variant>(*this) );
    }

    static_variant( static_variant&& mv )
    {
       mv.visit( impl::move_construct<static_variant>(*this) );
    }

    template<typename X>
    static_variant(const X& v) {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        init(v);
    }
    ~static_variant() {
       impl::storage_ops<0, Types...>::del(_tag, storage);
    }

    template<typename X>
    static_variant& operator=(const X& v) {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        this->~static_variant();
        init(v);
        return *this;
    }
    static_variant& operator=( const static_variant& v )
    {
       if( this == &v ) return *this;
       this->~static_variant();
       v.visit( impl::copy_construct<static_variant>(*this) );
       return *this;
    }
    static_variant& operator=( static_variant&& v )
    {
       if( this == &v ) return *this;
       this->~static_variant();
       v.visit( impl::move_construct<static_variant>(*this) );
       return *this;
    }
    friend bool operator == ( const static_variant& a, const static_variant& b )
    {
       return a.which() == b.which();
    }
    friend bool operator < ( const static_variant& a, const static_variant& b )
    {
       return a.which() < b.which();
    }

    template<typename X>
    X& get() {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        if(_tag == impl::position<X, Types...>::pos) {
            void* tmp(storage);
            return *reinterpret_cast<X*>(tmp);
        } else {
            FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) );
           //     std::string("static_variant does not contain value of type ") + typeid(X).name()
           // );
        }
    }
    template<typename X>
    const X& get() const {
        static_assert(
            impl::position<X, Types...>::pos != -1,
            "Type not in static_variant."
        );
        if(_tag == impl::position<X, Types...>::pos) {
            const void* tmp(storage);
            return *reinterpret_cast<const X*>(tmp);
        } else {
            FC_THROW_EXCEPTION( fc::assert_exception, "static_variant does not contain a value of type ${t}", ("t",fc::get_typename<X>::name()) );
        }
    }
    template<typename visitor>
    typename visitor::result_type visit(visitor& v) {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    template<typename visitor>
    typename visitor::result_type visit(const visitor& v) {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    template<typename visitor>
    typename visitor::result_type visit(visitor& v)const {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    template<typename visitor>
    typename visitor::result_type visit(const visitor& v)const {
        return impl::storage_ops<0, Types...>::apply(_tag, storage, v);
    }

    static int count() { return impl::type_info<Types...>::count; }
    void set_which( int w ) {
      FC_ASSERT( w < count() );
      this->~static_variant();
      _tag = w;
      impl::storage_ops<0, Types...>::con(_tag, storage);
    }

    int which() const {return _tag;}

    template<typename X>
    bool contains() const { return which() == tag<X>::value; }

    template<typename X>
    static constexpr int position() { return impl::position<X, Types...>::pos; }

    template<int Pos, std::enable_if_t<Pos < impl::type_info<Types...>::size,int> = 1>
    using type_at = typename impl::type_at<Pos, Types...>::type;
};

template<typename Result>
struct visitor {
    typedef Result result_type;
};

   struct from_static_variant
   {
      variant& var;
      from_static_variant( variant& dv ):var(dv){}

      typedef void result_type;
      template<typename T> void operator()( const T& v )const
      {
         to_variant( v, var );
      }
   };

   struct to_static_variant
   {
      const variant& var;
      to_static_variant( const variant& dv ):var(dv){}

      typedef void result_type;
      template<typename T> void operator()( T& v )const
      {
         from_variant( var, v );
      }
   };

   template<typename... T> void to_variant( const fc::static_variant<T...>& s, fc::variant& v )
   {
      variant tmp;
      variants vars(2);
      vars[0] = s.which();
      s.visit( from_static_variant(vars[1]) );
      v = std::move(vars);
   }
   template<typename... T> void from_variant( const fc::variant& v, fc::static_variant<T...>& s )
   {
      auto ar = v.get_array();
      if( ar.size() < 2 ) return;
      s.set_which( ar[0].as_uint64() );
      s.visit( to_static_variant(ar[1]) );
   }

  template<typename... T> struct get_typename { static const char* name()   { return BOOST_CORE_TYPEID(static_variant<T...>).name();   } };
} // namespace fc
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "RawDecoder.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

	RawDecoder::RawDecoder(FileMap* file) : mRaw(RawImage::create()), mFile(file) {
  decoderVersion = 0;
}

RawDecoder::~RawDecoder(void) {
  for (uint32 i = 0 ; i < errors.size(); i++) {
    free((void*)errors[i]);
  }
  errors.clear();
}

void RawDecoder::decodeUncompressed(TiffIFD *rawIFD) {
  uint32 nslices = rawIFD->getEntry(STRIPOFFSETS)->count;
  const uint32 *offsets = rawIFD->getEntry(STRIPOFFSETS)->getIntArray();
  const uint32 *counts = rawIFD->getEntry(STRIPBYTECOUNTS)->getIntArray();
  uint32 yPerSlice = rawIFD->getEntry(ROWSPERSTRIP)->getInt();
  uint32 width = rawIFD->getEntry(IMAGEWIDTH)->getInt();
  uint32 height = rawIFD->getEntry(IMAGELENGTH)->getInt();
  uint32 bitPerPixel = rawIFD->getEntry(BITSPERSAMPLE)->getInt();

  vector<RawSlice> slices;
  uint32 offY = 0;

  for (uint32 s = 0; s < nslices; s++) {
    RawSlice slice;
    slice.offset = offsets[s];
    slice.count = counts[s];
    if (offY + yPerSlice > height)
      slice.h = height - offY;
    else
      slice.h = yPerSlice;

    offY += yPerSlice;

    if (mFile->isValid(slice.offset + slice.count)) // Only decode if size is valid
      slices.push_back(slice);
  }

  if (0 == slices.size())
    ThrowRDE("RAW Decoder: No valid slices found. File probably truncated.");

  mRaw->dim = iPoint2D(width, offY);
  mRaw->bpp = 2;
  mRaw->createData();
  mRaw->whitePoint = (1<<bitPerPixel)-1;

  offY = 0;
  for (uint32 i = 0; i < slices.size(); i++) {
    RawSlice slice = slices[i];
    ByteStream in(mFile->getData(slice.offset), slice.count);
    iPoint2D size(width, slice.h);
    iPoint2D pos(0, offY);
    bitPerPixel = (int)((__int64)(slice.count * 8) / (slice.h * width));
    try {
        readUncompressedRaw(in, size, pos, width*bitPerPixel / 8, bitPerPixel, true);
    } catch (RawDecoderException e) {
      if (i>0)
        errors.push_back(_strdup(e.what()));
      else
        throw;
    } catch (IOException e) {
      if (i>0)
        errors.push_back(_strdup(e.what()));
      else
        ThrowRDE("RAW decoder: IO error occurred in first slice, unable to decode more. Error is: %s", e.what());
    }
    offY += slice.h;
  }
}

void RawDecoder::readUncompressedRaw(ByteStream &input, iPoint2D& size, iPoint2D& offset, int inputPitch, int bitPerPixel, bool MSBOrder) {
  uchar8* data = mRaw->getData();
  uint32 outPitch = mRaw->pitch;
  uint32 w = size.x;
  uint32 h = size.y;
  uint32 cpp = mRaw->getCpp();

  if (input.getRemainSize() < (inputPitch*h)) {
    if ((int)input.getRemainSize() > inputPitch)
      h = input.getRemainSize() / inputPitch - 1;
    else
      ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated.");
  }
  if (bitPerPixel > 16)
    ThrowRDE("readUncompressedRaw: Unsupported bit depth");

  uint32 skipBits = inputPitch - w * bitPerPixel / 8;  // Skip per line
  if (offset.y > mRaw->dim.y)
    ThrowRDE("readUncompressedRaw: Invalid y offset");
  if (offset.x + size.x > mRaw->dim.x)
    ThrowRDE("readUncompressedRaw: Invalid x offset");

  uint32 y = offset.y;
  h = MIN(h + (uint32)offset.y, (uint32)mRaw->dim.y);

  if (MSBOrder) {
    BitPumpMSB bits(&input);
    w *= cpp;
    for (; y < h; y++) {
      ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)*cpp+y*outPitch];
      bits.checkPos();
      for (uint32 x = 0 ; x < w; x++) {
        uint32 b = bits.getBits(bitPerPixel);
        dest[x] = b;
      }
      bits.skipBits(skipBits);
    }

  } else {

    if (bitPerPixel == 16 && getHostEndianness() == little)  {
      BitBlt(&data[offset.x*sizeof(ushort16)*cpp+y*outPitch], outPitch,
             input.getData(), inputPitch, w*mRaw->bpp, h - y);
      return;
    }
    if (bitPerPixel == 12 && (int)w == inputPitch * 8 / 12 && getHostEndianness() == little)  {
      Decode12BitRaw(input, w, h);
      return;
    }
    BitPumpPlain bits(&input);
    w *= cpp;
    for (; y < h; y++) {
      ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)+y*outPitch];
      bits.checkPos();
      for (uint32 x = 0 ; x < w; x++) {
        uint32 b = bits.getBits(bitPerPixel);
        dest[x] = b;
      }
      bits.skipBits(skipBits);
    }
  }
}

void RawDecoder::Decode12BitRaw(ByteStream &input, uint32 w, uint32 h) {
  uchar8* data = mRaw->getData();
  uint32 pitch = mRaw->pitch;
  const uchar8 *in = input.getData();
  if (input.getRemainSize() < ((w*12/8)*h)) {
    if ((uint32)input.getRemainSize() > (w*12/8))
      h = input.getRemainSize() / (w*12/8) - 1;
    else
      ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated.");
  }
  for (uint32 y = 0; y < h; y++) {
    ushort16* dest = (ushort16*) & data[y*pitch];
    for (uint32 x = 0 ; x < w; x += 2) {
      uint32 g1 = *in++;
      uint32 g2 = *in++;
      dest[x] = g1 | ((g2 & 0xf) << 8);
      uint32 g3 = *in++;
      dest[x+1] = (g2 >> 4) | (g3 << 4);
    }
  }
}

void RawDecoder::checkCameraSupported(CameraMetaData *meta, string make, string model, string mode) {
  TrimSpaces(make);
  TrimSpaces(model);
  Camera* cam = meta->getCamera(make, model, mode);
  if (!cam) {
    if (mode.length() == 0)
      printf("Unable to find camera in database: %s %s %s\n", make.c_str(), model.c_str(), mode.c_str());

    return;    // Assume true.
  }

  if (!cam->supported)
    ThrowRDE("Camera not supported (explicit). Sorry.");

  if (cam->decoderVersion > decoderVersion)
    ThrowRDE("Camera not supported in this version. Update RawSpeed for support.");

  hints = cam->hints;
}

void RawDecoder::setMetaData(CameraMetaData *meta, string make, string model, string mode) {
  TrimSpaces(make);
  TrimSpaces(model);
  Camera *cam = meta->getCamera(make, model, mode);
  if (!cam) {
    printf("Unable to find camera in database: %s %s %s\nPlease upload file to ftp.rawstudio.org, thanks!\n", make.c_str(), model.c_str(), mode.c_str());
    return;
  }

  iPoint2D new_size = cam->cropSize;

  // If crop size is negative, use relative cropping
  if (new_size.x <= 0)
    new_size.x = mRaw->dim.x - cam->cropPos.x + new_size.x;

  if (new_size.y <= 0)
    new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;

  mRaw->subFrame(cam->cropPos, new_size);
  mRaw->cfa = cam->cfa;

  // Shift CFA to match crop
  if (cam->cropPos.x & 1)
    mRaw->cfa.shiftLeft();
  if (cam->cropPos.y & 1)
    mRaw->cfa.shiftDown();

  mRaw->blackLevel = cam->black;
  mRaw->whitePoint = cam->white;

}

void RawDecoder::TrimSpaces(string& str) {
  // Trim Both leading and trailing spaces
  size_t startpos = str.find_first_not_of(" \t"); // Find the first character position after excluding leading blank spaces
  size_t endpos = str.find_last_not_of(" \t"); // Find the first character position from reverse af

  // if all spaces or empty return an empty string
  if ((string::npos == startpos) || (string::npos == endpos)) {
    str = "";
  } else
    str = str.substr(startpos, endpos - startpos + 1);
}

void *RawDecoderDecodeThread(void *_this) {
  RawDecoderThread* me = (RawDecoderThread*)_this;
  try {
    me->parent->decodeThreaded(me);
  } catch (RawDecoderException ex) {
    me->error = _strdup(ex.what());
  } catch (IOException ex) {
    me->error = _strdup(ex.what());
  }

  pthread_exit(NULL);
  return 0;
}

void RawDecoder::startThreads() {
  uint32 threads;
  threads = getThreadCount();
  int y_offset = 0;
  int y_per_thread = (mRaw->dim.y + threads - 1) / threads;
  RawDecoderThread *t = new RawDecoderThread[threads];

  pthread_attr_t attr;

  /* Initialize and set thread detached attribute */
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  for (uint32 i = 0; i < threads; i++) {
    t[i].start_y = y_offset;
    t[i].end_y = MIN(y_offset + y_per_thread, mRaw->dim.y);
    t[i].parent = this;
    pthread_create(&t[i].threadid, &attr, RawDecoderDecodeThread, &t[i]);
    y_offset = t[i].end_y;
  }

  void *status;
  for (uint32 i = 0; i < threads; i++) {
    pthread_join(t[i].threadid, &status);
    if (t[i].error) {
      errors.push_back(t[i].error);
    }
  }
  if (errors.size() >= threads)
    ThrowRDE("RawDecoder::startThreads: All threads reported errors. Cannot load image.");

  delete[] t;
}

void RawDecoder::decodeThreaded(RawDecoderThread * t) {
  ThrowRDE("Internal Error: This class does not support threaded decoding");
}

} // namespace RawSpeed<commit_msg>Use our own type for 64 bit int.<commit_after>#include "StdAfx.h"
#include "RawDecoder.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

	RawDecoder::RawDecoder(FileMap* file) : mRaw(RawImage::create()), mFile(file) {
  decoderVersion = 0;
}

RawDecoder::~RawDecoder(void) {
  for (uint32 i = 0 ; i < errors.size(); i++) {
    free((void*)errors[i]);
  }
  errors.clear();
}

void RawDecoder::decodeUncompressed(TiffIFD *rawIFD) {
  uint32 nslices = rawIFD->getEntry(STRIPOFFSETS)->count;
  const uint32 *offsets = rawIFD->getEntry(STRIPOFFSETS)->getIntArray();
  const uint32 *counts = rawIFD->getEntry(STRIPBYTECOUNTS)->getIntArray();
  uint32 yPerSlice = rawIFD->getEntry(ROWSPERSTRIP)->getInt();
  uint32 width = rawIFD->getEntry(IMAGEWIDTH)->getInt();
  uint32 height = rawIFD->getEntry(IMAGELENGTH)->getInt();
  uint32 bitPerPixel = rawIFD->getEntry(BITSPERSAMPLE)->getInt();

  vector<RawSlice> slices;
  uint32 offY = 0;

  for (uint32 s = 0; s < nslices; s++) {
    RawSlice slice;
    slice.offset = offsets[s];
    slice.count = counts[s];
    if (offY + yPerSlice > height)
      slice.h = height - offY;
    else
      slice.h = yPerSlice;

    offY += yPerSlice;

    if (mFile->isValid(slice.offset + slice.count)) // Only decode if size is valid
      slices.push_back(slice);
  }

  if (0 == slices.size())
    ThrowRDE("RAW Decoder: No valid slices found. File probably truncated.");

  mRaw->dim = iPoint2D(width, offY);
  mRaw->bpp = 2;
  mRaw->createData();
  mRaw->whitePoint = (1<<bitPerPixel)-1;

  offY = 0;
  for (uint32 i = 0; i < slices.size(); i++) {
    RawSlice slice = slices[i];
    ByteStream in(mFile->getData(slice.offset), slice.count);
    iPoint2D size(width, slice.h);
    iPoint2D pos(0, offY);
    bitPerPixel = (int)((uint64)(slice.count * 8) / (slice.h * width));
    try {
        readUncompressedRaw(in, size, pos, width*bitPerPixel / 8, bitPerPixel, true);
    } catch (RawDecoderException e) {
      if (i>0)
        errors.push_back(_strdup(e.what()));
      else
        throw;
    } catch (IOException e) {
      if (i>0)
        errors.push_back(_strdup(e.what()));
      else
        ThrowRDE("RAW decoder: IO error occurred in first slice, unable to decode more. Error is: %s", e.what());
    }
    offY += slice.h;
  }
}

void RawDecoder::readUncompressedRaw(ByteStream &input, iPoint2D& size, iPoint2D& offset, int inputPitch, int bitPerPixel, bool MSBOrder) {
  uchar8* data = mRaw->getData();
  uint32 outPitch = mRaw->pitch;
  uint32 w = size.x;
  uint32 h = size.y;
  uint32 cpp = mRaw->getCpp();

  if (input.getRemainSize() < (inputPitch*h)) {
    if ((int)input.getRemainSize() > inputPitch)
      h = input.getRemainSize() / inputPitch - 1;
    else
      ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated.");
  }
  if (bitPerPixel > 16)
    ThrowRDE("readUncompressedRaw: Unsupported bit depth");

  uint32 skipBits = inputPitch - w * bitPerPixel / 8;  // Skip per line
  if (offset.y > mRaw->dim.y)
    ThrowRDE("readUncompressedRaw: Invalid y offset");
  if (offset.x + size.x > mRaw->dim.x)
    ThrowRDE("readUncompressedRaw: Invalid x offset");

  uint32 y = offset.y;
  h = MIN(h + (uint32)offset.y, (uint32)mRaw->dim.y);

  if (MSBOrder) {
    BitPumpMSB bits(&input);
    w *= cpp;
    for (; y < h; y++) {
      ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)*cpp+y*outPitch];
      bits.checkPos();
      for (uint32 x = 0 ; x < w; x++) {
        uint32 b = bits.getBits(bitPerPixel);
        dest[x] = b;
      }
      bits.skipBits(skipBits);
    }

  } else {

    if (bitPerPixel == 16 && getHostEndianness() == little)  {
      BitBlt(&data[offset.x*sizeof(ushort16)*cpp+y*outPitch], outPitch,
             input.getData(), inputPitch, w*mRaw->bpp, h - y);
      return;
    }
    if (bitPerPixel == 12 && (int)w == inputPitch * 8 / 12 && getHostEndianness() == little)  {
      Decode12BitRaw(input, w, h);
      return;
    }
    BitPumpPlain bits(&input);
    w *= cpp;
    for (; y < h; y++) {
      ushort16* dest = (ushort16*) & data[offset.x*sizeof(ushort16)+y*outPitch];
      bits.checkPos();
      for (uint32 x = 0 ; x < w; x++) {
        uint32 b = bits.getBits(bitPerPixel);
        dest[x] = b;
      }
      bits.skipBits(skipBits);
    }
  }
}

void RawDecoder::Decode12BitRaw(ByteStream &input, uint32 w, uint32 h) {
  uchar8* data = mRaw->getData();
  uint32 pitch = mRaw->pitch;
  const uchar8 *in = input.getData();
  if (input.getRemainSize() < ((w*12/8)*h)) {
    if ((uint32)input.getRemainSize() > (w*12/8))
      h = input.getRemainSize() / (w*12/8) - 1;
    else
      ThrowIOE("readUncompressedRaw: Not enough data to decode a single line. Image file truncated.");
  }
  for (uint32 y = 0; y < h; y++) {
    ushort16* dest = (ushort16*) & data[y*pitch];
    for (uint32 x = 0 ; x < w; x += 2) {
      uint32 g1 = *in++;
      uint32 g2 = *in++;
      dest[x] = g1 | ((g2 & 0xf) << 8);
      uint32 g3 = *in++;
      dest[x+1] = (g2 >> 4) | (g3 << 4);
    }
  }
}

void RawDecoder::checkCameraSupported(CameraMetaData *meta, string make, string model, string mode) {
  TrimSpaces(make);
  TrimSpaces(model);
  Camera* cam = meta->getCamera(make, model, mode);
  if (!cam) {
    if (mode.length() == 0)
      printf("Unable to find camera in database: %s %s %s\n", make.c_str(), model.c_str(), mode.c_str());

    return;    // Assume true.
  }

  if (!cam->supported)
    ThrowRDE("Camera not supported (explicit). Sorry.");

  if (cam->decoderVersion > decoderVersion)
    ThrowRDE("Camera not supported in this version. Update RawSpeed for support.");

  hints = cam->hints;
}

void RawDecoder::setMetaData(CameraMetaData *meta, string make, string model, string mode) {
  TrimSpaces(make);
  TrimSpaces(model);
  Camera *cam = meta->getCamera(make, model, mode);
  if (!cam) {
    printf("Unable to find camera in database: %s %s %s\nPlease upload file to ftp.rawstudio.org, thanks!\n", make.c_str(), model.c_str(), mode.c_str());
    return;
  }

  iPoint2D new_size = cam->cropSize;

  // If crop size is negative, use relative cropping
  if (new_size.x <= 0)
    new_size.x = mRaw->dim.x - cam->cropPos.x + new_size.x;

  if (new_size.y <= 0)
    new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;

  mRaw->subFrame(cam->cropPos, new_size);
  mRaw->cfa = cam->cfa;

  // Shift CFA to match crop
  if (cam->cropPos.x & 1)
    mRaw->cfa.shiftLeft();
  if (cam->cropPos.y & 1)
    mRaw->cfa.shiftDown();

  mRaw->blackLevel = cam->black;
  mRaw->whitePoint = cam->white;

}

void RawDecoder::TrimSpaces(string& str) {
  // Trim Both leading and trailing spaces
  size_t startpos = str.find_first_not_of(" \t"); // Find the first character position after excluding leading blank spaces
  size_t endpos = str.find_last_not_of(" \t"); // Find the first character position from reverse af

  // if all spaces or empty return an empty string
  if ((string::npos == startpos) || (string::npos == endpos)) {
    str = "";
  } else
    str = str.substr(startpos, endpos - startpos + 1);
}

void *RawDecoderDecodeThread(void *_this) {
  RawDecoderThread* me = (RawDecoderThread*)_this;
  try {
    me->parent->decodeThreaded(me);
  } catch (RawDecoderException ex) {
    me->error = _strdup(ex.what());
  } catch (IOException ex) {
    me->error = _strdup(ex.what());
  }

  pthread_exit(NULL);
  return 0;
}

void RawDecoder::startThreads() {
  uint32 threads;
  threads = getThreadCount();
  int y_offset = 0;
  int y_per_thread = (mRaw->dim.y + threads - 1) / threads;
  RawDecoderThread *t = new RawDecoderThread[threads];

  pthread_attr_t attr;

  /* Initialize and set thread detached attribute */
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

  for (uint32 i = 0; i < threads; i++) {
    t[i].start_y = y_offset;
    t[i].end_y = MIN(y_offset + y_per_thread, mRaw->dim.y);
    t[i].parent = this;
    pthread_create(&t[i].threadid, &attr, RawDecoderDecodeThread, &t[i]);
    y_offset = t[i].end_y;
  }

  void *status;
  for (uint32 i = 0; i < threads; i++) {
    pthread_join(t[i].threadid, &status);
    if (t[i].error) {
      errors.push_back(t[i].error);
    }
  }
  if (errors.size() >= threads)
    ThrowRDE("RawDecoder::startThreads: All threads reported errors. Cannot load image.");

  delete[] t;
}

void RawDecoder::decodeThreaded(RawDecoderThread * t) {
  ThrowRDE("Internal Error: This class does not support threaded decoding");
}

} // namespace RawSpeed<|endoftext|>


<commit_before>
#include <layout/form_layout.h>
#include <layout/box_layout.h>
#include <gui/application.h>
#include <gui/cocoa_style.h>

namespace {

////////////////////////////////////////

void build_form_window( const std::shared_ptr<gui::window> &win )
{
	using layout::form_layout;

	gui::builder builder( win );
	auto layout = builder.new_layout<form_layout>( layout::direction::RIGHT );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	auto row = layout->new_row();
	builder.make_label( row.first, "Hello World" );
	builder.make_button( row.second, "Press Me" );

	row = layout->new_row();
	builder.make_label( row.first, "Goodbye World" );
	builder.make_button( row.second, "Me Too" );
}

void build_box_window( const std::shared_ptr<gui::window> &win )
{
	using layout::box_layout;

	gui::builder builder( win );
	auto layout = builder.new_layout<box_layout>( layout::direction::DOWN );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	builder.make_label( layout->new_area(), "Hello World" );
	builder.make_button( layout->new_area(), "Press Me" );

	builder.make_label( layout->new_area(), "Goodbye World" );
	builder.make_button( layout->new_area(), "Me Too" );
}

////////////////////////////////////////

int safemain( int argc, char **argv )
{
	auto app = std::make_shared<gui::application>();
	app->push();
	app->set_style( std::make_shared<gui::cocoa_style>() );

	auto win1 = app->new_window();
	build_form_window( win1 );
	win1->show();

	auto win2 = app->new_window();
	build_box_window( win2 );
	win2->show();

	int code = app->run();
	app->pop();
	return code;
}

////////////////////////////////////////

}

////////////////////////////////////////

int main( int argc, char *argv[] )
{
	int ret = -1;
	try
	{
		ret = safemain( argc, argv );
	}
	catch ( std::exception &e )
	{
		print_exception( std::cerr, e );
	}
	return ret;
}

////////////////////////////////////////

<commit_msg>Added grid test.<commit_after>
#include <sstream>

#include <layout/form_layout.h>
#include <layout/box_layout.h>
#include <layout/grid_layout.h>
#include <gui/application.h>
#include <gui/cocoa_style.h>

namespace {

////////////////////////////////////////

void build_form_window( const std::shared_ptr<gui::window> &win )
{
	using layout::form_layout;

	gui::builder builder( win );
	auto layout = builder.new_layout<form_layout>( layout::direction::RIGHT );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	auto row = layout->new_row();
	builder.make_label( row.first, "Hello World" );
	builder.make_button( row.second, "Press Me" );

	row = layout->new_row();
	builder.make_label( row.first, "Goodbye World" );
	builder.make_button( row.second, "Me Too" );
}

void build_box_window( const std::shared_ptr<gui::window> &win )
{
	using layout::box_layout;

	gui::builder builder( win );
	auto layout = builder.new_layout<box_layout>( layout::direction::DOWN );
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	builder.make_label( layout->new_area(), "Hello World" );
	builder.make_button( layout->new_area(), "Press Me" );

	builder.make_label( layout->new_area(), "Goodbye World" );
	builder.make_button( layout->new_area(), "Me Too" );
}

void build_grid_window( const std::shared_ptr<gui::window> &win )
{
	using layout::grid_layout;

	gui::builder builder( win );
	auto layout = builder.new_layout<grid_layout>();
	layout->set_pad( 12.0, 12.0, 12.0, 12.0 );
	layout->set_spacing( 12.0, 12.0 );

	for ( size_t i = 0; i < 5; ++i )
		layout->new_column( 1.0 );

	int count = 0;
	for ( size_t i = 0; i < 5; ++i )
	{
		auto cols = layout->new_row();
		for ( auto a: cols )
		{
			std::stringstream tmp;
			tmp << ++count;
			builder.make_label( a, tmp.str() );
		}
	}
}

////////////////////////////////////////

int safemain( int argc, char **argv )
{
	auto app = std::make_shared<gui::application>();
	app->push();
	app->set_style( std::make_shared<gui::cocoa_style>() );

	auto win1 = app->new_window();
	build_form_window( win1 );
	win1->show();

	auto win2 = app->new_window();
	build_box_window( win2 );
	win2->show();

	auto win3 = app->new_window();
	build_grid_window( win3 );
	win3->show();

	int code = app->run();
	app->pop();
	return code;
}

////////////////////////////////////////

}

////////////////////////////////////////

int main( int argc, char *argv[] )
{
	int ret = -1;
	try
	{
		ret = safemain( argc, argv );
	}
	catch ( std::exception &e )
	{
		print_exception( std::cerr, e );
	}
	return ret;
}

////////////////////////////////////////

<|endoftext|>


<commit_before><commit_msg>Remove device get_default().<commit_after><|endoftext|>


<commit_before>//-----------------------------------------------------------
//
// Copyright (C) 2017 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
//-----------------------------------------------------------

#include <deal.II/sundials/copy.h>

#ifdef DEAL_II_WITH_SUNDIALS

DEAL_II_NAMESPACE_OPEN
namespace SUNDIALS
{
  namespace internal
  {
    namespace
    {
      /**
       * SUNDIALS provides different macros for getting the local length of a
       * vector for serial and parallel vectors (as well as various parallel
       * vectors that are not yet supported by deal.II). This function provides
       * a generic interface to both and does a (checked) conversion from long
       * int (the type SUNDIALS uses for lengths) to std::size_t.
       */
      inline
      std::size_t
      N_Vector_length(const N_Vector &vec)
      {
        const N_Vector_ID id = N_VGetVectorID(vec);
        long int length = -1;
        switch (id)
          {
          case SUNDIALS_NVEC_SERIAL:
          {
            length = NV_LENGTH_S(vec);
            break;
          }
          case SUNDIALS_NVEC_PARALLEL:
          {
            length = NV_LOCLENGTH_P(vec);
            break;
          }
          default:
            Assert(false, ExcNotImplemented());
          }

        Assert(length >= 0, ExcInternalError());
        return static_cast<std::size_t>(length);
      }
    }

#ifdef DEAL_II_WITH_MPI

#ifdef DEAL_II_WITH_TRILINOS

    void copy(TrilinosWrappers::MPI::Vector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const TrilinosWrappers::MPI::Vector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

    void copy(TrilinosWrappers::MPI::BlockVector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const TrilinosWrappers::MPI::BlockVector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

#endif //DEAL_II_WITH_TRILINOS

#ifdef DEAL_II_WITH_PETSC

    void copy(PETScWrappers::MPI::Vector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const PETScWrappers::MPI::Vector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

    void copy(PETScWrappers::MPI::BlockVector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const PETScWrappers::MPI::BlockVector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

#endif //DEAL_II_WITH_PETSC

#endif //mpi

    void copy(BlockVector<double> &dst, const N_Vector &src)
    {
      AssertDimension(N_Vector_length(src), dst.size());
      for (unsigned int i=0; i<dst.size(); ++i)
        {
          dst[i] = NV_Ith_S(src, i);
        }
    }

    void copy(N_Vector &dst, const BlockVector<double> &src)
    {
      AssertDimension(N_Vector_length(dst), src.size());
      for (unsigned int i=0; i<src.size(); ++i)
        {
          NV_Ith_S(dst, i) = src[i];
        }
    }

    void copy(Vector<double> &dst, const N_Vector &src)
    {
      AssertDimension(N_Vector_length(src), dst.size());
      for (unsigned int i=0; i<dst.size(); ++i)
        {
          dst[i] = NV_Ith_S(src, i);
        }
    }

    void copy(N_Vector &dst, const Vector<double> &src)
    {
      AssertDimension(N_Vector_length(dst), src.size());
      for (unsigned int i=0; i<src.size(); ++i)
        {
          NV_Ith_S(dst, i) = src[i];
        }
    }
  }
}
DEAL_II_NAMESPACE_CLOSE

#endif
<commit_msg>Move a function out of an anonymous namespace.<commit_after>//-----------------------------------------------------------
//
// Copyright (C) 2017 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
//-----------------------------------------------------------

#include <deal.II/sundials/copy.h>

#ifdef DEAL_II_WITH_SUNDIALS

DEAL_II_NAMESPACE_OPEN
namespace SUNDIALS
{
  namespace internal
  {
    /**
     * SUNDIALS provides different macros for getting the local length of a
     * vector for serial and parallel vectors (as well as various parallel
     * vectors that are not yet supported by deal.II). This function provides
     * a generic interface to both and does a (checked) conversion from long
     * int (the type SUNDIALS uses for lengths) to std::size_t.
     */
    inline
    std::size_t
    N_Vector_length(const N_Vector &vec)
    {
      const N_Vector_ID id = N_VGetVectorID(vec);
      long int length = -1;
      switch (id)
        {
        case SUNDIALS_NVEC_SERIAL:
        {
          length = NV_LENGTH_S(vec);
          break;
        }
        case SUNDIALS_NVEC_PARALLEL:
        {
          length = NV_LOCLENGTH_P(vec);
          break;
        }
        default:
          Assert(false, ExcNotImplemented());
        }

      Assert(length >= 0, ExcInternalError());
      return static_cast<std::size_t>(length);
    }

#ifdef DEAL_II_WITH_MPI

#ifdef DEAL_II_WITH_TRILINOS

    void copy(TrilinosWrappers::MPI::Vector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const TrilinosWrappers::MPI::Vector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

    void copy(TrilinosWrappers::MPI::BlockVector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const TrilinosWrappers::MPI::BlockVector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

#endif //DEAL_II_WITH_TRILINOS

#ifdef DEAL_II_WITH_PETSC

    void copy(PETScWrappers::MPI::Vector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const PETScWrappers::MPI::Vector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

    void copy(PETScWrappers::MPI::BlockVector &dst, const N_Vector &src)
    {
      IndexSet is = dst.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(src));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          dst[is.nth_index_in_set(i)] = NV_Ith_P(src, i);
        }
      dst.compress(VectorOperation::insert);
    }

    void copy(N_Vector &dst, const PETScWrappers::MPI::BlockVector &src)
    {
      IndexSet is = src.locally_owned_elements();
      AssertDimension(is.n_elements(), N_Vector_length(dst));
      for (unsigned int i=0; i<is.n_elements(); ++i)
        {
          NV_Ith_P(dst, i) = src[is.nth_index_in_set(i)];
        }
    }

#endif //DEAL_II_WITH_PETSC

#endif //mpi

    void copy(BlockVector<double> &dst, const N_Vector &src)
    {
      AssertDimension(N_Vector_length(src), dst.size());
      for (unsigned int i=0; i<dst.size(); ++i)
        {
          dst[i] = NV_Ith_S(src, i);
        }
    }

    void copy(N_Vector &dst, const BlockVector<double> &src)
    {
      AssertDimension(N_Vector_length(dst), src.size());
      for (unsigned int i=0; i<src.size(); ++i)
        {
          NV_Ith_S(dst, i) = src[i];
        }
    }

    void copy(Vector<double> &dst, const N_Vector &src)
    {
      AssertDimension(N_Vector_length(src), dst.size());
      for (unsigned int i=0; i<dst.size(); ++i)
        {
          dst[i] = NV_Ith_S(src, i);
        }
    }

    void copy(N_Vector &dst, const Vector<double> &src)
    {
      AssertDimension(N_Vector_length(dst), src.size());
      for (unsigned int i=0; i<src.size(); ++i)
        {
          NV_Ith_S(dst, i) = src[i];
        }
    }
  }
}
DEAL_II_NAMESPACE_CLOSE

#endif
<|endoftext|>


<commit_before><commit_msg>Separate Best AI stats from game results<commit_after><|endoftext|>


<commit_before>/*
 *
 *   NRF24L01+ to Message Protocol gateway
 *   Copyright (C) 2013 Dustin Brewer
 *   License: MIT
 */
#include <algorithm>
#include <unordered_map>
#include <string>
#include <sstream>
#include <vector>
#include <ctime>

#include "csiphash.c"
#include "StringSplit.h"
#include "IMessageProtocol.h"
#include "IRadioNetwork.h"
#include "RF24Node.h"

RF24Node::RF24Node(IRadioNetwork& _network, IMessageProtocol& _msg_proto, char _key[16]) :
  msg_proto(_msg_proto), network(_network), key(_key) { }

void RF24Node::begin(void) {
    this->msg_proto.set_on_message_callback([this](std::string subject, std::string body) { this->handle_receive_message(subject, body); });
    this->msg_proto.begin();

    this->network.begin();
}

void RF24Node::end(void) {
    this->msg_proto.end();
}

void RF24Node::loop(void) {
    this->network.update();
    while (this->network.available()) {
        RF24NetworkHeader header;
        this->network.peek(header);

        switch (header.type) {
            case PKT_POWER:
                this->handle_receive_power(header);
                break;
            case PKT_TEMP:
                this->handle_receive_temp(header);
                break;
            case PKT_HUMID:
                this->handle_receive_humidity(header);
                break;
            case PKT_SWITCH:
                this->handle_receive_switch(header);
                break;
            case PKT_MOISTURE:
                this->handle_receive_moisture(header);
                break;
            case PKT_ENERGY:
                this->handle_receive_energy(header);
                break;
            case PKT_RGB:
                // Not Implemented
                break;
            case PKT_TIME:
                this->handle_receive_timesync(header);
                break;
            case PKT_CHALLENGE:
                this->handle_receive_challenge(header);
                break;
            default:
                break;
        }
    }
    this->msg_proto.loop();
}

bool RF24Node::write(RF24NetworkHeader& header,const void* message, size_t len) {
    const uint8_t max_retries = 1;
    bool ok = false;

    uint8_t retries = max_retries;
    while (!ok && retries-- > 0) {
        ok = this->network.write(header, message, len);
    }
    return ok;
}

/**
 * Upon receiving a command via the C++/Python IPC topic, queue the message
 */
void RF24Node::handle_receive_message(std::string subject, std::string body) {
    if (this->debug) printf("Received '%s' via topic '%s' from MQTT\n", subject.c_str(), body.c_str());

    std::vector<std::string> elements = split(subject, '/');
    uint16_t to_node = std::stoul("0" + elements[3], nullptr, 0);
    uint8_t type_command = std::stoi(elements[4], nullptr);
    uint8_t type = type_command % 64;

    if (type_command < 64) {
        // Asking for sensor data is unsupported
        return;
    }

    this->queued_payloads[to_node][type] = body;

    if (this->debug) printf("Queuing: '%s' for node 0%o, payload type %d\n", body.c_str(), to_node, type);

    pkt_challenge_t payload;
    payload.type = type;
    RF24NetworkHeader header(to_node, PKT_CHALLENGE);
    this->write(header, &payload, sizeof(payload));
}

/*
 * Upon receiving a header specifying a challenge response, store the challenge
 */
void RF24Node::handle_receive_challenge(RF24NetworkHeader& header) {
    if (this->debug) printf("Handling challenge request for node 0%o.\n", header.from_node);

    // Read the challenge request response
    pkt_challenge_t payload;
    this->network.read(header, &payload, sizeof(payload));

    switch (payload.type) {
        case PKT_SWITCH:
            this->handle_send_switch(header.from_node, this->queued_payloads[header.from_node][payload.type], payload.challenge);
            break;
        case PKT_RGB:
            // Not implemented
            break;
    }

}

/*
 * Upon receiving a header specifying a timesync request, send the time to the node
 */
void RF24Node::handle_receive_timesync(RF24NetworkHeader& header) {
    if (this->debug) printf("Handling timesync request for node 0%o.\n", header.from_node);

    // Read in the packet; not used
    this->network.read(header, nullptr, 0);

    // Set the current timestamp
    pkt_time_t t = { time(0) };

    // Send the packet (timestamp) to the desired node
    RF24NetworkHeader new_header(header.from_node, PKT_TIME);
    this->write(new_header, &t, sizeof(t));
}

/*
 * Publish temps on MQTT
 */
void RF24Node::handle_receive_temp(RF24NetworkHeader& header) {
    pkt_temp_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << (double)(payload.temp / 10.0);

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Temp: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish humidity on MQTT
 */
void RF24Node::handle_receive_humidity(RF24NetworkHeader& header) {
    pkt_humid_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << ((double)(payload.humidity / 10.0));

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Humidity: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish power on MQTT
 */
void RF24Node::handle_receive_power(RF24NetworkHeader& header) {
    pkt_power_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.battery << "|" << payload.solar << "|" << payload.vcc << "|" << payload.vs;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Power: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish moisture on MQTT
 */
void RF24Node::handle_receive_moisture(RF24NetworkHeader& header) {
    pkt_moisture_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << payload.moisture;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Moisture: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish energy on MQTT
 */
void RF24Node::handle_receive_energy(RF24NetworkHeader& header) {
    pkt_energy_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << payload.energy;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Energy: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish switch on MQTT
 */
void RF24Node::handle_receive_switch(RF24NetworkHeader& header) {
    pkt_switch_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << payload.state << "|" << payload.timer;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Switch: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

void RF24Node::handle_send_switch(uint16_t node, std::string queued_payload, time_t challenge) {
    std::vector<std::string> elements = split(queued_payload.c_str(), '|');

    pkt_switch_t payload;
    payload.id = std::stoi(elements[0], nullptr, 0);
    payload.state = std::stoi(elements[1], nullptr, 0);
    payload.timer = std::stoi(elements[2], nullptr, 0);
    this->generate_siphash(challenge, payload.hash);

    if (this->debug) {
        printf("Republishing Switch Command: 0%o:%s\n", node, queued_payload.c_str());
        printf("-- payload: %d, %d, %d\n", payload.id, payload.state, payload.timer);
        printf("-- using siphashed (%d, %d, %d, %d, %d, %d, %d, %d) challenge %lu\n",
        payload.hash[0], payload.hash[1], payload.hash[2], payload.hash[3], payload.hash[4],
        payload.hash[5], payload.hash[6], payload.hash[7], challenge);
    }

    // Send a challenge request to the appropriate node
    RF24NetworkHeader header(node, PKT_SWITCH);
    this->write(header, &payload, sizeof(payload));
}

std::string RF24Node::generate_msg_proto_subject(RF24NetworkHeader& header) {
    char from_node_oct[5];
    sprintf(from_node_oct, "%o", header.from_node);

    std::stringstream s_topic;
    s_topic << "/sensornet/out/" << from_node_oct << "/" << std::to_string(header.type);

    return s_topic.str();
}

void RF24Node::generate_siphash(time_t challenge, unsigned char (&hash)[8]) {
    // Convert the challenge into a byte array
    char challenge_array[4];
    for(int i = 0; i <= 3; i++) {
        challenge_array[i] = (challenge >> (8 * i) ) & 0xFF;
    }

    // Generate the hash
    uint64_t siphash = siphash24(challenge_array, sizeof(challenge_array), this->key);

    // Convert the siphash into a byte array
    for(unsigned int i = 0; i < sizeof(hash); i++) {
        hash[i] = (siphash >> (8 * i) ) & 0xFF;
    }
}
<commit_msg>Handle Challenge improvements<commit_after>/*
 *
 *   NRF24L01+ to Message Protocol gateway
 *   Copyright (C) 2013 Dustin Brewer
 *   License: MIT
 */
#include <algorithm>
#include <unordered_map>
#include <string>
#include <sstream>
#include <vector>
#include <ctime>

#include "csiphash.c"
#include "StringSplit.h"
#include "IMessageProtocol.h"
#include "IRadioNetwork.h"
#include "RF24Node.h"

RF24Node::RF24Node(IRadioNetwork& _network, IMessageProtocol& _msg_proto, char _key[16]) :
  msg_proto(_msg_proto), network(_network), key(_key) { }

void RF24Node::begin(void) {
    this->msg_proto.set_on_message_callback([this](std::string subject, std::string body) { this->handle_receive_message(subject, body); });
    this->msg_proto.begin();

    this->network.begin();
}

void RF24Node::end(void) {
    this->msg_proto.end();
}

void RF24Node::loop(void) {
    this->network.update();
    while (this->network.available()) {
        RF24NetworkHeader header;
        this->network.peek(header);

        switch (header.type) {
            case PKT_POWER:
                this->handle_receive_power(header);
                break;
            case PKT_TEMP:
                this->handle_receive_temp(header);
                break;
            case PKT_HUMID:
                this->handle_receive_humidity(header);
                break;
            case PKT_SWITCH:
                this->handle_receive_switch(header);
                break;
            case PKT_MOISTURE:
                this->handle_receive_moisture(header);
                break;
            case PKT_ENERGY:
                this->handle_receive_energy(header);
                break;
            case PKT_RGB:
                // Not Implemented
                break;
            case PKT_TIME:
                this->handle_receive_timesync(header);
                break;
            case PKT_CHALLENGE:
                this->handle_receive_challenge(header);
                break;
            default:
                break;
        }
    }
    this->msg_proto.loop();
}

bool RF24Node::write(RF24NetworkHeader& header,const void* message, size_t len) {
    const uint8_t max_retries = 1;
    bool ok = false;

    uint8_t retries = max_retries;
    while (!ok && retries-- > 0) {
        ok = this->network.write(header, message, len);
    }
    return ok;
}

/**
 * Upon receiving a command via the C++/Python IPC topic, queue the message
 */
void RF24Node::handle_receive_message(std::string subject, std::string body) {
    if (this->debug) printf("Received '%s' via topic '%s' from MQTT\n", subject.c_str(), body.c_str());

    std::vector<std::string> elements = split(subject, '/');
    uint16_t to_node = std::stoul("0" + elements[3], nullptr, 0);
    uint8_t type_command = std::stoi(elements[4], nullptr);
    uint8_t type = type_command % 64;

    if (type_command < 64) {
        // Asking for sensor data is unsupported
        return;
    }

    this->queued_payloads[to_node][type] = body;

    if (this->debug) printf("Queuing: '%s' for node 0%o, payload type %d\n", body.c_str(), to_node, type);

    pkt_challenge_t payload;
    payload.type = type;
    RF24NetworkHeader header(to_node, PKT_CHALLENGE);
    this->write(header, &payload, sizeof(payload));
}

/*
 * Upon receiving a header specifying a challenge response, store the challenge
 */
void RF24Node::handle_receive_challenge(RF24NetworkHeader& header) {
    if (this->debug) printf("Handling challenge request for node 0%o.\n", header.from_node);

    // Read the challenge request response
    pkt_challenge_t payload;
    this->network.read(header, &payload, sizeof(payload));

    if (this->queued_payloads.find(header.from_node) == this->queued_payloads.end() ||
        this->queued_payloads[header.from_node].find(payload.type) == this->queued_payloads[header.from_node].end()) {
        if (this->debug) printf("No queued payload for for node 0%o of payload type %d.\n", header.from_node, payload.type);
        return;
    }

    switch (payload.type) {
        case PKT_SWITCH:
            this->handle_send_switch(header.from_node, this->queued_payloads[header.from_node][payload.type], payload.challenge);
            break;
        case PKT_RGB:
            // Not implemented
            break;
    }

    this->queued_payloads[header.from_node].erase(payload.type);
}

/*
 * Upon receiving a header specifying a timesync request, send the time to the node
 */
void RF24Node::handle_receive_timesync(RF24NetworkHeader& header) {
    if (this->debug) printf("Handling timesync request for node 0%o.\n", header.from_node);

    // Read in the packet; not used
    this->network.read(header, nullptr, 0);

    // Set the current timestamp
    pkt_time_t t = { time(0) };

    // Send the packet (timestamp) to the desired node
    RF24NetworkHeader new_header(header.from_node, PKT_TIME);
    this->write(new_header, &t, sizeof(t));
}

/*
 * Publish temps on MQTT
 */
void RF24Node::handle_receive_temp(RF24NetworkHeader& header) {
    pkt_temp_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << (double)(payload.temp / 10.0);

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Temp: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish humidity on MQTT
 */
void RF24Node::handle_receive_humidity(RF24NetworkHeader& header) {
    pkt_humid_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << ((double)(payload.humidity / 10.0));

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Humidity: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish power on MQTT
 */
void RF24Node::handle_receive_power(RF24NetworkHeader& header) {
    pkt_power_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.battery << "|" << payload.solar << "|" << payload.vcc << "|" << payload.vs;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Power: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish moisture on MQTT
 */
void RF24Node::handle_receive_moisture(RF24NetworkHeader& header) {
    pkt_moisture_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << payload.moisture;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Moisture: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish energy on MQTT
 */
void RF24Node::handle_receive_energy(RF24NetworkHeader& header) {
    pkt_energy_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << payload.energy;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Energy: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

/*
 * Publish switch on MQTT
 */
void RF24Node::handle_receive_switch(RF24NetworkHeader& header) {
    pkt_switch_t payload;
    this->network.read(header, &payload, sizeof(payload));

    std::stringstream s_value;
    s_value << payload.id << "|" << payload.state << "|" << payload.timer;

    std::string topic = this->generate_msg_proto_subject(header);
    std::string value = s_value.str();

    if (this->debug) printf("Republishing Switch: %s:%s\n", topic.c_str(), value.c_str());
    this->msg_proto.send_message(topic, value);
}

void RF24Node::handle_send_switch(uint16_t node, std::string queued_payload, time_t challenge) {
    std::vector<std::string> elements = split(queued_payload.c_str(), '|');

    pkt_switch_t payload;
    payload.id = std::stoi(elements[0], nullptr, 0);
    payload.state = std::stoi(elements[1], nullptr, 0);
    payload.timer = std::stoi(elements[2], nullptr, 0);
    this->generate_siphash(challenge, payload.hash);

    if (this->debug) {
        printf("Republishing Switch Command: 0%o:%s\n", node, queued_payload.c_str());
        printf("-- payload: %d, %d, %d\n", payload.id, payload.state, payload.timer);
        printf("-- using siphashed (%d, %d, %d, %d, %d, %d, %d, %d) challenge %lu\n",
        payload.hash[0], payload.hash[1], payload.hash[2], payload.hash[3], payload.hash[4],
        payload.hash[5], payload.hash[6], payload.hash[7], challenge);
    }

    // Send a challenge request to the appropriate node
    RF24NetworkHeader header(node, PKT_SWITCH);
    this->write(header, &payload, sizeof(payload));
}

std::string RF24Node::generate_msg_proto_subject(RF24NetworkHeader& header) {
    char from_node_oct[5];
    sprintf(from_node_oct, "%o", header.from_node);

    std::stringstream s_topic;
    s_topic << "/sensornet/out/" << from_node_oct << "/" << std::to_string(header.type);

    return s_topic.str();
}

void RF24Node::generate_siphash(time_t challenge, unsigned char (&hash)[8]) {
    // Convert the challenge into a byte array
    char challenge_array[4];
    for(int i = 0; i <= 3; i++) {
        challenge_array[i] = (challenge >> (8 * i) ) & 0xFF;
    }

    // Generate the hash
    uint64_t siphash = siphash24(challenge_array, sizeof(challenge_array), this->key);

    // Convert the siphash into a byte array
    for(unsigned int i = 0; i < sizeof(hash); i++) {
        hash[i] = (siphash >> (8 * i) ) & 0xFF;
    }
}
<|endoftext|>