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

#ifndef _SVWIN_H
#include <tools/svwin.h>
#endif

#ifndef _SV_WINCOMP_HXX
#include <wincomp.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif

// =======================================================================

static HBITMAP ImplCreateVirDevBitmap( HDC hDC, long nDX, long nDY,
                                       USHORT nBitCount )
{
    HBITMAP hBitmap;

    if ( nBitCount == 1 )
        hBitmap = CreateBitmap( (int)nDX, (int)nDY, 1, 1, NULL );
    else
        hBitmap = CreateCompatibleBitmap( hDC, (int)nDX, (int)nDY );

    return hBitmap;
}

// =======================================================================

SalVirtualDevice* WinSalInstance::CreateVirtualDevice( SalGraphics* pSGraphics,
                                                       long nDX, long nDY,
                                                       USHORT nBitCount,
                                                       const SystemGraphicsData* pData )
{
    WinSalGraphics* pGraphics = static_cast<WinSalGraphics*>(pSGraphics);

    HDC     hDC = NULL;
    HBITMAP hBmp = NULL;
    BOOL    bOk = FALSE;

    if( pData )
    {
        hDC = pData->hDC;
        hBmp = NULL;
        bOk = (hDC != NULL);
    }
    else
    {
        hDC     = CreateCompatibleDC( pGraphics->mhDC );
        hBmp    = ImplCreateVirDevBitmap( pGraphics->mhDC,
                                        nDX, nDY, nBitCount );
        bOk = ( (hDC != NULL) && (hBmp != NULL) );
    }

    if ( bOk )
    {
        WinSalVirtualDevice*    pVDev = new WinSalVirtualDevice;
        SalData*                pSalData = GetSalData();
        WinSalGraphics*         pVirGraphics = new WinSalGraphics;
        pVirGraphics->SetLayout( 0 );   // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
        pVirGraphics->mhDC     = hDC;
        pVirGraphics->mhWnd    = 0;
        pVirGraphics->mbPrinter = FALSE;
        pVirGraphics->mbVirDev  = TRUE;
        pVirGraphics->mbWindow  = FALSE;
        pVirGraphics->mbScreen  = pGraphics->mbScreen;
        if ( pSalData->mhDitherPal && pVirGraphics->mbScreen )
        {
            pVirGraphics->mhDefPal = SelectPalette( hDC, pSalData->mhDitherPal, TRUE );
            RealizePalette( hDC );
        }
        ImplSalInitGraphics( pVirGraphics );

        pVDev->mhDC         = hDC;
        pVDev->mhBmp        = hBmp;
        if( hBmp )
            pVDev->mhDefBmp = SelectBitmap( hDC, hBmp );
        else
            pVDev->mhDefBmp = NULL;
        pVDev->mpGraphics   = pVirGraphics;
        pVDev->mnBitCount   = nBitCount;
        pVDev->mbGraphics   = FALSE;
        pVDev->mbForeignDC  = (pData != NULL);

        // insert VirDev in VirDevList
        pVDev->mpNext = pSalData->mpFirstVD;
        pSalData->mpFirstVD = pVDev;

        return pVDev;
    }
    else
    {
        if ( hDC && !pData )
            DeleteDC( hDC );
        if ( hBmp )
            DeleteBitmap( hBmp );
        return NULL;
    }
}

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

void WinSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// =======================================================================

WinSalVirtualDevice::WinSalVirtualDevice()
{
}

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

WinSalVirtualDevice::~WinSalVirtualDevice()
{
    SalData* pSalData = GetSalData();

    // destroy saved DC
    if ( mpGraphics->mhDefPal )
        SelectPalette( mpGraphics->mhDC, mpGraphics->mhDefPal, TRUE );
    ImplSalDeInitGraphics( mpGraphics );
    if( mhDefBmp )
        SelectBitmap( mpGraphics->mhDC, mhDefBmp );
    if( !mbForeignDC )
        DeleteDC( mpGraphics->mhDC );
    if( mhBmp )
        DeleteBitmap( mhBmp );
    delete mpGraphics;

    // remove VirDev from VirDevList
    if ( this == pSalData->mpFirstVD )
        pSalData->mpFirstVD = mpNext;
    else
    {
        WinSalVirtualDevice* pTempVD = pSalData->mpFirstVD;
        while ( pTempVD->mpNext != this )
            pTempVD = pTempVD->mpNext;

        pTempVD->mpNext = mpNext;
    }
}

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

SalGraphics* WinSalVirtualDevice::GetGraphics()
{
    if ( mbGraphics )
        return NULL;

    if ( mpGraphics )
        mbGraphics = TRUE;

    return mpGraphics;
}

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

void WinSalVirtualDevice::ReleaseGraphics( SalGraphics* )
{
    mbGraphics = FALSE;
}

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

BOOL WinSalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( mbForeignDC || !mhBmp )
        return TRUE;    // ???
    else
    {
        HBITMAP hNewBmp = ImplCreateVirDevBitmap( mhDC, nDX, nDY,
                                              mnBitCount );
        if ( hNewBmp )
        {
            SelectBitmap( mhDC, hNewBmp );
            DeleteBitmap( mhBmp );
            mhBmp = hNewBmp;
            return TRUE;
        }
        else
            return FALSE;
    }
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.290); FILE MERGED 2005/09/05 14:46:29 rt 1.5.290.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:06:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVWIN_H
#include <tools/svwin.h>
#endif

#ifndef _SV_WINCOMP_HXX
#include <wincomp.hxx>
#endif
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#ifndef _SV_SALINST_H
#include <salinst.h>
#endif
#ifndef _SV_SALGDI_H
#include <salgdi.h>
#endif
#ifndef _SV_SALVD_H
#include <salvd.h>
#endif
#ifndef _SV_SYSDATA_HXX
#include <sysdata.hxx>
#endif

// =======================================================================

static HBITMAP ImplCreateVirDevBitmap( HDC hDC, long nDX, long nDY,
                                       USHORT nBitCount )
{
    HBITMAP hBitmap;

    if ( nBitCount == 1 )
        hBitmap = CreateBitmap( (int)nDX, (int)nDY, 1, 1, NULL );
    else
        hBitmap = CreateCompatibleBitmap( hDC, (int)nDX, (int)nDY );

    return hBitmap;
}

// =======================================================================

SalVirtualDevice* WinSalInstance::CreateVirtualDevice( SalGraphics* pSGraphics,
                                                       long nDX, long nDY,
                                                       USHORT nBitCount,
                                                       const SystemGraphicsData* pData )
{
    WinSalGraphics* pGraphics = static_cast<WinSalGraphics*>(pSGraphics);

    HDC     hDC = NULL;
    HBITMAP hBmp = NULL;
    BOOL    bOk = FALSE;

    if( pData )
    {
        hDC = pData->hDC;
        hBmp = NULL;
        bOk = (hDC != NULL);
    }
    else
    {
        hDC     = CreateCompatibleDC( pGraphics->mhDC );
        hBmp    = ImplCreateVirDevBitmap( pGraphics->mhDC,
                                        nDX, nDY, nBitCount );
        bOk = ( (hDC != NULL) && (hBmp != NULL) );
    }

    if ( bOk )
    {
        WinSalVirtualDevice*    pVDev = new WinSalVirtualDevice;
        SalData*                pSalData = GetSalData();
        WinSalGraphics*         pVirGraphics = new WinSalGraphics;
        pVirGraphics->SetLayout( 0 );   // by default no! mirroring for VirtualDevices, can be enabled with EnableRTL()
        pVirGraphics->mhDC     = hDC;
        pVirGraphics->mhWnd    = 0;
        pVirGraphics->mbPrinter = FALSE;
        pVirGraphics->mbVirDev  = TRUE;
        pVirGraphics->mbWindow  = FALSE;
        pVirGraphics->mbScreen  = pGraphics->mbScreen;
        if ( pSalData->mhDitherPal && pVirGraphics->mbScreen )
        {
            pVirGraphics->mhDefPal = SelectPalette( hDC, pSalData->mhDitherPal, TRUE );
            RealizePalette( hDC );
        }
        ImplSalInitGraphics( pVirGraphics );

        pVDev->mhDC         = hDC;
        pVDev->mhBmp        = hBmp;
        if( hBmp )
            pVDev->mhDefBmp = SelectBitmap( hDC, hBmp );
        else
            pVDev->mhDefBmp = NULL;
        pVDev->mpGraphics   = pVirGraphics;
        pVDev->mnBitCount   = nBitCount;
        pVDev->mbGraphics   = FALSE;
        pVDev->mbForeignDC  = (pData != NULL);

        // insert VirDev in VirDevList
        pVDev->mpNext = pSalData->mpFirstVD;
        pSalData->mpFirstVD = pVDev;

        return pVDev;
    }
    else
    {
        if ( hDC && !pData )
            DeleteDC( hDC );
        if ( hBmp )
            DeleteBitmap( hBmp );
        return NULL;
    }
}

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

void WinSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// =======================================================================

WinSalVirtualDevice::WinSalVirtualDevice()
{
}

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

