<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <osl/diagnose.h>
#include <rtl/ustrbuf.hxx>
#include "resourceprovider.hxx"
#include <osl/mutex.hxx>
#include <vcl/svapp.hxx>

#include <tools/simplerm.hxx>
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>

#include <svtools/svtools.hrc>

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define FOLDERPICKER_TITLE            500
#define FOLDER_PICKER_DEF_DESCRIPTION 501

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_SVT_FILEPICKER_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_SVT_FILEPICKER_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_SVT_FILEPICKER_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_SVT_FILEPICKER_READONLY },
    { CHECKBOX_LINK,                            STR_SVT_FILEPICKER_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_SVT_FILEPICKER_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_SVT_FILEPICKER_PLAY },
    { LISTBOX_VERSION_LABEL,                    STR_SVT_FILEPICKER_VERSION },
    { LISTBOX_TEMPLATE_LABEL,                   STR_SVT_FILEPICKER_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE_LABEL,             STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_SVT_FILEPICKER_SELECTION },
    { FOLDERPICKER_TITLE,                       STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
    { FOLDER_PICKER_DEF_DESCRIPTION,            STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};

const sal_Int32 SIZE_TABLE = SAL_N_ELEMENTS( CtrlIdToResIdTable );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        const SolarMutexGuard aGuard;

        com::sun::star::lang::Locale aLoc( Application::GetSettings().GetUILocale() );
        m_ResMgr = new SimpleResMgr( CREATEVERSIONRESMGR_NAME( fps_office ), aLoc );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        OUString aResOUString;

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
                aResOUString = m_ResMgr->ReadString( aResId );
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    SimpleResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

OUString CResourceProvider::getResString( sal_Int16 aId )
{
   return m_pImpl->getResString( aId );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix build on Windows: use OUString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <osl/diagnose.h>
#include <rtl/ustrbuf.hxx>
#include "resourceprovider.hxx"
#include <osl/mutex.hxx>
#include <vcl/svapp.hxx>

#include <tools/simplerm.hxx>
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>

#include <svtools/svtools.hrc>

//------------------------------------------------------------
// namespace directives
//------------------------------------------------------------

using rtl::OUString;
using namespace ::com::sun::star::ui::dialogs::ExtendedFilePickerElementIds;
using namespace ::com::sun::star::ui::dialogs::CommonFilePickerElementIds;

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

#define FOLDERPICKER_TITLE            500
#define FOLDER_PICKER_DEF_DESCRIPTION 501

//------------------------------------------------------------
// we have to translate control ids to resource ids
//------------------------------------------------------------

struct _Entry
{
    sal_Int32 ctrlId;
    sal_Int16 resId;
};

_Entry CtrlIdToResIdTable[] = {
    { CHECKBOX_AUTOEXTENSION,                   STR_SVT_FILEPICKER_AUTO_EXTENSION },
    { CHECKBOX_PASSWORD,                        STR_SVT_FILEPICKER_PASSWORD },
    { CHECKBOX_FILTEROPTIONS,                   STR_SVT_FILEPICKER_FILTER_OPTIONS },
    { CHECKBOX_READONLY,                        STR_SVT_FILEPICKER_READONLY },
    { CHECKBOX_LINK,                            STR_SVT_FILEPICKER_INSERT_AS_LINK },
    { CHECKBOX_PREVIEW,                         STR_SVT_FILEPICKER_SHOW_PREVIEW },
    { PUSHBUTTON_PLAY,                          STR_SVT_FILEPICKER_PLAY },
    { LISTBOX_VERSION_LABEL,                    STR_SVT_FILEPICKER_VERSION },
    { LISTBOX_TEMPLATE_LABEL,                   STR_SVT_FILEPICKER_TEMPLATES },
    { LISTBOX_IMAGE_TEMPLATE_LABEL,             STR_SVT_FILEPICKER_IMAGE_TEMPLATE },
    { CHECKBOX_SELECTION,                       STR_SVT_FILEPICKER_SELECTION },
    { FOLDERPICKER_TITLE,                       STR_SVT_FOLDERPICKER_DEFAULT_TITLE },
    { FOLDER_PICKER_DEF_DESCRIPTION,            STR_SVT_FOLDERPICKER_DEFAULT_DESCRIPTION }
};

const sal_Int32 SIZE_TABLE = SAL_N_ELEMENTS( CtrlIdToResIdTable );

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

sal_Int16 CtrlIdToResId( sal_Int32 aControlId )
{
    sal_Int16 aResId = -1;

    for ( sal_Int32 i = 0; i < SIZE_TABLE; i++ )
    {
        if ( CtrlIdToResIdTable[i].ctrlId == aControlId )
        {
            aResId = CtrlIdToResIdTable[i].resId;
            break;
        }
    }

    return aResId;
}

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

class CResourceProvider_Impl
{
public:

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

    CResourceProvider_Impl( )
    {
        const SolarMutexGuard aGuard;

        com::sun::star::lang::Locale aLoc( Application::GetSettings().GetUILocale() );
        m_ResMgr = new SimpleResMgr( OUString( "fps_office" ), aLoc );
    }

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

    ~CResourceProvider_Impl( )
    {
        delete m_ResMgr;
    }

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

    OUString getResString( sal_Int16 aId )
    {
        OUString aResOUString;

        try
        {
            OSL_ASSERT( m_ResMgr );

            // translate the control id to a resource id
            sal_Int16 aResId = CtrlIdToResId( aId );

            if ( aResId > -1 )
                aResOUString = m_ResMgr->ReadString( aResId );
        }
        catch(...)
        {
        }

        return aResOUString;
    }

public:
    SimpleResMgr* m_ResMgr;
};

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

CResourceProvider::CResourceProvider( ) :
    m_pImpl( new CResourceProvider_Impl() )
{
}

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

CResourceProvider::~CResourceProvider( )
{
    delete m_pImpl;
}

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

OUString CResourceProvider::getResString( sal_Int16 aId )
{
   return m_pImpl->getResString( aId );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: registerservices.cxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: obo $ $Date: 2004-09-09 17:09: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: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
//_________________________________________________________________________________________________________________
//  includes of my own project
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif

/*=================================================================================================================
    Add new include and new register info to for new services.

    Example:

        #ifndef __YOUR_SERVICE_1_HXX_
        #include <service1.hxx>
        #endif

        #ifndef __YOUR_SERVICE_2_HXX_
        #include <service2.hxx>
        #endif

        COMPONENTGETIMPLEMENTATIONENVIRONMENT

        COMPONENTWRITEINFO  (   COMPONENTINFO( Service1 )
                                 COMPONENTINFO( Service2 )
                            )

        COMPONENTGETFACTORY (   IFFACTORIE( Service1 )
                                 else
                                IFFACTORIE( Service2 )
                             )
=================================================================================================================*/

#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_
#include <services/urltransformer.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_
#include <services/desktop.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_
#include <services/documentproperties.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_
#include <services/modulemanager.hxx>
#endif

#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_
#include <jobs/jobexecutor.hxx>
#endif

#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_
#include <dispatch/soundhandler.hxx>
#endif

#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif

#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif

#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#include <dispatch/mailtodispatcher.hxx>
#endif

#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_
#include <dispatch/servicehandler.hxx>
#endif

#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_
#include <jobs/jobdispatch.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#include <services/backingcomp.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_
#include <services/layoutmanager.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_
#include <services/license.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
#include <uifactory/uielementfactorymanager.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_
#include <uifactory/popupmenucontrollerfactory.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_
#include <uielement/fontmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_
#include <uielement/fontsizemenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
#include <uielement/objectmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_
#include <uielement/headermenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_
#include <uielement/footermenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_
#include <uielement/controlmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_
#include <uielement/macrosmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_
#include <uielement/uicommanddescription.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
#include <uiconfiguration/uiconfigurationmanager.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_
#include <uiconfiguration/moduleuicfgsupplier.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
#include <uiconfiguration/moduleuiconfigurationmanager.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_
#include <uifactory/menubarfactory.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_
#include <uifactory/toolboxfactory.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_
#include <uifactory/addonstoolboxfactory.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_
#include "uiconfiguration/windowstateconfiguration.hxx"
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#include "uifactory/toolbarcontrollerfactory.hxx"
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_
#include <uielement/recentfilesmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_
#include <uifactory/statusbarfactory.hxx>
#endif

COMPONENTGETIMPLEMENTATIONENVIRONMENT

COMPONENTWRITEINFO  (   COMPONENTINFO( ::framework::URLTransformer                          )
                        COMPONENTINFO( ::framework::Desktop                                 )
                        COMPONENTINFO( ::framework::Frame                                   )
                        COMPONENTINFO( ::framework::DocumentProperties                      )
                        COMPONENTINFO( ::framework::SoundHandler                            )
                        COMPONENTINFO( ::framework::JobExecutor                             )
                        COMPONENTINFO( ::framework::DispatchRecorderSupplier                )
                        COMPONENTINFO( ::framework::DispatchRecorder                        )
                        COMPONENTINFO( ::framework::MailToDispatcher                        )
                        COMPONENTINFO( ::framework::ServiceHandler                          )
                        COMPONENTINFO( ::framework::JobDispatch                             )
                        COMPONENTINFO( ::framework::BackingComp                             )
                        COMPONENTINFO( ::framework::DispatchHelper                          )
                        COMPONENTINFO( ::framework::LayoutManager                           )
                        COMPONENTINFO( ::framework::License                                 )
                        COMPONENTINFO( ::framework::UIElementFactoryManager                 )
                        COMPONENTINFO( ::framework::PopupMenuControllerFactory              )
                        COMPONENTINFO( ::framework::FontMenuController                      )
                        COMPONENTINFO( ::framework::FontSizeMenuController                  )
                        COMPONENTINFO( ::framework::ObjectMenuController                    )
                        COMPONENTINFO( ::framework::HeaderMenuController                    )
                        COMPONENTINFO( ::framework::FooterMenuController                    )
                        COMPONENTINFO( ::framework::ControlMenuController                   )
                        COMPONENTINFO( ::framework::MacrosMenuController                    )
                        COMPONENTINFO( ::framework::UICommandDescription                    )
                        COMPONENTINFO( ::framework::ModuleManager                           )
                        COMPONENTINFO( ::framework::UIConfigurationManager                  )
                        COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier    )
                        COMPONENTINFO( ::framework::ModuleUIConfigurationManager            )
                        COMPONENTINFO( ::framework::MenuBarFactory                          )
                        COMPONENTINFO( ::framework::ToolBoxFactory                          )
                        COMPONENTINFO( ::framework::AddonsToolBoxFactory                    )
                        COMPONENTINFO( ::framework::WindowStateConfiguration                )
                        COMPONENTINFO( ::framework::ToolbarsMenuController                  )
                        COMPONENTINFO( ::framework::ToolbarControllerFactory                )
                        COMPONENTINFO( ::framework::ToolbarsMenuController                  )
                        COMPONENTINFO( ::framework::RecentFilesMenuController               )
                        COMPONENTINFO( ::framework::StatusBarFactory                        )
                    )

COMPONENTGETFACTORY (   IFFACTORY( ::framework::URLTransformer                          )   else
                        IFFACTORY( ::framework::Desktop                                 )   else
                        IFFACTORY( ::framework::Frame                                   )   else
                        IFFACTORY( ::framework::DocumentProperties                      )   else
                        IFFACTORY( ::framework::SoundHandler                            )   else
                        IFFACTORY( ::framework::JobExecutor                             )   else
                        IFFACTORY( ::framework::DispatchRecorderSupplier                )   else
                        IFFACTORY( ::framework::DispatchRecorder                        )   else
                        IFFACTORY( ::framework::MailToDispatcher                        )   else
                        IFFACTORY( ::framework::ServiceHandler                          )   else
                        IFFACTORY( ::framework::JobDispatch                             )   else
                        IFFACTORY( ::framework::BackingComp                             )   else
                        IFFACTORY( ::framework::DispatchHelper                          )   else
                        IFFACTORY( ::framework::LayoutManager                           )   else
                        IFFACTORY( ::framework::License                                 )   else
                        IFFACTORY( ::framework::UIElementFactoryManager                 )   else
                        IFFACTORY( ::framework::PopupMenuControllerFactory              )   else
                        IFFACTORY( ::framework::FontMenuController                      )   else
                        IFFACTORY( ::framework::FontSizeMenuController                  )   else
                        IFFACTORY( ::framework::ObjectMenuController                    )   else
                        IFFACTORY( ::framework::HeaderMenuController                    )   else
                        IFFACTORY( ::framework::FooterMenuController                    )   else
                        IFFACTORY( ::framework::ControlMenuController                   )   else
                        IFFACTORY( ::framework::MacrosMenuController                    )   else
                        IFFACTORY( ::framework::UICommandDescription                    )   else
                        IFFACTORY( ::framework::ModuleManager                           )   else
                        IFFACTORY( ::framework::UIConfigurationManager                  )   else
                        IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier    )   else
                        IFFACTORY( ::framework::ModuleUIConfigurationManager            )   else
                        IFFACTORY( ::framework::MenuBarFactory                          )   else
                        IFFACTORY( ::framework::ToolBoxFactory                          )   else
                        IFFACTORY( ::framework::AddonsToolBoxFactory                    )   else
                        IFFACTORY( ::framework::WindowStateConfiguration                )   else
                        IFFACTORY( ::framework::ToolbarsMenuController                  )   else
                        IFFACTORY( ::framework::ToolbarControllerFactory                )   else
                        IFFACTORY( ::framework::ToolbarsMenuController                  )   else
                        IFFACTORY( ::framework::RecentFilesMenuController               )   else
                        IFFACTORY( ::framework::StatusBarFactory                        )
            )

<commit_msg>INTEGRATION: CWS keyconfig01 (1.19.36); FILE MERGED 2004/07/10 18:16:52 as 1.19.36.4: RESYNC: (1.19-1.22); FILE MERGED resolve merge conflict 2004/07/08 06:45:42 as 1.19.36.3: #i29863# support localized UI config, support new UI directory structure, adopt converter tool to support accelerators 2004/06/22 07:57:39 as 1.19.36.2: #i29863# second revision of shortcut configuration 2004/06/04 09:34:57 as 1.19.36.1: #i29863# new services for accelerator config<commit_after>/*************************************************************************
 *
 *  $RCSfile: registerservices.cxx,v $
 *
 *  $Revision: 1.25 $
 *
 *  last change: $Author: rt $ $Date: 2004-09-20 10:08:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
//_________________________________________________________________________________________________________________
//  includes of my own project
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_MACROS_REGISTRATION_HXX_
#include <macros/registration.hxx>
#endif

/*=================================================================================================================
    Add new include and new register info to for new services.

    Example:

        #ifndef __YOUR_SERVICE_1_HXX_
        #include <service1.hxx>
        #endif

        #ifndef __YOUR_SERVICE_2_HXX_
        #include <service2.hxx>
        #endif

        COMPONENTGETIMPLEMENTATIONENVIRONMENT

        COMPONENTWRITEINFO  (   COMPONENTINFO( Service1 )
                                 COMPONENTINFO( Service2 )
                            )

        COMPONENTGETFACTORY (   IFFACTORIE( Service1 )
                                 else
                                IFFACTORIE( Service2 )
                             )
=================================================================================================================*/

#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_
#include <services/urltransformer.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_DESKTOP_HXX_
#include <services/desktop.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_DOCUMENTPROPERTIES_HXX_
#include <services/documentproperties.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_MODULEMANAGER_HXX_
#include <services/modulemanager.hxx>
#endif

#ifndef __FRAMEWORK_JOBS_JOBEXECUTOR_HXX_
#include <jobs/jobexecutor.hxx>
#endif

#ifndef __FRAMEWORK_DISPATCH_SOUNDHANDLER_HXX_
#include <dispatch/soundhandler.hxx>
#endif

#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDERSUPPLIER_HXX_
#include <recording/dispatchrecordersupplier.hxx>
#endif

#ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_
#include <recording/dispatchrecorder.hxx>
#endif

#ifndef __FRAMEWORK_DISPATCH_MAILTODISPATCHER_HXX_
#include <dispatch/mailtodispatcher.hxx>
#endif

#ifndef __FRAMEWORK_DISPATCH_SERVICEHANDLER_HXX_
#include <dispatch/servicehandler.hxx>
#endif

#ifndef __FRAMEWORK_JOBS_JOBDISPATCH_HXX_
#include <jobs/jobdispatch.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_BACKINGCOMP_HXX_
#include <services/backingcomp.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_DISPATCHHELPER_HXX_
#include <services/dispatchhelper.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_LAYOUTMANAGER_HXX_
#include <services/layoutmanager.hxx>
#endif

#ifndef __FRAMEWORK_SERVICES_LICENSE_HXX_
#include <services/license.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_UIELEMENTFACTORYMANAGER_HXX_
#include <uifactory/uielementfactorymanager.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_POPUPMENUCONTROLLERFACTORY_HXX_
#include <uifactory/popupmenucontrollerfactory.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_FONTMENUCONTROLLER_HXX_
#include <uielement/fontmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_FONTSIZEMENUCONTROLLER_HXX_
#include <uielement/fontsizemenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_OBJECTMENUCONTROLLER_HXX_
#include <uielement/objectmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_HEADERMENUCONTROLLER_HXX_
#include <uielement/headermenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_FOOTERMENUCONTROLLER_HXX_
#include <uielement/footermenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_CONTROLMENUCONTROLLER_HXX_
#include <uielement/controlmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_MACROSMENUCONTROLLER_HXX_
#include <uielement/macrosmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_UICOMMANDDESCRIPTION_HXX_
#include <uielement/uicommanddescription.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_UICONFIGMANAGER_HXX_
#include <uiconfiguration/uiconfigurationmanager.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICFGSUPPLIER_HXX_
#include <uiconfiguration/moduleuicfgsupplier.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
#include <uiconfiguration/moduleuiconfigurationmanager.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_MENUBARFACTORY_HXX_
#include <uifactory/menubarfactory.hxx>
#endif

#ifndef __FRAMEWORK_ACCELERATORS_GLOBALACCELERATORCONFIGURATION_HXX_
#include <accelerators/globalacceleratorconfiguration.hxx>
#endif

#ifndef __FRAMEWORK_ACCELERATORS_MODULEACCELERATORCONFIGURATION_HXX_
#include <accelerators/moduleacceleratorconfiguration.hxx>
#endif

#ifndef __FRAMEWORK_ACCELERATORS_DOCUMENTACCELERATORCONFIGURATION_HXX_
#include <accelerators/documentacceleratorconfiguration.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_
#include <uifactory/toolboxfactory.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_ADDONSTOOLBOXFACTORY_HXX_
#include <uifactory/addonstoolboxfactory.hxx>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_WINDOWSTATECONFIGURATION_HXX_
#include "uiconfiguration/windowstateconfiguration.hxx"
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_TOOLBARCONTROLLERFACTORY_HXX_
#include "uifactory/toolbarcontrollerfactory.hxx"
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARSMENUCONTROLLER_HXX_
#include <uielement/toolbarsmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_RECENTFILESMENUCONTROLLER_HXX_
#include <uielement/recentfilesmenucontroller.hxx>
#endif

#ifndef __FRAMEWORK_UIFACTORY_STATUSBARFACTORY_HXX_
#include <uifactory/statusbarfactory.hxx>
#endif

COMPONENTGETIMPLEMENTATIONENVIRONMENT

COMPONENTWRITEINFO  (   COMPONENTINFO( ::framework::URLTransformer                          )
                        COMPONENTINFO( ::framework::Desktop                                 )
                        COMPONENTINFO( ::framework::Frame                                   )
                        COMPONENTINFO( ::framework::DocumentProperties                      )
                        COMPONENTINFO( ::framework::SoundHandler                            )
                        COMPONENTINFO( ::framework::JobExecutor                             )
                        COMPONENTINFO( ::framework::DispatchRecorderSupplier                )
                        COMPONENTINFO( ::framework::DispatchRecorder                        )
                        COMPONENTINFO( ::framework::MailToDispatcher                        )
                        COMPONENTINFO( ::framework::ServiceHandler                          )
                        COMPONENTINFO( ::framework::JobDispatch                             )
                        COMPONENTINFO( ::framework::BackingComp                             )
                        COMPONENTINFO( ::framework::DispatchHelper                          )
                        COMPONENTINFO( ::framework::LayoutManager                           )
                        COMPONENTINFO( ::framework::License                                 )
                        COMPONENTINFO( ::framework::UIElementFactoryManager                 )
                        COMPONENTINFO( ::framework::PopupMenuControllerFactory              )
                        COMPONENTINFO( ::framework::FontMenuController                      )
                        COMPONENTINFO( ::framework::FontSizeMenuController                  )
                        COMPONENTINFO( ::framework::ObjectMenuController                    )
                        COMPONENTINFO( ::framework::HeaderMenuController                    )
                        COMPONENTINFO( ::framework::FooterMenuController                    )
                        COMPONENTINFO( ::framework::ControlMenuController                   )
                        COMPONENTINFO( ::framework::MacrosMenuController                    )
                        COMPONENTINFO( ::framework::UICommandDescription                    )
                        COMPONENTINFO( ::framework::ModuleManager                           )
                        COMPONENTINFO( ::framework::UIConfigurationManager                  )
                        COMPONENTINFO( ::framework::ModuleUIConfigurationManagerSupplier    )
                        COMPONENTINFO( ::framework::ModuleUIConfigurationManager            )
                        COMPONENTINFO( ::framework::MenuBarFactory                          )
                        COMPONENTINFO( ::framework::GlobalAcceleratorConfiguration          )
                        COMPONENTINFO( ::framework::ModuleAcceleratorConfiguration          )
                        COMPONENTINFO( ::framework::DocumentAcceleratorConfiguration        )
                        COMPONENTINFO( ::framework::ToolBoxFactory                          )
                        COMPONENTINFO( ::framework::AddonsToolBoxFactory                    )
                        COMPONENTINFO( ::framework::WindowStateConfiguration                )
                        COMPONENTINFO( ::framework::ToolbarsMenuController                  )
                        COMPONENTINFO( ::framework::ToolbarControllerFactory                )
                        COMPONENTINFO( ::framework::ToolbarsMenuController                  )
                        COMPONENTINFO( ::framework::RecentFilesMenuController               )
                        COMPONENTINFO( ::framework::StatusBarFactory                        )
                    )

COMPONENTGETFACTORY (   IFFACTORY( ::framework::URLTransformer                          )   else
                        IFFACTORY( ::framework::Desktop                                 )   else
                        IFFACTORY( ::framework::Frame                                   )   else
                        IFFACTORY( ::framework::DocumentProperties                      )   else
                        IFFACTORY( ::framework::SoundHandler                            )   else
                        IFFACTORY( ::framework::JobExecutor                             )   else
                        IFFACTORY( ::framework::DispatchRecorderSupplier                )   else
                        IFFACTORY( ::framework::DispatchRecorder                        )   else
                        IFFACTORY( ::framework::MailToDispatcher                        )   else
                        IFFACTORY( ::framework::ServiceHandler                          )   else
                        IFFACTORY( ::framework::JobDispatch                             )   else
                        IFFACTORY( ::framework::BackingComp                             )   else
                        IFFACTORY( ::framework::DispatchHelper                          )   else
                        IFFACTORY( ::framework::LayoutManager                           )   else
                        IFFACTORY( ::framework::License                                 )   else
                        IFFACTORY( ::framework::UIElementFactoryManager                 )   else
                        IFFACTORY( ::framework::PopupMenuControllerFactory              )   else
                        IFFACTORY( ::framework::FontMenuController                      )   else
                        IFFACTORY( ::framework::FontSizeMenuController                  )   else
                        IFFACTORY( ::framework::ObjectMenuController                    )   else
                        IFFACTORY( ::framework::HeaderMenuController                    )   else
                        IFFACTORY( ::framework::FooterMenuController                    )   else
                        IFFACTORY( ::framework::ControlMenuController                   )   else
                        IFFACTORY( ::framework::MacrosMenuController                    )   else
                        IFFACTORY( ::framework::UICommandDescription                    )   else
                        IFFACTORY( ::framework::ModuleManager                           )   else
                        IFFACTORY( ::framework::UIConfigurationManager                  )   else
                        IFFACTORY( ::framework::ModuleUIConfigurationManagerSupplier    )   else
                        IFFACTORY( ::framework::ModuleUIConfigurationManager            )   else
                        IFFACTORY( ::framework::MenuBarFactory                          )   else
                        IFFACTORY( ::framework::GlobalAcceleratorConfiguration          )   else
                        IFFACTORY( ::framework::ModuleAcceleratorConfiguration          )   else
                        IFFACTORY( ::framework::DocumentAcceleratorConfiguration        )   else
                        IFFACTORY( ::framework::ToolBoxFactory                          )   else
                        IFFACTORY( ::framework::AddonsToolBoxFactory                    )   else
                        IFFACTORY( ::framework::WindowStateConfiguration                )   else
                        IFFACTORY( ::framework::ToolbarsMenuController                  )   else
                        IFFACTORY( ::framework::ToolbarControllerFactory                )   else
                        IFFACTORY( ::framework::ToolbarsMenuController                  )   else
                        IFFACTORY( ::framework::RecentFilesMenuController               )   else
                        IFFACTORY( ::framework::StatusBarFactory                        )
            )

<|endoftext|>


<commit_before>/*
 *  tests_SGLGraph.cpp
 *
 *  Created on: Oct 11, 2013
 *
 *  Author: Alexandre Baron
 */

#include "gtest/gtest.h"
#include "SGLGraph.h"

using namespace SGL;
using namespace std;

//*********************************FIXTURES************************************
//*****************************************************************************
//  GraphTest fixture
// *****************************************************************************
class GraphTest: public ::testing::Test {
public:
	SGLGraph<int> graph;

protected:
	void addVertices(int nbr, int p_from);
};

void GraphTest::addVertices(int p_nbr, int p_from) {
	for (int i = 0; i < p_nbr; i++) {
		graph.addVertex(p_from);
		p_from++;
	}
}

TEST_F(GraphTest, constructor) {
	EXPECT_EQ((int)graph.size(), 0);
	EXPECT_EQ((int)graph.order(), 0);
}

TEST_F(GraphTest, LogicOnEmptyGraph) {
	EXPECT_THROW(graph.deleteEdge(42, 21), logic_error);
	EXPECT_THROW(graph.deleteVertex(42), logic_error);
	EXPECT_THROW(graph.hasEdge(42, 21), logic_error);
	EXPECT_THROW(graph.vertexInDegree(42), logic_error);
	EXPECT_THROW(graph.vertexOutDegree(42), logic_error);
	EXPECT_THROW(graph.vertexNeighborhood(42), logic_error);
}

TEST_F(GraphTest, addVertex) {
	graph.addVertex(42);
	EXPECT_THROW(graph.addVertex(42), logic_error);
	graph.addVertex(21);
}

TEST_F(GraphTest, deleteVertex) {
	graph.addVertex(42);
	EXPECT_THROW(graph.deleteVertex(41), logic_error);
	graph.deleteVertex(42);
	EXPECT_THROW(graph.deleteVertex(42), logic_error);
}

TEST_F(GraphTest, hasVertex) {
	EXPECT_FALSE(graph.hasVertex(42));
	graph.addVertex(42);
	EXPECT_TRUE(graph.hasVertex(42));
	graph.deleteVertex(42);
	EXPECT_FALSE(graph.hasVertex(42));
	addVertices(2, 42);
	EXPECT_TRUE(graph.hasVertex(42));
	EXPECT_TRUE(graph.hasVertex(43));
}

TEST_F(GraphTest, vertexInDegree) {
	graph.addVertex(42);
	EXPECT_EQ((int)graph.vertexInDegree(42), 0);
	graph.addVertex(21);
	graph.addEdge(21, 42);
	EXPECT_EQ((int)graph.vertexInDegree(42), 1);
	graph.addVertex(84);
	graph.addEdge(84, 42);
	EXPECT_EQ((int)graph.vertexInDegree(42), 2);
	graph.deleteVertex(84);
	EXPECT_EQ((int)graph.vertexInDegree(42), 1);
	graph.deleteVertex(21);
	EXPECT_EQ((int)graph.vertexInDegree(42), 0);
	graph.deleteVertex(42);
	EXPECT_THROW(graph.vertexInDegree(42), logic_error);
}

TEST_F(GraphTest, vertexOutDegree) {
	graph.addVertex(42);
	EXPECT_EQ((int)graph.vertexOutDegree(42), 0);
	graph.addVertex(21);
	graph.addEdge(42, 21);
	EXPECT_EQ((int)graph.vertexOutDegree(42), 1);
	graph.addVertex(84);
	graph.addEdge(42, 84);
	EXPECT_EQ((int)graph.vertexOutDegree(42), 2);
	graph.deleteVertex(84);
	EXPECT_EQ((int)graph.vertexOutDegree(42), 1);
	graph.deleteVertex(21);
	EXPECT_EQ((int)graph.vertexOutDegree(42), 0);
	graph.deleteVertex(42);
	EXPECT_THROW(graph.vertexOutDegree(42), logic_error);
}

TEST_F(GraphTest, vertexIsSource) {
	EXPECT_THROW(graph.vertexIsSource(42), logic_error);
	graph.addVertex(42);
	EXPECT_TRUE(graph.vertexIsSource(42));
	graph.addVertex(21);
	graph.addEdge(21, 42);
	EXPECT_FALSE(graph.vertexIsSource(42));
	graph.deleteVertex(21);
	EXPECT_TRUE(graph.vertexIsSource(42));
	graph.addVertex(21);
	graph.addEdge(42, 21);
	EXPECT_TRUE(graph.vertexIsSource(42));
}

TEST_F(GraphTest, vertexIsSink) {
	EXPECT_THROW(graph.vertexIsSink(42), logic_error);
	graph.addVertex(42);
	EXPECT_TRUE(graph.vertexIsSink(42));
	graph.addVertex(21);
	graph.addEdge(21, 42);
	EXPECT_TRUE(graph.vertexIsSink(42));
	graph.deleteVertex(21);
	EXPECT_TRUE(graph.vertexIsSink(42));
	graph.addVertex(21);
	graph.addEdge(42, 21);
	EXPECT_FALSE(graph.vertexIsSink(42));
}

TEST_F(GraphTest, vertexNeighborhood) {
	addVertices(6, 42);
	// Two edges coming to 42
	graph.addEdge(43, 42);
	graph.addEdge(44, 42);
	// Two edges coming from 42
	graph.addEdge(42, 44);
	graph.addEdge(42, 45);

	vector<int> neighbors = graph.vertexNeighborhood(42);
	vector<int>::const_iterator found;

	// Neighborhood of 42 should be 3 vertices
	EXPECT_EQ((int)neighbors.size(), 3);
	for (int i = 43; i < 46; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(neighbors.begin(), neighbors.end(), i);
		EXPECT_NE(found, neighbors.end());
	}
	// Vertices which aren't in 42's neighborhood shouldn't be in the vector
	found = std::find(neighbors.begin(), neighbors.end(), 46);
	EXPECT_EQ(found, neighbors.end());

	// Let's test the "closed" parameter (should include the vertex itself in the vector)
	neighbors = graph.vertexNeighborhood(42, true);
	EXPECT_EQ((int)neighbors.size(), 4);
	for (int i = 42; i < 46; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(neighbors.begin(), neighbors.end(), i);
		EXPECT_NE(found, neighbors.end());
	}
	// Vertices which aren't in 42's neighborhood shouldn't be in the vector
	graph.addEdge(46, 43);
	found = std::find(neighbors.begin(), neighbors.end(), 46);
	EXPECT_EQ(found, neighbors.end());
	found = std::find(neighbors.begin(), neighbors.end(), 47);
	EXPECT_EQ(found, neighbors.end());
}

TEST_F(GraphTest, vertices) {
	vector<int> vertices = graph.vertices();
	EXPECT_EQ((int)vertices.size(), 0);
	addVertices(6, 42);
	vertices = graph.vertices();

	vector<int>::const_iterator found;

	EXPECT_EQ((int)vertices.size(), 6);
	for (int i = 42; i < 48; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(vertices.begin(), vertices.end(), i);
		EXPECT_NE(found, vertices.end());
	}
}

TEST_F(GraphTest, addEdge) {
	EXPECT_THROW(graph.addEdge(41, 42), logic_error);
	addVertices(2, 42);
	graph.addEdge(42, 43);
	graph.addEdge(43, 42);
	EXPECT_THROW(graph.addEdge(42, 41), logic_error);
	EXPECT_THROW(graph.addEdge(41, 43), logic_error);
}

TEST_F(GraphTest, deleteEdge) {
	EXPECT_THROW(graph.deleteEdge(42, 41), logic_error);
	addVertices(2, 42);
	EXPECT_THROW(graph.deleteEdge(42, 41), logic_error);
	EXPECT_THROW(graph.deleteEdge(41, 43), logic_error);
	graph.addEdge(42, 43);
	EXPECT_THROW(graph.deleteEdge(43, 42), logic_error);
	graph.addEdge(43, 42);
	graph.deleteEdge(42, 43);
	graph.deleteEdge(43, 42);
	EXPECT_THROW(graph.deleteEdge(42, 43), logic_error);
	EXPECT_THROW(graph.deleteEdge(43, 42), logic_error);
}

TEST_F(GraphTest, hasEdge) {
	EXPECT_THROW(graph.addEdge(41, 42), logic_error);
	addVertices(2, 42);
	EXPECT_FALSE(graph.hasEdge(42, 43));
	graph.addEdge(42, 43);
	EXPECT_FALSE(graph.hasEdge(43, 42));
	EXPECT_TRUE(graph.hasEdge(42, 43));
	graph.addEdge(43, 42);
	EXPECT_TRUE(graph.hasEdge(43, 42));
	EXPECT_TRUE(graph.hasEdge(42, 43));
	graph.deleteEdge(42, 43);
	EXPECT_TRUE(graph.hasEdge(43, 42));
	EXPECT_FALSE(graph.hasEdge(42, 43));
	graph.deleteEdge(43, 42);
	EXPECT_FALSE(graph.hasEdge(43, 42));
	EXPECT_FALSE(graph.hasEdge(42, 43));
}

TEST_F(GraphTest, display) {
	cout << graph;
	addVertices(6, 42);
	cout << graph;
	graph.addEdge(42, 43);
	graph.addEdge(42, 45);
	graph.addEdge(43, 46);
	graph.addEdge(43, 42);
	graph.addEdge(46, 45);
	graph.addEdge(46, 42);
	graph.addEdge(47, 42);
	graph.addEdge(47, 43);
	graph.addEdge(47, 44);
	graph.addEdge(47, 45);
	graph.addEdge(47, 46);
	graph.addEdge(47, 47);
	cout << graph;
}

TEST_F(GraphTest, areEqual) {
	SGLGraph<int>	copy(graph);

	EXPECT_TRUE(copy == graph);
	graph.addVertex(42);
	graph.addVertex(43);
	EXPECT_FALSE(copy == graph);
	copy.addVertex(42);
	copy.addVertex(43);
	EXPECT_TRUE(copy == graph);
	graph.addEdge(42, 43);
	graph.addEdge(43, 42);
	EXPECT_FALSE(copy == graph);
	copy.addEdge(42, 43);
	EXPECT_FALSE(copy == graph);
	copy.addEdge(43, 42);
	EXPECT_TRUE(copy == graph);
}

TEST_F(GraphTest, CopyConstructor) {
	SGLGraph<int>	copy(graph);

	EXPECT_EQ((int)copy.size(), 0);
	EXPECT_EQ((int)copy.order(), 0);

	addVertices(6, 42);
	EXPECT_EQ((int)graph.order(), 6);

	SGLGraph<int>	copy2(graph);
	vector<int> vertices = copy2.vertices();
	vector<int>::const_iterator found;

	EXPECT_EQ(graph.order(), copy2.order());
	for (int i = 42; i < 48; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(vertices.begin(), vertices.end(), i);
		EXPECT_NE(found, vertices.end());
	}
}

TEST_F(GraphTest, AssignmentOperator) {
	// from empty graph to empty graph
	SGLGraph<int>	copy;

	EXPECT_EQ((int)graph.size(), 0);
	EXPECT_EQ((int)graph.order(), 0);
	copy = graph;
	EXPECT_EQ((int)copy.size(), 0);
	EXPECT_EQ((int)copy.order(), 0);

	// from full graph to empty graph
	addVertices(6, 42);
	graph.addEdge(42, 43);
	graph.addEdge(42, 45);
	graph.addEdge(43, 46);

	copy = graph;
	EXPECT_TRUE(copy == graph);

	// from empty graph to full graph
	SGLGraph<int>	copy2;

	copy = copy2;
	EXPECT_TRUE(copy == copy2);

	// from full graph to full graph
	copy = graph;
	addVertices(2, 1);
	graph.addEdge(46, 45);
	graph.addEdge(46, 42);
	copy = graph;
	EXPECT_TRUE(copy == graph);
}
<commit_msg>Correction of the unit tests names<commit_after>/*
 *  tests_theGraph.cpp
 *
 *  Created on: Oct 11, 2013
 *
 *  Author: Alexandre Baron
 */

#include "gtest/gtest.h"
#include "SGL.h"

using namespace SGL;
using namespace std;

//*********************************FIXTURES************************************
//*****************************************************************************
//  GraphTest fixture
// *****************************************************************************
class GraphTest: public ::testing::Test {
public:
	graph<int> theGraph;

protected:
	void addVertices(int nbr, int p_from);
};

void GraphTest::addVertices(int p_nbr, int p_from) {
	for (int i = 0; i < p_nbr; i++) {
		theGraph.addVertex(p_from);
		p_from++;
	}
}

TEST_F(GraphTest, constructor) {
	EXPECT_EQ((int)theGraph.size(), 0);
	EXPECT_EQ((int)theGraph.order(), 0);
}

TEST_F(GraphTest, LogicOnEmptyGraph) {
	EXPECT_THROW(theGraph.deleteEdge(42, 21), logic_error);
	EXPECT_THROW(theGraph.deleteVertex(42), logic_error);
	EXPECT_THROW(theGraph.hasEdge(42, 21), logic_error);
	EXPECT_THROW(theGraph.vertexInDegree(42), logic_error);
	EXPECT_THROW(theGraph.vertexOutDegree(42), logic_error);
	EXPECT_THROW(theGraph.vertexNeighborhood(42), logic_error);
}

TEST_F(GraphTest, addVertex) {
	theGraph.addVertex(42);
	EXPECT_THROW(theGraph.addVertex(42), logic_error);
	theGraph.addVertex(21);
}

TEST_F(GraphTest, deleteVertex) {
	theGraph.addVertex(42);
	EXPECT_THROW(theGraph.deleteVertex(41), logic_error);
	theGraph.deleteVertex(42);
	EXPECT_THROW(theGraph.deleteVertex(42), logic_error);
}

TEST_F(GraphTest, hasVertex) {
	EXPECT_FALSE(theGraph.hasVertex(42));
	theGraph.addVertex(42);
	EXPECT_TRUE(theGraph.hasVertex(42));
	theGraph.deleteVertex(42);
	EXPECT_FALSE(theGraph.hasVertex(42));
	addVertices(2, 42);
	EXPECT_TRUE(theGraph.hasVertex(42));
	EXPECT_TRUE(theGraph.hasVertex(43));
}

TEST_F(GraphTest, vertexInDegree) {
	theGraph.addVertex(42);
	EXPECT_EQ((int)theGraph.vertexInDegree(42), 0);
	theGraph.addVertex(21);
	theGraph.addEdge(21, 42);
	EXPECT_EQ((int)theGraph.vertexInDegree(42), 1);
	theGraph.addVertex(84);
	theGraph.addEdge(84, 42);
	EXPECT_EQ((int)theGraph.vertexInDegree(42), 2);
	theGraph.deleteVertex(84);
	EXPECT_EQ((int)theGraph.vertexInDegree(42), 1);
	theGraph.deleteVertex(21);
	EXPECT_EQ((int)theGraph.vertexInDegree(42), 0);
	theGraph.deleteVertex(42);
	EXPECT_THROW(theGraph.vertexInDegree(42), logic_error);
}

TEST_F(GraphTest, vertexOutDegree) {
	theGraph.addVertex(42);
	EXPECT_EQ((int)theGraph.vertexOutDegree(42), 0);
	theGraph.addVertex(21);
	theGraph.addEdge(42, 21);
	EXPECT_EQ((int)theGraph.vertexOutDegree(42), 1);
	theGraph.addVertex(84);
	theGraph.addEdge(42, 84);
	EXPECT_EQ((int)theGraph.vertexOutDegree(42), 2);
	theGraph.deleteVertex(84);
	EXPECT_EQ((int)theGraph.vertexOutDegree(42), 1);
	theGraph.deleteVertex(21);
	EXPECT_EQ((int)theGraph.vertexOutDegree(42), 0);
	theGraph.deleteVertex(42);
	EXPECT_THROW(theGraph.vertexOutDegree(42), logic_error);
}

TEST_F(GraphTest, vertexIsSource) {
	EXPECT_THROW(theGraph.vertexIsSource(42), logic_error);
	theGraph.addVertex(42);
	EXPECT_TRUE(theGraph.vertexIsSource(42));
	theGraph.addVertex(21);
	theGraph.addEdge(21, 42);
	EXPECT_FALSE(theGraph.vertexIsSource(42));
	theGraph.deleteVertex(21);
	EXPECT_TRUE(theGraph.vertexIsSource(42));
	theGraph.addVertex(21);
	theGraph.addEdge(42, 21);
	EXPECT_TRUE(theGraph.vertexIsSource(42));
}

TEST_F(GraphTest, vertexIsSink) {
	EXPECT_THROW(theGraph.vertexIsSink(42), logic_error);
	theGraph.addVertex(42);
	EXPECT_TRUE(theGraph.vertexIsSink(42));
	theGraph.addVertex(21);
	theGraph.addEdge(21, 42);
	EXPECT_TRUE(theGraph.vertexIsSink(42));
	theGraph.deleteVertex(21);
	EXPECT_TRUE(theGraph.vertexIsSink(42));
	theGraph.addVertex(21);
	theGraph.addEdge(42, 21);
	EXPECT_FALSE(theGraph.vertexIsSink(42));
}

TEST_F(GraphTest, vertexNeighborhood) {
	addVertices(6, 42);
	// Two edges coming to 42
	theGraph.addEdge(43, 42);
	theGraph.addEdge(44, 42);
	// Two edges coming from 42
	theGraph.addEdge(42, 44);
	theGraph.addEdge(42, 45);

	vector<int> neighbors = theGraph.vertexNeighborhood(42);
	vector<int>::const_iterator found;

	// Neighborhood of 42 should be 3 vertices
	EXPECT_EQ((int)neighbors.size(), 3);
	for (int i = 43; i < 46; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(neighbors.begin(), neighbors.end(), i);
		EXPECT_NE(found, neighbors.end());
	}
	// Vertices which aren't in 42's neighborhood shouldn't be in the vector
	found = std::find(neighbors.begin(), neighbors.end(), 46);
	EXPECT_EQ(found, neighbors.end());

	// Let's test the "closed" parameter (should include the vertex itself in the vector)
	neighbors = theGraph.vertexNeighborhood(42, true);
	EXPECT_EQ((int)neighbors.size(), 4);
	for (int i = 42; i < 46; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(neighbors.begin(), neighbors.end(), i);
		EXPECT_NE(found, neighbors.end());
	}
	// Vertices which aren't in 42's neighborhood shouldn't be in the vector
	theGraph.addEdge(46, 43);
	found = std::find(neighbors.begin(), neighbors.end(), 46);
	EXPECT_EQ(found, neighbors.end());
	found = std::find(neighbors.begin(), neighbors.end(), 47);
	EXPECT_EQ(found, neighbors.end());
}

TEST_F(GraphTest, vertices) {
	vector<int> vertices = theGraph.vertices();
	EXPECT_EQ((int)vertices.size(), 0);
	addVertices(6, 42);
	vertices = theGraph.vertices();

	vector<int>::const_iterator found;

	EXPECT_EQ((int)vertices.size(), 6);
	for (int i = 42; i < 48; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(vertices.begin(), vertices.end(), i);
		EXPECT_NE(found, vertices.end());
	}
}

TEST_F(GraphTest, addEdge) {
	EXPECT_THROW(theGraph.addEdge(41, 42), logic_error);
	addVertices(2, 42);
	theGraph.addEdge(42, 43);
	theGraph.addEdge(43, 42);
	EXPECT_THROW(theGraph.addEdge(42, 41), logic_error);
	EXPECT_THROW(theGraph.addEdge(41, 43), logic_error);
}

TEST_F(GraphTest, deleteEdge) {
	EXPECT_THROW(theGraph.deleteEdge(42, 41), logic_error);
	addVertices(2, 42);
	EXPECT_THROW(theGraph.deleteEdge(42, 41), logic_error);
	EXPECT_THROW(theGraph.deleteEdge(41, 43), logic_error);
	theGraph.addEdge(42, 43);
	EXPECT_THROW(theGraph.deleteEdge(43, 42), logic_error);
	theGraph.addEdge(43, 42);
	theGraph.deleteEdge(42, 43);
	theGraph.deleteEdge(43, 42);
	EXPECT_THROW(theGraph.deleteEdge(42, 43), logic_error);
	EXPECT_THROW(theGraph.deleteEdge(43, 42), logic_error);
}

TEST_F(GraphTest, hasEdge) {
	EXPECT_THROW(theGraph.addEdge(41, 42), logic_error);
	addVertices(2, 42);
	EXPECT_FALSE(theGraph.hasEdge(42, 43));
	theGraph.addEdge(42, 43);
	EXPECT_FALSE(theGraph.hasEdge(43, 42));
	EXPECT_TRUE(theGraph.hasEdge(42, 43));
	theGraph.addEdge(43, 42);
	EXPECT_TRUE(theGraph.hasEdge(43, 42));
	EXPECT_TRUE(theGraph.hasEdge(42, 43));
	theGraph.deleteEdge(42, 43);
	EXPECT_TRUE(theGraph.hasEdge(43, 42));
	EXPECT_FALSE(theGraph.hasEdge(42, 43));
	theGraph.deleteEdge(43, 42);
	EXPECT_FALSE(theGraph.hasEdge(43, 42));
	EXPECT_FALSE(theGraph.hasEdge(42, 43));
}

TEST_F(GraphTest, display) {
	cout << theGraph;
	addVertices(6, 42);
	cout << theGraph;
	theGraph.addEdge(42, 43);
	theGraph.addEdge(42, 45);
	theGraph.addEdge(43, 46);
	theGraph.addEdge(43, 42);
	theGraph.addEdge(46, 45);
	theGraph.addEdge(46, 42);
	theGraph.addEdge(47, 42);
	theGraph.addEdge(47, 43);
	theGraph.addEdge(47, 44);
	theGraph.addEdge(47, 45);
	theGraph.addEdge(47, 46);
	theGraph.addEdge(47, 47);
	cout << theGraph;
}

TEST_F(GraphTest, areEqual) {
	graph<int>	copy(theGraph);

	EXPECT_TRUE(copy == theGraph);
	theGraph.addVertex(42);
	theGraph.addVertex(43);
	EXPECT_FALSE(copy == theGraph);
	copy.addVertex(42);
	copy.addVertex(43);
	EXPECT_TRUE(copy == theGraph);
	theGraph.addEdge(42, 43);
	theGraph.addEdge(43, 42);
	EXPECT_FALSE(copy == theGraph);
	copy.addEdge(42, 43);
	EXPECT_FALSE(copy == theGraph);
	copy.addEdge(43, 42);
	EXPECT_TRUE(copy == theGraph);
}

TEST_F(GraphTest, CopyConstructor) {
	graph<int>	copy(theGraph);

	EXPECT_EQ((int)copy.size(), 0);
	EXPECT_EQ((int)copy.order(), 0);

	addVertices(6, 42);
	EXPECT_EQ((int)theGraph.order(), 6);

	graph<int>	copy2(theGraph);
	vector<int> vertices = copy2.vertices();
	vector<int>::const_iterator found;

	EXPECT_EQ(theGraph.order(), copy2.order());
	for (int i = 42; i < 48; i++) {
		// each of the concerned vertices should be in the vector
		found = std::find(vertices.begin(), vertices.end(), i);
		EXPECT_NE(found, vertices.end());
	}
}

TEST_F(GraphTest, AssignmentOperator) {
	// from empty graph to empty graph
	graph<int>	copy;

	EXPECT_EQ((int)theGraph.size(), 0);
	EXPECT_EQ((int)theGraph.order(), 0);
	copy = theGraph;
	EXPECT_EQ((int)copy.size(), 0);
	EXPECT_EQ((int)copy.order(), 0);

	// from full graph to empty graph
	addVertices(6, 42);
	theGraph.addEdge(42, 43);
	theGraph.addEdge(42, 45);
	theGraph.addEdge(43, 46);

	copy = theGraph;
	EXPECT_TRUE(copy == theGraph);

	// from empty graph to full graph
	graph<int>	copy2;

	copy = copy2;
	EXPECT_TRUE(copy == copy2);

	// from full graph to full graph
	copy = theGraph;
	addVertices(2, 1);
	theGraph.addEdge(46, 45);
	theGraph.addEdge(46, 42);
	copy = theGraph;
	EXPECT_TRUE(copy == theGraph);
}
<|endoftext|>


<commit_before>#line 2 "quanta/core/object/object.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <quanta/core/config.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/memory.hpp>

#include <quanta/core/string/unmanaged_string.hpp>
#include <quanta/core/object/internal.hpp>
#include <quanta/core/object/object.hpp>

namespace quanta {

/// Set type.
///
/// Returns true if type changed.
bool object::set_type(Object& obj, ObjectValueType const type) {
	if (object::type(obj) == type) {
		return false;
	}
	object::clear_value(obj);
	internal::set_property(obj, M_TYPE, 0, unsigned_cast(type));
	if (type == ObjectValueType::null) {
		internal::clear_property(obj, M_VALUE_GUESS);
	} else if (type == ObjectValueType::expression) {
		object::clear_value_markers(obj);
		object::clear_source(obj);
		object::clear_tags(obj);
		object::clear_quantity(obj);
	}
	return true;
}

/// Reset value to type default.
///
/// This does not clear children if the object is an expression.
void object::clear_value(Object& obj) {
	auto& a = memory::default_allocator();
	switch (object::type(obj)) {
	case ObjectValueType::null:
		break;
	case ObjectValueType::boolean:
		obj.value.boolean = false;
		break;
	case ObjectValueType::integer:
		obj.value.numeric.integer = 0;
		unmanaged_string::clear(obj.value.numeric.unit, a);
		break;
	case ObjectValueType::decimal:
		obj.value.numeric.decimal = 0.0f;
		unmanaged_string::clear(obj.value.numeric.unit, a);
		break;
	case ObjectValueType::time:
		obj.value.time = {};
		internal::clear_property(obj, M_TM_PROPERTIES);
		break;
	case ObjectValueType::string:
		unmanaged_string::clear(obj.value.string, a);
		break;
	case ObjectValueType::expression:
		break;
	}
}

/// Copy an object.
void object::copy(Object& dst, Object const& src, bool const children IGEN_DEFAULT(true)) {
	auto& a = memory::default_allocator();
	object::clear_value(dst);
	dst.properties = src.properties;
	dst.source = src.source;
	dst.sub_source = src.sub_source;
	unmanaged_string::set(dst.name, src.name, a);
	switch (object::type(src)) {
	case ObjectValueType::null:
		break;
	case ObjectValueType::boolean:
		dst.value.boolean = src.value.boolean;
		break;
	case ObjectValueType::integer:
		dst.value.numeric.integer = src.value.numeric.integer;
		unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
		break;
	case ObjectValueType::decimal:
		dst.value.numeric.decimal = src.value.numeric.decimal;
		unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
		break;
	case ObjectValueType::time:
		dst.value.time = src.value.time;
		break;
	case ObjectValueType::string:
		unmanaged_string::set(dst.value.string, src.value.string, a);
		break;
	case ObjectValueType::expression:
		break;
	}
	array::copy(dst.tags, src.tags);
	if (children) {
		array::copy(dst.children, src.children);
	}
	if (object::has_quantity(src)) {
		if (object::has_quantity(dst)) {
			object::copy(*dst.quantity, *src.quantity);
		} else {
			dst.quantity = TOGO_CONSTRUCT(a, Object, *src.quantity);
		}
	}
}

/// Create quantity or clear existing quantity.
Object& object::make_quantity(Object& obj) {
	if (object::has_quantity(obj)) {
		object::clear(*obj.quantity);
	} else {
		obj.quantity = TOGO_CONSTRUCT_DEFAULT(memory::default_allocator(), Object);
	}
	return *obj.quantity;
}

/// Set to null and clear all properties.
void object::clear(Object& obj) {
	object::clear_name(obj);
	object::set_null(obj);
	object::clear_value_markers(obj);
	object::clear_source(obj);
	object::clear_tags(obj);
	object::clear_children(obj);
	object::clear_quantity(obj);
}

/// Resolve time value from context.
///
/// Relative date parts are taken from the context time.
/// If the time value does not specify a zone offset, it is adjusted to the
/// zone offset of the context (time assumed to be zone-local).
void object::resolve_time(Object& obj, Time context) {
	TOGO_ASSERTE(object::is_type(obj, ObjectValueType::time));
	if (!object::is_zoned(obj)) {
		time::adjust_zone_offset(obj.value.time, context.zone_offset);
	}
	// context is only used as a date, so we don't want the zone offset to shove
	// our value into another date as we apply it
	time::adjust_zone_utc(context);
	auto ct = time::clock_seconds_utc(obj.value.time);
	unsigned rel_parts = internal::get_property(obj, M_TM_CONTEXTUAL_YEAR | M_TM_CONTEXTUAL_MONTH, 0);
	if (!object::has_date(obj)) {
		obj.value.time.sec = time::date_seconds_utc(context);
		if (object::has_clock(obj)) {
			obj.value.time.sec += ct;
			object::set_time_type(obj, ObjectTimeType::date_and_clock);
		} else {
			object::set_time_type(obj, ObjectTimeType::date);
		}
	} else if (rel_parts) {
		Date date = time::gregorian::date_utc(obj.value.time);
		Date const context_date = time::gregorian::date_utc(context);
		if (rel_parts & M_TM_CONTEXTUAL_MONTH) {
			date.month = context_date.month;
			date.year = context_date.year; // implied
		} else/* if (rel_parts & M_TM_CONTEXTUAL_YEAR)*/ {
			date.year = context_date.year;
		}
		time::gregorian::set_utc(obj.value.time, date);
		if (object::has_clock(obj)) {
			obj.value.time.sec = time::date_seconds_utc(obj.value.time) + ct;
		}
	}
	internal::clear_property(obj, M_TM_UNZONED | M_TM_CONTEXTUAL_MONTH | M_TM_CONTEXTUAL_YEAR);
}

IGEN_PRIVATE
Object const* object::find_impl(
	Array<Object> const& collection,
	StringRef const& name,
	ObjectNameHash const name_hash
) {
	if (name_hash == OBJECT_NAME_NULL || array::empty(collection)) {
		return nullptr;
	}
	for (Object const& item : collection) {
		if (name_hash == item.name.hash) {
			#if defined(TOGO_DEBUG)
			if (name.valid() && !string::compare_equal(name, object::name(item))) {
				TOGO_LOG_DEBUGF(
					"hashes matched, but names mismatched: '%.*s' != '%.*s' (lookup_name != name)\n",
					name.size, name.data,
					item.name.size, item.name.data
				);
			}
			#else
				(void)name;
			#endif
			return &item;
		}
	}
	return nullptr;
}

/// Find tag by name.
Object* object::find_tag(Object& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return const_cast<Object*>(object::find_impl(obj.tags, name, name_hash));
}

/// Find tag by name.
Object const* object::find_tag(Object const& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return object::find_impl(obj.tags, name, name_hash);
}

/// Find tag by name hash.
Object* object::find_tag(Object& obj, ObjectNameHash const name_hash) {
	return const_cast<Object*>(
		object::find_impl(obj.tags, StringRef{}, name_hash)
	);
}

/// Find tag by name hash.
Object const* object::find_tag(Object const& obj, ObjectNameHash const name_hash) {
	return object::find_impl(obj.tags, StringRef{}, name_hash);
}

/// Find tag by name.
Object* object::find_child(Object& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return const_cast<Object*>(object::find_impl(obj.children, name, name_hash));
}

/// Find tag by name.
Object const* object::find_child(Object const& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return object::find_impl(obj.children, name, name_hash);
}

/// Find tag by name hash.
Object* object::find_child(Object& obj, ObjectNameHash const name_hash) {
	return const_cast<Object*>(
		object::find_impl(obj.children, StringRef{}, name_hash)
	);
}

/// Find tag by name hash.
Object const* object::find_child(Object const& obj, ObjectNameHash const name_hash) {
	return object::find_impl(obj.children, StringRef{}, name_hash);
}

} // namespace quanta
<commit_msg>lib/core/object/object: doc corrections.<commit_after>#line 2 "quanta/core/object/object.cpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
*/

#include <quanta/core/config.hpp>
#include <togo/core/log/log.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/memory.hpp>

#include <quanta/core/string/unmanaged_string.hpp>
#include <quanta/core/object/internal.hpp>
#include <quanta/core/object/object.hpp>

namespace quanta {

/// Set type.
///
/// Returns true if type changed.
bool object::set_type(Object& obj, ObjectValueType const type) {
	if (object::type(obj) == type) {
		return false;
	}
	object::clear_value(obj);
	internal::set_property(obj, M_TYPE, 0, unsigned_cast(type));
	if (type == ObjectValueType::null) {
		internal::clear_property(obj, M_VALUE_GUESS);
	} else if (type == ObjectValueType::expression) {
		object::clear_value_markers(obj);
		object::clear_source(obj);
		object::clear_tags(obj);
		object::clear_quantity(obj);
	}
	return true;
}

/// Reset value to type default.
///
/// This does not clear children if the object is an expression.
void object::clear_value(Object& obj) {
	auto& a = memory::default_allocator();
	switch (object::type(obj)) {
	case ObjectValueType::null:
		break;
	case ObjectValueType::boolean:
		obj.value.boolean = false;
		break;
	case ObjectValueType::integer:
		obj.value.numeric.integer = 0;
		unmanaged_string::clear(obj.value.numeric.unit, a);
		break;
	case ObjectValueType::decimal:
		obj.value.numeric.decimal = 0.0f;
		unmanaged_string::clear(obj.value.numeric.unit, a);
		break;
	case ObjectValueType::time:
		obj.value.time = {};
		internal::clear_property(obj, M_TM_PROPERTIES);
		break;
	case ObjectValueType::string:
		unmanaged_string::clear(obj.value.string, a);
		break;
	case ObjectValueType::expression:
		break;
	}
}

/// Copy an object.
void object::copy(Object& dst, Object const& src, bool const children IGEN_DEFAULT(true)) {
	auto& a = memory::default_allocator();
	object::clear_value(dst);
	dst.properties = src.properties;
	dst.source = src.source;
	dst.sub_source = src.sub_source;
	unmanaged_string::set(dst.name, src.name, a);
	switch (object::type(src)) {
	case ObjectValueType::null:
		break;
	case ObjectValueType::boolean:
		dst.value.boolean = src.value.boolean;
		break;
	case ObjectValueType::integer:
		dst.value.numeric.integer = src.value.numeric.integer;
		unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
		break;
	case ObjectValueType::decimal:
		dst.value.numeric.decimal = src.value.numeric.decimal;
		unmanaged_string::set(dst.value.numeric.unit, src.value.numeric.unit, a);
		break;
	case ObjectValueType::time:
		dst.value.time = src.value.time;
		break;
	case ObjectValueType::string:
		unmanaged_string::set(dst.value.string, src.value.string, a);
		break;
	case ObjectValueType::expression:
		break;
	}
	array::copy(dst.tags, src.tags);
	if (children) {
		array::copy(dst.children, src.children);
	}
	if (object::has_quantity(src)) {
		if (object::has_quantity(dst)) {
			object::copy(*dst.quantity, *src.quantity);
		} else {
			dst.quantity = TOGO_CONSTRUCT(a, Object, *src.quantity);
		}
	}
}

/// Create quantity or clear existing quantity.
Object& object::make_quantity(Object& obj) {
	if (object::has_quantity(obj)) {
		object::clear(*obj.quantity);
	} else {
		obj.quantity = TOGO_CONSTRUCT_DEFAULT(memory::default_allocator(), Object);
	}
	return *obj.quantity;
}

/// Set to null and clear all properties.
void object::clear(Object& obj) {
	object::clear_name(obj);
	object::set_null(obj);
	object::clear_value_markers(obj);
	object::clear_source(obj);
	object::clear_tags(obj);
	object::clear_children(obj);
	object::clear_quantity(obj);
}

/// Resolve time value from context.
///
/// Relative date parts are taken from the context time.
/// If the time value does not specify a zone offset, it is adjusted to the
/// zone offset of the context (time assumed to be zone-local).
void object::resolve_time(Object& obj, Time context) {
	TOGO_ASSERTE(object::is_type(obj, ObjectValueType::time));
	if (!object::is_zoned(obj)) {
		time::adjust_zone_offset(obj.value.time, context.zone_offset);
	}
	// context is only used as a date, so we don't want the zone offset to shove
	// our value into another date as we apply it
	time::adjust_zone_utc(context);
	auto ct = time::clock_seconds_utc(obj.value.time);
	unsigned rel_parts = internal::get_property(obj, M_TM_CONTEXTUAL_YEAR | M_TM_CONTEXTUAL_MONTH, 0);
	if (!object::has_date(obj)) {
		obj.value.time.sec = time::date_seconds_utc(context);
		if (object::has_clock(obj)) {
			obj.value.time.sec += ct;
			object::set_time_type(obj, ObjectTimeType::date_and_clock);
		} else {
			object::set_time_type(obj, ObjectTimeType::date);
		}
	} else if (rel_parts) {
		Date date = time::gregorian::date_utc(obj.value.time);
		Date const context_date = time::gregorian::date_utc(context);
		if (rel_parts & M_TM_CONTEXTUAL_MONTH) {
			date.month = context_date.month;
			date.year = context_date.year; // implied
		} else/* if (rel_parts & M_TM_CONTEXTUAL_YEAR)*/ {
			date.year = context_date.year;
		}
		time::gregorian::set_utc(obj.value.time, date);
		if (object::has_clock(obj)) {
			obj.value.time.sec = time::date_seconds_utc(obj.value.time) + ct;
		}
	}
	internal::clear_property(obj, M_TM_UNZONED | M_TM_CONTEXTUAL_MONTH | M_TM_CONTEXTUAL_YEAR);
}

IGEN_PRIVATE
Object const* object::find_impl(
	Array<Object> const& collection,
	StringRef const& name,
	ObjectNameHash const name_hash
) {
	if (name_hash == OBJECT_NAME_NULL || array::empty(collection)) {
		return nullptr;
	}
	for (Object const& item : collection) {
		if (name_hash == item.name.hash) {
			#if defined(TOGO_DEBUG)
			if (name.valid() && !string::compare_equal(name, object::name(item))) {
				TOGO_LOG_DEBUGF(
					"hashes matched, but names mismatched: '%.*s' != '%.*s' (lookup_name != name)\n",
					name.size, name.data,
					item.name.size, item.name.data
				);
			}
			#else
				(void)name;
			#endif
			return &item;
		}
	}
	return nullptr;
}

/// Find tag by name.
Object* object::find_tag(Object& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return const_cast<Object*>(object::find_impl(obj.tags, name, name_hash));
}

/// Find tag by name.
Object const* object::find_tag(Object const& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return object::find_impl(obj.tags, name, name_hash);
}

/// Find tag by name hash.
Object* object::find_tag(Object& obj, ObjectNameHash const name_hash) {
	return const_cast<Object*>(
		object::find_impl(obj.tags, StringRef{}, name_hash)
	);
}

/// Find tag by name hash.
Object const* object::find_tag(Object const& obj, ObjectNameHash const name_hash) {
	return object::find_impl(obj.tags, StringRef{}, name_hash);
}

/// Find child by name.
Object* object::find_child(Object& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return const_cast<Object*>(object::find_impl(obj.children, name, name_hash));
}

/// Find child by name.
Object const* object::find_child(Object const& obj, StringRef const& name) {
	ObjectNameHash const name_hash = object::hash_name(name);
	return object::find_impl(obj.children, name, name_hash);
}

/// Find child by name hash.
Object* object::find_child(Object& obj, ObjectNameHash const name_hash) {
	return const_cast<Object*>(
		object::find_impl(obj.children, StringRef{}, name_hash)
	);
}

/// Find child by name hash.
Object const* object::find_child(Object const& obj, ObjectNameHash const name_hash) {
	return object::find_impl(obj.children, StringRef{}, name_hash);
}

} // namespace quanta
<|endoftext|>


<commit_before>//
//  MSX.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 24/11/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#include "MSX.hpp"

#include "../../Processors/Z80/Z80.hpp"

#include "../../Components/1770/1770.hpp"
#include "../../Components/9918/9918.hpp"
#include "../../Components/8255/i8255.hpp"
#include "../../Components/AY38910/AY38910.hpp"

#include "../CRTMachine.hpp"
#include "../ConfigurationTarget.hpp"

namespace MSX {

class i8255PortHandler: public Intel::i8255::PortHandler {
};

class AYPortHandler: public GI::AY38910::PortHandler {
};

class ConcreteMachine:
	public Machine,
	public CPU::Z80::BusHandler,
	public CRTMachine::Machine,
	public ConfigurationTarget::Machine {
	public:
		ConcreteMachine():
			z80_(*this),
			i8255_(i8255_port_handler_) {
			ay_.set_port_handler(&ay_port_handler_);
			set_clock_rate(3579545);
		}

		void setup_output(float aspect_ratio) override {
			vdp_.reset(new TI::TMS9918(TI::TMS9918::TMS9918A));
		}

		void close_output() override {
		}

		std::shared_ptr<Outputs::CRT::CRT> get_crt() override {
			return vdp_->get_crt();
		}

		std::shared_ptr<Outputs::Speaker> get_speaker() override {
			return nullptr;
		}

		void run_for(const Cycles cycles) override {
			z80_.run_for(cycles);
		}

		void configure_as_target(const StaticAnalyser::Target &target) override {
		}

		bool insert_media(const StaticAnalyser::Media &media) override {
			return true;
		}

		HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {
			uint16_t address = cycle.address ? *cycle.address : 0x0000;
			switch(cycle.operation) {
				case CPU::Z80::PartialMachineCycle::ReadOpcode:
				case CPU::Z80::PartialMachineCycle::Read:
					*cycle.value = read_pointers_[address >> 14][address & 16383];
				break;

				case CPU::Z80::PartialMachineCycle::Write:
					write_pointers_[address >> 14][address & 16383] = *cycle.value;
				break;

				case CPU::Z80::PartialMachineCycle::Input:
					switch(address & 0xff) {
						case 0x98:	case 0x99:
							*cycle.value = vdp_->get_register(address);
						break;

						case 0xa2:
							ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC1));
							ay_.set_data_input(*cycle.value);
						break;

						case 0xa8:	case 0xa9:
						case 0xaa:	case 0xab:
							*cycle.value = i8255_.get_register(address);
						break;
					}
				break;

				case CPU::Z80::PartialMachineCycle::Output:
					switch(address & 0xff) {
						case 0x98:	case 0x99:
							vdp_->set_register(address, *cycle.value);
						break;

						case 0xa0:
							ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2 | GI::AY38910::BC1));
							ay_.set_data_input(*cycle.value);
						break;

						case 0xa1:
							ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2));
							ay_.set_data_input(*cycle.value);
						break;

						case 0xa8:	case 0xa9:
						case 0xaa:	case 0xab:
							i8255_.set_register(address, *cycle.value);
						break;
					}
				break;

				default: break;
			}

			// Per the best information I currently have, the MSX inserts an extra cycle into each opcode read,
			// but otherwise runs without pause.
			return HalfCycles((cycle.operation == CPU::Z80::PartialMachineCycle::ReadOpcode) ? 2 : 0);;
		}

		// Obtains the system ROMs.
		bool set_rom_fetcher(const std::function<std::vector<std::unique_ptr<std::vector<uint8_t>>>(const std::string &machine, const std::vector<std::string> &names)> &roms_with_names) override {
			auto roms = roms_with_names(
				"MSX",
				{
					"basic.rom",	"main_msx1.rom"
				});

			if(!roms[0] || !roms[1]) return false;

			basic_ = std::move(*roms[0]);
			basic_.resize(16384);

			main_ = std::move(*roms[1]);
			main_.resize(16384);

			return true;
		}

	private:
		CPU::Z80::Processor<ConcreteMachine, false, false> z80_;
		std::unique_ptr<TI::TMS9918> vdp_;
		Intel::i8255::i8255<i8255PortHandler> i8255_;
		GI::AY38910::AY38910 ay_;

		i8255PortHandler i8255_port_handler_;
		AYPortHandler ay_port_handler_;

		uint8_t *read_pointers_[4];
		uint8_t *write_pointers_[4];
		uint8_t ram_[65536];
		std::vector<uint8_t> basic_, main_;
};

}

