<commit_before>/* vi:set ts=8 sts=8 sw=8 noet:
 *
 * PMS	<<Practical Music Search>>
 * Copyright (C) 2006-2015  Kim Tore Jensen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * options.cpp - the options class
 *
 */

#include "options.h"
#include "color.h"
#include "i18n.h"
#include "pms.h"

extern Pms * pms;

/**
 * Macros for easy creation of options
 */
#define NEW_OPTION(CLASS, TYPE, GROUP, NAME) option_index.push_back(new CLASS(this, TYPE, GROUP, #NAME, &NAME))
#define NEW_BOOL(NAME) NEW_OPTION(Option, OPT_BOOL, OPT_GROUP_NONE, NAME)
#define NEW_BOOL_GROUPED(NAME, GROUP) NEW_OPTION(Option, OPT_BOOL, GROUP, NAME)
#define NEW_LONG(NAME) NEW_OPTION(Option, OPT_LONG, OPT_GROUP_NONE, NAME)
#define NEW_LONG_GROUPED(NAME, GROUP) NEW_OPTION(Option, OPT_LONG, GROUP, NAME)
#define NEW_STRING(NAME) NEW_OPTION(Option, OPT_STRING, OPT_GROUP_NONE, NAME)
#define NEW_STRING_GROUPED(NAME, GROUP) NEW_OPTION(Option, OPT_STRING, GROUP, NAME)
#define NEW_TAG_LIST(NAME, GROUP) NEW_OPTION(TagListOption, OPT_STRING, OPT_GROUP_NONE, NAME)
#define NEW_TOPBAR(NAME, GROUP) NEW_OPTION(TopbarOption, OPT_STRING, GROUP, NAME)
#define NEW_SCROLL_MODE(NAME, GROUP) NEW_OPTION(ScrollModeOption, OPT_STRING, GROUP, NAME)

Option::Option(Options * parent_, option_t type_, uint32_t groups_, const char * name_, void * pointer_)
{
	parent = parent_;
	type = type_;
	groups = groups_;
	strncpy(name, name_, 31);
	name[31] = '\0';
	pointer = pointer_;
}

bool *
Option::as_bool_ptr()
{
	return static_cast<bool *>(pointer);
}

long *
Option::as_long_ptr()
{
	return static_cast<long *>(pointer);
}

string *
Option::as_string_ptr()
{
	return static_cast<string *>(pointer);
}

bool
Option::set(void * value)
{
	switch(type) {
		case OPT_BOOL:
			*(static_cast<bool *>(pointer)) = *(static_cast<bool *>(value));
			break;
		case OPT_LONG:
			*(static_cast<long *>(pointer)) = *(static_cast<long *>(value));
			break;
		case OPT_STRING:
			*(static_cast<string *>(pointer)) = *(static_cast<string *>(value));
			break;
		default:
			abort();
	};

	parent->add_changed_flags(groups);

	return true;
}

bool
TagListOption::set(void * value)
{
	vector<string> *		v;
	vector<string>::iterator	iter;
	string *			s;

	s = static_cast<string *>(value);

	if (!s->size()) {
		return false;
	}

	v = Pms::splitstr(*s, " ");

	iter = v->begin();

	while (iter != v->end()) {
		if (pms->fieldtypes->lookup(*iter) == -1) {
			delete v;
			return false;
		}
		++iter;
	}

	delete v;

	return Option::set(value);
}

void
TopbarOption::clear()
{
	vector<Topbarline *>::const_iterator	iter;

	iter = topbar.begin();
	while (iter != topbar.end()) {
		delete *iter;
		++iter;
	}

	topbar.clear();
}

bool
TopbarOption::parse(const string * value)
{
	uint32_t		position = 0;
	bool			escaped = false;
	Topbarline *		line = NULL;
	string			buffer = "";
	string::const_iterator	iter;

	clear();
	iter = value->begin();

	while (iter != value->end()) {
		if (!line) {
			line = new Topbarline();
			position = 0;
		}
		if (!escaped) {
			if (*iter == '\\') {
				escaped = true;
			} else {
				buffer += *iter;
			}
		} else {
			if (*iter == 't' || *iter == 'n') {
				line->strings[position] = buffer;
				buffer.clear();
			}
			if (*iter == 'n') {
				topbar.push_back(line);
				line = NULL;
			} else if (*iter == 't') {
				if (++position > 2) {
					break;
				}
			} else {
				break;
			}
			escaped = false;
		}
		++iter;
	}

	if (line) {
		line->strings[position] = buffer;
		topbar.push_back(line);
	}

	if (iter != value->end()) {
		clear();
		return false;
	}

	return true;
}

bool
TopbarOption::set(void * value)
{
	string * s;

	s = static_cast<string *>(value);

	if (!parse(s)) {
		return false;
	}

	parent->topbar_lines = topbar;
	topbar.clear();

	return Option::set(value);
}

bool
ScrollModeOption::set(void * value)
{
	string * s = static_cast<string *>(value);

	if (*s == "normal") {
		parent->scroll_mode = SCROLL_NORMAL;
	} else if (*s == "center" || *s == "centered" || *s == "centre" || *s == "centred") {
		parent->scroll_mode = SCROLL_CENTERED;
	} else {
		return false;
	}

	return Option::set(value);
}

Options::Options()
{
	colors = NULL;
	changed_flags = 0;

	NEW_BOOL(addtoreturns);
	NEW_BOOL_GROUPED(columnborders, OPT_GROUP_DISPLAY);
	NEW_BOOL(debug);
	NEW_BOOL(followcursor);
	NEW_BOOL(followplayback);
	NEW_BOOL(followwindow);
	NEW_BOOL_GROUPED(ignorecase, OPT_GROUP_SORT);
	NEW_BOOL(mouse);
	NEW_BOOL(nextafteraction);
	NEW_BOOL(regexsearch);
	NEW_BOOL_GROUPED(topbarborders, OPT_GROUP_DISPLAY);
	NEW_BOOL_GROUPED(topbarvisible, OPT_GROUP_DISPLAY);

	NEW_LONG(crossfade);
	NEW_LONG_GROUPED(mpd_timeout, OPT_GROUP_CONNECTION);
	NEW_LONG(msg_buffer_size);
	NEW_LONG(nextinterval);
	NEW_LONG_GROUPED(port, OPT_GROUP_CONNECTION);
	NEW_LONG(reconnectdelay);
	NEW_LONG(resetstatus);
	NEW_LONG_GROUPED(scrolloff, OPT_GROUP_DISPLAY);

	NEW_TAG_LIST(columns, OPT_GROUP_COLUMNS);
	NEW_STRING_GROUPED(host, OPT_GROUP_CONNECTION);
	NEW_STRING(libraryroot);
	NEW_STRING(onplaylistfinish);
	NEW_STRING(password);
	NEW_SCROLL_MODE(scroll, OPT_GROUP_DISPLAY);
	NEW_TAG_LIST(sort, OPT_GROUP_SORT);
	NEW_STRING(startuplist);
	NEW_STRING_GROUPED(status_pause, OPT_GROUP_DISPLAY);
	NEW_STRING_GROUPED(status_play, OPT_GROUP_DISPLAY);
	NEW_STRING_GROUPED(status_stop, OPT_GROUP_DISPLAY);
	NEW_STRING_GROUPED(status_unknown, OPT_GROUP_DISPLAY);
	NEW_TOPBAR(topbar, OPT_GROUP_DISPLAY);
	NEW_STRING(xtermtitle);

	reset();
}

Options::~Options()
{
	vector<Option *>::iterator iter;

	iter = option_index.begin();
	while (iter != option_index.end()) {
		delete *iter;
		++iter;
	}
}

void
Options::reset()
{
	TopbarOption * topbar_option;
	ScrollModeOption * scroll_option;

	if (colors != NULL) {
		delete colors;
	}

	colors = new Colortable();

	addtoreturns = false;
	columnborders = false;
	columns = "artist track title album length";
	crossfade = 5;
	debug = false;
	followcursor = false;
	followplayback = false;
	followwindow = false;
	host = "localhost";
	ignorecase = true;
	libraryroot = "";
	mouse = false;
	mpd_timeout = 2;
	msg_buffer_size = 1024;
	nextafteraction = true;
	nextinterval = 5;
	onplaylistfinish = "";
	password = "";
	port = 6600;
	reconnectdelay = 10;
	regexsearch = false;
	resetstatus = 3;
	scroll = "normal";
	scrolloff = 0;
	sort = "track disc album date albumartistsort";
	startuplist = "playlist";
	status_pause = Pms::unicode() ? "‖" : "||";
	status_play = Pms::unicode() ? "▶" : "|>";
	status_stop = Pms::unicode() ? "■" : "[]";
	status_unknown = Pms::unicode() ? "?" : "??";
	topbar = "\\n"
		"%volume%%% Mode: %muteshort%%consumeshort%%repeatshort%%randomshort%%singleshort%%ifcursong% %playstate% %time_elapsed% / %time_remaining%%endif%\\t"
		"%ifcursong%%artist% - %title% on %album% from %date%%else%Not playing anything%endif%\\t"
		"Queue has %livequeuesize%\\n"
		"\\t\\t%listsize%\\n"
		"%progressbar%";
	topbarborders = false;
	topbarvisible = true;
	xtermtitle = "PMS: %playstate%%ifcursong% %artist% – %title%%endif%";

	/* Derive scroll mode */
	scroll_option = dynamic_cast<ScrollModeOption *>(lookup_option("scroll"));
	scroll_option->set(&scroll);

	/* Set up default top bar values */
	topbar_option = dynamic_cast<TopbarOption *>(lookup_option("topbar"));
	topbar_option->set(&topbar);
}

