<commit_before>/*************************************************************************
 *
 *  $RCSfile: X11_service.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: pl $ $Date: 2001-09-11 11:23:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc..
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <X11_clipboard.hxx>

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif

#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h> // declaration of generic uno interface
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx> // mapping stuff
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif

using namespace rtl;
using namespace cppu;
using namespace com::sun::star::lang;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::awt;
using namespace x11;

namespace x11 {

class X11ClipboardFactory : public ::cppu::WeakComponentImplHelper1 <
    ::com::sun::star::lang::XSingleServiceFactory
>
{
    ::osl::Mutex m_aMutex;
    ::std::hash_map< OUString, ::std::hash_map< Atom, Reference< XClipboard > >, ::rtl::OUStringHash > m_aInstances;
public:
    X11ClipboardFactory();
    virtual ~X11ClipboardFactory();

    /*
     *  XSingleServiceFactory
     */
    virtual Reference< XInterface > createInstance() throw();
    virtual Reference< XInterface > createInstanceWithArguments( const Sequence< Any >& rArgs ) throw();
};

// ------------------------------------------------------------------------

X11ClipboardFactory::X11ClipboardFactory() :
        ::cppu::WeakComponentImplHelper1<
    ::com::sun::star::lang::XSingleServiceFactory
>( m_aMutex )
{
}

// ------------------------------------------------------------------------

X11ClipboardFactory::~X11ClipboardFactory()
{
}

// ------------------------------------------------------------------------

Reference< XInterface > X11ClipboardFactory::createInstance() throw()
{
    return createInstanceWithArguments( Sequence< Any >() );
}

// ------------------------------------------------------------------------

Reference< XInterface > X11ClipboardFactory::createInstanceWithArguments( const Sequence< Any >& arguments ) throw()
{
    OUString aDisplayName;
    Atom nSelection;

    // extract display name from connection argument. An exception is thrown
    // by SelectionManager.initialize() if no display connection is given.
    if( arguments.getLength() > 0 )
    {
        Reference< XDisplayConnection > xConn;
        arguments.getConstArray()[0] >>= xConn;

        if( xConn.is() )
        {
            Any aIdentifier = xConn->getIdentifier();
            aIdentifier >>= aDisplayName;
        }
    }

    SelectionManager& rManager = SelectionManager::get( aDisplayName );
    rManager.initialize( arguments );

    // check if any other selection than clipboard selection is specified
    if( arguments.getLength() > 1 )
    {
        OUString aSelectionName;

        arguments.getConstArray()[1] >>= aSelectionName;
        nSelection = rManager.getAtom( aSelectionName );
    }
    else
    {
        // default atom is clipboard selection
        nSelection = rManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) );
    }

    ::std::hash_map< Atom, Reference< XClipboard > >& rMap( m_aInstances[ aDisplayName ] );
    ::std::hash_map< Atom, Reference< XClipboard > >::iterator it = rMap.find( nSelection );
    if( it != rMap.end() )
        return it->second;

    X11Clipboard* pClipboard = new X11Clipboard( rManager, nSelection );
    rMap[ nSelection ] = pClipboard;

    return static_cast<OWeakObject*>(pClipboard);
}

// ------------------------------------------------------------------------

Sequence< OUString > SAL_CALL X11Clipboard_getSupportedServiceNames()
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard");
    return aRet;
}

// ------------------------------------------------------------------------

Sequence< OUString > SAL_CALL Xdnd_getSupportedServiceNames()
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DragSource");
    return aRet;
}

// ------------------------------------------------------------------------

Reference< XInterface > SAL_CALL Xdnd_createInstance(
    const Reference< XMultiServiceFactory > & xMultiServiceFactory)
{
    return Reference < XInterface >( ( OWeakObject * ) new SelectionManagerHolder() );
}

// ------------------------------------------------------------------------

Sequence< OUString > SAL_CALL Xdnd_dropTarget_getSupportedServiceNames()
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DropTarget");
    return aRet;
}

// ------------------------------------------------------------------------

Reference< XInterface > SAL_CALL Xdnd_dropTarget_createInstance(
    const Reference< XMultiServiceFactory > & xMultiServiceFactory)
{
    return Reference < XInterface >( ( OWeakObject * ) new DropTarget() );
}

}

static const OUString& getClipboardImplementationName()
{
    static OUString aImpl = OUString::createFromAscii(X11_CLIPBOARD_IMPLEMENTATION_NAME);
    return aImpl;
}

static const OUString& getClipboardServiceName()
{
    static OUString aImpl = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard" );
    return aImpl;
}

static const OUString& getXdndImplementationName()
{
    static OUString aImpl = OUString::createFromAscii(XDND_IMPLEMENTATION_NAME );
    return aImpl;
}

static const OUString& getXdndServiceName()
{
    static OUString aImpl = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DragSource" );
    return aImpl;
}

static const OUString& getXdndDropTargetImplementationName()
{
    static OUString aImpl = OUString::createFromAscii(XDND_DROPTARGET_IMPLEMENTATION_NAME);
    return aImpl;
}

static const OUString& getXdndDropTargetServiceName()
{
    static OUString aImpl = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DropTarget" );
    return aImpl;
}

extern "C" {
    void SAL_CALL component_getImplementationEnvironment(
        const sal_Char** ppEnvTypeName,
        uno_Environment** ppEnv )
    {
        *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
    }

    sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pXUnoKey )
    {
        if( pXUnoKey )
        {
            try
            {
                Reference< ::com::sun::star::registry::XRegistryKey > xKey( reinterpret_cast< ::com::sun::star::registry::XRegistryKey* >( pXUnoKey ) );

                OUString aImplName = OUString::createFromAscii( "/" );
                aImplName += getClipboardImplementationName();
                aImplName += ::rtl::OUString::createFromAscii( "/UNO/SERVICES/" );
                aImplName += getClipboardServiceName();
                xKey->createKey( aImplName );

                aImplName = OUString::createFromAscii( "/" );
                aImplName += getXdndImplementationName();
                aImplName += ::rtl::OUString::createFromAscii( "/UNO/SERVICES/" );
                aImplName += getXdndServiceName();
                xKey->createKey( aImplName );

                aImplName = OUString::createFromAscii( "/" );
                aImplName += getXdndDropTargetImplementationName();
                aImplName += ::rtl::OUString::createFromAscii( "/UNO/SERVICES/" );
                aImplName += getXdndDropTargetServiceName();
                xKey->createKey( aImplName );

                return sal_True;
            }
            catch( ::com::sun::star::registry::InvalidRegistryException& )
            {
            }
        }
        return sal_False;
    }

    void* SAL_CALL component_getFactory(
        const sal_Char* pImplementationName,
        void* pXUnoSMgr,
        void* pXUnoKey
        )
    {
        void* pRet = 0;

        ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplementationName ) );

        if( pXUnoSMgr )
        {
            Reference< ::com::sun::star::lang::XMultiServiceFactory > xMgr(
                reinterpret_cast< ::com::sun::star::lang::XMultiServiceFactory* >( pXUnoSMgr )
                );
            Reference< ::com::sun::star::lang::XSingleServiceFactory > xFactory;
            if( aImplName.equals( getClipboardImplementationName() ) )
                xFactory = new X11ClipboardFactory();
            else if( aImplName.equals( getXdndImplementationName() ) )
            {
                xFactory = ::cppu::createSingleFactory(
                    xMgr, aImplName, Xdnd_createInstance,
                    Xdnd_getSupportedServiceNames() );
            }
            else if( aImplName.equals( getXdndDropTargetImplementationName() ) )
            {
                xFactory = ::cppu::createSingleFactory(
                    xMgr, aImplName, Xdnd_dropTarget_createInstance,
                    Xdnd_dropTarget_getSupportedServiceNames() );
            }
            if( xFactory.is() )
            {
                xFactory->acquire();
                pRet = xFactory.get();
            }
        }
        return pRet;
    }

} /* extern "C" */
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.172); FILE MERGED 2005/09/05 18:48:03 rt 1.7.172.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: X11_service.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:03:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <X11_clipboard.hxx>

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif

#ifndef _UNO_DISPATCHER_H_
#include <uno/dispatcher.h> // declaration of generic uno interface
#endif
#ifndef _UNO_MAPPING_HXX_
#include <uno/mapping.hxx> // mapping stuff
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif

using namespace rtl;
using namespace cppu;
using namespace com::sun::star::lang;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::awt;
using namespace x11;

namespace x11 {

class X11ClipboardFactory : public ::cppu::WeakComponentImplHelper1 <
    ::com::sun::star::lang::XSingleServiceFactory
>
{
    ::osl::Mutex m_aMutex;
    ::std::hash_map< OUString, ::std::hash_map< Atom, Reference< XClipboard > >, ::rtl::OUStringHash > m_aInstances;
public:
    X11ClipboardFactory();
    virtual ~X11ClipboardFactory();

    /*
     *  XSingleServiceFactory
     */
    virtual Reference< XInterface > createInstance() throw();
    virtual Reference< XInterface > createInstanceWithArguments( const Sequence< Any >& rArgs ) throw();
};

// ------------------------------------------------------------------------

X11ClipboardFactory::X11ClipboardFactory() :
        ::cppu::WeakComponentImplHelper1<
    ::com::sun::star::lang::XSingleServiceFactory
>( m_aMutex )
{
}

// ------------------------------------------------------------------------

X11ClipboardFactory::~X11ClipboardFactory()
{
}

// ------------------------------------------------------------------------

Reference< XInterface > X11ClipboardFactory::createInstance() throw()
{
    return createInstanceWithArguments( Sequence< Any >() );
}

// ------------------------------------------------------------------------

Reference< XInterface > X11ClipboardFactory::createInstanceWithArguments( const Sequence< Any >& arguments ) throw()
{
    OUString aDisplayName;
    Atom nSelection;

    // extract display name from connection argument. An exception is thrown
    // by SelectionManager.initialize() if no display connection is given.
    if( arguments.getLength() > 0 )
    {
        Reference< XDisplayConnection > xConn;
        arguments.getConstArray()[0] >>= xConn;

        if( xConn.is() )
        {
            Any aIdentifier = xConn->getIdentifier();
            aIdentifier >>= aDisplayName;
        }
    }

    SelectionManager& rManager = SelectionManager::get( aDisplayName );
    rManager.initialize( arguments );

    // check if any other selection than clipboard selection is specified
    if( arguments.getLength() > 1 )
    {
        OUString aSelectionName;

        arguments.getConstArray()[1] >>= aSelectionName;
        nSelection = rManager.getAtom( aSelectionName );
    }
    else
    {
        // default atom is clipboard selection
        nSelection = rManager.getAtom( OUString::createFromAscii( "CLIPBOARD" ) );
    }

    ::std::hash_map< Atom, Reference< XClipboard > >& rMap( m_aInstances[ aDisplayName ] );
    ::std::hash_map< Atom, Reference< XClipboard > >::iterator it = rMap.find( nSelection );
    if( it != rMap.end() )
        return it->second;

    X11Clipboard* pClipboard = new X11Clipboard( rManager, nSelection );
    rMap[ nSelection ] = pClipboard;

    return static_cast<OWeakObject*>(pClipboard);
}

// ------------------------------------------------------------------------

Sequence< OUString > SAL_CALL X11Clipboard_getSupportedServiceNames()
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard");
    return aRet;
}