using namespace MSX;

Machine *Machine::MSX() {
	return new ConcreteMachine;
}

Machine::~Machine() {}
<commit_msg>Adds just enough of the MSX memory map for the Z80 to appear to try to do useful things.<commit_after>//
//  MSX.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 24/11/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#include "MSX.hpp"

#include "../../Processors/Z80/Z80.hpp"

#include "../../Components/1770/1770.hpp"
#include "../../Components/9918/9918.hpp"
#include "../../Components/8255/i8255.hpp"
#include "../../Components/AY38910/AY38910.hpp"

#include "../CRTMachine.hpp"
#include "../ConfigurationTarget.hpp"

namespace MSX {

class i8255PortHandler: public Intel::i8255::PortHandler {
};

class AYPortHandler: public GI::AY38910::PortHandler {
};

class ConcreteMachine:
	public Machine,
	public CPU::Z80::BusHandler,
	public CRTMachine::Machine,
	public ConfigurationTarget::Machine {
	public:
		ConcreteMachine():
			z80_(*this),
			i8255_(i8255_port_handler_) {
			ay_.set_port_handler(&ay_port_handler_);
			set_clock_rate(3579545);
		}

		void setup_output(float aspect_ratio) override {
			vdp_.reset(new TI::TMS9918(TI::TMS9918::TMS9918A));
		}

		void close_output() override {
		}

		std::shared_ptr<Outputs::CRT::CRT> get_crt() override {
			return vdp_->get_crt();
		}

		std::shared_ptr<Outputs::Speaker> get_speaker() override {
			return nullptr;
		}

		void run_for(const Cycles cycles) override {
			z80_.run_for(cycles);
		}

		void configure_as_target(const StaticAnalyser::Target &target) override {
		}

		bool insert_media(const StaticAnalyser::Media &media) override {
			return true;
		}

		HalfCycles perform_machine_cycle(const CPU::Z80::PartialMachineCycle &cycle) {
			uint16_t address = cycle.address ? *cycle.address : 0x0000;
			switch(cycle.operation) {
				case CPU::Z80::PartialMachineCycle::ReadOpcode:
				case CPU::Z80::PartialMachineCycle::Read:
					*cycle.value = read_pointers_[address >> 14][address & 16383];
				break;

				case CPU::Z80::PartialMachineCycle::Write:
					write_pointers_[address >> 14][address & 16383] = *cycle.value;
				break;

				case CPU::Z80::PartialMachineCycle::Input:
					switch(address & 0xff) {
						case 0x98:	case 0x99:
							*cycle.value = vdp_->get_register(address);
						break;

						case 0xa2:
							ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC1));
							ay_.set_data_input(*cycle.value);
						break;

						case 0xa8:	case 0xa9:
						case 0xaa:	case 0xab:
							*cycle.value = i8255_.get_register(address);
						break;
					}
				break;

				case CPU::Z80::PartialMachineCycle::Output:
					switch(address & 0xff) {
						case 0x98:	case 0x99:
							printf("VDP %d %02x\n", address&1, *cycle.value);
							vdp_->set_register(address, *cycle.value);
						break;

						case 0xa0:
							ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2 | GI::AY38910::BC1));
							ay_.set_data_input(*cycle.value);
						break;