Option *
Options::lookup_option(const char * varname)
{
	vector<Option *>::const_iterator iter;

	iter = option_index.begin();

	while (iter != option_index.end()) {
		if (!strcmp((*iter)->name, varname)) {
			return *iter;
		}
		++iter;
	}

	return NULL;
}

uint32_t
Options::get_changed_flags()
{
	return changed_flags;
}

uint32_t
Options::set_changed_flags(uint32_t flags)
{
	changed_flags = flags;
	return get_changed_flags();
}

uint32_t
Options::add_changed_flags(uint32_t flags)
{
	changed_flags |= flags;
	return get_changed_flags();
}
<commit_msg>Fix default startuplist option to Queue instead of playlist<commit_after>/* vi:set ts=8 sts=8 sw=8 noet:
 *
 * PMS	<<Practical Music Search>>
 * Copyright (C) 2006-2015  Kim Tore Jensen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * options.cpp - the options class
 *
 */

#include "options.h"
#include "color.h"
#include "i18n.h"
#include "pms.h"

extern Pms * pms;

/**
 * Macros for easy creation of options
 */
#define NEW_OPTION(CLASS, TYPE, GROUP, NAME) option_index.push_back(new CLASS(this, TYPE, GROUP, #NAME, &NAME))
#define NEW_BOOL(NAME) NEW_OPTION(Option, OPT_BOOL, OPT_GROUP_NONE, NAME)
#define NEW_BOOL_GROUPED(NAME, GROUP) NEW_OPTION(Option, OPT_BOOL, GROUP, NAME)
#define NEW_LONG(NAME) NEW_OPTION(Option, OPT_LONG, OPT_GROUP_NONE, NAME)
#define NEW_LONG_GROUPED(NAME, GROUP) NEW_OPTION(Option, OPT_LONG, GROUP, NAME)
#define NEW_STRING(NAME) NEW_OPTION(Option, OPT_STRING, OPT_GROUP_NONE, NAME)
#define NEW_STRING_GROUPED(NAME, GROUP) NEW_OPTION(Option, OPT_STRING, GROUP, NAME)
#define NEW_TAG_LIST(NAME, GROUP) NEW_OPTION(TagListOption, OPT_STRING, OPT_GROUP_NONE, NAME)
#define NEW_TOPBAR(NAME, GROUP) NEW_OPTION(TopbarOption, OPT_STRING, GROUP, NAME)
#define NEW_SCROLL_MODE(NAME, GROUP) NEW_OPTION(ScrollModeOption, OPT_STRING, GROUP, NAME)

Option::Option(Options * parent_, option_t type_, uint32_t groups_, const char * name_, void * pointer_)
{
	parent = parent_;
	type = type_;
	groups = groups_;
	strncpy(name, name_, 31);
	name[31] = '\0';
	pointer = pointer_;
}

bool *
Option::as_bool_ptr()
{
	return static_cast<bool *>(pointer);
}

long *
Option::as_long_ptr()
{
	return static_cast<long *>(pointer);
}

string *
Option::as_string_ptr()
{
	return static_cast<string *>(pointer);
}

bool
Option::set(void * value)
{
	switch(type) {
		case OPT_BOOL:
			*(static_cast<bool *>(pointer)) = *(static_cast<bool *>(value));
			break;
		case OPT_LONG:
			*(static_cast<long *>(pointer)) = *(static_cast<long *>(value));
			break;
		case OPT_STRING:
			*(static_cast<string *>(pointer)) = *(static_cast<string *>(value));
			break;
		default:
			abort();
	};

	parent->add_changed_flags(groups);

	return true;
}

bool
TagListOption::set(void * value)
{
	vector<string> *		v;
	vector<string>::iterator	iter;
	string *			s;

	s = static_cast<string *>(value);

	if (!s->size()) {
		return false;
	}

	v = Pms::splitstr(*s, " ");

	iter = v->begin();

	while (iter != v->end()) {
		if (pms->fieldtypes->lookup(*iter) == -1) {
			delete v;
			return false;
		}
		++iter;
	}

	delete v;

	return Option::set(value);
}

void
TopbarOption::clear()
{
	vector<Topbarline *>::const_iterator	iter;

	iter = topbar.begin();
	while (iter != topbar.end()) {
		delete *iter;
		++iter;
	}

	topbar.clear();
}

bool
TopbarOption::parse(const string * value)
{
	uint32_t		position = 0;
	bool			escaped = false;
	Topbarline *		line = NULL;
	string			buffer = "";
	string::const_iterator	iter;

	clear();
	iter = value->begin();

	while (iter != value->end()) {
		if (!line) {
			line = new Topbarline();
			position = 0;
		}
		if (!escaped) {
			if (*iter == '\\') {
				escaped = true;
			} else {
				buffer += *iter;
			}
		} else {
			if (*iter == 't' || *iter == 'n') {
				line->strings[position] = buffer;
				buffer.clear();
			}
			if (*iter == 'n') {
				topbar.push_back(line);
				line = NULL;
			} else if (*iter == 't') {
				if (++position > 2) {
					break;
				}
			} else {
				break;
			}
			escaped = false;
		}
		++iter;
	}

	if (line) {
		line->strings[position] = buffer;
		topbar.push_back(line);
	}

	if (iter != value->end()) {
		clear();
		return false;
	}

	return true;
}

bool
TopbarOption::set(void * value)
{
	string * s;

	s = static_cast<string *>(value);

	if (!parse(s)) {
		return false;
	}

	parent->topbar_lines = topbar;
	topbar.clear();

	return Option::set(value);
}

bool
ScrollModeOption::set(void * value)
{
	string * s = static_cast<string *>(value);

	if (*s == "normal") {
		parent->scroll_mode = SCROLL_NORMAL;
	} else if (*s == "center" || *s == "centered" || *s == "centre" || *s == "centred") {
		parent->scroll_mode = SCROLL_CENTERED;
	} else {
		return false;
	}

	return Option::set(value);
}

Options::Options()
{
	colors = NULL;
	changed_flags = 0;

	NEW_BOOL(addtoreturns);
	NEW_BOOL_GROUPED(columnborders, OPT_GROUP_DISPLAY);
	NEW_BOOL(debug);
	NEW_BOOL(followcursor);
	NEW_BOOL(followplayback);
	NEW_BOOL(followwindow);
	NEW_BOOL_GROUPED(ignorecase, OPT_GROUP_SORT);
	NEW_BOOL(mouse);
	NEW_BOOL(nextafteraction);
	NEW_BOOL(regexsearch);
	NEW_BOOL_GROUPED(topbarborders, OPT_GROUP_DISPLAY);
	NEW_BOOL_GROUPED(topbarvisible, OPT_GROUP_DISPLAY);

	NEW_LONG(crossfade);
	NEW_LONG_GROUPED(mpd_timeout, OPT_GROUP_CONNECTION);
	NEW_LONG(msg_buffer_size);
	NEW_LONG(nextinterval);
	NEW_LONG_GROUPED(port, OPT_GROUP_CONNECTION);
	NEW_LONG(reconnectdelay);
	NEW_LONG(resetstatus);
	NEW_LONG_GROUPED(scrolloff, OPT_GROUP_DISPLAY);

	NEW_TAG_LIST(columns, OPT_GROUP_COLUMNS);
	NEW_STRING_GROUPED(host, OPT_GROUP_CONNECTION);
	NEW_STRING(libraryroot);
	NEW_STRING(onplaylistfinish);
	NEW_STRING(password);
	NEW_SCROLL_MODE(scroll, OPT_GROUP_DISPLAY);
	NEW_TAG_LIST(sort, OPT_GROUP_SORT);
	NEW_STRING(startuplist);
	NEW_STRING_GROUPED(status_pause, OPT_GROUP_DISPLAY);
	NEW_STRING_GROUPED(status_play, OPT_GROUP_DISPLAY);
	NEW_STRING_GROUPED(status_stop, OPT_GROUP_DISPLAY);
	NEW_STRING_GROUPED(status_unknown, OPT_GROUP_DISPLAY);
	NEW_TOPBAR(topbar, OPT_GROUP_DISPLAY);
	NEW_STRING(xtermtitle);

	reset();
}

Options::~Options()
{
	vector<Option *>::iterator iter;

	iter = option_index.begin();
	while (iter != option_index.end()) {
		delete *iter;
		++iter;
	}
}