WinSalVirtualDevice::~WinSalVirtualDevice()
{
    SalData* pSalData = GetSalData();

    // destroy saved DC
    if ( mpGraphics->mhDefPal )
        SelectPalette( mpGraphics->mhDC, mpGraphics->mhDefPal, TRUE );
    ImplSalDeInitGraphics( mpGraphics );
    if( mhDefBmp )
        SelectBitmap( mpGraphics->mhDC, mhDefBmp );
    if( !mbForeignDC )
        DeleteDC( mpGraphics->mhDC );
    if( mhBmp )
        DeleteBitmap( mhBmp );
    delete mpGraphics;

    // remove VirDev from VirDevList
    if ( this == pSalData->mpFirstVD )
        pSalData->mpFirstVD = mpNext;
    else
    {
        WinSalVirtualDevice* pTempVD = pSalData->mpFirstVD;
        while ( pTempVD->mpNext != this )
            pTempVD = pTempVD->mpNext;

        pTempVD->mpNext = mpNext;
    }
}

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

SalGraphics* WinSalVirtualDevice::GetGraphics()
{
    if ( mbGraphics )
        return NULL;

    if ( mpGraphics )
        mbGraphics = TRUE;

    return mpGraphics;
}

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

void WinSalVirtualDevice::ReleaseGraphics( SalGraphics* )
{
    mbGraphics = FALSE;
}

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

BOOL WinSalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( mbForeignDC || !mhBmp )
        return TRUE;    // ???
    else
    {
        HBITMAP hNewBmp = ImplCreateVirDevBitmap( mhDC, nDX, nDY,
                                              mnBitCount );
        if ( hNewBmp )
        {
            SelectBitmap( mhDC, hNewBmp );
            DeleteBitmap( mhBmp );
            mhBmp = hNewBmp;
            return TRUE;
        }
        else
            return FALSE;
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 SRG Technology, LLC
//
// 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 "anyrpc/api.h"
#include "anyrpc/logger.h"
#include "anyrpc/error.h"
#include "anyrpc/value.h"
#include "anyrpc/method.h"

namespace anyrpc
{

void ListMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->ListMethods(params, result);
}

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

void HelpMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->FindHelpMethod(params, result);
}

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

MethodManager::MethodManager()
{
    methods_[LIST_METHODS] = new ListMethod(this,LIST_METHODS,LIST_METHODS_HELP);
    methods_[METHOD_HELP] = new HelpMethod(this,METHOD_HELP,METHOD_HELP_HELP);
}

MethodManager::~MethodManager()
{
    mutex_.lock();
    MethodMap::iterator it = methods_.begin();
    for (MethodMap::iterator it = methods_.begin(); it != methods_.end(); it++)
    {
        if (it->second->DeleteOnRemove())
            delete it->second;  // free the method pointer data
    }
    methods_.clear();
}

void MethodManager::AddFunction(Function* function, std::string const& name, std::string const& help)
{
    mutex_.lock();
    MethodMap::const_iterator it = methods_.find(name);
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[name] = new MethodFunction(function,name,help);
        mutex_.unlock();
    }
    else
    {
        mutex_.unlock();
        // function already defined, throw exception
        // the user can catch and ignore the exception if this behavior is desired
        anyrpc_throw(AnyRpcErrorFunctionRedefine, "Attempt to redefine function name: " + name);
    }
}

void MethodManager::AddMethod(Method* method)
{
    mutex_.lock();
    MethodMap::const_iterator it = methods_.find(method->Name());
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[method->Name()] = method;
        mutex_.unlock();
    }
    else
    {
        mutex_.unlock();
        // method already defined, clean up then throw exception
        // the user can catch and ignore the exception if this behavior is desired
        if (method->DeleteOnRemove())
            delete method;
        anyrpc_throw(AnyRpcErrorMethodRedefine, "Attempt to redefine method name: " + method->Name());
    }
}

bool MethodManager::RemoveMethod(std::string const& name)
{
    mutex_.lock();
	MethodMap::const_iterator it = methods_.find(name);
	if (it == methods_.end())
	{
	    mutex_.unlock();
        return false; // no such method exists
	}
	Method *method = it->second;
	if (method->ActiveThreads() > 0)
	{
	    method->SetDelayedRemove();
	}
	else
	{
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
	}
	mutex_.unlock();
	return true;
}

bool MethodManager::ExecuteMethod(std::string const& name, Value& params, Value& result)
{
    mutex_.lock();
    MethodMap::const_iterator it = methods_.find(name);
    if ((it == methods_.end()) || it->second->DelayedRemove())
    {
        mutex_.unlock();
        return false;
    }
    // Add this thread to the list of users for this method
    Method *method = it->second;
    method->AddThread();
    mutex_.unlock();

    it->second->Execute(params,result);

    mutex_.lock();
    // Finish with this thread using this method
    method->RemoveThread();
    // Check if we should remove the method - must have no active threads
    if (method->DelayedRemove() && (method->ActiveThreads() == 0))
    {
        // Find the method again in case other changes to the list have occurred
        it = methods_.find(name);
        if (it == methods_.end())
        {
            mutex_.unlock();
            anyrpc_throw(AnyRpcErrorInternalError, "Method not found for delayed remove: " + name);
        }
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
    }

    mutex_.unlock();

    return true;
}

void MethodManager::ListMethods(Value& params, Value& result)
{
    int i=0;
    result.SetArray();
    mutex_.lock();
    result.SetSize(methods_.size());
    for (MethodMap::const_iterator it = methods_.begin(); it != methods_.end(); ++it)
        result[i++] = it->first;
    mutex_.unlock();
}

void MethodManager::FindHelpMethod(Value& params, Value& result)
{
    if (!params.IsArray() || (params.Size() != 1) || !params[0].IsString())
        anyrpc_throw(AnyRpcErrorInvalidParams, "Invalid parameters");

    mutex_.lock();
    MethodMap::const_iterator it = methods_.find(params[0].GetString());
    if (it == methods_.end())
    {
        mutex_.unlock();
        anyrpc_throw(AnyRpcErrorMethodNotFound, "Unknown method name: " + std::string(params[0].GetString()));
    }

    result = it->second->Help();
    mutex_.unlock();
}

}
<commit_msg>Use lock_guard and unique_lock for locking in MethodManager<commit_after>// Copyright (C) 2015 SRG Technology, LLC
//
// 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 "anyrpc/api.h"
#include "anyrpc/logger.h"
#include "anyrpc/error.h"
#include "anyrpc/value.h"
#include "anyrpc/method.h"

namespace anyrpc
{

void ListMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->ListMethods(params, result);
}

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

void HelpMethod::Execute(Value& params, Value& result)
{
    if (manager_)
        manager_->FindHelpMethod(params, result);
}

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

MethodManager::MethodManager()
{
    methods_[LIST_METHODS] = new ListMethod(this,LIST_METHODS,LIST_METHODS_HELP);
    methods_[METHOD_HELP] = new HelpMethod(this,METHOD_HELP,METHOD_HELP_HELP);
}

MethodManager::~MethodManager()
{
    MethodMap::iterator it = methods_.begin();
    for (MethodMap::iterator it = methods_.begin(); it != methods_.end(); it++)
    {
        if (it->second->DeleteOnRemove())
            delete it->second;  // free the method pointer data
    }
    methods_.clear();
}

void MethodManager::AddFunction(Function* function, std::string const& name, std::string const& help)
{
    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[name] = new MethodFunction(function,name,help);
    }
    else
    {
        // function already defined, throw exception
        // the user can catch and ignore the exception if this behavior is desired
        anyrpc_throw(AnyRpcErrorFunctionRedefine, "Attempt to redefine function name: " + name);
    }
}

void MethodManager::AddMethod(Method* method)
{
    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(method->Name());
    if (it == methods_.end())
    {
        // not found so add new method
        methods_[method->Name()] = method;
    }
    else
    {
        // method already defined, clean up then throw exception
        // the user can catch and ignore the exception if this behavior is desired
        if (method->DeleteOnRemove())
            delete method;
        anyrpc_throw(AnyRpcErrorMethodRedefine, "Attempt to redefine method name: " + method->Name());
    }
}

bool MethodManager::RemoveMethod(std::string const& name)
{
    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if (it == methods_.end())
        return false; // no such method exists

    Method *method = it->second;
    if (method->ActiveThreads() > 0)
    {
        method->SetDelayedRemove();
    }
    else
    {
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
    }
    return true;
}

bool MethodManager::ExecuteMethod(std::string const& name, Value& params, Value& result)
{
    std::unique_lock<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(name);
    if ((it == methods_.end()) || it->second->DelayedRemove())
        return false;
    // Add this thread to the list of users for this method
    Method *method = it->second;
    method->AddThread();
    lock.unlock();

    it->second->Execute(params,result);

    lock.lock();
    // Finish with this thread using this method
    method->RemoveThread();
    // Check if we should remove the method - must have no active threads
    if (method->DelayedRemove() && (method->ActiveThreads() == 0))
    {
        // Find the method again in case other changes to the list have occurred
        it = methods_.find(name);
        if (it == methods_.end())
            anyrpc_throw(AnyRpcErrorInternalError, "Method not found for delayed remove: " + name);
        if (method->DeleteOnRemove())
            delete method;  // free the method pointer data
        methods_.erase(it);
    }

    return true;
}

void MethodManager::ListMethods(Value& params, Value& result)
{
    int i=0;
    result.SetArray();
    std::lock_guard<std::mutex> lock(mutex_);
    result.SetSize(methods_.size());
    for (MethodMap::const_iterator it = methods_.begin(); it != methods_.end(); ++it)
        result[i++] = it->first;
}

void MethodManager::FindHelpMethod(Value& params, Value& result)
{
    if (!params.IsArray() || (params.Size() != 1) || !params[0].IsString())
        anyrpc_throw(AnyRpcErrorInvalidParams, "Invalid parameters");

    std::lock_guard<std::mutex> lock(mutex_);
    MethodMap::const_iterator it = methods_.find(params[0].GetString());
    if (it == methods_.end())
        anyrpc_throw(AnyRpcErrorMethodNotFound, "Unknown method name: " + std::string(params[0].GetString()));

    result = it->second->Help();
}

}
<|endoftext|>


