<commit_before>/*************************************************************************
 *
 *  $RCSfile: elementformatter.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ssmith $ $Date: 2002-10-21 13:17:59 $
 *
 *  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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "elementformatter.hxx"

#ifndef CONFIGMGR_XML_STRINGS_HXX_
#include "xmlstrings.hxx"
#endif

#ifndef CONFIGMGR_TYPECONVERTER_HXX
#include "typeconverter.hxx"
#endif
#ifndef CONFIGMGR_MISC_ATTRIBUTELIST_HXX
#include "attributelist.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#include <drafts/com/sun/star/configuration/backend/SchemaAttribute.hpp>
#include <drafts/com/sun/star/configuration/backend/NodeAttribute.hpp>

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

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace xml
    {
// -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        namespace sax       = ::com::sun::star::xml::sax;
// -----------------------------------------------------------------------------

ElementFormatter::ElementFormatter()
: m_aElementType(ElementType::unknown)
, m_xAttributes()
{
}
// -----------------------------------------------------------------------------

ElementFormatter::~ElementFormatter()
{
}
// -----------------------------------------------------------------------------

void ElementFormatter::reset()
{
    m_aElementType = ElementType::unknown;
    m_xAttributes.clear();
}
// -----------------------------------------------------------------------------

void ElementFormatter::addAttribute(OUString const & _anAttributeName, OUString const & _aValue)
{
    OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list");

    m_xAttributes->addAttribute(_anAttributeName,
                                XML_ATTRTYPE_CDATA,
                                _aValue);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addAttribute(OUString const & _anAttributeName, bool _bValue)
{
    OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list");

    m_xAttributes->addAttribute(_anAttributeName,
                                XML_ATTRTYPE_CDATA,
                                _bValue ? ATTR_VALUE_TRUE : ATTR_VALUE_FALSE);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addNamespaces()
{
    static OUString const sNamespaceDecl( RTL_CONSTASCII_USTRINGPARAM("xmlns:") );

    addAttribute( sNamespaceDecl.concat(NS_PREFIX_OOR), static_cast<OUString const &>(NS_URI_OOR));
    addAttribute( sNamespaceDecl.concat(NS_PREFIX_XS ), static_cast<OUString const &>(NS_URI_XS ));
}
// -----------------------------------------------------------------------------

void ElementFormatter::prepareElement(ElementInfo const& _aInfo)
{
    if (!m_xAttributes.is())
    {
        m_xAttributes.set( new AttributeListImpl() );
        addNamespaces();
    }
    else
        m_xAttributes->clear();

    m_aElementType = _aInfo.type;

    addName(_aInfo.name);
    addNodeFlags(_aInfo.flags);
    addOperation(_aInfo.op);
}
// -----------------------------------------------------------------------------

void ElementFormatter::prepareSimpleElement(ElementType::Enum _eType)
{
    if (!m_xAttributes.is())
    {
        m_xAttributes.set( new AttributeListImpl() );
        addNamespaces();
    }
    else
        m_xAttributes->clear();

    m_aElementType = _eType;
}
// -----------------------------------------------------------------------------

void ElementFormatter::addName(OUString const & _aName)
{
    OUString _aContext;
    OUString _aNodeName;
    sal_Int32 _aIndex;

    if ( m_aElementType == ElementType::layer )
    {
        _aIndex = _aName.lastIndexOf ( '.');

        if (_aName.getLength())
        {
            _aNodeName = _aName.copy(++_aIndex);
            addAttribute(ATTR_NAME, _aNodeName);
        }
        _aContext = _aName.copy( 0, --_aIndex);
        addAttribute(ATTR_CONTEXT, _aContext);
    }
    else
    {
        if (_aName.getLength())
            addAttribute(ATTR_NAME, _aName);
    }
}
// -----------------------------------------------------------------------------

inline
void ElementFormatter::maybeAddFlag(FlagsType _eFlags, FlagsType _eSelect, OUString const & _anAttributeName, bool _bValue)
{
    if (_eFlags & _eSelect) addAttribute(_anAttributeName,_bValue);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addNodeFlags(FlagsType _eFlags)
{
    using namespace drafts::com::sun::star::configuration::backend;;

    maybeAddFlag(_eFlags,SchemaAttribute::REQUIRED,    ATTR_FLAG_NULLABLE, false);
    maybeAddFlag(_eFlags,SchemaAttribute::LOCALIZED,   ATTR_FLAG_LOCALIZED);
    maybeAddFlag(_eFlags,SchemaAttribute::EXTENSIBLE,  ATTR_FLAG_EXTENSIBLE);

    maybeAddFlag(_eFlags,NodeAttribute::FINALIZED, ATTR_FLAG_FINALIZED);
    maybeAddFlag(_eFlags,NodeAttribute::MANDATORY, ATTR_FLAG_MANDATORY);
    maybeAddFlag(_eFlags,NodeAttribute::READONLY,  ATTR_FLAG_READONLY);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addOperation(Operation::Enum _eOp)
{
    switch (_eOp)
    {
    case Operation::none:       break;
    case Operation::modify:     break ; //addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_MODIFY));  break;
    case Operation::replace:    addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REPLACE)); break;
    case Operation::remove:     addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REMOVE));  break;

    case Operation::unknown:
        OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for 'unknown' operation");
        break;
    default:
        OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for invalid operation");
        break;
    }
}
// -----------------------------------------------------------------------------

void ElementFormatter::addInstanceType(OUString const & _aElementType, OUString const & _aElementTypeModule)
{
}
// -----------------------------------------------------------------------------

static ::rtl::OUString toXmlTypeName(const uno::TypeClass& _rTypeClass)
{
    ::rtl::OUString aRet;
    switch(_rTypeClass)
    {
    case uno::TypeClass_BOOLEAN:  aRet = VALUETYPE_BOOLEAN; break;
    case uno::TypeClass_SHORT:    aRet = VALUETYPE_SHORT; break;
    case uno::TypeClass_LONG:     aRet = VALUETYPE_INT; break;
    case uno::TypeClass_HYPER:    aRet = VALUETYPE_LONG; break;
    case uno::TypeClass_DOUBLE:   aRet = VALUETYPE_DOUBLE; break;
    case uno::TypeClass_STRING:   aRet = VALUETYPE_STRING; break;
    case uno::TypeClass_SEQUENCE: aRet = VALUETYPE_BINARY; break;
    case uno::TypeClass_ANY:      aRet = VALUETYPE_ANY; break;
    default:
        OSL_ENSURE(false,"Cannot get type name: unknown typeclass");
        break;
    }
    return aRet;
}
// -----------------------------------------------------------------------------

void ElementFormatter::addPropertyValueType(uno::Type const& _aType)
{
    if (_aType == uno::Type()) return;

    bool bList = false;
    uno::Type       aSimpleType         = getBasicType(_aType, bList);
    uno::TypeClass  aSimpleTypeClass    = aSimpleType.getTypeClass();
    OUString        aSimpleTypeName     = toXmlTypeName(aSimpleTypeClass);

    OUString sNsPrefix = (bList || aSimpleTypeClass == uno::TypeClass_ANY) ? NS_PREFIX_OOR : NS_PREFIX_XS;

    rtl::OUStringBuffer aTypeNameBuf(sNsPrefix);

    if (sNsPrefix.getLength())
        aTypeNameBuf. append(k_NS_SEPARATOR);

    aTypeNameBuf. append(aSimpleTypeName);

    if (bList)
        aTypeNameBuf. append(VALUETYPE_LIST_SUFFIX);

    addAttribute( ATTR_VALUETYPE, aTypeNameBuf.makeStringAndClear());
}
// -----------------------------------------------------------------------------

void ElementFormatter::addLanguage(OUString const & _sLanguage)
{
    OSL_ENSURE(_sLanguage.getLength(), "ElementFormatter: Trying to add empty language attribute");
    addAttribute(EXT_ATTR_LANGUAGE, _sLanguage);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addIsNull(bool _bIsNull)
{
    addAttribute( EXT_ATTR_NULL, _bIsNull);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addSeparator(OUString const& _sSeparator)
{
    addAttribute( ATTR_VALUESEPARATOR, _sSeparator);
}
// -----------------------------------------------------------------------------

OUString ElementFormatter::getElementTag() const
{
    switch (m_aElementType)
    {
    case ElementType::schema:    return TAG_SCHEMA;
    case ElementType::layer:     return TAG_LAYER;

    case ElementType::component: return TAG_COMPONENT;
    case ElementType::templates: return TAG_TEMPLATES;

    case ElementType::property:  return TAG_PROP;
    case ElementType::node:      return TAG_NODE;
    case ElementType::group:     return TAG_GROUP;
    case ElementType::set:       return TAG_SET;

    case ElementType::import:    return TAG_IMPORT;
    case ElementType::instance:  return TAG_INSTANCE;
    case ElementType::item_type: return TAG_ITEMTYPE;
    case ElementType::value:     return TAG_VALUE;
    case ElementType::uses:      return TAG_USES;

    case ElementType::unknown:
        OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'unknown' element type");
        break;
    case ElementType::other:
        OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'other' element type");
        break;
    default:
        OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for invalid element type");
        break;
    }
    return OUString();
}
// -----------------------------------------------------------------------------

uno::Reference< sax::XAttributeList > ElementFormatter::getElementAttributes() const
{
    return m_xAttributes.get();
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
} // namespace
} // namespace

<commit_msg>#103812# updated root node name format<commit_after>/*************************************************************************
 *
 *  $RCSfile: elementformatter.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ssmith $ $Date: 2002-10-21 13:33:56 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT 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: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "elementformatter.hxx"

#ifndef CONFIGMGR_XML_STRINGS_HXX_
#include "xmlstrings.hxx"
#endif

#ifndef CONFIGMGR_TYPECONVERTER_HXX
#include "typeconverter.hxx"
#endif
#ifndef CONFIGMGR_MISC_ATTRIBUTELIST_HXX
#include "attributelist.hxx"
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#include <drafts/com/sun/star/configuration/backend/SchemaAttribute.hpp>
#include <drafts/com/sun/star/configuration/backend/NodeAttribute.hpp>

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

namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace xml
    {
// -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        namespace sax       = ::com::sun::star::xml::sax;
// -----------------------------------------------------------------------------

ElementFormatter::ElementFormatter()
: m_aElementType(ElementType::unknown)
, m_xAttributes()
{
}
// -----------------------------------------------------------------------------

ElementFormatter::~ElementFormatter()
{
}
// -----------------------------------------------------------------------------

void ElementFormatter::reset()
{
    m_aElementType = ElementType::unknown;
    m_xAttributes.clear();
}
// -----------------------------------------------------------------------------

void ElementFormatter::addAttribute(OUString const & _anAttributeName, OUString const & _aValue)
{
    OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list");

    m_xAttributes->addAttribute(_anAttributeName,
                                XML_ATTRTYPE_CDATA,
                                _aValue);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addAttribute(OUString const & _anAttributeName, bool _bValue)
{
    OSL_PRECOND(m_xAttributes.is(),"Trying to add an attribute to a non-existing list");

    m_xAttributes->addAttribute(_anAttributeName,
                                XML_ATTRTYPE_CDATA,
                                _bValue ? ATTR_VALUE_TRUE : ATTR_VALUE_FALSE);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addNamespaces()
{
    static OUString const sNamespaceDecl( RTL_CONSTASCII_USTRINGPARAM("xmlns:") );

    addAttribute( sNamespaceDecl.concat(NS_PREFIX_OOR), static_cast<OUString const &>(NS_URI_OOR));
    addAttribute( sNamespaceDecl.concat(NS_PREFIX_XS ), static_cast<OUString const &>(NS_URI_XS ));
}
// -----------------------------------------------------------------------------

void ElementFormatter::prepareElement(ElementInfo const& _aInfo)
{
    if (!m_xAttributes.is())
    {
        m_xAttributes.set( new AttributeListImpl() );
        addNamespaces();
    }
    else
        m_xAttributes->clear();

    m_aElementType = _aInfo.type;

    addName(_aInfo.name);
    addNodeFlags(_aInfo.flags);
    addOperation(_aInfo.op);
}
// -----------------------------------------------------------------------------

void ElementFormatter::prepareSimpleElement(ElementType::Enum _eType)
{
    if (!m_xAttributes.is())
    {
        m_xAttributes.set( new AttributeListImpl() );
        addNamespaces();
    }
    else
        m_xAttributes->clear();

    m_aElementType = _eType;
}
// -----------------------------------------------------------------------------

void ElementFormatter::addName(OUString const & _aName)
{
    OUString _aContext;
    OUString _aNodeName;
    sal_Int32 _aIndex;

    if ( m_aElementType == ElementType::layer )
    {
        if (_aName.getLength())
        {
            _aIndex = _aName.lastIndexOf ( '.');
            _aNodeName = _aName.copy(++_aIndex);
            addAttribute(ATTR_NAME, _aNodeName);
            _aContext = _aName.copy( 0, --_aIndex);
            addAttribute(ATTR_CONTEXT, _aContext);
        }
    }
    else
    {
        if (_aName.getLength())
            addAttribute(ATTR_NAME, _aName);
    }
}
// -----------------------------------------------------------------------------

inline
void ElementFormatter::maybeAddFlag(FlagsType _eFlags, FlagsType _eSelect, OUString const & _anAttributeName, bool _bValue)
{
    if (_eFlags & _eSelect) addAttribute(_anAttributeName,_bValue);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addNodeFlags(FlagsType _eFlags)
{
    using namespace drafts::com::sun::star::configuration::backend;;

    maybeAddFlag(_eFlags,SchemaAttribute::REQUIRED,    ATTR_FLAG_NULLABLE, false);
    maybeAddFlag(_eFlags,SchemaAttribute::LOCALIZED,   ATTR_FLAG_LOCALIZED);
    maybeAddFlag(_eFlags,SchemaAttribute::EXTENSIBLE,  ATTR_FLAG_EXTENSIBLE);

    maybeAddFlag(_eFlags,NodeAttribute::FINALIZED, ATTR_FLAG_FINALIZED);
    maybeAddFlag(_eFlags,NodeAttribute::MANDATORY, ATTR_FLAG_MANDATORY);
    maybeAddFlag(_eFlags,NodeAttribute::READONLY,  ATTR_FLAG_READONLY);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addOperation(Operation::Enum _eOp)
{
    switch (_eOp)
    {
    case Operation::none:       break;
    case Operation::modify:     break ; //addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_MODIFY));  break;
    case Operation::replace:    addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REPLACE)); break;
    case Operation::remove:     addAttribute(ATTR_OPERATION, static_cast<OUString const &>(OPERATION_REMOVE));  break;

    case Operation::unknown:
        OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for 'unknown' operation");
        break;
    default:
        OSL_ENSURE(false, "ElementFormatter: Trying to add attribute for invalid operation");
        break;
    }
}
// -----------------------------------------------------------------------------

void ElementFormatter::addInstanceType(OUString const & _aElementType, OUString const & _aElementTypeModule)
{
}
// -----------------------------------------------------------------------------

static ::rtl::OUString toXmlTypeName(const uno::TypeClass& _rTypeClass)
{
    ::rtl::OUString aRet;
    switch(_rTypeClass)
    {
    case uno::TypeClass_BOOLEAN:  aRet = VALUETYPE_BOOLEAN; break;
    case uno::TypeClass_SHORT:    aRet = VALUETYPE_SHORT; break;
    case uno::TypeClass_LONG:     aRet = VALUETYPE_INT; break;
    case uno::TypeClass_HYPER:    aRet = VALUETYPE_LONG; break;
    case uno::TypeClass_DOUBLE:   aRet = VALUETYPE_DOUBLE; break;
    case uno::TypeClass_STRING:   aRet = VALUETYPE_STRING; break;
    case uno::TypeClass_SEQUENCE: aRet = VALUETYPE_BINARY; break;
    case uno::TypeClass_ANY:      aRet = VALUETYPE_ANY; break;
    default:
        OSL_ENSURE(false,"Cannot get type name: unknown typeclass");
        break;
    }
    return aRet;
}
// -----------------------------------------------------------------------------

void ElementFormatter::addPropertyValueType(uno::Type const& _aType)
{
    if (_aType == uno::Type()) return;

    bool bList = false;
    uno::Type       aSimpleType         = getBasicType(_aType, bList);
    uno::TypeClass  aSimpleTypeClass    = aSimpleType.getTypeClass();
    OUString        aSimpleTypeName     = toXmlTypeName(aSimpleTypeClass);

    OUString sNsPrefix = (bList || aSimpleTypeClass == uno::TypeClass_ANY) ? NS_PREFIX_OOR : NS_PREFIX_XS;

    rtl::OUStringBuffer aTypeNameBuf(sNsPrefix);

    if (sNsPrefix.getLength())
        aTypeNameBuf. append(k_NS_SEPARATOR);

    aTypeNameBuf. append(aSimpleTypeName);

    if (bList)
        aTypeNameBuf. append(VALUETYPE_LIST_SUFFIX);

    addAttribute( ATTR_VALUETYPE, aTypeNameBuf.makeStringAndClear());
}
// -----------------------------------------------------------------------------

void ElementFormatter::addLanguage(OUString const & _sLanguage)
{
    OSL_ENSURE(_sLanguage.getLength(), "ElementFormatter: Trying to add empty language attribute");
    addAttribute(EXT_ATTR_LANGUAGE, _sLanguage);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addIsNull(bool _bIsNull)
{
    addAttribute( EXT_ATTR_NULL, _bIsNull);
}
// -----------------------------------------------------------------------------

void ElementFormatter::addSeparator(OUString const& _sSeparator)
{
    addAttribute( ATTR_VALUESEPARATOR, _sSeparator);
}
// -----------------------------------------------------------------------------

OUString ElementFormatter::getElementTag() const
{
    switch (m_aElementType)
    {
    case ElementType::schema:    return TAG_SCHEMA;
    case ElementType::layer:     return TAG_LAYER;

    case ElementType::component: return TAG_COMPONENT;
    case ElementType::templates: return TAG_TEMPLATES;

    case ElementType::property:  return TAG_PROP;
    case ElementType::node:      return TAG_NODE;
    case ElementType::group:     return TAG_GROUP;
    case ElementType::set:       return TAG_SET;

    case ElementType::import:    return TAG_IMPORT;
    case ElementType::instance:  return TAG_INSTANCE;
    case ElementType::item_type: return TAG_ITEMTYPE;
    case ElementType::value:     return TAG_VALUE;
    case ElementType::uses:      return TAG_USES;

    case ElementType::unknown:
        OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'unknown' element type");
        break;
    case ElementType::other:
        OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for 'other' element type");
        break;
    default:
        OSL_ENSURE(false, "ElementFormatter: Trying to get Tag for invalid element type");
        break;
    }
    return OUString();
}
// -----------------------------------------------------------------------------

uno::Reference< sax::XAttributeList > ElementFormatter::getElementAttributes() const
{
    return m_xAttributes.get();
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
} // namespace
} // namespace

<|endoftext|>


<commit_before>/*
 * CardDeck.cpp
 *
 *  Created on: 2014年10月25日
 *      Author: nemo
 */