void
Options::reset()
{
	TopbarOption * topbar_option;
	ScrollModeOption * scroll_option;

	if (colors != NULL) {
		delete colors;
	}

	colors = new Colortable();

	addtoreturns = false;
	columnborders = false;
	columns = "artist track title album length";
	crossfade = 5;
	debug = false;
	followcursor = false;
	followplayback = false;
	followwindow = false;
	host = "localhost";
	ignorecase = true;
	libraryroot = "";
	mouse = false;
	mpd_timeout = 2;
	msg_buffer_size = 1024;
	nextafteraction = true;
	nextinterval = 5;
	onplaylistfinish = "";
	password = "";
	port = 6600;
	reconnectdelay = 10;
	regexsearch = false;
	resetstatus = 3;
	scroll = "normal";
	scrolloff = 0;
	sort = "track disc album date albumartistsort";
	startuplist = "Queue";
	status_pause = Pms::unicode() ? "‖" : "||";
	status_play = Pms::unicode() ? "▶" : "|>";
	status_stop = Pms::unicode() ? "■" : "[]";
	status_unknown = Pms::unicode() ? "?" : "??";
	topbar = "\\n"
		"%volume%%% Mode: %muteshort%%consumeshort%%repeatshort%%randomshort%%singleshort%%ifcursong% %playstate% %time_elapsed% / %time_remaining%%endif%\\t"
		"%ifcursong%%artist% - %title% on %album% from %date%%else%Not playing anything%endif%\\t"
		"Queue has %livequeuesize%\\n"
		"\\t\\t%listsize%\\n"
		"%progressbar%";
	topbarborders = false;
	topbarvisible = true;
	xtermtitle = "PMS: %playstate%%ifcursong% %artist% – %title%%endif%";

	/* Derive scroll mode */
	scroll_option = dynamic_cast<ScrollModeOption *>(lookup_option("scroll"));
	scroll_option->set(&scroll);

	/* Set up default top bar values */
	topbar_option = dynamic_cast<TopbarOption *>(lookup_option("topbar"));
	topbar_option->set(&topbar);
}

Option *
Options::lookup_option(const char * varname)
{
	vector<Option *>::const_iterator iter;

	iter = option_index.begin();

	while (iter != option_index.end()) {
		if (!strcmp((*iter)->name, varname)) {
			return *iter;
		}
		++iter;
	}

	return NULL;
}

uint32_t
Options::get_changed_flags()
{
	return changed_flags;
}

uint32_t
Options::set_changed_flags(uint32_t flags)
{
	changed_flags = flags;
	return get_changed_flags();
}

uint32_t
Options::add_changed_flags(uint32_t flags)
{
	changed_flags |= flags;
	return get_changed_flags();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: test_aquacb.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:55:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dtrans.hxx"

#include "aqua_clipboard.hxx"

#ifndef _CPPUHELPER_SERVICEFACTORY_HXX_
#include <cppuhelper/servicefactory.hxx>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDEX_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#include <stdio.h>

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::clipboard;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

Reference< XTransferable > rXTransfRead;

class TestTransferable : public WeakImplHelper2< XClipboardOwner, XTransferable >
{
public:
    TestTransferable();
    virtual Any SAL_CALL getTransferData( const DataFlavor& aFlavor ) throw(UnsupportedFlavorException, IOException, RuntimeException);
    virtual Sequence< DataFlavor > SAL_CALL getTransferDataFlavors() throw(RuntimeException);
    virtual sal_Bool SAL_CALL isDataFlavorSupported( const DataFlavor& aFlavor ) throw(RuntimeException);
    virtual void SAL_CALL lostOwnership( const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans ) throw(RuntimeException);

private:
    Sequence< DataFlavor > m_seqDFlv;
    OUString               m_Data;
};

TestTransferable::TestTransferable() :
    m_seqDFlv( 1 ),
    m_Data( RTL_CONSTASCII_USTRINGPARAM( "This is a test string" ) )
{
    DataFlavor df;

    df.MimeType = OUString::createFromAscii( "text/html" );
    df.DataType = getCppuType( ( Sequence< sal_Int8 >* )0 );

    m_seqDFlv[0] = df;
}

Any SAL_CALL TestTransferable::getTransferData( const DataFlavor& aFlavor )
    throw(UnsupportedFlavorException, IOException, RuntimeException)
{
    Any anyData;

    if ( aFlavor.MimeType == m_seqDFlv[0].MimeType )
    {
        OString aStr( m_Data.getStr(), m_Data.getLength(), 1252 );
        Sequence< sal_Int8 > sOfChars( aStr.getLength() );
        sal_Int32 lenStr = aStr.getLength();

        for ( sal_Int32 i = 0; i < lenStr; ++i )
            sOfChars[i] = aStr[i];

        anyData = makeAny( sOfChars );
    }

    return anyData;
}

Sequence< DataFlavor > SAL_CALL TestTransferable::getTransferDataFlavors()
    throw(RuntimeException)
{
    return m_seqDFlv;
}

sal_Bool SAL_CALL TestTransferable::isDataFlavorSupported( const DataFlavor& aFlavor )
    throw(RuntimeException)
{
    sal_Int32 nLength = m_seqDFlv.getLength();
    sal_Bool bRet     = sal_False;

    for ( sal_Int32 i = 0; i < nLength; ++i )
    {
        if ( m_seqDFlv[i].MimeType == aFlavor.MimeType )
        {
            bRet = sal_True;
            break;
        }
    }

    return bRet;
}

void SAL_CALL TestTransferable::lostOwnership( const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans )
    throw(RuntimeException)
{
}

int SAL_CALL main( int argc, char** argv )
{
    if(argc != 2)
    {
        fprintf( stderr, "usage: %s <my rdb file>\n", argv[0] );
        return 1;
    }

    //-------------------------------------------------
    // get the global service-manager
    //-------------------------------------------------
    OUString rdbName = OUString::createFromAscii( argv[1] );
    Reference< XMultiServiceFactory > g_xFactory( createRegistryServiceFactory( rdbName ) );

    // Print a message if an error occured.
    if ( !g_xFactory.is() )
    {
        OSL_ENSURE(sal_False, "Can't create RegistryServiceFactory");
        return(-1);
    }

    //-------------------------------------------------
    // try to get an Interface to a XFilePicker Service
    //-------------------------------------------------

    Reference< XTransferable > rXTransf( static_cast< XTransferable* >( new TestTransferable ) );

    Reference< XClipboard > xClipboard( g_xFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( AQUA_CLIPBOARD_SERVICE_NAME ) ) ), UNO_QUERY );
    if ( !xClipboard.is() )
    {
        OSL_ENSURE( sal_False, "Error creating FolderPicker Service" );
        return(-1);
    }

    Reference< XTypeProvider > rXTypProv( xClipboard, UNO_QUERY );

    if ( rXTypProv.is() )
    {
        Sequence< Type >     seqType = rXTypProv->getTypes();
        sal_Int32 nLen = seqType.getLength();
        for ( sal_Int32 i = 0; i < nLen; i++ )
        {
            Type nxtType = seqType[i];
        }

        Sequence< sal_Int8 > seqInt8 = rXTypProv->getImplementationId();
    }

    xClipboard->setContents( rXTransf, Reference< XClipboardOwner >( rXTransf, UNO_QUERY )  );

    rXTransfRead = xClipboard->getContents();

    // destroy the transferable explicitly
    rXTransfRead = Reference< XTransferable>();

    // destroy the clipboard
    xClipboard = Reference< XClipboard >();

    //--------------------------------------------------
    // shutdown the service manager
    //--------------------------------------------------

    // Cast factory to XComponent
    Reference< XComponent > xComponent( g_xFactory, UNO_QUERY );

    if ( !xComponent.is() )
        OSL_ENSURE(sal_False, "Error shuting down");

    // Dispose and clear factory
    xComponent->dispose();
    g_xFactory.clear();
    g_xFactory = Reference< XMultiServiceFactory >();

    return 0;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.5.60); FILE MERGED 2008/04/01 15:13:29 thb 1.5.60.3: #i85898# Stripping all external header guards 2008/04/01 12:28:26 thb 1.5.60.2: #i85898# Stripping all external header guards 2008/03/31 13:08:53 rt 1.5.60.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: test_aquacb.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dtrans.hxx"

#include "aqua_clipboard.hxx"
#include <cppuhelper/servicefactory.hxx>
#include <com/sun/star/datatransfer/XTransferable.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#include <com/sun/star/lang/XComponent.hpp>

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#include <rtl/ustring.hxx>
#include <sal/types.h>
#include <osl/diagnose.h>

#include <stdio.h>

using namespace ::rtl;
using namespace ::std;
using namespace ::cppu;
using namespace ::com::sun::star::datatransfer;
using namespace ::com::sun::star::datatransfer::clipboard;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;

Reference< XTransferable > rXTransfRead;