<commit_before>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_FUNCTION_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_FUNCTION_HPP

#include "meta_list.hpp"
#include "void_t.hpp"
#include "traits.hpp"
#include "service_map.hpp"

#if _MSC_VER == 1900
#ifndef __clang__
// MSVC has a defect that makes the use of the template keyword an error in some corner cases.
#define KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD
#endif // !__clang__
#endif // _MSC_VER

namespace kgr {
namespace detail {

/*
 * Checks if some given pointer to member function is invokable
 *
 * Assumes that P is a reflectable function type.
 */
template<typename Map, typename T, typename P, typename... Args>
struct is_pointer_invokable_helper {
private:
	template<typename U, typename V, typename... As, std::size_t... S, int_t<decltype(
		(std::declval<U>().*std::declval<V>())(
			std::declval<ServiceType<service_map_t<Map, function_argument_t<S, V>>>>()...,
			std::declval<As>()...
		)
	)> = 0>
	static std::true_type test(seq<S...>);

	template<typename...>
	static std::false_type test(...);

public:
	using type = decltype(test<T, P, Args...>(tuple_seq_minus<function_arguments_t<P>, sizeof...(Args)>{}));
};

/*
 * Alias for the is_pointer_invokable_helper trait
 */
template<typename Map, typename T, typename P, typename... Args>
struct is_pointer_invokable : is_pointer_invokable_helper<Map, T, P, Args...>::type {};

/*
 * Trait that checks if a class T has a call operator callable using given service map
 */
template<typename, typename, typename, typename, typename = void>
struct is_template_call_callable : std::false_type {};

/*
 * Specialization of is_template_call_callable when the call operator is callable
 */
template<typename Map, typename T, typename... TArgs, typename... Args>
struct is_template_call_callable<
	Map, T, meta_list<TArgs...>, meta_list<Args...>,
	enable_if_t<is_pointer_invokable<Map, T,

#ifdef KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD
	decltype(exact(&T::operator()<TArgs...>)),
#else
	decltype(exact(&T::template operator()<TArgs...>)),
#endif // KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD

	Args...>::value>
> : std::true_type {};

/*
 * Trait that returns the type of the first matching callable template call operator
 */
template<typename, typename, typename, typename, typename = void>
struct get_template_call;

/*
 * Specialization of get_template_call_helper when there is no functoin found
 */
template<typename Map, typename T, typename... Args>
struct get_template_call<
	Map, T, meta_list<>, meta_list<Args...>,
	enable_if_t<!is_template_call_callable<Map, T, meta_list<>, meta_list<Args...>>::value>
> {};

/*
 * Specialization of get_template_call_helper when current template arguments does
 * not result in a callable template call operator.
 *
 * Will call recursively the next iteration of the trait.
 */
template<typename Map, typename T, typename Head, typename... Tail, typename... Args>
struct get_template_call<
	Map, T, meta_list<Head, Tail...>, meta_list<Args...>,
	enable_if_t<!is_template_call_callable<Map, T, meta_list<Head, Tail...>, meta_list<Args...>>::value>
> : get_template_call<Map, T, meta_list<Tail...>, meta_list<Args...>> {};

/*
 * Specialization of get_template_call_helper when a callable candidate is found.
 */
template<typename Map, typename T, typename... TArgs, typename... Args>
struct get_template_call<
	Map, T, meta_list<TArgs...>, meta_list<Args...>,
	enable_if_t<is_template_call_callable<Map, T, meta_list<TArgs...>, meta_list<Args...>>::value>
> {
	// Some MSVC vesions cannoet parse the valid syntax corretly. We must write
	// the expression in that way in order to compile.
#ifdef KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD
	using type = decltype(exact(&T::operator()<TArgs...>));
#else
	using type = decltype(exact(&T::template operator()<TArgs...>));
#endif // KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD
};

/*
 * Alias for get_template_call_helper::type
 */
template<typename Map, typename T, typename... Args>
using get_template_call_t = typename get_template_call<Map, T, meta_list<Args...>, meta_list<Args...>>::type;

/*
 * Trait that tells if the class T has a callable template call operator
 */
template<typename, typename, typename, typename = void>
struct has_template_call_operator : std::false_type {};

template<typename Map, typename T, typename... Args>
struct has_template_call_operator<Map, T, meta_list<Args...>, void_t<get_template_call_t<Map, T, Args...>>> : std::true_type {};

/*
 * function_trait equivalent for an invoke function. It has to choose if it's a lambda, generic lambda or a function.
 */
template<typename, typename, typename, typename = void>
struct invoke_function_helper {};

/*
 * Specialization of invoke_function_helper for function types and ordinary lambda.
 * Will extract correctly argument types, called function type and return type.
 */
template<typename Map, typename T, typename... Args>
struct invoke_function_helper<
	Map, T, meta_list<Args...>,
	enable_if_t<has_call_operator<T>::value || std::is_pointer<T>::value>
> : function_traits<T> {};

/*
 * Specialization of invoke_function_helper for generic lambda.
 * Will extract correctly argument types, called function type and return type.
 */
template<typename Map, typename T, typename... Args>
struct invoke_function_helper<
	Map, T, meta_list<Args...>,
	enable_if_t<!has_call_operator<T>::value && !std::is_pointer<T>::value && has_template_call_operator<Map, T, meta_list<Args...>>::value>
> : function_traits<get_template_call_t<Map, T, Args...>> {};

/*
 * Alias for invoke_function_helper
 */
template<typename Map, typename T, typename... Args>
struct invoke_function : invoke_function_helper<Map, T, meta_list<Args...>> {};

/*
 * Alias for invoke_function::argument_types, a meta list of argument types.
 */
template<typename Map, typename T, typename... Args>
using invoke_function_arguments_t = typename invoke_function<Map, T, Args...>::argument_types;

/*
 * Alias for invoke_function::argument_type, the type of the nth argument.
 */
template<std::size_t n, typename Map, typename T, typename... Args>
using invoke_function_argument_t = typename invoke_function<Map, T, Args...>::template argument_type<n>;

template<typename Map, typename T, typename... Args>
using invoke_function_result_t = typename invoke_function<Map, T, Args...>::return_type;

template<typename Map, typename T, typename... Args>
struct is_invokable_helper {
private:
	template<std::size_t I, typename U>
	struct expand {
		using type = invoke_function_argument_t<I, Map, U, Args...>;
	};

	// This sub trait is for visual studio
	// The constraint can be simplified because every argument are simple template argument
	template<typename U, typename... As>
	struct call_test {
	private:
		template<typename...>
		static std::false_type test(...);

		template<typename V, typename... A2s, int_t<decltype(std::declval<V>()(std::declval<A2s>()...))> = 0>
		static std::true_type test(int);

		using type = decltype(test<U, As...>(0));

	public:
		static constexpr bool value = type::value;
	};

	// Alias for not using a template template argument in the next expression, will help simplify the expression and MSVC to parse it.
	template<typename U>
	using map_t = service_map_t<Map, U>;

	// We forward injected argument types (from expand) and additional arguments (As) to the sub trait call_test
	template<typename U, typename... As, std::size_t... S, enable_if_t<call_test<U, ServiceType<map_t<typename expand<S, U>::type>>..., As...>::value, int> = 0>
	static std::true_type test_helper(seq<S...>);

	template<typename...>
	static std::false_type test_helper(...);

	template<typename U, typename... As>
	static decltype(test_helper<U, As...>(tuple_seq_minus<invoke_function_arguments_t<Map, U, As...>, sizeof...(Args)>{})) test(int);

	template<typename...>
	static std::false_type test(...);

public:
	using type = decltype(test<T, Args...>(0));
};

/*
 * Alias for is_invokable_helper
 */
template<typename Map, typename T, typename... Args>
struct is_invokable : is_invokable_helper<Map, T, Args...>::type {};

} // namespace detail
} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_FUNCTION_HPP
<commit_msg>Fixed a bug with GCC where generic lambdas are not invokable<commit_after>#ifndef KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_FUNCTION_HPP
#define KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_FUNCTION_HPP

#include "meta_list.hpp"
#include "void_t.hpp"
#include "traits.hpp"
#include "service_map.hpp"

#if _MSC_VER == 1900
#ifndef __clang__
// MSVC has a defect that makes the use of the template keyword an error in some corner cases.
#define KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD
#endif // !__clang__
#endif // _MSC_VER

#if _MSC_VER
#ifndef __clang__
// MSVC has a defect that makes decltype with the address of a
// generic lambda not possible unless sending the address to a function.
#define KGR_KANGARU_MSVC_EXACT_DECLTYPE
#endif // !__clang__
#endif // _MSC_VER

namespace kgr {
namespace detail {

/*
 * Checks if some given pointer to member function is invokable
 *
 * Assumes that P is a reflectable function type.
 */
template<typename Map, typename T, typename P, typename... Args>
struct is_pointer_invokable_helper {
private:
	template<typename U, typename V, typename... As, std::size_t... S, int_t<decltype(
		(std::declval<U>().*std::declval<V>())(
			std::declval<ServiceType<service_map_t<Map, function_argument_t<S, V>>>>()...,
			std::declval<As>()...
		)
	)> = 0>
	static std::true_type test(seq<S...>);