#include "CardDeck.h"

#include <iostream>

CardDeck::CardDeck()
{
	LOG_TRACE("Construct CardDeck.")

}

CardDeck::~CardDeck()
{
	// TODO Auto-generated destructor stub
}

///	Insert card into card deck.
/**
 * @brief	Insert card into card deck.
 *
 * @param 	card	Input card pointer.
 */
void CardDeck::push_back(Card *card)
{
	_card.push_back(card);
}

///	Show all card in card deck.
void CardDeck::show()
{
	for(auto card :_card)
	{
		card->show();
	}

}
<commit_msg>Set auto card in show(0) as const.<commit_after>/*
 * CardDeck.cpp
 *
 *  Created on: 2014年10月25日
 *      Author: nemo
 */

#include "CardDeck.h"

#include <iostream>

CardDeck::CardDeck()
{
	LOG_TRACE("Construct CardDeck.")

}

CardDeck::~CardDeck()
{
	// TODO Auto-generated destructor stub
}

///	Insert card into card deck.
/**
 * @brief	Insert card into card deck.
 *
 * @param 	card	Input card pointer.
 */
void CardDeck::push_back(Card *card)
{
	_card.push_back(card);
}

///	Show all card in card deck.
void CardDeck::show()
{
	for(const auto card :_card)
	{
		card->show();
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

#include <assert.h>
#include <cstddef>
#include <string.h>
#include <stdlib.h>

extern "C" {
#include <ovsdb_wrapper.h>
};
#include <oper/agent_sandesh.h>
#include <ovsdb_types.h>
#include <ovsdb_client_idl.h>
#include <ovsdb_client_session.h>
#include <ovsdb_route_peer.h>
#include <ovsdb_entry.h>
#include <physical_switch_ovsdb.h>
#include <logical_switch_ovsdb.h>
#include <physical_port_ovsdb.h>
#include <physical_locator_ovsdb.h>
#include <vlan_port_binding_ovsdb.h>
#include <unicast_mac_local_ovsdb.h>
#include <unicast_mac_remote_ovsdb.h>
#include <vm_interface_ksync.h>

SandeshTraceBufferPtr OvsdbTraceBuf(SandeshTraceBufferCreate("Ovsdb", 5000));
SandeshTraceBufferPtr OvsdbPktTraceBuf(SandeshTraceBufferCreate("Ovsdb Pkt", 5000));

class PhysicalDeviceTable;
class InterfaceTable;
class PhysicalDeviceVnTable;

using OVSDB::OvsdbClientIdl;
using OVSDB::OvsdbClientSession;
using OVSDB::OvsdbEntryBase;
using OVSDB::VMInterfaceKSyncObject;
using OVSDB::PhysicalSwitchTable;
using OVSDB::LogicalSwitchTable;
using OVSDB::PhysicalPortTable;
using OVSDB::PhysicalLocatorTable;
using OVSDB::VlanPortBindingTable;
using OVSDB::UnicastMacLocalOvsdb;
using OVSDB::VrfOvsdbObject;

namespace OVSDB {
void ovsdb_wrapper_idl_callback(void *idl_base, int op,
        struct ovsdb_idl_row *row) {
    OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;
    int i = ovsdb_wrapper_row_type(row);
    if (i >= OvsdbClientIdl::OVSDB_TYPE_COUNT)
        return;
    if (client_idl->callback_[i] != NULL)
        client_idl->callback_[i]((OvsdbClientIdl::Op)op, row);
}

void ovsdb_wrapper_idl_txn_ack(void *idl_base, struct ovsdb_idl_txn *txn) {
    OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;
    OvsdbEntryBase *entry = client_idl->pending_txn_[txn];
    bool success = ovsdb_wrapper_is_txn_success(txn);
    if (!success) {
        OVSDB_TRACE(Error, "Transaction failed: " +
                std::string(ovsdb_wrapper_txn_get_error(txn)));
        // we don't handle the case where txn fails, when entry is not present
        // case of unicast_mac_remote entry.
        assert(entry != NULL);
    }
    client_idl->DeleteTxn(txn);
    if (entry)
        entry->Ack(success);
}
};

OvsdbClientIdl::OvsdbClientIdl(OvsdbClientSession *session, Agent *agent,
        OvsPeerManager *manager) : idl_(ovsdb_wrapper_idl_create()),
    session_(session), agent_(agent), pending_txn_() {
    vtep_global_= ovsdb_wrapper_vteprec_global_first(idl_);
    ovsdb_wrapper_idl_set_callback(idl_, (void *)this,
            ovsdb_wrapper_idl_callback, ovsdb_wrapper_idl_txn_ack);
    parser_ = NULL;
    for (int i = 0; i < OVSDB_TYPE_COUNT; i++) {
        callback_[i] = NULL;
    }
    route_peer_.reset(manager->Allocate(IpAddress()));
    vm_interface_table_.reset(new VMInterfaceKSyncObject(this,
                (DBTable *)agent->interface_table()));
    physical_switch_table_.reset(new PhysicalSwitchTable(this));
    logical_switch_table_.reset(new LogicalSwitchTable(this,
               (DBTable *)agent->physical_device_vn_table()));
    physical_port_table_.reset(new PhysicalPortTable(this));
    physical_locator_table_.reset(new PhysicalLocatorTable(this));
    vlan_port_table_.reset(new VlanPortBindingTable(this,
                (DBTable *)agent->interface_table()));
    unicast_mac_local_ovsdb_.reset(new UnicastMacLocalOvsdb(this,
                route_peer()));
    vrf_ovsdb_.reset(new VrfOvsdbObject(this, (DBTable *)agent->vrf_table()));
}

OvsdbClientIdl::~OvsdbClientIdl() {
    ovsdb_wrapper_idl_destroy(idl_);
}

void OvsdbClientIdl::SendMointorReq() {
    OVSDB_TRACE(Trace, "Sending Monitor Request");
    SendJsonRpc(ovsdb_wrapper_idl_encode_monitor_request(idl_));
}

void OvsdbClientIdl::SendJsonRpc(struct jsonrpc_msg *msg) {
    struct json *json_msg = ovsdb_wrapper_jsonrpc_msg_to_json(msg);
    char *s = ovsdb_wrapper_json_to_string(json_msg, 0);
    ovsdb_wrapper_json_destroy(json_msg);

    session_->SendMsg((u_int8_t *)s, strlen(s));
}

void OvsdbClientIdl::MessageProcess(const u_int8_t *buf, std::size_t len) {
    std::size_t used = 0;
    // Multiple json message may be clubbed together, need to keep reading
    // the buffer till whole message is consumed.
    while (used != len) {
        if (parser_ == NULL) {
            parser_ = ovsdb_wrapper_json_parser_create(0);
        }
        const u_int8_t *pkt = buf + used;
        std::size_t pkt_len = len - used;
        std::size_t read;
        read = ovsdb_wrapper_json_parser_feed(parser_, (const char *)pkt,
                                              pkt_len);
        OVSDB_PKT_TRACE(Trace, "Processed: " + std::string((const char *)pkt, read));
        used +=read;

        /* If we have complete JSON, attempt to parse it as JSON-RPC. */
        if (ovsdb_wrapper_json_parser_is_done(parser_)) {
            struct json *json = ovsdb_wrapper_json_parser_finish(parser_);
            parser_ = NULL;
            struct jsonrpc_msg *msg;
            char *error = ovsdb_wrapper_jsonrpc_msg_from_json(json, &msg);
            if (error) {
                assert(0);
                free(error);
                //continue;
            }

            if (ovsdb_wrapper_msg_echo_req(msg)) {
                /* Echo request.  Send reply. */
                struct jsonrpc_msg *reply;
                reply = ovsdb_wrapper_jsonrpc_create_reply(msg);
                SendJsonRpc(reply);
                //jsonrpc_session_send(s, reply);
            } else if (ovsdb_wrapper_msg_echo_reply(msg)) {
                /* It's a reply to our echo request.  Suppress it. */
            } else {
                ovsdb_wrapper_idl_msg_process(idl_, msg);
                continue;
            }
            ovsdb_wrapper_jsonrpc_msg_destroy(msg);
        }
    }
}

struct ovsdb_idl_txn *OvsdbClientIdl::CreateTxn(OvsdbEntryBase *entry) {
    struct ovsdb_idl_txn *txn =  ovsdb_wrapper_idl_txn_create(idl_);
    pending_txn_[txn] = entry;
    return txn;
}

void OvsdbClientIdl::DeleteTxn(struct ovsdb_idl_txn *txn) {
    pending_txn_.erase(txn);
    ovsdb_wrapper_idl_txn_destroy(txn);
}

Ip4Address OvsdbClientIdl::tsn_ip() {
    return session_->tsn_ip();
}

KSyncObjectManager *OvsdbClientIdl::ksync_obj_manager() {
    return session_->ksync_obj_manager();
}

OvsPeer *OvsdbClientIdl::route_peer() {
    return route_peer_.get();
}

VMInterfaceKSyncObject *OvsdbClientIdl::vm_interface_table() {
    return vm_interface_table_.get();
}

PhysicalSwitchTable *OvsdbClientIdl::physical_switch_table() {
    return physical_switch_table_.get();
}

LogicalSwitchTable *OvsdbClientIdl::logical_switch_table() {
    return logical_switch_table_.get();
}

PhysicalPortTable *OvsdbClientIdl::physical_port_table() {
    return physical_port_table_.get();
}

PhysicalLocatorTable *OvsdbClientIdl::physical_locator_table() {
    return physical_locator_table_.get();
}

VlanPortBindingTable *OvsdbClientIdl::vlan_port_table() {
    return vlan_port_table_.get();
}

UnicastMacLocalOvsdb *OvsdbClientIdl::unicast_mac_local_ovsdb() {
    return unicast_mac_local_ovsdb_.get();
}

VrfOvsdbObject *OvsdbClientIdl::vrf_ovsdb() {
    return vrf_ovsdb_.get();
}

<commit_msg>fix memory leak, while doing ovs send.<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

#include <assert.h>
#include <cstddef>
#include <string.h>
#include <stdlib.h>

extern "C" {
#include <ovsdb_wrapper.h>
};
#include <oper/agent_sandesh.h>
#include <ovsdb_types.h>
#include <ovsdb_client_idl.h>
#include <ovsdb_client_session.h>
#include <ovsdb_route_peer.h>
#include <ovsdb_entry.h>
#include <physical_switch_ovsdb.h>
#include <logical_switch_ovsdb.h>
#include <physical_port_ovsdb.h>
#include <physical_locator_ovsdb.h>
#include <vlan_port_binding_ovsdb.h>
#include <unicast_mac_local_ovsdb.h>
#include <unicast_mac_remote_ovsdb.h>
#include <vm_interface_ksync.h>

SandeshTraceBufferPtr OvsdbTraceBuf(SandeshTraceBufferCreate("Ovsdb", 5000));
SandeshTraceBufferPtr OvsdbPktTraceBuf(SandeshTraceBufferCreate("Ovsdb Pkt", 5000));

class PhysicalDeviceTable;
class InterfaceTable;
class PhysicalDeviceVnTable;

using OVSDB::OvsdbClientIdl;
using OVSDB::OvsdbClientSession;
using OVSDB::OvsdbEntryBase;
using OVSDB::VMInterfaceKSyncObject;
using OVSDB::PhysicalSwitchTable;
using OVSDB::LogicalSwitchTable;
using OVSDB::PhysicalPortTable;
using OVSDB::PhysicalLocatorTable;
using OVSDB::VlanPortBindingTable;
using OVSDB::UnicastMacLocalOvsdb;
using OVSDB::VrfOvsdbObject;

namespace OVSDB {
void ovsdb_wrapper_idl_callback(void *idl_base, int op,
        struct ovsdb_idl_row *row) {
    OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;
    int i = ovsdb_wrapper_row_type(row);
    if (i >= OvsdbClientIdl::OVSDB_TYPE_COUNT)
        return;
    if (client_idl->callback_[i] != NULL)
        client_idl->callback_[i]((OvsdbClientIdl::Op)op, row);
}

void ovsdb_wrapper_idl_txn_ack(void *idl_base, struct ovsdb_idl_txn *txn) {
    OvsdbClientIdl *client_idl = (OvsdbClientIdl *) idl_base;
    OvsdbEntryBase *entry = client_idl->pending_txn_[txn];
    bool success = ovsdb_wrapper_is_txn_success(txn);
    if (!success) {
        OVSDB_TRACE(Error, "Transaction failed: " +
                std::string(ovsdb_wrapper_txn_get_error(txn)));
        // we don't handle the case where txn fails, when entry is not present
        // case of unicast_mac_remote entry.
        assert(entry != NULL);
    }
    client_idl->DeleteTxn(txn);
    if (entry)
        entry->Ack(success);
}
};

OvsdbClientIdl::OvsdbClientIdl(OvsdbClientSession *session, Agent *agent,
        OvsPeerManager *manager) : idl_(ovsdb_wrapper_idl_create()),
    session_(session), agent_(agent), pending_txn_() {
    vtep_global_= ovsdb_wrapper_vteprec_global_first(idl_);
    ovsdb_wrapper_idl_set_callback(idl_, (void *)this,
            ovsdb_wrapper_idl_callback, ovsdb_wrapper_idl_txn_ack);
    parser_ = NULL;
    for (int i = 0; i < OVSDB_TYPE_COUNT; i++) {
        callback_[i] = NULL;
    }
    route_peer_.reset(manager->Allocate(IpAddress()));
    vm_interface_table_.reset(new VMInterfaceKSyncObject(this,
                (DBTable *)agent->interface_table()));
    physical_switch_table_.reset(new PhysicalSwitchTable(this));
    logical_switch_table_.reset(new LogicalSwitchTable(this,
               (DBTable *)agent->physical_device_vn_table()));
    physical_port_table_.reset(new PhysicalPortTable(this));
    physical_locator_table_.reset(new PhysicalLocatorTable(this));
    vlan_port_table_.reset(new VlanPortBindingTable(this,
                (DBTable *)agent->interface_table()));
    unicast_mac_local_ovsdb_.reset(new UnicastMacLocalOvsdb(this,
                route_peer()));
    vrf_ovsdb_.reset(new VrfOvsdbObject(this, (DBTable *)agent->vrf_table()));
}

OvsdbClientIdl::~OvsdbClientIdl() {
    ovsdb_wrapper_idl_destroy(idl_);
}

void OvsdbClientIdl::SendMointorReq() {
    OVSDB_TRACE(Trace, "Sending Monitor Request");
    SendJsonRpc(ovsdb_wrapper_idl_encode_monitor_request(idl_));
}

void OvsdbClientIdl::SendJsonRpc(struct jsonrpc_msg *msg) {
    struct json *json_msg = ovsdb_wrapper_jsonrpc_msg_to_json(msg);
    char *s = ovsdb_wrapper_json_to_string(json_msg, 0);
    ovsdb_wrapper_json_destroy(json_msg);

    session_->SendMsg((u_int8_t *)s, strlen(s));
    // release the memory allocated by ovsdb_wrapper_json_to_string
    free(s);
}

void OvsdbClientIdl::MessageProcess(const u_int8_t *buf, std::size_t len) {
    std::size_t used = 0;
    // Multiple json message may be clubbed together, need to keep reading
    // the buffer till whole message is consumed.
    while (used != len) {
        if (parser_ == NULL) {
            parser_ = ovsdb_wrapper_json_parser_create(0);
        }
        const u_int8_t *pkt = buf + used;
        std::size_t pkt_len = len - used;
        std::size_t read;
        read = ovsdb_wrapper_json_parser_feed(parser_, (const char *)pkt,
                                              pkt_len);
        OVSDB_PKT_TRACE(Trace, "Processed: " + std::string((const char *)pkt, read));
        used +=read;

        /* If we have complete JSON, attempt to parse it as JSON-RPC. */
        if (ovsdb_wrapper_json_parser_is_done(parser_)) {
            struct json *json = ovsdb_wrapper_json_parser_finish(parser_);
            parser_ = NULL;
            struct jsonrpc_msg *msg;
            char *error = ovsdb_wrapper_jsonrpc_msg_from_json(json, &msg);
            if (error) {
                assert(0);
                free(error);
                //continue;
            }

            if (ovsdb_wrapper_msg_echo_req(msg)) {
                /* Echo request.  Send reply. */
                struct jsonrpc_msg *reply;
                reply = ovsdb_wrapper_jsonrpc_create_reply(msg);
                SendJsonRpc(reply);
                //jsonrpc_session_send(s, reply);
            } else if (ovsdb_wrapper_msg_echo_reply(msg)) {
                /* It's a reply to our echo request.  Suppress it. */
            } else {
                ovsdb_wrapper_idl_msg_process(idl_, msg);
                continue;
            }
            ovsdb_wrapper_jsonrpc_msg_destroy(msg);
        }
    }
}

struct ovsdb_idl_txn *OvsdbClientIdl::CreateTxn(OvsdbEntryBase *entry) {
    struct ovsdb_idl_txn *txn =  ovsdb_wrapper_idl_txn_create(idl_);
    pending_txn_[txn] = entry;
    return txn;
}

void OvsdbClientIdl::DeleteTxn(struct ovsdb_idl_txn *txn) {
    pending_txn_.erase(txn);
    ovsdb_wrapper_idl_txn_destroy(txn);
}

Ip4Address OvsdbClientIdl::tsn_ip() {
    return session_->tsn_ip();
}

KSyncObjectManager *OvsdbClientIdl::ksync_obj_manager() {
    return session_->ksync_obj_manager();
}

OvsPeer *OvsdbClientIdl::route_peer() {
    return route_peer_.get();
}

VMInterfaceKSyncObject *OvsdbClientIdl::vm_interface_table() {
    return vm_interface_table_.get();
}

PhysicalSwitchTable *OvsdbClientIdl::physical_switch_table() {
    return physical_switch_table_.get();
}

LogicalSwitchTable *OvsdbClientIdl::logical_switch_table() {
    return logical_switch_table_.get();
}

PhysicalPortTable *OvsdbClientIdl::physical_port_table() {
    return physical_port_table_.get();
}

PhysicalLocatorTable *OvsdbClientIdl::physical_locator_table() {
    return physical_locator_table_.get();
}

VlanPortBindingTable *OvsdbClientIdl::vlan_port_table() {
    return vlan_port_table_.get();
}

UnicastMacLocalOvsdb *OvsdbClientIdl::unicast_mac_local_ovsdb() {
    return unicast_mac_local_ovsdb_.get();
}

VrfOvsdbObject *OvsdbClientIdl::vrf_ovsdb() {
    return vrf_ovsdb_.get();
}

<|endoftext|>


<commit_before>#include "Genes/Pawn_Advancement_Gene.h"

#include <string>
#include <memory>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Pieces/Piece.h"

double Pawn_Advancement_Gene::score_board(const Board& board) const
{
    double score = 0.0;
    auto perspective = board.whose_turn();
    int home_rank = (perspective == WHITE ? 2 : 7);

    for(char file = 'a'; file <= 'h'; ++file)
    {
        for(int rank = 1; rank <= 8; ++rank)
        {
            auto piece = board.piece_on_square(file, rank);
            if(piece && piece->color() == perspective && piece->is_pawn())
            {
                // 1 point per move towards promotion
                score += std::abs(home_rank - rank);
            }
        }
    }

    // Count pawn promotions
    const auto& move_list = board.get_game_record();
    for(size_t i = (perspective == board.first_to_move() ? 0 : 1);
        i < move_list.size();
        i += 2)
    {
        if(move_list[i]->promotion_piece())
        {
            score += 6; // pawn made it to last rank
        }
    }

    return score/(8*6); // normalize to 8 pawns 6 ranks from home (promotion rank)
}

std::unique_ptr<Gene> Pawn_Advancement_Gene::duplicate() const
{
    return std::make_unique<Pawn_Advancement_Gene>(*this);
}

std::string Pawn_Advancement_Gene::name() const
{
    return "Pawn Advancement Gene";
}
<commit_msg>Save work in Pawn Advancement Gene<commit_after>#include "Genes/Pawn_Advancement_Gene.h"

#include <string>
#include <memory>

#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Pieces/Piece.h"

double Pawn_Advancement_Gene::score_board(const Board& board) const
{
    double score = 0.0;
    auto perspective = board.whose_turn();
    int home_rank = (perspective == WHITE ? 2 : 7);

    for(char file = 'a'; file <= 'h'; ++file)
    {
        for(int rank = 2; rank <= 7; ++rank)
        {
            auto piece = board.piece_on_square(file, rank);
            if(piece && piece->color() == perspective && piece->is_pawn())
            {
                // 1 point per move towards promotion
                score += std::abs(home_rank - rank);
            }
        }
    }

    // Count pawn promotions
    const auto& move_list = board.get_game_record();
    for(size_t i = (perspective == board.first_to_move() ? 0 : 1);
        i < move_list.size();
        i += 2)
    {
        if(move_list[i]->promotion_piece())
        {
            score += 6; // pawn made it to last rank
        }
    }

    return score/(8*6); // normalize to 8 pawns 6 ranks from home (promotion rank)
}

std::unique_ptr<Gene> Pawn_Advancement_Gene::duplicate() const
{
    return std::make_unique<Pawn_Advancement_Gene>(*this);
}

std::string Pawn_Advancement_Gene::name() const
{
    return "Pawn Advancement Gene";
}
<|endoftext|>


<commit_before>
/*!
	\file

	\author Igor Mironchik (igor.mironchik at gmail dot com).

	Copyright (c) 2014 Igor Mironchik

	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.
*/

// Qt include.
#include <QObject>
#include <QtTest/QtTest>
#include <QSharedPointer>

// QtMWidgets include.
#include <QtMWidgets/PageControl>
#include <QtMWidgets/FingerGeometry>

class TestPageControl
	:	public QObject
{
	Q_OBJECT

private slots:

	void initTestCase()
	{
		m_btnSize = QtMWidgets::FingerGeometry::width() * 0.3 / 2 * 3;
	}

	void testBusy()
	{
		QtMWidgets::PageControl p;

		p.resize( m_btnSize * 3, m_btnSize * 4 );
		p.show();

		QVERIFY( QTest::qWaitForWindowActive( &p ) );

		p.setPageIndicatorColor( Qt::red );
		p.setCurrentPageIndicatorColor( Qt::red );

		QVERIFY( p.pageIndicatorColor() == Qt::red );
		QVERIFY( p.currentPageIndicatorColor() == Qt::red );

		p.setCount( 10 );

		p.setCurrentIndex( 4 );

		QVERIFY( p.count() == 10 );
		QVERIFY( p.currentIndex() == 4 );

		QTest::mouseClick( &p, Qt::LeftButton, {}, QRect( 0, 0, m_btnSize, m_btnSize ).center(),
			20 );

		QVERIFY( p.currentIndex() == 0 );

		p.resize( m_btnSize * 5, m_btnSize * 2 );

		QTest::qWait( 50 );

		QSignalSpy spy( &p, &QtMWidgets::PageControl::currentChanged );

		QTest::mouseClick( &p, Qt::LeftButton, {},
			QRect( m_btnSize * 4, 0, m_btnSize, m_btnSize ).center(), 20 );

		QVERIFY( p.currentIndex() == 4 );
		QVERIFY( spy.count() == 1 );
	}

private:
	int m_btnSize;
};

QTEST_MAIN( TestPageControl )

#include "main.moc"
<commit_msg>Fix test.<commit_after>
/*!
	\file

	\author Igor Mironchik (igor.mironchik at gmail dot com).

	Copyright (c) 2014 Igor Mironchik

	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.
*/

// Qt include.
#include <QObject>
#include <QtTest/QtTest>
#include <QSharedPointer>

// QtMWidgets include.
#include <QtMWidgets/PageControl>
#include <QtMWidgets/FingerGeometry>

class TestPageControl
	:	public QObject
{
	Q_OBJECT

private slots:

	void initTestCase()
	{
		m_btnSize = QtMWidgets::FingerGeometry::width() * 0.3 / 2 * 3;
	}

	void testBusy()
	{
		QtMWidgets::PageControl p;

		p.resize( m_btnSize * 3, m_btnSize * 4 );
		p.show();

		QVERIFY( QTest::qWaitForWindowActive( &p ) );

		p.setPageIndicatorColor( Qt::red );
		p.setCurrentPageIndicatorColor( Qt::red );

		QVERIFY( p.pageIndicatorColor() == Qt::red );
		QVERIFY( p.currentPageIndicatorColor() == Qt::red );

		p.setCount( 10 );

		p.setCurrentIndex( 4 );

		QVERIFY( p.count() == 10 );
		QVERIFY( p.currentIndex() == 4 );

		QTest::mouseClick( &p, Qt::LeftButton, {},
			QRect( ( p.width() - m_btnSize * 3 ) / 2, 0, m_btnSize, m_btnSize ).center(),
			20 );

		QVERIFY( p.currentIndex() == 0 );

		p.resize( m_btnSize * 5, m_btnSize * 2 );

		QTest::qWait( 50 );

		QSignalSpy spy( &p, &QtMWidgets::PageControl::currentChanged );

		QTest::mouseClick( &p, Qt::LeftButton, {},
			QRect( ( p.width() - m_btnSize * 5 ) / 2 + m_btnSize * 4, 0,
				m_btnSize, m_btnSize ).center(), 20 );

		QVERIFY( p.currentIndex() == 4 );
		QVERIFY( spy.count() == 1 );
	}

private:
	int m_btnSize;
};

QTEST_MAIN( TestPageControl )

#include "main.moc"
<|endoftext|>


<commit_before>// Copyright (c) 2014-2017 Michael J. Sullivan
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file.

#ifndef QSPINLOCK_SC_H
#define QSPINLOCK_SC_H

#include <rmc++.h>
#include <utility>
#include "tagged_ptr.hpp"

#define CLEAR_RMW 1

namespace rmclib {

// This is based on "MCS locks" and linux's qspinlocks.  The key idea
// here, and the reason for the extra complication relative to
// ticket-taking spinlocks, is that different threads can spin-wait on
// different locations, reducing cache contention.

//// BEGIN SNIP
class QSpinLock {
//// END SNIP
    // This should be yield() or cpu_relax() or something
    void delay() { }
    // Aligned to 256 so the CLEAR_BYTE_WRITE trick can work.
//// BEGIN SNIP
    struct alignas(256) Node {
        using Ptr = tagged_ptr<Node *>;
        rmc::atomic<Node *> next{nullptr};
        rmc::atomic<bool> ready{false};
    };

    rmc::atomic<Node::Ptr> tail_;

//// END SNIP
    void clearLowBit(rmc::atomic<Node::Ptr> &loc) {
        // We want to just xadd(-1) the thing, but C++ doesn't let us
        // because of the level of obstruction^Wabstraction that
        // tagged_ptr adds.
        //
        // Or maybe what we want to do is to align Node on 256 boundaries
        // so that we can do a one byte write to clear the locked flag.
        // That is *especially* not a thing in the C++ memory model.
#if CLEAR_RMW
        // This is probably undefined
        auto &intloc = reinterpret_cast<rmc::atomic<uintptr_t> &>(loc);
        intloc.fetch_and(~Node::Ptr::kTagBits);
#elif CLEAR_BYTE_WRITE
        // This is certainly undefined, and only works on little endian.
        // C++ really does not have any story for mixed-size atomics
        // and mixed-size atomics are pretty funky in practice.
        // Linux does do this on some platforms, though.
        auto &byteloc = reinterpret_cast<rmc::atomic<uint8_t> &>(loc);
        byteloc = 0;
#else
        Node::Ptr state(nullptr, 1);
        while (!loc.compare_exchange_weak(state, Node::Ptr(state, 0))) {
        }
#endif
    }
//// BEGIN SNIP

    void slowpathLock(Node::Ptr oldTail) {
        // makes sure that init of me.next is prior to tail_link in
        // other thread
        VEDGE(node_init, enqueue);
        // init of me needs to be done before publishing it to
        // previous thread also
        VEDGE(node_init, tail_link);
        // Can't write self into previous node until we have read out
        // the correct previous node (which we do while enqueueing).
        XEDGE(enqueue, tail_link);

        LS(node_init, Node me);
        Node::Ptr curTail;
        bool newThreads;

        // Step one, put ourselves at the back of the queue
        for (;;) {
            Node::Ptr newTail = Node::Ptr(&me, oldTail.tag());

            // Enqueue ourselves...
            if (L(enqueue,
                  tail_.compare_exchange_strong(oldTail, newTail))) break;

            // OK, maybe the whole thing is just unlocked now?
            if (oldTail == Node::Ptr(nullptr, 0)) {
                // If so, just try to take the lock and be done.
                if (tail_.compare_exchange_strong(
                        oldTail, Node::Ptr(nullptr, 1)))
                    goto out;
            }
        }

        // Need to make sure not to compete for the lock before the
        // right time. This makes sure the ordering doesn't get messed
        // up.
        XEDGE(ready_wait, lock);

        // Step two: OK, there is an actual queue, so link up with the old
        // tail and wait until we are at the head of the queue
        if (oldTail.ptr()) {
            // * Writing into the oldTail is safe because threads can't
            //   leave unless there is no thread after them or they have
            //   marked the next ready
            L(tail_link, oldTail->next = &me);

            while (!L(ready_wait, me.ready)) delay();
        }

        // Step three: wait until the lock is freed
        // We don't need a a constraint from this load; "lock" serves
        // to handle this just fine: lock can't succeed until we've
        // read an unlocked tail_.
        while ((curTail = tail_).tag()) {
            delay();
        }

        // Our lock acquisition needs to be finished before we give the
        // next thread a chance to try to acquire the lock or it could
        // compete with us for it, causing trouble.
        VEDGE(lock, signal_next);

        // Step four: take the lock
        for (;;) {
            assert_eq(curTail.tag(), 0);
            assert_ne(curTail.ptr(), nullptr);

            newThreads = curTail.ptr() != &me;

            // If there aren't any waiters after us, the queue is
            // empty. Otherwise, keep the old tail.
            Node *newTailP = newThreads ? curTail : nullptr;
            Node::Ptr newTail = Node::Ptr(newTailP, 1);

            // This can fail if new threads add themselves to the
            // queue. However, nobody else can actually *take* the
            // lock, so we'll succeed quickly.
            if (L(lock, tail_.compare_exchange_strong(curTail, newTail))) break;
        }

        // Step five: now that we have the lock, if any threads came
        // in after us, indicate to the next one that it is at the
        // head of the queue
        if (newThreads) {
            // Next thread might not have written itself in, yet,
            // so we have to wait.
            // Waiting for threads *after* you in the queue kind of
            // offends me, to be honest.
            Node *next;
            XEDGE(load_next, signal_next);
            while (!L(load_next, next = me.next)) delay();
            L(signal_next, next->ready = true);
        }

    out:
        return;
    }

public:
    void lock() {
        XEDGE(lock, out);
        // If the lock is unlocked and has no waiters, we can acquire
        // it with no fanfare. Otherwise we need to fall back to the
        // slow path.
        Node::Ptr unlocked(nullptr, 0);
        if (!L(lock,
               tail_.compare_exchange_strong(unlocked, Node::Ptr(nullptr, 1)))){
            LS(lock, slowpathLock(unlocked));
        }
        LPOST(out);
    }
    void unlock() {
        VEDGE(pre, unlock);
        LS(unlock, clearLowBit(tail_));
    }

};
//// END SNIP

}

#endif
<commit_msg>rename a label<commit_after>// Copyright (c) 2014-2017 Michael J. Sullivan
// Use of this source code is governed by an MIT-style license that can be
// found in the LICENSE file.

#ifndef QSPINLOCK_SC_H
#define QSPINLOCK_SC_H

#include <rmc++.h>
#include <utility>
#include "tagged_ptr.hpp"

#define CLEAR_RMW 1

namespace rmclib {

// This is based on "MCS locks" and linux's qspinlocks.  The key idea
// here, and the reason for the extra complication relative to
// ticket-taking spinlocks, is that different threads can spin-wait on
// different locations, reducing cache contention.

//// BEGIN SNIP
class QSpinLock {
//// END SNIP
    // This should be yield() or cpu_relax() or something
    void delay() { }
    // Aligned to 256 so the CLEAR_BYTE_WRITE trick can work.
//// BEGIN SNIP
    struct alignas(256) Node {
        using Ptr = tagged_ptr<Node *>;
        rmc::atomic<Node *> next{nullptr};
        rmc::atomic<bool> ready{false};
    };

    rmc::atomic<Node::Ptr> tail_;

//// END SNIP
    void clearLowBit(rmc::atomic<Node::Ptr> &loc) {
        // We want to just xadd(-1) the thing, but C++ doesn't let us
        // because of the level of obstruction^Wabstraction that
        // tagged_ptr adds.
        //
        // Or maybe what we want to do is to align Node on 256 boundaries
        // so that we can do a one byte write to clear the locked flag.
        // That is *especially* not a thing in the C++ memory model.
#if CLEAR_RMW
        // This is probably undefined
        auto &intloc = reinterpret_cast<rmc::atomic<uintptr_t> &>(loc);
        intloc.fetch_and(~Node::Ptr::kTagBits);
#elif CLEAR_BYTE_WRITE
        // This is certainly undefined, and only works on little endian.
        // C++ really does not have any story for mixed-size atomics
        // and mixed-size atomics are pretty funky in practice.
        // Linux does do this on some platforms, though.
        auto &byteloc = reinterpret_cast<rmc::atomic<uint8_t> &>(loc);
        byteloc = 0;
#else
        Node::Ptr state(nullptr, 1);
        while (!loc.compare_exchange_weak(state, Node::Ptr(state, 0))) {
        }
#endif
    }
//// BEGIN SNIP

    void slowpathLock(Node::Ptr oldTail) {
        // makes sure that init of me.next is prior to tail_link in
        // other thread
        VEDGE(node_init, enqueue);
        // init of me needs to be done before publishing it to
        // previous thread also
        VEDGE(node_init, tail_link);
        // Can't write self into previous node until we have read out
        // the correct previous node (which we do while enqueueing).
        XEDGE(enqueue, tail_link);

        LS(node_init, Node me);
        Node::Ptr curTail;
        bool newThreads;

        // Step one, put ourselves at the back of the queue
        for (;;) {
            Node::Ptr newTail = Node::Ptr(&me, oldTail.tag());

            // Enqueue ourselves...
            if (L(enqueue,
                  tail_.compare_exchange_strong(oldTail, newTail))) break;

            // OK, maybe the whole thing is just unlocked now?
            if (oldTail == Node::Ptr(nullptr, 0)) {
                // If so, just try to take the lock and be done.
                if (tail_.compare_exchange_strong(
                        oldTail, Node::Ptr(nullptr, 1)))
                    goto out;
            }
        }

        // Need to make sure not to compete for the lock before the
        // right time. This makes sure the ordering doesn't get messed
        // up.
        XEDGE(ready_wait, lock);

        // Step two: OK, there is an actual queue, so link up with the old
        // tail and wait until we are at the head of the queue
        if (oldTail.ptr()) {
            // * Writing into the oldTail is safe because threads can't
            //   leave unless there is no thread after them or they have
            //   marked the next ready
            L(tail_link, oldTail->next = &me);

            while (!L(ready_wait, me.ready)) delay();
        }

        // Step three: wait until the lock is freed
        // We don't need a a constraint from this load; "lock" serves
        // to handle this just fine: lock can't succeed until we've
        // read an unlocked tail_.
        while ((curTail = tail_).tag()) {
            delay();
        }

        // Our lock acquisition needs to be finished before we give the
        // next thread a chance to try to acquire the lock or it could
        // compete with us for it, causing trouble.
        VEDGE(lock, signal_next);

        // Step four: take the lock
        for (;;) {
            assert_eq(curTail.tag(), 0);
            assert_ne(curTail.ptr(), nullptr);

            newThreads = curTail.ptr() != &me;

            // If there aren't any waiters after us, the queue is
            // empty. Otherwise, keep the old tail.
            Node *newTailP = newThreads ? curTail : nullptr;
            Node::Ptr newTail = Node::Ptr(newTailP, 1);

            // This can fail if new threads add themselves to the
            // queue. However, nobody else can actually *take* the
            // lock, so we'll succeed quickly.
            if (L(lock, tail_.compare_exchange_strong(curTail, newTail))) break;
        }

        // Step five: now that we have the lock, if any threads came
        // in after us, indicate to the next one that it is at the
        // head of the queue
        if (newThreads) {
            // Next thread might not have written itself in, yet,
            // so we have to wait.
            // Waiting for threads *after* you in the queue kind of
            // offends me, to be honest.
            Node *next;
            XEDGE(load_next, signal_next);
            while (!L(load_next, next = me.next)) delay();
            L(signal_next, next->ready = true);
        }

    out:
        return;
    }

public:
    void lock() {
        XEDGE(lock, body);
        // If the lock is unlocked and has no waiters, we can acquire
        // it with no fanfare. Otherwise we need to fall back to the
        // slow path.
        Node::Ptr unlocked(nullptr, 0);
        if (!L(lock,
               tail_.compare_exchange_strong(unlocked, Node::Ptr(nullptr, 1)))){
            LS(lock, slowpathLock(unlocked));
        }
        LPOST(body);
    }
    void unlock() {
        VEDGE(pre, unlock);
        LS(unlock, clearLowBit(tail_));
    }

};
//// END SNIP

}

#endif
<|endoftext|>


<commit_before>// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.hpp"

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
// #include <windows.h>

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>

#include <vector>

#include "BaseBlock.hpp"
#include "Block.hpp"
#include "Blocks/BlockI.hpp"
#include "Blocks/BlockJ.hpp"
#include "Blocks/BlockL.hpp"
#include "Blocks/BlockO.hpp"
#include "Blocks/BlockS.hpp"
#include "Blocks/BlockT.hpp"
#include "Blocks/BlockZ.hpp"
#include "BlockChooser.hpp"
#include "Field.hpp"
<commit_msg>Izmantot GLM matemātikas bibliotēku<commit_after>// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.hpp"

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
// #include <windows.h>

#define GLM_FORCE_RADIANS
#include <glm/fwd.hpp>
#include <glm/common.hpp>
#include <glm/matrix.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>

#include <vector>

#include "BaseBlock.hpp"
#include "Block.hpp"
#include "Blocks/BlockI.hpp"
#include "Blocks/BlockJ.hpp"
#include "Blocks/BlockL.hpp"
#include "Blocks/BlockO.hpp"
#include "Blocks/BlockS.hpp"
#include "Blocks/BlockT.hpp"
#include "Blocks/BlockZ.hpp"
#include "BlockChooser.hpp"
#include "Field.hpp"
<|endoftext|>


<commit_before>//===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Lightweight interface to dynamic library linking and loading, and dynamic
// symbol lookup functionality, in whatever form the operating system
// provides it.
//
// Possible future extensions include support for the HPUX shl_load()
// interface, the Mac OS X NSLinkModule() interface, and the Windows
// LoadLibrary() interface.
//
// Note that we assume that if dlopen() is available, then dlsym() is too.
//
//===----------------------------------------------------------------------===//

#include "Support/DynamicLinker.h"
#include "Config/dlfcn.h"
#include "Config/windows.h"
#include <cassert>
using namespace llvm;

bool llvm::LinkDynamicObject (const char *filename, std::string *ErrorMessage) {
#if defined (HAVE_DLOPEN)
  if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) {
    if (ErrorMessage) *ErrorMessage = dlerror ();
    return true;
  }
  return false;
#elif defined(HAVE_WINDOWS_H)
  if (LoadLibrary(filename))
    return false;
  if (ErrorMessage) {
    char Buffer[100];
    // FIXME: This should use FormatMessage
    sprintf(Buffer, "Windows error code %d\n", GetLastError());
    *ErrorMessage = Buffer;
  }
  return true;
#else
  assert (0 && "Dynamic object linking not implemented for this platform");
#endif
}

void *llvm::GetAddressOfSymbol (const char *symbolName) {
#if defined (HAVE_DLOPEN)
#  ifdef RTLD_DEFAULT
    return dlsym (RTLD_DEFAULT, symbolName);
#  else
    static void* CurHandle = dlopen(0, RTLD_LAZY);
    return dlsym(CurHandle, symbolName);
#  endif
#elif defined(HAVE_WINDOWS_H)
  static HMODULE ModHandle = NULL;
  if (ModHandle == 0) ModHandle = GetModuleHandle(NULL);
  return (void*)GetProcAddress(ModHandle, symbolName);
#else
  assert (0 && "Dynamic symbol lookup not implemented for this platform");
#endif
}

// soft, cushiony C++ interface.
void *llvm::GetAddressOfSymbol(const std::string &symbolName) {
  return GetAddressOfSymbol(symbolName.c_str());
}
<commit_msg>Thoroughly rehack the dynamic linking mechanisms on Win32.  The Win32 dynamic linker does not automatically search libraries when looking up symbols with GetProcAddress.  Because of this we have to emulate it.  The only detail is that there doesn't seem to be a way to enumerate the libraries loaded, so we have a gross hack (tm).<commit_after>//===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Lightweight interface to dynamic library linking and loading, and dynamic
// symbol lookup functionality, in whatever form the operating system
// provides it.
//
// Possible future extensions include support for the HPUX shl_load()
// interface, and the Mac OS X NSLinkModule() interface.
//
// Note that we assume that if dlopen() is available, then dlsym() is too.
//
//===----------------------------------------------------------------------===//

#include "Support/DynamicLinker.h"
#include "Config/dlfcn.h"
#include "Config/windows.h"
#include <cassert>
#include <vector>
using namespace llvm;

#if defined(HAVE_WINDOWS_H)
// getLoadedLibs - Keep track of the shared objects that are loaded into the
// process address space, as the windows GetProcAddress function does not
// automatically search an entire address space, it only searches a specific
// object.
static std::vector<HMODULE> &getLoadedLibHandles() {
  static std::vector<HMODULE> *LoadedLibHandles = 0;
  if (LoadedLibHandles == 0) {
    LoadedLibHandles = new std::vector<HMODULE>();
    if (HMODULE H = GetModuleHandle(NULL))                // JIT symbols
      LoadedLibHandles->push_back(H);
    if (HMODULE MH = GetModuleHandle("cygwin1.dll"))      // Cygwin symbols OR
      LoadedLibHandles->push_back(MH);
    else if (HMODULE MH = GetModuleHandle("msvcr80.dll")) // VC++ symbols
      LoadedLibHandles->push_back(MH);
  }
  return *LoadedLibHandles;
}
#endif

bool llvm::LinkDynamicObject(const char *filename, std::string *ErrorMessage) {
#if defined(HAVE_WINDOWS_H)
  if (HMODULE Handle = LoadLibrary(filename)) {
    // Allow GetProcAddress in this module
    getLoadedLibHandles().push_back(Handle);
    return false;
  }
  if (ErrorMessage) {
    char Buffer[100];
    // FIXME: This should use FormatMessage
    sprintf(Buffer, "Windows error code %d\n", GetLastError());
    *ErrorMessage = Buffer;
  }
  return true;
#elif defined (HAVE_DLOPEN)
  if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) {
    if (ErrorMessage) *ErrorMessage = dlerror ();
    return true;
  }
  return false;
#else
  assert (0 && "Dynamic object linking not implemented for this platform");
#endif
}