class TestTransferable : public WeakImplHelper2< XClipboardOwner, XTransferable >
{
public:
    TestTransferable();
    virtual Any SAL_CALL getTransferData( const DataFlavor& aFlavor ) throw(UnsupportedFlavorException, IOException, RuntimeException);
    virtual Sequence< DataFlavor > SAL_CALL getTransferDataFlavors() throw(RuntimeException);
    virtual sal_Bool SAL_CALL isDataFlavorSupported( const DataFlavor& aFlavor ) throw(RuntimeException);
    virtual void SAL_CALL lostOwnership( const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans ) throw(RuntimeException);

private:
    Sequence< DataFlavor > m_seqDFlv;
    OUString               m_Data;
};

TestTransferable::TestTransferable() :
    m_seqDFlv( 1 ),
    m_Data( RTL_CONSTASCII_USTRINGPARAM( "This is a test string" ) )
{
    DataFlavor df;

    df.MimeType = OUString::createFromAscii( "text/html" );
    df.DataType = getCppuType( ( Sequence< sal_Int8 >* )0 );

    m_seqDFlv[0] = df;
}

Any SAL_CALL TestTransferable::getTransferData( const DataFlavor& aFlavor )
    throw(UnsupportedFlavorException, IOException, RuntimeException)
{
    Any anyData;

    if ( aFlavor.MimeType == m_seqDFlv[0].MimeType )
    {
        OString aStr( m_Data.getStr(), m_Data.getLength(), 1252 );
        Sequence< sal_Int8 > sOfChars( aStr.getLength() );
        sal_Int32 lenStr = aStr.getLength();

        for ( sal_Int32 i = 0; i < lenStr; ++i )
            sOfChars[i] = aStr[i];

        anyData = makeAny( sOfChars );
    }

    return anyData;
}

Sequence< DataFlavor > SAL_CALL TestTransferable::getTransferDataFlavors()
    throw(RuntimeException)
{
    return m_seqDFlv;
}

sal_Bool SAL_CALL TestTransferable::isDataFlavorSupported( const DataFlavor& aFlavor )
    throw(RuntimeException)
{
    sal_Int32 nLength = m_seqDFlv.getLength();
    sal_Bool bRet     = sal_False;

    for ( sal_Int32 i = 0; i < nLength; ++i )
    {
        if ( m_seqDFlv[i].MimeType == aFlavor.MimeType )
        {
            bRet = sal_True;
            break;
        }
    }

    return bRet;
}

void SAL_CALL TestTransferable::lostOwnership( const Reference< XClipboard >& xClipboard, const Reference< XTransferable >& xTrans )
    throw(RuntimeException)
{
}

int SAL_CALL main( int argc, char** argv )
{
    if(argc != 2)
    {
        fprintf( stderr, "usage: %s <my rdb file>\n", argv[0] );
        return 1;
    }

    //-------------------------------------------------
    // get the global service-manager
    //-------------------------------------------------
    OUString rdbName = OUString::createFromAscii( argv[1] );
    Reference< XMultiServiceFactory > g_xFactory( createRegistryServiceFactory( rdbName ) );

    // Print a message if an error occured.
    if ( !g_xFactory.is() )
    {
        OSL_ENSURE(sal_False, "Can't create RegistryServiceFactory");
        return(-1);
    }

    //-------------------------------------------------
    // try to get an Interface to a XFilePicker Service
    //-------------------------------------------------

    Reference< XTransferable > rXTransf( static_cast< XTransferable* >( new TestTransferable ) );

    Reference< XClipboard > xClipboard( g_xFactory->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( AQUA_CLIPBOARD_SERVICE_NAME ) ) ), UNO_QUERY );
    if ( !xClipboard.is() )
    {
        OSL_ENSURE( sal_False, "Error creating FolderPicker Service" );
        return(-1);
    }

    Reference< XTypeProvider > rXTypProv( xClipboard, UNO_QUERY );

    if ( rXTypProv.is() )
    {
        Sequence< Type >     seqType = rXTypProv->getTypes();
        sal_Int32 nLen = seqType.getLength();
        for ( sal_Int32 i = 0; i < nLen; i++ )
        {
            Type nxtType = seqType[i];
        }

        Sequence< sal_Int8 > seqInt8 = rXTypProv->getImplementationId();
    }

    xClipboard->setContents( rXTransf, Reference< XClipboardOwner >( rXTransf, UNO_QUERY )  );

    rXTransfRead = xClipboard->getContents();

    // destroy the transferable explicitly
    rXTransfRead = Reference< XTransferable>();

    // destroy the clipboard
    xClipboard = Reference< XClipboard >();

    //--------------------------------------------------
    // shutdown the service manager
    //--------------------------------------------------

    // Cast factory to XComponent
    Reference< XComponent > xComponent( g_xFactory, UNO_QUERY );

    if ( !xComponent.is() )
        OSL_ENSURE(sal_False, "Error shuting down");

    // Dispose and clear factory
    xComponent->dispose();
    g_xFactory.clear();
    g_xFactory = Reference< XMultiServiceFactory >();

    return 0;
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PROLONGATIONS_L2_LOCAL_HH
#define DUNE_GDT_PROLONGATIONS_L2_LOCAL_HH

#include <dune/stuff/common/memory.hh>

#include <dune/gdt/exceptions.hh>
#include <dune/gdt/discretefunction/reinterpret.hh>
#include <dune/gdt/operators/default.hh>
#include <dune/gdt/projections/l2-local.hh>