	template<typename...>
	static std::false_type test(...);

public:
	using type = decltype(test<T, P, Args...>(tuple_seq_minus<function_arguments_t<P>, sizeof...(Args)>{}));
};

/*
 * Alias for the is_pointer_invokable_helper trait
 */
template<typename Map, typename T, typename P, typename... Args>
struct is_pointer_invokable : is_pointer_invokable_helper<Map, T, P, Args...>::type {};

/*
 * Trait that checks if a class T has a call operator callable using given service map
 */
template<typename, typename, typename, typename, typename = void>
struct is_template_call_callable : std::false_type {};

/*
 * Specialization of is_template_call_callable when the call operator is callable
 */
template<typename Map, typename T, typename... TArgs, typename... Args>
struct is_template_call_callable<
	Map, T, meta_list<TArgs...>, meta_list<Args...>,
	enable_if_t<is_pointer_invokable<Map, T,

	// Some MSVC vesions cannoet parse the valid syntax corretly. We must write
	// the expression in that way in order to compile.
#ifdef KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD
	decltype(exact(&T::operator()<TArgs...>)),
#elif defined(KGR_KANGARU_MSVC_EXACT_DECLTYPE)
	// GCC won't accept taking the address of a generic lambda if the address is sent to a function like exact.
	decltype(exact(&T::template operator()<TArgs...>)),
#else
	// Vanilla syntax
	decltype(&T::template operator()<TArgs...>),
#endif // KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD

	Args...>::value>
> : std::true_type {};

/*
 * Trait that returns the type of the first matching callable template call operator
 */
template<typename, typename, typename, typename, typename = void>
struct get_template_call;

/*
 * Specialization of get_template_call_helper when there is no functoin found
 */
template<typename Map, typename T, typename... Args>
struct get_template_call<
	Map, T, meta_list<>, meta_list<Args...>,
	enable_if_t<!is_template_call_callable<Map, T, meta_list<>, meta_list<Args...>>::value>
> {};

/*
 * Specialization of get_template_call_helper when current template arguments does
 * not result in a callable template call operator.
 *
 * Will call recursively the next iteration of the trait.
 */
template<typename Map, typename T, typename Head, typename... Tail, typename... Args>
struct get_template_call<
	Map, T, meta_list<Head, Tail...>, meta_list<Args...>,
	enable_if_t<!is_template_call_callable<Map, T, meta_list<Head, Tail...>, meta_list<Args...>>::value>
> : get_template_call<Map, T, meta_list<Tail...>, meta_list<Args...>> {};

/*
 * Specialization of get_template_call_helper when a callable candidate is found.
 */
template<typename Map, typename T, typename... TArgs, typename... Args>
struct get_template_call<
	Map, T, meta_list<TArgs...>, meta_list<Args...>,
	enable_if_t<is_template_call_callable<Map, T, meta_list<TArgs...>, meta_list<Args...>>::value>
> {
	// Some MSVC vesions cannoet parse the valid syntax corretly. We must write
	// the expression in that way in order to compile.
#ifdef KGR_KANGARU_MSVC_NO_DEPENDENT_TEMPLATE_KEYWORD
	using type = decltype(exact(&T::operator()<TArgs...>));
#elif defined(KGR_KANGARU_MSVC_EXACT_DECLTYPE)
	// GCC won't accept taking the address of a generic lambda if the address is sent to a function like exact.
	using type = decltype(exact(&T::template operator()<TArgs...>));
#else
	// Vanilla syntax
	using type = decltype(&T::template operator()<TArgs...>);
#endif
};

/*
 * Alias for get_template_call_helper::type
 */
template<typename Map, typename T, typename... Args>
using get_template_call_t = typename get_template_call<Map, T, meta_list<Args...>, meta_list<Args...>>::type;

/*
 * Trait that tells if the class T has a callable template call operator
 */
template<typename, typename, typename, typename = void>
struct has_template_call_operator : std::false_type {};

template<typename Map, typename T, typename... Args>
struct has_template_call_operator<Map, T, meta_list<Args...>, void_t<get_template_call_t<Map, T, Args...>>> : std::true_type {};

/*
 * function_trait equivalent for an invoke function. It has to choose if it's a lambda, generic lambda or a function.
 */
template<typename, typename, typename, typename = void>
struct invoke_function_helper {};

/*
 * Specialization of invoke_function_helper for function types and ordinary lambda.
 * Will extract correctly argument types and return type.
 */
template<typename Map, typename T, typename... Args>
struct invoke_function_helper<
	Map, T, meta_list<Args...>,
	enable_if_t<has_call_operator<T>::value || std::is_pointer<T>::value>
> : function_traits<T> {};

/*
 * Specialization of invoke_function_helper for generic lambda.
 * Will extract correctly argument types and return type.
 */
template<typename Map, typename T, typename... Args>
struct invoke_function_helper<
	Map, T, meta_list<Args...>,
	enable_if_t<!has_call_operator<T>::value && !std::is_pointer<T>::value && has_template_call_operator<Map, T, meta_list<Args...>>::value>
> : function_traits<get_template_call_t<Map, T, Args...>> {};

/*
 * Alias for invoke_function_helper
 */
template<typename Map, typename T, typename... Args>
struct invoke_function : invoke_function_helper<Map, T, meta_list<Args...>> {};

/*
 * Alias for invoke_function::argument_types, a meta list of argument types.
 */
template<typename Map, typename T, typename... Args>
using invoke_function_arguments_t = typename invoke_function<Map, T, Args...>::argument_types;

/*
 * Alias for invoke_function::argument_type, the type of the nth argument.
 */
template<std::size_t n, typename Map, typename T, typename... Args>
using invoke_function_argument_t = typename invoke_function<Map, T, Args...>::template argument_type<n>;

template<typename Map, typename T, typename... Args>
using invoke_function_result_t = typename invoke_function<Map, T, Args...>::return_type;

template<typename Map, typename T, typename... Args>
struct is_invokable_helper {
private:
	template<std::size_t I, typename U>
	struct expand {
		using type = invoke_function_argument_t<I, Map, U, Args...>;
	};

	// This sub trait is for visual studio
	// The constraint can be simplified because every argument are simple template argument
	template<typename U, typename... As>
	struct call_test {
	private:
		template<typename...>
		static std::false_type test(...);

		template<typename V, typename... A2s, int_t<decltype(std::declval<V>()(std::declval<A2s>()...))> = 0>
		static std::true_type test(int);

		using type = decltype(test<U, As...>(0));

	public:
		static constexpr bool value = type::value;
	};

	// Alias for not using a template template argument in the next expression, will help simplify the expression and MSVC to parse it.
	template<typename U>
	using map_t = service_map_t<Map, U>;

	// We forward injected argument types (from expand) and additional arguments (As) to the sub trait call_test
	template<typename U, typename... As, std::size_t... S, enable_if_t<call_test<U, ServiceType<map_t<typename expand<S, U>::type>>..., As...>::value, int> = 0>
	static std::true_type test_helper(seq<S...>);

	template<typename...>
	static std::false_type test_helper(...);

	template<typename U, typename... As>
	static decltype(test_helper<U, As...>(tuple_seq_minus<invoke_function_arguments_t<Map, U, As...>, sizeof...(Args)>{})) test(int);

	template<typename...>
	static std::false_type test(...);

public:
	using type = decltype(test<T, Args...>(0));
};

/*
 * Alias for is_invokable_helper
 */
template<typename Map, typename T, typename... Args>
struct is_invokable : is_invokable_helper<Map, T, Args...>::type {};

} // namespace detail
} // namespace kgr

#endif // KGR_KANGARU_INCLUDE_KANGARU_DETAIL_INVOKE_FUNCTION_HPP
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP

//stl
#include <vector>
// boost
#include <boost/progress.hpp>
// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>

namespace mapnik
{
   template <typename Processor>
   class feature_style_processor
   {
         struct symbol_dispatch : public boost::static_visitor<>
         {
               symbol_dispatch (Processor & output,
                                Feature const& f,
                                proj_transform const& prj_trans)
                  : output_(output),
                    f_(f),
                    prj_trans_(prj_trans)  {}

               template <typename T>
               void operator () (T const& sym) const
               {
                  output_.process(sym,f_,prj_trans_);
               }

               Processor & output_;
               Feature const& f_;
               proj_transform const& prj_trans_;
         };
      public:
         feature_style_processor(Map const& m)
            : m_(m) {}