void *llvm::GetAddressOfSymbol(const char *symbolName) {
#if defined(HAVE_WINDOWS_H)
  std::vector<HMODULE> &LH = getLoadedLibHandles();
  for (unsigned i = 0, e = LH.size(); i != e; ++i)
    if (void *Val = (void*)GetProcAddress(LH[i], symbolName))
      return Val;
  return 0;
#elif defined(HAVE_DLOPEN)
#  ifdef RTLD_DEFAULT
    return dlsym (RTLD_DEFAULT, symbolName);
#  else
    static void* CurHandle = dlopen(0, RTLD_LAZY);
    return dlsym(CurHandle, symbolName);
#  endif
#else
  assert (0 && "Dynamic symbol lookup not implemented for this platform");
#endif
}

// soft, cushiony C++ interface.
void *llvm::GetAddressOfSymbol(const std::string &symbolName) {
  return GetAddressOfSymbol(symbolName.c_str());
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QGridLayout>
#include <QPointer>
#include <QBackingStore>
#include <QList>
#include <QBasicTimer>
#include <QImage>
#include <QPixmap>
#include <QTime>
#include <QDebug>

class WidgetMonitor : public QObject
{
    Q_OBJECT
    QSet<QWidget *> m_awake;
    QBasicTimer m_timer;
    int m_counter;
    void queue(QWidget * w) {
        m_awake << w->window();
        if (! m_timer.isActive()) m_timer.start(0, this);
    }
    bool eventFilter(QObject * obj, QEvent * ev) {
        switch (ev->type()) {
        case QEvent::Paint: {
            if (! obj->isWidgetType()) break;
            queue(static_cast<QWidget*>(obj));
            break;
        }
        case QEvent::ChildAdded: {
            if (obj->isWidgetType()) obj->installEventFilter(this);
            break;
        }
        default: break;
        }
        return false;
    }
    void timerEvent(QTimerEvent * ev) {
        if (ev->timerId() != m_timer.timerId()) return;
        qDebug() << "painting: " << m_counter++ << m_awake;
        foreach (QWidget * w, m_awake) {
            QImage * img = dynamic_cast<QImage*>(w->backingStore()->paintDevice());
            if (img) emit newContents(img, w);
        }
        m_awake.clear();
        m_timer.stop();
    }
    Q_SLOT void windowDestroyed(QObject * obj) {
        if (! obj->isWidgetType()) return;
        m_awake.remove(static_cast<QWidget*>(obj));
    }
public:
    explicit WidgetMonitor(QObject * parent = 0) : QObject(parent), m_counter(0) {}
    explicit WidgetMonitor(QWidget * w, QObject * parent = 0) : QObject(parent), m_counter(0) {
        monitor(w);
    }
    Q_SLOT void monitor(QWidget * w) {
        w = w->window();
        connect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);
        w->installEventFilter(this);
        foreach (QObject * obj, w->children()) {
            if (obj->isWidgetType()) obj->installEventFilter(this);
        }
        queue(w);
    }
    Q_SLOT void unMonitor(QWidget * w) {
        w = w->window();
        disconnect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);
        m_awake.remove(w);
        w->removeEventFilter(this);
        foreach (QObject * obj, w->children()) {
            if (obj->isWidgetType()) obj->removeEventFilter(this);
        }
    }
    Q_SIGNAL void newContents(const QImage *, QWidget * w);
};