namespace Dune {
namespace GDT {

/**
 * \brief Carries out a prolongation (in a localized manner) using a local L2 projection.
 *
 *        This is done by reinterpreting the source on the range grid view and applying a
 *        L2LocalProjectionLocalizableOperator.
 */
template <class GridViewImp, class SourceImp, class RangeImp>
class L2LocalProlongationLocalizableOperator
    : Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>>,
      public L2LocalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
{
  typedef Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>> SourceStorage;
  typedef L2LocalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
      BaseOperatorType;

public:
  typedef SourceImp SourceType;
  using typename BaseOperatorType::GridViewType;
  using typename BaseOperatorType::RangeType;

  L2LocalProlongationLocalizableOperator(const size_t over_integrate, GridViewType grd_vw, const SourceType& src,
                                         RangeType& rng)
    : SourceStorage(new ReinterpretDiscreteFunction<SourceType>(src))
    , BaseOperatorType(over_integrate, grd_vw, SourceStorage::access(), rng)
  {
  }

  L2LocalProlongationLocalizableOperator(GridViewType grd_vw, const SourceType& src, RangeType& rng)
    : L2LocalProlongationLocalizableOperator(0, grd_vw, src, rng)
  {
  }

  ///! Calls L2LocalProjectionLocalizableOperator::apply and gives a meaningful error message.
  void apply()
  {
    try {
      BaseOperatorType::apply();
    } catch (Stuff::Exceptions::reinterpretation_error& ee) {
      DUNE_THROW(Exceptions::prolongation_error,
                 "This prolongation (using a local L2 projection) failed, because the source could not be reinterpreted"
                     << " on the given grid view!\n"
                     << "This was the original error:\n\n"
                     << ee.what());
    }
  } // ... apply(...)
}; // class L2LocalProlongationLocalizableOperator

template <class GridViewType, class SourceType, class SpaceType, class VectorType>
typename std::
    enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && Stuff::is_localizable_function<SourceType>::value
                  && is_space<SpaceType>::value && Stuff::LA::is_vector<VectorType>::value,
              std::unique_ptr<L2LocalProlongationLocalizableOperator<GridViewType, SourceType,
                                                                     DiscreteFunction<SpaceType, VectorType>>>>::type
    make_local_l2_prolongation_localizable_operator(const GridViewType& grid_view, const SourceType& source,
                                                    DiscreteFunction<SpaceType, VectorType>& range,
                                                    const size_t over_integrate = 0)
{
  return DSC::make_unique<L2LocalProlongationLocalizableOperator<GridViewType,
                                                                 SourceType,
                                                                 DiscreteFunction<SpaceType, VectorType>>>(
      over_integrate, grid_view, source, range);
} // ... make_local_l2_prolongation_localizable_operator(...)

template <class SourceType, class SpaceType, class VectorType>
typename std::
    enable_if<Stuff::is_localizable_function<SourceType>::value && is_space<SpaceType>::value
                  && Stuff::LA::is_vector<VectorType>::value,
              std::unique_ptr<L2LocalProlongationLocalizableOperator<typename SpaceType::GridViewType, SourceType,
                                                                     DiscreteFunction<SpaceType, VectorType>>>>::type
    make_local_l2_prolongation_localizable_operator(const SourceType& source,
                                                    DiscreteFunction<SpaceType, VectorType>& range,
                                                    const size_t over_integrate = 0)
{
  return DSC::make_unique<L2LocalProlongationLocalizableOperator<typename SpaceType::GridViewType,
                                                                 SourceType,
                                                                 DiscreteFunction<SpaceType, VectorType>>>(
      over_integrate, range.space().grid_view(), source, range);
} // ... make_local_l2_prolongation_localizable_operator(...)

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_L2_LOCAL_HH
<commit_msg>[prolongations.l2-local] source has to be a discrete function<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PROLONGATIONS_L2_LOCAL_HH
#define DUNE_GDT_PROLONGATIONS_L2_LOCAL_HH

#include <dune/stuff/common/memory.hh>

#include <dune/gdt/discretefunction/reinterpret.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/operators/default.hh>
#include <dune/gdt/projections/l2-local.hh>

namespace Dune {
namespace GDT {

/**
 * \brief Carries out a prolongation (in a localized manner) using a local L2 projection.
 *
 *        This is done by reinterpreting the source on the range grid view and applying a
 *        L2LocalProjectionLocalizableOperator.
 */
template <class GridViewImp, class SourceImp, class RangeImp>
class L2LocalProlongationLocalizableOperator
    : Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>>,
      public L2LocalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
{
  static_assert(is_const_discrete_function<SourceImp>::value, "");
  static_assert(is_discrete_function<RangeImp>::value, "");
  typedef Stuff::Common::ConstStorageProvider<ReinterpretDiscreteFunction<SourceImp>> SourceStorage;
  typedef L2LocalProjectionLocalizableOperator<GridViewImp, ReinterpretDiscreteFunction<SourceImp>, RangeImp>
      BaseOperatorType;

public:
  typedef SourceImp SourceType;
  using typename BaseOperatorType::GridViewType;
  using typename BaseOperatorType::RangeType;

  L2LocalProlongationLocalizableOperator(const size_t over_integrate, GridViewType grd_vw, const SourceType& src,
                                         RangeType& rng)
    : SourceStorage(new ReinterpretDiscreteFunction<SourceImp>(src))
    , BaseOperatorType(over_integrate, grd_vw, SourceStorage::access(), rng)
  {
  }

  L2LocalProlongationLocalizableOperator(GridViewType grd_vw, const SourceType& src, RangeType& rng)
    : L2LocalProlongationLocalizableOperator(0, grd_vw, src, rng)
  {
  }

  ///! Calls L2LocalProjectionLocalizableOperator::apply and gives a meaningful error message.
  void apply()
  {
    try {
      BaseOperatorType::apply();
    } catch (Stuff::Exceptions::reinterpretation_error& ee) {
      DUNE_THROW(Exceptions::prolongation_error,
                 "This prolongation (using a local L2 projection) failed, because the source could not be reinterpreted"
                     << " on the given grid view!\n"
                     << "This was the original error:\n\n"
                     << ee.what());
    }
  } // ... apply(...)
}; // class L2LocalProlongationLocalizableOperator

template <class GridViewType, class SourceSpaceType, class SourceVectorType, class RangeSpaceType,
          class RangeVectorType>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && is_space<SourceSpaceType>::value
                            && Stuff::LA::is_vector<SourceVectorType>::value && is_space<RangeSpaceType>::value
                            && Stuff::LA::is_vector<RangeVectorType>::value,
                        std::unique_ptr<L2LocalProlongationLocalizableOperator<GridViewType,
                                                                               ConstDiscreteFunction<SourceSpaceType,
                                                                                SourceVectorType>,
                                                                               DiscreteFunction<RangeSpaceType,
                                                                                RangeVectorType>>>>::
    type
    make_local_l2_prolongation_localizable_operator(
        const GridViewType& grid_view, const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source,
        DiscreteFunction<RangeSpaceType, RangeVectorType>& range, const size_t over_integrate = 0)
{
  return DSC::
      make_unique<L2LocalProlongationLocalizableOperator<GridViewType,
                                                         ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
                                                         DiscreteFunction<RangeSpaceType, RangeVectorType>>>(
          over_integrate, grid_view, source, range);
} // ... make_local_l2_prolongation_localizable_operator(...)

template <class SourceSpaceType, class SourceVectorType, class RangeSpaceType, class RangeVectorType>
typename std::enable_if<is_space<SourceSpaceType>::value && Stuff::LA::is_vector<SourceVectorType>::value
                            && is_space<RangeSpaceType>::value && Stuff::LA::is_vector<RangeVectorType>::value,
                        std::unique_ptr<L2LocalProlongationLocalizableOperator<
                            typename RangeSpaceType::GridViewType,
                            ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
                            DiscreteFunction<RangeSpaceType, RangeVectorType>>>>::type
make_local_l2_prolongation_localizable_operator(const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source,
                                                DiscreteFunction<RangeSpaceType, RangeVectorType>& range,
                                                const size_t over_integrate = 0)
{
  return DSC::make_unique<L2LocalProlongationLocalizableOperator<
      typename RangeSpaceType::GridViewType,
      ConstDiscreteFunction<SourceSpaceType, SourceVectorType>,
      DiscreteFunction<RangeSpaceType, RangeVectorType>>>(over_integrate, range.space().grid_view(), source, range);
} // ... make_local_l2_prolongation_localizable_operator(...)

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_L2_LOCAL_HH
<|endoftext|>


<commit_before>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH
#define DUNE_PYMOR_OPERATORS_INTERFACES_HH

#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/la/container/interfaces.hh>
#include <dune/pymor/la/container.hh>

namespace Dune {
namespace Pymor {

class OperatorInterface
  : public Parametric
{
public:
  template< class... Args >
  OperatorInterface(Args&& ...args)
    : Parametric(std::forward< Args >(args)...)
  {}

  virtual ~OperatorInterface() {}

  virtual bool linear() const = 0;

  virtual unsigned int dim_source() const = 0;

  virtual unsigned int dim_range() const = 0;

  virtual std::string type_source() const = 0;

  virtual std::string type_range() const = 0;

  virtual void apply(const LA::VectorInterface* /*source*/,
                     LA::VectorInterface* /*range*/,
                     const Parameter /*mu*/ = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type) = 0;

  virtual LA::VectorInterface* apply(const LA::VectorInterface* source, const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                     "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")!");
    LA::VectorInterface* ret = LA::createVector(type_range(), dim_range());
    apply(source, ret, mu);
    return ret;
  }

  virtual double apply2(const LA::VectorInterface* range,
                        const LA::VectorInterface* source,
                        const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    std::stringstream msg;
    size_t throw_up = 0;
    if (source->type() != type_source()) {
      msg << "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")";
      ++throw_up;
    }
    if (range->type() != type_range()) {
      if (throw_up)
        msg << " and ";
      msg << "range (" << range->type() << ") is not a compatible type_range (" << type_range() << ")";
    }
    if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << "!");
    LA::VectorInterface* tmp = apply(source, mu);
    return range->dot(tmp);
  }

  virtual OperatorInterface* freeze_parameter(const Parameter /*mu*/ = Parameter()) const
    throw (Exception::this_is_not_parametric) = 0;
}; // class OperatorInterface

} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_OPERATORS_INTERFACES_HH
<commit_msg>[operators.interfaec] added exception<commit_after>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH
#define DUNE_PYMOR_OPERATORS_INTERFACES_HH

#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/la/container/interfaces.hh>
#include <dune/pymor/la/container.hh>

namespace Dune {
namespace Pymor {

class OperatorInterface
  : public Parametric
{
public:
  template< class... Args >
  OperatorInterface(Args&& ...args)
    : Parametric(std::forward< Args >(args)...)
  {}

  virtual ~OperatorInterface() {}

  virtual bool linear() const = 0;

  virtual unsigned int dim_source() const = 0;

  virtual unsigned int dim_range() const = 0;

  virtual std::string type_source() const = 0;

  virtual std::string type_range() const = 0;

  virtual void apply(const LA::VectorInterface* /*source*/,
                     LA::VectorInterface* /*range*/,
                     const Parameter /*mu*/ = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type,
           Exception::requirements_not_met) = 0;

  virtual LA::VectorInterface* apply(const LA::VectorInterface* source, const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::you_have_to_implement_this,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
                     "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")!");
    LA::VectorInterface* ret = LA::createVector(type_range(), dim_range());
    apply(source, ret, mu);
    return ret;
  }

  virtual double apply2(const LA::VectorInterface* range,
                        const LA::VectorInterface* source,
                        const Parameter mu = Parameter()) const
    throw (Exception::types_are_not_compatible,
           Exception::sizes_do_not_match,
           Exception::wrong_parameter_type)
  {
    std::stringstream msg;
    size_t throw_up = 0;
    if (source->type() != type_source()) {
      msg << "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")";
      ++throw_up;
    }
    if (range->type() != type_range()) {
      if (throw_up)
        msg << " and ";
      msg << "range (" << range->type() << ") is not a compatible type_range (" << type_range() << ")";
    }
    if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << "!");
    LA::VectorInterface* tmp = apply(source, mu);
    return range->dot(tmp);
  }

  virtual OperatorInterface* freeze_parameter(const Parameter /*mu*/ = Parameter()) const
    throw (Exception::this_is_not_parametric) = 0;
}; // class OperatorInterface

} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_OPERATORS_INTERFACES_HH
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <types.hpp>
#include "prot.hpp"
#include <stdio.h>
#include <functional>
#include "coutil.hpp"
#include <iostream>
#include <unordered_map>