         void apply()
         {
#ifdef MAPNIK_DEBUG
            boost::progress_timer t(std::clog);
#endif
            Processor & p = static_cast<Processor&>(*this);
            p.start_map_processing(m_);

            try
            {
               projection proj(m_.srs()); // map projection
               double scale_denom = scale_denominator(m_,proj.is_geographic());
#ifdef MAPNIK_DEBUG
               std::clog << "scale denominator = " << scale_denom << "\n";
#endif
               std::vector<Layer>::const_iterator itr = m_.layers().begin();
               std::vector<Layer>::const_iterator end = m_.layers().end();

               while (itr != end)
               {
                  if (itr->isVisible(scale_denom))
                  {
                     apply_to_layer(*itr, p, proj, scale_denom);
                  }
                  ++itr;
               }
            }
            catch (proj_init_error& ex)
            {
               std::clog << ex.what() << "\n";
            }

            p.end_map_processing(m_);
         }
      private:
         void apply_to_layer(Layer const& lay, Processor & p,
                             projection const& proj0,double scale_denom)
         {
            p.start_layer_processing(lay);
            boost::shared_ptr<datasource> ds=lay.datasource();
            if (ds)
            {
               Envelope<double> const& ext=m_.getCurrentExtent();

               projection proj1(lay.srs());
               proj_transform prj_trans(proj0,proj1);

               double x0 = ext.minx();
               double y0 = ext.miny();
               double z0 = 0.0;
               double x1 = ext.maxx();
               double y1 = ext.maxy();
               double z1 = 0.0;
               prj_trans.forward(x0,y0,z0);
               prj_trans.forward(x1,y1,z1);
               Envelope<double> bbox(x0,y0,x1,y1);

               double resolution = m_.getWidth()/bbox.width();
#ifdef MAPNIK_DEBUG
               std::clog << bbox << "\n";
#endif
               std::vector<std::string> const& style_names = lay.styles();
               std::vector<std::string>::const_iterator stylesIter = style_names.begin();
               std::vector<std::string>::const_iterator stylesEnd = style_names.end();

               while (stylesIter != stylesEnd)
               {
                  std::set<std::string> names;
                  attribute_collector<Feature> collector(names);
                  std::vector<rule_type*> if_rules;
                  std::vector<rule_type*> else_rules;

                  bool active_rules=false;

                  feature_type_style const& style=m_.find_style(*stylesIter++);

                  query q(bbox,resolution); //BBOX query

                  const std::vector<rule_type>& rules=style.get_rules();
                  std::vector<rule_type>::const_iterator ruleIter=rules.begin();
                  std::vector<rule_type>::const_iterator ruleEnd=rules.end();

                  while (ruleIter!=ruleEnd)
                  {
                     if (ruleIter->active(scale_denom))
                     {
                        active_rules=true;
                        ruleIter->accept(collector);

                        if (ruleIter->has_else_filter())
                        {
                           else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                        else
                        {
                           if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                     }
                     ++ruleIter;
                  }
                  std::set<std::string>::const_iterator namesIter=names.begin();
                  std::set<std::string>::const_iterator namesEnd =names.end();

                  // push all property names
                  while (namesIter!=namesEnd)
                  {
                     q.add_property_name(*namesIter);
                     ++namesIter;
                  }
                  if (active_rules)
                  {
                     featureset_ptr fs=ds->features(q);
                     if (fs)
                     {
                        feature_ptr feature;
                        while ((feature = fs->next()))
                        {
                           bool do_else=true;
                           std::vector<rule_type*>::const_iterator itr=if_rules.begin();
                           std::vector<rule_type*>::const_iterator end=if_rules.end();
                           while (itr != end)
                           {
                              filter_ptr const& filter=(*itr)->get_filter();
                              if (filter->pass(*feature))
                              {
                                 do_else=false;
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter=symbols.begin();
                                 symbolizers::const_iterator symEnd =symbols.end();
                                 while (symIter != symEnd)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),*symIter++);
                                 }
                              }
                              ++itr;
                           }
                           if (do_else)
                           {
                              //else filter
                              std::vector<rule_type*>::const_iterator itr=
                                 else_rules.begin();
                              std::vector<rule_type*>::const_iterator end=
                                 else_rules.end();
                              while (itr != end)
                              {
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter= symbols.begin();
                                 symbolizers::const_iterator symEnd = symbols.end();

                                 while (symIter!=symEnd)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),
                                        *symIter++);
                                 }
                                 ++itr;
                              }
                           }
                        }
                     }
                  }
               }

            }
            p.end_layer_processing(lay);
         }
         Map const& m_;
   };
}

#endif //FEATURE_STYLE_PROCESSOR_HPP
<commit_msg>clip query bbox to layer's extent<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef FEATURE_STYLE_PROCESSOR_HPP
#define FEATURE_STYLE_PROCESSOR_HPP

//stl
#include <vector>
// boost
#include <boost/progress.hpp>
// mapnik
#include <mapnik/envelope.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/attribute_collector.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/projection.hpp>
#include <mapnik/scale_denominator.hpp>

namespace mapnik
{
   template <typename Processor>
   class feature_style_processor
   {
         struct symbol_dispatch : public boost::static_visitor<>
         {
               symbol_dispatch (Processor & output,
                                Feature const& f,
                                proj_transform const& prj_trans)
                  : output_(output),
                    f_(f),
                    prj_trans_(prj_trans)  {}

               template <typename T>
               void operator () (T const& sym) const
               {
                  output_.process(sym,f_,prj_trans_);
               }

               Processor & output_;
               Feature const& f_;
               proj_transform const& prj_trans_;
         };
      public:
         feature_style_processor(Map const& m)
            : m_(m) {}

         void apply()
         {
#ifdef MAPNIK_DEBUG
            boost::progress_timer t(std::clog);
#endif
            Processor & p = static_cast<Processor&>(*this);
            p.start_map_processing(m_);

            try
            {
               projection proj(m_.srs()); // map projection
               double scale_denom = scale_denominator(m_,proj.is_geographic());
#ifdef MAPNIK_DEBUG
               std::clog << "scale denominator = " << scale_denom << "\n";
#endif
               std::vector<Layer>::const_iterator itr = m_.layers().begin();
               std::vector<Layer>::const_iterator end = m_.layers().end();

               while (itr != end)
               {
                  if (itr->isVisible(scale_denom))
                  {
                     apply_to_layer(*itr, p, proj, scale_denom);
                  }
                  ++itr;
               }
            }
            catch (proj_init_error& ex)
            {
               std::clog << "proj_init_error:" << ex.what() << "\n";
            }

            p.end_map_processing(m_);
         }
      private:
         void apply_to_layer(Layer const& lay, Processor & p,
                             projection const& proj0,double scale_denom)
         {
            p.start_layer_processing(lay);
            boost::shared_ptr<datasource> ds=lay.datasource();
            if (ds)
            {
               Envelope<double> const& ext=m_.getCurrentExtent();
               projection proj1(lay.srs());
               proj_transform prj_trans(proj0,proj1);

               Envelope<double> layer_ext = lay.envelope();
               double lx0 = layer_ext.minx();
               double ly0 = layer_ext.miny();
               double lz0 = 0.0;
               double lx1 = layer_ext.maxx();
               double ly1 = layer_ext.maxy();
               double lz1 = 0.0;
               // back project layers extent into main map projection
               prj_trans.backward(lx0,ly0,lz0);
               prj_trans.backward(lx1,ly1,lz1);
               // clip query bbox
               lx0 = std::max(ext.minx(),lx0);
               ly0 = std::max(ext.miny(),ly0);
               lx1 = std::min(ext.maxx(),lx1);
               ly1 = std::min(ext.maxy(),ly1);

               prj_trans.forward(lx0,ly0,lz0);
               prj_trans.forward(lx1,ly1,lz1);
               Envelope<double> bbox(lx0,ly0,lx1,ly1);
               double resolution = m_.getWidth()/bbox.width();

               std::vector<std::string> const& style_names = lay.styles();
               std::vector<std::string>::const_iterator stylesIter = style_names.begin();
               std::vector<std::string>::const_iterator stylesEnd = style_names.end();

               while (stylesIter != stylesEnd)
               {
                  std::set<std::string> names;
                  attribute_collector<Feature> collector(names);
                  std::vector<rule_type*> if_rules;
                  std::vector<rule_type*> else_rules;

                  bool active_rules=false;

                  feature_type_style const& style=m_.find_style(*stylesIter++);

                  query q(bbox,resolution); //BBOX query

                  const std::vector<rule_type>& rules=style.get_rules();
                  std::vector<rule_type>::const_iterator ruleIter=rules.begin();
                  std::vector<rule_type>::const_iterator ruleEnd=rules.end();

                  while (ruleIter!=ruleEnd)
                  {
                     if (ruleIter->active(scale_denom))
                     {
                        active_rules=true;
                        ruleIter->accept(collector);

                        if (ruleIter->has_else_filter())
                        {
                           else_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                        else
                        {
                           if_rules.push_back(const_cast<rule_type*>(&(*ruleIter)));
                        }
                     }
                     ++ruleIter;
                  }
                  std::set<std::string>::const_iterator namesIter=names.begin();
                  std::set<std::string>::const_iterator namesEnd =names.end();

                  // push all property names
                  while (namesIter!=namesEnd)
                  {
                     q.add_property_name(*namesIter);
                     ++namesIter;
                  }
                  if (active_rules)
                  {
                     featureset_ptr fs=ds->features(q);
                     if (fs)
                     {
                        feature_ptr feature;
                        while ((feature = fs->next()))
                        {
                           bool do_else=true;
                           std::vector<rule_type*>::const_iterator itr=if_rules.begin();
                           std::vector<rule_type*>::const_iterator end=if_rules.end();
                           while (itr != end)
                           {
                              filter_ptr const& filter=(*itr)->get_filter();
                              if (filter->pass(*feature))
                              {
                                 do_else=false;
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter=symbols.begin();
                                 symbolizers::const_iterator symEnd =symbols.end();
                                 while (symIter != symEnd)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),*symIter++);
                                 }
                              }
                              ++itr;
                           }
                           if (do_else)
                           {
                              //else filter
                              std::vector<rule_type*>::const_iterator itr=
                                 else_rules.begin();
                              std::vector<rule_type*>::const_iterator end=
                                 else_rules.end();
                              while (itr != end)
                              {
                                 const symbolizers& symbols = (*itr)->get_symbolizers();
                                 symbolizers::const_iterator symIter= symbols.begin();
                                 symbolizers::const_iterator symEnd = symbols.end();

                                 while (symIter!=symEnd)
                                 {
                                    boost::apply_visitor
                                       (symbol_dispatch(p,*feature,prj_trans),
                                        *symIter++);
                                 }
                                 ++itr;
                              }
                           }
                        }
                     }
                  }
               }

            }
            p.end_layer_processing(lay);
         }
         Map const& m_;
   };
}