class TestWidget : public QWidget {
    QLabel * m_time;
    QBasicTimer m_timer;
    void timerEvent(QTimerEvent * ev) {
        if (ev->timerId() != m_timer.timerId()) return;
        m_time->setText(QTime::currentTime().toString());
    }
public:
    explicit TestWidget(QWidget * parent = 0) : QWidget(parent), m_time(new QLabel) {
        QGridLayout * lay = new QGridLayout(this);
        lay->addWidget(m_time, 0, 0);
        lay->addWidget(new QLabel("Static Label"), 1, 0);
        lay->addWidget(new QPushButton("A Button"), 2, 0);
        m_timer.start(1000, this);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    TestWidget src;
    QWidget dst;
    QGridLayout * dl = new QGridLayout(&dst);
    QLabel * dstLabel = new QLabel;
    dstLabel->setFrameShape(QFrame::Box);
    dl->addWidget(new QLabel("Destination"), 0, 0);
    dl->addWidget(dstLabel);
    src.show();
    dst.show();

    WidgetMonitor mon(&src);
    QObject::connect(&mon, &WidgetMonitor::newContents, [=](const QImage * img){
        dstLabel->resize(img->size());
        dstLabel->setPixmap(QPixmap::fromImage(*img));

    });
    return a.exec();
}

#include "main.moc"
<commit_msg>C++11-ize<commit_after>// https://github.com/KubaO/stackoverflown/tree/master/questions/surface-20737882
#include <QtWidgets>

class WidgetMonitor : public QObject
{
   Q_OBJECT
   QSet<QWidget *> m_awake;
   QBasicTimer m_timer;
   int m_counter = 0;
   void queue(QWidget * w) {
      m_awake << w->window();
      if (! m_timer.isActive()) m_timer.start(0, this);
   }
   bool eventFilter(QObject * obj, QEvent * ev) {
      switch (ev->type()) {
      case QEvent::Paint: {
         if (! obj->isWidgetType()) break;
         queue(static_cast<QWidget*>(obj));
         break;
      }
      case QEvent::ChildAdded: {
         if (obj->isWidgetType()) obj->installEventFilter(this);
         break;
      }
      default: break;
      }
      return false;
   }
   void timerEvent(QTimerEvent * ev) {
      if (ev->timerId() != m_timer.timerId()) return;
      qDebug() << "painting: " << m_counter++ << m_awake;
      for (auto w : m_awake) {
         auto img = dynamic_cast<QImage*>(w->backingStore()->paintDevice());
         if (img) emit newContents(img, w);
      }
      m_awake.clear();
      m_timer.stop();
   }
   Q_SLOT void windowDestroyed(QObject * obj) {
      if (! obj->isWidgetType()) return;
      m_awake.remove(static_cast<QWidget*>(obj));
   }
public:
   explicit WidgetMonitor(QObject * parent = nullptr) : QObject{parent} {}
   explicit WidgetMonitor(QWidget * w, QObject * parent = nullptr) : QObject{parent} {
      monitor(w);
   }
   Q_SLOT void monitor(QWidget * w) {
      w = w->window();
      connect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);
      w->installEventFilter(this);
      for (auto obj : w->children())
         if (obj->isWidgetType()) obj->installEventFilter(this);
      queue(w);
   }
   Q_SLOT void unMonitor(QWidget * w) {
      w = w->window();
      disconnect(w, &QObject::destroyed, this, &WidgetMonitor::windowDestroyed);
      m_awake.remove(w);
      w->removeEventFilter(this);
      for (auto obj : w->children()) {
         if (obj->isWidgetType()) obj->removeEventFilter(this);
      }
   }
   Q_SIGNAL void newContents(const QImage *, QWidget * w);
};