						case 0xa1:
							ay_.set_control_lines(static_cast<GI::AY38910::ControlLines>(GI::AY38910::BDIR | GI::AY38910::BC2));
							ay_.set_data_input(*cycle.value);
						break;

						case 0xa8:	case 0xa9:
						case 0xaa:	case 0xab:
							printf("8255 %d %02x\n", address&3, *cycle.value);
							i8255_.set_register(address, *cycle.value);
						break;
					}
				break;

				default: break;
			}

			// Per the best information I currently have, the MSX inserts an extra cycle into each opcode read,
			// but otherwise runs without pause.
			return HalfCycles((cycle.operation == CPU::Z80::PartialMachineCycle::ReadOpcode) ? 2 : 0);;
		}

		// Obtains the system ROMs.
		bool set_rom_fetcher(const std::function<std::vector<std::unique_ptr<std::vector<uint8_t>>>(const std::string &machine, const std::vector<std::string> &names)> &roms_with_names) override {
			auto roms = roms_with_names(
				"MSX",
				{
					"basic.rom",
					"main_msx1.rom"
				});

			if(!roms[0] || !roms[1]) return false;

			basic_ = std::move(*roms[0]);
			basic_.resize(16384);

			main_ = std::move(*roms[1]);
			main_.resize(16384);

			for(size_t c = 0; c < 4; ++c) {
				write_pointers_[c] = &ram_[c * 16384];
				read_pointers_[c] = &ram_[c * 16384];
			}
			read_pointers_[0] = main_.data();
			write_pointers_[0] = scratch_;
			read_pointers_[1] = basic_.data();
			write_pointers_[1] = scratch_;

			return true;
		}

	private:
		CPU::Z80::Processor<ConcreteMachine, false, false> z80_;
		std::unique_ptr<TI::TMS9918> vdp_;
		Intel::i8255::i8255<i8255PortHandler> i8255_;
		GI::AY38910::AY38910 ay_;

		i8255PortHandler i8255_port_handler_;
		AYPortHandler ay_port_handler_;

		uint8_t *read_pointers_[4];
		uint8_t *write_pointers_[4];
		uint8_t ram_[65536];
		uint8_t scratch_[16384];
		std::vector<uint8_t> basic_, main_;
};

}