// ------------------------------------------------------------------------

Sequence< OUString > SAL_CALL Xdnd_getSupportedServiceNames()
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DragSource");
    return aRet;
}

// ------------------------------------------------------------------------

Reference< XInterface > SAL_CALL Xdnd_createInstance(
    const Reference< XMultiServiceFactory > & xMultiServiceFactory)
{
    return Reference < XInterface >( ( OWeakObject * ) new SelectionManagerHolder() );
}

// ------------------------------------------------------------------------

Sequence< OUString > SAL_CALL Xdnd_dropTarget_getSupportedServiceNames()
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DropTarget");
    return aRet;
}

// ------------------------------------------------------------------------

Reference< XInterface > SAL_CALL Xdnd_dropTarget_createInstance(
    const Reference< XMultiServiceFactory > & xMultiServiceFactory)
{
    return Reference < XInterface >( ( OWeakObject * ) new DropTarget() );
}

}

static const OUString& getClipboardImplementationName()
{
    static OUString aImpl = OUString::createFromAscii(X11_CLIPBOARD_IMPLEMENTATION_NAME);
    return aImpl;
}

static const OUString& getClipboardServiceName()
{
    static OUString aImpl = OUString::createFromAscii("com.sun.star.datatransfer.clipboard.SystemClipboard" );
    return aImpl;
}

static const OUString& getXdndImplementationName()
{
    static OUString aImpl = OUString::createFromAscii(XDND_IMPLEMENTATION_NAME );
    return aImpl;
}

static const OUString& getXdndServiceName()
{
    static OUString aImpl = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DragSource" );
    return aImpl;
}

static const OUString& getXdndDropTargetImplementationName()
{
    static OUString aImpl = OUString::createFromAscii(XDND_DROPTARGET_IMPLEMENTATION_NAME);
    return aImpl;
}

static const OUString& getXdndDropTargetServiceName()
{
    static OUString aImpl = OUString::createFromAscii("com.sun.star.datatransfer.dnd.X11DropTarget" );
    return aImpl;
}

extern "C" {
    void SAL_CALL component_getImplementationEnvironment(
        const sal_Char** ppEnvTypeName,
        uno_Environment** ppEnv )
    {
        *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
    }

    sal_Bool SAL_CALL component_writeInfo( void* pServiceManager, void* pXUnoKey )
    {
        if( pXUnoKey )
        {
            try
            {
                Reference< ::com::sun::star::registry::XRegistryKey > xKey( reinterpret_cast< ::com::sun::star::registry::XRegistryKey* >( pXUnoKey ) );

                OUString aImplName = OUString::createFromAscii( "/" );
                aImplName += getClipboardImplementationName();
                aImplName += ::rtl::OUString::createFromAscii( "/UNO/SERVICES/" );
                aImplName += getClipboardServiceName();
                xKey->createKey( aImplName );

                aImplName = OUString::createFromAscii( "/" );
                aImplName += getXdndImplementationName();
                aImplName += ::rtl::OUString::createFromAscii( "/UNO/SERVICES/" );
                aImplName += getXdndServiceName();
                xKey->createKey( aImplName );

                aImplName = OUString::createFromAscii( "/" );
                aImplName += getXdndDropTargetImplementationName();
                aImplName += ::rtl::OUString::createFromAscii( "/UNO/SERVICES/" );
                aImplName += getXdndDropTargetServiceName();
                xKey->createKey( aImplName );

                return sal_True;
            }
            catch( ::com::sun::star::registry::InvalidRegistryException& )
            {
            }
        }
        return sal_False;
    }

    void* SAL_CALL component_getFactory(
        const sal_Char* pImplementationName,
        void* pXUnoSMgr,
        void* pXUnoKey
        )
    {
        void* pRet = 0;

        ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplementationName ) );

        if( pXUnoSMgr )
        {
            Reference< ::com::sun::star::lang::XMultiServiceFactory > xMgr(
                reinterpret_cast< ::com::sun::star::lang::XMultiServiceFactory* >( pXUnoSMgr )
                );
            Reference< ::com::sun::star::lang::XSingleServiceFactory > xFactory;
            if( aImplName.equals( getClipboardImplementationName() ) )
                xFactory = new X11ClipboardFactory();
            else if( aImplName.equals( getXdndImplementationName() ) )
            {
                xFactory = ::cppu::createSingleFactory(
                    xMgr, aImplName, Xdnd_createInstance,
                    Xdnd_getSupportedServiceNames() );
            }
            else if( aImplName.equals( getXdndDropTargetImplementationName() ) )
            {
                xFactory = ::cppu::createSingleFactory(
                    xMgr, aImplName, Xdnd_dropTarget_createInstance,
                    Xdnd_dropTarget_getSupportedServiceNames() );
            }
            if( xFactory.is() )
            {
                xFactory->acquire();
                pRet = xFactory.get();
            }
        }
        return pRet;
    }

} /* extern "C" */
<|endoftext|>


<commit_before>/**
* @project nanorpc
* @file EchoCommon.hh
* @author  S Roychowdhury <sroycode AT gmail DOT com>
* @version 1.0
*
* @section LICENSE
*
* Copyright (c) 2013 S Roychowdhury
*
* 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 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.
*
* @section DESCRIPTION
*
* example: echo endpoint only
*
*/
#ifndef _NRPC_ECHO_COMMON_HH_
#define _NRPC_ECHO_COMMON_HH_

#define ECHO_ENDPOINT "tcp://127.0.0.1:9999"
// #define ECHO_ENDPOINT "ipc:///tmp/echo.sock"
#endif
<commit_msg>Sat Oct 19 10:12:49 IST 2013<commit_after><|endoftext|>


<commit_before>//
//  AsyncTaskQueue.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 07/10/2016.
//  Copyright 2016 Thomas Harte. All rights reserved.
//

#include "AsyncTaskQueue.hpp"

using namespace Concurrency;

AsyncTaskQueue::AsyncTaskQueue()
#ifndef USE_GCD
	: should_destruct_(false)
#endif
{
#ifdef USE_GCD
	serial_dispatch_queue_ = dispatch_queue_create("com.thomasharte.clocksignal.asyntaskqueue", DISPATCH_QUEUE_SERIAL);
#else
	thread_ = std::make_unique<std::thread>([this]() {
		while(!should_destruct_) {
			std::function<void(void)> next_function;

			// Take lock, check for a new task
			std::unique_lock lock(queue_mutex_);
			if(!pending_tasks_.empty()) {
				next_function = pending_tasks_.front();
				pending_tasks_.pop_front();
			}

			if(next_function) {
				// If there is a task, release lock and perform it
				lock.unlock();
				next_function();
			} else {
				// If there isn't a task, atomically block on the processing condition and release the lock
				// until there's something pending (and then release it again via scope)
				processing_condition_.wait(lock);
			}
		}
	});
#endif
}

AsyncTaskQueue::~AsyncTaskQueue() {
#ifdef USE_GCD
	flush();
	dispatch_release(serial_dispatch_queue_);
	serial_dispatch_queue_ = nullptr;
#else
	should_destruct_ = true;
	enqueue([](){});
	thread_->join();
	thread_.reset();
#endif
}

void AsyncTaskQueue::enqueue(std::function<void(void)> function) {
#ifdef USE_GCD
	dispatch_async(serial_dispatch_queue_, ^{function();});
#else
	std::lock_guard lock(queue_mutex_);
	pending_tasks_.push_back(function);
	processing_condition_.notify_all();
#endif
}

void AsyncTaskQueue::flush() {
#ifdef USE_GCD
	dispatch_sync(serial_dispatch_queue_, ^{});
#else
	auto flush_mutex = std::make_shared<std::mutex>();
	auto flush_condition = std::make_shared<std::condition_variable>();
	std::unique_lock lock(*flush_mutex);
	enqueue([=] () {
		std::unique_lock inner_lock(*flush_mutex);
		flush_condition->notify_all();
	});
	flush_condition->wait(lock);
#endif
}

DeferringAsyncTaskQueue::~DeferringAsyncTaskQueue() {
	perform();
	flush();
}

void DeferringAsyncTaskQueue::defer(std::function<void(void)> function) {
	if(!deferred_tasks_) {
		deferred_tasks_ = std::make_unique<std::list<std::function<void(void)>>>();
	}
	deferred_tasks_->push_back(function);
}

void DeferringAsyncTaskQueue::perform() {
	if(!deferred_tasks_) return;
	auto deferred_tasks_raw = deferred_tasks_.release();
	enqueue([deferred_tasks_raw] {
		std::unique_ptr<std::list<std::function<void(void)>>> deferred_tasks(deferred_tasks_raw);
		for(const auto &function : *deferred_tasks) {
			function();
		}
	});
}

void DeferringAsyncTaskQueue::flush() {
	perform();
	AsyncTaskQueue::flush();
}
<commit_msg>Further simplify syntax.<commit_after>//
//  AsyncTaskQueue.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 07/10/2016.
//  Copyright 2016 Thomas Harte. All rights reserved.
//

#include "AsyncTaskQueue.hpp"

using namespace Concurrency;

AsyncTaskQueue::AsyncTaskQueue()
#ifndef USE_GCD
	: should_destruct_(false)