class TestWidget : public QWidget {
   QVBoxLayout m_layout{this};
   QLabel m_time;
   QBasicTimer m_timer;
   void timerEvent(QTimerEvent * ev) override {
      if (ev->timerId() != m_timer.timerId()) return;
      m_time.setText(QTime::currentTime().toString());
   }
public:
   explicit TestWidget(QWidget * parent = 0) : QWidget{parent} {
      m_layout.addWidget(&m_time);
      m_layout.addWidget(new QLabel{"Static Label"});
      m_layout.addWidget(new QPushButton{"A Button"});
      m_timer.start(1000, this);
   }
};

int main(int argc, char **argv)
{
   QApplication app{argc, argv};
   TestWidget src;
   QWidget dst;
   QVBoxLayout dl{&dst};
   QLabel description{"Destination"};
   QLabel contents;
   contents.setFrameShape(QFrame::Box);
   dl.addWidget(&description);
   dl.addWidget(&contents);
   src.show();
   dst.show();

   WidgetMonitor mon(&src);
   QObject::connect(&mon, &WidgetMonitor::newContents, [&](const QImage * img){
      contents.resize(img->size());
      contents.setPixmap(QPixmap::fromImage(*img));
   });
   return app.exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an API used to indicate fatal error conditions.  Non-fatal
// errors (most of them) should be handled through LLVMContext.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ErrorHandling.h"
#include "llvm-c/Core.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/MutexGuard.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/WindowsError.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdlib>

#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(_MSC_VER)
# include <io.h>
# include <fcntl.h>
#endif

using namespace llvm;

static fatal_error_handler_t ErrorHandler = nullptr;
static void *ErrorHandlerUserData = nullptr;

static sys::Mutex ErrorHandlerMutex;

void llvm::install_fatal_error_handler(fatal_error_handler_t handler,
                                       void *user_data) {
  llvm::MutexGuard Lock(ErrorHandlerMutex);
  assert(!ErrorHandler && "Error handler already registered!\n");
  ErrorHandler = handler;
  ErrorHandlerUserData = user_data;
}

void llvm::remove_fatal_error_handler() {
  llvm::MutexGuard Lock(ErrorHandlerMutex);
  ErrorHandler = nullptr;
  ErrorHandlerUserData = nullptr;
}

void llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {
  report_fatal_error(Twine(Reason), GenCrashDiag);
}

void llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) {
  report_fatal_error(Twine(Reason), GenCrashDiag);
}

void llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {
  report_fatal_error(Twine(Reason), GenCrashDiag);
}

void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {
  llvm::fatal_error_handler_t handler = nullptr;
  void* handlerData = nullptr;
  {
    // Only acquire the mutex while reading the handler, so as not to invoke a
    // user-supplied callback under a lock.
    llvm::MutexGuard Lock(ErrorHandlerMutex);
    handler = ErrorHandler;
    handlerData = ErrorHandlerUserData;
  }

  if (handler) {
    handler(handlerData, Reason.str(), GenCrashDiag);
  } else {
    // Blast the result out to stderr.  We don't try hard to make sure this
    // succeeds (e.g. handling EINTR) and we can't use errs() here because
    // raw ostreams can call report_fatal_error.
    SmallVector<char, 64> Buffer;
    raw_svector_ostream OS(Buffer);
    OS << "LLVM ERROR: " << Reason << "\n";
    StringRef MessageStr = OS.str();
    ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
    (void)written; // If something went wrong, we deliberately just give up.
  }

  // If we reached here, we are failing ungracefully. Run the interrupt handlers
  // to make sure any special cleanups get done, in particular that we remove
  // files registered with RemoveFileOnSignal.
  sys::RunInterruptHandlers();

  exit(1);
}

void llvm::llvm_unreachable_internal(const char *msg, const char *file,
                                     unsigned line) {
  // This code intentionally doesn't call the ErrorHandler callback, because
  // llvm_unreachable is intended to be used to indicate "impossible"
  // situations, and not legitimate runtime errors.
  if (msg)
    dbgs() << msg << "\n";
  dbgs() << "UNREACHABLE executed";
  if (file)
    dbgs() << " at " << file << ":" << line;
  dbgs() << "!\n";
  abort();
#ifdef LLVM_BUILTIN_UNREACHABLE
  // Windows systems and possibly others don't declare abort() to be noreturn,
  // so use the unreachable builtin to avoid a Clang self-host warning.
  LLVM_BUILTIN_UNREACHABLE;
#endif
}