using namespace MSX;

Machine *Machine::MSX() {
	return new ConcreteMachine;
}

Machine::~Machine() {}
<|endoftext|>


<commit_before>//  illarionserver - server for the game Illarion
//  Copyright 2011 Illarion e.V.
//
//  This file is part of illarionserver.
//
//  illarionserver is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  illarionserver 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 Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with illarionserver.  If not, see <http://www.gnu.org/licenses/>.

#include "InitialConnection.hpp"

#include "Config.hpp"
#include "Logger.hpp"
#include "netinterface/NetInterface.hpp"

#include <memory>
#include <thread>

auto InitialConnection::create() -> std::shared_ptr<InitialConnection> {
    std::shared_ptr<InitialConnection> ptr(new InitialConnection());
    std::thread servicethread([shared_this = ptr->shared_from_this()] { shared_this->run_service(); });
    servicethread.detach();
    return ptr;
}

auto InitialConnection::getNewPlayers() -> NewPlayerVector & { return newPlayers; }

void InitialConnection::run_service() {
    using boost::asio::ip::tcp;

    int port = Config::instance().port;

    auto endpoint = tcp::endpoint(tcp::v4(), port);
    acceptor = std::make_unique<tcp::acceptor>(io_service, endpoint);
    auto newConnection = std::make_shared<NetInterface>(io_service);
    using std::placeholders::_1;
    acceptor->async_accept(newConnection->getSocket(), [shared_this = shared_from_this(), newConnection](auto &&PH1) {
        shared_this->accept_connection(newConnection, PH1);
    });
    Logger::info(LogFacility::Other) << "Starting the IO Service!" << Log::end;
    io_service.run();
}