std::unordered_map<KOMA_TYPE, KOMA_TYPE> naru_map;
u64_t teban_number;
extern i64_t E_VALUE_ARRAY[29];

//#define _D

std::function<std::vector<Point>(KOMA_TYPE **, Point)> wcm_function_table[] = {
	null_wcm,
	pl_hu_wcm,
	pl_kyousha_wcm,
	pl_keima_wcm,
	pl_gin_wcm,
	pl_kin_wcm,
	pl_hisha_wcm,
	pl_kaku_wcm,
	pl_kin_wcm,
	pl_kin_wcm,
	pl_kin_wcm,
	pl_kin_wcm,
	pl_ryu_wcm,
	pl_uma_wcm,
	pl_ou_wcm,
	ai_hu_wcm,
	ai_kyousha_wcm,
	ai_keima_wcm,
	ai_gin_wcm,
	ai_kin_wcm,
	ai_hisha_wcm,
	ai_kaku_wcm,
	ai_kin_wcm,
	ai_kin_wcm,
	ai_kin_wcm,
	ai_kin_wcm,
	ai_ryu_wcm,
	ai_uma_wcm,
	ai_ou_wcm
};

void map_init();

int main(int argc, char **argv) {

	Node *node;

	map_init();

	CoyuriIniter initer;
	initer.init(argv[1], &node, &teban_number);

	CoyuriNegaScout searcher(node, teban_number);
	searcher.dual_thread_start();

	searcher.print(argv[2]);
}

void map_init() {

	naru_map.insert(std::make_pair(EMPTY, EMPTY));
	naru_map.insert(std::make_pair(HU, TOKIN));
	naru_map.insert(std::make_pair(KYOUSHA, NARIKEI));
	naru_map.insert(std::make_pair(KEIMA, NARIKEI));
	naru_map.insert(std::make_pair(GIN, NARIGIN));
	naru_map.insert(std::make_pair(KIN, KIN));
	naru_map.insert(std::make_pair(HISHA, RYU));
	naru_map.insert(std::make_pair(KAKU, UMA));
	naru_map.insert(std::make_pair(TOKIN, TOKIN));
	naru_map.insert(std::make_pair(NARIKYOU, NARIKYOU));
	naru_map.insert(std::make_pair(NARIKEI, NARIKEI));
	naru_map.insert(std::make_pair(NARIGIN, NARIGIN));
	naru_map.insert(std::make_pair(RYU, RYU));
	naru_map.insert(std::make_pair(UMA, UMA));
	naru_map.insert(std::make_pair(OU, OU));
	naru_map.insert(std::make_pair(EN_HU, EN_TOKIN));
	naru_map.insert(std::make_pair(EN_KYOUSHA, EN_NARIKEI));
	naru_map.insert(std::make_pair(EN_KEIMA, EN_NARIKEI));
	naru_map.insert(std::make_pair(EN_GIN, EN_NARIGIN));
	naru_map.insert(std::make_pair(EN_KIN, EN_KIN));
	naru_map.insert(std::make_pair(EN_HISHA, EN_RYU));
	naru_map.insert(std::make_pair(EN_KAKU, EN_UMA));
	naru_map.insert(std::make_pair(EN_TOKIN, EN_TOKIN));
	naru_map.insert(std::make_pair(EN_NARIKYOU, EN_NARIKYOU));
	naru_map.insert(std::make_pair(EN_NARIKEI, EN_NARIKEI));
	naru_map.insert(std::make_pair(EN_NARIGIN, EN_NARIGIN));
	naru_map.insert(std::make_pair(EN_RYU, EN_RYU));
	naru_map.insert(std::make_pair(EN_UMA, EN_UMA));
	naru_map.insert(std::make_pair(EN_OU, EN_OU));

#ifdef _D
	cut::json_parser eval_json("C:\\Users\\Akihiro\\Desktop\\coyuri_eval.json");
#endif
#ifndef _D
	cut::json_parser eval_json("./coyuri_eval.json");
#endif
	E_VALUE_ARRAY[0] = 0;

	E_VALUE_ARRAY[1] = eval_json.get_value<i64_t>("Eval.PL_HU");
	E_VALUE_ARRAY[2] = eval_json.get_value<i64_t>("Eval.PL_KYOUSHA");
	E_VALUE_ARRAY[3] = eval_json.get_value<i64_t>("Eval.PL_KEIMA");
	E_VALUE_ARRAY[4] = eval_json.get_value<i64_t>("Eval.PL_GIN");
	E_VALUE_ARRAY[5] = eval_json.get_value<i64_t>("Eval.PL_KIN");
	E_VALUE_ARRAY[6] = eval_json.get_value<i64_t>("Eval.PL_HISHA");
	E_VALUE_ARRAY[7] = eval_json.get_value<i64_t>("Eval.PL_KAKU");
	E_VALUE_ARRAY[8] = eval_json.get_value<i64_t>("Eval.PL_TOKIN");
	E_VALUE_ARRAY[9] = eval_json.get_value<i64_t>("Eval.PL_NARIKYOU");
	E_VALUE_ARRAY[10] = eval_json.get_value<i64_t>("Eval.PL_NARIKEI");
	E_VALUE_ARRAY[11] = eval_json.get_value<i64_t>("Eval.PL_NARIGIN");
	E_VALUE_ARRAY[12] = eval_json.get_value<i64_t>("Eval.PL_RYU");
	E_VALUE_ARRAY[13] = eval_json.get_value<i64_t>("Eval.PL_UMA");
	E_VALUE_ARRAY[14] = eval_json.get_value<i64_t>("Eval.PL_OU");

	E_VALUE_ARRAY[15] = eval_json.get_value<i64_t>("Eval.AI_HU");
	E_VALUE_ARRAY[16] = eval_json.get_value<i64_t>("Eval.AI_KYOUSHA");
	E_VALUE_ARRAY[17] = eval_json.get_value<i64_t>("Eval.AI_KEIMA");
	E_VALUE_ARRAY[18] = eval_json.get_value<i64_t>("Eval.AI_GIN");
	E_VALUE_ARRAY[19] = eval_json.get_value<i64_t>("Eval.AI_KIN");
	E_VALUE_ARRAY[20] = eval_json.get_value<i64_t>("Eval.AI_HISHA");
	E_VALUE_ARRAY[21] = eval_json.get_value<i64_t>("Eval.AI_KAKU");
	E_VALUE_ARRAY[22] = eval_json.get_value<i64_t>("Eval.AI_TOKIN");
	E_VALUE_ARRAY[23] = eval_json.get_value<i64_t>("Eval.AI_NARIKYOU");
	E_VALUE_ARRAY[24] = eval_json.get_value<i64_t>("Eval.AI_NARIKEI");
	E_VALUE_ARRAY[25] = eval_json.get_value<i64_t>("Eval.AI_NARIGIN");
	E_VALUE_ARRAY[26] = eval_json.get_value<i64_t>("Eval.AI_RYU");
	E_VALUE_ARRAY[27] = eval_json.get_value<i64_t>("Eval.AI_OU");
}
<commit_msg>成る処理のバグを修正<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <types.hpp>
#include "prot.hpp"
#include <stdio.h>
#include <functional>
#include "coutil.hpp"
#include <iostream>
#include <unordered_map>

std::unordered_map<KOMA_TYPE, KOMA_TYPE> naru_map;
u64_t teban_number;
extern i64_t E_VALUE_ARRAY[29];

//#define _D

std::function<std::vector<Point>(KOMA_TYPE **, Point)> wcm_function_table[] = {
	null_wcm,
	pl_hu_wcm,
	pl_kyousha_wcm,
	pl_keima_wcm,
	pl_gin_wcm,
	pl_kin_wcm,
	pl_hisha_wcm,
	pl_kaku_wcm,
	pl_kin_wcm,
	pl_kin_wcm,
	pl_kin_wcm,
	pl_kin_wcm,
	pl_ryu_wcm,
	pl_uma_wcm,
	pl_ou_wcm,
	ai_hu_wcm,
	ai_kyousha_wcm,
	ai_keima_wcm,
	ai_gin_wcm,
	ai_kin_wcm,
	ai_hisha_wcm,
	ai_kaku_wcm,
	ai_kin_wcm,
	ai_kin_wcm,
	ai_kin_wcm,
	ai_kin_wcm,
	ai_ryu_wcm,
	ai_uma_wcm,
	ai_ou_wcm
};

void map_init();

int main(int argc, char **argv) {

	Node *node;

	map_init();

	CoyuriIniter initer;
	initer.init(argv[1], &node, &teban_number);

	CoyuriNegaScout searcher(node, teban_number);
	searcher.dual_thread_start();

	searcher.print(argv[2]);
}