static void bindingsErrorHandler(void *user_data, const std::string& reason,
                                 bool gen_crash_diag) {
  LLVMFatalErrorHandler handler =
      LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);
  handler(reason.c_str());
}

void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {
  install_fatal_error_handler(bindingsErrorHandler,
                              LLVM_EXTENSION reinterpret_cast<void *>(Handler));
}

void LLVMResetFatalErrorHandler() {
  remove_fatal_error_handler();
}

#ifdef LLVM_ON_WIN32

#include <winerror.h>

// I'd rather not double the line count of the following.
#define MAP_ERR_TO_COND(x, y)                                                  \
  case x:                                                                      \
    return make_error_code(errc::y)

std::error_code llvm::mapWindowsError(unsigned EV) {
  switch (EV) {
    MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);
    MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);
    MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);
    MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);
    MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);
    MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);
    MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);
    MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);
    MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);
    MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);
    MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);
    MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);
    MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);
    MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);
    MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);
    MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);
    MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);
    MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);
    MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);
    MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);
    MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);
    MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);
    MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);
    MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);
    MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);
    MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);
    MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);
    MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);
    MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);
    MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);
    MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);
    MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);
    MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);
    MAP_ERR_TO_COND(ERROR_SEEK, io_error);
    MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);
    MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);
    MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);
    MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);
    MAP_ERR_TO_COND(WSAEACCES, permission_denied);
    MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);
    MAP_ERR_TO_COND(WSAEFAULT, bad_address);
    MAP_ERR_TO_COND(WSAEINTR, interrupted);
    MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);
    MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);
    MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);
  default:
    return std::error_code(EV, std::system_category());
  }
}