#endif
{
#ifdef USE_GCD
	serial_dispatch_queue_ = dispatch_queue_create("com.thomasharte.clocksignal.asyntaskqueue", DISPATCH_QUEUE_SERIAL);
#else
	thread_ = std::make_unique<std::thread>([this]() {
		while(!should_destruct_) {
			std::function<void(void)> next_function;

			// Take lock, check for a new task
			std::unique_lock lock(queue_mutex_);
			if(!pending_tasks_.empty()) {
				next_function = pending_tasks_.front();
				pending_tasks_.pop_front();
			}

			if(next_function) {
				// If there is a task, release lock and perform it
				lock.unlock();
				next_function();
			} else {
				// If there isn't a task, atomically block on the processing condition and release the lock
				// until there's something pending (and then release it again via scope)
				processing_condition_.wait(lock);
			}
		}
	});
#endif
}

AsyncTaskQueue::~AsyncTaskQueue() {
#ifdef USE_GCD
	flush();
	dispatch_release(serial_dispatch_queue_);
	serial_dispatch_queue_ = nullptr;
#else
	should_destruct_ = true;
	enqueue([](){});
	thread_->join();
	thread_.reset();
#endif
}

void AsyncTaskQueue::enqueue(std::function<void(void)> function) {
#ifdef USE_GCD
	dispatch_async(serial_dispatch_queue_, ^{function();});
#else
	std::lock_guard lock(queue_mutex_);
	pending_tasks_.push_back(function);
	processing_condition_.notify_all();
#endif
}

void AsyncTaskQueue::flush() {
#ifdef USE_GCD
	dispatch_sync(serial_dispatch_queue_, ^{});
#else
	auto flush_mutex = std::make_shared<std::mutex>();
	auto flush_condition = std::make_shared<std::condition_variable>();
	std::unique_lock lock(*flush_mutex);
	enqueue([=] () {
		std::unique_lock inner_lock(*flush_mutex);
		flush_condition->notify_all();
	});
	flush_condition->wait(lock);
#endif
}

DeferringAsyncTaskQueue::~DeferringAsyncTaskQueue() {
	perform();
	flush();
}

void DeferringAsyncTaskQueue::defer(std::function<void(void)> function) {
	if(!deferred_tasks_) {
		deferred_tasks_ = std::make_unique<std::list<std::function<void(void)>>>();
	}
	deferred_tasks_->push_back(function);
}

void DeferringAsyncTaskQueue::perform() {
	if(!deferred_tasks_) return;
	enqueue([deferred_tasks_raw = deferred_tasks_.release()] {
		std::unique_ptr<std::list<std::function<void(void)>>> deferred_tasks(deferred_tasks_raw);
		for(const auto &function : *deferred_tasks) {
			function();
		}
	});
}

void DeferringAsyncTaskQueue::flush() {
	perform();
	AsyncTaskQueue::flush();
}
<|endoftext|>


<commit_before>#include <Windows.h>
#include <Commctrl.h>
#include <initguid.h>
#include <cguid.h>

#include "resource.h"

#include "GEKMath.h"
#include "GEKUtility.h"
#include "GEKContext.h"
#include "GEKEngine.h"

#include "GEKEngineCLSIDs.h"

static CGEKConfig kConfig;
INT_PTR CALLBACK DialogProc(HWND hDialog, UINT nMessage, WPARAM wParam, LPARAM lParam)
{
    switch (nMessage)
    {
    case WM_CLOSE:
        EndDialog(hDialog, IDCANCEL);
        return TRUE;

    case WM_INITDIALOG:
        {
            kConfig.Load(L"%root%\\config.cfg");

            UINT32 nSelectID = 0;
            SendDlgItemMessage(hDialog, IDC_MODES, CB_RESETCONTENT, 0, 0);
            std::vector<GEKMODE> akModes = GEKGetDisplayModes()[32];
            for(UINT32 nMode = 0; nMode < akModes.size(); ++nMode)
            {
                GEKMODE &kMode = akModes[nMode];

                CStringW strAspect(L"");
                switch (kMode.GetAspect())
                {
                case _ASPECT_4x3:
                    strAspect = L", (4x3)";
                    break;

                case _ASPECT_16x9:
                    strAspect = L", (16x9)";
                    break;

                case _ASPECT_16x10:
                    strAspect = L", (16x10)";
                    break;
                };

                CStringW strMode;
                strMode.Format(L"%dx%d%s", kMode.xsize, kMode.ysize, strAspect.GetString());
                int nID = SendDlgItemMessage(hDialog, IDC_MODES, CB_ADDSTRING, 0, (WPARAM)strMode.GetString());
                if (kMode.xsize == StrToUINT32(kConfig.GetValue(L"video", L"xsize", L"640")) &&
                    kMode.ysize == StrToUINT32(kConfig.GetValue(L"video", L"ysize", L"480")))
                {
                    nSelectID = nID;
                }
            }

            SendDlgItemMessage(hDialog, IDC_FULLSCREEN, BM_SETCHECK, (StrToUINT32(kConfig.GetValue(L"video", L"windowed", L"0")) ? BST_UNCHECKED : BST_CHECKED), 0);

            SendDlgItemMessage(hDialog, IDC_MODES, CB_SETMINVISIBLE, 5, 0);
            SendDlgItemMessage(hDialog, IDC_MODES, CB_SETEXTENDEDUI, TRUE, 0);
            SendDlgItemMessage(hDialog, IDC_MODES, CB_SETCURSEL, nSelectID, 0);
            return TRUE;
        }

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDOK:
            {
                std::vector<GEKMODE> akModes = GEKGetDisplayModes()[32];
                UINT32 nMode = SendDlgItemMessage(hDialog, IDC_MODES, CB_GETCURSEL, 0, 0);
                GEKMODE &kMode = akModes[nMode];

                kConfig.SetValue(L"video", L"xsize", L"%d", kMode.xsize);
                kConfig.SetValue(L"video", L"ysize", L"%d", kMode.ysize);
                kConfig.SetValue(L"video", L"windowed", (SendDlgItemMessage(hDialog, IDC_FULLSCREEN, BM_GETCHECK, 0, 0) == BST_CHECKED ? L"0" : L"1"));

                kConfig.Save(L"%root%\\config.cfg");

                EndDialog(hDialog, IDOK);
                return TRUE;
            }

        case IDCANCEL:
            EndDialog(hDialog, IDCANCEL);
            return TRUE;
        };

        return TRUE;
    };

    return FALSE;
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR strCommandLine, int nCmdShow)
{
    if (DialogBox(hInstance, MAKEINTRESOURCE(IDD_SETTINGS), nullptr, DialogProc) == IDOK)
    {
        CComPtr<IGEKContext> spContext;
        GEKCreateContext(&spContext);
        if (spContext)
        {
#ifdef _DEBUG
            SetCurrentDirectory(GEKParseFileName(L"%root%\\Debug"));
            spContext->AddSearchPath(GEKParseFileName(L"%root%\\Debug"));
#else
            SetCurrentDirectory(GEKParseFileName(L"%root%\\Release"));
            spContext->AddSearchPath(GEKParseFileName(L"%root%\\Release"));
#endif

            if (SUCCEEDED(spContext->Initialize()))
            {
                CComPtr<IGEKGameApplication> spGame;
                spContext->CreateInstance(CLSID_GEKEngine, IID_PPV_ARGS(&spGame));
                if (spGame)
                {
                    spGame->Run();
                }
            }
        }

        return 0;
    }

    return -1;
}<commit_msg>Trying to add templates<commit_after>#include <Windows.h>
#include <Commctrl.h>
#include <initguid.h>
#include <cguid.h>

#include "resource.h"

#include "GEKMath.h"
#include "GEKUtility.h"
#include "GEKContext.h"
#include "GEKEngine.h"

#include "GEKEngineCLSIDs.h"

static CGEKConfig kConfig;
INT_PTR CALLBACK DialogProc(HWND hDialog, UINT nMessage, WPARAM wParam, LPARAM lParam)
{
    switch (nMessage)
    {
    case WM_CLOSE:
        EndDialog(hDialog, IDCANCEL);
        return TRUE;

    case WM_INITDIALOG:
        {
            kConfig.Load(L"%root%\\config.cfg");

            UINT32 nSelectID = 0;
            SendDlgItemMessage(hDialog, IDC_MODES, CB_RESETCONTENT, 0, 0);
            std::vector<GEKMODE> akModes = GEKGetDisplayModes()[32];
            for(UINT32 nMode = 0; nMode < akModes.size(); ++nMode)
            {
                GEKMODE &kMode = akModes[nMode];

                CStringW strAspect(L"");
                switch (kMode.GetAspect())
                {
                case _ASPECT_4x3:
                    strAspect = L", (4x3)";
                    break;

                case _ASPECT_16x9:
                    strAspect = L", (16x9)";
                    break;

                case _ASPECT_16x10:
                    strAspect = L", (16x10)";
                    break;
                };

                CStringW strMode;
                strMode.Format(L"%dx%d%s", kMode.xsize, kMode.ysize, strAspect.GetString());
                int nID = SendDlgItemMessage(hDialog, IDC_MODES, CB_ADDSTRING, 0, (WPARAM)strMode.GetString());
                if (kMode.xsize == StrToUINT32(kConfig.GetValue(L"video", L"xsize", L"640")) &&
                    kMode.ysize == StrToUINT32(kConfig.GetValue(L"video", L"ysize", L"480")))
                {
                    nSelectID = nID;
                }
            }

            SendDlgItemMessage(hDialog, IDC_FULLSCREEN, BM_SETCHECK, (StrToUINT32(kConfig.GetValue(L"video", L"windowed", L"0")) ? BST_UNCHECKED : BST_CHECKED), 0);

            SendDlgItemMessage(hDialog, IDC_MODES, CB_SETMINVISIBLE, 5, 0);
            SendDlgItemMessage(hDialog, IDC_MODES, CB_SETEXTENDEDUI, TRUE, 0);
            SendDlgItemMessage(hDialog, IDC_MODES, CB_SETCURSEL, nSelectID, 0);
            return TRUE;
        }

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDOK:
            {
                std::vector<GEKMODE> akModes = GEKGetDisplayModes()[32];
                UINT32 nMode = SendDlgItemMessage(hDialog, IDC_MODES, CB_GETCURSEL, 0, 0);
                GEKMODE &kMode = akModes[nMode];

                kConfig.SetValue(L"video", L"xsize", L"%d", kMode.xsize);
                kConfig.SetValue(L"video", L"ysize", L"%d", kMode.ysize);
                kConfig.SetValue(L"video", L"windowed", (SendDlgItemMessage(hDialog, IDC_FULLSCREEN, BM_GETCHECK, 0, 0) == BST_CHECKED ? L"0" : L"1"));

                kConfig.Save(L"%root%\\config.cfg");

                EndDialog(hDialog, IDOK);
                return TRUE;
            }

        case IDCANCEL:
            EndDialog(hDialog, IDCANCEL);
            return TRUE;
        };

        return TRUE;
    };

    return FALSE;
}