#endif //FEATURE_STYLE_PROCESSOR_HPP
<|endoftext|>


<commit_before>/*
 * Mickey Scheme
 *
 * Copyright (C) 2011-2012 Christian Stigen Larsen <csl@sublevel3.org>
 * http://csl.sublevel3.org                              _
 *                                                        \
 * Distributed under the LGPL 2.1; see LICENSE            /\
 * Please post bugfixes and suggestions to the author.   /  \_
 *
 */

#include <stdlib.h>
#include <libgen.h> // dirname
#include "mickey.h"
#include "repl.h"

/*
 * Environment variables:
 */
#define MICKEY_LIB "MICKEY_LIB"

void version();
void help();

void execute(const char* file)
{
  TRY {
    environment_t *env = null_import_environment();
    reset_for_programs(&global_opts, file);
    load(file, env);
  }
  CATCH (const exception_t& e) {
    const char* file = global_opts.current_filename;
    bool has_file = file && strcmp(file, "-");

    /*
     * Finish any unfinished printing before
     * writing errors.
     */
    fflush(stdout);

    fprintf(stderr, "\nError%s%s: %s\n",
      has_file? " in " : "",
      has_file? file : "",
      e.what());

    backtrace();
    backtrace_clear();
    exit(1);
  }
}

void execute_string(const char* s)
{
  TRY {
    environment_t *env = null_import_environment();
    reset_for_programs(&global_opts, NULL);

    program_t *p = parse(s, env);
    p->root = cons(symbol("begin"), p->root);
    printf("%s\n", sprint(eval(p->root, env)).c_str());
  }
  CATCH (const exception_t& e) {
    fprintf(stderr, "\nError: %s\n", e.what());
    backtrace();
    backtrace_clear();
    exit(1);
  }
}

// return true if rest of parameters are files
bool parse_option(const char* s, struct options_t* p)
{
  #define ARGHIT(_short, _long) (!strcmp(s, _short) || !strcmp(s, _long))

  if ( !strcmp(s, "--") ) {
    return true;
  } else if ( !strncmp(s, "-I", 2) && strlen(s) > 2 ) {
    p->include_path = s+2;
  } else if ( !strncmp(s, "-L", 2) && strlen(s) > 2 ) {
    p->lib_path = s+2;
  } else if ( !strcmp(s, "-") ) {
    // TODO: read from standard input
  } else if ( ARGHIT("-v", "--verbose") ) {
    p->verbose = true;
  } else if ( ARGHIT("-V", "--version") ) {
    version();
    exit(0);
  } else if ( ARGHIT("-h", "--help") ) {
    help();
    exit(0);
  } else if ( ARGHIT("-e", "--eval") ) {
    p->eval_next = true;
  } else if ( ARGHIT("-z", "--zero-env") ) {
    p->empty_repl_env = true;
  } else {
    fprintf(stderr, "Unknown option: %s\n\n", s);
    help();
    exit(1);
  }

  return false;
}

void help()
{
  printf("Usage: mickey [ option(s) ] [ file(s) | - ]\n"
    "\n"
    "Options:\n"
    "  -             Read program from standard input\n"
    "  --            Rest of arguments are files, i.e. files can now begin with -\n"
    "  -e --eval     Execute expression and print result\n"
    "  -h --help     Print help\n"
    "  -I<path>      Set include path for (load)\n"
    "  -L<path>      Set location for library imports\n"
    "  -V --version  Print version\n"
    "  -v --verbose  Verbose operation\n"
    "  -z --zero-env Start REPL with only (import) defined\n"
    "\n");
}

void version()
{
  printf("%s\n", VERSION);
  printf("Compiler version: %s\n", __VERSION__);
}

int main(int argc, char** argv)
{
  bool rest_is_files = false; // used with option `--`
  bool run_repl = true;

  set_default(&global_opts, argc, argv);

  /*
   * If there was no -L<path> option, set library path using either
   * environment variable or current working directory.
   */
  if ( strlen(global_opts.lib_path) == 0 ) {
    if ( getenv(MICKEY_LIB) )
      set_lib_path(&global_opts, getenv(MICKEY_LIB));
    else
      set_lib_path(&global_opts,
        format("%s/lib/", global_opts.mickey_absolute_path).c_str());
  }

  for ( int n=1; n<argc; ++n ) {
    if ( global_opts.eval_next ) {
      execute_string(argv[n]);
      global_opts.eval_next = false;
      run_repl = false;
    } else if ( !rest_is_files && argv[n][0] == '-' ) {
      if ( argv[n][1] == '\0' )
        execute("-"); // stdin
      else
        rest_is_files |= parse_option(argv[n], &global_opts);
    } else {
      execute(argv[n]); // file
      run_repl = false;
    }
  }

  if ( run_repl )
    repl();

  return 0;
}
<commit_msg>Add newline after error<commit_after>/*
 * Mickey Scheme
 *
 * Copyright (C) 2011-2012 Christian Stigen Larsen <csl@sublevel3.org>
 * http://csl.sublevel3.org                              _
 *                                                        \
 * Distributed under the LGPL 2.1; see LICENSE            /\
 * Please post bugfixes and suggestions to the author.   /  \_
 *
 */

#include <stdlib.h>
#include <libgen.h> // dirname
#include "mickey.h"
#include "repl.h"

/*
 * Environment variables:
 */
#define MICKEY_LIB "MICKEY_LIB"

void version();
void help();

void execute(const char* file)
{
  TRY {
    environment_t *env = null_import_environment();
    reset_for_programs(&global_opts, file);
    load(file, env);
  }
  CATCH (const exception_t& e) {
    const char* file = global_opts.current_filename;
    bool has_file = file && strcmp(file, "-");

    /*
     * Finish any unfinished printing before
     * writing errors.
     */
    fflush(stdout);

    fprintf(stderr, "\nError%s%s: %s\n\n",
      has_file? " in " : "",
      has_file? file : "",
      e.what());

    backtrace();
    backtrace_clear();
    exit(1);
  }
}

void execute_string(const char* s)
{
  TRY {
    environment_t *env = null_import_environment();
    reset_for_programs(&global_opts, NULL);

    program_t *p = parse(s, env);
    p->root = cons(symbol("begin"), p->root);
    printf("%s\n", sprint(eval(p->root, env)).c_str());
  }
  CATCH (const exception_t& e) {
    fprintf(stderr, "\nError: %s\n", e.what());
    backtrace();
    backtrace_clear();
    exit(1);
  }
}

// return true if rest of parameters are files
bool parse_option(const char* s, struct options_t* p)
{
  #define ARGHIT(_short, _long) (!strcmp(s, _short) || !strcmp(s, _long))

  if ( !strcmp(s, "--") ) {
    return true;
  } else if ( !strncmp(s, "-I", 2) && strlen(s) > 2 ) {
    p->include_path = s+2;
  } else if ( !strncmp(s, "-L", 2) && strlen(s) > 2 ) {
    p->lib_path = s+2;
  } else if ( !strcmp(s, "-") ) {
    // TODO: read from standard input
  } else if ( ARGHIT("-v", "--verbose") ) {
    p->verbose = true;
  } else if ( ARGHIT("-V", "--version") ) {
    version();
    exit(0);
  } else if ( ARGHIT("-h", "--help") ) {
    help();
    exit(0);
  } else if ( ARGHIT("-e", "--eval") ) {
    p->eval_next = true;
  } else if ( ARGHIT("-z", "--zero-env") ) {
    p->empty_repl_env = true;
  } else {
    fprintf(stderr, "Unknown option: %s\n\n", s);
    help();
    exit(1);
  }

  return false;
}

void help()
{
  printf("Usage: mickey [ option(s) ] [ file(s) | - ]\n"
    "\n"
    "Options:\n"
    "  -             Read program from standard input\n"
    "  --            Rest of arguments are files, i.e. files can now begin with -\n"
    "  -e --eval     Execute expression and print result\n"
    "  -h --help     Print help\n"
    "  -I<path>      Set include path for (load)\n"
    "  -L<path>      Set location for library imports\n"
    "  -V --version  Print version\n"
    "  -v --verbose  Verbose operation\n"
    "  -z --zero-env Start REPL with only (import) defined\n"
    "\n");
}

void version()
{
  printf("%s\n", VERSION);
  printf("Compiler version: %s\n", __VERSION__);
}

int main(int argc, char** argv)
{
  bool rest_is_files = false; // used with option `--`
  bool run_repl = true;

  set_default(&global_opts, argc, argv);

  /*
   * If there was no -L<path> option, set library path using either
   * environment variable or current working directory.
   */
  if ( strlen(global_opts.lib_path) == 0 ) {
    if ( getenv(MICKEY_LIB) )
      set_lib_path(&global_opts, getenv(MICKEY_LIB));
    else
      set_lib_path(&global_opts,
        format("%s/lib/", global_opts.mickey_absolute_path).c_str());
  }

  for ( int n=1; n<argc; ++n ) {
    if ( global_opts.eval_next ) {
      execute_string(argv[n]);
      global_opts.eval_next = false;
      run_repl = false;
    } else if ( !rest_is_files && argv[n][0] == '-' ) {
      if ( argv[n][1] == '\0' )
        execute("-"); // stdin
      else
        rest_is_files |= parse_option(argv[n], &global_opts);
    } else {
      execute(argv[n]); // file
      run_repl = false;
    }
  }

  if ( run_repl )
    repl();

  return 0;
}
<|endoftext|>