void map_init() {

	naru_map.insert(std::make_pair(EMPTY, EMPTY));
	naru_map.insert(std::make_pair(HU, TOKIN));
	naru_map.insert(std::make_pair(KYOUSHA, NARIKYOU));
	naru_map.insert(std::make_pair(KEIMA, NARIKEI));
	naru_map.insert(std::make_pair(GIN, NARIGIN));
	naru_map.insert(std::make_pair(KIN, KIN));
	naru_map.insert(std::make_pair(HISHA, RYU));
	naru_map.insert(std::make_pair(KAKU, UMA));
	naru_map.insert(std::make_pair(TOKIN, TOKIN));
	naru_map.insert(std::make_pair(NARIKYOU, NARIKYOU));
	naru_map.insert(std::make_pair(NARIKEI, NARIKEI));
	naru_map.insert(std::make_pair(NARIGIN, NARIGIN));
	naru_map.insert(std::make_pair(RYU, RYU));
	naru_map.insert(std::make_pair(UMA, UMA));
	naru_map.insert(std::make_pair(OU, OU));
	naru_map.insert(std::make_pair(EN_HU, EN_TOKIN));
	naru_map.insert(std::make_pair(EN_KYOUSHA, EN_NARIKYOU));
	naru_map.insert(std::make_pair(EN_KEIMA, EN_NARIKEI));
	naru_map.insert(std::make_pair(EN_GIN, EN_NARIGIN));
	naru_map.insert(std::make_pair(EN_KIN, EN_KIN));
	naru_map.insert(std::make_pair(EN_HISHA, EN_RYU));
	naru_map.insert(std::make_pair(EN_KAKU, EN_UMA));
	naru_map.insert(std::make_pair(EN_TOKIN, EN_TOKIN));
	naru_map.insert(std::make_pair(EN_NARIKYOU, EN_NARIKYOU));
	naru_map.insert(std::make_pair(EN_NARIKEI, EN_NARIKEI));
	naru_map.insert(std::make_pair(EN_NARIGIN, EN_NARIGIN));
	naru_map.insert(std::make_pair(EN_RYU, EN_RYU));
	naru_map.insert(std::make_pair(EN_UMA, EN_UMA));
	naru_map.insert(std::make_pair(EN_OU, EN_OU));

#ifdef _D
	cut::json_parser eval_json("C:\\Users\\Akihiro\\Desktop\\coyuri_eval.json");
#endif
#ifndef _D
	cut::json_parser eval_json("./coyuri_eval.json");
#endif
	E_VALUE_ARRAY[0] = 0;

	E_VALUE_ARRAY[1] = eval_json.get_value<i64_t>("Eval.PL_HU");
	E_VALUE_ARRAY[2] = eval_json.get_value<i64_t>("Eval.PL_KYOUSHA");
	E_VALUE_ARRAY[3] = eval_json.get_value<i64_t>("Eval.PL_KEIMA");
	E_VALUE_ARRAY[4] = eval_json.get_value<i64_t>("Eval.PL_GIN");
	E_VALUE_ARRAY[5] = eval_json.get_value<i64_t>("Eval.PL_KIN");
	E_VALUE_ARRAY[6] = eval_json.get_value<i64_t>("Eval.PL_HISHA");
	E_VALUE_ARRAY[7] = eval_json.get_value<i64_t>("Eval.PL_KAKU");
	E_VALUE_ARRAY[8] = eval_json.get_value<i64_t>("Eval.PL_TOKIN");
	E_VALUE_ARRAY[9] = eval_json.get_value<i64_t>("Eval.PL_NARIKYOU");
	E_VALUE_ARRAY[10] = eval_json.get_value<i64_t>("Eval.PL_NARIKEI");
	E_VALUE_ARRAY[11] = eval_json.get_value<i64_t>("Eval.PL_NARIGIN");
	E_VALUE_ARRAY[12] = eval_json.get_value<i64_t>("Eval.PL_RYU");
	E_VALUE_ARRAY[13] = eval_json.get_value<i64_t>("Eval.PL_UMA");
	E_VALUE_ARRAY[14] = eval_json.get_value<i64_t>("Eval.PL_OU");

	E_VALUE_ARRAY[15] = eval_json.get_value<i64_t>("Eval.AI_HU");
	E_VALUE_ARRAY[16] = eval_json.get_value<i64_t>("Eval.AI_KYOUSHA");
	E_VALUE_ARRAY[17] = eval_json.get_value<i64_t>("Eval.AI_KEIMA");
	E_VALUE_ARRAY[18] = eval_json.get_value<i64_t>("Eval.AI_GIN");
	E_VALUE_ARRAY[19] = eval_json.get_value<i64_t>("Eval.AI_KIN");
	E_VALUE_ARRAY[20] = eval_json.get_value<i64_t>("Eval.AI_HISHA");
	E_VALUE_ARRAY[21] = eval_json.get_value<i64_t>("Eval.AI_KAKU");
	E_VALUE_ARRAY[22] = eval_json.get_value<i64_t>("Eval.AI_TOKIN");
	E_VALUE_ARRAY[23] = eval_json.get_value<i64_t>("Eval.AI_NARIKYOU");
	E_VALUE_ARRAY[24] = eval_json.get_value<i64_t>("Eval.AI_NARIKEI");
	E_VALUE_ARRAY[25] = eval_json.get_value<i64_t>("Eval.AI_NARIGIN");
	E_VALUE_ARRAY[26] = eval_json.get_value<i64_t>("Eval.AI_RYU");
	E_VALUE_ARRAY[27] = eval_json.get_value<i64_t>("Eval.AI_OU");
}
<|endoftext|>


<commit_before>#ifndef MATH_UTILS_HPP_INCLUDED
#define MATH_UTILS_HPP_INCLUDED

/**
 @file math_utils.hpp
 @author François Becker

MIT License

Copyright (c) 2015-2017 François Becker

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "math_float_constants.hpp"

#include <cassert>

#define DEG2RAD (M_PI / 180.)
#define DEG2RADf (M_PIf / 180.f)
#define RAD2DEG (180. / M_PI)
#define RAD2DEGf (180.f / M_PIf)

namespace mu
{
    //==============================================================================
    template <typename T>
    T finvsqrt(T x)
    {
        //assert(x >= (T)0); // caller is responsible for checking that
        return (T)1 / std::sqrt(x); // the compiler is expected to detect and optimize this,
                                    // but /!\ that may not actually happen
    }

#if 0
    /**
     @copyright public domain
     */
    template <>
    inline float finvsqrt<float>(float number)
    {
        float x2 = number * 0.5f;
        float y = number;
        uint32_t i = *(uint32_t*)&y;
        i = 0x5f375a86 - (i >> 1);
        y = *(float*) &i;
        y = y * (1.5f - (x2 * y * y));
        return y;
    }

    /**
     @copyright public domain
     */
    template <>
    inline double finvsqrt<double>(double number)
    {
        uint64_t i;
        double x2, y;
        x2 = number * 0.5;
        y = number;
        i = *(uint64_t*) &y;
        i = 0x5fe6eb50c7b537a9 - (i >> 1);
        y = *(double*) &i;
        y = y * (1.5 - (x2 * y * y));
        return y;
    }