template <class ... TYPES>
class TGEKComponent
{
private:
    CStringW m_strName;
    std::map<TYPES... args> m_aData;

public:
    TGEKComponent(LPCWSTR pName)
        : m_strName(pName)
    {
    }

    STDMETHODIMP_(LPCWSTR) GetName(void) const
    {
        return m_strName;
    }
};

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR strCommandLine, int nCmdShow)
{
    TGEKComponent<int, float> kTest(L"Test");
    CStringW strString = kTest.GetName();

    if (DialogBox(hInstance, MAKEINTRESOURCE(IDD_SETTINGS), nullptr, DialogProc) == IDOK)
    {
        CComPtr<IGEKContext> spContext;
        GEKCreateContext(&spContext);
        if (spContext)
        {
#ifdef _DEBUG
            SetCurrentDirectory(GEKParseFileName(L"%root%\\Debug"));
            spContext->AddSearchPath(GEKParseFileName(L"%root%\\Debug"));
#else
            SetCurrentDirectory(GEKParseFileName(L"%root%\\Release"));
            spContext->AddSearchPath(GEKParseFileName(L"%root%\\Release"));
#endif

            if (SUCCEEDED(spContext->Initialize()))
            {
                CComPtr<IGEKGameApplication> spGame;
                spContext->CreateInstance(CLSID_GEKEngine, IID_PPV_ARGS(&spGame));
                if (spGame)
                {
                    spGame->Run();
                }
            }
        }

        return 0;
    }

    return -1;
}<|endoftext|>


<commit_before>// RUN: %clangxx_tsan -O1 %s -o %t && %t
// Regtest for https://code.google.com/p/thread-sanitizer/issues/detail?id=40
// This is a correct program and tsan should not report a race.
#include <pthread.h>
#include <unistd.h>
int g;
__attribute__((noinline))
int foo(int cond) {
  if (cond)
    return g;
  return 0;
}
void *Thread1(void *p) {
  long res = foo((long)p);
  sleep(1);
  return (void*) res;
}

int main() {
  pthread_t t;
  pthread_create(&t, 0, Thread1, 0);
  g = 1;
  pthread_join(t, 0);
}
<commit_msg>[tsan] use FileCheck in race_on_speculative_load.cc<commit_after>// RUN: %clangxx_tsan -O1 %s -o %t && %t | FileCheck %s
// Regtest for https://code.google.com/p/thread-sanitizer/issues/detail?id=40
// This is a correct program and tsan should not report a race.
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
int g;
__attribute__((noinline))
int foo(int cond) {
  if (cond)
    return g;
  return 0;
}
void *Thread1(void *p) {
  long res = foo((long)p);
  sleep(1);
  return (void*) res;
}

int main() {
  pthread_t t;
  pthread_create(&t, 0, Thread1, 0);
  g = 1;
  pthread_join(t, 0);
  printf("PASS\n");
  // CHECK: PASS
}
<|endoftext|>


<commit_before>#include "WildMidi.h"

#ifdef HAVE_WILDMIDI

#include <array>
#include <cassert>

#include "../Utilities/Debug.h"

#include "components/vfs/manager.hpp"
#include "wildmidi_lib.h"

namespace
{
	int sInitState = -1;

	class WildMidiSong : public MidiSong {
		midi *mSong;

	public:
		WildMidiSong(midi *song);
		virtual ~WildMidiSong();

		virtual void getFormat(int *sampleRate) override;

		virtual size_t read(char *buffer, size_t count) override;

		virtual bool seek(size_t offset) override;
	};

	WildMidiSong::WildMidiSong(midi *song)
		: mSong(song) { }

	WildMidiSong::~WildMidiSong()
	{
		WildMidi_Close(mSong);
	}

	void WildMidiSong::getFormat(int *sampleRate)
	{
		/* Currently always outputs 16-bit stereo 48khz */
		*sampleRate = 48000;
	}

	size_t WildMidiSong::read(char *buffer, size_t count)
	{
		/* WildMidi wants bytes, so convert from and to sample frames. */
#if LIBWILDMIDI_VERSION >= ((0u << 16) | (4u << 8) | 0)
		return WildMidi_GetOutput(mSong, reinterpret_cast<int8_t*>(buffer),
			static_cast<uint32_t>(count * 4)) / 4;
#else
		return WildMidi_GetOutput(mSong, buffer, static_cast<unsigned long>(count * 4)) / 4;
#endif
	}

	bool WildMidiSong::seek(size_t offset)
	{
		unsigned long pos = static_cast<unsigned long>(offset);
		const int status = WildMidi_FastSeek(mSong, &pos);
		return status >= 0;
	}
}

WildMidiDevice::WildMidiDevice(const std::string &midiConfig)
{
	sInitState = WildMidi_Init(midiConfig.c_str(), 48000, WM_MO_ENHANCED_RESAMPLING);
	if (sInitState < 0)
		DebugWarning("Failed to init WildMIDI.");
	else
		WildMidi_MasterVolume(100);
}

WildMidiDevice::~WildMidiDevice()
{
	if (sInitState >= 0)
		WildMidi_Shutdown();
}

void WildMidiDevice::init(const std::string &midiConfig)
{
	sInstance = std::make_unique<WildMidiDevice>(midiConfig);
}

MidiSongPtr WildMidiDevice::open(const std::string &name)
{
	if (sInitState < 0)
		return MidiSongPtr(nullptr);

	VFS::IStreamPtr fstream = VFS::Manager::get().open(name.c_str());
	if (fstream == nullptr)
	{
		DebugWarning("Failed to open \"" + name + "\".");
		return MidiSongPtr(nullptr);
	}

	/* Read the file into a buffer through the VFS, as it may be in an archive
	 * that WildMidi can't read from.
	 */
	std::vector<char> midiBuffer;
	while (fstream->good())
	{
		std::array<char, 1024> readBuffer;
		fstream->read(readBuffer.data(), readBuffer.size());
		midiBuffer.insert(midiBuffer.end(), readBuffer.begin(),
			readBuffer.begin() + fstream->gcount());
	}

	midi *song = WildMidi_OpenBuffer(
		reinterpret_cast<unsigned char*>(midiBuffer.data()),
		static_cast<unsigned long>(midiBuffer.size()));

	return (song != nullptr) ? std::make_unique<WildMidiSong>(song) : nullptr;
}

#endif /* HAVE_WILDMIDI */
<commit_msg>Improved WildMIDI error reporting on init failure.<commit_after>#include "WildMidi.h"

#ifdef HAVE_WILDMIDI

#include <array>
#include <cassert>

#include "../Utilities/Debug.h"

#include "components/vfs/manager.hpp"
#include "wildmidi_lib.h"

namespace
{
	int sInitState = -1;

	class WildMidiSong : public MidiSong {
		midi *mSong;

	public:
		WildMidiSong(midi *song);
		virtual ~WildMidiSong();

		virtual void getFormat(int *sampleRate) override;

		virtual size_t read(char *buffer, size_t count) override;

		virtual bool seek(size_t offset) override;
	};

	WildMidiSong::WildMidiSong(midi *song)
		: mSong(song) { }

	WildMidiSong::~WildMidiSong()
	{
		WildMidi_Close(mSong);
	}

	void WildMidiSong::getFormat(int *sampleRate)
	{
		/* Currently always outputs 16-bit stereo 48khz */
		*sampleRate = 48000;
	}

	size_t WildMidiSong::read(char *buffer, size_t count)
	{
		/* WildMidi wants bytes, so convert from and to sample frames. */
#if LIBWILDMIDI_VERSION >= ((0u << 16) | (4u << 8) | 0)
		return WildMidi_GetOutput(mSong, reinterpret_cast<int8_t*>(buffer),
			static_cast<uint32_t>(count * 4)) / 4;
#else
		return WildMidi_GetOutput(mSong, buffer, static_cast<unsigned long>(count * 4)) / 4;
#endif
	}

	bool WildMidiSong::seek(size_t offset)
	{
		unsigned long pos = static_cast<unsigned long>(offset);
		const int status = WildMidi_FastSeek(mSong, &pos);
		return status >= 0;
	}
}

WildMidiDevice::WildMidiDevice(const std::string &midiConfig)
{
	sInitState = WildMidi_Init(midiConfig.c_str(), 48000, WM_MO_ENHANCED_RESAMPLING);
	if (sInitState < 0)
		DebugWarning("Failed to init WildMIDI with config \"" + midiConfig + "\".");
	else
		WildMidi_MasterVolume(100);
}

WildMidiDevice::~WildMidiDevice()
{
	if (sInitState >= 0)
		WildMidi_Shutdown();
}

void WildMidiDevice::init(const std::string &midiConfig)
{
	sInstance = std::make_unique<WildMidiDevice>(midiConfig);
}

MidiSongPtr WildMidiDevice::open(const std::string &name)
{
	if (sInitState < 0)
		return MidiSongPtr(nullptr);

	VFS::IStreamPtr fstream = VFS::Manager::get().open(name.c_str());
	if (fstream == nullptr)
	{
		DebugWarning("Failed to open \"" + name + "\".");
		return MidiSongPtr(nullptr);
	}

	/* Read the file into a buffer through the VFS, as it may be in an archive
	 * that WildMidi can't read from.
	 */
	std::vector<char> midiBuffer;
	while (fstream->good())
	{
		std::array<char, 1024> readBuffer;
		fstream->read(readBuffer.data(), readBuffer.size());
		midiBuffer.insert(midiBuffer.end(), readBuffer.begin(),
			readBuffer.begin() + fstream->gcount());
	}

	midi *song = WildMidi_OpenBuffer(
		reinterpret_cast<unsigned char*>(midiBuffer.data()),
		static_cast<unsigned long>(midiBuffer.size()));

	return (song != nullptr) ? std::make_unique<WildMidiSong>(song) : nullptr;
}