void InitialConnection::accept_connection(const std::shared_ptr<NetInterface> &connection,
                                          const boost::system::error_code &error) {
    if (!error) {
        if (connection->activate()) {
            newPlayers.push_back(connection);
        } else {
            Logger::error(LogFacility::Other) << "Error while activating connection!" << Log::end;
        }

        auto newConnection = std::make_shared<NetInterface>(io_service);
        using std::placeholders::_1;
        acceptor->async_accept(newConnection->getSocket(),
                               [shared_this = shared_from_this(), newConnection](auto &&PH1) {
                                   shared_this->accept_connection(newConnection, PH1);
                               });
    } else {
        Logger::error(LogFacility::Other) << "Could not accept connection: " << error.message() << Log::end;
    }
}

InitialConnection::~InitialConnection() { io_service.stop(); }
<commit_msg>Log and abort on io service start-up failure<commit_after>//  illarionserver - server for the game Illarion
//  Copyright 2011 Illarion e.V.
//
//  This file is part of illarionserver.
//
//  illarionserver is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Affero General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  illarionserver 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 Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License
//  along with illarionserver.  If not, see <http://www.gnu.org/licenses/>.

#include "InitialConnection.hpp"

#include "Config.hpp"
#include "Logger.hpp"
#include "netinterface/NetInterface.hpp"