<commit_before>#pragma once
#include "mtao/iterator/reverse.hpp"
#include "mtao/iterator/zip.hpp"
#include "mtao/type_utils.h"

namespace mtao {
    namespace algebra {

        template <typename T, typename Coefficients>
            auto horner_evaluate(const T& value, const Coefficients& coeffs) {
                using Scalar = mtao::types::remove_cvref_t<T>;
                static_assert(std::is_convertible_v<std::remove_reference_t<typename Coefficients::value_type>,Scalar>);
                Scalar ret{};
                for(auto&& c: coeffs) {
                    ret = ret * value + c;
                }
                return ret;
            }

        template <typename Values, typename Coefficients>
            auto horner_rowminor_index(const Values& values, const Coefficients& coeffs) {
                using T = typename Values::value_type;
                static_assert(std::is_convertible_v<typename Coefficients::value_type,std::remove_cv_t<T>>);
                T ret {};
                using namespace mtao::iterator;
                if constexpr(std::tuple_size_v<Coefficients> == 2) {
                    auto& A = coeffs[0];
                    auto& B = coeffs[1];
                    auto& a = values[0];
                    auto& b = values[1];
                    return a +  A *  b;
                } else if constexpr(std::tuple_size_v<Coefficients> == 3) {
                    auto& A = coeffs[0];
                    auto& B = coeffs[1];
                    auto& C = coeffs[2];
                    auto& a = values[0];
                    auto& b = values[1];
                    auto& c = values[2];
                    return a + A * ( b + B  * c);
                }
                for(auto&& [v,c]: zip(reverse(values),reverse(coeffs))) {
                    ret = ret * c + v;
                }
                return ret;
            }
        template <typename Values, typename Coefficients>
            auto horner_rowmajor_index(const Values& values, const Coefficients& coeffs) {
                using T = typename Values::value_type;
                static_assert(std::is_convertible_v<typename Coefficients::value_type,std::remove_cv_t<T>>);
                T ret{};
                if constexpr(std::tuple_size_v<Coefficients> == 2) {
                    auto& A = coeffs[0];
                    auto& B = coeffs[1];
                    auto& a = values[0];
                    auto& b = values[1];
                    return a * B +  b;
                } else if constexpr(std::tuple_size_v<Coefficients> == 3) {
                    auto& A = coeffs[0];
                    auto& B = coeffs[1];
                    auto& C = coeffs[2];
                    auto& a = values[0];
                    auto& b = values[1];
                    auto& c = values[2];
                    return (a * B +  b) * C  + c;
                }
                using namespace mtao::iterator;
                for(auto&& [v,c]:zip(values,coeffs)) {
                    ret = ret * c + v;
                }
                return ret;
            }
        template <typename T, typename Coefficients>
            auto horner_rowminor_inverse_index(T index, const Coefficients& coeffs) {
                std::array<T,std::tuple_size_v<Coefficients>> ret;
                using namespace mtao::iterator;
                for(auto&& [v,c]:zip(ret,coeffs)) {
                    auto q = std::div(index,c);
                    std::tie(index,v) = std::tie(q.quot,q.rem);
                }
                return ret;
            }
        template <typename T, typename Coefficients>
            auto horner_rowmajor_inverse_index(T index, const Coefficients& coeffs) {
                std::array<T,std::tuple_size_v<Coefficients>> ret;
                using namespace mtao::iterator;
                for(auto&& [v,c]:zip(reverse(ret),reverse(coeffs))) {
                    auto q = std::div(index,c);
                    std::tie(index,v) = std::tie(q.quot,q.rem);
                }
                return ret;
            }

    }
}
<commit_msg>Removed warnings in horner evaluation caused by pedantic copy-paste<commit_after>#pragma once
#include "mtao/iterator/reverse.hpp"
#include "mtao/iterator/zip.hpp"
#include "mtao/type_utils.h"

namespace mtao {
    namespace algebra {

        template <typename T, typename Coefficients>
            auto horner_evaluate(const T& value, const Coefficients& coeffs) {
                using Scalar = mtao::types::remove_cvref_t<T>;
                static_assert(std::is_convertible_v<std::remove_reference_t<typename Coefficients::value_type>,Scalar>);
                Scalar ret{};
                for(auto&& c: coeffs) {
                    ret = ret * value + c;
                }
                return ret;
            }

        template <typename Values, typename Coefficients>
            auto horner_rowminor_index(const Values& values, const Coefficients& coeffs) {
                using T = typename Values::value_type;
                static_assert(std::is_convertible_v<typename Coefficients::value_type,std::remove_cv_t<T>>);
                T ret {};
                using namespace mtao::iterator;
                if constexpr(std::tuple_size_v<Coefficients> == 2) {
                    auto& A = coeffs[0];
                    //auto& B = coeffs[1];
                    auto& a = values[0];
                    auto& b = values[1];
                    return a +  A *  b;
                } else if constexpr(std::tuple_size_v<Coefficients> == 3) {
                    auto& A = coeffs[0];
                    auto& B = coeffs[1];
                    //auto& C = coeffs[2];
                    auto& a = values[0];
                    auto& b = values[1];
                    auto& c = values[2];
                    return a + A * ( b + B  * c);
                }
                for(auto&& [v,c]: zip(reverse(values),reverse(coeffs))) {
                    ret = ret * c + v;
                }
                return ret;
            }
        template <typename Values, typename Coefficients>
            auto horner_rowmajor_index(const Values& values, const Coefficients& coeffs) {
                using T = typename Values::value_type;
                static_assert(std::is_convertible_v<typename Coefficients::value_type,std::remove_cv_t<T>>);
                T ret{};
                if constexpr(std::tuple_size_v<Coefficients> == 2) {
                    auto& A = coeffs[0];
                    auto& B = coeffs[1];
                    auto& a = values[0];
                    auto& b = values[1];
                    return a * B +  b;
                } else if constexpr(std::tuple_size_v<Coefficients> == 3) {
                    auto& A = coeffs[0];
                    auto& B = coeffs[1];
                    auto& C = coeffs[2];
                    auto& a = values[0];
                    auto& b = values[1];
                    auto& c = values[2];
                    return (a * B +  b) * C  + c;
                }
                using namespace mtao::iterator;
                for(auto&& [v,c]:zip(values,coeffs)) {
                    ret = ret * c + v;
                }
                return ret;
            }
        template <typename T, typename Coefficients>
            auto horner_rowminor_inverse_index(T index, const Coefficients& coeffs) {
                std::array<T,std::tuple_size_v<Coefficients>> ret;
                using namespace mtao::iterator;
                for(auto&& [v,c]:zip(ret,coeffs)) {
                    auto q = std::div(index,c);
                    std::tie(index,v) = std::tie(q.quot,q.rem);
                }
                return ret;
            }
        template <typename T, typename Coefficients>
            auto horner_rowmajor_inverse_index(T index, const Coefficients& coeffs) {
                std::array<T,std::tuple_size_v<Coefficients>> ret;
                using namespace mtao::iterator;
                for(auto&& [v,c]:zip(reverse(ret),reverse(coeffs))) {
                    auto q = std::div(index,c);
                    std::tie(index,v) = std::tie(q.quot,q.rem);
                }
                return ret;
            }

    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2019 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#ifndef VCF2MULTIALIGN_PREPROCESS_TYPES_HH
#define VCF2MULTIALIGN_PREPROCESS_TYPES_HH

#include <cstdint>
#include <vector>

namespace vcf2multialign {

	typedef std::uint16_t path_number_type;
	typedef std::uint32_t sample_number_type;
	typedef std::vector <path_number_type>		path_vector;
	typedef std::vector <path_vector>			path_matrix;
	typedef std::vector <sample_number_type>	sample_vector;
	typedef std::vector <sample_vector>			sample_map;