#endif /* HAVE_WILDMIDI */
<|endoftext|>


<commit_before><commit_msg>fdo#65483 Invalid po lines caused missing translations<commit_after><|endoftext|>


<commit_before>#include "delta.hpp"

//////////////
// Includes //
#include <chrono>

//////////
// Code //

// Getting the current system time in milliseconds.
int getTimeMillis() {
    auto now = std::chrono::system_clock::now();
    return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}

//// A utility to do some delta timing stuff.
//class Delta {
//private:
    //int last, curr;
    //bool first;

//public:

// Constructing a delta.
Delta::Delta() {
    this->last = 0;
    this->curr = 0;
    this->first = true;
}

// Getting the time since the last time this was run.
float Delta::since() {
    curr = getTimeMillis();
    float dt = (curr - last) / 1000.f;
    last = curr;

    if (this->first) {
        this->first = false;
        return 0;
    }

    return dt;
}

//};
<commit_msg>Cleaned up the CPPs<commit_after>#include "delta.hpp"

//////////////
// Includes //
#include <chrono>

//////////
// Code //

// Getting the current system time in milliseconds.
int getTimeMillis() {
    auto now = std::chrono::system_clock::now();
    return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
}

// Constructing a delta.
Delta::Delta() {
    this->last = 0;
    this->curr = 0;
    this->first = true;
}

// Getting the time since the last time this was run.
float Delta::since() {
    curr = getTimeMillis();
    float dt = (curr - last) / 1000.f;
    last = curr;

    if (this->first) {
        this->first = false;
        return 0;
    }

    return dt;
}
<|endoftext|>


<commit_before>#include <PCU.h>
#include "phRestart.h"
#include <apf.h>
#include "phIO.h"
#include "ph.h"
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cassert>
#include <cstring>

namespace ph {

/* in_size is the number of dofs for the data array
   and out_size is the number of dofs in the field.
   they are unequal when we read a restart file
   and want to add more dofs for the next restart files */

void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int in_size,
    int out_size)
{
  if (!(in_size <= out_size))
    fprintf(stderr, "field \"%s\" in_size %d out_size %d\n", fieldname, in_size, out_size);
  assert(in_size <= out_size);
  apf::Field* f = apf::createPackedField(m, fieldname, out_size);
  size_t n = m->count(0);
  apf::NewArray<double> c(out_size);
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    for (int j = 0; j < in_size; ++j)
      c[j] = data[j * n + i];
    apf::setComponents(f, e, 0, &c[0]);
    ++i;
  }
  m->end(it);
  assert(i == n);
}

/* convenience wrapper, in most cases in_size=out_size */
void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int size)
{
  attachField(m, fieldname, data, size, size);
}

void detachField(
    apf::Field* f,
    double*& data,
    int& size)
{
  apf::Mesh* m = apf::getMesh(f);
  size = apf::countComponents(f);
  size_t n = m->count(0);
  apf::NewArray<double> c(size);
  data = (double*)malloc(sizeof(double) * size * m->count(0));
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    apf::getComponents(f, e, 0, &c[0]);
    for (int j = 0; j < size; ++j)
      data[j * n + i] = c[j];
    ++i;
  }
  m->end(it);
  assert(i == n);
  apf::destroyField(f);
}

void detachField(
    apf::Mesh* m,
    const char* fieldname,
    double*& data,
    int& size)
{
  apf::Field* f = m->findField(fieldname);
  assert(f);
  detachField(f, data, size);
}

static bool isNodalField(const char* fieldname, int nnodes, apf::Mesh* m)
{
  static char const* const known_nodal_fields[] = {
    "solution",
    "displacement",
    "dwal",
    "mapping_partid",
    "mapping_vtxid",
    "errors",
    "time derivative of solution"
  };
  static char const* const known_cell_fields[] = {
    "VOF solution",
  };
  int known_nodal_field_count =
    sizeof(known_nodal_fields) / sizeof(known_nodal_fields[0]);
  int known_cell_field_count =
    sizeof(known_cell_fields) / sizeof(known_cell_fields[0]);
  for (int i = 0; i < known_nodal_field_count; ++i)
    if (!strcmp(fieldname, known_nodal_fields[i])) {
      assert(static_cast<size_t>(nnodes) == m->count(0));
      return true;
    }
  for (int i = 0; i < known_cell_field_count; ++i)
    if (!strcmp(fieldname, known_cell_fields[i]))
      return false;
  fprintf(stderr, "unknown restart field name \"%s\"\n", fieldname);
  fprintf(stderr, "please add \"%s\" to isNodalField above line %d of %s\n",
      fieldname, __LINE__, __FILE__);
  if (static_cast<size_t>(nnodes) == m->count(0)) {
    fprintf(stderr, "assuming \"%s\" is a nodal field,\n"
                    "it is the right size...\n", fieldname);
    return true;
  }
  return false;
}

int readAndAttachField(
    Input& in,
    FILE* f,
    apf::Mesh* m,
    int swap)
{
  double* data;
  int nodes, vars, step;
  char hname[1024];
  const char* anyfield = "";
  int ret = ph_read_field(f, anyfield, swap,
      &data, &nodes, &vars, &step, hname);
  /* no field was found or the field has an empty data block */
  if(ret==0 || ret==1)
    return ret;
  if (!isNodalField(hname, nodes, m)) {
    free(data);
    return 1;
  }
  assert(step == in.timeStepNumber);
  int out_size = vars;
  if ( std::string(hname) == std::string("solution") )
    out_size = in.ensa_dof;
  if (m->findField(hname)) {
    if (!PCU_Comm_Self())
      fprintf(stderr, "field \"%s\" listed twice in restart files, ignoring...\n",
          hname);
  } else {
    attachField(m, hname, data, vars, out_size);
  }
  free(data);
  return 1;
}

void detachAndWriteField(
    Input& in,
    apf::Mesh* m,
    FILE* f,
    const char* fieldname)
{
  double* data;
  int size;
  detachField(m, fieldname, data, size);
  ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);
  free(data);
}

/* silliest darn fields I ever did see */
static double* buildMappingPartId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  int self = PCU_Comm_Self();
  for (int i = 0; i < n; ++i)
    data[i] = self;
  return data;
}
static double* buildMappingVtxId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  for (int i = 0; i < n; ++i)
    data[i] = i;
  return data;
}

static std::string buildRestartFileName(std::string prefix, int step)
{
  std::stringstream ss;
  int rank = PCU_Comm_Self() + 1;
  ss << prefix << '.' << step << '.' << rank;
  return ss.str();
}

void readAndAttachFields(Input& in, apf::Mesh* m) {
  double t0 = PCU_Time();
  setupInputSubdir(in.restartFileName);
  std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);
  FILE* f = in.openfile_read(in, filename.c_str());
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", filename.c_str());
    abort();
  }
  int swap = ph_should_swap(f);
  /* stops when ph_read_field returns 0 */
  while( readAndAttachField(in,f,m,swap) );
  fclose(f);
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("fields read and attached in %f seconds\n", t1 - t0);
}

static void destroyIfExists(apf::Mesh* m, const char* name)
{
  apf::Field* f = m->findField(name);
  if (f)
    apf::destroyField(f);
}

void buildMapping(apf::Mesh* m)
{
  destroyIfExists(m, "mapping_partid");
  double* mapping = buildMappingPartId(m);
  attachField(m, "mapping_partid", mapping, 1);
  free(mapping);
  destroyIfExists(m, "mapping_vtxid");
  mapping = buildMappingVtxId(m);
  attachField(m, "mapping_vtxid", mapping, 1);
  free(mapping);
}

void attachZeroSolution(Input& in, apf::Mesh* m)
{
  int vars = in.ensa_dof;
  int nodes = m->count(0);
  double* data = new double[nodes * vars]();
  attachField(m, "solution", data, vars);
  delete [] data;
}

void detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)
{
  double t0 = PCU_Time();
  path += buildRestartFileName("restart", in.timeStepNumber);
  FILE* f = out.openfile_write(out, path.c_str());
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", path.c_str());
    abort();
  }
  ph_write_preamble(f);
  int nodes = m->count(0);
  ph_write_header(f, "number of modes", 0, 1, &nodes);
  ph_write_header(f, "number of variables", 0, 1, &in.ensa_dof);
  apf::Field* errField = m->findField("errors");
  if (errField)
    apf::destroyField(errField);
  if (m->findField("solution"))
    detachAndWriteField(in, m, f, "solution");
  if (in.displacementMigration)
    detachAndWriteField(in, m, f, "displacement");
  if (in.dwalMigration)
    detachAndWriteField(in, m, f, "dwal");
  if (in.buildMapping) {
    detachAndWriteField(in, m, f, "mapping_partid");
    detachAndWriteField(in, m, f, "mapping_vtxid");
  }
  /* detach any remaining fields */
  while(m->countFields())
    apf::destroyField( m->getField(0) );
  fclose(f);
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("solution written in %f seconds\n", t1 - t0);
}

}
<commit_msg>destroy the existing field when creating a new one<commit_after>#include <PCU.h>
#include "phRestart.h"
#include <apf.h>
#include <apfField.h>
#include "phIO.h"
#include "ph.h"
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cassert>
#include <cstring>

namespace ph {

/* in_size is the number of dofs for the data array
   and out_size is the number of dofs in the field.
   they are unequal when we read a restart file
   and want to add more dofs for the next restart files */

void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int in_size,
    int out_size)
{
  if (!(in_size <= out_size))
    fprintf(stderr, "field \"%s\" in_size %d out_size %d\n", fieldname, in_size, out_size);
  assert(in_size <= out_size);
  apf::Field* f = m->findField(fieldname);
  if( f )
    apf::destroyField(f);
  f = apf::createPackedField(m, fieldname, out_size);
  size_t n = m->count(0);
  apf::NewArray<double> c(out_size);
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    for (int j = 0; j < in_size; ++j)
      c[j] = data[j * n + i];
    apf::setComponents(f, e, 0, &c[0]);
    ++i;
  }
  m->end(it);
  assert(i == n);
}

/* convenience wrapper, in most cases in_size=out_size */
void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int size)
{
  attachField(m, fieldname, data, size, size);
}