#include <cstdlib>
#include <memory>
#include <thread>

auto InitialConnection::create() -> std::shared_ptr<InitialConnection> {
    std::shared_ptr<InitialConnection> ptr(new InitialConnection());
    std::thread servicethread([shared_this = ptr->shared_from_this()] { shared_this->run_service(); });
    servicethread.detach();
    return ptr;
}

auto InitialConnection::getNewPlayers() -> NewPlayerVector & { return newPlayers; }

void InitialConnection::run_service() {
    try {
        using boost::asio::ip::tcp;

        int port = Config::instance().port;

        auto endpoint = tcp::endpoint(tcp::v4(), port);
        acceptor = std::make_unique<tcp::acceptor>(io_service, endpoint);
        auto newConnection = std::make_shared<NetInterface>(io_service);
        using std::placeholders::_1;
        acceptor->async_accept(newConnection->getSocket(),
                               [shared_this = shared_from_this(), newConnection](auto &&PH1) {
                                   shared_this->accept_connection(newConnection, PH1);
                               });
        Logger::info(LogFacility::Other) << "Starting the io service." << Log::end;
        io_service.run();
    } catch (const boost::system::system_error &e) {
        Logger::critical(LogFacility::Other) << "Failed to start io service: " << e.what() << Log::end;
        std::abort();
    }
}