#endif

    //==============================================================================
    /**
     Check if an angle is in )-π,π)
     */
    inline bool isDomainAngle(float pAngle)
    {
        return ((pAngle > - M_PIf) && (pAngle <= M_PIf));
    }

    //==============================================================================
    /**
     Check if an angle is in (-π,π)
     */
    inline bool isDomainAnglePermissive(float pAngle)
    {
        return ((pAngle >= - M_PIf) && (pAngle <= M_PIf));
    }

    //==============================================================================
    /**
     Get an angle in )-π,π) provided the input is in )-3π,3π)
     */
    inline float domainAngleSimple(float pAngle)
    {
        if (pAngle > M_PIf)
        {
            pAngle -= 2.f * M_PIf;
        }
        else if (pAngle <= - M_PIf)
        {
            pAngle += 2.f * M_PIf;
        }
        assert(isDomainAngle(pAngle));
        return pAngle;
    }

    //==============================================================================
    /**
     Get an angle in )-π,π)
     */
    inline float domainAngle(float pAngle)
    {
        float lAngle = std::remainder(pAngle, 2.f * M_PIf);
        if (lAngle <= -M_PIf) // TODO: change the domain so as to avoid this
        {
            lAngle += 2.f * M_PIf;
        }
        assert(isDomainAngle(lAngle));
        return lAngle;
    }

    //==============================================================================
    template <typename T>
    void limitRange(T& value, T low, T high)
    {
        assert(low <= high);
        if (value < low)
        {
            value = low;
        }
        else if (value > high)
        {
            value = high;
        }
    }

    //==============================================================================
    template <typename T>
    T limitedRange(T value, T low, T high)
    {
        assert(low <= high);
        if (value < low)
        {
            return low;
        }
        else if (value > high)
        {
            return high;
        }
        return value;
    }

    //==============================================================================
    template <typename T>
    constexpr bool inRange(T value, T low, T high)
    {
        //assert(low <= high);
        return value >= low && value <= high;
    }

    //==============================================================================
    inline int nextPowerOf2(int n)
    {
        --n;
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;
        return n + 1;
    }

    //==============================================================================
    inline int fftOrderFor(int pNumSamples)
    {
        int v = nextPowerOf2(pNumSamples);  // find the number of trailing zeros in 32-bit v
        constexpr const int MultiplyDeBruijnBitPosition[32] =
        {
            0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
            31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
        };
        return MultiplyDeBruijnBitPosition[((uint32_t)((v/* & -v*/) * 0x077CB531U)) >> 27];
    }

    //==============================================================================
    inline bool isPowerOf2(unsigned int x)
    {
        return ((x != 0) && ((x & (~x + 1)) == x));
    }

    //==============================================================================
    template<typename T>
    constexpr T dBToGain(T pDB)
    {
        return std::pow((T)10, pDB / (T)20);
    }

    //==============================================================================
    template <typename T>
    constexpr T affineTransform(T fromMin, T fromMax, T toMin, T toMax, T value)
    {
        //assert(fromMax - fromMin != (T)0);
        return toMin + (toMax - toMin) * (value - fromMin) / (fromMax - fromMin);
    }

    //==============================================================================
    template<typename T>
    constexpr T square(T pVal)
    {
        return pVal * pVal;
    }

    //==============================================================================
    /**
     @copyright public domain
     */
    inline float fast_log2(float val)
    {
        union {float f; int i;} t;
        t.f = val;
        int * const exp_ptr = &t.i;
        int x = *exp_ptr;
        const int log_2 = ((x >> 23) & 255) - 128;
        x &= ~(255 << 23);
        x += 127 << 23;
        *exp_ptr = x;

        val = ((-1.0f/3) * t.f + 2) * t.f - 2.0f/3;

        return (val + log_2);
    }

    /**
     @copyright public domain
     */
    inline float fast_log(const float val)
    {
        return (fast_log2(val) * 0.69314718f);
    }

    /**
     @copyright public domain
     */
    inline float fast_log10(const float val)
    {
        return fast_log2(val) / 3.312500f;
    }

    //==============================================================================
    inline float fast_gainToDB(const float g)
    {
        return 20.f * fast_log10(g);
    }

    inline float fast_powToDB(const float g)
    {
        return 10.f * fast_log10(g);
    }

    //==============================================================================
    template <typename T>
    void boundsSafeGuard(T* pChannel, int pNumSamples)
    {
        for (int i = 0 ; i != pNumSamples ; ++i)
        {
            if (! std::isfinite(pChannel[i]))
            {
                pChannel[i] = (T)0;
            }
        }
    }
}

#endif
<commit_msg>math_utils.hpp: added <cstdint> include for int32_t<commit_after>#ifndef MATH_UTILS_HPP_INCLUDED
#define MATH_UTILS_HPP_INCLUDED

/**
 @file math_utils.hpp
 @author François Becker

MIT License

Copyright (c) 2015-2017 François Becker

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "math_float_constants.hpp"

#include <cstdint>
#include <cassert>

#define DEG2RAD (M_PI / 180.)
#define DEG2RADf (M_PIf / 180.f)
#define RAD2DEG (180. / M_PI)
#define RAD2DEGf (180.f / M_PIf)

namespace mu
{
    //==============================================================================
    template <typename T>
    T finvsqrt(T x)
    {
        //assert(x >= (T)0); // caller is responsible for checking that
        return (T)1 / std::sqrt(x); // the compiler is expected to detect and optimize this,
                                    // but /!\ that may not actually happen
    }

#if 0
    /**
     @copyright public domain
     */
    template <>
    inline float finvsqrt<float>(float number)
    {
        float x2 = number * 0.5f;
        float y = number;
        uint32_t i = *(uint32_t*)&y;
        i = 0x5f375a86 - (i >> 1);
        y = *(float*) &i;
        y = y * (1.5f - (x2 * y * y));
        return y;
    }

    /**
     @copyright public domain
     */
    template <>
    inline double finvsqrt<double>(double number)
    {
        uint64_t i;
        double x2, y;
        x2 = number * 0.5;
        y = number;
        i = *(uint64_t*) &y;
        i = 0x5fe6eb50c7b537a9 - (i >> 1);
        y = *(double*) &i;
        y = y * (1.5 - (x2 * y * y));
        return y;
    }
#endif

    //==============================================================================
    /**
     Check if an angle is in )-π,π)
     */
    inline bool isDomainAngle(float pAngle)
    {
        return ((pAngle > - M_PIf) && (pAngle <= M_PIf));
    }

    //==============================================================================
    /**
     Check if an angle is in (-π,π)
     */
    inline bool isDomainAnglePermissive(float pAngle)
    {
        return ((pAngle >= - M_PIf) && (pAngle <= M_PIf));
    }

    //==============================================================================
    /**
     Get an angle in )-π,π) provided the input is in )-3π,3π)
     */
    inline float domainAngleSimple(float pAngle)
    {
        if (pAngle > M_PIf)
        {
            pAngle -= 2.f * M_PIf;
        }
        else if (pAngle <= - M_PIf)
        {
            pAngle += 2.f * M_PIf;
        }
        assert(isDomainAngle(pAngle));
        return pAngle;
    }

    //==============================================================================
    /**
     Get an angle in )-π,π)
     */
    inline float domainAngle(float pAngle)
    {
        float lAngle = std::remainder(pAngle, 2.f * M_PIf);
        if (lAngle <= -M_PIf) // TODO: change the domain so as to avoid this
        {
            lAngle += 2.f * M_PIf;
        }
        assert(isDomainAngle(lAngle));
        return lAngle;
    }

    //==============================================================================
    template <typename T>
    void limitRange(T& value, T low, T high)
    {
        assert(low <= high);
        if (value < low)
        {
            value = low;
        }
        else if (value > high)
        {
            value = high;
        }
    }

    //==============================================================================
    template <typename T>
    T limitedRange(T value, T low, T high)
    {
        assert(low <= high);
        if (value < low)
        {
            return low;
        }
        else if (value > high)
        {
            return high;
        }
        return value;
    }

    //==============================================================================
    template <typename T>
    constexpr bool inRange(T value, T low, T high)
    {
        //assert(low <= high);
        return value >= low && value <= high;
    }

    //==============================================================================
    inline int nextPowerOf2(int n)
    {
        --n;
        n |= n >> 1;
        n |= n >> 2;
        n |= n >> 4;
        n |= n >> 8;
        n |= n >> 16;
        return n + 1;
    }

    //==============================================================================
    inline int fftOrderFor(int pNumSamples)
    {
        int v = nextPowerOf2(pNumSamples);  // find the number of trailing zeros in 32-bit v
        constexpr const int MultiplyDeBruijnBitPosition[32] =
        {
            0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
            31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
        };
        return MultiplyDeBruijnBitPosition[((uint32_t)((v/* & -v*/) * 0x077CB531U)) >> 27];
    }

    //==============================================================================
    inline bool isPowerOf2(unsigned int x)
    {
        return ((x != 0) && ((x & (~x + 1)) == x));
    }

    //==============================================================================
    template<typename T>
    constexpr T dBToGain(T pDB)
    {
        return std::pow((T)10, pDB / (T)20);
    }

    //==============================================================================
    template <typename T>
    constexpr T affineTransform(T fromMin, T fromMax, T toMin, T toMax, T value)
    {
        //assert(fromMax - fromMin != (T)0);
        return toMin + (toMax - toMin) * (value - fromMin) / (fromMax - fromMin);
    }

    //==============================================================================
    template<typename T>
    constexpr T square(T pVal)
    {
        return pVal * pVal;
    }

    //==============================================================================
    /**
     @copyright public domain
     */
    inline float fast_log2(float val)
    {
        union {float f; int i;} t;
        t.f = val;
        int * const exp_ptr = &t.i;
        int x = *exp_ptr;
        const int log_2 = ((x >> 23) & 255) - 128;
        x &= ~(255 << 23);
        x += 127 << 23;
        *exp_ptr = x;

        val = ((-1.0f/3) * t.f + 2) * t.f - 2.0f/3;

        return (val + log_2);
    }

    /**
     @copyright public domain
     */
    inline float fast_log(const float val)
    {
        return (fast_log2(val) * 0.69314718f);
    }

    /**
     @copyright public domain
     */
    inline float fast_log10(const float val)
    {
        return fast_log2(val) / 3.312500f;
    }

    //==============================================================================
    inline float fast_gainToDB(const float g)
    {
        return 20.f * fast_log10(g);
    }

    inline float fast_powToDB(const float g)
    {
        return 10.f * fast_log10(g);
    }

    //==============================================================================
    template <typename T>
    void boundsSafeGuard(T* pChannel, int pNumSamples)
    {
        for (int i = 0 ; i != pNumSamples ; ++i)
        {
            if (! std::isfinite(pChannel[i]))
            {
                pChannel[i] = (T)0;
            }
        }
    }
}

#endif
<|endoftext|>