void detachField(
    apf::Field* f,
    double*& data,
    int& size)
{
  apf::Mesh* m = apf::getMesh(f);
  size = apf::countComponents(f);
  size_t n = m->count(0);
  apf::NewArray<double> c(size);
  data = (double*)malloc(sizeof(double) * size * m->count(0));
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    apf::getComponents(f, e, 0, &c[0]);
    for (int j = 0; j < size; ++j)
      data[j * n + i] = c[j];
    ++i;
  }
  m->end(it);
  assert(i == n);
  apf::destroyField(f);
}

void detachField(
    apf::Mesh* m,
    const char* fieldname,
    double*& data,
    int& size)
{
  apf::Field* f = m->findField(fieldname);
  assert(f);
  detachField(f, data, size);
}

static bool isNodalField(const char* fieldname, int nnodes, apf::Mesh* m)
{
  static char const* const known_nodal_fields[] = {
    "solution",
    "displacement",
    "dwal",
    "mapping_partid",
    "mapping_vtxid",
    "errors",
    "time derivative of solution"
  };
  static char const* const known_cell_fields[] = {
    "VOF solution",
  };
  int known_nodal_field_count =
    sizeof(known_nodal_fields) / sizeof(known_nodal_fields[0]);
  int known_cell_field_count =
    sizeof(known_cell_fields) / sizeof(known_cell_fields[0]);
  for (int i = 0; i < known_nodal_field_count; ++i)
    if (!strcmp(fieldname, known_nodal_fields[i])) {
      assert(static_cast<size_t>(nnodes) == m->count(0));
      return true;
    }
  for (int i = 0; i < known_cell_field_count; ++i)
    if (!strcmp(fieldname, known_cell_fields[i]))
      return false;
  fprintf(stderr, "unknown restart field name \"%s\"\n", fieldname);
  fprintf(stderr, "please add \"%s\" to isNodalField above line %d of %s\n",
      fieldname, __LINE__, __FILE__);
  if (static_cast<size_t>(nnodes) == m->count(0)) {
    fprintf(stderr, "assuming \"%s\" is a nodal field,\n"
                    "it is the right size...\n", fieldname);
    return true;
  }
  return false;
}

int readAndAttachField(
    Input& in,
    FILE* f,
    apf::Mesh* m,
    int swap)
{
  double* data;
  int nodes, vars, step;
  char hname[1024];
  const char* anyfield = "";
  int ret = ph_read_field(f, anyfield, swap,
      &data, &nodes, &vars, &step, hname);
  /* no field was found or the field has an empty data block */
  if(ret==0 || ret==1)
    return ret;
  if (!isNodalField(hname, nodes, m)) {
    free(data);
    return 1;
  }
  assert(step == in.timeStepNumber);
  int out_size = vars;
  if ( std::string(hname) == std::string("solution") )
    out_size = in.ensa_dof;
  if (m->findField(hname)) {
    if (!PCU_Comm_Self())
      fprintf(stderr, "field \"%s\" listed twice in restart files, ignoring...\n",
          hname);
  } else {
    attachField(m, hname, data, vars, out_size);
  }
  free(data);
  return 1;
}

void detachAndWriteField(
    Input& in,
    apf::Mesh* m,
    FILE* f,
    const char* fieldname)
{
  double* data;
  int size;
  detachField(m, fieldname, data, size);
  ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);
  free(data);
}

/* silliest darn fields I ever did see */
static double* buildMappingPartId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  int self = PCU_Comm_Self();
  for (int i = 0; i < n; ++i)
    data[i] = self;
  return data;
}
static double* buildMappingVtxId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  for (int i = 0; i < n; ++i)
    data[i] = i;
  return data;
}

static std::string buildRestartFileName(std::string prefix, int step)
{
  std::stringstream ss;
  int rank = PCU_Comm_Self() + 1;
  ss << prefix << '.' << step << '.' << rank;
  return ss.str();
}

void readAndAttachFields(Input& in, apf::Mesh* m) {
  double t0 = PCU_Time();
  setupInputSubdir(in.restartFileName);
  std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);
  FILE* f = in.openfile_read(in, filename.c_str());
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", filename.c_str());
    abort();
  }
  int swap = ph_should_swap(f);
  /* stops when ph_read_field returns 0 */
  while( readAndAttachField(in,f,m,swap) );
  fclose(f);
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("fields read and attached in %f seconds\n", t1 - t0);
}

static void destroyIfExists(apf::Mesh* m, const char* name)
{
  apf::Field* f = m->findField(name);
  if (f)
    apf::destroyField(f);
}

void buildMapping(apf::Mesh* m)
{
  destroyIfExists(m, "mapping_partid");
  double* mapping = buildMappingPartId(m);
  attachField(m, "mapping_partid", mapping, 1);
  free(mapping);
  destroyIfExists(m, "mapping_vtxid");
  mapping = buildMappingVtxId(m);
  attachField(m, "mapping_vtxid", mapping, 1);
  free(mapping);
}

void attachZeroSolution(Input& in, apf::Mesh* m)
{
  int vars = in.ensa_dof;
  int nodes = m->count(0);
  double* data = new double[nodes * vars]();
  attachField(m, "solution", data, vars);
  delete [] data;
}

void detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)
{
  double t0 = PCU_Time();
  path += buildRestartFileName("restart", in.timeStepNumber);
  FILE* f = out.openfile_write(out, path.c_str());
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", path.c_str());
    abort();
  }
  ph_write_preamble(f);
  int nodes = m->count(0);
  ph_write_header(f, "number of modes", 0, 1, &nodes);
  ph_write_header(f, "number of variables", 0, 1, &in.ensa_dof);
  apf::Field* errField = m->findField("errors");
  if (errField)
    apf::destroyField(errField);
  if (m->findField("solution"))
    detachAndWriteField(in, m, f, "solution");
  if (in.displacementMigration)
    detachAndWriteField(in, m, f, "displacement");
  if (in.dwalMigration)
    detachAndWriteField(in, m, f, "dwal");
  if (in.buildMapping) {
    detachAndWriteField(in, m, f, "mapping_partid");
    detachAndWriteField(in, m, f, "mapping_vtxid");
  }
  /* detach any remaining fields */
  while(m->countFields())
    apf::destroyField( m->getField(0) );
  fclose(f);
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("solution written in %f seconds\n", t1 - t0);
}

}
<|endoftext|>


<commit_before>//=====================================================================//
/*! @file
    @brief  ファースト・サンプル（LED 点滅） @n
			RX64M, RX71M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/format.hpp"
#include "common/cmt_io.hpp"

#include "common/fixed_string.hpp"

/// #include <iostream>

namespace {

#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX71M" };
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX64M" };
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
	typedef device::SCI9 SCI_CH;
	static const char* system_str_ = { "RX65N" };
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX24T" };
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX66T" };
#endif

	typedef utils::fixed_fifo<char, 512> RXB;  // RX (RECV) バッファの定義
	typedef utils::fixed_fifo<char, 256> TXB;  // TX (SEND) バッファの定義

	typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
// SCI ポートの第二候補を選択する場合
//	typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::option::SECOND> SCI;
	SCI		sci_;

	device::cmt_io<device::CMT0, utils::null_task>  cmt_;
}

extern "C" {

	// syscalls.c から呼ばれる、標準出力（stdout, stderr）
	void sci_putch(char ch)
	{
		sci_.putch(ch);
	}

	void sci_puts(const char* str)
	{
		sci_.puts(str);
	}

	// syscalls.c から呼ばれる、標準入力（stdin）
	char sci_getch(void)
	{
		return sci_.getch();
	}

	uint16_t sci_length()
	{
		return sci_.recv_length();
	}
}

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

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	{  // タイマー設定（100Hz）
		uint8_t intr = 4;
		cmt_.start(100, intr);
	}

	{  // SCI の開始
		uint8_t intr = 2;        // 割り込みレベル
		uint32_t baud = 115200;  // ボーレート
		sci_.start(baud, intr);
	}

///	auto iclk = F_ICLK / 1000000;
///	utils::format("Start test for '%s' %d[MHz]\n") % system_str_ % iclk;

///

#if 0
	utils::STR16 str;

	str = "asdfg";

	for(const auto ch : str) {
		utils::format("%c") % ch;
	}
	utils::format("\n");

	utils::STR16 a("012");
	utils::STR16 b("013");

	utils::format("a: '%s'\n") % a.c_str();
	utils::format("b: '%s'\n") % b.c_str();
	{
		int a_eq_b = a == b;
		utils::format("a.EQ.b: %d\n") % a_eq_b;
	}
	{
		int a_eq_b = a == "013";
		utils::format("a.EQ.\"013\": %d\n") % a_eq_b;
	}

	int a_lt_b = a < b;
	utils::format("a.LT.b: %d\n") % a_lt_b;

	int a_gt_b = a > b;
	utils::format("a.GT.b: %d\n") % a_gt_b;

//	if(a > b) utils::format("a < b: %d\n") % (a > b);
#endif

///	std::cout << "Hello!" << std::endl;
	utils::format("Hello!\n");
///	printf("Hello!\n");

#if 0
	LED::OUTPUT();  // LED ポートを出力に設定
	uint8_t cnt = 0;
	while(1) {
		cmt_.sync();

		++cnt;
		if(cnt >= 50) {
			cnt = 0;
		}
		if(cnt < 25) {
			LED::P = 0;
		} else {
			LED::P = 1;
		}
	}
#endif

	while(1) ;
}
<commit_msg>Update: cleanup<commit_after>//=====================================================================//
/*! @file
    @brief  ファースト・サンプル（LED 点滅） @n
			RX64M, RX71M: @n
					12MHz のベースクロックを使用する @n
			　　　　P07 ピンにLEDを接続する @n
			RX65N (Renesas Envision kit RX65N): @n
					12MHz のベースクロックを使用する @n
			　　　　P70 に接続された LED を利用する @n
			RX63T @n
					12MHz のベースクロックを使用する @n
					PB7 に接続された LED を利用する @n
			RX24T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する @n
			RX66T: @n
					10MHz のベースクロックを使用する @n
			　　　　P00 ピンにLEDを接続する
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/fixed_fifo.hpp"
#include "common/sci_io.hpp"
#include "common/format.hpp"
#include "common/cmt_io.hpp"

#include "common/fixed_string.hpp"

/// #include <iostream>

namespace {

#if defined(SIG_RX71M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX71M" };
#elif defined(SIG_RX64M)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B7> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX64M" };
#elif defined(SIG_RX65N)
	typedef device::system_io<12000000> SYSTEM_IO;
	typedef device::PORT<device::PORT7, device::bitpos::B0> LED;
	typedef device::SCI9 SCI_CH;
	static const char* system_str_ = { "RX65N" };
#elif defined(SIG_RX24T)
	typedef device::system_io<10000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX24T" };
#elif defined(SIG_RX66T)
	typedef device::system_io<10000000, 160000000> SYSTEM_IO;
	typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
	typedef device::SCI1 SCI_CH;
	static const char* system_str_ = { "RX66T" };
#endif

	typedef utils::fixed_fifo<char, 512> RXB;  // RX (RECV) バッファの定義
	typedef utils::fixed_fifo<char, 256> TXB;  // TX (SEND) バッファの定義

	typedef device::sci_io<SCI_CH, RXB, TXB> SCI;
// SCI ポートの第二候補を選択する場合
//	typedef device::sci_io<SCI_CH, RXB, TXB, device::port_map::option::SECOND> SCI;
	SCI		sci_;

	device::cmt_io<device::CMT0, utils::null_task>  cmt_;

}

extern "C" {

	// syscalls.c から呼ばれる、標準出力（stdout, stderr）
	void sci_putch(char ch)
	{
		sci_.putch(ch);
	}

	void sci_puts(const char* str)
	{
		sci_.puts(str);
	}

	// syscalls.c から呼ばれる、標準入力（stdin）
	char sci_getch(void)
	{
		return sci_.getch();
	}

	uint16_t sci_length()
	{
		return sci_.recv_length();
	}
}

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

int main(int argc, char** argv)
{
	SYSTEM_IO::setup_system_clock();

	{  // タイマー設定（100Hz）
		uint8_t intr = 4;
		cmt_.start(100, intr);
	}

	{  // SCI の開始
		uint8_t intr = 2;        // 割り込みレベル
		uint32_t baud = 115200;  // ボーレート
		sci_.start(baud, intr);
	}

///	auto iclk = F_ICLK / 1000000;
///	utils::format("Start test for '%s' %d[MHz]\n") % system_str_ % iclk;

///

#if 0
	utils::STR16 str;

	str = "asdfg";

	for(const auto ch : str) {
		utils::format("%c") % ch;
	}
	utils::format("\n");

	utils::STR16 a("012");
	utils::STR16 b("013");

	utils::format("a: '%s'\n") % a.c_str();
	utils::format("b: '%s'\n") % b.c_str();
	{
		int a_eq_b = a == b;
		utils::format("a.EQ.b: %d\n") % a_eq_b;
	}
	{
		int a_eq_b = a == "013";
		utils::format("a.EQ.\"013\": %d\n") % a_eq_b;
	}

	int a_lt_b = a < b;
	utils::format("a.LT.b: %d\n") % a_lt_b;

	int a_gt_b = a > b;
	utils::format("a.GT.b: %d\n") % a_gt_b;

//	if(a > b) utils::format("a < b: %d\n") % (a > b);
#endif

///	std::cout << "Hello!" << std::endl;
	utils::format("Hello!\n");
///	printf("Hello!\n");

#if 0
	LED::OUTPUT();  // LED ポートを出力に設定
	uint8_t cnt = 0;
	while(1) {
		cmt_.sync();

		++cnt;
		if(cnt >= 50) {
			cnt = 0;
		}
		if(cnt < 25) {
			LED::P = 0;
		} else {
			LED::P = 1;
		}
	}
#endif

	while(1) ;
}
<|endoftext|>


<commit_before>/**
 * @file transformer.cpp
 */