void InitialConnection::accept_connection(const std::shared_ptr<NetInterface> &connection,
                                          const boost::system::error_code &error) {
    if (!error) {
        if (connection->activate()) {
            newPlayers.push_back(connection);
        } else {
            Logger::error(LogFacility::Other) << "Error while activating connection!" << Log::end;
        }

        auto newConnection = std::make_shared<NetInterface>(io_service);
        using std::placeholders::_1;
        acceptor->async_accept(newConnection->getSocket(),
                               [shared_this = shared_from_this(), newConnection](auto &&PH1) {
                                   shared_this->accept_connection(newConnection, PH1);
                               });
    } else {
        Logger::error(LogFacility::Other) << "Could not accept connection: " << error.message() << Log::end;
    }
}

InitialConnection::~InitialConnection() { io_service.stop(); }
<|endoftext|>


<commit_before>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_Aps.hpp"

namespace JDKSAvdeccMCU
{

ApsStateMachine::ApsStateMachine( ApsStateMachine::StateVariables *events,
                                  ApsStateMachine::StateActions *actions,
                                  ApsStateMachine::States *states )
    : m_variables( events ), m_actions( actions ), m_states( states )
{
    m_variables->setOwner( this );
    m_actions->setOwner( this );
    m_states->setOwner( this );

    m_variables->clear();
    m_actions->clear();
    m_states->clear();
}

ApsStateMachine::~ApsStateMachine()
{
    m_variables->setOwner( 0 );
    m_actions->setOwner( 0 );
    m_states->setOwner( 0 );
}

bool ApsStateMachine::run() { return getStates()->run(); }
}
<commit_msg>Parameter name is variables not events<commit_after>/*
  Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   3. Neither the name of J.D. Koftinoff Software, Ltd. nor the names of its
      contributors may be used to endorse or promote products derived from
      this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
*/

#include "JDKSAvdeccMCU_World.hpp"
#include "JDKSAvdeccMCU_Aps.hpp"

namespace JDKSAvdeccMCU
{

ApsStateMachine::ApsStateMachine( ApsStateMachine::StateVariables *variables,
                                  ApsStateMachine::StateActions *actions,
                                  ApsStateMachine::States *states )
    : m_variables( variables ), m_actions( actions ), m_states( states )
{
    m_variables->setOwner( this );
    m_actions->setOwner( this );
    m_states->setOwner( this );

    m_variables->clear();
    m_actions->clear();
    m_states->clear();
}

ApsStateMachine::~ApsStateMachine()
{
    m_variables->setOwner( 0 );
    m_actions->setOwner( 0 );
    m_states->setOwner( 0 );
}

bool ApsStateMachine::run() { return getStates()->run(); }
}
<|endoftext|>