	enum { PATH_NUMBER_MAX = std::numeric_limits <path_number_type>::max() };
}

#endif
<commit_msg>Add constant for maximum sample number<commit_after>/*
 * Copyright (c) 2019 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#ifndef VCF2MULTIALIGN_PREPROCESS_TYPES_HH
#define VCF2MULTIALIGN_PREPROCESS_TYPES_HH

#include <cstdint>
#include <vector>

namespace vcf2multialign {

	typedef std::uint16_t path_number_type;
	typedef std::uint32_t sample_number_type;
	typedef std::vector <path_number_type>		path_vector;
	typedef std::vector <path_vector>			path_matrix;
	typedef std::vector <sample_number_type>	sample_vector;
	typedef std::vector <sample_vector>			sample_map;

	enum {
		PATH_NUMBER_MAX		= std::numeric_limits <path_number_type>::max(),
		SAMPLE_NUMBER_MAX	= std::numeric_limits <sample_number_type>::max()
	};
}

#endif
<|endoftext|>


<commit_before>#ifndef VMU_WINDOWS_DEFINITIONS_HPP
#define VMU_WINDOWS_DEFINITIONS_HPP

namespace vmu { namespace detail {

#ifdef _WIN64
    #if defined(__CYGWIN__)
    typedef unsigned long ULONG_PTR_;
    #else
    typedef unsigned __int64 ULONG_PTR_;
    #endif
#else
    typedef unsigned long ULONG_PTR_;
#endif

    struct MEMORY_BASIC_INFORMATION {
        void* BaseAddress;
        void* AllocationBase;
        unsigned long AllocationProtect;
        ULONG_PTR_    RegionSize;
        unsigned long State;
        unsigned long Protect;
        unsigned long Type;
    };

    struct SYSTEM_INFO {
        union {
            unsigned long dwOemId;
            struct {
                unsigned short wProcessorArchitecture;
                unsigned short wReserved;
            };
        };
        unsigned long dwPageSize;
        void* lpMinimumApplicationAddress;
        void* lpMaximumApplicationAddress;
        ULONG_PTR_     dwActiveProcessorMask;
        unsigned long  dwNumberOfProcessors;
        unsigned long  dwProcessorType;
        unsigned long  dwAllocationGranularity;
        unsigned short wProcessorLevel;
        unsigned short wProcessorRevision;
    };

    extern "C" __declspec(dllimport) unsigned long __stdcall GetLastError();

    extern "C" __declspec(dllimport) ULONG_PTR_ __stdcall
    VirtualQueryEx(void* handle
                   , const void* address
                   , MEMORY_BASIC_INFORMATION* buffer
                   , ULONG_PTR_ size_of_info);

    extern "C" __declspec(dllimport) void __stdcall GetSystemInfo(SYSTEM_INFO* info);

    constexpr static unsigned long mem_commit  = 0x1000;
    constexpr static unsigned long mem_free    = 0x10000;
    constexpr static unsigned long mem_reserve = 0x2000;
    constexpr static unsigned long mem_private = 0x20000;
    constexpr static unsigned long page_guard  = 0x100;
    constexpr static unsigned long no_access   = 0x01;

}} // namespace vmu::detail

#endif // include guard
<commit_msg>added GetCurrentProcess import<commit_after>#ifndef VMU_WINDOWS_DEFINITIONS_HPP
#define VMU_WINDOWS_DEFINITIONS_HPP

namespace vmu { namespace detail {

#ifdef _WIN64
    #if defined(__CYGWIN__)
    typedef unsigned long ULONG_PTR_;
    #else
    typedef unsigned __int64 ULONG_PTR_;
    #endif
#else
    typedef unsigned long ULONG_PTR_;
#endif

    struct MEMORY_BASIC_INFORMATION {
        void* BaseAddress;
        void* AllocationBase;
        unsigned long AllocationProtect;
        ULONG_PTR_    RegionSize;
        unsigned long State;
        unsigned long Protect;
        unsigned long Type;
    };

    struct SYSTEM_INFO {
        union {
            unsigned long dwOemId;
            struct {
                unsigned short wProcessorArchitecture;
                unsigned short wReserved;
            };
        };
        unsigned long dwPageSize;
        void* lpMinimumApplicationAddress;
        void* lpMaximumApplicationAddress;
        ULONG_PTR_     dwActiveProcessorMask;
        unsigned long  dwNumberOfProcessors;
        unsigned long  dwProcessorType;
        unsigned long  dwAllocationGranularity;
        unsigned short wProcessorLevel;
        unsigned short wProcessorRevision;
    };

    extern "C" __declspec(dllimport) unsigned long __stdcall GetLastError();

    extern "C" __declspec(dllimport) ULONG_PTR_ __stdcall
    VirtualQueryEx(void* handle
                   , const void* address
                   , MEMORY_BASIC_INFORMATION* buffer
                   , ULONG_PTR_ size_of_info);

    extern "C" __declspec(dllimport) void __stdcall GetSystemInfo(SYSTEM_INFO* info);

    extern "C" __deckspec(dllimport) void* __stdcall GetCurrentProcess();

    constexpr static unsigned long mem_commit  = 0x1000;
    constexpr static unsigned long mem_free    = 0x10000;
    constexpr static unsigned long mem_reserve = 0x2000;
    constexpr static unsigned long mem_private = 0x20000;
    constexpr static unsigned long page_guard  = 0x100;
    constexpr static unsigned long no_access   = 0x01;

}} // namespace vmu::detail

#endif // include guard
<|endoftext|>


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

#ifndef __FRAMEWORK_CLASSES_IMAGESCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_IMAGESCONFIGURATION_HXX_

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif

// #110897#
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

#include <vector>

namespace framework
{

enum ImageMaskMode
{
    ImageMaskMode_Color,
    ImageMaskMode_Bitmap
};

struct ImageItemDescriptor
{
    ImageItemDescriptor() : nIndex( -1 ) {}

    String  aCommandURL;                // URL command to dispatch
    long    nIndex;                     // index of the bitmap inside the bitmaplist
};

struct ExternalImageItemDescriptor
{
    String  aCommandURL;                // URL command to dispatch
    String  aURL;                       // a URL to an external bitmap
};

typedef ImageItemDescriptor* ImageItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ImageItemListDescriptor, ImageItemDescriptorPtr, 10, 2)

typedef ExternalImageItemDescriptor* ExternalImageItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ExternalImageItemListDescriptor, ExternalImageItemDescriptorPtr, 10, 2)

struct ImageListItemDescriptor
{
    ImageListItemDescriptor() : pImageItemList( 0 )
                                , nMaskMode( ImageMaskMode_Color ) {}
    ~ImageListItemDescriptor() { delete pImageItemList; }

    String                      aURL;                   // an URL to a bitmap with several images inside
    Color                       aMaskColor;             // a color used as transparent
    String                      aMaskURL;               // an URL to an optional bitmap used as a mask
    ImageMaskMode               nMaskMode;              // an enum to describe the current mask mode
    ImageItemListDescriptor*    pImageItemList;         // an array of ImageItemDescriptors that describes every image
    String                      aHighContrastURL;       // an URL to an optional high contrast bitmap with serveral images inside
    String                      aHighContrastMaskURL;   // an URL to an optional high contrast bitmap as a mask
};

typedef ImageListItemDescriptor* ImageListItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ImageListDescriptor, ImageListItemDescriptorPtr, 10, 2)

struct ImageListsDescriptor
{
    ImageListsDescriptor() : pImageList( 0 ),
                             pExternalImageList( 0 ) {}
    ~ImageListsDescriptor() { delete pImageList; delete pExternalImageList; }

    ImageListDescriptor*                pImageList;
    ExternalImageItemListDescriptor*    pExternalImageList;
};

class ImagesConfiguration
{
    public:
        // #110897#
        static sal_Bool LoadImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rInStream, ImageListsDescriptor& aItems );

        // #110897#
        static sal_Bool StoreImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rOutStream, const ImageListsDescriptor& aItems );

        static sal_Bool LoadImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream,
            ImageListsDescriptor& rItems );

        static sal_Bool StoreImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream,
            const ImageListsDescriptor& rItems );
};

} // namespace framework

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

#ifndef __FRAMEWORK_CLASSES_IMAGESCONFIGURATION_HXX_
#define __FRAMEWORK_CLASSES_IMAGESCONFIGURATION_HXX_

#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif

// #110897#
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

#include <vector>

namespace framework
{

enum ImageMaskMode
{
    ImageMaskMode_Color,
    ImageMaskMode_Bitmap
};

struct ImageItemDescriptor
{
    ImageItemDescriptor() : nIndex( -1 ) {}

    String  aCommandURL;                // URL command to dispatch
    long    nIndex;                     // index of the bitmap inside the bitmaplist
};

struct ExternalImageItemDescriptor
{
    String  aCommandURL;                // URL command to dispatch
    String  aURL;                       // a URL to an external bitmap
};

typedef ImageItemDescriptor* ImageItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ImageItemListDescriptor, ImageItemDescriptorPtr, 10, 2)

typedef ExternalImageItemDescriptor* ExternalImageItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ExternalImageItemListDescriptor, ExternalImageItemDescriptorPtr, 10, 2)

struct ImageListItemDescriptor
{
    ImageListItemDescriptor() : pImageItemList( 0 )
                                , nMaskMode( ImageMaskMode_Color ) {}
    ~ImageListItemDescriptor() { delete pImageItemList; }

    String                      aURL;                   // an URL to a bitmap with several images inside
    Color                       aMaskColor;             // a color used as transparent
    String                      aMaskURL;               // an URL to an optional bitmap used as a mask
    ImageMaskMode               nMaskMode;              // an enum to describe the current mask mode
    ImageItemListDescriptor*    pImageItemList;         // an array of ImageItemDescriptors that describes every image
    String                      aHighContrastURL;       // an URL to an optional high contrast bitmap with serveral images inside
    String                      aHighContrastMaskURL;   // an URL to an optional high contrast bitmap as a mask
};

typedef ImageListItemDescriptor* ImageListItemDescriptorPtr;
SV_DECL_PTRARR_DEL( ImageListDescriptor, ImageListItemDescriptorPtr, 10, 2)

struct ImageListsDescriptor
{
    ImageListsDescriptor() : pImageList( 0 ),
                             pExternalImageList( 0 ) {}
    ~ImageListsDescriptor() { delete pImageList; delete pExternalImageList; }

    ImageListDescriptor*                pImageList;
    ExternalImageItemListDescriptor*    pExternalImageList;
};

class ImagesConfiguration
{
    public:
        // #110897#
        static sal_Bool LoadImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rInStream, ImageListsDescriptor& aItems );

        // #110897#
        static sal_Bool StoreImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            SvStream& rOutStream, const ImageListsDescriptor& aItems );

        static sal_Bool LoadImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& rInputStream,
            ImageListsDescriptor& rItems );

        static sal_Bool StoreImages(
            const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
            const ::com::sun::star::uno::Reference< ::com::sun::star::io::XOutputStream >& rOutputStream,
            const ImageListsDescriptor& rItems );
};

} // namespace framework

#endif // __FRAMEWORK_CLASSES_IMAGES
<|endoftext|>