#include "transformer.h"
#include "forecast_time.h"
#include "json_parser.h"
#include "level.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include "util.h"
#include <boost/lexical_cast.hpp>

#include "fetcher.h"

using namespace std;
using namespace himan::plugin;

#include "cuda_helper.h"

transformer::transformer()
    : itsBase(0.0),
      itsScale(1.0),
      itsTargetUnivID(9999),
      itsApplyLandSeaMask(false),
      itsLandSeaMaskThreshold(0.5),
      itsInterpolationMethod(kUnknownInterpolationMethod)
{
	itsClearTextFormula = "target_param = source_param * itsScale + itsBase";
	itsCudaEnabledCalculation = true;

	itsLogger = logger_factory::Instance()->GetLog("transformer");
}

vector<himan::level> transformer::LevelsFromString(const string& levelType, const string& levelValues) const
{
	HPLevelType theLevelType = HPStringToLevelType.at(boost::to_lower_copy(levelType));

	vector<string> levelsStr = util::Split(levelValues, ",", true);

	vector<level> levels;

	for (size_t i = 0; i < levelsStr.size(); i++)
	{
		levels.push_back(level(theLevelType, boost::lexical_cast<float>(levelsStr[i]), levelType));
	}

	return levels;
}

void transformer::SetAdditionalParameters()
{
	std::string itsSourceLevelType;
	std::string SourceLevels;

	if (!itsConfiguration->GetValue("base").empty())
	{
		itsBase = boost::lexical_cast<double>(itsConfiguration->GetValue("base"));
	}
	else
	{
		itsLogger->Warning("Base not specified, using default value 0.0");
	}

	if (!itsConfiguration->GetValue("scale").empty())
	{
		itsScale = boost::lexical_cast<double>(itsConfiguration->GetValue("scale"));
	}
	else
	{
		itsLogger->Warning("Scale not specified, using default value 1.0");
	}

	if (!itsConfiguration->GetValue("target_univ_id").empty())
	{
		itsTargetUnivID = boost::lexical_cast<int>(itsConfiguration->GetValue("target_univ_id"));
	}
	else
	{
		itsLogger->Warning("Target_univ_id not specified, using default value 9999");
	}

	if (!itsConfiguration->GetValue("target_param").empty())
	{
		itsTargetParam = itsConfiguration->GetValue("target_param");
	}
	else
	{
		throw runtime_error("Transformer_plugin: target_param not specified.");
	}

	if (!itsConfiguration->GetValue("source_param").empty())
	{
		itsSourceParam = itsConfiguration->GetValue("source_param");
	}
	else
	{
		itsSourceParam = itsTargetParam;
		itsLogger->Warning("Source_param not specified, source_param set to target_param");
	}

	if (!itsConfiguration->GetValue("source_level_type").empty())
	{
		itsSourceLevelType = itsConfiguration->GetValue("source_level_type");
	}
	else
	{
		throw runtime_error("Transformer_plugin: source_level_type not specified.");
	}

	if (!itsConfiguration->GetValue("source_levels").empty())
	{
		SourceLevels = itsConfiguration->GetValue("source_levels");
	}
	else
	{
		throw runtime_error("Transformer_plugin: source_level_type not specified.");
	}

	// Check apply land sea mask parameter

	if (itsConfiguration->Exists("apply_landsea_mask") && itsConfiguration->GetValue("apply_landsea_mask") == "true")
	{
		itsApplyLandSeaMask = true;

		// Check for optional threshold parameter
		if (itsConfiguration->Exists("landsea_mask_threshold"))
		{
			itsLandSeaMaskThreshold = boost::lexical_cast<double>(itsConfiguration->GetValue("landsea_mask_threshold"));
		}
	}

	if (itsConfiguration->Exists("interpolation"))
	{
		itsInterpolationMethod = HPStringToInterpolationMethod.at(itsConfiguration->GetValue("interpolation"));
	}

	// looks useful to use this function to create source_levels
	itsSourceLevels = LevelsFromString(itsSourceLevelType, SourceLevels);
}

void transformer::Process(std::shared_ptr<const plugin_configuration> conf)
{
	Init(conf);
	SetAdditionalParameters();

	/*
	 * Set target parameter to T
	 * - name T-C
	 * - univ_id 4
	 * - grib2 descriptor 0'00'000
	 *
	 * We need to specify grib and querydata parameter information
	 * since we don't know which one will be the output format.
	 *
	 */

	vector<param> theParams;

	param requestedParam(itsTargetParam, itsTargetUnivID);

	// GRIB 2
	if (itsConfiguration->OutputFileType() == kGRIB2)
	{
		if (!itsConfiguration->GetValue("grib_discipline").empty() &&
		    !itsConfiguration->GetValue("grib_category").empty() &&
		    !itsConfiguration->GetValue("grib_parameter").empty())
		{
			requestedParam.GribDiscipline(boost::lexical_cast<int>(itsConfiguration->GetValue("grib_discipline")));
			requestedParam.GribCategory(boost::lexical_cast<int>(itsConfiguration->GetValue("grib_category")));
			requestedParam.GribParameter(boost::lexical_cast<int>(itsConfiguration->GetValue("grib_parameter")));
		}
		else
		{
			throw runtime_error(
			    "Transformer_plugin: Grib2 output requested but Grib2 parameter specifiers for output parameter not "
			    "given in json file.");
		}
	}

	if (itsInterpolationMethod != kUnknownInterpolationMethod)
	{
		requestedParam.InterpolationMethod(itsInterpolationMethod);
	}

	theParams.push_back(requestedParam);

	SetParams(theParams);

	Start();
}

/*
 * Calculate()
 *
 * This function does the actual calculation.
 */

void transformer::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
	// Required source parameter

	param InputParam(itsSourceParam);

	auto myThreadedLogger =
	    logger_factory::Instance()->GetLog("transformerThread #" + boost::lexical_cast<string>(threadIndex));

	forecast_time forecastTime = myTargetInfo->Time();
	level forecastLevel = myTargetInfo->Level();
	forecast_type forecastType = myTargetInfo->ForecastType();

	myThreadedLogger->Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " +
	                       static_cast<string>(forecastLevel));

	auto f = GET_PLUGIN(fetcher);

	if (itsApplyLandSeaMask)
	{
		f->ApplyLandSeaMask(true);
		f->LandSeaMaskThreshold(itsLandSeaMaskThreshold);
	}

	info_t sourceInfo;

	try
	{
		sourceInfo = f->Fetch(itsConfiguration, forecastTime, itsSourceLevels[myTargetInfo->LevelIndex()], InputParam,
		                      forecastType, itsConfiguration->UseCudaForPacking());
	}
	catch (HPExceptionType& e)
	{
		myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " +
		                          static_cast<string>(forecastLevel));
		return;
	}

	SetAB(myTargetInfo, sourceInfo);

	bool levelOnly = (itsScale == 1.0 && itsBase == 0.0);

	string deviceType;