#endif
<commit_msg>Converting the ErrorHandlerMutex to a ManagedStatic to avoid the static constructor and destructor.<commit_after>//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an API used to indicate fatal error conditions.  Non-fatal
// errors (most of them) should be handled through LLVMContext.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ErrorHandling.h"
#include "llvm-c/Core.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/MutexGuard.h"
#include "llvm/Support/Threading.h"
#include "llvm/Support/WindowsError.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <cstdlib>

#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif
#if defined(_MSC_VER)
# include <io.h>
# include <fcntl.h>
#endif

using namespace llvm;

static fatal_error_handler_t ErrorHandler = nullptr;
static void *ErrorHandlerUserData = nullptr;

static ManagedStatic<sys::Mutex> ErrorHandlerMutex;

void llvm::install_fatal_error_handler(fatal_error_handler_t handler,
                                       void *user_data) {
  llvm::MutexGuard Lock(*ErrorHandlerMutex);
  assert(!ErrorHandler && "Error handler already registered!\n");
  ErrorHandler = handler;
  ErrorHandlerUserData = user_data;
}

void llvm::remove_fatal_error_handler() {
  llvm::MutexGuard Lock(*ErrorHandlerMutex);
  ErrorHandler = nullptr;
  ErrorHandlerUserData = nullptr;
}

void llvm::report_fatal_error(const char *Reason, bool GenCrashDiag) {
  report_fatal_error(Twine(Reason), GenCrashDiag);
}

void llvm::report_fatal_error(const std::string &Reason, bool GenCrashDiag) {
  report_fatal_error(Twine(Reason), GenCrashDiag);
}

void llvm::report_fatal_error(StringRef Reason, bool GenCrashDiag) {
  report_fatal_error(Twine(Reason), GenCrashDiag);
}

void llvm::report_fatal_error(const Twine &Reason, bool GenCrashDiag) {
  llvm::fatal_error_handler_t handler = nullptr;
  void* handlerData = nullptr;
  {
    // Only acquire the mutex while reading the handler, so as not to invoke a
    // user-supplied callback under a lock.
    llvm::MutexGuard Lock(*ErrorHandlerMutex);
    handler = ErrorHandler;
    handlerData = ErrorHandlerUserData;
  }

  if (handler) {
    handler(handlerData, Reason.str(), GenCrashDiag);
  } else {
    // Blast the result out to stderr.  We don't try hard to make sure this
    // succeeds (e.g. handling EINTR) and we can't use errs() here because
    // raw ostreams can call report_fatal_error.
    SmallVector<char, 64> Buffer;
    raw_svector_ostream OS(Buffer);
    OS << "LLVM ERROR: " << Reason << "\n";
    StringRef MessageStr = OS.str();
    ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
    (void)written; // If something went wrong, we deliberately just give up.
  }

  // If we reached here, we are failing ungracefully. Run the interrupt handlers
  // to make sure any special cleanups get done, in particular that we remove
  // files registered with RemoveFileOnSignal.
  sys::RunInterruptHandlers();

  exit(1);
}

void llvm::llvm_unreachable_internal(const char *msg, const char *file,
                                     unsigned line) {
  // This code intentionally doesn't call the ErrorHandler callback, because
  // llvm_unreachable is intended to be used to indicate "impossible"
  // situations, and not legitimate runtime errors.
  if (msg)
    dbgs() << msg << "\n";
  dbgs() << "UNREACHABLE executed";
  if (file)
    dbgs() << " at " << file << ":" << line;
  dbgs() << "!\n";
  abort();
#ifdef LLVM_BUILTIN_UNREACHABLE
  // Windows systems and possibly others don't declare abort() to be noreturn,
  // so use the unreachable builtin to avoid a Clang self-host warning.
  LLVM_BUILTIN_UNREACHABLE;
#endif
}

static void bindingsErrorHandler(void *user_data, const std::string& reason,
                                 bool gen_crash_diag) {
  LLVMFatalErrorHandler handler =
      LLVM_EXTENSION reinterpret_cast<LLVMFatalErrorHandler>(user_data);
  handler(reason.c_str());
}

void LLVMInstallFatalErrorHandler(LLVMFatalErrorHandler Handler) {
  install_fatal_error_handler(bindingsErrorHandler,
                              LLVM_EXTENSION reinterpret_cast<void *>(Handler));
}

void LLVMResetFatalErrorHandler() {
  remove_fatal_error_handler();
}

#ifdef LLVM_ON_WIN32

#include <winerror.h>

// I'd rather not double the line count of the following.
#define MAP_ERR_TO_COND(x, y)                                                  \
  case x:                                                                      \
    return make_error_code(errc::y)

std::error_code llvm::mapWindowsError(unsigned EV) {
  switch (EV) {
    MAP_ERR_TO_COND(ERROR_ACCESS_DENIED, permission_denied);
    MAP_ERR_TO_COND(ERROR_ALREADY_EXISTS, file_exists);
    MAP_ERR_TO_COND(ERROR_BAD_UNIT, no_such_device);
    MAP_ERR_TO_COND(ERROR_BUFFER_OVERFLOW, filename_too_long);
    MAP_ERR_TO_COND(ERROR_BUSY, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_BUSY_DRIVE, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_CANNOT_MAKE, permission_denied);
    MAP_ERR_TO_COND(ERROR_CANTOPEN, io_error);
    MAP_ERR_TO_COND(ERROR_CANTREAD, io_error);
    MAP_ERR_TO_COND(ERROR_CANTWRITE, io_error);
    MAP_ERR_TO_COND(ERROR_CURRENT_DIRECTORY, permission_denied);
    MAP_ERR_TO_COND(ERROR_DEV_NOT_EXIST, no_such_device);
    MAP_ERR_TO_COND(ERROR_DEVICE_IN_USE, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_DIR_NOT_EMPTY, directory_not_empty);
    MAP_ERR_TO_COND(ERROR_DIRECTORY, invalid_argument);
    MAP_ERR_TO_COND(ERROR_DISK_FULL, no_space_on_device);
    MAP_ERR_TO_COND(ERROR_FILE_EXISTS, file_exists);
    MAP_ERR_TO_COND(ERROR_FILE_NOT_FOUND, no_such_file_or_directory);
    MAP_ERR_TO_COND(ERROR_HANDLE_DISK_FULL, no_space_on_device);
    MAP_ERR_TO_COND(ERROR_INVALID_ACCESS, permission_denied);
    MAP_ERR_TO_COND(ERROR_INVALID_DRIVE, no_such_device);
    MAP_ERR_TO_COND(ERROR_INVALID_FUNCTION, function_not_supported);
    MAP_ERR_TO_COND(ERROR_INVALID_HANDLE, invalid_argument);
    MAP_ERR_TO_COND(ERROR_INVALID_NAME, invalid_argument);
    MAP_ERR_TO_COND(ERROR_LOCK_VIOLATION, no_lock_available);
    MAP_ERR_TO_COND(ERROR_LOCKED, no_lock_available);
    MAP_ERR_TO_COND(ERROR_NEGATIVE_SEEK, invalid_argument);
    MAP_ERR_TO_COND(ERROR_NOACCESS, permission_denied);
    MAP_ERR_TO_COND(ERROR_NOT_ENOUGH_MEMORY, not_enough_memory);
    MAP_ERR_TO_COND(ERROR_NOT_READY, resource_unavailable_try_again);
    MAP_ERR_TO_COND(ERROR_OPEN_FAILED, io_error);
    MAP_ERR_TO_COND(ERROR_OPEN_FILES, device_or_resource_busy);
    MAP_ERR_TO_COND(ERROR_OUTOFMEMORY, not_enough_memory);
    MAP_ERR_TO_COND(ERROR_PATH_NOT_FOUND, no_such_file_or_directory);
    MAP_ERR_TO_COND(ERROR_BAD_NETPATH, no_such_file_or_directory);
    MAP_ERR_TO_COND(ERROR_READ_FAULT, io_error);
    MAP_ERR_TO_COND(ERROR_RETRY, resource_unavailable_try_again);
    MAP_ERR_TO_COND(ERROR_SEEK, io_error);
    MAP_ERR_TO_COND(ERROR_SHARING_VIOLATION, permission_denied);
    MAP_ERR_TO_COND(ERROR_TOO_MANY_OPEN_FILES, too_many_files_open);
    MAP_ERR_TO_COND(ERROR_WRITE_FAULT, io_error);
    MAP_ERR_TO_COND(ERROR_WRITE_PROTECT, permission_denied);
    MAP_ERR_TO_COND(WSAEACCES, permission_denied);
    MAP_ERR_TO_COND(WSAEBADF, bad_file_descriptor);
    MAP_ERR_TO_COND(WSAEFAULT, bad_address);
    MAP_ERR_TO_COND(WSAEINTR, interrupted);
    MAP_ERR_TO_COND(WSAEINVAL, invalid_argument);
    MAP_ERR_TO_COND(WSAEMFILE, too_many_files_open);
    MAP_ERR_TO_COND(WSAENAMETOOLONG, filename_too_long);
  default:
    return std::error_code(EV, std::system_category());
  }
}

#endif
<|endoftext|>