#ifdef HAVE_CUDA

	if (itsConfiguration->UseCuda() && !levelOnly)
	{
		deviceType = "GPU";

		auto opts = CudaPrepare(myTargetInfo, sourceInfo);

		transformer_cuda::Process(*opts);
	}
	else
#endif
	{
		deviceType = "CPU";

		LOCKSTEP(myTargetInfo, sourceInfo)
		{
			double value = sourceInfo->Value();

			if (value == kFloatMissing)
			{
				continue;
			}

			if (!levelOnly)
			{
				double newValue = value * itsScale + itsBase;

				myTargetInfo->Value(newValue);
			}
			else
			{
				myTargetInfo->Value(value);
			}
		}
	}

	myThreadedLogger->Info("[" + deviceType + "] Missing values: " +
	                       boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" +
	                       boost::lexical_cast<string>(myTargetInfo->Data().Size()));
}

#ifdef HAVE_CUDA

unique_ptr<transformer_cuda::options> transformer::CudaPrepare(shared_ptr<info> myTargetInfo,
                                                               shared_ptr<info> sourceInfo)
{
	unique_ptr<transformer_cuda::options> opts(new transformer_cuda::options);

	opts->N = sourceInfo->Data().Size();

	opts->base = itsBase;
	opts->scale = itsScale;

	opts->source = sourceInfo->ToSimple();
	opts->dest = myTargetInfo->ToSimple();

	return opts;
}
#endif
<commit_msg>Relax transformer input requirements<commit_after>/**
 * @file transformer.cpp
 */

#include "transformer.h"
#include "forecast_time.h"
#include "json_parser.h"
#include "level.h"
#include "logger_factory.h"
#include "plugin_factory.h"
#include "util.h"
#include <boost/lexical_cast.hpp>

#include "fetcher.h"

using namespace std;
using namespace himan::plugin;

#include "cuda_helper.h"

transformer::transformer()
    : itsBase(0.0),
      itsScale(1.0),
      itsTargetUnivID(9999),
      itsApplyLandSeaMask(false),
      itsLandSeaMaskThreshold(0.5),
      itsInterpolationMethod(kUnknownInterpolationMethod)
{
	itsClearTextFormula = "target_param = source_param * itsScale + itsBase";
	itsCudaEnabledCalculation = true;

	itsLogger = logger_factory::Instance()->GetLog("transformer");
}

vector<himan::level> transformer::LevelsFromString(const string& levelType, const string& levelValues) const
{
	HPLevelType theLevelType = HPStringToLevelType.at(boost::to_lower_copy(levelType));

	vector<string> levelsStr = util::Split(levelValues, ",", true);

	vector<level> levels;

	for (size_t i = 0; i < levelsStr.size(); i++)
	{
		levels.push_back(level(theLevelType, boost::lexical_cast<float>(levelsStr[i]), levelType));
	}

	return levels;
}

void transformer::SetAdditionalParameters()
{
	std::string itsSourceLevelType;
	std::string SourceLevels;

	if (!itsConfiguration->GetValue("base").empty())
	{
		itsBase = boost::lexical_cast<double>(itsConfiguration->GetValue("base"));
	}
	else
	{
		itsLogger->Warning("Base not specified, using default value 0.0");
	}

	if (!itsConfiguration->GetValue("scale").empty())
	{
		itsScale = boost::lexical_cast<double>(itsConfiguration->GetValue("scale"));
	}
	else
	{
		itsLogger->Warning("Scale not specified, using default value 1.0");
	}

	if (!itsConfiguration->GetValue("target_univ_id").empty())
	{
		itsTargetUnivID = boost::lexical_cast<int>(itsConfiguration->GetValue("target_univ_id"));
	}
	else
	{
		itsLogger->Warning("Target_univ_id not specified, using default value 9999");
	}

	if (!itsConfiguration->GetValue("target_param").empty())
	{
		itsTargetParam = itsConfiguration->GetValue("target_param");
	}
	else
	{
		throw runtime_error("Transformer_plugin: target_param not specified.");
	}

	if (!itsConfiguration->GetValue("source_param").empty())
	{
		itsSourceParam = itsConfiguration->GetValue("source_param");
	}
	else
	{
		itsSourceParam = itsTargetParam;
		itsLogger->Warning("Source_param not specified, source_param set to target_param");
	}

	if (!itsConfiguration->GetValue("source_level_type").empty())
	{
		itsSourceLevelType = itsConfiguration->GetValue("source_level_type");
	}
	else
	{
		itsLogger->Warning("Source_level not specified, source_level set to target level");
	}

	if (!itsConfiguration->GetValue("source_levels").empty())
	{
		SourceLevels = itsConfiguration->GetValue("source_levels");
	}
	else
	{
		itsLogger->Warning("Source_levels not specified, source_levels set to target levels");
	}

	// Check apply land sea mask parameter

	if (itsConfiguration->Exists("apply_landsea_mask") && itsConfiguration->GetValue("apply_landsea_mask") == "true")
	{
		itsApplyLandSeaMask = true;

		// Check for optional threshold parameter
		if (itsConfiguration->Exists("landsea_mask_threshold"))
		{
			itsLandSeaMaskThreshold = boost::lexical_cast<double>(itsConfiguration->GetValue("landsea_mask_threshold"));
		}
	}

	if (itsConfiguration->Exists("interpolation"))
	{
		itsInterpolationMethod = HPStringToInterpolationMethod.at(itsConfiguration->GetValue("interpolation"));
	}

	if (!SourceLevels.empty())
	{
		// looks useful to use this function to create source_levels

		itsSourceLevels = LevelsFromString(itsSourceLevelType, SourceLevels);
	}
	else
	{
		// copy levels from target
		auto x = make_shared<info> (*itsInfo);
		for (x->ResetLevel(); x->NextLevel();)
		{
			itsSourceLevels.push_back(x->Level());
		}
	}
}

void transformer::Process(std::shared_ptr<const plugin_configuration> conf)
{
	Init(conf);
	SetAdditionalParameters();

	/*
	 * Set target parameter to T
	 * - name T-C
	 * - univ_id 4
	 * - grib2 descriptor 0'00'000
	 *
	 * We need to specify grib and querydata parameter information
	 * since we don't know which one will be the output format.
	 *
	 */

	vector<param> theParams;

	param requestedParam(itsTargetParam, itsTargetUnivID);

	// GRIB 2
	if (itsConfiguration->OutputFileType() == kGRIB2)
	{
		if (!itsConfiguration->GetValue("grib_discipline").empty() &&
		    !itsConfiguration->GetValue("grib_category").empty() &&
		    !itsConfiguration->GetValue("grib_parameter").empty())
		{
			requestedParam.GribDiscipline(boost::lexical_cast<int>(itsConfiguration->GetValue("grib_discipline")));
			requestedParam.GribCategory(boost::lexical_cast<int>(itsConfiguration->GetValue("grib_category")));
			requestedParam.GribParameter(boost::lexical_cast<int>(itsConfiguration->GetValue("grib_parameter")));
		}
	}

	if (itsInterpolationMethod != kUnknownInterpolationMethod)
	{
		requestedParam.InterpolationMethod(itsInterpolationMethod);
	}

	theParams.push_back(requestedParam);

	SetParams(theParams);

	Start();
}

/*
 * Calculate()
 *
 * This function does the actual calculation.
 */

void transformer::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex)
{
	// Required source parameter

	param InputParam(itsSourceParam);

	auto myThreadedLogger =
	    logger_factory::Instance()->GetLog("transformerThread #" + boost::lexical_cast<string>(threadIndex));

	forecast_time forecastTime = myTargetInfo->Time();
	level forecastLevel = myTargetInfo->Level();
	forecast_type forecastType = myTargetInfo->ForecastType();

	myThreadedLogger->Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " +
	                       static_cast<string>(forecastLevel));

	auto f = GET_PLUGIN(fetcher);

	if (itsApplyLandSeaMask)
	{
		f->ApplyLandSeaMask(true);
		f->LandSeaMaskThreshold(itsLandSeaMaskThreshold);
	}

	info_t sourceInfo;

	try
	{
		sourceInfo = f->Fetch(itsConfiguration, forecastTime, itsSourceLevels[myTargetInfo->LevelIndex()], InputParam,
		                      forecastType, itsConfiguration->UseCudaForPacking());
	}
	catch (HPExceptionType& e)
	{
		myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " +
		                          static_cast<string>(forecastLevel));
		return;
	}

	SetAB(myTargetInfo, sourceInfo);

	bool levelOnly = (itsScale == 1.0 && itsBase == 0.0);

	string deviceType;

#ifdef HAVE_CUDA

	if (itsConfiguration->UseCuda() && !levelOnly)
	{
		deviceType = "GPU";

		auto opts = CudaPrepare(myTargetInfo, sourceInfo);

		transformer_cuda::Process(*opts);
	}
	else
#endif
	{
		deviceType = "CPU";

		LOCKSTEP(myTargetInfo, sourceInfo)
		{
			double value = sourceInfo->Value();

			if (value == kFloatMissing)
			{
				continue;
			}

			if (!levelOnly)
			{
				double newValue = value * itsScale + itsBase;

				myTargetInfo->Value(newValue);
			}
			else
			{
				myTargetInfo->Value(value);
			}
		}
	}

	myThreadedLogger->Info("[" + deviceType + "] Missing values: " +
	                       boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" +
	                       boost::lexical_cast<string>(myTargetInfo->Data().Size()));
}

#ifdef HAVE_CUDA

unique_ptr<transformer_cuda::options> transformer::CudaPrepare(shared_ptr<info> myTargetInfo,
                                                               shared_ptr<info> sourceInfo)
{
	unique_ptr<transformer_cuda::options> opts(new transformer_cuda::options);

	opts->N = sourceInfo->Data().Size();

	opts->base = itsBase;
	opts->scale = itsScale;

	opts->source = sourceInfo->ToSimple();
	opts->dest = myTargetInfo->ToSimple();

	return opts;
}
#endif
<|endoftext|>