text
stringlengths
54
60.6k
<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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_formula.hxx" #include "core_resource.hxx" #include <tools/resmgr.hxx> // ---- needed as long as we have no contexts for components --- #include <vcl/svapp.hxx> #include <svl/solar.hrc> //......................................................................... namespace formula { //================================================================== //= ResourceManager //================================================================== ::osl::Mutex ResourceManager::s_aMutex; sal_Int32 ResourceManager::s_nClients = 0; ResMgr* ResourceManager::m_pImpl = NULL; //------------------------------------------------------------------ void ResourceManager::ensureImplExists() { if (m_pImpl) return; ::com::sun::star::lang::Locale aLocale = Application::GetSettings().GetUILocale(); ByteString sFileName("for"); m_pImpl = ResMgr::CreateResMgr(sFileName.GetBuffer(), aLocale); } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString(sal_uInt16 _nResId) { ::rtl::OUString sReturn; ensureImplExists(); if (m_pImpl) sReturn = String(ResId(_nResId,*m_pImpl)); return sReturn; } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString( sal_uInt16 _nResId, const sal_Char* _pPlaceholderAscii, const ::rtl::OUString& _rReplace ) { String sString( loadString( _nResId ) ); sString.SearchAndReplaceAscii( _pPlaceholderAscii, _rReplace ); return sString; } //------------------------------------------------------------------------- void ResourceManager::registerClient() { ::osl::MutexGuard aGuard(s_aMutex); ++s_nClients; } //------------------------------------------------------------------------- void ResourceManager::revokeClient() { ::osl::MutexGuard aGuard(s_aMutex); if (!--s_nClients && m_pImpl) { delete m_pImpl; m_pImpl = NULL; } } ResMgr* ResourceManager::getResManager() { ensureImplExists(); return m_pImpl; } //......................................................................... } // formula //......................................................................... /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>totally pointless intermediate object<commit_after>/************************************************************************* * * 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. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_formula.hxx" #include "core_resource.hxx" #include <tools/resmgr.hxx> // ---- needed as long as we have no contexts for components --- #include <vcl/svapp.hxx> #include <svl/solar.hrc> //......................................................................... namespace formula { //================================================================== //= ResourceManager //================================================================== ::osl::Mutex ResourceManager::s_aMutex; sal_Int32 ResourceManager::s_nClients = 0; ResMgr* ResourceManager::m_pImpl = NULL; //------------------------------------------------------------------ void ResourceManager::ensureImplExists() { if (m_pImpl) return; ::com::sun::star::lang::Locale aLocale = Application::GetSettings().GetUILocale(); m_pImpl = ResMgr::CreateResMgr("for", aLocale); } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString(sal_uInt16 _nResId) { ::rtl::OUString sReturn; ensureImplExists(); if (m_pImpl) sReturn = String(ResId(_nResId,*m_pImpl)); return sReturn; } //------------------------------------------------------------------ ::rtl::OUString ResourceManager::loadString( sal_uInt16 _nResId, const sal_Char* _pPlaceholderAscii, const ::rtl::OUString& _rReplace ) { String sString( loadString( _nResId ) ); sString.SearchAndReplaceAscii( _pPlaceholderAscii, _rReplace ); return sString; } //------------------------------------------------------------------------- void ResourceManager::registerClient() { ::osl::MutexGuard aGuard(s_aMutex); ++s_nClients; } //------------------------------------------------------------------------- void ResourceManager::revokeClient() { ::osl::MutexGuard aGuard(s_aMutex); if (!--s_nClients && m_pImpl) { delete m_pImpl; m_pImpl = NULL; } } ResMgr* ResourceManager::getResManager() { ensureImplExists(); return m_pImpl; } //......................................................................... } // formula //......................................................................... /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: resourceprovider.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: ihi $ $Date: 2007-07-12 13:40:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RESOURCEPROVIDER_HXX_ #include "resourceprovider.hxx" #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _TOOLS_SIMPLERESMGR_HXX #include <tools/simplerm.hxx> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #endif #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 = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry ); //------------------------------------------------------------ // //------------------------------------------------------------ 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 ::vos::OGuard aGuard( Application::GetSolarMutex() ); 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 ); } <commit_msg>INTEGRATION: CWS changefileheader (1.12.84); FILE MERGED 2008/04/01 15:17:08 thb 1.12.84.3: #i85898# Stripping all external header guards 2008/04/01 12:30:52 thb 1.12.84.2: #i85898# Stripping all external header guards 2008/03/31 13:13:21 rt 1.12.84.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: resourceprovider.cxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #include <osl/diagnose.h> #include <rtl/ustrbuf.hxx> #include "resourceprovider.hxx" #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #ifndef _TOOLS_SIMPLERESMGR_HXX #include <tools/simplerm.hxx> #endif #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 = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry ); //------------------------------------------------------------ // //------------------------------------------------------------ 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 ::vos::OGuard aGuard( Application::GetSolarMutex() ); 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 ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: resourceprovider.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-10-12 10:56:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RESOURCEPROVIDER_HXX_ #include "resourceprovider.hxx" #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _TOOLS_RESMGR_HXX #include <tools/resmgr.hxx> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #endif #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 RES_NAME fps_office #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 = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry ); //------------------------------------------------------------ // //------------------------------------------------------------ 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( ) { m_ResMgr = CREATEVERSIONRESMGR( RES_NAME ); } //------------------------------------- // //------------------------------------- ~CResourceProvider_Impl( ) { delete m_ResMgr; } //------------------------------------- // //------------------------------------- OUString getResString( sal_Int16 aId ) { String aResString; OUString aResOUString; const ::vos::OGuard aGuard( Application::GetSolarMutex() ); try { OSL_ASSERT( m_ResMgr ); // translate the control id to a resource id sal_Int16 aResId = CtrlIdToResId( aId ); if ( aResId > -1 ) { aResString = String( ResId( aResId, m_ResMgr ) ); aResOUString = OUString( aResString ); } } catch(...) { } return aResOUString; } public: ResMgr* 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 ); } <commit_msg>INTEGRATION: CWS residcleanup (1.9.52); FILE MERGED 2007/03/07 10:16:23 pl 1.9.52.1: #i74635# ResId cleanup<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: resourceprovider.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2007-04-26 08:26:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_fpicker.hxx" //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _RESOURCEPROVIDER_HXX_ #include "resourceprovider.hxx" #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _TOOLS_RESMGR_HXX #include <tools/resmgr.hxx> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #endif #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 RES_NAME fps_office #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 = sizeof( CtrlIdToResIdTable ) / sizeof( _Entry ); //------------------------------------------------------------ // //------------------------------------------------------------ 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( ) { m_ResMgr = CREATEVERSIONRESMGR( RES_NAME ); } //------------------------------------- // //------------------------------------- ~CResourceProvider_Impl( ) { delete m_ResMgr; } //------------------------------------- // //------------------------------------- OUString getResString( sal_Int16 aId ) { String aResString; OUString aResOUString; const ::vos::OGuard aGuard( Application::GetSolarMutex() ); try { OSL_ASSERT( m_ResMgr ); // translate the control id to a resource id sal_Int16 aResId = CtrlIdToResId( aId ); if ( aResId > -1 ) { aResString = String( ResId( aResId, *m_ResMgr ) ); aResOUString = OUString( aResString ); } } catch(...) { } return aResOUString; } public: ResMgr* 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 ); } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #define VERIFY_TRSM(TRI,XB) { \ (XB).setRandom(); ref = (XB); \ (TRI).solveInPlace(XB); \ VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \ } #define VERIFY_TRSM_ONTHERIGHT(TRI,XB) { \ (XB).setRandom(); ref = (XB); \ (TRI).transpose().template solveInPlace<OnTheRight>(XB.transpose()); \ VERIFY_IS_APPROX((XB).transpose() * (TRI).transpose().toDenseMatrix(), ref.transpose()); \ } template<typename Scalar,int Size, int Cols> void trsolve(int size=Size,int cols=Cols) { typedef typename NumTraits<Scalar>::Real RealScalar; Matrix<Scalar,Size,Size,ColMajor> cmLhs(size,size); Matrix<Scalar,Size,Size,RowMajor> rmLhs(size,size); enum { colmajor = Size==1 ? RowMajor : ColMajor, rowmajor = Cols==1 ? ColMajor : RowMajor }; Matrix<Scalar,Size,Cols,colmajor> cmRhs(size,cols), ref(size,cols); Matrix<Scalar,Size,Cols,rowmajor> rmRhs(size,cols); cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().array() += static_cast<RealScalar>(1); rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().array() += static_cast<RealScalar>(1); VERIFY_TRSM(cmLhs.conjugate().template triangularView<Lower>(), cmRhs); VERIFY_TRSM(cmLhs.adjoint() .template triangularView<Lower>(), cmRhs); VERIFY_TRSM(cmLhs .template triangularView<Upper>(), cmRhs); VERIFY_TRSM(cmLhs .template triangularView<Lower>(), rmRhs); VERIFY_TRSM(cmLhs.conjugate().template triangularView<Upper>(), rmRhs); VERIFY_TRSM(cmLhs.adjoint() .template triangularView<Upper>(), rmRhs); VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs); VERIFY_TRSM(cmLhs .template triangularView<UnitUpper>(), rmRhs); VERIFY_TRSM(rmLhs .template triangularView<Lower>(), cmRhs); VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Lower>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<Upper>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<Lower>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Upper>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<UnitUpper>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(rmLhs .template triangularView<Lower>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs); int c = internal::random<int>(0,cols-1); VERIFY_TRSM(rmLhs.template triangularView<Lower>(), rmRhs.col(c)); VERIFY_TRSM(cmLhs.template triangularView<Lower>(), rmRhs.col(c)); } void test_product_trsolve() { for(int i = 0; i < g_repeat ; i++) { // matrices CALL_SUBTEST_1((trsolve<float,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320)))); CALL_SUBTEST_2((trsolve<double,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320)))); CALL_SUBTEST_3((trsolve<std::complex<float>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200)))); CALL_SUBTEST_4((trsolve<std::complex<double>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200)))); // vectors CALL_SUBTEST_1((trsolve<float,Dynamic,1>(internal::random<int>(1,320)))); CALL_SUBTEST_5((trsolve<std::complex<double>,Dynamic,1>(internal::random<int>(1,320)))); CALL_SUBTEST_6((trsolve<float,1,1>())); CALL_SUBTEST_7((trsolve<float,1,2>())); CALL_SUBTEST_8((trsolve<std::complex<float>,4,1>())); } } <commit_msg>fix bug 120 : compilation issue of trsolve unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #define VERIFY_TRSM(TRI,XB) { \ (XB).setRandom(); ref = (XB); \ (TRI).solveInPlace(XB); \ VERIFY_IS_APPROX((TRI).toDenseMatrix() * (XB), ref); \ } #define VERIFY_TRSM_ONTHERIGHT(TRI,XB) { \ (XB).setRandom(); ref = (XB); \ (TRI).transpose().template solveInPlace<OnTheRight>(XB.transpose()); \ VERIFY_IS_APPROX((XB).transpose() * (TRI).transpose().toDenseMatrix(), ref.transpose()); \ } template<typename Scalar,int Size, int Cols> void trsolve(int size=Size,int cols=Cols) { typedef typename NumTraits<Scalar>::Real RealScalar; Matrix<Scalar,Size,Size,ColMajor> cmLhs(size,size); Matrix<Scalar,Size,Size,RowMajor> rmLhs(size,size); enum { colmajor = Size==1 ? RowMajor : ColMajor, rowmajor = Cols==1 ? ColMajor : RowMajor }; Matrix<Scalar,Size,Cols,colmajor> cmRhs(size,cols); Matrix<Scalar,Size,Cols,rowmajor> rmRhs(size,cols); Matrix<Scalar,Dynamic,Dynamic,colmajor> ref(size,cols); cmLhs.setRandom(); cmLhs *= static_cast<RealScalar>(0.1); cmLhs.diagonal().array() += static_cast<RealScalar>(1); rmLhs.setRandom(); rmLhs *= static_cast<RealScalar>(0.1); rmLhs.diagonal().array() += static_cast<RealScalar>(1); VERIFY_TRSM(cmLhs.conjugate().template triangularView<Lower>(), cmRhs); VERIFY_TRSM(cmLhs.adjoint() .template triangularView<Lower>(), cmRhs); VERIFY_TRSM(cmLhs .template triangularView<Upper>(), cmRhs); VERIFY_TRSM(cmLhs .template triangularView<Lower>(), rmRhs); VERIFY_TRSM(cmLhs.conjugate().template triangularView<Upper>(), rmRhs); VERIFY_TRSM(cmLhs.adjoint() .template triangularView<Upper>(), rmRhs); VERIFY_TRSM(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs); VERIFY_TRSM(cmLhs .template triangularView<UnitUpper>(), rmRhs); VERIFY_TRSM(rmLhs .template triangularView<Lower>(), cmRhs); VERIFY_TRSM(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Lower>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<Upper>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<Lower>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<Upper>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs.conjugate().template triangularView<UnitLower>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(cmLhs .template triangularView<UnitUpper>(), rmRhs); VERIFY_TRSM_ONTHERIGHT(rmLhs .template triangularView<Lower>(), cmRhs); VERIFY_TRSM_ONTHERIGHT(rmLhs.conjugate().template triangularView<UnitUpper>(), rmRhs); int c = internal::random<int>(0,cols-1); VERIFY_TRSM(rmLhs.template triangularView<Lower>(), rmRhs.col(c)); VERIFY_TRSM(cmLhs.template triangularView<Lower>(), rmRhs.col(c)); } void test_product_trsolve() { for(int i = 0; i < g_repeat ; i++) { // matrices CALL_SUBTEST_1((trsolve<float,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320)))); CALL_SUBTEST_2((trsolve<double,Dynamic,Dynamic>(internal::random<int>(1,320),internal::random<int>(1,320)))); CALL_SUBTEST_3((trsolve<std::complex<float>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200)))); CALL_SUBTEST_4((trsolve<std::complex<double>,Dynamic,Dynamic>(internal::random<int>(1,200),internal::random<int>(1,200)))); // vectors CALL_SUBTEST_1((trsolve<float,Dynamic,1>(internal::random<int>(1,320)))); CALL_SUBTEST_5((trsolve<std::complex<double>,Dynamic,1>(internal::random<int>(1,320)))); CALL_SUBTEST_6((trsolve<float,1,1>())); CALL_SUBTEST_7((trsolve<float,1,2>())); CALL_SUBTEST_8((trsolve<std::complex<float>,4,1>())); } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/tools/test_shell/simple_appcache_system.h" #include "base/callback.h" #include "base/lock.h" #include "base/task.h" #include "base/waitable_event.h" #include "webkit/appcache/appcache_interceptor.h" #include "webkit/appcache/web_application_cache_host_impl.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" using WebKit::WebApplicationCacheHost; using WebKit::WebApplicationCacheHostClient; using appcache::WebApplicationCacheHostImpl; using appcache::AppCacheBackendImpl; using appcache::AppCacheInterceptor; using appcache::AppCacheThread; namespace appcache { // An impl of AppCacheThread we need to provide to the appcache lib. bool AppCacheThread::PostTask( int id, const tracked_objects::Location& from_here, Task* task) { if (SimpleAppCacheSystem::thread_provider()) { return SimpleAppCacheSystem::thread_provider()->PostTask( id, from_here, task); } scoped_ptr<Task> task_ptr(task); MessageLoop* loop = SimpleAppCacheSystem::GetMessageLoop(id); if (loop) loop->PostTask(from_here, task_ptr.release()); return loop ? true : false; } bool AppCacheThread::CurrentlyOn(int id) { if (SimpleAppCacheSystem::thread_provider()) return SimpleAppCacheSystem::thread_provider()->CurrentlyOn(id); return MessageLoop::current() == SimpleAppCacheSystem::GetMessageLoop(id); } } // namespace appcache // SimpleFrontendProxy -------------------------------------------------------- // Proxies method calls from the backend IO thread to the frontend UI thread. class SimpleFrontendProxy : public base::RefCountedThreadSafe<SimpleFrontendProxy>, public appcache::AppCacheFrontend { public: explicit SimpleFrontendProxy(SimpleAppCacheSystem* appcache_system) : system_(appcache_system) { } void clear_appcache_system() { system_ = NULL; } virtual void OnCacheSelected(int host_id, int64 cache_id , appcache::Status status) { if (!system_) return; if (system_->is_io_thread()) system_->ui_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleFrontendProxy::OnCacheSelected, host_id, cache_id, status)); else if (system_->is_ui_thread()) system_->frontend_impl_.OnCacheSelected(host_id, cache_id, status); else NOTREACHED(); } virtual void OnStatusChanged(const std::vector<int>& host_ids, appcache::Status status) { if (!system_) return; if (system_->is_io_thread()) system_->ui_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleFrontendProxy::OnStatusChanged, host_ids, status)); else if (system_->is_ui_thread()) system_->frontend_impl_.OnStatusChanged(host_ids, status); else NOTREACHED(); } virtual void OnEventRaised(const std::vector<int>& host_ids, appcache::EventID event_id) { if (!system_) return; if (system_->is_io_thread()) system_->ui_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleFrontendProxy::OnEventRaised, host_ids, event_id)); else if (system_->is_ui_thread()) system_->frontend_impl_.OnEventRaised(host_ids, event_id); else NOTREACHED(); } virtual void OnContentBlocked(int host_id) {} private: friend class base::RefCountedThreadSafe<SimpleFrontendProxy>; ~SimpleFrontendProxy() {} SimpleAppCacheSystem* system_; }; // SimpleBackendProxy -------------------------------------------------------- // Proxies method calls from the frontend UI thread to the backend IO thread. class SimpleBackendProxy : public base::RefCountedThreadSafe<SimpleBackendProxy>, public appcache::AppCacheBackend { public: explicit SimpleBackendProxy(SimpleAppCacheSystem* appcache_system) : system_(appcache_system), event_(true, false) { get_status_callback_.reset( NewCallback(this, &SimpleBackendProxy::GetStatusCallback)); start_update_callback_.reset( NewCallback(this, &SimpleBackendProxy::StartUpdateCallback)); swap_cache_callback_.reset( NewCallback(this, &SimpleBackendProxy::SwapCacheCallback)); } virtual void RegisterHost(int host_id) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::RegisterHost, host_id)); } else if (system_->is_io_thread()) { system_->backend_impl_->RegisterHost(host_id); } else { NOTREACHED(); } } virtual void UnregisterHost(int host_id) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::UnregisterHost, host_id)); } else if (system_->is_io_thread()) { system_->backend_impl_->UnregisterHost(host_id); } else { NOTREACHED(); } } virtual void SelectCache(int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::SelectCache, host_id, document_url, cache_document_was_loaded_from, manifest_url)); } else if (system_->is_io_thread()) { system_->backend_impl_->SelectCache(host_id, document_url, cache_document_was_loaded_from, manifest_url); } else { NOTREACHED(); } } virtual void MarkAsForeignEntry(int host_id, const GURL& document_url, int64 cache_document_was_loaded_from) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::MarkAsForeignEntry, host_id, document_url, cache_document_was_loaded_from)); } else if (system_->is_io_thread()) { system_->backend_impl_->MarkAsForeignEntry( host_id, document_url, cache_document_was_loaded_from); } else { NOTREACHED(); } } virtual appcache::Status GetStatus(int host_id) { if (system_->is_ui_thread()) { status_result_ = appcache::UNCACHED; event_.Reset(); system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::GetStatus, host_id)); event_.Wait(); } else if (system_->is_io_thread()) { system_->backend_impl_->GetStatusWithCallback( host_id, get_status_callback_.get(), NULL); } else { NOTREACHED(); } return status_result_; } virtual bool StartUpdate(int host_id) { if (system_->is_ui_thread()) { bool_result_ = false; event_.Reset(); system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::StartUpdate, host_id)); event_.Wait(); } else if (system_->is_io_thread()) { system_->backend_impl_->StartUpdateWithCallback( host_id, start_update_callback_.get(), NULL); } else { NOTREACHED(); } return bool_result_; } virtual bool SwapCache(int host_id) { if (system_->is_ui_thread()) { bool_result_ = false; event_.Reset(); system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::SwapCache, host_id)); event_.Wait(); } else if (system_->is_io_thread()) { system_->backend_impl_->SwapCacheWithCallback( host_id, swap_cache_callback_.get(), NULL); } else { NOTREACHED(); } return bool_result_; } void GetStatusCallback(appcache::Status status, void* param) { status_result_ = status; event_.Signal(); } void StartUpdateCallback(bool result, void* param) { bool_result_ = result; event_.Signal(); } void SwapCacheCallback(bool result, void* param) { bool_result_ = result; event_.Signal(); } void SignalEvent() { event_.Signal(); } private: friend class base::RefCountedThreadSafe<SimpleBackendProxy>; ~SimpleBackendProxy() {} SimpleAppCacheSystem* system_; base::WaitableEvent event_; bool bool_result_; appcache::Status status_result_; scoped_ptr<appcache::GetStatusCallback> get_status_callback_; scoped_ptr<appcache::StartUpdateCallback> start_update_callback_; scoped_ptr<appcache::SwapCacheCallback> swap_cache_callback_; }; // SimpleAppCacheSystem -------------------------------------------------------- // This class only works for a single process browser. static const int kSingleProcessId = 1; // A not so thread safe singleton, but should work for test_shell. SimpleAppCacheSystem* SimpleAppCacheSystem::instance_ = NULL; SimpleAppCacheSystem::SimpleAppCacheSystem() : io_message_loop_(NULL), ui_message_loop_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST( backend_proxy_(new SimpleBackendProxy(this))), ALLOW_THIS_IN_INITIALIZER_LIST( frontend_proxy_(new SimpleFrontendProxy(this))), backend_impl_(NULL), service_(NULL), db_thread_("AppCacheDBThread"), thread_provider_(NULL) { DCHECK(!instance_); instance_ = this; } static void SignalEvent(base::WaitableEvent* event) { event->Signal(); } SimpleAppCacheSystem::~SimpleAppCacheSystem() { DCHECK(!io_message_loop_ && !backend_impl_ && !service_); frontend_proxy_->clear_appcache_system(); // in case a task is in transit instance_ = NULL; if (db_thread_.IsRunning()) { // We pump a task thru the db thread to ensure any tasks previously // scheduled on that thread have been performed prior to return. base::WaitableEvent event(false, false); db_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableFunction(&SignalEvent, &event)); event.Wait(); } } void SimpleAppCacheSystem::InitOnUIThread( const FilePath& cache_directory) { DCHECK(!ui_message_loop_); // TODO(michaeln): provide a cache_thread message loop AppCacheThread::Init(DB_THREAD_ID, IO_THREAD_ID, NULL); ui_message_loop_ = MessageLoop::current(); cache_directory_ = cache_directory; } void SimpleAppCacheSystem::InitOnIOThread(URLRequestContext* request_context) { if (!is_initailized_on_ui_thread()) return; DCHECK(!io_message_loop_); io_message_loop_ = MessageLoop::current(); io_message_loop_->AddDestructionObserver(this); if (!db_thread_.IsRunning()) db_thread_.Start(); // Recreate and initialize per each IO thread. service_ = new appcache::AppCacheService(); backend_impl_ = new appcache::AppCacheBackendImpl(); service_->Initialize(cache_directory_); service_->set_request_context(request_context); backend_impl_->Initialize(service_, frontend_proxy_.get(), kSingleProcessId); AppCacheInterceptor::EnsureRegistered(); } WebApplicationCacheHost* SimpleAppCacheSystem::CreateCacheHostForWebKit( WebApplicationCacheHostClient* client) { if (!is_initailized_on_ui_thread()) return NULL; DCHECK(is_ui_thread()); // The IO thread needs to be running for this system to work. SimpleResourceLoaderBridge::EnsureIOThread(); if (!is_initialized()) return NULL; return new WebApplicationCacheHostImpl(client, backend_proxy_.get()); } void SimpleAppCacheSystem::SetExtraRequestBits( URLRequest* request, int host_id, ResourceType::Type resource_type) { if (is_initialized()) { DCHECK(is_io_thread()); AppCacheInterceptor::SetExtraRequestInfo( request, service_, kSingleProcessId, host_id, resource_type); } } void SimpleAppCacheSystem::GetExtraResponseBits( URLRequest* request, int64* cache_id, GURL* manifest_url) { if (is_initialized()) { DCHECK(is_io_thread()); AppCacheInterceptor::GetExtraResponseInfo( request, cache_id, manifest_url); } } void SimpleAppCacheSystem::WillDestroyCurrentMessageLoop() { DCHECK(is_io_thread()); DCHECK(backend_impl_->hosts().empty()); delete backend_impl_; delete service_; backend_impl_ = NULL; service_ = NULL; io_message_loop_ = NULL; // Just in case the main thread is waiting on it. backend_proxy_->SignalEvent(); } <commit_msg>Remove DCHECK in SimpleAppCacheSysmte::WillDestroyCurrentMessageLoop. This was causing the test_shell to die trying to produce the extension docs.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/tools/test_shell/simple_appcache_system.h" #include "base/callback.h" #include "base/lock.h" #include "base/task.h" #include "base/waitable_event.h" #include "webkit/appcache/appcache_interceptor.h" #include "webkit/appcache/web_application_cache_host_impl.h" #include "webkit/tools/test_shell/simple_resource_loader_bridge.h" using WebKit::WebApplicationCacheHost; using WebKit::WebApplicationCacheHostClient; using appcache::WebApplicationCacheHostImpl; using appcache::AppCacheBackendImpl; using appcache::AppCacheInterceptor; using appcache::AppCacheThread; namespace appcache { // An impl of AppCacheThread we need to provide to the appcache lib. bool AppCacheThread::PostTask( int id, const tracked_objects::Location& from_here, Task* task) { if (SimpleAppCacheSystem::thread_provider()) { return SimpleAppCacheSystem::thread_provider()->PostTask( id, from_here, task); } scoped_ptr<Task> task_ptr(task); MessageLoop* loop = SimpleAppCacheSystem::GetMessageLoop(id); if (loop) loop->PostTask(from_here, task_ptr.release()); return loop ? true : false; } bool AppCacheThread::CurrentlyOn(int id) { if (SimpleAppCacheSystem::thread_provider()) return SimpleAppCacheSystem::thread_provider()->CurrentlyOn(id); return MessageLoop::current() == SimpleAppCacheSystem::GetMessageLoop(id); } } // namespace appcache // SimpleFrontendProxy -------------------------------------------------------- // Proxies method calls from the backend IO thread to the frontend UI thread. class SimpleFrontendProxy : public base::RefCountedThreadSafe<SimpleFrontendProxy>, public appcache::AppCacheFrontend { public: explicit SimpleFrontendProxy(SimpleAppCacheSystem* appcache_system) : system_(appcache_system) { } void clear_appcache_system() { system_ = NULL; } virtual void OnCacheSelected(int host_id, int64 cache_id , appcache::Status status) { if (!system_) return; if (system_->is_io_thread()) system_->ui_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleFrontendProxy::OnCacheSelected, host_id, cache_id, status)); else if (system_->is_ui_thread()) system_->frontend_impl_.OnCacheSelected(host_id, cache_id, status); else NOTREACHED(); } virtual void OnStatusChanged(const std::vector<int>& host_ids, appcache::Status status) { if (!system_) return; if (system_->is_io_thread()) system_->ui_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleFrontendProxy::OnStatusChanged, host_ids, status)); else if (system_->is_ui_thread()) system_->frontend_impl_.OnStatusChanged(host_ids, status); else NOTREACHED(); } virtual void OnEventRaised(const std::vector<int>& host_ids, appcache::EventID event_id) { if (!system_) return; if (system_->is_io_thread()) system_->ui_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleFrontendProxy::OnEventRaised, host_ids, event_id)); else if (system_->is_ui_thread()) system_->frontend_impl_.OnEventRaised(host_ids, event_id); else NOTREACHED(); } virtual void OnContentBlocked(int host_id) {} private: friend class base::RefCountedThreadSafe<SimpleFrontendProxy>; ~SimpleFrontendProxy() {} SimpleAppCacheSystem* system_; }; // SimpleBackendProxy -------------------------------------------------------- // Proxies method calls from the frontend UI thread to the backend IO thread. class SimpleBackendProxy : public base::RefCountedThreadSafe<SimpleBackendProxy>, public appcache::AppCacheBackend { public: explicit SimpleBackendProxy(SimpleAppCacheSystem* appcache_system) : system_(appcache_system), event_(true, false) { get_status_callback_.reset( NewCallback(this, &SimpleBackendProxy::GetStatusCallback)); start_update_callback_.reset( NewCallback(this, &SimpleBackendProxy::StartUpdateCallback)); swap_cache_callback_.reset( NewCallback(this, &SimpleBackendProxy::SwapCacheCallback)); } virtual void RegisterHost(int host_id) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::RegisterHost, host_id)); } else if (system_->is_io_thread()) { system_->backend_impl_->RegisterHost(host_id); } else { NOTREACHED(); } } virtual void UnregisterHost(int host_id) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::UnregisterHost, host_id)); } else if (system_->is_io_thread()) { system_->backend_impl_->UnregisterHost(host_id); } else { NOTREACHED(); } } virtual void SelectCache(int host_id, const GURL& document_url, const int64 cache_document_was_loaded_from, const GURL& manifest_url) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::SelectCache, host_id, document_url, cache_document_was_loaded_from, manifest_url)); } else if (system_->is_io_thread()) { system_->backend_impl_->SelectCache(host_id, document_url, cache_document_was_loaded_from, manifest_url); } else { NOTREACHED(); } } virtual void MarkAsForeignEntry(int host_id, const GURL& document_url, int64 cache_document_was_loaded_from) { if (system_->is_ui_thread()) { system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::MarkAsForeignEntry, host_id, document_url, cache_document_was_loaded_from)); } else if (system_->is_io_thread()) { system_->backend_impl_->MarkAsForeignEntry( host_id, document_url, cache_document_was_loaded_from); } else { NOTREACHED(); } } virtual appcache::Status GetStatus(int host_id) { if (system_->is_ui_thread()) { status_result_ = appcache::UNCACHED; event_.Reset(); system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::GetStatus, host_id)); event_.Wait(); } else if (system_->is_io_thread()) { system_->backend_impl_->GetStatusWithCallback( host_id, get_status_callback_.get(), NULL); } else { NOTREACHED(); } return status_result_; } virtual bool StartUpdate(int host_id) { if (system_->is_ui_thread()) { bool_result_ = false; event_.Reset(); system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::StartUpdate, host_id)); event_.Wait(); } else if (system_->is_io_thread()) { system_->backend_impl_->StartUpdateWithCallback( host_id, start_update_callback_.get(), NULL); } else { NOTREACHED(); } return bool_result_; } virtual bool SwapCache(int host_id) { if (system_->is_ui_thread()) { bool_result_ = false; event_.Reset(); system_->io_message_loop()->PostTask(FROM_HERE, NewRunnableMethod( this, &SimpleBackendProxy::SwapCache, host_id)); event_.Wait(); } else if (system_->is_io_thread()) { system_->backend_impl_->SwapCacheWithCallback( host_id, swap_cache_callback_.get(), NULL); } else { NOTREACHED(); } return bool_result_; } void GetStatusCallback(appcache::Status status, void* param) { status_result_ = status; event_.Signal(); } void StartUpdateCallback(bool result, void* param) { bool_result_ = result; event_.Signal(); } void SwapCacheCallback(bool result, void* param) { bool_result_ = result; event_.Signal(); } void SignalEvent() { event_.Signal(); } private: friend class base::RefCountedThreadSafe<SimpleBackendProxy>; ~SimpleBackendProxy() {} SimpleAppCacheSystem* system_; base::WaitableEvent event_; bool bool_result_; appcache::Status status_result_; scoped_ptr<appcache::GetStatusCallback> get_status_callback_; scoped_ptr<appcache::StartUpdateCallback> start_update_callback_; scoped_ptr<appcache::SwapCacheCallback> swap_cache_callback_; }; // SimpleAppCacheSystem -------------------------------------------------------- // This class only works for a single process browser. static const int kSingleProcessId = 1; // A not so thread safe singleton, but should work for test_shell. SimpleAppCacheSystem* SimpleAppCacheSystem::instance_ = NULL; SimpleAppCacheSystem::SimpleAppCacheSystem() : io_message_loop_(NULL), ui_message_loop_(NULL), ALLOW_THIS_IN_INITIALIZER_LIST( backend_proxy_(new SimpleBackendProxy(this))), ALLOW_THIS_IN_INITIALIZER_LIST( frontend_proxy_(new SimpleFrontendProxy(this))), backend_impl_(NULL), service_(NULL), db_thread_("AppCacheDBThread"), thread_provider_(NULL) { DCHECK(!instance_); instance_ = this; } static void SignalEvent(base::WaitableEvent* event) { event->Signal(); } SimpleAppCacheSystem::~SimpleAppCacheSystem() { DCHECK(!io_message_loop_ && !backend_impl_ && !service_); frontend_proxy_->clear_appcache_system(); // in case a task is in transit instance_ = NULL; if (db_thread_.IsRunning()) { // We pump a task thru the db thread to ensure any tasks previously // scheduled on that thread have been performed prior to return. base::WaitableEvent event(false, false); db_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableFunction(&SignalEvent, &event)); event.Wait(); } } void SimpleAppCacheSystem::InitOnUIThread( const FilePath& cache_directory) { DCHECK(!ui_message_loop_); // TODO(michaeln): provide a cache_thread message loop AppCacheThread::Init(DB_THREAD_ID, IO_THREAD_ID, NULL); ui_message_loop_ = MessageLoop::current(); cache_directory_ = cache_directory; } void SimpleAppCacheSystem::InitOnIOThread(URLRequestContext* request_context) { if (!is_initailized_on_ui_thread()) return; DCHECK(!io_message_loop_); io_message_loop_ = MessageLoop::current(); io_message_loop_->AddDestructionObserver(this); if (!db_thread_.IsRunning()) db_thread_.Start(); // Recreate and initialize per each IO thread. service_ = new appcache::AppCacheService(); backend_impl_ = new appcache::AppCacheBackendImpl(); service_->Initialize(cache_directory_); service_->set_request_context(request_context); backend_impl_->Initialize(service_, frontend_proxy_.get(), kSingleProcessId); AppCacheInterceptor::EnsureRegistered(); } WebApplicationCacheHost* SimpleAppCacheSystem::CreateCacheHostForWebKit( WebApplicationCacheHostClient* client) { if (!is_initailized_on_ui_thread()) return NULL; DCHECK(is_ui_thread()); // The IO thread needs to be running for this system to work. SimpleResourceLoaderBridge::EnsureIOThread(); if (!is_initialized()) return NULL; return new WebApplicationCacheHostImpl(client, backend_proxy_.get()); } void SimpleAppCacheSystem::SetExtraRequestBits( URLRequest* request, int host_id, ResourceType::Type resource_type) { if (is_initialized()) { DCHECK(is_io_thread()); AppCacheInterceptor::SetExtraRequestInfo( request, service_, kSingleProcessId, host_id, resource_type); } } void SimpleAppCacheSystem::GetExtraResponseBits( URLRequest* request, int64* cache_id, GURL* manifest_url) { if (is_initialized()) { DCHECK(is_io_thread()); AppCacheInterceptor::GetExtraResponseInfo( request, cache_id, manifest_url); } } void SimpleAppCacheSystem::WillDestroyCurrentMessageLoop() { DCHECK(is_io_thread()); delete backend_impl_; delete service_; backend_impl_ = NULL; service_ = NULL; io_message_loop_ = NULL; // Just in case the main thread is waiting on it. backend_proxy_->SignalEvent(); } <|endoftext|>
<commit_before>#include <signal.h> #ifdef PROFILER #include <gperftools/profiler.h> #endif #include "sparse_matrix.h" #include "matrix/FG_sparse_matrix.h" using namespace fm; void int_handler(int sig_num) { #ifdef PROFILER printf("stop profiling\n"); if (!fg::graph_conf.get_prof_file().empty()) ProfilerStop(); #endif exit(0); } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "test conf_file graph_file index_file\n"); exit(1); } std::string conf_file = argv[1]; std::string graph_file = argv[2]; std::string index_file = argv[3]; signal(SIGINT, int_handler); struct timeval start, end; config_map::ptr configs = config_map::create(conf_file); init_flash_matrix(configs); fg::FG_graph::ptr fg = fg::FG_graph::create(graph_file, index_file, configs); fg::FG_adj_matrix::ptr fg_m = fg::FG_adj_matrix::create(fg); fg::FG_vector<double>::ptr in = fg::FG_vector<double>::create(fg_m->get_num_cols()); for (size_t i = 0; i < in->get_size(); i++) in->set(i, i); printf("sum of input: %lf\n", in->sum()); gettimeofday(&start, NULL); fg::FG_vector<double>::ptr fg_out = fg::FG_vector<double>::create( fg_m->get_num_rows()); gettimeofday(&end, NULL); printf("initialize FG_vector of %ld entries takes %.3f seconds\n", fg_out->get_size(), time_diff(start, end)); gettimeofday(&start, NULL); fg_m->multiply<double>(*in, *fg_out); gettimeofday(&end, NULL); printf("sum of input: %lf, sum of FG product: %lf, it takes %.3f seconds\n", in->sum(), fg_out->sum(), time_diff(start, end)); NUMA_vector::ptr in_vec = NUMA_vector::create(fg_m->get_num_cols(), get_scalar_type<double>()); for (size_t i = 0; i < fg_m->get_num_cols(); i++) in_vec->set(i, i); sparse_matrix::ptr m = sparse_matrix::create(fg); gettimeofday(&start, NULL); NUMA_vector::ptr out = m->multiply<double>(in_vec); gettimeofday(&end, NULL); double sum = 0; for (size_t i = 0; i < fg_m->get_num_cols(); i++) sum += out->get<double>(i); printf("sum of input: %lf, sum of product: %lf, it takes %.3f seconds\n", in->sum(), sum, time_diff(start, end)); destroy_flash_matrix(); } <commit_msg>[Matrix]: fix a bug caused by remove type_mem_vector.<commit_after>#include <signal.h> #ifdef PROFILER #include <gperftools/profiler.h> #endif #include "sparse_matrix.h" #include "matrix/FG_sparse_matrix.h" using namespace fm; void int_handler(int sig_num) { #ifdef PROFILER printf("stop profiling\n"); if (!fg::graph_conf.get_prof_file().empty()) ProfilerStop(); #endif exit(0); } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "test conf_file graph_file index_file\n"); exit(1); } std::string conf_file = argv[1]; std::string graph_file = argv[2]; std::string index_file = argv[3]; signal(SIGINT, int_handler); struct timeval start, end; config_map::ptr configs = config_map::create(conf_file); init_flash_matrix(configs); fg::FG_graph::ptr fg = fg::FG_graph::create(graph_file, index_file, configs); fg::FG_adj_matrix::ptr fg_m = fg::FG_adj_matrix::create(fg); fg::FG_vector<double>::ptr in = fg::FG_vector<double>::create(fg_m->get_num_cols()); for (size_t i = 0; i < in->get_size(); i++) in->set(i, i); printf("sum of input: %lf\n", in->sum()); gettimeofday(&start, NULL); fg::FG_vector<double>::ptr fg_out = fg::FG_vector<double>::create( fg_m->get_num_rows()); gettimeofday(&end, NULL); printf("initialize FG_vector of %ld entries takes %.3f seconds\n", fg_out->get_size(), time_diff(start, end)); gettimeofday(&start, NULL); fg_m->multiply<double>(*in, *fg_out); gettimeofday(&end, NULL); printf("sum of input: %lf, sum of FG product: %lf, it takes %.3f seconds\n", in->sum(), fg_out->sum(), time_diff(start, end)); NUMA_vector::ptr in_vec = NUMA_vector::create(fg_m->get_num_cols(), get_scalar_type<double>()); for (size_t i = 0; i < fg_m->get_num_cols(); i++) in_vec->set<double>(i, i); sparse_matrix::ptr m = sparse_matrix::create(fg); gettimeofday(&start, NULL); NUMA_vector::ptr out = m->multiply<double>(in_vec); gettimeofday(&end, NULL); double sum = 0; for (size_t i = 0; i < fg_m->get_num_cols(); i++) sum += out->get<double>(i); printf("sum of input: %lf, sum of product: %lf, it takes %.3f seconds\n", in->sum(), sum, time_diff(start, end)); destroy_flash_matrix(); } <|endoftext|>
<commit_before>/* * TH02_dev.cpp * Driver for DIGITAL I2C HUMIDITY AND TEMPERATURE SENSOR * * Copyright (c) 2014 seeed technology inc. * Website : www.seeed.cc * Author : Oliver Wang * Create Time: April 2014 * Change Log : * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /****************************************************************************/ /*** Include files ***/ /****************************************************************************/ #include "TH02_dev.h" /* Use Serial IIC */ #ifdef SERIAL_IIC #endif TH02_dev TH02; /****************************************************************************/ /*** Local Variable ***/ /****************************************************************************/ /****************************************************************************/ /*** Class member Functions ***/ /****************************************************************************/ void TH02_dev::begin(void) { /* Start IIC */ Wire.begin(); /* TH02 don't need to software reset */ } float TH02_dev::ReadTemperature(void) { /* Start a new temperature conversion */ TH02_IIC_WriteReg(REG_CONFIG, CMD_MEASURE_TEMP); //delay(100); /* Wait until conversion is done */ while(!isAvailable()); uint16_t value = TH02_IIC_ReadData(); value = value >> 2; /* Formula: Temperature(C) = (Value/32) - 50 */ float temper = (value/32.0)-50.0; return temper; } float TH02_dev::ReadHumidity(void) { /* Start a new humility conversion */ TH02_IIC_WriteReg(REG_CONFIG, CMD_MEASURE_HUMI); /* Wait until conversion is done */ //delay(100); while(!isAvailable()); uint16_t value = TH02_IIC_ReadData(); value = value >> 4; /* Formula: Humidity(%) = (Value/16) - 24 */ float humility = (value/16.0)-24.0; return humility; } /****************************************************************************/ /*** Local Functions ***/ /****************************************************************************/ uint8_t TH02_dev::isAvailable() { uint8_t status = TH02_IIC_ReadReg(REG_STATUS); if(status & STATUS_RDY_MASK) { return 0; //ready } else { return 1; //not ready yet } } void TH02_dev::TH02_IIC_WriteCmd(uint8_t u8Cmd) { /* Port to arduino */ Wire.beginTransmission(TH02_I2C_DEV_ID); Wire.write(u8Cmd); Wire.endTransmission(); } uint8_t TH02_dev::TH02_IIC_ReadReg(uint8_t u8Reg) { /* Port to arduino */ uint8_t Temp = 0; /* Send a register reading command */ TH02_IIC_WriteCmd(u8Reg); Wire.requestFrom(TH02_I2C_DEV_ID, 1); while(Wire.available()) { Temp = Wire.read(); } return Temp; } void TH02_dev::TH02_IIC_WriteReg(uint8_t u8Reg,uint8_t u8Data) { Wire.beginTransmission(TH02_I2C_DEV_ID); Wire.write(u8Reg); Wire.write(u8Data); Wire.endTransmission(); } uint16_t TH02_dev::TH02_IIC_ReadData(void) { /* Port to arduino */ uint16_t Temp = TH02_IIC_ReadData2byte(); return Temp; } uint16_t TH02_dev::TH02_IIC_ReadData2byte() { uint16_t TempData = 0; uint16_t tmpArray[3]={0}; int cnt = 0; TH02_IIC_WriteCmd(REG_DATA_H); Wire.requestFrom(TH02_I2C_DEV_ID, 3); while(Wire.available()) { tmpArray[cnt] = (uint16_t)Wire.read(); cnt++; } /* MSB */ TempData = (tmpArray[1]<<8)|(tmpArray[2]); return TempData; } <commit_msg>Update Grove-Temper_Humidity_TH02.cpp<commit_after>/* * TH02_dev.cpp * Driver for DIGITAL I2C HUMIDITY AND TEMPERATURE SENSOR * * Copyright (c) 2014 seeed technology inc. * Website : www.seeed.cc * Author : Oliver Wang * Create Time: April 2014 * Change Log : * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /****************************************************************************/ /*** Include files ***/ /****************************************************************************/ #include "Grove-Temper_Humidity_TH02.h" /* Use Serial IIC */ #ifdef SERIAL_IIC #endif TH02_dev TH02; /****************************************************************************/ /*** Local Variable ***/ /****************************************************************************/ /****************************************************************************/ /*** Class member Functions ***/ /****************************************************************************/ void TH02_dev::begin(void) { /* Start IIC */ Wire.begin(); /* TH02 don't need to software reset */ } float TH02_dev::ReadTemperature(void) { /* Start a new temperature conversion */ TH02_IIC_WriteReg(REG_CONFIG, CMD_MEASURE_TEMP); //delay(100); /* Wait until conversion is done */ while(!isAvailable()); uint16_t value = TH02_IIC_ReadData(); value = value >> 2; /* Formula: Temperature(C) = (Value/32) - 50 */ float temper = (value/32.0)-50.0; return temper; } float TH02_dev::ReadHumidity(void) { /* Start a new humility conversion */ TH02_IIC_WriteReg(REG_CONFIG, CMD_MEASURE_HUMI); /* Wait until conversion is done */ //delay(100); while(!isAvailable()); uint16_t value = TH02_IIC_ReadData(); value = value >> 4; /* Formula: Humidity(%) = (Value/16) - 24 */ float humility = (value/16.0)-24.0; return humility; } /****************************************************************************/ /*** Local Functions ***/ /****************************************************************************/ uint8_t TH02_dev::isAvailable() { uint8_t status = TH02_IIC_ReadReg(REG_STATUS); if(status & STATUS_RDY_MASK) { return 0; //ready } else { return 1; //not ready yet } } void TH02_dev::TH02_IIC_WriteCmd(uint8_t u8Cmd) { /* Port to arduino */ Wire.beginTransmission(TH02_I2C_DEV_ID); Wire.write(u8Cmd); Wire.endTransmission(); } uint8_t TH02_dev::TH02_IIC_ReadReg(uint8_t u8Reg) { /* Port to arduino */ uint8_t Temp = 0; /* Send a register reading command */ TH02_IIC_WriteCmd(u8Reg); Wire.requestFrom(TH02_I2C_DEV_ID, 1); while(Wire.available()) { Temp = Wire.read(); } return Temp; } void TH02_dev::TH02_IIC_WriteReg(uint8_t u8Reg,uint8_t u8Data) { Wire.beginTransmission(TH02_I2C_DEV_ID); Wire.write(u8Reg); Wire.write(u8Data); Wire.endTransmission(); } uint16_t TH02_dev::TH02_IIC_ReadData(void) { /* Port to arduino */ uint16_t Temp = TH02_IIC_ReadData2byte(); return Temp; } uint16_t TH02_dev::TH02_IIC_ReadData2byte() { uint16_t TempData = 0; uint16_t tmpArray[3]={0}; int cnt = 0; TH02_IIC_WriteCmd(REG_DATA_H); Wire.requestFrom(TH02_I2C_DEV_ID, 3); while(Wire.available()) { tmpArray[cnt] = (uint16_t)Wire.read(); cnt++; } /* MSB */ TempData = (tmpArray[1]<<8)|(tmpArray[2]); return TempData; } <|endoftext|>
<commit_before>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2018 by Kaushik Ghose. Some rights reserved, see LICENSE Renders a text label */ #include "textlabel.hpp" namespace sim { TextBase::TextBase(Font& font, Text::Alignment ta) { _text.reset(new Text::Renderer2D(*(font._font), font._cache, 1.0f, ta)); // TODO: Figure out how to dynamically allocate _text->reserve( 100, GL::BufferUsage::DynamicDraw, GL::BufferUsage::StaticDraw); _shader.bindVectorTexture(font._cache.texture()); _color = { 1, 1, 1 }; _size = 100; } TextBase& TextBase::set_text(std::string str) { // TODO: Figure out how to dynamically allocate if (str.size() > 100) str.resize(100); _text->render(str); return *this; } TextBase& TextBase::set_size(float s) { _size = s; return *this; } TextBase& TextBase::set_color(Color3 col) { _color = col; return *this; } Label2D::Label2D(Font& font, Text::Alignment ta) : TextBase(font, ta) { } Label2D& Label2D::set_anchor(Anchor a) { anchor = a; return *this; } Label2D& Label2D::set_pos(const Vector2& p) { _pos = p; return *this; } void Label2D::draw(const Camera& camera) { Vector2d normalized_pos; const View& view = camera.get_view(); switch (anchor) { case BOTTOM_LEFT: normalized_pos = { 2 * _pos.x() / view.width - 1.0, 2 * _pos.y() / view.height - 1.0 }; break; case BOTTOM_RIGHT: normalized_pos = { 1.0 - 2 * _pos.x() / view.width, 2 * _pos.y() / view.height - 1.0 }; break; case TOP_LEFT: normalized_pos = { 2 * _pos.x() / view.width - 1.0, 1.0 - 2 * _pos.y() / view.height }; break; case TOP_RIGHT: normalized_pos = { 1.0 - 2 * _pos.x() / view.width, 1.0 - 2 * _pos.y() / view.height }; break; default: break; } _shader .setTransformationProjectionMatrix( Matrix3::translation((Vector2)normalized_pos) * Matrix3::scaling({ _size / view.width, _size / view.height })) .setColor(_color); _text->mesh().draw(_shader); } Billboard::Billboard(Font& font, Text::Alignment ta) : TextBase(font, ta) { } Billboard& Billboard::set_pos(const Vector3& p) { _pos = p; return *this; } void Billboard::draw(const Camera& camera) { _shader.setTransformationProjectionMatrix(camera.get_billboard_matrix()) .setColor(_color); _text->mesh().draw(_shader); } }<commit_msg>Disable Billboard text until it's needed<commit_after>/* This file is part of Groho, a simulator for inter-planetary travel and warfare. Copyright (c) 2018 by Kaushik Ghose. Some rights reserved, see LICENSE Renders a text label */ #include "textlabel.hpp" namespace sim { TextBase::TextBase(Font& font, Text::Alignment ta) { _text.reset(new Text::Renderer2D(*(font._font), font._cache, 1.0f, ta)); // TODO: Figure out how to dynamically allocate _text->reserve( 100, GL::BufferUsage::DynamicDraw, GL::BufferUsage::StaticDraw); _shader.bindVectorTexture(font._cache.texture()); _color = { 1, 1, 1 }; _size = 100; } TextBase& TextBase::set_text(std::string str) { // TODO: Figure out how to dynamically allocate if (str.size() > 100) str.resize(100); _text->render(str); return *this; } TextBase& TextBase::set_size(float s) { _size = s; return *this; } TextBase& TextBase::set_color(Color3 col) { _color = col; return *this; } Label2D::Label2D(Font& font, Text::Alignment ta) : TextBase(font, ta) { } Label2D& Label2D::set_anchor(Anchor a) { anchor = a; return *this; } Label2D& Label2D::set_pos(const Vector2& p) { _pos = p; return *this; } void Label2D::draw(const Camera& camera) { Vector2d normalized_pos; const View& view = camera.get_view(); switch (anchor) { case BOTTOM_LEFT: normalized_pos = { 2 * _pos.x() / view.width - 1.0, 2 * _pos.y() / view.height - 1.0 }; break; case BOTTOM_RIGHT: normalized_pos = { 1.0 - 2 * _pos.x() / view.width, 2 * _pos.y() / view.height - 1.0 }; break; case TOP_LEFT: normalized_pos = { 2 * _pos.x() / view.width - 1.0, 1.0 - 2 * _pos.y() / view.height }; break; case TOP_RIGHT: normalized_pos = { 1.0 - 2 * _pos.x() / view.width, 1.0 - 2 * _pos.y() / view.height }; break; default: break; } _shader .setTransformationProjectionMatrix( Matrix3::translation((Vector2)normalized_pos) * Matrix3::scaling({ _size / view.width, _size / view.height })) .setColor(_color); _text->mesh().draw(_shader); } Billboard::Billboard(Font& font, Text::Alignment ta) : TextBase(font, ta) { } Billboard& Billboard::set_pos(const Vector3& p) { _pos = p; return *this; } void Billboard::draw(const Camera& camera) { // _shader.setTransformationProjectionMatrix(camera.get_billboard_matrix()) // .setColor(_color); // _text->mesh().draw(_shader); } }<|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "proto_converter.h" #include <vespa/searchlib/common/mapnames.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/vespalib/data/slime/binary_format.h> #include <vespa/vespalib/data/smart_buffer.h> #include <vespa/vespalib/util/size_literals.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.engine.proto_converter"); namespace search::engine { namespace { template <typename T> vespalib::string make_sort_spec(const T &sorting) { vespalib::string spec; for (const auto &field_spec: sorting) { if (!spec.empty()) { spec.push_back(' '); } if (field_spec.ascending()) { spec.push_back('+'); } else { spec.push_back('-'); } spec.append(field_spec.field()); } return spec; } template <typename T> void add_single_props(fef::Properties &dst, const T &src) { for (const auto &entry: src) { dst.add(entry.name(), entry.value()); } } template <typename T> void add_multi_props(fef::Properties &dst, const T &src) { for (const auto &entry: src) { for (int i = 0; i < entry.values_size(); ++i) { dst.add(entry.name(), entry.values(i)); } } } } //----------------------------------------------------------------------------- void ProtoConverter::search_request_from_proto(const ProtoSearchRequest &proto, SearchRequest &request) { request.offset = proto.offset(); request.maxhits = proto.hits(); request.setTimeout(1ms * proto.timeout()); request.setTraceLevel(proto.trace_level()); request.sortSpec = make_sort_spec(proto.sorting()); request.sessionId.assign(proto.session_key().begin(), proto.session_key().end()); request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type()); if (proto.cache_grouping()) { request.propertiesMap.lookupCreate(MapNames::CACHES).add("grouping", "true"); } if (proto.cache_query()) { request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true"); } request.ranking = proto.rank_profile(); if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) { auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE); add_multi_props(feature_overrides, proto.feature_overrides()); add_single_props(feature_overrides, proto.tensor_feature_overrides()); } if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) { auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK); add_multi_props(rank_props, proto.rank_properties()); add_single_props(rank_props, proto.tensor_rank_properties()); } request.groupSpec.assign(proto.grouping_blob().begin(), proto.grouping_blob().end()); request.location = proto.geo_location(); request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end()); } void ProtoConverter::search_reply_to_proto(const SearchReply &reply, ProtoSearchReply &proto) { proto.set_total_hit_count(reply.totalHitCount); proto.set_coverage_docs(reply.coverage.getCovered()); proto.set_active_docs(reply.coverage.getActive()); proto.set_soon_active_docs(reply.coverage.getSoonActive()); proto.set_degraded_by_match_phase(reply.coverage.wasDegradedByMatchPhase()); proto.set_degraded_by_soft_timeout(reply.coverage.wasDegradedByTimeout()); bool has_sort_data = (reply.sortIndex.size() > 0); assert(!has_sort_data || (reply.sortIndex.size() == (reply.hits.size() + 1))); if (reply.request) { uint32_t asked_offset = reply.request->offset; uint32_t asked_hits = reply.request->maxhits; size_t got_hits = reply.hits.size(); if (got_hits < asked_hits && asked_offset + got_hits < reply.totalHitCount) { LOG(warning, "asked for %u hits [at offset %u] but only returning %zu hits from %" PRIu64 " available", asked_hits, asked_offset, got_hits, reply.totalHitCount); } } size_t num_match_features = reply.match_features.names.size(); using FeatureValuesIterator = std::vector<search::FeatureValues::Value>::const_iterator; FeatureValuesIterator mfv_iter; bool has_match_features = (num_match_features > 0 && reply.hits.size() > 0); if (has_match_features) { size_t num_match_feature_values = reply.match_features.values.size(); assert(num_match_feature_values == reply.hits.size() * num_match_features); for (const auto & name : reply.match_features.names) { *proto.add_match_feature_names() = name; } mfv_iter = reply.match_features.values.begin(); } for (size_t i = 0; i < reply.hits.size(); ++i) { auto *hit = proto.add_hits(); hit->set_global_id(reply.hits[i].gid.get(), document::GlobalId::LENGTH); hit->set_relevance(reply.hits[i].metric); if (has_sort_data) { size_t sort_data_offset = reply.sortIndex[i]; size_t sort_data_size = (reply.sortIndex[i + 1] - reply.sortIndex[i]); assert((sort_data_offset + sort_data_size) <= reply.sortData.size()); hit->set_sort_data(&reply.sortData[sort_data_offset], sort_data_size); } if (has_match_features) { for (size_t j = 0; j < num_match_features; ++j) { auto * obj = hit->add_match_features(); const auto & feature_value = *mfv_iter++; if (feature_value.is_data()) { auto mem = feature_value.as_data(); obj->set_tensor(mem.data, mem.size); } else if (feature_value.is_double()) { obj->set_number(feature_value.as_double()); } } } } if (has_match_features) { assert(mfv_iter == reply.match_features.values.end()); } proto.set_grouping_blob(&reply.groupResult[0], reply.groupResult.size()); const auto &slime_trace = reply.propertiesMap.trace().lookup("slime"); proto.set_slime_trace(slime_trace.get().data(), slime_trace.get().size()); if (reply.my_issues) { reply.my_issues->for_each_message([&](const vespalib::string &err_msg) { auto *err_obj = proto.add_errors(); err_obj->set_message(err_msg); }); } } //----------------------------------------------------------------------------- void ProtoConverter::docsum_request_from_proto(const ProtoDocsumRequest &proto, DocsumRequest &request) { request.setTimeout(1ms * proto.timeout()); request.sessionId.assign(proto.session_key().begin(), proto.session_key().end()); request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type()); request.resultClassName = proto.summary_class(); if (proto.cache_query()) { request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true"); } request.dumpFeatures = proto.dump_features(); request.ranking = proto.rank_profile(); if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) { auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE); add_multi_props(feature_overrides, proto.feature_overrides()); add_single_props(feature_overrides, proto.tensor_feature_overrides()); } if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) { auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK); add_multi_props(rank_props, proto.rank_properties()); add_single_props(rank_props, proto.tensor_rank_properties()); } if(proto.highlight_terms_size() > 0) { auto &highlight_terms = request.propertiesMap.lookupCreate(MapNames::HIGHLIGHTTERMS); add_multi_props(highlight_terms, proto.highlight_terms()); } request.location = proto.geo_location(); request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end()); request.hits.resize(proto.global_ids_size()); for (int i = 0; i < proto.global_ids_size(); ++i) { const auto &gid = proto.global_ids(i); if (gid.size() == document::GlobalId::LENGTH) { request.hits[i].gid = document::GlobalId(gid.data()); } } } void ProtoConverter::docsum_reply_to_proto(const DocsumReply &reply, ProtoDocsumReply &proto) { if (reply.hasResult()) { vespalib::SmartBuffer buf(4_Ki); vespalib::slime::BinaryFormat::encode(reply.slime(), buf); proto.set_slime_summaries(buf.obtain().data, buf.obtain().size); } if (reply.hasIssues()) { reply.issues().for_each_message([&](const vespalib::string &err_msg) { auto *err_obj = proto.add_errors(); err_obj->set_message(err_msg); }); } } //----------------------------------------------------------------------------- void ProtoConverter::monitor_request_from_proto(const ProtoMonitorRequest &, MonitorRequest &) { } void ProtoConverter::monitor_reply_to_proto(const MonitorReply &reply, ProtoMonitorReply &proto) { proto.set_online(reply.timestamp != 0); proto.set_active_docs(reply.activeDocs); proto.set_distribution_key(reply.distribution_key); proto.set_is_blocking_writes(reply.is_blocking_writes); } //----------------------------------------------------------------------------- } <commit_msg>simplify<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "proto_converter.h" #include <vespa/searchlib/common/mapnames.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/vespalib/data/slime/binary_format.h> #include <vespa/vespalib/data/smart_buffer.h> #include <vespa/vespalib/util/size_literals.h> #include <vespa/log/log.h> LOG_SETUP(".searchlib.engine.proto_converter"); namespace search::engine { namespace { template <typename T> vespalib::string make_sort_spec(const T &sorting) { vespalib::string spec; for (const auto &field_spec: sorting) { if (!spec.empty()) { spec.push_back(' '); } if (field_spec.ascending()) { spec.push_back('+'); } else { spec.push_back('-'); } spec.append(field_spec.field()); } return spec; } template <typename T> void add_single_props(fef::Properties &dst, const T &src) { for (const auto &entry: src) { dst.add(entry.name(), entry.value()); } } template <typename T> void add_multi_props(fef::Properties &dst, const T &src) { for (const auto &entry: src) { for (int i = 0; i < entry.values_size(); ++i) { dst.add(entry.name(), entry.values(i)); } } } } //----------------------------------------------------------------------------- void ProtoConverter::search_request_from_proto(const ProtoSearchRequest &proto, SearchRequest &request) { request.offset = proto.offset(); request.maxhits = proto.hits(); request.setTimeout(1ms * proto.timeout()); request.setTraceLevel(proto.trace_level()); request.sortSpec = make_sort_spec(proto.sorting()); request.sessionId.assign(proto.session_key().begin(), proto.session_key().end()); request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type()); if (proto.cache_grouping()) { request.propertiesMap.lookupCreate(MapNames::CACHES).add("grouping", "true"); } if (proto.cache_query()) { request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true"); } request.ranking = proto.rank_profile(); if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) { auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE); add_multi_props(feature_overrides, proto.feature_overrides()); add_single_props(feature_overrides, proto.tensor_feature_overrides()); } if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) { auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK); add_multi_props(rank_props, proto.rank_properties()); add_single_props(rank_props, proto.tensor_rank_properties()); } request.groupSpec.assign(proto.grouping_blob().begin(), proto.grouping_blob().end()); request.location = proto.geo_location(); request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end()); } void ProtoConverter::search_reply_to_proto(const SearchReply &reply, ProtoSearchReply &proto) { proto.set_total_hit_count(reply.totalHitCount); proto.set_coverage_docs(reply.coverage.getCovered()); proto.set_active_docs(reply.coverage.getActive()); proto.set_soon_active_docs(reply.coverage.getSoonActive()); proto.set_degraded_by_match_phase(reply.coverage.wasDegradedByMatchPhase()); proto.set_degraded_by_soft_timeout(reply.coverage.wasDegradedByTimeout()); bool has_sort_data = (reply.sortIndex.size() > 0); assert(!has_sort_data || (reply.sortIndex.size() == (reply.hits.size() + 1))); if (reply.request) { uint32_t asked_offset = reply.request->offset; uint32_t asked_hits = reply.request->maxhits; size_t got_hits = reply.hits.size(); if (got_hits < asked_hits && asked_offset + got_hits < reply.totalHitCount) { LOG(warning, "asked for %u hits [at offset %u] but only returning %zu hits from %" PRIu64 " available", asked_hits, asked_offset, got_hits, reply.totalHitCount); } } for (size_t i = 0; i < reply.hits.size(); ++i) { auto *hit = proto.add_hits(); hit->set_global_id(reply.hits[i].gid.get(), document::GlobalId::LENGTH); hit->set_relevance(reply.hits[i].metric); if (has_sort_data) { size_t sort_data_offset = reply.sortIndex[i]; size_t sort_data_size = (reply.sortIndex[i + 1] - reply.sortIndex[i]); assert((sort_data_offset + sort_data_size) <= reply.sortData.size()); hit->set_sort_data(&reply.sortData[sort_data_offset], sort_data_size); } } if (reply.match_features.values.size() > 0) { size_t num_match_features = reply.match_features.names.size(); for (const auto & name : reply.match_features.names) { *proto.add_match_feature_names() = name; } auto mfv_iter = reply.match_features.values.begin(); for (size_t i = 0; i < reply.hits.size(); ++i) { auto *hit = proto.mutable_hits(i); for (size_t j = 0; j < num_match_features; ++j) { auto * obj = hit->add_match_features(); const auto & feature_value = *mfv_iter++; if (feature_value.is_data()) { auto mem = feature_value.as_data(); obj->set_tensor(mem.data, mem.size); } else if (feature_value.is_double()) { obj->set_number(feature_value.as_double()); } } } assert(mfv_iter == reply.match_features.values.end()); } proto.set_grouping_blob(&reply.groupResult[0], reply.groupResult.size()); const auto &slime_trace = reply.propertiesMap.trace().lookup("slime"); proto.set_slime_trace(slime_trace.get().data(), slime_trace.get().size()); if (reply.my_issues) { reply.my_issues->for_each_message([&](const vespalib::string &err_msg) { auto *err_obj = proto.add_errors(); err_obj->set_message(err_msg); }); } } //----------------------------------------------------------------------------- void ProtoConverter::docsum_request_from_proto(const ProtoDocsumRequest &proto, DocsumRequest &request) { request.setTimeout(1ms * proto.timeout()); request.sessionId.assign(proto.session_key().begin(), proto.session_key().end()); request.propertiesMap.lookupCreate(MapNames::MATCH).add("documentdb.searchdoctype", proto.document_type()); request.resultClassName = proto.summary_class(); if (proto.cache_query()) { request.propertiesMap.lookupCreate(MapNames::CACHES).add("query", "true"); } request.dumpFeatures = proto.dump_features(); request.ranking = proto.rank_profile(); if ((proto.feature_overrides_size() + proto.tensor_feature_overrides_size()) > 0) { auto &feature_overrides = request.propertiesMap.lookupCreate(MapNames::FEATURE); add_multi_props(feature_overrides, proto.feature_overrides()); add_single_props(feature_overrides, proto.tensor_feature_overrides()); } if ((proto.rank_properties_size() + proto.tensor_rank_properties_size()) > 0) { auto &rank_props = request.propertiesMap.lookupCreate(MapNames::RANK); add_multi_props(rank_props, proto.rank_properties()); add_single_props(rank_props, proto.tensor_rank_properties()); } if(proto.highlight_terms_size() > 0) { auto &highlight_terms = request.propertiesMap.lookupCreate(MapNames::HIGHLIGHTTERMS); add_multi_props(highlight_terms, proto.highlight_terms()); } request.location = proto.geo_location(); request.stackDump.assign(proto.query_tree_blob().begin(), proto.query_tree_blob().end()); request.hits.resize(proto.global_ids_size()); for (int i = 0; i < proto.global_ids_size(); ++i) { const auto &gid = proto.global_ids(i); if (gid.size() == document::GlobalId::LENGTH) { request.hits[i].gid = document::GlobalId(gid.data()); } } } void ProtoConverter::docsum_reply_to_proto(const DocsumReply &reply, ProtoDocsumReply &proto) { if (reply.hasResult()) { vespalib::SmartBuffer buf(4_Ki); vespalib::slime::BinaryFormat::encode(reply.slime(), buf); proto.set_slime_summaries(buf.obtain().data, buf.obtain().size); } if (reply.hasIssues()) { reply.issues().for_each_message([&](const vespalib::string &err_msg) { auto *err_obj = proto.add_errors(); err_obj->set_message(err_msg); }); } } //----------------------------------------------------------------------------- void ProtoConverter::monitor_request_from_proto(const ProtoMonitorRequest &, MonitorRequest &) { } void ProtoConverter::monitor_reply_to_proto(const MonitorReply &reply, ProtoMonitorReply &proto) { proto.set_online(reply.timestamp != 0); proto.set_active_docs(reply.activeDocs); proto.set_distribution_key(reply.distribution_key); proto.set_is_blocking_writes(reply.is_blocking_writes); } //----------------------------------------------------------------------------- } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertysetbase.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-07-19 16:44:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PROPERTYSETBASE_HXX #define _PROPERTYSETBASE_HXX // include for parent class #include <cppuhelper/weak.hxx> #include <com/sun/star/lang/XTypeProvider.hpp> #include <comphelper/propstate.hxx> #include <comphelper/propertysetinfo.hxx> #include <comphelper/proparrhlp.hxx> #include <rtl/ref.hxx> // include for inlined helper function below #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/beans/PropertyAttribute.hpp> #include <map> // forward declarations for method arguments namespace com { namespace sun { namespace star { namespace uno { class Any; class Type; class RuntimeException; template<class T> class Sequence; } } } } /** base class which encapsulates accessing (reading/writing) concrete property values */ class PropertyAccessorBase : public ::rtl::IReference { private: oslInterlockedCount m_refCount; protected: PropertyAccessorBase() : m_refCount( 0 ) { } public: virtual oslInterlockedCount SAL_CALL acquire(); virtual oslInterlockedCount SAL_CALL release(); virtual bool approveValue( const com::sun::star::uno::Any& rValue ) const = 0; virtual void setValue( const com::sun::star::uno::Any& rValue ) = 0; virtual void getValue( com::sun::star::uno::Any& rValue ) const = 0; virtual bool isWriteable() const = 0; }; /** helper class for implementing property accessors through public member functions */ template< typename CLASS, typename VALUE, class WRITER, class READER > class GenericPropertyAccessor : public PropertyAccessorBase { public: typedef WRITER Writer; typedef READER Reader; private: CLASS* m_pInstance; Writer m_pWriter; Reader m_pReader; public: GenericPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :m_pInstance( pInstance ) ,m_pWriter( pWriter ) ,m_pReader( pReader ) { } virtual bool approveValue( const com::sun::star::uno::Any& rValue ) const { VALUE aVal; return ( rValue >>= aVal ); } virtual void setValue( const com::sun::star::uno::Any& rValue ) { VALUE aTypedVal = VALUE(); OSL_VERIFY( rValue >>= aTypedVal ); (m_pInstance->*m_pWriter)( aTypedVal ); } virtual void getValue( com::sun::star::uno::Any& rValue ) const { rValue = com::sun::star::uno::makeAny( (m_pInstance->*m_pReader)() ); } virtual bool isWriteable() const { return m_pWriter != NULL; } }; /** helper class for implementing property accessors via non-UNO methods */ template< typename CLASS, typename VALUE > class DirectPropertyAccessor :public GenericPropertyAccessor < CLASS , VALUE , void (CLASS::*)( const VALUE& ) , VALUE (CLASS::*)() const > { protected: typedef void (CLASS::*Writer)( const VALUE& ); typedef VALUE (CLASS::*Reader)() const; public: DirectPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :GenericPropertyAccessor< CLASS, VALUE, Writer, Reader >( pInstance, pWriter, pReader ) { } }; /** helper class for implementing non-UNO accessors to a boolean property */ template< typename CLASS, typename DUMMY > class BooleanPropertyAccessor :public GenericPropertyAccessor < CLASS , bool , void (CLASS::*)( bool ) , bool (CLASS::*)() const > { protected: typedef void (CLASS::*Writer)( bool ); typedef bool (CLASS::*Reader)() const; public: BooleanPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :GenericPropertyAccessor< CLASS, bool, Writer, Reader >( pInstance, pWriter, pReader ) { } }; /** helper class for implementing property accessors via UNO methods */ template< typename CLASS, typename VALUE > class APIPropertyAccessor :public GenericPropertyAccessor < CLASS , VALUE , void (SAL_CALL CLASS::*)( const VALUE& ) , VALUE (SAL_CALL CLASS::*)() > { protected: typedef void (SAL_CALL CLASS::*Writer)( const VALUE& ); typedef VALUE (SAL_CALL CLASS::*Reader)(); public: APIPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :GenericPropertyAccessor< CLASS, VALUE, Writer, Reader >( pInstance, pWriter, pReader ) { } }; /** bridges two XPropertySet helper implementations The <type scope="comphelper">OStatefulPropertySet</type> (basically, the <type scope="cppu">OPropertySetHelper</type>) implements a comprehensive framework for property sets, including property change notifications. However, it lacks some easy possibilities to declare the supported properties. Other helper structs and classes allow for this, but are lacking needed features such as property change notifications. The <type>PropertySetBase</type> bridges various implementations, so you have the best of both worlds. */ class PropertySetBase : public ::comphelper::OStatefulPropertySet { private: typedef com::sun::star::uno::Any Any_t; typedef ::std::map< const sal_Int32, ::rtl::Reference< PropertyAccessorBase > > PropertyAccessors; typedef ::std::vector< ::com::sun::star::beans::Property > PropertyArray; typedef ::std::map< const sal_Int32, Any_t > PropertyValueCache; PropertyArray m_aProperties; cppu::IPropertyArrayHelper* m_pProperties; PropertyAccessors m_aAccessors; PropertyValueCache m_aCache; protected: PropertySetBase(); virtual ~PropertySetBase(); /** registers a new property to be supported by this instance @param rProperty the descriptor for the to-be-supported property @param rAccessor an instance which is able to provide read and possibly write access to the property. @precond Must not be called after any of the property set related UNO interfaces has been used. Usually, you will do a number of <member>registerProperty</member> calls in the constructor of your class. */ void registerProperty( const com::sun::star::beans::Property& rProperty, const ::rtl::Reference< PropertyAccessorBase >& rAccessor ); /** notifies a change in a given property value, if necessary The necessity of the notification is determined by a cached value for the given property. Caching happens after notification. That is, when you call <member>notifyAndCachePropertyValue</member> for the first time, a value for the given property is default constructed, and considered to be the "old value". If this value differs from the current value, then this change is notified to all interested listeners. Finally, the current value is remembered. Subsequent calls to <member>notifyAndCachePropertyValue</member> use the remembered value as "old value", and from then on behave as the first call. @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @precond our ref count must not be 0. The reason is that during this method's execution, the instance might be acquired and released, which would immediately destroy the instance if it has a ref count of 0. @seealso initializePropertyValueCache */ void notifyAndCachePropertyValue( sal_Int32 nHandle ); /** initializes the property value cache for the given property, with its current value Usually used to initialize the cache with values which are different from default constructed values. Say you have a boolean property whose initial state is <TRUE/>. Say you call <member>notifyAndCachePropertyValue</member> the first time: it will default construct the "old value" for this property as <FALSE/>, and thus <b>not</b> do any notifications if the "current value" is also <FALSE/> - which might be wrong, since the guessing of the "old value" differed from the real initial value which was <TRUE/>. Too confusing? Okay, than just call this method for every property you have. @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @param rValue the value to cache @seealso notifyAndCachePropertyValue */ void initializePropertyValueCache( sal_Int32 nHandle ); /// OPropertysetHelper methods virtual sal_Bool SAL_CALL convertFastPropertyValue( Any_t& rConvertedValue, Any_t& rOldValue, sal_Int32 nHandle, const Any_t& rValue ) throw (::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any_t& rValue ) throw (::com::sun::star::uno::Exception); virtual void SAL_CALL getFastPropertyValue( Any_t& rValue, sal_Int32 nHandle ) const; virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); public: /// helper struct for granting selective access to some notification-related methods struct NotifierAccess { friend struct PropertyChangeNotifier; private: NotifierAccess() { } }; /** retrieves the current property value for the given handle @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @see registerProperty */ inline void getCurrentPropertyValueByHandle( sal_Int32 nHandle, Any_t& /* [out] */ rValue, const NotifierAccess& ) const { getFastPropertyValue( rValue, nHandle ); } /** notifies a change in a given property to all interested listeners */ inline void notifyPropertyChange( sal_Int32 nHandle, const Any_t& rOldValue, const Any_t& rNewValue, const NotifierAccess& ) const { const_cast< PropertySetBase* >( this )->firePropertyChange( nHandle, rNewValue, rOldValue ); } using ::comphelper::OStatefulPropertySet::getFastPropertyValue; private: /** locates a property given by handle @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @see registerProperty */ PropertyAccessorBase& locatePropertyHandler( sal_Int32 nHandle ) const; }; /** a helper class for notifying property changes in a <type>PropertySetBase</type> instance. You can create an instance of this class on the stack of a method which is to programmatically change the value of a property. In its constructor, the instance will acquire the current property value, and in its destructor, it will notify the change of this property's value (if necessary). You do not need this class if you are modifying property values by using the X(Fast|Multi)PropertSet methods, since those already care for property notifications. You only need it if you're changing the internal representation of your property directly. Also note that usually, notifications in the UNO world should be done without a locked mutex. So if you use this class in conjunction with a <type>MutexGuard</type>, ensure that you <b>first</b> instantiate the <type>PropertyChangeNotifier</type>, and <b>then</b> the <type>MutexGuard</type>, so your mutex is released before the notification happens. */ struct PropertyChangeNotifier { private: const PropertySetBase& m_rPropertySet; sal_Int32 m_nHandle; com::sun::star::uno::Any m_aOldValue; public: /** constructs a PropertyChangeNotifier @param rPropertySet the property set implementation whose property is going to be changed. Note that this property set implementation must live at least as long as the PropertyChangeNotifier instance does. @param nHandle the handle of the property which is going to be changed. Must be a valid property handle for the given <arg>rPropertySet</arg> */ inline PropertyChangeNotifier( const PropertySetBase& rPropertySet, sal_Int32 nHandle ) :m_rPropertySet( rPropertySet ) ,m_nHandle( nHandle ) { m_rPropertySet.getCurrentPropertyValueByHandle( m_nHandle, m_aOldValue, PropertySetBase::NotifierAccess() ); } inline ~PropertyChangeNotifier() { com::sun::star::uno::Any aNewValue; m_rPropertySet.getCurrentPropertyValueByHandle( m_nHandle, aNewValue, PropertySetBase::NotifierAccess() ); if ( aNewValue != m_aOldValue ) { m_rPropertySet.notifyPropertyChange( m_nHandle, m_aOldValue, aNewValue, PropertySetBase::NotifierAccess() ); } } }; #define PROPERTY_FLAGS( NAME, TYPE, FLAG ) com::sun::star::beans::Property( \ ::rtl::OUString( #NAME, sizeof( #NAME ) - 1, RTL_TEXTENCODING_ASCII_US ), \ HANDLE_##NAME, getCppuType( static_cast< TYPE* >( NULL ) ), FLAG ) #define PROPERTY( NAME, TYPE ) PROPERTY_FLAGS( NAME, TYPE, com::sun::star::beans::PropertyAttribute::BOUND ) #define PROPERTY_RO( NAME, TYPE ) PROPERTY_FLAGS( NAME, TYPE, com::sun::star::beans::PropertyAttribute::BOUND | com::sun::star::beans::PropertyAttribute::READONLY ) #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.150); FILE MERGED 2008/03/31 13:11:45 rt 1.6.150.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertysetbase.hxx,v $ * $Revision: 1.7 $ * * 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. * ************************************************************************/ #ifndef _PROPERTYSETBASE_HXX #define _PROPERTYSETBASE_HXX // include for parent class #include <cppuhelper/weak.hxx> #include <com/sun/star/lang/XTypeProvider.hpp> #include <comphelper/propstate.hxx> #include <comphelper/propertysetinfo.hxx> #include <comphelper/proparrhlp.hxx> #include <rtl/ref.hxx> // include for inlined helper function below #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/beans/PropertyAttribute.hpp> #include <map> // forward declarations for method arguments namespace com { namespace sun { namespace star { namespace uno { class Any; class Type; class RuntimeException; template<class T> class Sequence; } } } } /** base class which encapsulates accessing (reading/writing) concrete property values */ class PropertyAccessorBase : public ::rtl::IReference { private: oslInterlockedCount m_refCount; protected: PropertyAccessorBase() : m_refCount( 0 ) { } public: virtual oslInterlockedCount SAL_CALL acquire(); virtual oslInterlockedCount SAL_CALL release(); virtual bool approveValue( const com::sun::star::uno::Any& rValue ) const = 0; virtual void setValue( const com::sun::star::uno::Any& rValue ) = 0; virtual void getValue( com::sun::star::uno::Any& rValue ) const = 0; virtual bool isWriteable() const = 0; }; /** helper class for implementing property accessors through public member functions */ template< typename CLASS, typename VALUE, class WRITER, class READER > class GenericPropertyAccessor : public PropertyAccessorBase { public: typedef WRITER Writer; typedef READER Reader; private: CLASS* m_pInstance; Writer m_pWriter; Reader m_pReader; public: GenericPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :m_pInstance( pInstance ) ,m_pWriter( pWriter ) ,m_pReader( pReader ) { } virtual bool approveValue( const com::sun::star::uno::Any& rValue ) const { VALUE aVal; return ( rValue >>= aVal ); } virtual void setValue( const com::sun::star::uno::Any& rValue ) { VALUE aTypedVal = VALUE(); OSL_VERIFY( rValue >>= aTypedVal ); (m_pInstance->*m_pWriter)( aTypedVal ); } virtual void getValue( com::sun::star::uno::Any& rValue ) const { rValue = com::sun::star::uno::makeAny( (m_pInstance->*m_pReader)() ); } virtual bool isWriteable() const { return m_pWriter != NULL; } }; /** helper class for implementing property accessors via non-UNO methods */ template< typename CLASS, typename VALUE > class DirectPropertyAccessor :public GenericPropertyAccessor < CLASS , VALUE , void (CLASS::*)( const VALUE& ) , VALUE (CLASS::*)() const > { protected: typedef void (CLASS::*Writer)( const VALUE& ); typedef VALUE (CLASS::*Reader)() const; public: DirectPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :GenericPropertyAccessor< CLASS, VALUE, Writer, Reader >( pInstance, pWriter, pReader ) { } }; /** helper class for implementing non-UNO accessors to a boolean property */ template< typename CLASS, typename DUMMY > class BooleanPropertyAccessor :public GenericPropertyAccessor < CLASS , bool , void (CLASS::*)( bool ) , bool (CLASS::*)() const > { protected: typedef void (CLASS::*Writer)( bool ); typedef bool (CLASS::*Reader)() const; public: BooleanPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :GenericPropertyAccessor< CLASS, bool, Writer, Reader >( pInstance, pWriter, pReader ) { } }; /** helper class for implementing property accessors via UNO methods */ template< typename CLASS, typename VALUE > class APIPropertyAccessor :public GenericPropertyAccessor < CLASS , VALUE , void (SAL_CALL CLASS::*)( const VALUE& ) , VALUE (SAL_CALL CLASS::*)() > { protected: typedef void (SAL_CALL CLASS::*Writer)( const VALUE& ); typedef VALUE (SAL_CALL CLASS::*Reader)(); public: APIPropertyAccessor( CLASS* pInstance, Writer pWriter, Reader pReader ) :GenericPropertyAccessor< CLASS, VALUE, Writer, Reader >( pInstance, pWriter, pReader ) { } }; /** bridges two XPropertySet helper implementations The <type scope="comphelper">OStatefulPropertySet</type> (basically, the <type scope="cppu">OPropertySetHelper</type>) implements a comprehensive framework for property sets, including property change notifications. However, it lacks some easy possibilities to declare the supported properties. Other helper structs and classes allow for this, but are lacking needed features such as property change notifications. The <type>PropertySetBase</type> bridges various implementations, so you have the best of both worlds. */ class PropertySetBase : public ::comphelper::OStatefulPropertySet { private: typedef com::sun::star::uno::Any Any_t; typedef ::std::map< const sal_Int32, ::rtl::Reference< PropertyAccessorBase > > PropertyAccessors; typedef ::std::vector< ::com::sun::star::beans::Property > PropertyArray; typedef ::std::map< const sal_Int32, Any_t > PropertyValueCache; PropertyArray m_aProperties; cppu::IPropertyArrayHelper* m_pProperties; PropertyAccessors m_aAccessors; PropertyValueCache m_aCache; protected: PropertySetBase(); virtual ~PropertySetBase(); /** registers a new property to be supported by this instance @param rProperty the descriptor for the to-be-supported property @param rAccessor an instance which is able to provide read and possibly write access to the property. @precond Must not be called after any of the property set related UNO interfaces has been used. Usually, you will do a number of <member>registerProperty</member> calls in the constructor of your class. */ void registerProperty( const com::sun::star::beans::Property& rProperty, const ::rtl::Reference< PropertyAccessorBase >& rAccessor ); /** notifies a change in a given property value, if necessary The necessity of the notification is determined by a cached value for the given property. Caching happens after notification. That is, when you call <member>notifyAndCachePropertyValue</member> for the first time, a value for the given property is default constructed, and considered to be the "old value". If this value differs from the current value, then this change is notified to all interested listeners. Finally, the current value is remembered. Subsequent calls to <member>notifyAndCachePropertyValue</member> use the remembered value as "old value", and from then on behave as the first call. @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @precond our ref count must not be 0. The reason is that during this method's execution, the instance might be acquired and released, which would immediately destroy the instance if it has a ref count of 0. @seealso initializePropertyValueCache */ void notifyAndCachePropertyValue( sal_Int32 nHandle ); /** initializes the property value cache for the given property, with its current value Usually used to initialize the cache with values which are different from default constructed values. Say you have a boolean property whose initial state is <TRUE/>. Say you call <member>notifyAndCachePropertyValue</member> the first time: it will default construct the "old value" for this property as <FALSE/>, and thus <b>not</b> do any notifications if the "current value" is also <FALSE/> - which might be wrong, since the guessing of the "old value" differed from the real initial value which was <TRUE/>. Too confusing? Okay, than just call this method for every property you have. @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @param rValue the value to cache @seealso notifyAndCachePropertyValue */ void initializePropertyValueCache( sal_Int32 nHandle ); /// OPropertysetHelper methods virtual sal_Bool SAL_CALL convertFastPropertyValue( Any_t& rConvertedValue, Any_t& rOldValue, sal_Int32 nHandle, const Any_t& rValue ) throw (::com::sun::star::lang::IllegalArgumentException); virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const Any_t& rValue ) throw (::com::sun::star::uno::Exception); virtual void SAL_CALL getFastPropertyValue( Any_t& rValue, sal_Int32 nHandle ) const; virtual cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException); public: /// helper struct for granting selective access to some notification-related methods struct NotifierAccess { friend struct PropertyChangeNotifier; private: NotifierAccess() { } }; /** retrieves the current property value for the given handle @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @see registerProperty */ inline void getCurrentPropertyValueByHandle( sal_Int32 nHandle, Any_t& /* [out] */ rValue, const NotifierAccess& ) const { getFastPropertyValue( rValue, nHandle ); } /** notifies a change in a given property to all interested listeners */ inline void notifyPropertyChange( sal_Int32 nHandle, const Any_t& rOldValue, const Any_t& rNewValue, const NotifierAccess& ) const { const_cast< PropertySetBase* >( this )->firePropertyChange( nHandle, rNewValue, rOldValue ); } using ::comphelper::OStatefulPropertySet::getFastPropertyValue; private: /** locates a property given by handle @param nHandle the handle of the property. Must denote a property supported by this instance, i.e. one previously registered via <member>registerProperty</member>. @see registerProperty */ PropertyAccessorBase& locatePropertyHandler( sal_Int32 nHandle ) const; }; /** a helper class for notifying property changes in a <type>PropertySetBase</type> instance. You can create an instance of this class on the stack of a method which is to programmatically change the value of a property. In its constructor, the instance will acquire the current property value, and in its destructor, it will notify the change of this property's value (if necessary). You do not need this class if you are modifying property values by using the X(Fast|Multi)PropertSet methods, since those already care for property notifications. You only need it if you're changing the internal representation of your property directly. Also note that usually, notifications in the UNO world should be done without a locked mutex. So if you use this class in conjunction with a <type>MutexGuard</type>, ensure that you <b>first</b> instantiate the <type>PropertyChangeNotifier</type>, and <b>then</b> the <type>MutexGuard</type>, so your mutex is released before the notification happens. */ struct PropertyChangeNotifier { private: const PropertySetBase& m_rPropertySet; sal_Int32 m_nHandle; com::sun::star::uno::Any m_aOldValue; public: /** constructs a PropertyChangeNotifier @param rPropertySet the property set implementation whose property is going to be changed. Note that this property set implementation must live at least as long as the PropertyChangeNotifier instance does. @param nHandle the handle of the property which is going to be changed. Must be a valid property handle for the given <arg>rPropertySet</arg> */ inline PropertyChangeNotifier( const PropertySetBase& rPropertySet, sal_Int32 nHandle ) :m_rPropertySet( rPropertySet ) ,m_nHandle( nHandle ) { m_rPropertySet.getCurrentPropertyValueByHandle( m_nHandle, m_aOldValue, PropertySetBase::NotifierAccess() ); } inline ~PropertyChangeNotifier() { com::sun::star::uno::Any aNewValue; m_rPropertySet.getCurrentPropertyValueByHandle( m_nHandle, aNewValue, PropertySetBase::NotifierAccess() ); if ( aNewValue != m_aOldValue ) { m_rPropertySet.notifyPropertyChange( m_nHandle, m_aOldValue, aNewValue, PropertySetBase::NotifierAccess() ); } } }; #define PROPERTY_FLAGS( NAME, TYPE, FLAG ) com::sun::star::beans::Property( \ ::rtl::OUString( #NAME, sizeof( #NAME ) - 1, RTL_TEXTENCODING_ASCII_US ), \ HANDLE_##NAME, getCppuType( static_cast< TYPE* >( NULL ) ), FLAG ) #define PROPERTY( NAME, TYPE ) PROPERTY_FLAGS( NAME, TYPE, com::sun::star::beans::PropertyAttribute::BOUND ) #define PROPERTY_RO( NAME, TYPE ) PROPERTY_FLAGS( NAME, TYPE, com::sun::star::beans::PropertyAttribute::BOUND | com::sun::star::beans::PropertyAttribute::READONLY ) #endif <|endoftext|>
<commit_before>#define VEXCL_SHOW_KERNELS #define BOOST_TEST_MODULE KernelGenerator #include <boost/test/unit_test.hpp> #include "context_setup.hpp" using namespace vex; template <class state_type> state_type sys_func(const state_type &x) { return sin(x); } template <class state_type, class SysFunction> void runge_kutta_2(SysFunction sys, state_type &x, double dt) { state_type k1 = dt * sys(x); state_type k2 = dt * sys(x + 0.5 * k1); x += k2; } BOOST_AUTO_TEST_CASE(kernel_generator) { typedef vex::generator::symbolic<double> sym_state; const size_t n = 1024; const double dt = 0.01; std::ostringstream body; vex::generator::set_recorder(body); sym_state sym_x(sym_state::VectorParameter); // Record expression sequence. runge_kutta_2(sys_func<sym_state>, sym_x, dt); // Build kernel. auto kernel = vex::generator::build_kernel( ctx, "rk2_stepper", body.str(), sym_x); std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) kernel(X); check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) runge_kutta_2(sys_func<double>, s, dt); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } /* An alternative variant, which does not use the generator facility. Intermediate subexpression are captured with help of 'auto' keyword, and are combined into larger expression. This is not as effective as generated kernel, because same input vector (here 'x') is passed as several different parameters. This specific example takes about twice as long to execute as the above variant. Nevertheless, this may be more convenient in some cases. */ BOOST_AUTO_TEST_CASE(lazy_evaluation) { const size_t n = 1024; const double dt = 0.01; auto rk2 = [](vex::vector<double> &x, double dt) { auto k1 = dt * sin(x); auto x1 = x + 0.5 * k1; auto k2 = dt * sin(x1); x += k2; }; std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) rk2(X, dt); check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) runge_kutta_2(sys_func<double>, s, dt); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Workaround for a bug in AMD OpenCL<commit_after>#define BOOST_TEST_MODULE KernelGenerator #include <boost/test/unit_test.hpp> #include "context_setup.hpp" using namespace vex; template <class state_type> state_type sys_func(const state_type &x) { return sin(x); } template <class state_type, class SysFunction> void runge_kutta_2(SysFunction sys, state_type &x, double dt) { state_type k1 = dt * sys(x); state_type k2 = dt * sys(x + 0.5 * k1); x += k2; } BOOST_AUTO_TEST_CASE(kernel_generator) { typedef vex::generator::symbolic<double> sym_state; const size_t n = 1024; const double dt = 0.01; std::ostringstream body; vex::generator::set_recorder(body); sym_state sym_x(sym_state::VectorParameter); // Record expression sequence. runge_kutta_2(sys_func<sym_state>, sym_x, dt); // Build kernel. auto kernel = vex::generator::build_kernel( ctx, "rk2_stepper", body.str(), sym_x); std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) kernel(X); check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) runge_kutta_2(sys_func<double>, s, dt); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } /* An alternative variant, which does not use the generator facility. Intermediate subexpression are captured with help of 'auto' keyword, and are combined into larger expression. This is not as effective as generated kernel, because same input vector (here 'x') is passed as several different parameters. This specific example takes about twice as long to execute as the above variant. Nevertheless, this may be more convenient in some cases. */ BOOST_AUTO_TEST_CASE(lazy_evaluation) { const size_t n = 1024; const double dt = 0.01; auto rk2 = [](vex::vector<double> &x, double dt) { auto k1 = dt * sin(x); auto x1 = x + 0.5 * k1; auto k2 = dt * sin(x1); x += k2; }; std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) { rk2(X, dt); // Temporary workaround for ati bug: // http://devgurus.amd.com/message/1295503#1295503 for(unsigned d = 0; d < ctx.size(); ++d) ctx.queue(d).finish(); } check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) runge_kutta_2(sys_func<double>, s, dt); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// // Created by Александр on 09.12.17. // #include <QIODevice> #include <QDataStream> #include "DiffieHellmanCmd.h" QByteArray* DiffieHellmanCmd::req(QByteArray* block) { QDataStream out(block, QIODevice::WriteOnly); out << "test"; return block; } bool DiffieHellmanCmd::res(QByteArray &array, QQueue<Command*> *queue) { return false; }<commit_msg>QDataStream issues, in this case server reads data successfull<commit_after>// // Created by Александр on 09.12.17. // #include <QIODevice> #include <QDataStream> #include "DiffieHellmanCmd.h" QByteArray* DiffieHellmanCmd::req(QByteArray* block) { // QDataStream out(block, QIODevice::WriteOnly); block->clear(); block->append("test"); // out << "tttt"; return block; } bool DiffieHellmanCmd::res(QByteArray &array, QQueue<Command*> *queue) { return false; }<|endoftext|>
<commit_before><commit_msg>skeleton for test, fill out...?<commit_after>/** * tests/jsonUtils.cpp * Generic JSON utility tests. */ #include "catch.hpp" #include "feJsonUtils.h" TEST_CASE("Export class correctly", "[feJsonUtils]") { }<|endoftext|>
<commit_before>/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxResamplerBase_hxx #define __elxResamplerBase_hxx #include "elxResamplerBase.h" #include "itkImageFileCastWriter.h" #include "elxTimer.h" namespace elastix { using namespace itk; /* * ******************* BeforeRegistrationBase ******************* */ template<class TElastix> void ResamplerBase<TElastix> ::BeforeRegistrationBase( void ) { /** Connect the components. */ this->SetComponents(); /** Set the size of the image to be produced by the resampler. */ /** Get a pointer to the fixedImage. * \todo make it a cast to the fixed image type */ typedef typename ElastixType::FixedImageType FixedImageType; FixedImageType * fixedImage = this->m_Elastix->GetFixedImage(); /** Set the region info to the same values as in the fixedImage. */ this->GetAsITKBaseType()->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); this->GetAsITKBaseType()->SetOutputStartIndex( fixedImage->GetLargestPossibleRegion().GetIndex() ); this->GetAsITKBaseType()->SetOutputOrigin( fixedImage->GetOrigin() ); this->GetAsITKBaseType()->SetOutputSpacing( fixedImage->GetSpacing() ); /** Set the DefaultPixelValue (for pixels in the resampled image * that come from outside the original (moving) image. */ double defaultPixelValueDouble = NumericTraits<double>::Zero; int defaultPixelValueInt = NumericTraits<int>::Zero; int retd = this->m_Configuration->ReadParameter( defaultPixelValueDouble, "DefaultPixelValue", 0, true ); int reti = this->m_Configuration->ReadParameter( defaultPixelValueInt, "DefaultPixelValue", 0, true ); /** Set the defaultPixelValue. int values overrule double values. */ if ( retd == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueDouble ) ); } if ( reti == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } if ( reti != 0 && retd != 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } } // end BeforeRegistrationBase /* * ******************* AfterEachResolutionBase ******************** */ template<class TElastix> void ResamplerBase<TElastix> ::AfterEachResolutionBase( void ) { /** Set the final transform parameters. */ this->GetElastix()->GetElxTransformBase()->SetFinalParameters(); /** What is the current resolution level? */ unsigned int level = this->m_Registration->GetAsITKBaseType()->GetCurrentLevel(); /** Decide whether or not to write the result image this resolution. */ bool writeResultImageThisResolution = false; this->m_Configuration->ReadParameter( writeResultImageThisResolution, "WriteResultImageAfterEachResolution", "", level, 0, true ); /** Writing result image. */ if ( writeResultImageThisResolution ) { /** Create a name for the final result. */ std::string resultImageFormat = "mhd"; this->m_Configuration->ReadParameter( resultImageFormat, "ResultImageFormat", 0, true); std::ostringstream makeFileName( "" ); makeFileName << this->m_Configuration->GetCommandLineArgument( "-out" ) << "result." << this->m_Configuration->GetElastixLevel() << ".R" << level << "." << resultImageFormat; /** Time the resampling. */ typedef tmr::Timer TimerType; TimerType::Pointer timer = TimerType::New(); timer->StartTimer(); /** Apply the final transform, and save the result. */ elxout << "Applying transform this resolution ..." << std::endl; try { this->WriteResultImage( makeFileName.str().c_str() ); } catch( itk::ExceptionObject & excp ) { xl::xout["error"] << "Exception caught: " << std::endl; xl::xout["error"] << excp << "Resuming elastix." << std::endl; } /** Print the elapsed time for the resampling. */ timer->StopTimer(); elxout << " Applying transform took " << static_cast<long>( timer->GetElapsedClockSec() ) << " s." << std::endl; } // end if } // end AfterEachResolutionBase() /* * ******************* AfterRegistrationBase ******************** */ template<class TElastix> void ResamplerBase<TElastix> ::AfterRegistrationBase(void) { /** Set the final transform parameters. */ this->GetElastix()->GetElxTransformBase()->SetFinalParameters(); /** Decide whether or not to write the result image. */ std::string writeResultImage = "true"; this->m_Configuration->ReadParameter( writeResultImage, "WriteResultImage", 0 ); /** Writing result image. */ if ( writeResultImage == "true" ) { /** Create a name for the final result. */ std::string resultImageFormat = "mhd"; this->m_Configuration->ReadParameter( resultImageFormat, "ResultImageFormat", 0); std::ostringstream makeFileName( "" ); makeFileName << this->m_Configuration->GetCommandLineArgument( "-out" ) << "result." << this->m_Configuration->GetElastixLevel() << "." << resultImageFormat; /** Time the resampling. */ typedef tmr::Timer TimerType; TimerType::Pointer timer = TimerType::New(); timer->StartTimer(); /** Apply the final transform, and save the result, * by calling WriteResultImage. */ elxout << "\nApplying final transform ..." << std::endl; try { this->WriteResultImage( makeFileName.str().c_str() ); } catch( itk::ExceptionObject & excp ) { xl::xout["error"] << "Exception caught: " << std::endl; xl::xout["error"] << excp << "Resuming elastix." << std::endl; } /** Print the elapsed time for the resampling. */ timer->StopTimer(); elxout << " Applying final transform took " << static_cast<long>( timer->GetElapsedClockSec() ) << " s." << std::endl; } else { /** Do not apply the final transform. */ elxout << std::endl << "Skipping applying final transform, no resulting output image generated." << std::endl; } // end if } // end AfterRegistrationBase() /* * *********************** SetComponents ************************ */ template <class TElastix> void ResamplerBase<TElastix> ::SetComponents(void) { /** Set the transform, the interpolator and the inputImage * (which is the moving image). */ this->GetAsITKBaseType()->SetTransform( dynamic_cast<TransformType *>( this->m_Elastix->GetElxTransformBase() ) ); this->GetAsITKBaseType()->SetInterpolator( dynamic_cast<InterpolatorType *>( this->m_Elastix->GetElxResampleInterpolatorBase() ) ); this->GetAsITKBaseType()->SetInput( dynamic_cast<InputImageType *>( this->m_Elastix->GetMovingImage() ) ); } // end SetComponents() /* * ******************* WriteResultImage ******************** */ template<class TElastix> void ResamplerBase<TElastix> ::WriteResultImage( const char * filename ) { /** Make sure the resampler is updated. */ this->GetAsITKBaseType()->Modified(); /** Add a progress observer to the resampler. */ ProgressCommandType::Pointer progressObserver = ProgressCommandType::New(); progressObserver->ConnectObserver( this->GetAsITKBaseType() ); progressObserver->SetStartString( " Progress: " ); progressObserver->SetEndString( "%" ); /** Read output pixeltype from parameter the file. Replace possible " " with "_". */ std::string resultImagePixelType = "short"; this->m_Configuration->ReadParameter( resultImagePixelType, "ResultImagePixelType", 0, true ); std::basic_string<char>::size_type pos = resultImagePixelType.find( " " ); const std::basic_string<char>::size_type npos = std::basic_string<char>::npos; if ( pos != npos ) resultImagePixelType.replace( pos, 1, "_" ); /** Read from the parameter file if compression is desired. */ bool doCompression = false; this->m_Configuration->ReadParameter( doCompression, "CompressResultImage", 0, true ); /** Typedef's for writing the output image. */ typedef ImageFileCastWriter< OutputImageType > WriterType; typedef typename WriterType::Pointer WriterPointer; /** Create writer. */ WriterPointer writer = WriterType::New(); /** Setup the pipeline. */ writer->SetInput( this->GetAsITKBaseType()->GetOutput() ); writer->SetFileName( filename ); writer->SetOutputComponentType( resultImagePixelType.c_str() ); writer->SetUseCompression( doCompression ); /** Do the writing. */ try { writer->Update(); } catch( itk::ExceptionObject & excp ) { /** Add information to the exception. */ excp.SetLocation( "ResamplerBase - AfterRegistrationBase()" ); std::string err_str = excp.GetDescription(); err_str += "\nError occured while writing resampled image.\n"; excp.SetDescription( err_str ); /** Pass the exception to an higher level. */ throw excp; } /** Disconnect from the resampler. */ progressObserver->DisconnectObserver( this->GetAsITKBaseType() ); } // end WriteResultImage() /* * ************************* ReadFromFile *********************** */ template<class TElastix> void ResamplerBase<TElastix> ::ReadFromFile( void ) { /** Connect the components. */ this->SetComponents(); /** Get spacing, origin and size of the image to be produced by the resampler. */ SpacingType spacing; IndexType index; OriginPointType origin; SizeType size; for ( unsigned int i = 0; i < ImageDimension; i++ ) { /** No default size. Read size from the parameter file. */ this->m_Configuration->ReadParameter( size[ i ], "Size", i ); /** Default index. Read index from the parameter file. */ index[ i ] = 0; this->m_Configuration->ReadParameter( index[ i ], "Index", i ); /** Default spacing. Read spacing from the parameter file. */ spacing[ i ] = 1.0; this->m_Configuration->ReadParameter( spacing[ i ], "Spacing", i ); /** Default origin. Read origin from the parameter file. */ origin[ i ] = 0.0; this->m_Configuration->ReadParameter( origin[ i ], "Origin", i ); } /** Check for image size. */ unsigned int sum = 0; for ( unsigned int i = 0; i < ImageDimension; i++ ) { if ( size[ i ] == 0 ) sum++; } if ( sum > 0 ) { xl::xout["error"] << "ERROR: One or more image sizes are 0!" << std::endl; /** \todo quit program nicely. */ } /** Set the region info to the same values as in the fixedImage. */ this->GetAsITKBaseType()->SetSize( size ); this->GetAsITKBaseType()->SetOutputStartIndex( index ); this->GetAsITKBaseType()->SetOutputOrigin( origin ); this->GetAsITKBaseType()->SetOutputSpacing( spacing ); /** Set the DefaultPixelValue (for pixels in the resampled image * that come from outside the original (moving) image. */ double defaultPixelValueDouble = NumericTraits<double>::Zero; int defaultPixelValueInt = NumericTraits<int>::Zero; int retd = this->m_Configuration->ReadParameter( defaultPixelValueDouble, "DefaultPixelValue", 0, true ); int reti = this->m_Configuration->ReadParameter( defaultPixelValueInt, "DefaultPixelValue", 0, true ); /** Set the defaultPixelValue. int values overrule double values in case * both have been supplied. */ if ( retd == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueDouble ) ); } if ( reti == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } if ( reti != 0 && retd != 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } } // end ReadFromFile() /** * ******************* WriteToFile ****************************** */ template <class TElastix> void ResamplerBase<TElastix> ::WriteToFile( void ) { /** Write Resampler specific things. */ xl::xout["transpar"] << std::endl << "// Resampler specific" << std::endl; /** Write the name of the Resampler. */ xl::xout["transpar"] << "(Resampler \"" << this->elxGetClassName() << "\")" << std::endl; /** Write the DefaultPixelValue. */ xl::xout["transpar"] << "(DefaultPixelValue " << this->GetAsITKBaseType()->GetDefaultPixelValue() << ")" << std::endl; /** Write the output image format. */ std::string resultImageFormat = "mhd"; this->m_Configuration->ReadParameter( resultImageFormat, "ResultImageFormat", 0, true ); xl::xout["transpar"] << "(ResultImageFormat \"" << resultImageFormat << "\")" << std::endl; /** Write output pixeltype. */ std::string resultImagePixelType = "short"; this->m_Configuration->ReadParameter( resultImagePixelType, "ResultImagePixelType", 0, true ); xl::xout["transpar"] << "(ResultImagePixelType \"" << resultImagePixelType << "\")" << std::endl; /** Write compression flag. */ std::string doCompression = "false"; this->m_Configuration->ReadParameter( doCompression, "CompressResultImage", 0, true ); xl::xout["transpar"] << "(CompressResultImage \"" << doCompression << "\")" << std::endl; } // end WriteToFile() } // end namespace elastix #endif // end #ifndef __elxResamplerBase_hxx <commit_msg>MS:<commit_after>/*====================================================================== This file is part of the elastix software. Copyright (c) University Medical Center Utrecht. All rights reserved. See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. ======================================================================*/ #ifndef __elxResamplerBase_hxx #define __elxResamplerBase_hxx #include "elxResamplerBase.h" #include "itkImageFileCastWriter.h" #include "elxTimer.h" namespace elastix { using namespace itk; /* * ******************* BeforeRegistrationBase ******************* */ template<class TElastix> void ResamplerBase<TElastix> ::BeforeRegistrationBase( void ) { /** Connect the components. */ this->SetComponents(); /** Set the size of the image to be produced by the resampler. */ /** Get a pointer to the fixedImage. * \todo make it a cast to the fixed image type */ typedef typename ElastixType::FixedImageType FixedImageType; FixedImageType * fixedImage = this->m_Elastix->GetFixedImage(); /** Set the region info to the same values as in the fixedImage. */ this->GetAsITKBaseType()->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); this->GetAsITKBaseType()->SetOutputStartIndex( fixedImage->GetLargestPossibleRegion().GetIndex() ); this->GetAsITKBaseType()->SetOutputOrigin( fixedImage->GetOrigin() ); this->GetAsITKBaseType()->SetOutputSpacing( fixedImage->GetSpacing() ); /** Set the DefaultPixelValue (for pixels in the resampled image * that come from outside the original (moving) image. */ double defaultPixelValueDouble = NumericTraits<double>::Zero; int defaultPixelValueInt = NumericTraits<int>::Zero; int retd = this->m_Configuration->ReadParameter( defaultPixelValueDouble, "DefaultPixelValue", 0, true ); int reti = this->m_Configuration->ReadParameter( defaultPixelValueInt, "DefaultPixelValue", 0, true ); /** Set the defaultPixelValue. int values overrule double values. */ if ( retd == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueDouble ) ); } if ( reti == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } if ( reti != 0 && retd != 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } } // end BeforeRegistrationBase /* * ******************* AfterEachResolutionBase ******************** */ template<class TElastix> void ResamplerBase<TElastix> ::AfterEachResolutionBase( void ) { /** Set the final transform parameters. */ this->GetElastix()->GetElxTransformBase()->SetFinalParameters(); /** What is the current resolution level? */ unsigned int level = this->m_Registration->GetAsITKBaseType()->GetCurrentLevel(); /** Decide whether or not to write the result image this resolution. */ bool writeResultImageThisResolution = false; this->m_Configuration->ReadParameter( writeResultImageThisResolution, "WriteResultImageAfterEachResolution", "", level, 0, true ); /** Writing result image. */ if ( writeResultImageThisResolution ) { /** Create a name for the final result. */ std::string resultImageFormat = "mhd"; this->m_Configuration->ReadParameter( resultImageFormat, "ResultImageFormat", 0, true); std::ostringstream makeFileName( "" ); makeFileName << this->m_Configuration->GetCommandLineArgument( "-out" ) << "result." << this->m_Configuration->GetElastixLevel() << ".R" << level << "." << resultImageFormat; /** Time the resampling. */ typedef tmr::Timer TimerType; TimerType::Pointer timer = TimerType::New(); timer->StartTimer(); /** Apply the final transform, and save the result. */ elxout << "Applying transform this resolution ..." << std::endl; try { this->WriteResultImage( makeFileName.str().c_str() ); } catch( itk::ExceptionObject & excp ) { xl::xout["error"] << "Exception caught: " << std::endl; xl::xout["error"] << excp << "Resuming elastix." << std::endl; } /** Print the elapsed time for the resampling. */ timer->StopTimer(); elxout << " Applying transform took " << static_cast<long>( timer->GetElapsedClockSec() ) << " s." << std::endl; } // end if } // end AfterEachResolutionBase() /* * ******************* AfterRegistrationBase ******************** */ template<class TElastix> void ResamplerBase<TElastix> ::AfterRegistrationBase(void) { /** Set the final transform parameters. */ this->GetElastix()->GetElxTransformBase()->SetFinalParameters(); /** Decide whether or not to write the result image. */ std::string writeResultImage = "true"; this->m_Configuration->ReadParameter( writeResultImage, "WriteResultImage", 0 ); /** Writing result image. */ if ( writeResultImage == "true" ) { /** Create a name for the final result. */ std::string resultImageFormat = "mhd"; this->m_Configuration->ReadParameter( resultImageFormat, "ResultImageFormat", 0); std::ostringstream makeFileName( "" ); makeFileName << this->m_Configuration->GetCommandLineArgument( "-out" ) << "result." << this->m_Configuration->GetElastixLevel() << "." << resultImageFormat; /** Time the resampling. */ typedef tmr::Timer TimerType; TimerType::Pointer timer = TimerType::New(); timer->StartTimer(); /** Apply the final transform, and save the result, * by calling WriteResultImage. */ elxout << "\nApplying final transform ..." << std::endl; try { this->WriteResultImage( makeFileName.str().c_str() ); } catch( itk::ExceptionObject & excp ) { xl::xout["error"] << "Exception caught: " << std::endl; xl::xout["error"] << excp << "Resuming elastix." << std::endl; } /** Print the elapsed time for the resampling. */ timer->StopTimer(); elxout << " Applying final transform took " << static_cast<long>( timer->GetElapsedClockSec() ) << " s." << std::endl; } else { /** Do not apply the final transform. */ elxout << std::endl << "Skipping applying final transform, no resulting output image generated." << std::endl; } // end if } // end AfterRegistrationBase() /* * *********************** SetComponents ************************ */ template <class TElastix> void ResamplerBase<TElastix> ::SetComponents(void) { /** Set the transform, the interpolator and the inputImage * (which is the moving image). */ this->GetAsITKBaseType()->SetTransform( dynamic_cast<TransformType *>( this->m_Elastix->GetElxTransformBase() ) ); this->GetAsITKBaseType()->SetInterpolator( dynamic_cast<InterpolatorType *>( this->m_Elastix->GetElxResampleInterpolatorBase() ) ); this->GetAsITKBaseType()->SetInput( dynamic_cast<InputImageType *>( this->m_Elastix->GetMovingImage() ) ); } // end SetComponents() /* * ******************* WriteResultImage ******************** */ template<class TElastix> void ResamplerBase<TElastix> ::WriteResultImage( const char * filename ) { /** Make sure the resampler is updated. */ this->GetAsITKBaseType()->Modified(); /** Add a progress observer to the resampler. */ typename ProgressCommandType::Pointer progressObserver = ProgressCommandType::New(); progressObserver->ConnectObserver( this->GetAsITKBaseType() ); progressObserver->SetStartString( " Progress: " ); progressObserver->SetEndString( "%" ); /** Read output pixeltype from parameter the file. Replace possible " " with "_". */ std::string resultImagePixelType = "short"; this->m_Configuration->ReadParameter( resultImagePixelType, "ResultImagePixelType", 0, true ); std::basic_string<char>::size_type pos = resultImagePixelType.find( " " ); const std::basic_string<char>::size_type npos = std::basic_string<char>::npos; if ( pos != npos ) resultImagePixelType.replace( pos, 1, "_" ); /** Read from the parameter file if compression is desired. */ bool doCompression = false; this->m_Configuration->ReadParameter( doCompression, "CompressResultImage", 0, true ); /** Typedef's for writing the output image. */ typedef ImageFileCastWriter< OutputImageType > WriterType; typedef typename WriterType::Pointer WriterPointer; /** Create writer. */ WriterPointer writer = WriterType::New(); /** Setup the pipeline. */ writer->SetInput( this->GetAsITKBaseType()->GetOutput() ); writer->SetFileName( filename ); writer->SetOutputComponentType( resultImagePixelType.c_str() ); writer->SetUseCompression( doCompression ); /** Do the writing. */ try { writer->Update(); } catch( itk::ExceptionObject & excp ) { /** Add information to the exception. */ excp.SetLocation( "ResamplerBase - AfterRegistrationBase()" ); std::string err_str = excp.GetDescription(); err_str += "\nError occured while writing resampled image.\n"; excp.SetDescription( err_str ); /** Pass the exception to an higher level. */ throw excp; } /** Disconnect from the resampler. */ progressObserver->DisconnectObserver( this->GetAsITKBaseType() ); } // end WriteResultImage() /* * ************************* ReadFromFile *********************** */ template<class TElastix> void ResamplerBase<TElastix> ::ReadFromFile( void ) { /** Connect the components. */ this->SetComponents(); /** Get spacing, origin and size of the image to be produced by the resampler. */ SpacingType spacing; IndexType index; OriginPointType origin; SizeType size; for ( unsigned int i = 0; i < ImageDimension; i++ ) { /** No default size. Read size from the parameter file. */ this->m_Configuration->ReadParameter( size[ i ], "Size", i ); /** Default index. Read index from the parameter file. */ index[ i ] = 0; this->m_Configuration->ReadParameter( index[ i ], "Index", i ); /** Default spacing. Read spacing from the parameter file. */ spacing[ i ] = 1.0; this->m_Configuration->ReadParameter( spacing[ i ], "Spacing", i ); /** Default origin. Read origin from the parameter file. */ origin[ i ] = 0.0; this->m_Configuration->ReadParameter( origin[ i ], "Origin", i ); } /** Check for image size. */ unsigned int sum = 0; for ( unsigned int i = 0; i < ImageDimension; i++ ) { if ( size[ i ] == 0 ) sum++; } if ( sum > 0 ) { xl::xout["error"] << "ERROR: One or more image sizes are 0!" << std::endl; /** \todo quit program nicely. */ } /** Set the region info to the same values as in the fixedImage. */ this->GetAsITKBaseType()->SetSize( size ); this->GetAsITKBaseType()->SetOutputStartIndex( index ); this->GetAsITKBaseType()->SetOutputOrigin( origin ); this->GetAsITKBaseType()->SetOutputSpacing( spacing ); /** Set the DefaultPixelValue (for pixels in the resampled image * that come from outside the original (moving) image. */ double defaultPixelValueDouble = NumericTraits<double>::Zero; int defaultPixelValueInt = NumericTraits<int>::Zero; int retd = this->m_Configuration->ReadParameter( defaultPixelValueDouble, "DefaultPixelValue", 0, true ); int reti = this->m_Configuration->ReadParameter( defaultPixelValueInt, "DefaultPixelValue", 0, true ); /** Set the defaultPixelValue. int values overrule double values in case * both have been supplied. */ if ( retd == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueDouble ) ); } if ( reti == 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } if ( reti != 0 && retd != 0 ) { this->GetAsITKBaseType()->SetDefaultPixelValue( static_cast<OutputPixelType>( defaultPixelValueInt ) ); } } // end ReadFromFile() /** * ******************* WriteToFile ****************************** */ template <class TElastix> void ResamplerBase<TElastix> ::WriteToFile( void ) { /** Write Resampler specific things. */ xl::xout["transpar"] << std::endl << "// Resampler specific" << std::endl; /** Write the name of the Resampler. */ xl::xout["transpar"] << "(Resampler \"" << this->elxGetClassName() << "\")" << std::endl; /** Write the DefaultPixelValue. */ xl::xout["transpar"] << "(DefaultPixelValue " << this->GetAsITKBaseType()->GetDefaultPixelValue() << ")" << std::endl; /** Write the output image format. */ std::string resultImageFormat = "mhd"; this->m_Configuration->ReadParameter( resultImageFormat, "ResultImageFormat", 0, true ); xl::xout["transpar"] << "(ResultImageFormat \"" << resultImageFormat << "\")" << std::endl; /** Write output pixeltype. */ std::string resultImagePixelType = "short"; this->m_Configuration->ReadParameter( resultImagePixelType, "ResultImagePixelType", 0, true ); xl::xout["transpar"] << "(ResultImagePixelType \"" << resultImagePixelType << "\")" << std::endl; /** Write compression flag. */ std::string doCompression = "false"; this->m_Configuration->ReadParameter( doCompression, "CompressResultImage", 0, true ); xl::xout["transpar"] << "(CompressResultImage \"" << doCompression << "\")" << std::endl; } // end WriteToFile() } // end namespace elastix #endif // end #ifndef __elxResamplerBase_hxx <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2012 Jrgen Riegel <juergen.riegel@web.de> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include "ui_TaskTransformedMessages.h" #include "TaskTransformedMessages.h" #include <Gui/Application.h> #include <Gui/Document.h> #include <Gui/BitmapFactory.h> #include <boost/bind.hpp> #include "ViewProviderTransformed.h" using namespace PartDesignGui; using namespace Gui::TaskView; TaskTransformedMessages::TaskTransformedMessages(ViewProviderTransformed *transformedView_) : TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Transformed feature messages"),true, 0), transformedView(transformedView_) { // we need a separate container widget to add all controls to proxy = new QWidget(this); ui = new Ui_TaskTransformedMessages(); ui->setupUi(proxy); QMetaObject::connectSlotsByName(this); this->groupLayout()->addWidget(proxy); connectionDiagnosis = transformedView->signalDiagnosis.connect(boost::bind(&PartDesignGui::TaskTransformedMessages::slotDiagnosis, this,_1)); } TaskTransformedMessages::~TaskTransformedMessages() { connectionDiagnosis.disconnect(); delete ui; } void TaskTransformedMessages::slotDiagnosis(QString msg) { ui->labelTransformationStatus->setText(msg); } #include "moc_TaskTransformedMessages.cpp" <commit_msg>+ minor issue solved with message label of linear pattern panel<commit_after>/*************************************************************************** * Copyright (c) 2012 Jrgen Riegel <juergen.riegel@web.de> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ #endif #include "ui_TaskTransformedMessages.h" #include "TaskTransformedMessages.h" #include <Gui/Application.h> #include <Gui/Document.h> #include <Gui/BitmapFactory.h> #include <boost/bind.hpp> #include "ViewProviderTransformed.h" using namespace PartDesignGui; using namespace Gui::TaskView; TaskTransformedMessages::TaskTransformedMessages(ViewProviderTransformed *transformedView_) : TaskBox(Gui::BitmapFactory().pixmap("document-new"),tr("Transformed feature messages"),true, 0), transformedView(transformedView_) { // we need a separate container widget to add all controls to proxy = new QWidget(this); ui = new Ui_TaskTransformedMessages(); ui->setupUi(proxy); // set a minimum height to avoid a sudden resize and to // lose focus of the currently used spin boxes ui->labelTransformationStatus->setMinimumHeight(50); QMetaObject::connectSlotsByName(this); this->groupLayout()->addWidget(proxy); connectionDiagnosis = transformedView->signalDiagnosis.connect(boost::bind(&PartDesignGui::TaskTransformedMessages::slotDiagnosis, this,_1)); } TaskTransformedMessages::~TaskTransformedMessages() { connectionDiagnosis.disconnect(); delete ui; } void TaskTransformedMessages::slotDiagnosis(QString msg) { ui->labelTransformationStatus->setText(msg); } #include "moc_TaskTransformedMessages.cpp" <|endoftext|>
<commit_before>#include <seastar/rpc/rpc.hh> #include "messaging_service.hh" #include "serializer.hh" #include "seastarx.hh" namespace netw { struct serializer; // thunk from rpc serializers to generate serializers template <typename T, typename Output> void write(serializer, Output& out, const T& data) { ser::serialize(out, data); } template <typename T, typename Input> T read(serializer, Input& in, boost::type<T> type) { return ser::deserialize(in, type); } template <typename Output, typename T> void write(serializer s, Output& out, const foreign_ptr<T>& v) { return write(s, out, *v); } template <typename Input, typename T> foreign_ptr<T> read(serializer s, Input& in, boost::type<foreign_ptr<T>>) { return make_foreign(read(s, in, boost::type<T>())); } template <typename Output, typename T> void write(serializer s, Output& out, const lw_shared_ptr<T>& v) { return write(s, out, *v); } template <typename Input, typename T> lw_shared_ptr<T> read(serializer s, Input& in, boost::type<lw_shared_ptr<T>>) { return make_lw_shared<T>(read(s, in, boost::type<T>())); } using rpc_protocol = rpc::protocol<serializer, messaging_verb>; class messaging_service::rpc_protocol_wrapper { rpc_protocol _impl; public: explicit rpc_protocol_wrapper(serializer &&s) : _impl(std::move(s)) {} rpc_protocol &protocol() { return _impl; } template<typename Func> auto make_client(messaging_verb t) { return _impl.make_client<Func>(t); } template<typename Func> auto register_handler(messaging_verb t, Func &&func) { return _impl.register_handler(t, std::forward<Func>(func)); } template<typename Func> auto register_handler(messaging_verb t, scheduling_group sg, Func &&func) { return _impl.register_handler(t, sg, std::forward<Func>(func)); } future<> unregister_handler(messaging_verb t) { return _impl.unregister_handler(t); } void set_logger(::seastar::logger *logger) { _impl.set_logger(logger); } bool has_handler(messaging_verb msg_id) { return _impl.has_handler(msg_id); } bool has_handlers() const noexcept { return _impl.has_handlers(); } }; // This wrapper pretends to be rpc_protocol::client, but also handles // stopping it before destruction, in case it wasn't stopped already. // This should be integrated into messaging_service proper. class messaging_service::rpc_protocol_client_wrapper { std::unique_ptr<rpc_protocol::client> _p; ::shared_ptr<seastar::tls::server_credentials> _credentials; public: rpc_protocol_client_wrapper(rpc_protocol &proto, rpc::client_options opts, socket_address addr, socket_address local = {}) : _p(std::make_unique<rpc_protocol::client>(proto, std::move(opts), addr, local)) { } rpc_protocol_client_wrapper(rpc_protocol &proto, rpc::client_options opts, socket_address addr, socket_address local, ::shared_ptr<seastar::tls::server_credentials> c) : _p( std::make_unique<rpc_protocol::client>(proto, std::move(opts), seastar::tls::socket(c), addr, local)), _credentials(c) {} auto get_stats() const { return _p->get_stats(); } future<> stop() { return _p->stop(); } bool error() { return _p->error(); } operator rpc_protocol::client &() { return *_p; } /** * #3787 Must ensure we use the right type of socket. I.e. tls or not. * See above, we retain credentials object so we here can know if we * are tls or not. */ template<typename Serializer, typename... Out> future<rpc::sink<Out...>> make_stream_sink() { if (_credentials) { return _p->make_stream_sink<Serializer, Out...>(seastar::tls::socket(_credentials)); } return _p->make_stream_sink<Serializer, Out...>(); } }; // Register a handler (a callback lambda) for verb template<typename Func> void register_handler(messaging_service *ms, messaging_verb verb, Func &&func) { ms->rpc()->register_handler(verb, ms->scheduling_group_for_verb(verb), std::move(func)); } // Send a message for verb template <typename MsgIn, typename... MsgOut> auto send_message(messaging_service* ms, messaging_verb verb, msg_addr id, MsgOut&&... msg) { auto rpc_handler = ms->rpc()->make_client<MsgIn(MsgOut...)>(verb); if (ms->is_shutting_down()) { using futurator = futurize<std::result_of_t<decltype(rpc_handler)(rpc_protocol::client&, MsgOut...)>>; return futurator::make_exception_future(rpc::closed_error()); } auto rpc_client_ptr = ms->get_rpc_client(verb, id); auto& rpc_client = *rpc_client_ptr; return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([ms = ms->shared_from_this(), id, verb, rpc_client_ptr = std::move(rpc_client_ptr)] (auto&& f) { try { if (f.failed()) { ms->increment_dropped_messages(verb); f.get(); assert(false); // never reached } return std::move(f); } catch (rpc::closed_error&) { // This is a transport error ms->remove_error_rpc_client(verb, id); throw; } catch (...) { // This is expected to be a rpc server error, e.g., the rpc handler throws a std::runtime_error. throw; } }); } // TODO: Remove duplicated code in send_message template <typename MsgIn, typename Timeout, typename... MsgOut> auto send_message_timeout(messaging_service* ms, messaging_verb verb, msg_addr id, Timeout timeout, MsgOut&&... msg) { auto rpc_handler = ms->rpc()->make_client<MsgIn(MsgOut...)>(verb); if (ms->is_shutting_down()) { using futurator = futurize<std::result_of_t<decltype(rpc_handler)(rpc_protocol::client&, MsgOut...)>>; return futurator::make_exception_future(rpc::closed_error()); } auto rpc_client_ptr = ms->get_rpc_client(verb, id); auto& rpc_client = *rpc_client_ptr; return rpc_handler(rpc_client, timeout, std::forward<MsgOut>(msg)...).then_wrapped([ms = ms->shared_from_this(), id, verb, rpc_client_ptr = std::move(rpc_client_ptr)] (auto&& f) { try { if (f.failed()) { ms->increment_dropped_messages(verb); f.get(); assert(false); // never reached } return std::move(f); } catch (rpc::closed_error&) { // This is a transport error ms->remove_error_rpc_client(verb, id); throw; } catch (...) { // This is expected to be a rpc server error, e.g., the rpc handler throws a std::runtime_error. throw; } }); } // TODO: Remove duplicated code in send_message template <typename MsgIn, typename... MsgOut> auto send_message_abortable(messaging_service* ms, messaging_verb verb, msg_addr id, abort_source& as, MsgOut&&... msg) { auto rpc_handler = ms->rpc()->make_client<MsgIn(MsgOut...)>(verb); if (ms->is_shutting_down()) { using futurator = futurize<std::result_of_t<decltype(rpc_handler)(rpc_protocol::client&, MsgOut...)>>; return futurator::make_exception_future(rpc::closed_error()); } auto rpc_client_ptr = ms->get_rpc_client(verb, id); auto& rpc_client = *rpc_client_ptr; auto c = std::make_unique<seastar::rpc::cancellable>(); auto& c_ref = *c; auto sub = as.subscribe([c = std::move(c)] () noexcept { c->cancel(); }); if (!sub) { throw abort_requested_exception{}; } return rpc_handler(rpc_client, c_ref, std::forward<MsgOut>(msg)...).then_wrapped([ms = ms->shared_from_this(), id, verb, rpc_client_ptr = std::move(rpc_client_ptr), sub = std::move(sub)] (auto&& f) { try { if (f.failed()) { ms->increment_dropped_messages(verb); f.get(); assert(false); // never reached } return std::move(f); } catch (rpc::closed_error&) { // This is a transport error ms->remove_error_rpc_client(verb, id); throw; } catch (rpc::canceled_error&) { // Translate low-level canceled_error into high-level abort_requested_exception. throw abort_requested_exception{}; } catch (...) { // This is expected to be a rpc server error, e.g., the rpc handler throws a std::runtime_error. throw; } }); } // Send one way message for verb template <typename... MsgOut> auto send_message_oneway(messaging_service* ms, messaging_verb verb, msg_addr id, MsgOut&&... msg) { return send_message<rpc::no_wait_type>(ms, std::move(verb), std::move(id), std::forward<MsgOut>(msg)...); } // Send one way message for verb template <typename Timeout, typename... MsgOut> auto send_message_oneway_timeout(messaging_service* ms, Timeout timeout, messaging_verb verb, msg_addr id, MsgOut&&... msg) { return send_message_timeout<rpc::no_wait_type>(ms, std::move(verb), std::move(id), timeout, std::forward<MsgOut>(msg)...); } } // namespace netw <commit_msg>messaging: add boilerplate to rpc_protocol_impl.hh<commit_after>// SPDX-License-Identifier: AGPL-3.0-or-later // Copyright 2021-present ScyllaDB #pragma once #include <seastar/rpc/rpc.hh> #include "messaging_service.hh" #include "serializer.hh" #include "seastarx.hh" namespace netw { struct serializer; // thunk from rpc serializers to generate serializers template <typename T, typename Output> void write(serializer, Output& out, const T& data) { ser::serialize(out, data); } template <typename T, typename Input> T read(serializer, Input& in, boost::type<T> type) { return ser::deserialize(in, type); } template <typename Output, typename T> void write(serializer s, Output& out, const foreign_ptr<T>& v) { return write(s, out, *v); } template <typename Input, typename T> foreign_ptr<T> read(serializer s, Input& in, boost::type<foreign_ptr<T>>) { return make_foreign(read(s, in, boost::type<T>())); } template <typename Output, typename T> void write(serializer s, Output& out, const lw_shared_ptr<T>& v) { return write(s, out, *v); } template <typename Input, typename T> lw_shared_ptr<T> read(serializer s, Input& in, boost::type<lw_shared_ptr<T>>) { return make_lw_shared<T>(read(s, in, boost::type<T>())); } using rpc_protocol = rpc::protocol<serializer, messaging_verb>; class messaging_service::rpc_protocol_wrapper { rpc_protocol _impl; public: explicit rpc_protocol_wrapper(serializer &&s) : _impl(std::move(s)) {} rpc_protocol &protocol() { return _impl; } template<typename Func> auto make_client(messaging_verb t) { return _impl.make_client<Func>(t); } template<typename Func> auto register_handler(messaging_verb t, Func &&func) { return _impl.register_handler(t, std::forward<Func>(func)); } template<typename Func> auto register_handler(messaging_verb t, scheduling_group sg, Func &&func) { return _impl.register_handler(t, sg, std::forward<Func>(func)); } future<> unregister_handler(messaging_verb t) { return _impl.unregister_handler(t); } void set_logger(::seastar::logger *logger) { _impl.set_logger(logger); } bool has_handler(messaging_verb msg_id) { return _impl.has_handler(msg_id); } bool has_handlers() const noexcept { return _impl.has_handlers(); } }; // This wrapper pretends to be rpc_protocol::client, but also handles // stopping it before destruction, in case it wasn't stopped already. // This should be integrated into messaging_service proper. class messaging_service::rpc_protocol_client_wrapper { std::unique_ptr<rpc_protocol::client> _p; ::shared_ptr<seastar::tls::server_credentials> _credentials; public: rpc_protocol_client_wrapper(rpc_protocol &proto, rpc::client_options opts, socket_address addr, socket_address local = {}) : _p(std::make_unique<rpc_protocol::client>(proto, std::move(opts), addr, local)) { } rpc_protocol_client_wrapper(rpc_protocol &proto, rpc::client_options opts, socket_address addr, socket_address local, ::shared_ptr<seastar::tls::server_credentials> c) : _p( std::make_unique<rpc_protocol::client>(proto, std::move(opts), seastar::tls::socket(c), addr, local)), _credentials(c) {} auto get_stats() const { return _p->get_stats(); } future<> stop() { return _p->stop(); } bool error() { return _p->error(); } operator rpc_protocol::client &() { return *_p; } /** * #3787 Must ensure we use the right type of socket. I.e. tls or not. * See above, we retain credentials object so we here can know if we * are tls or not. */ template<typename Serializer, typename... Out> future<rpc::sink<Out...>> make_stream_sink() { if (_credentials) { return _p->make_stream_sink<Serializer, Out...>(seastar::tls::socket(_credentials)); } return _p->make_stream_sink<Serializer, Out...>(); } }; // Register a handler (a callback lambda) for verb template<typename Func> void register_handler(messaging_service *ms, messaging_verb verb, Func &&func) { ms->rpc()->register_handler(verb, ms->scheduling_group_for_verb(verb), std::move(func)); } // Send a message for verb template <typename MsgIn, typename... MsgOut> auto send_message(messaging_service* ms, messaging_verb verb, msg_addr id, MsgOut&&... msg) { auto rpc_handler = ms->rpc()->make_client<MsgIn(MsgOut...)>(verb); if (ms->is_shutting_down()) { using futurator = futurize<std::result_of_t<decltype(rpc_handler)(rpc_protocol::client&, MsgOut...)>>; return futurator::make_exception_future(rpc::closed_error()); } auto rpc_client_ptr = ms->get_rpc_client(verb, id); auto& rpc_client = *rpc_client_ptr; return rpc_handler(rpc_client, std::forward<MsgOut>(msg)...).then_wrapped([ms = ms->shared_from_this(), id, verb, rpc_client_ptr = std::move(rpc_client_ptr)] (auto&& f) { try { if (f.failed()) { ms->increment_dropped_messages(verb); f.get(); assert(false); // never reached } return std::move(f); } catch (rpc::closed_error&) { // This is a transport error ms->remove_error_rpc_client(verb, id); throw; } catch (...) { // This is expected to be a rpc server error, e.g., the rpc handler throws a std::runtime_error. throw; } }); } // TODO: Remove duplicated code in send_message template <typename MsgIn, typename Timeout, typename... MsgOut> auto send_message_timeout(messaging_service* ms, messaging_verb verb, msg_addr id, Timeout timeout, MsgOut&&... msg) { auto rpc_handler = ms->rpc()->make_client<MsgIn(MsgOut...)>(verb); if (ms->is_shutting_down()) { using futurator = futurize<std::result_of_t<decltype(rpc_handler)(rpc_protocol::client&, MsgOut...)>>; return futurator::make_exception_future(rpc::closed_error()); } auto rpc_client_ptr = ms->get_rpc_client(verb, id); auto& rpc_client = *rpc_client_ptr; return rpc_handler(rpc_client, timeout, std::forward<MsgOut>(msg)...).then_wrapped([ms = ms->shared_from_this(), id, verb, rpc_client_ptr = std::move(rpc_client_ptr)] (auto&& f) { try { if (f.failed()) { ms->increment_dropped_messages(verb); f.get(); assert(false); // never reached } return std::move(f); } catch (rpc::closed_error&) { // This is a transport error ms->remove_error_rpc_client(verb, id); throw; } catch (...) { // This is expected to be a rpc server error, e.g., the rpc handler throws a std::runtime_error. throw; } }); } // TODO: Remove duplicated code in send_message template <typename MsgIn, typename... MsgOut> auto send_message_abortable(messaging_service* ms, messaging_verb verb, msg_addr id, abort_source& as, MsgOut&&... msg) { auto rpc_handler = ms->rpc()->make_client<MsgIn(MsgOut...)>(verb); if (ms->is_shutting_down()) { using futurator = futurize<std::result_of_t<decltype(rpc_handler)(rpc_protocol::client&, MsgOut...)>>; return futurator::make_exception_future(rpc::closed_error()); } auto rpc_client_ptr = ms->get_rpc_client(verb, id); auto& rpc_client = *rpc_client_ptr; auto c = std::make_unique<seastar::rpc::cancellable>(); auto& c_ref = *c; auto sub = as.subscribe([c = std::move(c)] () noexcept { c->cancel(); }); if (!sub) { throw abort_requested_exception{}; } return rpc_handler(rpc_client, c_ref, std::forward<MsgOut>(msg)...).then_wrapped([ms = ms->shared_from_this(), id, verb, rpc_client_ptr = std::move(rpc_client_ptr), sub = std::move(sub)] (auto&& f) { try { if (f.failed()) { ms->increment_dropped_messages(verb); f.get(); assert(false); // never reached } return std::move(f); } catch (rpc::closed_error&) { // This is a transport error ms->remove_error_rpc_client(verb, id); throw; } catch (rpc::canceled_error&) { // Translate low-level canceled_error into high-level abort_requested_exception. throw abort_requested_exception{}; } catch (...) { // This is expected to be a rpc server error, e.g., the rpc handler throws a std::runtime_error. throw; } }); } // Send one way message for verb template <typename... MsgOut> auto send_message_oneway(messaging_service* ms, messaging_verb verb, msg_addr id, MsgOut&&... msg) { return send_message<rpc::no_wait_type>(ms, std::move(verb), std::move(id), std::forward<MsgOut>(msg)...); } // Send one way message for verb template <typename Timeout, typename... MsgOut> auto send_message_oneway_timeout(messaging_service* ms, Timeout timeout, messaging_verb verb, msg_addr id, MsgOut&&... msg) { return send_message_timeout<rpc::no_wait_type>(ms, std::move(verb), std::move(id), timeout, std::forward<MsgOut>(msg)...); } } // namespace netw <|endoftext|>
<commit_before>#include <UnitTest++.h> #include "model/unique-multimap.h" bool found_in_category(UniqueMultimap<int, int> multimap, int value, int category) { for (typename UniqueMultimap<int, int>::member_iter iter = multimap.get_members_of_begin(category); iter != multimap.get_members_of_end(category); ++iter) { if (*iter == value) return true; } return false; } struct UniqueMultimapFixture { UniqueMultimap<int, int> multimap; UniqueMultimapFixture() { multimap.add_category(0); multimap.add_category(1); for (int i = 0; i <= 10; i++) { multimap.add_member(i % 2, i); } } }; SUITE(UniqueMultimapTests) { /** * Ensures that 0 and 1 are in the multimap, and other values are not. */ TEST_FIXTURE(UniqueMultimapFixture, test_is_category) { CHECK_EQUAL(multimap.is_category(0), true); CHECK_EQUAL(multimap.is_category(1), true); CHECK_EQUAL(multimap.is_category(42), false); } /** * Ensures that [0, 10] are all members, and other values are not. */ TEST_FIXTURE(UniqueMultimapFixture, test_is_member) { for (int i = 0; i <= 10; i++) { CHECK_EQUAL(multimap.is_member(i), true); } CHECK_EQUAL(multimap.is_member(42), false); } /** * Ensures that getting the category of a value returns the correct * category. */ TEST_FIXTURE(UniqueMultimapFixture, test_get_category_of) { for (int i = 0; i <= 10; i++) { CHECK_EQUAL(multimap.get_category_of(i), i % 2); } } /** * Ensures that getting the members of a category returns all the * members in that category. */ TEST_FIXTURE(UniqueMultimapFixture, test_get_members_of) { int member = 0; for (UniqueMultimap<int,int>::member_iter iter = multimap.get_members_of_begin(0); iter != multimap.get_members_of_end(0); ++iter, member += 2) { // member += 2 is because, by getting category 0, we're getting // all even values CHECK_EQUAL(*iter, member); } } /** * Ensures that counting the members of a category returns the correct * number of values. */ TEST_FIXTURE(UniqueMultimapFixture, test_count_members_of) { // 0, 2, 4, 6, 8 and 10 CHECK_EQUAL(multimap.count_members_of(0), 6); } /** * Ensures that: * - Adding a new member to an existent category succeeds * - Adding a new member to a nonexistent category fails * - Adding a non-new member to an existent category fails * - Adding a non-new member to a nonexistent category fails */ TEST_FIXTURE(UniqueMultimapFixture, test_add_member) { // Case 1 - new member, existent category CHECK_EQUAL(multimap.add_member(0, 12), true); // Case 2 - new member, nonexistent category CHECK_EQUAL(multimap.add_member(3, 13), false); // Case 3 - non-new member, existent category CHECK_EQUAL(multimap.add_member(0, 8), false); // Case 4 - non-new member, nonexistent category CHECK_EQUAL(multimap.add_member(3, 8), false); } /** * This ensures that a new member shows up, using: * * - is_member * - get_category_of * - get_members_of */ TEST_FIXTURE(UniqueMultimapFixture, test_add_member_works) { CHECK_EQUAL(multimap.add_member(0, 12), true); CHECK_EQUAL(multimap.is_member(12), true); CHECK_EQUAL(multimap.get_category_of(12), 0); CHECK_EQUAL(found_in_category(multimap, 12, 0), true); } /** * This ensures that: * * - Moving an existent member to an existent category works * - Moving a nonexistent member to an existent category fails * - Moving an existent member to a nonexistent category fails * - Moving a nonexistent member to a nonexistent category fails */ TEST_FIXTURE(UniqueMultimapFixture, test_move) { // 13 is miscategorized as even on purpose CHECK_EQUAL(multimap.add_member(0, 13), true); // Case 1: Existent member, existent category CHECK_EQUAL(multimap.move_member(13, 1), true); // Case 2: Nonexistent member, existent category CHECK_EQUAL(multimap.move_member(14, 0), false); // Case 3: Existent member, nonexistent category CHECK_EQUAL(multimap.move_member(13, 3), false); // Case 4: Nonexistent member, nonexistent category CHECK_EQUAL(multimap.move_member(14, 3), false); } /** * This ensures that a moved member shows up in the right places, * including: * * - is_member * - get_category_of (returns the new) * - get_members_of (in the new, not in the old) */ TEST_FIXTURE(UniqueMultimapFixture, test_move_works) { // 6 is odd now. Deal with it. CHECK_EQUAL(multimap.move_member(6, 1), true); CHECK_EQUAL(multimap.is_member(6), true); CHECK_EQUAL(multimap.get_category_of(6), 1); bool found_six_in_new = found_in_category(multimap, 6, 1); bool found_six_in_old = found_in_category(multimap, 6, 0); CHECK_EQUAL(found_six_in_new && !found_six_in_old, true); } /** * Ensure that: * * - Removing an existent element works. * - Removing a nonexistent element fails. */ TEST_FIXTURE(UniqueMultimapFixture, test_remove) { CHECK_EQUAL(multimap.add_member(0, -2), true); // Case 1: Existent member CHECK_EQUAL(multimap.remove_member(-2), true); // Case 2: Nonexistent member CHECK_EQUAL(multimap.remove_member(14), false); } /** * Ensure that a removed member doesn't show up where it used to: * * - is_member * - get_members_of * * We can't test get_category_of, since it is undefined for nonexistent * values. */ TEST_FIXTURE(UniqueMultimapFixture, test_remove_works) { // 6 is not a number now. Deal with it. CHECK_EQUAL(multimap.remove_member(6), true); CHECK_EQUAL(multimap.is_member(6), false); CHECK_EQUAL(found_in_category(multimap, 6, 0), false); } /** * Ensures that: * * - Adding an existent category fails * - Adding a nonexistent category succeeds. */ TEST_FIXTURE(UniqueMultimapFixture, test_add_category) { // Case 1: Existent category CHECK_EQUAL(multimap.add_category(0), false); // Case 2: Nonexistent category CHECK_EQUAL(multimap.add_category(3), true); } /** * Ensures that adding a category actually works, by adding elements to it * and moving elements to it, and then ensuring that they show up in the * typical ways: * * - get_category_of * - get_members_of TEST_FIXTURE(UniqueMultimapFixture, test_add_category_works) { CHECK_EQUAL(multimap.add_category(3), true); CHECK_EQUAL(multimap.add_member(15, 3), true); CHECK_EQUAL(multimap.move_member(9, 3), true); CHECK_EQUAL(multimap. }**/ } int main() { return UnitTest::RunAllTests(); } <commit_msg>Finish UniqueMultimap tests<commit_after>#include <UnitTest++.h> #include "model/unique-multimap.h" bool found_in_category(UniqueMultimap<int, int> multimap, int value, int category) { for (typename UniqueMultimap<int, int>::member_iter iter = multimap.get_members_of_begin(category); iter != multimap.get_members_of_end(category); ++iter) { if (*iter == value) return true; } return false; } struct UniqueMultimapFixture { UniqueMultimap<int, int> multimap; UniqueMultimapFixture() { multimap.add_category(0); multimap.add_category(1); for (int i = 0; i <= 10; i++) { multimap.add_member(i % 2, i); } } }; SUITE(UniqueMultimapTests) { /** * Ensures that 0 and 1 are in the multimap, and other values are not. */ TEST_FIXTURE(UniqueMultimapFixture, test_is_category) { CHECK_EQUAL(multimap.is_category(0), true); CHECK_EQUAL(multimap.is_category(1), true); CHECK_EQUAL(multimap.is_category(42), false); } /** * Ensures that [0, 10] are all members, and other values are not. */ TEST_FIXTURE(UniqueMultimapFixture, test_is_member) { for (int i = 0; i <= 10; i++) { CHECK_EQUAL(multimap.is_member(i), true); } CHECK_EQUAL(multimap.is_member(42), false); } /** * Ensures that getting the category of a value returns the correct * category. */ TEST_FIXTURE(UniqueMultimapFixture, test_get_category_of) { for (int i = 0; i <= 10; i++) { CHECK_EQUAL(multimap.get_category_of(i), i % 2); } } /** * Ensures that getting the members of a category returns all the * members in that category. */ TEST_FIXTURE(UniqueMultimapFixture, test_get_members_of) { int member = 0; for (UniqueMultimap<int,int>::member_iter iter = multimap.get_members_of_begin(0); iter != multimap.get_members_of_end(0); ++iter, member += 2) { // member += 2 is because, by getting category 0, we're getting // all even values CHECK_EQUAL(*iter, member); } } /** * Ensures that counting the members of a category returns the correct * number of values. */ TEST_FIXTURE(UniqueMultimapFixture, test_count_members_of) { // 0, 2, 4, 6, 8 and 10 CHECK_EQUAL(multimap.count_members_of(0), 6); } /** * Ensures that: * - Adding a new member to an existent category succeeds * - Adding a new member to a nonexistent category fails * - Adding a non-new member to an existent category fails * - Adding a non-new member to a nonexistent category fails */ TEST_FIXTURE(UniqueMultimapFixture, test_add_member) { // Case 1 - new member, existent category CHECK_EQUAL(multimap.add_member(0, 12), true); // Case 2 - new member, nonexistent category CHECK_EQUAL(multimap.add_member(3, 13), false); // Case 3 - non-new member, existent category CHECK_EQUAL(multimap.add_member(0, 8), false); // Case 4 - non-new member, nonexistent category CHECK_EQUAL(multimap.add_member(3, 8), false); } /** * This ensures that a new member shows up, using: * * - is_member * - get_category_of * - get_members_of */ TEST_FIXTURE(UniqueMultimapFixture, test_add_member_works) { CHECK_EQUAL(multimap.add_member(0, 12), true); CHECK_EQUAL(multimap.is_member(12), true); CHECK_EQUAL(multimap.get_category_of(12), 0); CHECK_EQUAL(found_in_category(multimap, 12, 0), true); } /** * This ensures that: * * - Moving an existent member to an existent category works * - Moving a nonexistent member to an existent category fails * - Moving an existent member to a nonexistent category fails * - Moving a nonexistent member to a nonexistent category fails */ TEST_FIXTURE(UniqueMultimapFixture, test_move) { // 13 is miscategorized as even on purpose CHECK_EQUAL(multimap.add_member(0, 13), true); // Case 1: Existent member, existent category CHECK_EQUAL(multimap.move_member(13, 1), true); // Case 2: Nonexistent member, existent category CHECK_EQUAL(multimap.move_member(14, 0), false); // Case 3: Existent member, nonexistent category CHECK_EQUAL(multimap.move_member(13, 3), false); // Case 4: Nonexistent member, nonexistent category CHECK_EQUAL(multimap.move_member(14, 3), false); } /** * This ensures that a moved member shows up in the right places, * including: * * - is_member * - get_category_of (returns the new) * - get_members_of (in the new, not in the old) */ TEST_FIXTURE(UniqueMultimapFixture, test_move_works) { // 6 is odd now. Deal with it. CHECK_EQUAL(multimap.move_member(6, 1), true); CHECK_EQUAL(multimap.is_member(6), true); CHECK_EQUAL(multimap.get_category_of(6), 1); bool found_six_in_new = found_in_category(multimap, 6, 1); bool found_six_in_old = found_in_category(multimap, 6, 0); CHECK_EQUAL(found_six_in_new && !found_six_in_old, true); } /** * Ensure that: * * - Removing an existent element works. * - Removing a nonexistent element fails. */ TEST_FIXTURE(UniqueMultimapFixture, test_remove) { CHECK_EQUAL(multimap.add_member(0, -2), true); // Case 1: Existent member CHECK_EQUAL(multimap.remove_member(-2), true); // Case 2: Nonexistent member CHECK_EQUAL(multimap.remove_member(14), false); } /** * Ensure that a removed member doesn't show up where it used to: * * - is_member * - get_members_of * * We can't test get_category_of, since it is undefined for nonexistent * values. */ TEST_FIXTURE(UniqueMultimapFixture, test_remove_works) { // 6 is not a number now. Deal with it. CHECK_EQUAL(multimap.remove_member(6), true); CHECK_EQUAL(multimap.is_member(6), false); CHECK_EQUAL(found_in_category(multimap, 6, 0), false); } /** * Ensures that: * * - Adding an existent category fails * - Adding a nonexistent category succeeds. */ TEST_FIXTURE(UniqueMultimapFixture, test_add_category) { // Case 1: Existent category CHECK_EQUAL(multimap.add_category(0), false); // Case 2: Nonexistent category CHECK_EQUAL(multimap.add_category(3), true); } /** * Ensures that adding a category actually works, by adding elements to it * and moving elements to it, and then ensuring that they show up in the * typical ways: * * - get_category_of * - get_members_of */ TEST_FIXTURE(UniqueMultimapFixture, test_add_category_works) { CHECK_EQUAL(multimap.add_category(3), true); CHECK_EQUAL(multimap.add_member(3, 15), true); CHECK_EQUAL(multimap.move_member(9, 3), true); CHECK_EQUAL(multimap.get_category_of(15), 3); CHECK_EQUAL(multimap.get_category_of(9), 3); CHECK_EQUAL(found_in_category(multimap, 15, 3), true); CHECK_EQUAL(found_in_category(multimap, 9, 3), true); } } int main() { return UnitTest::RunAllTests(); } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2015. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ //===- llvm/unittest/Support/LEB128Test.cpp - LEB128 function tests -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "leb128.h" #include "gtest/gtest.h" #include <string> #include "llvm/StringRef.h" #include "raw_istream.h" namespace nt { TEST(LEB128Test, WriteUleb128) { #define EXPECT_ULEB128_EQ(EXPECTED, VALUE, PAD) \ do { \ llvm::StringRef expected(EXPECTED, sizeof(EXPECTED)-1); \ char buf[32]; \ std::size_t size = WriteUleb128(buf, VALUE); \ llvm::StringRef actual(buf, size); \ EXPECT_EQ(expected, actual); \ } while (0) // Write ULEB128 EXPECT_ULEB128_EQ("\x00", 0, 0); EXPECT_ULEB128_EQ("\x01", 1, 0); EXPECT_ULEB128_EQ("\x3f", 63, 0); EXPECT_ULEB128_EQ("\x40", 64, 0); EXPECT_ULEB128_EQ("\x7f", 0x7f, 0); EXPECT_ULEB128_EQ("\x80\x01", 0x80, 0); EXPECT_ULEB128_EQ("\x81\x01", 0x81, 0); EXPECT_ULEB128_EQ("\x90\x01", 0x90, 0); EXPECT_ULEB128_EQ("\xff\x01", 0xff, 0); EXPECT_ULEB128_EQ("\x80\x02", 0x100, 0); EXPECT_ULEB128_EQ("\x81\x02", 0x101, 0); #undef EXPECT_ULEB128_EQ } TEST(LEB128Test, ReadUleb128) { #define EXPECT_READ_ULEB128_EQ(EXPECTED, VALUE) \ do { \ unsigned long val = 0; \ std::size_t size = ReadUleb128(VALUE, &val); \ EXPECT_EQ(sizeof(VALUE) - 1, size); \ EXPECT_EQ(EXPECTED, val); \ } while (0) // Read ULEB128 EXPECT_READ_ULEB128_EQ(0u, "\x00"); EXPECT_READ_ULEB128_EQ(1u, "\x01"); EXPECT_READ_ULEB128_EQ(63u, "\x3f"); EXPECT_READ_ULEB128_EQ(64u, "\x40"); EXPECT_READ_ULEB128_EQ(0x7fu, "\x7f"); EXPECT_READ_ULEB128_EQ(0x80u, "\x80\x01"); EXPECT_READ_ULEB128_EQ(0x81u, "\x81\x01"); EXPECT_READ_ULEB128_EQ(0x90u, "\x90\x01"); EXPECT_READ_ULEB128_EQ(0xffu, "\xff\x01"); EXPECT_READ_ULEB128_EQ(0x100u, "\x80\x02"); EXPECT_READ_ULEB128_EQ(0x101u, "\x81\x02"); EXPECT_READ_ULEB128_EQ(8320u, "\x80\xc1\x80\x80\x10"); #undef EXPECT_READ_ULEB128_EQ } TEST(LEB128Test, SizeUleb128) { // Testing Plan: // (1) 128 ^ n ............ need (n+1) bytes // (2) 128 ^ n * 64 ....... need (n+1) bytes // (3) 128 ^ (n+1) - 1 .... need (n+1) bytes EXPECT_EQ(1u, SizeUleb128(0)); // special case EXPECT_EQ(1u, SizeUleb128(0x1UL)); EXPECT_EQ(1u, SizeUleb128(0x40UL)); EXPECT_EQ(1u, SizeUleb128(0x7fUL)); EXPECT_EQ(2u, SizeUleb128(0x80UL)); EXPECT_EQ(2u, SizeUleb128(0x2000UL)); EXPECT_EQ(2u, SizeUleb128(0x3fffUL)); EXPECT_EQ(3u, SizeUleb128(0x4000UL)); EXPECT_EQ(3u, SizeUleb128(0x100000UL)); EXPECT_EQ(3u, SizeUleb128(0x1fffffUL)); EXPECT_EQ(4u, SizeUleb128(0x200000UL)); EXPECT_EQ(4u, SizeUleb128(0x8000000UL)); EXPECT_EQ(4u, SizeUleb128(0xfffffffUL)); EXPECT_EQ(5u, SizeUleb128(0x10000000UL)); EXPECT_EQ(5u, SizeUleb128(0x400000000UL)); EXPECT_EQ(5u, SizeUleb128(0x7ffffffffUL)); EXPECT_EQ(5u, SizeUleb128(UINT32_MAX)); } } // namespace nt <commit_msg>leb128Test: Fix incorrectly sized constants.<commit_after>/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2015. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ //===- llvm/unittest/Support/LEB128Test.cpp - LEB128 function tests -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "leb128.h" #include "gtest/gtest.h" #include <string> #include "llvm/StringRef.h" #include "raw_istream.h" namespace nt { TEST(LEB128Test, WriteUleb128) { #define EXPECT_ULEB128_EQ(EXPECTED, VALUE, PAD) \ do { \ llvm::StringRef expected(EXPECTED, sizeof(EXPECTED)-1); \ char buf[32]; \ std::size_t size = WriteUleb128(buf, VALUE); \ llvm::StringRef actual(buf, size); \ EXPECT_EQ(expected, actual); \ } while (0) // Write ULEB128 EXPECT_ULEB128_EQ("\x00", 0, 0); EXPECT_ULEB128_EQ("\x01", 1, 0); EXPECT_ULEB128_EQ("\x3f", 63, 0); EXPECT_ULEB128_EQ("\x40", 64, 0); EXPECT_ULEB128_EQ("\x7f", 0x7f, 0); EXPECT_ULEB128_EQ("\x80\x01", 0x80, 0); EXPECT_ULEB128_EQ("\x81\x01", 0x81, 0); EXPECT_ULEB128_EQ("\x90\x01", 0x90, 0); EXPECT_ULEB128_EQ("\xff\x01", 0xff, 0); EXPECT_ULEB128_EQ("\x80\x02", 0x100, 0); EXPECT_ULEB128_EQ("\x81\x02", 0x101, 0); #undef EXPECT_ULEB128_EQ } TEST(LEB128Test, ReadUleb128) { #define EXPECT_READ_ULEB128_EQ(EXPECTED, VALUE) \ do { \ unsigned long val = 0; \ std::size_t size = ReadUleb128(VALUE, &val); \ EXPECT_EQ(sizeof(VALUE) - 1, size); \ EXPECT_EQ(EXPECTED, val); \ } while (0) // Read ULEB128 EXPECT_READ_ULEB128_EQ(0u, "\x00"); EXPECT_READ_ULEB128_EQ(1u, "\x01"); EXPECT_READ_ULEB128_EQ(63u, "\x3f"); EXPECT_READ_ULEB128_EQ(64u, "\x40"); EXPECT_READ_ULEB128_EQ(0x7fu, "\x7f"); EXPECT_READ_ULEB128_EQ(0x80u, "\x80\x01"); EXPECT_READ_ULEB128_EQ(0x81u, "\x81\x01"); EXPECT_READ_ULEB128_EQ(0x90u, "\x90\x01"); EXPECT_READ_ULEB128_EQ(0xffu, "\xff\x01"); EXPECT_READ_ULEB128_EQ(0x100u, "\x80\x02"); EXPECT_READ_ULEB128_EQ(0x101u, "\x81\x02"); EXPECT_READ_ULEB128_EQ(8320u, "\x80\xc1\x80\x80\x10"); #undef EXPECT_READ_ULEB128_EQ } TEST(LEB128Test, SizeUleb128) { // Testing Plan: // (1) 128 ^ n ............ need (n+1) bytes // (2) 128 ^ n * 64 ....... need (n+1) bytes // (3) 128 ^ (n+1) - 1 .... need (n+1) bytes EXPECT_EQ(1u, SizeUleb128(0)); // special case EXPECT_EQ(1u, SizeUleb128(0x1UL)); EXPECT_EQ(1u, SizeUleb128(0x40UL)); EXPECT_EQ(1u, SizeUleb128(0x7fUL)); EXPECT_EQ(2u, SizeUleb128(0x80UL)); EXPECT_EQ(2u, SizeUleb128(0x2000UL)); EXPECT_EQ(2u, SizeUleb128(0x3fffUL)); EXPECT_EQ(3u, SizeUleb128(0x4000UL)); EXPECT_EQ(3u, SizeUleb128(0x100000UL)); EXPECT_EQ(3u, SizeUleb128(0x1fffffUL)); EXPECT_EQ(4u, SizeUleb128(0x200000UL)); EXPECT_EQ(4u, SizeUleb128(0x8000000UL)); EXPECT_EQ(4u, SizeUleb128(0xfffffffUL)); EXPECT_EQ(5u, SizeUleb128(0x10000000UL)); EXPECT_EQ(5u, SizeUleb128(0x40000000UL)); EXPECT_EQ(5u, SizeUleb128(0x7fffffffUL)); EXPECT_EQ(5u, SizeUleb128(UINT32_MAX)); } } // namespace nt <|endoftext|>
<commit_before>// Copyright 2017, Dawid Kurek, <dawikur@gmail.com> #include "lel/lambda.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #ifdef __clang__ #define IS_TEST_SUPPORTED \ (__clang_major__ > 3) or (__clang_major__ == 3 and __clang_minor__ > 7) #else #define IS_TEST_SUPPORTED 1 #endif #if IS_TEST_SUPPORTED using namespace ::testing; class lambda_test : public ::testing::Test { protected: struct MockImpl { MOCK_CONST_METHOD0(slice0, int()); MOCK_CONST_METHOD1(slice1, int(int)); }; template <class FuncT, FuncT Func> struct MockView { MockImpl& operator()() const { static MockImpl impl; return impl; } template <class Slice, class ... Args> auto slice(Slice, Args... args) const { return (operator()().*Func)(args...); } }; }; #define MOCK(ID, ARGS) \ MockView<decltype(&MockImpl::slice##ID), &MockImpl::slice##ID> mock; \ EXPECT_CALL(mock(), slice##ID(ARGS)) TEST_F(lambda_test, when_no_ids_and_view_doesnt_have_arguments_view_is_called) { MOCK(0, ) .WillOnce(Return(5)); LeL::Lambda<LeL::Context<LeL::Identity, decltype(mock)>, LeL::Template::Box<char>> lambda(mock); auto result = lambda(); ASSERT_EQ(5, result); } TEST_F(lambda_test, when_no_ids_view_can_be_called_with_arguments) { MOCK(1, 1) .WillOnce(Return(7)); LeL::Lambda<LeL::Context<LeL::Identity, decltype(mock)>, LeL::Template::Box<char, '0'>> lambda(mock); auto result = lambda(1); ASSERT_EQ(7, result); } #undef MOCK #endif // IS_TEST_SUPPORTED #undef IS_TEST_SUPPORTED <commit_msg>Try to fix lambda tests<commit_after>// Copyright 2017, Dawid Kurek, <dawikur@gmail.com> #include "lel/lambda.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #ifdef __clang__ #define IS_TEST_SUPPORTED \ (__clang_major__ > 3) or (__clang_major__ == 3 and __clang_minor__ > 7) #else #define IS_TEST_SUPPORTED 1 #endif #if IS_TEST_SUPPORTED using namespace ::testing; class lambda_test : public ::testing::Test { protected: struct Mock { Mock(int ret) : ret{ ret } {} template <class Slice, class ... Args> auto& slice(Slice, Args... ) const { return ret; } int const ret; }; }; TEST_F(lambda_test, when_no_ids_and_view_doesnt_have_arguments_view_is_called) { LeL::Lambda<LeL::Context<LeL::Identity, Mock>, LeL::Template::Box<char>> lambda(Mock(5)); auto result = lambda(); ASSERT_EQ(5, result); } TEST_F(lambda_test, when_no_ids_view_can_be_called_with_arguments) { LeL::Lambda<LeL::Context<LeL::Identity, Mock>, LeL::Template::Box<char, '0'>> lambda(Mock(7)); auto result = lambda(1); ASSERT_EQ(7, result); } #endif // IS_TEST_SUPPORTED #undef IS_TEST_SUPPORTED <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* Patch from Trevor Smigiel */ #if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680) #define HPUXDEFINITIONS_HEADER_GUARD_1357924680 // --------------------------------------------------------------------------- // A define in the build for each project is also used to control whether // the export keyword is from the project's viewpoint or the client's. // These defines provide the platform specific keywords that they need // to do this. // --------------------------------------------------------------------------- #define XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT #define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT #define XALAN_OLD_STREAM_HEADERS #define XALAN_NO_IOSFWD #define XALAN_RTTI_AVAILABLE #define XALAN_SGI_BASED_STL #define XALAN_NO_NAMESPACES #define XALAN_XALANDOMCHAR_USHORT_MISMATCH #define XALAN_NO_STD_ALLOCATORS #define XALAN_POSIX2_AVAILABLE #define XALAN_BIG_ENDIAN #define XALAN_UNALIGNED #endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680 <commit_msg>Added #define.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* Patch from Trevor Smigiel */ #if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680) #define HPUXDEFINITIONS_HEADER_GUARD_1357924680 // --------------------------------------------------------------------------- // A define in the build for each project is also used to control whether // the export keyword is from the project's viewpoint or the client's. // These defines provide the platform specific keywords that they need // to do this. // --------------------------------------------------------------------------- #define XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT #define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT #define XALAN_OLD_STREAM_HEADERS #define XALAN_NO_IOSFWD #define XALAN_RTTI_AVAILABLE #define XALAN_SGI_BASED_STL #define XALAN_NO_NAMESPACES #define XALAN_XALANDOMCHAR_USHORT_MISMATCH #define XALAN_NO_STD_ALLOCATORS #define XALAN_POSIX2_AVAILABLE #define XALAN_BIG_ENDIAN #define XALAN_INLINE_INITIALIZATION #define XALAN_UNALIGNED #endif // HPUXDEFINITIONS_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2017 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_STATEFUL_ACTOR_HPP #define CAF_STATEFUL_ACTOR_HPP #include <new> #include <type_traits> #include "caf/fwd.hpp" #include "caf/sec.hpp" #include "caf/logger.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// An event-based actor with managed state. The state is constructed /// before `make_behavior` will get called and destroyed after the /// actor called `quit`. This state management brakes cycles and /// allows actors to automatically release ressources as soon /// as possible. template <class State, class Base = event_based_actor> class stateful_actor : public Base { public: template <class... Ts> explicit stateful_actor(actor_config& cfg, Ts&&... xs) : Base(cfg, std::forward<Ts>(xs)...), state(state_) { if (detail::is_serializable<State>::value) this->setf(Base::is_serializable_flag); } ~stateful_actor() override { // nop } /// Destroys the state of this actor (no further overriding allowed). void on_exit() final { CAF_LOG_TRACE(""); if (this->getf(Base::is_initialized_flag)) state_.~State(); } const char* name() const final { return get_name(state_); } error save_state(serializer& sink, unsigned int version) override { return serialize_state(&sink, state, version); } error load_state(deserializer& source, unsigned int version) override { return serialize_state(&source, state, version); } /// A reference to the actor's state. State& state; /// @cond PRIVATE void initialize() override { cr_state(this); Base::initialize(); } /// @endcond private: template <class Inspector, class T> auto serialize_state(Inspector* f, T& x, unsigned int) -> decltype(inspect(*f, x)) { return inspect(*f, x); } template <class T> error serialize_state(void*, T&, unsigned int) { return sec::invalid_argument; } template <class T> typename std::enable_if<std::is_constructible<State, T>::value>::type cr_state(T arg) { new (&state_) State(arg); } template <class T> typename std::enable_if<!std::is_constructible<State, T>::value>::type cr_state(T) { new (&state_) State(); } static const char* unbox_str(const char* str) { return str; } template <class U> static const char* unbox_str(const U& str) { return str.c_str(); } template <class U> typename std::enable_if<detail::has_name<U>::value, const char*>::type get_name(const U& st) const { return unbox_str(st.name); } template <class U> typename std::enable_if<!detail::has_name<U>::value, const char*>::type get_name(const U&) const { return Base::name(); } union { State state_; }; }; } // namespace caf #endif // CAF_STATEFUL_ACTOR_HPP <commit_msg>Initialize state in ctor of parent actor<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2017 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_STATEFUL_ACTOR_HPP #define CAF_STATEFUL_ACTOR_HPP #include <new> #include <type_traits> #include "caf/fwd.hpp" #include "caf/sec.hpp" #include "caf/logger.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// An event-based actor with managed state. The state is constructed /// before `make_behavior` will get called and destroyed after the /// actor called `quit`. This state management brakes cycles and /// allows actors to automatically release ressources as soon /// as possible. template <class State, class Base = event_based_actor> class stateful_actor : public Base { public: template <class... Ts> explicit stateful_actor(actor_config& cfg, Ts&&... xs) : Base(cfg, std::forward<Ts>(xs)...), state(state_) { if (detail::is_serializable<State>::value) this->setf(Base::is_serializable_flag); cr_state(this); } ~stateful_actor() override { // nop } /// Destroys the state of this actor (no further overriding allowed). void on_exit() final { CAF_LOG_TRACE(""); state_.~State(); } const char* name() const final { return get_name(state_); } error save_state(serializer& sink, unsigned int version) override { return serialize_state(&sink, state, version); } error load_state(deserializer& source, unsigned int version) override { return serialize_state(&source, state, version); } /// A reference to the actor's state. State& state; /// @cond PRIVATE void initialize() override { Base::initialize(); } /// @endcond private: template <class Inspector, class T> auto serialize_state(Inspector* f, T& x, unsigned int) -> decltype(inspect(*f, x)) { return inspect(*f, x); } template <class T> error serialize_state(void*, T&, unsigned int) { return sec::invalid_argument; } template <class T> typename std::enable_if<std::is_constructible<State, T>::value>::type cr_state(T arg) { new (&state_) State(arg); } template <class T> typename std::enable_if<!std::is_constructible<State, T>::value>::type cr_state(T) { new (&state_) State(); } static const char* unbox_str(const char* str) { return str; } template <class U> static const char* unbox_str(const U& str) { return str.c_str(); } template <class U> typename std::enable_if<detail::has_name<U>::value, const char*>::type get_name(const U& st) const { return unbox_str(st.name); } template <class U> typename std::enable_if<!detail::has_name<U>::value, const char*>::type get_name(const U&) const { return Base::name(); } union { State state_; }; }; } // namespace caf #endif // CAF_STATEFUL_ACTOR_HPP <|endoftext|>
<commit_before>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "JoystickManager.h" #include "QGCApplication.h" #include <QQmlEngine> #ifndef __mobile__ #include "JoystickSDL.h" #define __sdljoystick__ #endif #ifdef __android__ /* * Android Joystick not yet supported * #include "JoystickAndroid.h" */ #endif QGC_LOGGING_CATEGORY(JoystickManagerLog, "JoystickManagerLog") const char * JoystickManager::_settingsGroup = "JoystickManager"; const char * JoystickManager::_settingsKeyActiveJoystick = "ActiveJoystick"; JoystickManager::JoystickManager(QGCApplication* app) : QGCTool(app) , _activeJoystick(NULL) , _multiVehicleManager(NULL) { } JoystickManager::~JoystickManager() { QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { qDebug() << "Releasing joystick:" << i.key(); delete i.value(); } qDebug() << "Done"; } void JoystickManager::setToolbox(QGCToolbox *toolbox) { QGCTool::setToolbox(toolbox); _multiVehicleManager = _toolbox->multiVehicleManager(); QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); } void JoystickManager::init() { #ifdef __sdljoystick__ if (JoystickSDL::init()) { _setActiveJoystickFromSettings(); connect(&_joystickCheckTimer, &QTimer::timeout, this, &JoystickManager::_updateAvailableJoysticks); _joystickCheckTimer.start(250); } #elif defined(__android__) /* * Android Joystick not yet supported */ #endif } void JoystickManager::_setActiveJoystickFromSettings(void) { QMap<QString,Joystick*> newMap; #ifdef __sdljoystick__ // Get the latest joystick mapping newMap = JoystickSDL::discover(_multiVehicleManager); #elif defined(__android__) /* * Android Joystick not yet supported * _name2JoystickMap = JoystickAndroid::discover(_multiVehicleManager); */ #endif // Check to see if our current mapping contains any joysticks that are not in the new mapping // If so, those joysticks have been unplugged, and need to be cleaned up QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { if (!newMap.contains(i.key())) { qCDebug(JoystickManagerLog) << "Releasing joystick:" << i.key(); if (_activeJoystick && !newMap.contains(_activeJoystick->name())) { qCDebug(JoystickManagerLog) << "\twas active"; setActiveJoystick(NULL); } i.value()->wait(1000); i.value()->deleteLater(); } } _name2JoystickMap = newMap; emit availableJoysticksChanged(); if (!_name2JoystickMap.count()) { setActiveJoystick(NULL); return; } QSettings settings; settings.beginGroup(_settingsGroup); QString name = settings.value(_settingsKeyActiveJoystick).toString(); if (name.isEmpty()) { name = _name2JoystickMap.first()->name(); } setActiveJoystick(_name2JoystickMap.value(name, _name2JoystickMap.first())); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } Joystick* JoystickManager::activeJoystick(void) { return _activeJoystick; } void JoystickManager::setActiveJoystick(Joystick* joystick) { QSettings settings; if (joystick != NULL && !_name2JoystickMap.contains(joystick->name())) { qCWarning(JoystickManagerLog) << "Set active not in map" << joystick->name(); return; } if (_activeJoystick == joystick) { return; } if (_activeJoystick) { _activeJoystick->stopPolling(); } _activeJoystick = joystick; if (_activeJoystick != NULL) { qCDebug(JoystickManagerLog) << "Set active:" << _activeJoystick->name(); settings.beginGroup(_settingsGroup); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } emit activeJoystickChanged(_activeJoystick); emit activeJoystickNameChanged(_activeJoystick?_activeJoystick->name():""); } QVariantList JoystickManager::joysticks(void) { QVariantList list; foreach (const QString &name, _name2JoystickMap.keys()) { list += QVariant::fromValue(_name2JoystickMap[name]); } return list; } QStringList JoystickManager::joystickNames(void) { return _name2JoystickMap.keys(); } QString JoystickManager::activeJoystickName(void) { return _activeJoystick ? _activeJoystick->name() : QString(); } void JoystickManager::setActiveJoystickName(const QString& name) { if (!_name2JoystickMap.contains(name)) { qCWarning(JoystickManagerLog) << "Set active not in map" << name; return; } setActiveJoystick(_name2JoystickMap[name]); } void JoystickManager::_updateAvailableJoysticks(void) { #ifdef __sdljoystick__ SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: qCDebug(JoystickManagerLog) << "SDL ERROR:" << SDL_GetError(); break; case SDL_JOYDEVICEADDED: qCDebug(JoystickManagerLog) << "Joystick added:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; case SDL_JOYDEVICEREMOVED: qCDebug(JoystickManagerLog) << "Joystick removed:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; default: break; } } #elif defined(__android__) /* * Android Joystick not yet supported */ #endif } <commit_msg>Always stopPolling joystick before stopping thread<commit_after>/**************************************************************************** * * (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org> * * QGroundControl is licensed according to the terms in the file * COPYING.md in the root of the source code directory. * ****************************************************************************/ #include "JoystickManager.h" #include "QGCApplication.h" #include <QQmlEngine> #ifndef __mobile__ #include "JoystickSDL.h" #define __sdljoystick__ #endif #ifdef __android__ /* * Android Joystick not yet supported * #include "JoystickAndroid.h" */ #endif QGC_LOGGING_CATEGORY(JoystickManagerLog, "JoystickManagerLog") const char * JoystickManager::_settingsGroup = "JoystickManager"; const char * JoystickManager::_settingsKeyActiveJoystick = "ActiveJoystick"; JoystickManager::JoystickManager(QGCApplication* app) : QGCTool(app) , _activeJoystick(NULL) , _multiVehicleManager(NULL) { } JoystickManager::~JoystickManager() { QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { qDebug() << "Releasing joystick:" << i.key(); delete i.value(); } qDebug() << "Done"; } void JoystickManager::setToolbox(QGCToolbox *toolbox) { QGCTool::setToolbox(toolbox); _multiVehicleManager = _toolbox->multiVehicleManager(); QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership); } void JoystickManager::init() { #ifdef __sdljoystick__ if (JoystickSDL::init()) { _setActiveJoystickFromSettings(); connect(&_joystickCheckTimer, &QTimer::timeout, this, &JoystickManager::_updateAvailableJoysticks); _joystickCheckTimer.start(250); } #elif defined(__android__) /* * Android Joystick not yet supported */ #endif } void JoystickManager::_setActiveJoystickFromSettings(void) { QMap<QString,Joystick*> newMap; #ifdef __sdljoystick__ // Get the latest joystick mapping newMap = JoystickSDL::discover(_multiVehicleManager); #elif defined(__android__) /* * Android Joystick not yet supported * _name2JoystickMap = JoystickAndroid::discover(_multiVehicleManager); */ #endif if (_activeJoystick && !newMap.contains(_activeJoystick->name())) { qCDebug(JoystickManagerLog) << "Active joystick removed"; setActiveJoystick(NULL); } // Check to see if our current mapping contains any joysticks that are not in the new mapping // If so, those joysticks have been unplugged, and need to be cleaned up QMap<QString, Joystick*>::iterator i; for (i = _name2JoystickMap.begin(); i != _name2JoystickMap.end(); ++i) { if (!newMap.contains(i.key())) { qCDebug(JoystickManagerLog) << "Releasing joystick:" << i.key(); i.value()->stopPolling(); i.value()->wait(1000); i.value()->deleteLater(); } } _name2JoystickMap = newMap; emit availableJoysticksChanged(); if (!_name2JoystickMap.count()) { setActiveJoystick(NULL); return; } QSettings settings; settings.beginGroup(_settingsGroup); QString name = settings.value(_settingsKeyActiveJoystick).toString(); if (name.isEmpty()) { name = _name2JoystickMap.first()->name(); } setActiveJoystick(_name2JoystickMap.value(name, _name2JoystickMap.first())); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } Joystick* JoystickManager::activeJoystick(void) { return _activeJoystick; } void JoystickManager::setActiveJoystick(Joystick* joystick) { QSettings settings; if (joystick != NULL && !_name2JoystickMap.contains(joystick->name())) { qCWarning(JoystickManagerLog) << "Set active not in map" << joystick->name(); return; } if (_activeJoystick == joystick) { return; } if (_activeJoystick) { _activeJoystick->stopPolling(); } _activeJoystick = joystick; if (_activeJoystick != NULL) { qCDebug(JoystickManagerLog) << "Set active:" << _activeJoystick->name(); settings.beginGroup(_settingsGroup); settings.setValue(_settingsKeyActiveJoystick, _activeJoystick->name()); } emit activeJoystickChanged(_activeJoystick); emit activeJoystickNameChanged(_activeJoystick?_activeJoystick->name():""); } QVariantList JoystickManager::joysticks(void) { QVariantList list; foreach (const QString &name, _name2JoystickMap.keys()) { list += QVariant::fromValue(_name2JoystickMap[name]); } return list; } QStringList JoystickManager::joystickNames(void) { return _name2JoystickMap.keys(); } QString JoystickManager::activeJoystickName(void) { return _activeJoystick ? _activeJoystick->name() : QString(); } void JoystickManager::setActiveJoystickName(const QString& name) { if (!_name2JoystickMap.contains(name)) { qCWarning(JoystickManagerLog) << "Set active not in map" << name; return; } setActiveJoystick(_name2JoystickMap[name]); } void JoystickManager::_updateAvailableJoysticks(void) { #ifdef __sdljoystick__ SDL_Event event; while (SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: qCDebug(JoystickManagerLog) << "SDL ERROR:" << SDL_GetError(); break; case SDL_JOYDEVICEADDED: qCDebug(JoystickManagerLog) << "Joystick added:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; case SDL_JOYDEVICEREMOVED: qCDebug(JoystickManagerLog) << "Joystick removed:" << event.jdevice.which; _setActiveJoystickFromSettings(); break; default: break; } } #elif defined(__android__) /* * Android Joystick not yet supported */ #endif } <|endoftext|>
<commit_before>/* Copyright DaiMysha (c) 2015, All rights reserved. https://github.com/DaiMysha Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 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. 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 HOLDER 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 <iostream> #include <SFML/OpenGL.hpp> #include <DMUtils/sfml.hpp> #include <LightSystem/LightSystem.hpp> ///See if you can do somethiing with viewports instead of moving everything by hand namespace DMGDVT { namespace LS { LightSystem::LightSystem(bool isometric) : _ambiant(sf::Color::Black), _multiplyState(sf::BlendMultiply), _addState(sf::BlendAdd), _isometric(isometric), _autoDelete(true) { //this will be loaded from internal memory when lib is created //or loaded external crypted //the idea is not to allow the user to modify it if(!_lightAttenuationShader.loadFromFile("shaders/lightAttenuation.frag",sf::Shader::Fragment)) { std::cerr << "Missing light attenuation Shader. System won't work" << std::endl; } } LightSystem::~LightSystem() { reset(); } void LightSystem::addLight(Light* l) { l->preRender(&_lightAttenuationShader); l->setIsometric(_isometric);//ignore what user set before _lights.emplace_back(l); } void LightSystem::removeLight(Light* l) { _lights.remove(l); } void LightSystem::reset() { if(_autoDelete) for(Light* l : _lights) delete l; _lights.empty(); } void LightSystem::render(const sf::View& screenView, sf::RenderTarget& target) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); _sprite.setPosition(screen.left,screen.top); _renderTexture.clear(_ambiant); sf::RenderStates st(_addState); sf::Transform t; t.translate(-_sprite.getPosition()); st.transform = t; for(Light* l : _lights) { if(l->getAABB().intersects(screen)) l->render(screen,_renderTexture,&_lightAttenuationShader,st); } _renderTexture.display(); } void LightSystem::debugRender(const sf::View& screenView, sf::RenderTarget& target, int flags) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); _sprite.setPosition(screen.left,screen.top); _renderTexture.clear(_ambiant); sf::RenderStates st(_addState); sf::Transform t; t.translate(-_sprite.getPosition()); st.transform = t; for(Light* l : _lights) { if(l->getAABB().intersects(screen)) { if(flags & DEBUG_FLAGS::SHADER_OFF) l->debugRender(_renderTexture,st); else l->render(screen,_renderTexture,&_lightAttenuationShader,st); } } _renderTexture.display(); if(flags & DEBUG_FLAGS::LIGHTMAP_ONLY) target.clear(sf::Color::White); } void LightSystem::draw(const sf::View& screenView, sf::RenderTarget& target) { target.draw(_sprite,_multiplyState); } void LightSystem::drawAABB(const sf::View& screen, sf::RenderTarget& target) { drawAABB(DMUtils::sfml::getViewInWorldAABB(screen),target); } void LightSystem::drawAABB(const sf::IntRect& screen, sf::RenderTarget& target) { for(Light* l : _lights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } } void LightSystem::update() { for(Light* ls : _lights) ls->preRender(&_lightAttenuationShader); } void LightSystem::update(Light* l) { l->preRender(&_lightAttenuationShader); } void LightSystem::setAmbiantLight(sf::Color c) { _ambiant = c; } sf::Color LightSystem::getAmbiantLight() const { return _ambiant; } void LightSystem::setIsometric(bool i) { _isometric = i; for(Light* l : _lights) { l->setIsometric(_isometric); update(l); } } bool LightSystem::isIsometric() const { return _isometric; } void LightSystem::setAutoDelete(bool ad) { _autoDelete = ad; } void LightSystem::setView(const sf::View& view) { _renderTexture.create(view.getSize().x,view.getSize().y); _sprite.setTexture(_renderTexture.getTexture()); } } } <commit_msg>move the render states as static<commit_after>/* Copyright DaiMysha (c) 2015, All rights reserved. https://github.com/DaiMysha Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 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. 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 HOLDER 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 <iostream> #include <SFML/OpenGL.hpp> #include <DMUtils/sfml.hpp> #include <LightSystem/LightSystem.hpp> namespace DMGDVT { namespace LS { const sf::RenderStates LightSystem::_multiplyState(sf::BlendMultiply); const sf::RenderStates LightSystem::_addState(sf::BlendAdd); LightSystem::LightSystem(bool isometric) : _ambiant(sf::Color::Black), _isometric(isometric), _autoDelete(true) { //this will be loaded from internal memory when lib is created //or loaded external crypted //the idea is not to allow the user to modify it if(!_lightAttenuationShader.loadFromFile("shaders/lightAttenuation.frag",sf::Shader::Fragment)) { std::cerr << "Missing light attenuation Shader. System won't work" << std::endl; } } LightSystem::~LightSystem() { reset(); } void LightSystem::addLight(Light* l) { l->preRender(&_lightAttenuationShader); l->setIsometric(_isometric);//ignore what user set before _lights.emplace_back(l); } void LightSystem::removeLight(Light* l) { _lights.remove(l); } void LightSystem::reset() { if(_autoDelete) for(Light* l : _lights) delete l; _lights.empty(); } void LightSystem::render(const sf::View& screenView, sf::RenderTarget& target) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); _sprite.setPosition(screen.left,screen.top); _renderTexture.clear(_ambiant); sf::RenderStates st(_addState); sf::Transform t; t.translate(-_sprite.getPosition()); st.transform = t; for(Light* l : _lights) { if(l->getAABB().intersects(screen)) l->render(screen,_renderTexture,&_lightAttenuationShader,st); } _renderTexture.display(); } void LightSystem::debugRender(const sf::View& screenView, sf::RenderTarget& target, int flags) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); _sprite.setPosition(screen.left,screen.top); _renderTexture.clear(_ambiant); sf::RenderStates st(_addState); sf::Transform t; t.translate(-_sprite.getPosition()); st.transform = t; for(Light* l : _lights) { if(l->getAABB().intersects(screen)) { if(flags & DEBUG_FLAGS::SHADER_OFF) l->debugRender(_renderTexture,st); else l->render(screen,_renderTexture,&_lightAttenuationShader,st); } } _renderTexture.display(); if(flags & DEBUG_FLAGS::LIGHTMAP_ONLY) target.clear(sf::Color::White); } void LightSystem::draw(const sf::View& screenView, sf::RenderTarget& target) { target.draw(_sprite,_multiplyState); } void LightSystem::drawAABB(const sf::View& screen, sf::RenderTarget& target) { drawAABB(DMUtils::sfml::getViewInWorldAABB(screen),target); } void LightSystem::drawAABB(const sf::IntRect& screen, sf::RenderTarget& target) { for(Light* l : _lights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } } void LightSystem::update() { for(Light* ls : _lights) ls->preRender(&_lightAttenuationShader); } void LightSystem::update(Light* l) { l->preRender(&_lightAttenuationShader); } void LightSystem::setAmbiantLight(sf::Color c) { _ambiant = c; } sf::Color LightSystem::getAmbiantLight() const { return _ambiant; } void LightSystem::setIsometric(bool i) { _isometric = i; for(Light* l : _lights) { l->setIsometric(_isometric); update(l); } } bool LightSystem::isIsometric() const { return _isometric; } void LightSystem::setAutoDelete(bool ad) { _autoDelete = ad; } void LightSystem::setView(const sf::View& view) { _renderTexture.create(view.getSize().x,view.getSize().y); _sprite.setTexture(_renderTexture.getTexture()); } } } <|endoftext|>
<commit_before>#ifdef _SALOME # include <utilities.h> #else #ifndef __MEDMEM_UTILITIES #define __MEDMEM_UTILITIES # include <cstdlib> # include <iostream> using namespace std; /* --- INFOS is always defined (without _DEBUG_): to be used for warnings, with release version --- */ # define HEREWEARE {cout<<flush ; cerr << __FILE__ << " [" << __LINE__ << "] : " << flush ;} # define INFOS(chain) {HEREWEARE ; cerr << chain << endl ;} # define PYSCRIPT(chain) {cout<<flush ; cerr << "---PYSCRIPT--- " << chain << endl ;} /* --- To print date and time of compilation of current source on stdout --- */ # if defined ( __GNUC__ ) # define COMPILER "g++" ; # elif defined ( __sun ) # define COMPILER "CC" ; # elif defined ( __KCC ) # define COMPILER "KCC" ; # elif defined ( __PGI ) # define COMPILER "pgCC" ; # else # define COMPILER "undefined" ; # endif # ifdef INFOS_COMPILATION # undef INFOS_COMPILATION # endif # define INFOS_COMPILATION {\ cerr << flush;\ cout << __FILE__ ;\ cout << " [" << __LINE__ << "] : " ;\ cout << "COMPILED with " << COMPILER ;\ cout << ", " << __DATE__ ; \ cout << " at " << __TIME__ << endl ;\ cout << "\n\n" ;\ cout << flush ;\ } # ifdef _DEBUG_ /* --- the following MACROS are useful at debug time --- */ # define HERE {cout<<flush ; cerr << "- Trace " << __FILE__ << " [" << __LINE__ << "] : " << flush ;} # define SCRUTE(var) {HERE ; cerr << #var << "=" << var << endl ;} # define MESSAGE(chain) {HERE ; cerr << chain << endl ;} # define INTERRUPTION(code) {HERE ; cerr << "INTERRUPTION return code= " << code << endl ; exit(code) ;} # ifndef ASSERT # define ASSERT(condition) if (!(condition)){ HERE ; cerr << "CONDITION " << #condition << " NOT VERIFIED"<< endl ; INTERRUPTION(1) ;} # endif /* ASSERT */ #define REPERE {cout<<flush ; cerr << " --------------" << endl << flush ;} #define BEGIN_OF(chain) {REPERE ; HERE ; cerr << "Begin of: " << chain << endl ; REPERE ; } #define END_OF(chain) {REPERE ; HERE ; cerr << "Normal end of: " << chain << endl ; REPERE ; } # else /* ifdef _DEBUG_*/ # define HERE # define SCRUTE(var) {} # define MESSAGE(chain) {} # define INTERRUPTION(code) {} # ifndef ASSERT # define ASSERT(condition) {} # endif /* ASSERT */ #define REPERE #define BEGIN_OF(chain) {} #define END_OF(chain) {} #endif #endif #endif <commit_msg>removing this useless file.<commit_after><|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2014 Nathan Miller <Nathan.A.Mill[at]gmail.com> * * Balázs Bámer * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <QString> # include <QDir> # include <QFileInfo> # include <QLineEdit> # include <QPointer> # include <Standard_math.hxx> # include <TopoDS_Shape.hxx> # include <TopExp_Explorer.hxx> # include <Inventor/events/SoMouseButtonEvent.h> #endif #include <Base/Console.h> #include <App/Document.h> //#include <Gui/Application.h> //#include <Gui/Command.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Document.h> #include <Gui/FileDialog.h> #include <Gui/MainWindow.h> #include <Gui/Selection.h> #include <Gui/View3DInventor.h> #include <Gui/View3DInventorViewer.h> #include <Gui/WaitCursor.h> #include <App/PropertyStandard.h> #include <App/PropertyUnits.h> #include <App/PropertyLinks.h> // Nate's stuff //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //=========================================================================== // CmdSurfaceFILLING THIS IS THE SURFACE FILLING COMMAND //=========================================================================== DEF_STD_CMD(CmdSurfaceFilling); CmdSurfaceFilling::CmdSurfaceFilling() :Command("Surface_Filling") { sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Surface Filling function"); sToolTipText = QT_TR_NOOP("Fills a series of boundary curves, constraint curves and verticies with a surface."); sWhatsThis = QT_TR_NOOP("Surface Filling function"); sStatusTip = QT_TR_NOOP("Surface Filling function"); sPixmap = "Filling.svg"; sAccel = "CTRL+H"; } void CmdSurfaceFilling::activated(int iMsg) { Base::Console().Message("Hello, World!\n"); } //=========================================================================== // CmdSurfaceCut THIS IS THE SURFACE CUT COMMAND //=========================================================================== DEF_STD_CMD(CmdSurfaceCut); CmdSurfaceCut::CmdSurfaceCut() :Command("Surface_Cut") { sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Surface Cut function"); sToolTipText = QT_TR_NOOP("Cuts a Shape with another Shape.\nReturns a modified version of the first shape"); sWhatsThis = QT_TR_NOOP("Surface Cut function"); sStatusTip = QT_TR_NOOP("Surface Cut function"); sPixmap = "Cut.svg"; sAccel = "CTRL+H"; } void CmdSurfaceCut::activated(int iMsg) { /* std::vector<Gui::SelectionObject> Sel = getSelection().getSelectionEx(0, Part::Feature::getClassTypeId()); if (Sel.size() != 2) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Invalid selection"), QObject::tr("Select two shapes please.")); return; } bool askUser = false; for (std::vector<Gui::SelectionObject>::iterator it = Sel.begin(); it != Sel.end(); ++it) { App::DocumentObject* obj = it->getObject(); if (obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { const TopoDS_Shape& shape = static_cast<Part::Feature*>(obj)->Shape.getValue(); if (!PartGui::checkForSolids(shape) && !askUser) { int ret = QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Non-solids selected"), QObject::tr("The use of non-solids for boolean operations may lead to unexpected results.\n" "Do you want to continue?"), QMessageBox::Yes, QMessageBox::No); if (ret == QMessageBox::No) return; askUser = true; } } } std::string FeatName = getUniqueObjectName("Cut"); std::string BaseName = Sel[0].getFeatName(); std::string ToolName = Sel[1].getFeatName(); openCommand("Part Cut"); doCommand(Doc,"App.activeDocument().addObject(\"Part::Cut\",\"%s\")",FeatName.c_str()); doCommand(Doc,"App.activeDocument().%s.Base = App.activeDocument().%s",FeatName.c_str(),BaseName.c_str()); doCommand(Doc,"App.activeDocument().%s.Tool = App.activeDocument().%s",FeatName.c_str(),ToolName.c_str()); doCommand(Gui,"Gui.activeDocument().hide('%s')",BaseName.c_str()); doCommand(Gui,"Gui.activeDocument().hide('%s')",ToolName.c_str()); copyVisual(FeatName.c_str(), "ShapeColor", BaseName.c_str()); copyVisual(FeatName.c_str(), "DisplayMode", BaseName.c_str()); updateActive(); commitCommand();*/ } // my stuff //=========================================================================== // Surface_Bezier //=========================================================================== DEF_STD_CMD_A(CmdSurfaceBezier); CmdSurfaceBezier::CmdSurfaceBezier() :Command("Surface_Bezier") { sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Bezier"); sToolTipText = QT_TR_NOOP("Creates a surface from 2, 3 or 4 Bezier curves"); sWhatsThis = "Surface_Bezier"; sStatusTip = sToolTipText; sPixmap = "BezSurf"; } void CmdSurfaceBezier::activated(int iMsg) { // TODO filter class type std::vector<Gui::SelectionObject> Sel = getSelection().getSelectionEx(0/*, Part::Feature::getClassTypeId()*/); // TODO check if input feature count is between 2 and 4 /*if (Sel.size() < 2) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select two shapes or more, please.")); return; }*/ bool askUser = false; std::string FeatName = getUniqueObjectName("BezierSurface"); std::stringstream bezListCmd; // std::vector<std::string> tempSelNames; bezListCmd << "FreeCAD.ActiveDocument.ActiveObject.aBezList = ["; for (std::vector<Gui::SelectionObject>::iterator it = Sel.begin(); it != Sel.end(); ++it) { App::DocumentObject* obj = it->getObject(); // TODO check object types /*if (obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { const TopoDS_Shape& shape = static_cast<Part::Feature*>(obj)->Shape.getValue(); if (!PartGui::checkForSolids(shape) && !askUser) { int ret = QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Non-solids selected"), QObject::tr("The use of non-solids for boolean operations may lead to unexpected results.\n" "Do you want to continue?"), QMessageBox::Yes, QMessageBox::No); if (ret == QMessageBox::No) return; askUser = true; }*/ bezListCmd << "FreeCAD.ActiveDocument." << it->getFeatName() << ", "; // tempSelNames.push_back(it->getFeatName()); //} } bezListCmd << "]"; openCommand("Create Bezier surface"); doCommand(Doc,"FreeCAD.ActiveDocument.addObject(\"Surface::BezSurf\",\"%s\")", FeatName.c_str()); doCommand(Doc, "FreeCAD.ActiveDocument.ActiveObject.filltype=1"); // TODO ask filltype from user and check it runCommand(Doc, bezListCmd.str().c_str()); updateActive(); commitCommand(); } bool CmdSurfaceBezier::isActive(void) { return true; //TODO check availability getSelection().countObjectsOfType(Part::Feature::getClassTypeId())>=2; } void CreateSurfaceCommands(void) { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSurfaceFilling()); rcCmdMgr.addCommand(new CmdSurfaceCut()); rcCmdMgr.addCommand(new CmdSurfaceBezier()); } <commit_msg>Specify edge name correctly<commit_after>/*************************************************************************** * Copyright (c) 2014 Nathan Miller <Nathan.A.Mill[at]gmail.com> * * Balázs Bámer * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <QString> # include <QDir> # include <QFileInfo> # include <QLineEdit> # include <QPointer> # include <Standard_math.hxx> # include <TopoDS_Shape.hxx> # include <TopExp_Explorer.hxx> # include <Inventor/events/SoMouseButtonEvent.h> #endif #include <Base/Console.h> #include <App/Document.h> //#include <Gui/Application.h> //#include <Gui/Command.h> #include <Gui/Application.h> #include <Gui/BitmapFactory.h> #include <Gui/Command.h> #include <Gui/Control.h> #include <Gui/Document.h> #include <Gui/FileDialog.h> #include <Gui/MainWindow.h> #include <Gui/Selection.h> #include <Gui/View3DInventor.h> #include <Gui/View3DInventorViewer.h> #include <Gui/WaitCursor.h> #include <App/PropertyStandard.h> #include <App/PropertyUnits.h> #include <App/PropertyLinks.h> // Nate's stuff //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //=========================================================================== // CmdSurfaceFILLING THIS IS THE SURFACE FILLING COMMAND //=========================================================================== DEF_STD_CMD(CmdSurfaceFilling); CmdSurfaceFilling::CmdSurfaceFilling() :Command("Surface_Filling") { sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Surface Filling function"); sToolTipText = QT_TR_NOOP("Fills a series of boundary curves, constraint curves and verticies with a surface."); sWhatsThis = QT_TR_NOOP("Surface Filling function"); sStatusTip = QT_TR_NOOP("Surface Filling function"); sPixmap = "Filling.svg"; sAccel = "CTRL+H"; } void CmdSurfaceFilling::activated(int iMsg) { Base::Console().Message("Hello, World!\n"); } //=========================================================================== // CmdSurfaceCut THIS IS THE SURFACE CUT COMMAND //=========================================================================== DEF_STD_CMD(CmdSurfaceCut); CmdSurfaceCut::CmdSurfaceCut() :Command("Surface_Cut") { sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Surface Cut function"); sToolTipText = QT_TR_NOOP("Cuts a Shape with another Shape.\nReturns a modified version of the first shape"); sWhatsThis = QT_TR_NOOP("Surface Cut function"); sStatusTip = QT_TR_NOOP("Surface Cut function"); sPixmap = "Cut.svg"; sAccel = "CTRL+H"; } void CmdSurfaceCut::activated(int iMsg) { /* std::vector<Gui::SelectionObject> Sel = getSelection().getSelectionEx(0, Part::Feature::getClassTypeId()); if (Sel.size() != 2) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Invalid selection"), QObject::tr("Select two shapes please.")); return; } bool askUser = false; for (std::vector<Gui::SelectionObject>::iterator it = Sel.begin(); it != Sel.end(); ++it) { App::DocumentObject* obj = it->getObject(); if (obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { const TopoDS_Shape& shape = static_cast<Part::Feature*>(obj)->Shape.getValue(); if (!PartGui::checkForSolids(shape) && !askUser) { int ret = QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Non-solids selected"), QObject::tr("The use of non-solids for boolean operations may lead to unexpected results.\n" "Do you want to continue?"), QMessageBox::Yes, QMessageBox::No); if (ret == QMessageBox::No) return; askUser = true; } } } std::string FeatName = getUniqueObjectName("Cut"); std::string BaseName = Sel[0].getFeatName(); std::string ToolName = Sel[1].getFeatName(); openCommand("Part Cut"); doCommand(Doc,"App.activeDocument().addObject(\"Part::Cut\",\"%s\")",FeatName.c_str()); doCommand(Doc,"App.activeDocument().%s.Base = App.activeDocument().%s",FeatName.c_str(),BaseName.c_str()); doCommand(Doc,"App.activeDocument().%s.Tool = App.activeDocument().%s",FeatName.c_str(),ToolName.c_str()); doCommand(Gui,"Gui.activeDocument().hide('%s')",BaseName.c_str()); doCommand(Gui,"Gui.activeDocument().hide('%s')",ToolName.c_str()); copyVisual(FeatName.c_str(), "ShapeColor", BaseName.c_str()); copyVisual(FeatName.c_str(), "DisplayMode", BaseName.c_str()); updateActive(); commitCommand();*/ } // my stuff //=========================================================================== // Surface_Bezier //=========================================================================== DEF_STD_CMD_A(CmdSurfaceBezier); CmdSurfaceBezier::CmdSurfaceBezier() :Command("Surface_Bezier") { sAppModule = "Surface"; sGroup = QT_TR_NOOP("Surface"); sMenuText = QT_TR_NOOP("Bezier"); sToolTipText = QT_TR_NOOP("Creates a surface from 2, 3 or 4 Bezier curves"); sWhatsThis = "Surface_Bezier"; sStatusTip = sToolTipText; sPixmap = "BezSurf"; } void CmdSurfaceBezier::activated(int iMsg) { // TODO filter class type std::vector<Gui::SelectionObject> Sel = getSelection().getSelectionEx(0/*, Part::Feature::getClassTypeId()*/); // TODO check if input feature count is between 2 and 4 /*if (Sel.size() < 2) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select two shapes or more, please.")); return; }*/ bool askUser = false; std::string FeatName = getUniqueObjectName("BezierSurface"); std::stringstream bezListCmd; // std::vector<std::string> tempSelNames; bezListCmd << "FreeCAD.ActiveDocument.ActiveObject.aBezList = ["; for (std::vector<Gui::SelectionObject>::iterator it = Sel.begin(); it != Sel.end(); ++it) { App::DocumentObject* obj = it->getObject(); // TODO check object types /*if (obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { const TopoDS_Shape& shape = static_cast<Part::Feature*>(obj)->Shape.getValue(); if (!PartGui::checkForSolids(shape) && !askUser) { int ret = QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Non-solids selected"), QObject::tr("The use of non-solids for boolean operations may lead to unexpected results.\n" "Do you want to continue?"), QMessageBox::Yes, QMessageBox::No); if (ret == QMessageBox::No) return; askUser = true; }*/ bezListCmd << "(App.activeDocument()." << it->getFeatName() << ", \'Edge1\'),"; // tempSelNames.push_back(it->getFeatName()); //} } bezListCmd << "]"; openCommand("Create Bezier surface"); doCommand(Doc,"FreeCAD.ActiveDocument.addObject(\"Surface::BezSurf\",\"%s\")", FeatName.c_str()); doCommand(Doc, "FreeCAD.ActiveDocument.ActiveObject.filltype=1"); // TODO ask filltype from user and check it runCommand(Doc, bezListCmd.str().c_str()); updateActive(); commitCommand(); } bool CmdSurfaceBezier::isActive(void) { return true; //TODO check availability getSelection().countObjectsOfType(Part::Feature::getClassTypeId())>=2; } void CreateSurfaceCommands(void) { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdSurfaceFilling()); rcCmdMgr.addCommand(new CmdSurfaceCut()); rcCmdMgr.addCommand(new CmdSurfaceBezier()); } <|endoftext|>
<commit_before> #include "../src/ReplyImpl.h" #include "UnitTest++/UnitTest++.h" using namespace std; using namespace restc_cpp; namespace restc_cpp{ namespace unittests { class TestReply : public ReplyImpl { public: using test_buffers_t = std::list<std::string>; TestReply(Context& ctx, RestClient& owner, test_buffers_t& buffers) : ReplyImpl(nullptr, ctx, owner), test_buffers_{buffers} { next_buffer_ = test_buffers_.begin(); } size_t AsyncReadSome(boost::asio::mutable_buffers_1 read_buffers) override { if (next_buffer_ == test_buffers_.end()) return 0; assert(boost::asio::buffer_size(read_buffers) >= next_buffer_->size()); memcpy(boost::asio::buffer_cast<char *>(read_buffers), &(*next_buffer_)[0], next_buffer_->size()); auto rval = next_buffer_->size(); ++next_buffer_; return rval; } void SimulateServerReply() { StartReceiveFromServer(); } private: test_buffers_t& test_buffers_; test_buffers_t::iterator next_buffer_; }; } // unittests } // restc_cpp TEST(TestFragmentedReply) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "X-Powered-By: Express\r\n" "Vary: Origin, Accept-Encoding\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n" "Expires: -1\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Content-Length: 0\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); CHECK_EQUAL("keep-alive", *reply.GetHeader("Connection")); CHECK_EQUAL("0", *reply.GetHeader("Content-Length")); }).wait(); } int main(int, const char *[]) { return UnitTest::RunAllTests(); } <commit_msg>Added more unit-tetst for received data (header parssing, chunk parsing)<commit_after> #include "../src/ReplyImpl.h" #include "UnitTest++/UnitTest++.h" using namespace std; using namespace restc_cpp; namespace restc_cpp{ namespace unittests { class TestReply : public ReplyImpl { public: using test_buffers_t = std::list<std::string>; TestReply(Context& ctx, RestClient& owner, test_buffers_t& buffers) : ReplyImpl(nullptr, ctx, owner), test_buffers_{buffers} { next_buffer_ = test_buffers_.begin(); } size_t AsyncReadSome(boost::asio::mutable_buffers_1 read_buffers) override { if (next_buffer_ == test_buffers_.end()) return 0; assert(boost::asio::buffer_size(read_buffers) >= next_buffer_->size()); const boost::string_ref ret{*next_buffer_}; memcpy(boost::asio::buffer_cast<char *>(read_buffers), ret.data(), ret.size()); // clog << "----- Returning " << ret.size() << " bytes ----" << endl // << ret // << "------------" << endl; auto rval = next_buffer_->size(); ++next_buffer_; return rval; } void SimulateServerReply() { StartReceiveFromServer(); } private: test_buffers_t& test_buffers_; test_buffers_t::iterator next_buffer_; }; } // unittests } // restc_cpp TEST(TestSimpleHeader) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "X-Powered-By: Express\r\n" "Vary: Origin, Accept-Encoding\r\n" "Cache-Control: no-cache\r\n" "Pragma: no-cache\r\n" "Expires: -1\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Content-Length: 0\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); CHECK_EQUAL("keep-alive", *reply.GetHeader("Connection")); CHECK_EQUAL("0", *reply.GetHeader("Content-Length")); }).wait(); } TEST(TestSimpleSegmentedHeader) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n"); buffer.push_back("Server: Cowboy\r\n"); buffer.push_back("Connection: keep-alive\r\n"); buffer.push_back("X-Powered-By: Express\r\n"); buffer.push_back("Vary: Origin, Accept-Encoding\r\n"); buffer.push_back("Cache-Control: no-cache\r\n"); buffer.push_back("Pragma: no-cache\r\n"); buffer.push_back("Expires: -1\r\n"); buffer.push_back("Content-Type: application/json; charset=utf-8\r\n"); buffer.push_back("Content-Length: 0\r\n"); buffer.push_back("Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n"); buffer.push_back("\r\n"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); CHECK_EQUAL("keep-alive", *reply.GetHeader("Connection")); CHECK_EQUAL("0", *reply.GetHeader("Content-Length")); }).wait(); } TEST(TestSimpleVerySegmentedHeader) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\nSer"); buffer.push_back("ver: Cowboy\r\n"); buffer.push_back("Connection: keep-alive\r"); buffer.push_back("\nX-Powered-By: Express\r\nV"); buffer.push_back("ary"); buffer.push_back(": Origin, Accept-Encoding\r\nCache-Control: no-cache\r\n"); buffer.push_back("Pragma: no-cache\r\n"); buffer.push_back("Expires: -1\r\n"); buffer.push_back("Content-Type: application/json; charset=utf-8\r\n"); buffer.push_back("Content-Length: 0\r\n"); buffer.push_back("Date: Thu, 21 Apr 2016 13:44:36 GMT"); buffer.push_back("\r"); buffer.push_back("\n"); buffer.push_back("\r"); buffer.push_back("\n"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); CHECK_EQUAL("keep-alive", *reply.GetHeader("Connection")); CHECK_EQUAL("0", *reply.GetHeader("Content-Length")); }).wait(); } TEST(TestSimpleBody) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "Vary: Origin, Accept-Encoding\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Content-Length: 10\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n" "1234567890"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); auto body = reply.GetBodyAsString(); CHECK_EQUAL("Cowboy", *reply.GetHeader("Server")); CHECK_EQUAL("10", *reply.GetHeader("Content-Length")); CHECK_EQUAL(10, (int)body.size()); }).wait(); } TEST(TestSimpleBody2) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "Vary: Origin, Accept-Encoding\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Content-Length: 10\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n"); buffer.push_back("1234567890"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); auto body = reply.GetBodyAsString(); CHECK_EQUAL("Cowboy", *reply.GetHeader("Server")); CHECK_EQUAL("10", *reply.GetHeader("Content-Length")); CHECK_EQUAL(10, (int)body.size()); }).wait(); } TEST(TestSimpleBody3) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "Vary: Origin, Accept-Encoding\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Content-Length: 10\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n"); buffer.push_back("1234567"); buffer.push_back("890"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); auto body = reply.GetBodyAsString(); CHECK_EQUAL("Cowboy", *reply.GetHeader("Server")); CHECK_EQUAL("10", *reply.GetHeader("Content-Length")); CHECK_EQUAL(10, (int)body.size()); }).wait(); } TEST(TestSimpleBody4) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "Vary: Origin, Accept-Encoding\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Content-Length: 10\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n12"); buffer.push_back("34567"); buffer.push_back("890"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); auto body = reply.GetBodyAsString(); CHECK_EQUAL("Cowboy", *reply.GetHeader("Server")); CHECK_EQUAL("10", *reply.GetHeader("Content-Length")); CHECK_EQUAL(10, (int)body.size()); }).wait(); } TEST(TestChunkedBody) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "Vary: Origin, Accept-Encoding\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Transfer-Encoding: chunked\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n" "4\r\nWiki\r\n5\r\npedia\r\nE\r\n in\r\n\r\nchunks." "\r\n0\r\n\r\n"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); auto body = reply.GetBodyAsString(); CHECK_EQUAL("Cowboy", *reply.GetHeader("Server")); CHECK_EQUAL("chunked", *reply.GetHeader("Transfer-Encoding")); CHECK_EQUAL((0x4 + 0x5 + 0xE), (int)body.size()); }).wait(); } TEST(TestChunkedBody2) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "Vary: Origin, Accept-Encoding\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Transfer-Encoding: chunked\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n"); buffer.push_back("4\r\nWiki\r\n"); buffer.push_back("5\r\npedia\r\n"); buffer.push_back("E\r\n in\r\n\r\nchunks.\r\n"); buffer.push_back("0\r\n\r\n"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); auto body = reply.GetBodyAsString(); CHECK_EQUAL("Cowboy", *reply.GetHeader("Server")); CHECK_EQUAL("chunked", *reply.GetHeader("Transfer-Encoding")); CHECK_EQUAL((0x4 + 0x5 + 0xE), (int)body.size()); }).wait(); } TEST(TestChunkedBody4) { ::restc_cpp::unittests::TestReply::test_buffers_t buffer; buffer.push_back("HTTP/1.1 200 OK\r\n" "Server: Cowboy\r\n" "Connection: keep-alive\r\n" "Vary: Origin, Accept-Encoding\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Transfer-Encoding: chunked\r\n" "Date: Thu, 21 Apr 2016 13:44:36 GMT\r\n" "\r\n"); buffer.push_back("4\r\nW"); buffer.push_back("iki\r\n5\r\npedi"); buffer.push_back("a\r\nE\r\n in\r\n\r\nchunks.\r"); buffer.push_back("\n"); buffer.push_back("0"); buffer.push_back("\r"); buffer.push_back("\n"); buffer.push_back("\r"); buffer.push_back("\n"); auto rest_client = RestClient::Create(); rest_client->ProcessWithPromise([&](Context& ctx) { ::restc_cpp::unittests::TestReply reply(ctx, *rest_client, buffer); reply.SimulateServerReply(); auto body = reply.GetBodyAsString(); CHECK_EQUAL("Cowboy", *reply.GetHeader("Server")); CHECK_EQUAL("chunked", *reply.GetHeader("Transfer-Encoding")); CHECK_EQUAL((0x4 + 0x5 + 0xE), (int)body.size()); }).wait(); } int main(int, const char *[]) { return UnitTest::RunAllTests(); } <|endoftext|>
<commit_before>#ifndef UTILS_URI_TEST_HPP #define UTILS_URI_TEST_HPP #include <io/uri.hpp> using namespace Arabica::io; class URITest : public TestCase { public: URITest(std::string name) : TestCase(name) { } // URITest void test1() { URI u("woo"); assertEquals("woo", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("woo", u.as_string()); } // test1 void test2() { URI u("woo.xml"); assertEquals("woo.xml", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("woo.xml", u.as_string()); } // test2 void test3() { URI u("woo/woo.xml"); assertEquals("woo/woo.xml", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("woo/woo.xml", u.as_string()); } // test3 void test4() { URI u("/woo/woo.xml"); assertEquals("/woo/woo.xml", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("/woo/woo.xml", u.as_string()); } // test4 void test5() { URI u("http://localhost/woo/woo.xml"); assertEquals("/woo/woo.xml", u.path()); assertEquals("localhost", u.host()); assertEquals("http", u.scheme()); assertEquals("80", u.port()); assertEquals("http://localhost/woo/woo.xml", u.as_string()); } void test6() { URI u("http://localhost:8080/woo/woo.xml"); assertEquals("/woo/woo.xml", u.path()); assertEquals("localhost", u.host()); assertEquals("http", u.scheme()); assertEquals("8080", u.port()); assertEquals("http://localhost:8080/woo/woo.xml", u.as_string()); } void test7() { URI u("http://www.jezuk.co.uk/arabica/news"); assertEquals("/arabica/news", u.path()); assertEquals("www.jezuk.co.uk", u.host()); assertEquals("http", u.scheme()); assertEquals("80", u.port()); assertEquals("http://www.jezuk.co.uk/arabica/news", u.as_string()); } void test8() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); assertEquals("/arabica/news", u.path()); assertEquals("www.jezuk.co.uk", u.host()); assertEquals("http", u.scheme()); assertEquals("8000", u.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/news", u.as_string()); } void test9() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "http://localhost/nobby"); assertEquals("/nobby", r.path()); assertEquals("localhost", r.host()); assertEquals("http", r.scheme()); assertEquals("80", r.port()); assertEquals("http://localhost/nobby", r.as_string()); } // test9 void test10() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "http://localhost/"); assertEquals("/", r.path()); assertEquals("localhost", r.host()); assertEquals("http", r.scheme()); assertEquals("80", r.port()); assertEquals("http://localhost/", r.as_string()); } // test10 void test11() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "/trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test11 void test12() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "trouser/press"); assertEquals("/arabica/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/trouser/press", r.as_string()); } // test12 void test13() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "./trouser/press"); assertEquals("/arabica/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/trouser/press", r.as_string()); } // test13 void test14() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "../trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test14 void test15() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "/trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test15 void test16() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "trouser/press"); assertEquals("/arabica/news/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/news/trouser/press", r.as_string()); } // test16 void test17() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "./trouser/press"); assertEquals("/arabica/news/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/news/trouser/press", r.as_string()); } // test17 void test18() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "../trouser/press"); assertEquals("/arabica/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/trouser/press", r.as_string()); } // test18 void test19() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "../../trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); } // test19 void test20() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "../../../trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test20 void test21() { URI e("http://www.jezuk.co.uk/arabica/news"); URI u; u = e; assertEquals("/arabica/news", u.path()); assertEquals("www.jezuk.co.uk", u.host()); assertEquals("http", u.scheme()); assertEquals("80", u.port()); } // test21 }; // class URITest TestSuite* URITest_suite() { TestSuite* suiteOfTests = new TestSuite(); suiteOfTests->addTest(new TestCaller<URITest>("test1", &URITest::test1)); suiteOfTests->addTest(new TestCaller<URITest>("test2", &URITest::test2)); suiteOfTests->addTest(new TestCaller<URITest>("test3", &URITest::test3)); suiteOfTests->addTest(new TestCaller<URITest>("test4", &URITest::test4)); suiteOfTests->addTest(new TestCaller<URITest>("test5", &URITest::test5)); suiteOfTests->addTest(new TestCaller<URITest>("test6", &URITest::test6)); suiteOfTests->addTest(new TestCaller<URITest>("test7", &URITest::test7)); suiteOfTests->addTest(new TestCaller<URITest>("test8", &URITest::test8)); suiteOfTests->addTest(new TestCaller<URITest>("test9", &URITest::test9)); suiteOfTests->addTest(new TestCaller<URITest>("test10", &URITest::test10)); suiteOfTests->addTest(new TestCaller<URITest>("test11", &URITest::test11)); suiteOfTests->addTest(new TestCaller<URITest>("test12", &URITest::test12)); suiteOfTests->addTest(new TestCaller<URITest>("test13", &URITest::test13)); suiteOfTests->addTest(new TestCaller<URITest>("test14", &URITest::test14)); suiteOfTests->addTest(new TestCaller<URITest>("test15", &URITest::test15)); suiteOfTests->addTest(new TestCaller<URITest>("test16", &URITest::test16)); suiteOfTests->addTest(new TestCaller<URITest>("test17", &URITest::test17)); suiteOfTests->addTest(new TestCaller<URITest>("test18", &URITest::test18)); suiteOfTests->addTest(new TestCaller<URITest>("test19", &URITest::test19)); suiteOfTests->addTest(new TestCaller<URITest>("test20", &URITest::test20)); suiteOfTests->addTest(new TestCaller<URITest>("test21", &URITest::test21)); return suiteOfTests; } // URITest_suite #endif <commit_msg>lots more URI tests, for cases wth leading ../<commit_after>#ifndef UTILS_URI_TEST_HPP #define UTILS_URI_TEST_HPP #include <io/uri.hpp> using namespace Arabica::io; class URITest : public TestCase { public: URITest(std::string name) : TestCase(name) { } // URITest void test1() { URI u("woo"); assertEquals("woo", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("woo", u.as_string()); } // test1 void test2() { URI u("woo.xml"); assertEquals("woo.xml", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("woo.xml", u.as_string()); } // test2 void test3() { URI u("woo/woo.xml"); assertEquals("woo/woo.xml", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("woo/woo.xml", u.as_string()); } // test3 void test4() { URI u("/woo/woo.xml"); assertEquals("/woo/woo.xml", u.path()); assertEquals("", u.host()); assertEquals("", u.scheme()); assertEquals("0", u.port()); assertEquals("/woo/woo.xml", u.as_string()); } // test4 void test5() { URI u("http://localhost/woo/woo.xml"); assertEquals("/woo/woo.xml", u.path()); assertEquals("localhost", u.host()); assertEquals("http", u.scheme()); assertEquals("80", u.port()); assertEquals("http://localhost/woo/woo.xml", u.as_string()); } void test6() { URI u("http://localhost:8080/woo/woo.xml"); assertEquals("/woo/woo.xml", u.path()); assertEquals("localhost", u.host()); assertEquals("http", u.scheme()); assertEquals("8080", u.port()); assertEquals("http://localhost:8080/woo/woo.xml", u.as_string()); } void test7() { URI u("http://www.jezuk.co.uk/arabica/news"); assertEquals("/arabica/news", u.path()); assertEquals("www.jezuk.co.uk", u.host()); assertEquals("http", u.scheme()); assertEquals("80", u.port()); assertEquals("http://www.jezuk.co.uk/arabica/news", u.as_string()); } void test8() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); assertEquals("/arabica/news", u.path()); assertEquals("www.jezuk.co.uk", u.host()); assertEquals("http", u.scheme()); assertEquals("8000", u.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/news", u.as_string()); } void test9() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "http://localhost/nobby"); assertEquals("/nobby", r.path()); assertEquals("localhost", r.host()); assertEquals("http", r.scheme()); assertEquals("80", r.port()); assertEquals("http://localhost/nobby", r.as_string()); } // test9 void test10() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "http://localhost/"); assertEquals("/", r.path()); assertEquals("localhost", r.host()); assertEquals("http", r.scheme()); assertEquals("80", r.port()); assertEquals("http://localhost/", r.as_string()); } // test10 void test11() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "/trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test11 void test12() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "trouser/press"); assertEquals("/arabica/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/trouser/press", r.as_string()); } // test12 void test13() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "./trouser/press"); assertEquals("/arabica/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/trouser/press", r.as_string()); } // test13 void test14() { URI u("http://www.jezuk.co.uk:8000/arabica/news"); URI r(u, "../trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test14 void test15() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "/trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test15 void test16() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "trouser/press"); assertEquals("/arabica/news/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/news/trouser/press", r.as_string()); } // test16 void test17() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "./trouser/press"); assertEquals("/arabica/news/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/news/trouser/press", r.as_string()); } // test17 void test18() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "../trouser/press"); assertEquals("/arabica/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/arabica/trouser/press", r.as_string()); } // test18 void test19() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "../../trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); } // test19 void test20() { URI u("http://www.jezuk.co.uk:8000/arabica/news/"); URI r(u, "../../../trouser/press"); assertEquals("/trouser/press", r.path()); assertEquals("www.jezuk.co.uk", r.host()); assertEquals("http", r.scheme()); assertEquals("8000", r.port()); assertEquals("http://www.jezuk.co.uk:8000/trouser/press", r.as_string()); } // test20 void test21() { URI e("http://www.jezuk.co.uk/arabica/news"); URI u; u = e; assertEquals("/arabica/news", u.path()); assertEquals("www.jezuk.co.uk", u.host()); assertEquals("http", u.scheme()); assertEquals("80", u.port()); } // test21 void test22() { URI e("/one/two/three/four"); URI r(e, "five"); assertEquals("/one/two/three/five", r.path()); } // test22 void test23() { URI e("/one/two/three/four"); URI r(e, "../five"); assertEquals("/one/two/five", r.path()); } // test23 void test24() { URI e("/one/two/three/four"); URI r(e, "../../five"); assertEquals("/one/five", r.path()); } // test24 void test25() { URI e("../one/two/three/four"); URI r(e, "../../five"); assertEquals("../one/five", r.path()); } // test25 void test26() { URI e("../../one/two/three/four"); URI r(e, "../../five"); assertEquals("../../one/five", r.path()); } // test26 void test27() { URI e("../../one/two/three/four"); URI r(e, "../five"); assertEquals("../../one/two/five", r.path()); } // test27 void test28() { URI e("../../one/two/three/four"); URI r(e, "five"); assertEquals("../../one/two/three/five", r.path()); } // test28 void test29() { URI e("../../../one/two/three/four"); URI r(e, "../../five"); assertEquals("../../../one/five", r.path()); } // test26 void test30() { URI e("../../../one/two/three/four"); URI r(e, "../five"); assertEquals("../../../one/two/five", r.path()); } // test30 void test31() { URI e("../../../one/two/three/four"); URI r(e, "five"); assertEquals("../../../one/two/three/five", r.path()); } // test31 }; // class URITest TestSuite* URITest_suite() { TestSuite* suiteOfTests = new TestSuite(); suiteOfTests->addTest(new TestCaller<URITest>("test1", &URITest::test1)); suiteOfTests->addTest(new TestCaller<URITest>("test2", &URITest::test2)); suiteOfTests->addTest(new TestCaller<URITest>("test3", &URITest::test3)); suiteOfTests->addTest(new TestCaller<URITest>("test4", &URITest::test4)); suiteOfTests->addTest(new TestCaller<URITest>("test5", &URITest::test5)); suiteOfTests->addTest(new TestCaller<URITest>("test6", &URITest::test6)); suiteOfTests->addTest(new TestCaller<URITest>("test7", &URITest::test7)); suiteOfTests->addTest(new TestCaller<URITest>("test8", &URITest::test8)); suiteOfTests->addTest(new TestCaller<URITest>("test9", &URITest::test9)); suiteOfTests->addTest(new TestCaller<URITest>("test10", &URITest::test10)); suiteOfTests->addTest(new TestCaller<URITest>("test11", &URITest::test11)); suiteOfTests->addTest(new TestCaller<URITest>("test12", &URITest::test12)); suiteOfTests->addTest(new TestCaller<URITest>("test13", &URITest::test13)); suiteOfTests->addTest(new TestCaller<URITest>("test14", &URITest::test14)); suiteOfTests->addTest(new TestCaller<URITest>("test15", &URITest::test15)); suiteOfTests->addTest(new TestCaller<URITest>("test16", &URITest::test16)); suiteOfTests->addTest(new TestCaller<URITest>("test17", &URITest::test17)); suiteOfTests->addTest(new TestCaller<URITest>("test18", &URITest::test18)); suiteOfTests->addTest(new TestCaller<URITest>("test19", &URITest::test19)); suiteOfTests->addTest(new TestCaller<URITest>("test20", &URITest::test20)); suiteOfTests->addTest(new TestCaller<URITest>("test21", &URITest::test21)); suiteOfTests->addTest(new TestCaller<URITest>("test22", &URITest::test22)); suiteOfTests->addTest(new TestCaller<URITest>("test23", &URITest::test23)); suiteOfTests->addTest(new TestCaller<URITest>("test24", &URITest::test24)); suiteOfTests->addTest(new TestCaller<URITest>("test25", &URITest::test25)); suiteOfTests->addTest(new TestCaller<URITest>("test26", &URITest::test26)); suiteOfTests->addTest(new TestCaller<URITest>("test27", &URITest::test27)); suiteOfTests->addTest(new TestCaller<URITest>("test28", &URITest::test28)); suiteOfTests->addTest(new TestCaller<URITest>("test29", &URITest::test29)); suiteOfTests->addTest(new TestCaller<URITest>("test30", &URITest::test30)); suiteOfTests->addTest(new TestCaller<URITest>("test31", &URITest::test31)); return suiteOfTests; } // URITest_suite #endif <|endoftext|>
<commit_before>#include "ArduinoRobot.h" #include "SquawkSD.h" #include "Fat16.h" SQUAWK_CONSTRUCT_ISR(SQUAWK_PWM_PIN5); void RobotControl::beginSpeaker(uint16_t frequency){ SquawkSynth::begin(frequency); SquawkSynth::play(); osc[2].vol = 0x7F; } void RobotControl::playNote(byte period, word length, char modifier) { // Modifier . makes note length 2/3 if(modifier == '.') length = (length * 2) / 3; // Set up the play frequency, 352800 is [sample_rate]=44100 * [tuning]=8.0 osc[2].freq = 352800 / period; // Delay, silence, delay delay(length); osc[2].freq = 0; delay(length); } void RobotControl::playMelody(char* script){ // Find length of play string word length = strlen(script); // Set the default note time word time = 500; // Loop through each character in the play string for(int n = 0; n < length; n++) { // Fetch the character AFTER the current one - it may contain a modifier char modifier = script[n + 1]; // Fetch the current character and branch accordingly switch(script[n]) { // Notes case 'c': playNote(214, time, modifier); break; // Play a C case 'C': playNote(202, time, modifier); break; // Play a C# case 'd': playNote(190, time, modifier); break; // Play a D case 'D': playNote(180, time, modifier); break; // Play a D# case 'e': playNote(170, time, modifier); break; // Play an F case 'f': playNote(160, time, modifier); break; // Play an F case 'F': playNote(151, time, modifier); break; // Play an F# case 'g': playNote(143, time, modifier); break; // Play a G case 'G': playNote(135, time, modifier); break; // Play a G# case 'a': playNote(127, time, modifier); break; // Play an A case 'A': playNote(120, time, modifier); break; // Play an A# case 'b': playNote(113, time, modifier); break; // Play a B // Delay case '-': playNote(0, time, modifier); break; // Play a quiet note // Note lengths case '1': time = 1000; break; // Full note case '2': time = 500; break; // Half note case '4': time = 250; break; // Quarter note case '8': time = 50; break; // Eigth note // Modifier '.' makes note length 2/3 } } } void RobotControl::beep(int beep_length){ char scr1[]="8F"; char scr2[]="8Fe"; char scr3[]="1F"; switch (beep_length) { case BEEP_SIMPLE: default: playMelody(scr1); break; case BEEP_DOUBLE: playMelody(scr2); break; case BEEP_LONG: playMelody(scr3); } } void RobotControl::tempoWrite(int tempo){ SquawkSynthSD::tempo(tempo); } void RobotControl::tuneWrite(float tune){ SquawkSynthSD::tune(tune); } void RobotControl::playFile(char* filename){ melody.open(filename,O_READ); SquawkSynthSD::play(melody); } void RobotControl::stopPlayFile(){ melody.close(); }<commit_msg>Fixed error in comment<commit_after>#include "ArduinoRobot.h" #include "SquawkSD.h" #include "Fat16.h" SQUAWK_CONSTRUCT_ISR(SQUAWK_PWM_PIN5); void RobotControl::beginSpeaker(uint16_t frequency){ SquawkSynth::begin(frequency); SquawkSynth::play(); osc[2].vol = 0x7F; } void RobotControl::playNote(byte period, word length, char modifier) { // Modifier . makes note length 2/3 if(modifier == '.') length = (length * 2) / 3; // Set up the play frequency, 352800 is [sample_rate]=44100 * [tuning]=8.0 osc[2].freq = 352800 / period; // Delay, silence, delay delay(length); osc[2].freq = 0; delay(length); } void RobotControl::playMelody(char* script){ // Find length of play string word length = strlen(script); // Set the default note time word time = 500; // Loop through each character in the play string for(int n = 0; n < length; n++) { // Fetch the character AFTER the current one - it may contain a modifier char modifier = script[n + 1]; // Fetch the current character and branch accordingly switch(script[n]) { // Notes case 'c': playNote(214, time, modifier); break; // Play a C case 'C': playNote(202, time, modifier); break; // Play a C# case 'd': playNote(190, time, modifier); break; // Play a D case 'D': playNote(180, time, modifier); break; // Play a D# case 'e': playNote(170, time, modifier); break; // Play an E case 'f': playNote(160, time, modifier); break; // Play an F case 'F': playNote(151, time, modifier); break; // Play an F# case 'g': playNote(143, time, modifier); break; // Play a G case 'G': playNote(135, time, modifier); break; // Play a G# case 'a': playNote(127, time, modifier); break; // Play an A case 'A': playNote(120, time, modifier); break; // Play an A# case 'b': playNote(113, time, modifier); break; // Play a B // Delay case '-': playNote(0, time, modifier); break; // Play a quiet note // Note lengths case '1': time = 1000; break; // Full note case '2': time = 500; break; // Half note case '4': time = 250; break; // Quarter note case '8': time = 50; break; // Eigth note // Modifier '.' makes note length 2/3 } } } void RobotControl::beep(int beep_length){ char scr1[]="8F"; char scr2[]="8Fe"; char scr3[]="1F"; switch (beep_length) { case BEEP_SIMPLE: default: playMelody(scr1); break; case BEEP_DOUBLE: playMelody(scr2); break; case BEEP_LONG: playMelody(scr3); } } void RobotControl::tempoWrite(int tempo){ SquawkSynthSD::tempo(tempo); } void RobotControl::tuneWrite(float tune){ SquawkSynthSD::tune(tune); } void RobotControl::playFile(char* filename){ melody.open(filename,O_READ); SquawkSynthSD::play(melody); } void RobotControl::stopPlayFile(){ melody.close(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/browser_bubble.h" void BrowserBubble::InitPopup(const gfx::Insets& content_margins) { // TODO(beng): NOTIMPLEMENTED(); } void BrowserBubble::Show(bool activate) { // TODO(beng): NOTIMPLEMENTED(); } void BrowserBubble::Hide() { // TODO(beng): NOTIMPLEMENTED(); } void BrowserBubble::ResizeToView() { // TODO(beng): NOTIMPLEMENTED(); } <commit_msg>Add reference to the bug in browser_bubble_aura.cc<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/browser_bubble.h" // TODO(msw|oshima): This will be replaced with new bubble. // See crbug.com/97248. void BrowserBubble::InitPopup(const gfx::Insets& content_margins) { NOTIMPLEMENTED(); } void BrowserBubble::Show(bool activate) { NOTIMPLEMENTED(); } void BrowserBubble::Hide() { NOTIMPLEMENTED(); } void BrowserBubble::ResizeToView() { NOTIMPLEMENTED(); } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include <cling/UserInterface/UserInterface.h> #include <cling/MetaProcessor/MetaProcessor.h> #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include <iostream> #include <sys/stat.h> namespace llvm { class Module; } //--------------------------------------------------------------------------- // Construct an interface for an interpreter //--------------------------------------------------------------------------- cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/): m_MetaProcessor(new MetaProcessor(interp)) { } //--------------------------------------------------------------------------- // Destruct the interface //--------------------------------------------------------------------------- cling::UserInterface::~UserInterface() { delete m_MetaProcessor; } //--------------------------------------------------------------------------- // Interact with the user using a prompt //--------------------------------------------------------------------------- void cling::UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { std::cerr << std::endl; std::cerr << "****************** CLING ******************" << std::endl; std::cerr << "* Type C++ code and press enter to run it *" << std::endl; std::cerr << "* Type .q to exit *" << std::endl; std::cerr << "*******************************************" << std::endl; } static const char* histfile = ".cling_history"; std::string Prompt("[cling]$ "); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfile); TI.SetPrompt(Prompt.c_str()); std::string line; MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts(); while (!MPOpts.Quitting) { TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { MPOpts.Quitting = true; continue; } int indent = m_MetaProcessor->process(line.c_str()); Prompt = "[cling]"; if (MPOpts.RawInput) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } <commit_msg>Don't use iostream.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include <cling/UserInterface/UserInterface.h> #include <cling/MetaProcessor/MetaProcessor.h> #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/Support/raw_ostream.h" //--------------------------------------------------------------------------- // Construct an interface for an interpreter //--------------------------------------------------------------------------- cling::UserInterface::UserInterface(Interpreter& interp, const char* prompt /*= "[cling] $"*/): m_MetaProcessor(new MetaProcessor(interp)) { } //--------------------------------------------------------------------------- // Destruct the interface //--------------------------------------------------------------------------- cling::UserInterface::~UserInterface() { delete m_MetaProcessor; } //--------------------------------------------------------------------------- // Interact with the user using a prompt //--------------------------------------------------------------------------- void cling::UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { llvm::outs() << "\n"; llvm::outs() << "****************** CLING ******************" << "\n"; llvm::outs() << "* Type C++ code and press enter to run it *" << "\n"; llvm::outs() << "* Type .q to exit *" << "\n"; llvm::outs() << "*******************************************" << "\n"; } static const char* histfile = ".cling_history"; std::string Prompt("[cling]$ "); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfile); TI.SetPrompt(Prompt.c_str()); std::string line; MetaProcessorOpts& MPOpts = m_MetaProcessor->getMetaProcessorOpts(); while (!MPOpts.Quitting) { TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { MPOpts.Quitting = true; continue; } int indent = m_MetaProcessor->process(line.c_str()); Prompt = "[cling]"; if (MPOpts.RawInput) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } <|endoftext|>
<commit_before>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "CommonTypes.h" #include "CommonMacros.h" #include "daccess.h" #include "PalRedhawkCommon.h" #include "CommonMacros.inl" #include "Volatile.h" #include "PalRedhawk.h" #include "rhassert.h" #include "slist.h" #include "gcrhinterface.h" #include "shash.h" #include "RWLock.h" #include "module.h" #include "varint.h" #include "holder.h" #include "rhbinder.h" #include "Crst.h" #include "RuntimeInstance.h" #include "event.h" #include "regdisplay.h" #include "StackFrameIterator.h" #include "thread.h" #include "threadstore.h" #include "eetype.h" #include "ObjectLayout.h" #include "GCMemoryHelpers.h" #include "GCMemoryHelpers.inl" EXTERN_C REDHAWK_API void* REDHAWK_CALLCONV RhpPublishObject(void* pObject, UIntNative cbSize); #if defined(FEATURE_SVR_GC) namespace SVR { class GCHeap; } #endif // defined(FEATURE_SVR_GC) struct alloc_context { UInt8* alloc_ptr; UInt8* alloc_limit; __int64 alloc_bytes; //Number of bytes allocated on SOH by this context __int64 alloc_bytes_loh; //Number of bytes allocated on LOH by this context #if defined(FEATURE_SVR_GC) SVR::GCHeap* alloc_heap; SVR::GCHeap* home_heap; #endif // defined(FEATURE_SVR_GC) int alloc_count; }; // // PInvoke // COOP_PINVOKE_HELPER(void, RhpReversePInvoke2, (ReversePInvokeFrame* pFrame)) { Thread* pCurThread = ThreadStore::RawGetCurrentThread(); pFrame->m_savedThread = pCurThread; if (pCurThread->TryFastReversePInvoke(pFrame)) return; pCurThread->ReversePInvoke(pFrame); } COOP_PINVOKE_HELPER(void, RhpReversePInvokeReturn, (ReversePInvokeFrame* pFrame)) { pFrame->m_savedThread->ReversePInvokeReturn(pFrame); } // // Allocations // COOP_PINVOKE_HELPER(Object *, RhpNewFast, (EEType* pEEType)) { ASSERT(!pEEType->RequiresAlign8()); ASSERT(!pEEType->HasFinalizer()); Thread * pCurThread = ThreadStore::GetCurrentThread(); alloc_context * acontext = pCurThread->GetAllocContext(); Object * pObject; size_t size = pEEType->get_BaseSize(); UInt8* result = acontext->alloc_ptr; UInt8* advance = result + size; if (advance <= acontext->alloc_limit) { acontext->alloc_ptr = advance; pObject = (Object *)result; pObject->set_EEType(pEEType); return pObject; } pObject = (Object *)RedhawkGCInterface::Alloc(pCurThread, size, 0, pEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } pObject->set_EEType(pEEType); if (size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } #define GC_ALLOC_FINALIZE 0x1 // TODO: Defined in gc.h COOP_PINVOKE_HELPER(Object *, RhpNewFinalizable, (EEType* pEEType)) { ASSERT(!pEEType->RequiresAlign8()); ASSERT(pEEType->HasFinalizer()); Thread * pCurThread = ThreadStore::GetCurrentThread(); Object * pObject; size_t size = pEEType->get_BaseSize(); pObject = (Object *)RedhawkGCInterface::Alloc(pCurThread, size, GC_ALLOC_FINALIZE, pEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } pObject->set_EEType(pEEType); if (size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } COOP_PINVOKE_HELPER(Array *, RhpNewArray, (EEType * pArrayEEType, int numElements)) { ASSERT_MSG(!pArrayEEType->RequiresAlign8(), "NYI"); Thread * pCurThread = ThreadStore::GetCurrentThread(); alloc_context * acontext = pCurThread->GetAllocContext(); Array * pObject; if (numElements < 0) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw overflow } size_t size; #ifndef BIT64 // if the element count is <= 0x10000, no overflow is possible because the component size is // <= 0xffff, and thus the product is <= 0xffff0000, and the base size is only ~12 bytes if (numElements > 0x10000) { // Perform the size computation using 64-bit integeres to detect overflow uint64_t size64 = (uint64_t)pArrayEEType->get_BaseSize() + ((uint64_t)numElements * (uint64_t)pArrayEEType->get_ComponentSize()); size64 = (size64 + (sizeof(UIntNative)-1)) & ~(sizeof(UIntNative)-1); size = (size_t)size64; if (size != size64) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw overflow } } else #endif // !BIT64 { size = (size_t)pArrayEEType->get_BaseSize() + ((size_t)numElements * (size_t)pArrayEEType->get_ComponentSize()); size = ALIGN_UP(size, sizeof(UIntNative)); } UInt8* result = acontext->alloc_ptr; UInt8* advance = result + size; if (advance <= acontext->alloc_limit) { acontext->alloc_ptr = advance; pObject = (Array *)result; pObject->set_EEType(pArrayEEType); pObject->InitArrayLength((UInt32)numElements); return pObject; } pObject = (Array *)RedhawkGCInterface::Alloc(pCurThread, size, 0, pArrayEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } pObject->set_EEType(pArrayEEType); pObject->InitArrayLength((UInt32)numElements); if (size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } COOP_PINVOKE_HELPER(MDArray *, RhNewMDArray, (EEType * pArrayEEType, UInt32 rank, ...)) { ASSERT_MSG(!pArrayEEType->RequiresAlign8(), "NYI"); Thread * pCurThread = ThreadStore::GetCurrentThread(); alloc_context * acontext = pCurThread->GetAllocContext(); MDArray * pObject; va_list argp; va_start(argp, rank); int numElements = va_arg(argp, int); for (UInt32 i = 1; i < rank; i++) { // TODO: Overflow checks numElements *= va_arg(argp, Int32); } // TODO: Overflow checks size_t size = 3 * sizeof(UIntNative) + 2 * rank * sizeof(Int32) + (numElements * pArrayEEType->get_ComponentSize()); // Align up size = (size + (sizeof(UIntNative) - 1)) & ~(sizeof(UIntNative) - 1); UInt8* result = acontext->alloc_ptr; UInt8* advance = result + size; bool needsPublish = false; if (advance <= acontext->alloc_limit) { acontext->alloc_ptr = advance; pObject = (MDArray *)result; } else { needsPublish = true; pObject = (MDArray *)RedhawkGCInterface::Alloc(pCurThread, size, 0, pArrayEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } } pObject->set_EEType(pArrayEEType); pObject->InitMDArrayLength((UInt32)numElements); va_start(argp, rank); for (UInt32 i = 0; i < rank; i++) { pObject->InitMDArrayDimension(i, va_arg(argp, UInt32)); } if (needsPublish && size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } #if defined(USE_PORTABLE_HELPERS) COOP_PINVOKE_HELPER(void, RhpInitialDynamicInterfaceDispatch, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch1, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch2, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch4, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch8, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch16, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch32, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch64, ()) { ASSERT_UNCONDITIONALLY("NYI"); } #endif #if defined(USE_PORTABLE_HELPERS) || !defined(_WIN32) typedef UIntTarget (*TargetFunc2)(UIntTarget, UIntTarget); COOP_PINVOKE_HELPER(UIntTarget, ManagedCallout2, (UIntTarget argument1, UIntTarget argument2, void *pTargetMethod, void *pPreviousManagedFrame)) { // @TODO Implement ManagedCallout2 on Unix // https://github.com/dotnet/corert/issues/685 TargetFunc2 target = (TargetFunc2)pTargetMethod; return (*target)(argument1, argument2); } #endif // finalizer.cs COOP_PINVOKE_HELPER(void, ProcessFinalizers, ()) { ASSERT_UNCONDITIONALLY("NYI"); } // // Return address hijacking // COOP_PINVOKE_HELPER(void, RhpGcProbeHijackScalar, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcProbeHijackObject, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcProbeHijackByref, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcStressHijackScalar, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcStressHijackObject, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcStressHijackByref, ()) { ASSERT_UNCONDITIONALLY("NYI"); } #ifdef USE_PORTABLE_HELPERS COOP_PINVOKE_HELPER(void, RhpAssignRef, (Object ** dst, Object * ref)) { // @TODO: USE_PORTABLE_HELPERS - Null check *dst = ref; InlineWriteBarrier(dst, ref); } COOP_PINVOKE_HELPER(void, RhpCheckedAssignRef, (Object ** dst, Object * ref)) { // @TODO: USE_PORTABLE_HELPERS - Null check *dst = ref; InlineCheckedWriteBarrier(dst, ref); } COOP_PINVOKE_HELPER(Object *, RhpCheckedLockCmpXchg, (Object ** location, Object * value, Object * comparand)) { // @TODO: USE_PORTABLE_HELPERS - Null check Object * ret = (Object *)PalInterlockedCompareExchangePointer((void * volatile *)location, value, comparand); InlineCheckedWriteBarrier(location, value); return ret; } COOP_PINVOKE_HELPER(Object *, RhpCheckedXchg, (Object ** location, Object * value)) { // @TODO: USE_PORTABLE_HELPERS - Null check Object * ret = (Object *)PalInterlockedExchangePointer((void * volatile *)location, value); InlineCheckedWriteBarrier(location, value); return ret; } COOP_PINVOKE_HELPER(Int32, RhpLockCmpXchg32, (Int32 * location, Int32 value, Int32 comparand)) { // @TODO: USE_PORTABLE_HELPERS - Null check return PalInterlockedCompareExchange(location, value, comparand); } COOP_PINVOKE_HELPER(Int64, RhpLockCmpXchg64, (Int64 * location, Int64 value, Int32 comparand)) { // @TODO: USE_PORTABLE_HELPERS - Null check return PalInterlockedCompareExchange64(location, value, comparand); } #endif // USE_PORTABLE_HELPERS COOP_PINVOKE_HELPER(void, RhpMemoryBarrier, ()) { PalMemoryBarrier(); } COOP_PINVOKE_HELPER(void, Native_GetThunksBase, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, Native_GetNumThunksPerMapping, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, Native_GetThunkSize, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhCallDescrWorker, (void * callDescr)) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(Int64, RhGetGcTotalMemory, ()) { ASSERT_UNCONDITIONALLY("NYI"); return 0; } COOP_PINVOKE_HELPER(void, RhpETWLogLiveCom, (Int32 eventType, void * ccwHandle, void * objectId, void * typeRawValue, void * iUnknown, void * vTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags)) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(bool, RhpETWShouldWalkCom, ()) { ASSERT_UNCONDITIONALLY("NYI"); return false; } <commit_msg>Fix build break in portable runtime flavor (#1154)<commit_after>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "CommonTypes.h" #include "CommonMacros.h" #include "daccess.h" #include "PalRedhawkCommon.h" #include "CommonMacros.inl" #include "Volatile.h" #include "PalRedhawk.h" #include "rhassert.h" #include "slist.h" #include "gcrhinterface.h" #include "shash.h" #include "RWLock.h" #include "module.h" #include "varint.h" #include "holder.h" #include "rhbinder.h" #include "Crst.h" #include "RuntimeInstance.h" #include "event.h" #include "regdisplay.h" #include "StackFrameIterator.h" #include "thread.h" #include "threadstore.h" #include "eetype.h" #include "ObjectLayout.h" #include "GCMemoryHelpers.h" #include "GCMemoryHelpers.inl" EXTERN_C REDHAWK_API void* REDHAWK_CALLCONV RhpPublishObject(void* pObject, UIntNative cbSize); #if defined(FEATURE_SVR_GC) namespace SVR { class GCHeap; } #endif // defined(FEATURE_SVR_GC) struct alloc_context { UInt8* alloc_ptr; UInt8* alloc_limit; __int64 alloc_bytes; //Number of bytes allocated on SOH by this context __int64 alloc_bytes_loh; //Number of bytes allocated on LOH by this context #if defined(FEATURE_SVR_GC) SVR::GCHeap* alloc_heap; SVR::GCHeap* home_heap; #endif // defined(FEATURE_SVR_GC) int alloc_count; }; // // PInvoke // COOP_PINVOKE_HELPER(void, RhpReversePInvoke2, (ReversePInvokeFrame* pFrame)) { Thread* pCurThread = ThreadStore::RawGetCurrentThread(); pFrame->m_savedThread = pCurThread; if (pCurThread->TryFastReversePInvoke(pFrame)) return; pCurThread->ReversePInvoke(pFrame); } COOP_PINVOKE_HELPER(void, RhpReversePInvokeReturn, (ReversePInvokeFrame* pFrame)) { pFrame->m_savedThread->ReversePInvokeReturn(pFrame); } // // Allocations // COOP_PINVOKE_HELPER(Object *, RhpNewFast, (EEType* pEEType)) { ASSERT(!pEEType->RequiresAlign8()); ASSERT(!pEEType->HasFinalizer()); Thread * pCurThread = ThreadStore::GetCurrentThread(); alloc_context * acontext = pCurThread->GetAllocContext(); Object * pObject; size_t size = pEEType->get_BaseSize(); UInt8* result = acontext->alloc_ptr; UInt8* advance = result + size; if (advance <= acontext->alloc_limit) { acontext->alloc_ptr = advance; pObject = (Object *)result; pObject->set_EEType(pEEType); return pObject; } pObject = (Object *)RedhawkGCInterface::Alloc(pCurThread, size, 0, pEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } pObject->set_EEType(pEEType); if (size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } #define GC_ALLOC_FINALIZE 0x1 // TODO: Defined in gc.h COOP_PINVOKE_HELPER(Object *, RhpNewFinalizable, (EEType* pEEType)) { ASSERT(!pEEType->RequiresAlign8()); ASSERT(pEEType->HasFinalizer()); Thread * pCurThread = ThreadStore::GetCurrentThread(); Object * pObject; size_t size = pEEType->get_BaseSize(); pObject = (Object *)RedhawkGCInterface::Alloc(pCurThread, size, GC_ALLOC_FINALIZE, pEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } pObject->set_EEType(pEEType); if (size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } COOP_PINVOKE_HELPER(Array *, RhpNewArray, (EEType * pArrayEEType, int numElements)) { ASSERT_MSG(!pArrayEEType->RequiresAlign8(), "NYI"); Thread * pCurThread = ThreadStore::GetCurrentThread(); alloc_context * acontext = pCurThread->GetAllocContext(); Array * pObject; if (numElements < 0) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw overflow } size_t size; #ifndef BIT64 // if the element count is <= 0x10000, no overflow is possible because the component size is // <= 0xffff, and thus the product is <= 0xffff0000, and the base size is only ~12 bytes if (numElements > 0x10000) { // Perform the size computation using 64-bit integeres to detect overflow uint64_t size64 = (uint64_t)pArrayEEType->get_BaseSize() + ((uint64_t)numElements * (uint64_t)pArrayEEType->get_ComponentSize()); size64 = (size64 + (sizeof(UIntNative)-1)) & ~(sizeof(UIntNative)-1); size = (size_t)size64; if (size != size64) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw overflow } } else #endif // !BIT64 { size = (size_t)pArrayEEType->get_BaseSize() + ((size_t)numElements * (size_t)pArrayEEType->get_ComponentSize()); size = ALIGN_UP(size, sizeof(UIntNative)); } UInt8* result = acontext->alloc_ptr; UInt8* advance = result + size; if (advance <= acontext->alloc_limit) { acontext->alloc_ptr = advance; pObject = (Array *)result; pObject->set_EEType(pArrayEEType); pObject->InitArrayLength((UInt32)numElements); return pObject; } pObject = (Array *)RedhawkGCInterface::Alloc(pCurThread, size, 0, pArrayEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } pObject->set_EEType(pArrayEEType); pObject->InitArrayLength((UInt32)numElements); if (size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } COOP_PINVOKE_HELPER(MDArray *, RhNewMDArray, (EEType * pArrayEEType, UInt32 rank, ...)) { ASSERT_MSG(!pArrayEEType->RequiresAlign8(), "NYI"); Thread * pCurThread = ThreadStore::GetCurrentThread(); alloc_context * acontext = pCurThread->GetAllocContext(); MDArray * pObject; va_list argp; va_start(argp, rank); int numElements = va_arg(argp, int); for (UInt32 i = 1; i < rank; i++) { // TODO: Overflow checks numElements *= va_arg(argp, Int32); } // TODO: Overflow checks size_t size = 3 * sizeof(UIntNative) + 2 * rank * sizeof(Int32) + (numElements * pArrayEEType->get_ComponentSize()); // Align up size = (size + (sizeof(UIntNative) - 1)) & ~(sizeof(UIntNative) - 1); UInt8* result = acontext->alloc_ptr; UInt8* advance = result + size; bool needsPublish = false; if (advance <= acontext->alloc_limit) { acontext->alloc_ptr = advance; pObject = (MDArray *)result; } else { needsPublish = true; pObject = (MDArray *)RedhawkGCInterface::Alloc(pCurThread, size, 0, pArrayEEType); if (pObject == nullptr) { ASSERT_UNCONDITIONALLY("NYI"); // TODO: Throw OOM } } pObject->set_EEType(pArrayEEType); pObject->InitMDArrayLength((UInt32)numElements); va_start(argp, rank); for (UInt32 i = 0; i < rank; i++) { pObject->InitMDArrayDimension(i, va_arg(argp, UInt32)); } if (needsPublish && size >= RH_LARGE_OBJECT_SIZE) RhpPublishObject(pObject, size); return pObject; } #if defined(USE_PORTABLE_HELPERS) COOP_PINVOKE_HELPER(void, RhpInitialDynamicInterfaceDispatch, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch1, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch2, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch4, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch8, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch16, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch32, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpInterfaceDispatch64, ()) { ASSERT_UNCONDITIONALLY("NYI"); } #endif #if defined(USE_PORTABLE_HELPERS) || !defined(_WIN32) typedef UIntTarget (*TargetFunc2)(UIntTarget, UIntTarget); COOP_PINVOKE_HELPER(UIntTarget, ManagedCallout2, (UIntTarget argument1, UIntTarget argument2, void *pTargetMethod, void *pPreviousManagedFrame)) { // @TODO Implement ManagedCallout2 on Unix // https://github.com/dotnet/corert/issues/685 TargetFunc2 target = (TargetFunc2)pTargetMethod; return (*target)(argument1, argument2); } #endif // finalizer.cs COOP_PINVOKE_HELPER(void, ProcessFinalizers, ()) { ASSERT_UNCONDITIONALLY("NYI"); } // // Return address hijacking // COOP_PINVOKE_HELPER(void, RhpGcProbeHijackScalar, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcProbeHijackObject, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcProbeHijackByref, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcStressHijackScalar, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcStressHijackObject, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpGcStressHijackByref, ()) { ASSERT_UNCONDITIONALLY("NYI"); } #ifdef USE_PORTABLE_HELPERS COOP_PINVOKE_HELPER(void, RhpAssignRef, (Object ** dst, Object * ref)) { // @TODO: USE_PORTABLE_HELPERS - Null check *dst = ref; InlineWriteBarrier(dst, ref); } COOP_PINVOKE_HELPER(void, RhpCheckedAssignRef, (Object ** dst, Object * ref)) { // @TODO: USE_PORTABLE_HELPERS - Null check *dst = ref; InlineCheckedWriteBarrier(dst, ref); } COOP_PINVOKE_HELPER(Object *, RhpCheckedLockCmpXchg, (Object ** location, Object * value, Object * comparand)) { // @TODO: USE_PORTABLE_HELPERS - Null check Object * ret = (Object *)PalInterlockedCompareExchangePointer((void * volatile *)location, value, comparand); InlineCheckedWriteBarrier(location, value); return ret; } COOP_PINVOKE_HELPER(Object *, RhpCheckedXchg, (Object ** location, Object * value)) { // @TODO: USE_PORTABLE_HELPERS - Null check Object * ret = (Object *)PalInterlockedExchangePointer((void * volatile *)location, value); InlineCheckedWriteBarrier(location, value); return ret; } COOP_PINVOKE_HELPER(Int32, RhpLockCmpXchg32, (Int32 * location, Int32 value, Int32 comparand)) { // @TODO: USE_PORTABLE_HELPERS - Null check return PalInterlockedCompareExchange(location, value, comparand); } COOP_PINVOKE_HELPER(Int64, RhpLockCmpXchg64, (Int64 * location, Int64 value, Int32 comparand)) { // @TODO: USE_PORTABLE_HELPERS - Null check return PalInterlockedCompareExchange64(location, value, comparand); } #endif // USE_PORTABLE_HELPERS COOP_PINVOKE_HELPER(void, RhpMemoryBarrier, ()) { PalMemoryBarrier(); } COOP_PINVOKE_HELPER(void, Native_GetThunksBase, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, Native_GetNumThunksPerMapping, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, Native_GetThunkSize, ()) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhCallDescrWorker, (void * callDescr)) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(void, RhpETWLogLiveCom, (Int32 eventType, void * ccwHandle, void * objectId, void * typeRawValue, void * iUnknown, void * vTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags)) { ASSERT_UNCONDITIONALLY("NYI"); } COOP_PINVOKE_HELPER(bool, RhpETWShouldWalkCom, ()) { ASSERT_UNCONDITIONALLY("NYI"); return false; } <|endoftext|>
<commit_before>#include "glwidget.h" #include <QtOpenGL> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <glut.h> #endif #include <QDebug> #include "db/database.h" #include "algorithms/pathalgorithms.h" #include "../stable.h" GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent) { canvasWidth = 0; canvasHeight = 0; timer = new QTimer(this); camera = new GLCamera(); isStop = false; startPoint = 0; endPoint = 0; } void GLWidget::initializeGL() { glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glClearColor(0, 0, 0, 1.0); glColor3f(1.0, 1.0, 1.0); glEnable(GL_DEPTH_TEST); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // glEnable( GL_POINT_SPRITE ); // glEnable( GL_BLEND ); connect(timer, SIGNAL(timeout()), this, SLOT(updateLC())); timer->start(10); this->setFocus(); } void GLWidget::updateLC() { // Do my update stuff //map->update(); updateGL(); } void GLWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(camera->x, camera->y, camera->z, camera->look_x, camera->look_y, camera->look_z, 0.0, 1.0, 0.0); glPushMatrix(); glColor3f(1.0f, 1.0f, 1.0f); glLineWidth(1.0f); // map<unsigned long int,Way*>* allWays = db->getAllWays(); if(allWays == 0) return; map<unsigned long int, Way*>::iterator wayIt; for(wayIt = allWays->begin(); wayIt != allWays->end(); ++wayIt) { glBegin(GL_LINE_STRIP); //((Way*)(*wayIt).second)->getNodesBegin() for (vector<Node*>::iterator nodeIt = ((Way*)(*wayIt).second)->getNodesBegin(); nodeIt != ((Way*)(*wayIt).second)->getNodesEnd(); nodeIt++){ //cout<<(*nodeIt)->getId()<<endl; boost_xy_point& nodeGeoPos = (*nodeIt)->getGeoPosition(); //qDebug() << "Node Pos: " << nodeGeoPos.x() << " " << nodeGeoPos.y(); //glVertex2f(nodeGeoPos.x() * 1000000, nodeGeoPos.y() * 1000000); //glVertex2f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100); glVertex3f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100, 0.0f); //qDebug() << "Node Pos: " << nodeGeoPos.x() * 100<< " " << nodeGeoPos.y() * 100; //glVertex2d(nodeGeoPos.x(), nodeGeoPos.y()); // lat="46.7918039" lon="4.4277047" } glEnd(); } //// vector<WaySegment*> segments_in_area; //// //d->searchWaySegmentsInArea(boost_xy_point(46.78,4.402), boost_xy_point(46.79,4.403),segments_in_area); //// d->searchWaySegmentsInArea(boost_xy_point(4.400,46.76), boost_xy_point(4.403,46.79),segments_in_area); //// //qDebug() << "Size of the segment: " << segments_in_area.size(); //// glColor3f(1.0f, 0.0f, 0.0f); //// for(int i = 0; i < segments_in_area.size(); i++) //// { //// WaySegment* waySegment = segments_in_area[i]; //// boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition(); //// boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition(); //// glBegin(GL_LINES); //// glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f); //// glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f); //// glEnd(); //// } // glColor3f(1.0f, 0.0f, 0.0f); // glLineWidth(5.0f); // vector<WaySegment*> path; // float cost,time; // boost_xy_point start_point(4.4097667,46.7901184); // boost_xy_point end_point(4.4249021,46.7990036); // ns_permisions::transport_type tt = ns_permisions::foot; // bool found = PathAlgorithms::findShortestPath(d, start_point, end_point, tt, path, cost, time); // //bool found = PathAlgorithms::findShortestPath(&d, &start_point, &end_point, tt, path, cost, time); // if(found) // { // for(int i = 0; i < path.size(); i++) // { // WaySegment* waySegment = path[i]; // boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition(); // boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition(); // glBegin(GL_LINES); // //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y(); // //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y(); // glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f); // glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f); // glEnd(); // } // } if(!startPoint->isNull()) { //glPushMatrix(); glColor3f(0.0f, 1.0f, 0.0f); glPointSize(2.0f); glBegin(GL_POINTS); glVertex3f(startPoint->x() / 100.f, startPoint->y() / 100.f, 2.0f); glEnd(); //glPopMatrix(); } if(!endPoint->isNull()) { //glPushMatrix(); glColor3f(1.0f, 0.0f, 0.0f); glPointSize(2.0f); glBegin(GL_POINTS); glVertex3f(endPoint->x() / 100.f, endPoint->y() / 100.f, 2.0f); glEnd(); //glPopMatrix(); } glPopMatrix(); } void GLWidget::resizeGL(int w, int h) { glViewport(0, 0, w, h); camera->canvasWidth = w; camera->canvasHeight = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); float ratio = float(w) / float(h); glOrtho(camera->planeLeft, camera->planeRight, camera->planeBottom, camera->planeTop, camera->planeNear, camera->planeFar); //gluPerspective(60.0, ratio, 1.0, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void GLWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_W: camera->up(); break; case Qt::Key_A: camera->left(); break; case Qt::Key_S: camera->down(); break; case Qt::Key_D: camera->right(); break; case Qt::Key_Q: camera->zoomIn(); break; case Qt::Key_E: camera->zoomOut(); break; case Qt::Key_Up: camera->up(); break; case Qt::Key_Down: camera->down(); break; case Qt::Key_Left: camera->left(); break; case Qt::Key_Right: camera->right(); break; case Qt::Key_Plus: camera->zoomIn(); break; case Qt::Key_Minus: camera->zoomOut(); break; case Qt::Key_Escape: this->parentWidget()->parentWidget()->close(); break; default: break; } event->accept(); } void GLWidget::wheelEvent(QWheelEvent *event) { if(event->orientation() == Qt::Vertical) { if(event->delta() > 0) camera->zoomIn(); else camera->zoomOut(); } else { if(event->delta() > 0) camera->right(); else camera->left(); } event->accept(); } void GLWidget::mousePressEvent(QMouseEvent *event) { lastPos = event->pos(); event->accept(); } void GLWidget::mouseMoveEvent(QMouseEvent *event) { //qDebug() << "mouseMoveEvent"<<endl; int dx = event->x() - lastPos.x(); int dy = event->y() - lastPos.y(); // qDebug() << "lastPos.x: "<< lastPos.x() << " lastPost.y: " << lastPos.y() <<endl; // qDebug() << "event->x: "<< event->x() << " event->y: " << event->y() << endl; // qDebug() << "dx: "<< dx << " dy: " << dy << endl; // qDebug() << "===========================================" << endl; if (event->buttons() & Qt::LeftButton) { camera->move(dx, dy); //setXRotation(xRot + 8 * dy); //setYRotation(yRot + 8 * dx); } else if (event->buttons() & Qt::RightButton) { //setXRotation(xRot + 8 * dy); //setZRotation(zRot + 8 * dx); } lastPos = event->pos(); } void GLWidget::startGL() { isStop = false; timer->start(10); } void GLWidget::stopGL() { isStop = true; timer->stop(); } QPointF GLWidget::getGeoPosition(QPoint point) { GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLfloat winX, winY, winZ; GLdouble posX, posY, posZ; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); winX = (float)point.x(); winY = (float)viewport[3] - (float)point.y(); glReadPixels(point.x(), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ ); gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ); return QPointF(posX / 100.0, posY / 100.0); } void GLWidget::centerMap() { } void GLWidget::setMap(map<unsigned long int,Way*>* ways) { allWays = ways; } void GLWidget::drawStartPoint(QPointF *startp) { startPoint = startp; } void GLWidget::drawEndPoint(QPointF *endp) { endPoint = endp; } void GLWidget::deleteStartPoint() { delete startPoint; startPoint = 0; } void GLWidget::deleteEndPoint() { delete endPoint; endPoint = 0; } <commit_msg>Fix: draw start and end point<commit_after>#include "glwidget.h" #include <QtOpenGL> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <glut.h> #endif #include <QDebug> #include "db/database.h" #include "algorithms/pathalgorithms.h" #include "../stable.h" GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent) { canvasWidth = 0; canvasHeight = 0; timer = new QTimer(this); camera = new GLCamera(); isStop = false; startPoint = 0; endPoint = 0; } void GLWidget::initializeGL() { glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glClearColor(0, 0, 0, 1.0); glColor3f(1.0, 1.0, 1.0); glEnable(GL_DEPTH_TEST); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // glEnable( GL_POINT_SPRITE ); // glEnable( GL_BLEND ); connect(timer, SIGNAL(timeout()), this, SLOT(updateLC())); timer->start(10); this->setFocus(); } void GLWidget::updateLC() { // Do my update stuff //map->update(); updateGL(); } void GLWidget::paintGL() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(camera->x, camera->y, camera->z, camera->look_x, camera->look_y, camera->look_z, 0.0, 1.0, 0.0); glPushMatrix(); glColor3f(1.0f, 1.0f, 1.0f); glLineWidth(1.0f); // map<unsigned long int,Way*>* allWays = db->getAllWays(); if(allWays == 0) return; map<unsigned long int, Way*>::iterator wayIt; for(wayIt = allWays->begin(); wayIt != allWays->end(); ++wayIt) { glBegin(GL_LINE_STRIP); //((Way*)(*wayIt).second)->getNodesBegin() for (vector<Node*>::iterator nodeIt = ((Way*)(*wayIt).second)->getNodesBegin(); nodeIt != ((Way*)(*wayIt).second)->getNodesEnd(); nodeIt++){ //cout<<(*nodeIt)->getId()<<endl; boost_xy_point& nodeGeoPos = (*nodeIt)->getGeoPosition(); //qDebug() << "Node Pos: " << nodeGeoPos.x() << " " << nodeGeoPos.y(); //glVertex2f(nodeGeoPos.x() * 1000000, nodeGeoPos.y() * 1000000); //glVertex2f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100); glVertex3f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100, 0.0f); //qDebug() << "Node Pos: " << nodeGeoPos.x() * 100<< " " << nodeGeoPos.y() * 100; //glVertex2d(nodeGeoPos.x(), nodeGeoPos.y()); // lat="46.7918039" lon="4.4277047" } glEnd(); } //// vector<WaySegment*> segments_in_area; //// //d->searchWaySegmentsInArea(boost_xy_point(46.78,4.402), boost_xy_point(46.79,4.403),segments_in_area); //// d->searchWaySegmentsInArea(boost_xy_point(4.400,46.76), boost_xy_point(4.403,46.79),segments_in_area); //// //qDebug() << "Size of the segment: " << segments_in_area.size(); //// glColor3f(1.0f, 0.0f, 0.0f); //// for(int i = 0; i < segments_in_area.size(); i++) //// { //// WaySegment* waySegment = segments_in_area[i]; //// boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition(); //// boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition(); //// glBegin(GL_LINES); //// glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f); //// glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f); //// glEnd(); //// } // glColor3f(1.0f, 0.0f, 0.0f); // glLineWidth(5.0f); // vector<WaySegment*> path; // float cost,time; // boost_xy_point start_point(4.4097667,46.7901184); // boost_xy_point end_point(4.4249021,46.7990036); // ns_permisions::transport_type tt = ns_permisions::foot; // bool found = PathAlgorithms::findShortestPath(d, start_point, end_point, tt, path, cost, time); // //bool found = PathAlgorithms::findShortestPath(&d, &start_point, &end_point, tt, path, cost, time); // if(found) // { // for(int i = 0; i < path.size(); i++) // { // WaySegment* waySegment = path[i]; // boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition(); // boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition(); // glBegin(GL_LINES); // //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y(); // //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y(); // glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f); // glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f); // glEnd(); // } // } if(startPoint != NULL) { //glPushMatrix(); glColor3f(0.0f, 1.0f, 0.0f); glPointSize(2.0f); glBegin(GL_POINTS); glVertex3f(startPoint->x() / 100.f, startPoint->y() / 100.f, 2.0f); glEnd(); //glPopMatrix(); } if(endPoint != NULL) { //glPushMatrix(); glColor3f(1.0f, 0.0f, 0.0f); glPointSize(2.0f); glBegin(GL_POINTS); glVertex3f(endPoint->x() / 100.f, endPoint->y() / 100.f, 2.0f); glEnd(); //glPopMatrix(); } glPopMatrix(); } void GLWidget::resizeGL(int w, int h) { glViewport(0, 0, w, h); camera->canvasWidth = w; camera->canvasHeight = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); float ratio = float(w) / float(h); glOrtho(camera->planeLeft, camera->planeRight, camera->planeBottom, camera->planeTop, camera->planeNear, camera->planeFar); //gluPerspective(60.0, ratio, 1.0, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void GLWidget::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_W: camera->up(); break; case Qt::Key_A: camera->left(); break; case Qt::Key_S: camera->down(); break; case Qt::Key_D: camera->right(); break; case Qt::Key_Q: camera->zoomIn(); break; case Qt::Key_E: camera->zoomOut(); break; case Qt::Key_Up: camera->up(); break; case Qt::Key_Down: camera->down(); break; case Qt::Key_Left: camera->left(); break; case Qt::Key_Right: camera->right(); break; case Qt::Key_Plus: camera->zoomIn(); break; case Qt::Key_Minus: camera->zoomOut(); break; case Qt::Key_Escape: this->parentWidget()->parentWidget()->close(); break; default: break; } event->accept(); } void GLWidget::wheelEvent(QWheelEvent *event) { if(event->orientation() == Qt::Vertical) { if(event->delta() > 0) camera->zoomIn(); else camera->zoomOut(); } else { if(event->delta() > 0) camera->right(); else camera->left(); } event->accept(); } void GLWidget::mousePressEvent(QMouseEvent *event) { lastPos = event->pos(); event->accept(); } void GLWidget::mouseMoveEvent(QMouseEvent *event) { //qDebug() << "mouseMoveEvent"<<endl; int dx = event->x() - lastPos.x(); int dy = event->y() - lastPos.y(); // qDebug() << "lastPos.x: "<< lastPos.x() << " lastPost.y: " << lastPos.y() <<endl; // qDebug() << "event->x: "<< event->x() << " event->y: " << event->y() << endl; // qDebug() << "dx: "<< dx << " dy: " << dy << endl; // qDebug() << "===========================================" << endl; if (event->buttons() & Qt::LeftButton) { camera->move(dx, dy); //setXRotation(xRot + 8 * dy); //setYRotation(yRot + 8 * dx); } else if (event->buttons() & Qt::RightButton) { //setXRotation(xRot + 8 * dy); //setZRotation(zRot + 8 * dx); } lastPos = event->pos(); } void GLWidget::startGL() { isStop = false; timer->start(10); } void GLWidget::stopGL() { isStop = true; timer->stop(); } QPointF GLWidget::getGeoPosition(QPoint point) { GLint viewport[4]; GLdouble modelview[16]; GLdouble projection[16]; GLfloat winX, winY, winZ; GLdouble posX, posY, posZ; glGetDoublev(GL_MODELVIEW_MATRIX, modelview); glGetDoublev(GL_PROJECTION_MATRIX, projection); glGetIntegerv(GL_VIEWPORT, viewport); winX = (float)point.x(); winY = (float)viewport[3] - (float)point.y(); glReadPixels(point.x(), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ ); gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ); return QPointF(posX / 100.0, posY / 100.0); } void GLWidget::centerMap() { } void GLWidget::setMap(map<unsigned long int,Way*>* ways) { allWays = ways; } void GLWidget::drawStartPoint(QPointF *startp) { startPoint = startp; } void GLWidget::drawEndPoint(QPointF *endp) { endPoint = endp; } void GLWidget::deleteStartPoint() { delete startPoint; startPoint = 0; } void GLWidget::deleteEndPoint() { delete endPoint; endPoint = 0; } <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef __YLIKUUTIO_CALLBACK_CALLBACK_PARAMETER_HPP_INCLUDED #define __YLIKUUTIO_CALLBACK_CALLBACK_PARAMETER_HPP_INCLUDED #include "callback_object.hpp" #include "code/ylikuutio/data/any_value.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <limits> // std::numeric_limits #include <memory> // std::make_shared, std::shared_ptr #include <queue> // std::queue #include <string> // std::string #include <vector> // std::vector namespace yli::ontology { class Universe; } namespace yli::callback { class CallbackParameter { public: // destructor. ~CallbackParameter(); // getter. std::shared_ptr<yli::data::AnyValue> get_any_value() const; friend class yli::callback::CallbackObject; template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); private: void bind_to_parent(); // constructor. CallbackParameter(const std::string& name, std::shared_ptr<yli::data::AnyValue> any_value, const bool is_reference, yli::callback::CallbackObject* const parent); yli::callback::CallbackObject* parent; // pointer to the callback object. std::size_t childID { std::numeric_limits<std::size_t>::max() }; // callback parameter ID, returned by `yli::callback::CallbackObject->get_callback_parameterID()`. std::string name; std::shared_ptr<yli::data::AnyValue> any_value; // this is `private` to make sure that someone does not overwrite it. bool is_reference; // if true, the value is read from the hashmap. if false, then the value is read from the union. }; } #endif <commit_msg>`CallbackParameter`: initialize pointers to `nullptr`.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2021 Antti Nuortimo. // // This program 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. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef __YLIKUUTIO_CALLBACK_CALLBACK_PARAMETER_HPP_INCLUDED #define __YLIKUUTIO_CALLBACK_CALLBACK_PARAMETER_HPP_INCLUDED #include "callback_object.hpp" #include "code/ylikuutio/data/any_value.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <limits> // std::numeric_limits #include <memory> // std::make_shared, std::shared_ptr #include <queue> // std::queue #include <string> // std::string #include <vector> // std::vector namespace yli::ontology { class Universe; } namespace yli::callback { class CallbackParameter { public: // destructor. ~CallbackParameter(); // getter. std::shared_ptr<yli::data::AnyValue> get_any_value() const; friend class yli::callback::CallbackObject; template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); private: void bind_to_parent(); // constructor. CallbackParameter(const std::string& name, std::shared_ptr<yli::data::AnyValue> any_value, const bool is_reference, yli::callback::CallbackObject* const parent); yli::callback::CallbackObject* parent { nullptr }; // pointer to the callback object. std::size_t childID { std::numeric_limits<std::size_t>::max() }; // callback parameter ID, returned by `yli::callback::CallbackObject->get_callback_parameterID()`. std::string name; std::shared_ptr<yli::data::AnyValue> any_value { nullptr }; // this is `private` to make sure that someone does not overwrite it. bool is_reference; // if true, the value is read from the hashmap. if false, then the value is read from the union. }; } #endif <|endoftext|>
<commit_before>/* type_test.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 12 Apr 2014 FreeBSD-style copyright and disclaimer apply Tests for types. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "test_types.h" #include <boost/test/unit_test.hpp> using namespace std; using namespace reflect; BOOST_AUTO_TEST_CASE(void_) { Type* t = type<void>(); BOOST_CHECK(!t->parent()); BOOST_CHECK(t->isParentOf<void>()); BOOST_CHECK(t->isChildOf<void>()); BOOST_CHECK_EQUAL(t->fields().size(), 0); BOOST_CHECK(!t->isCopiable()); BOOST_CHECK(!t->isMovable()); } BOOST_AUTO_TEST_CASE(print) { std::cerr << type<int>()->print() << std::endl; std::cerr << type<test::Object>()->print() << std::endl; std::cerr << type<test::NotCopiable>()->print() << std::endl; std::cerr << type<test::NotMovable>()->print() << std::endl; std::cerr << type<test::NotConstructible>()->print() << std::endl; std::cerr << type<test::Child>()->print() << std::endl; std::cerr << type<test::Convertible>()->print() << std::endl; } BOOST_AUTO_TEST_CASE(field) { Type* tInt = type<int>(); BOOST_CHECK( tInt->hasField("int")); BOOST_CHECK( tInt->hasField("operator=")); BOOST_CHECK(!tInt->hasField("bob")); Type* tObject = type<test::Object>(); BOOST_CHECK( tObject->hasField("test::Object")); BOOST_CHECK(!tObject->hasField("Object")); BOOST_CHECK( tObject->hasField("value")); BOOST_CHECK( tObject->hasField("operator=")); BOOST_CHECK( tObject->hasField("operator+=")); BOOST_CHECK( tObject->hasField("operator++")); BOOST_CHECK(!tObject->hasField("bob")); Type* tParent = type<test::Parent>(); BOOST_CHECK( tParent->hasField("test::Parent")); BOOST_CHECK(!tParent->hasField("test::Child")); BOOST_CHECK( tParent->hasField("value")); BOOST_CHECK(!tParent->hasField("childValue")); BOOST_CHECK( tParent->hasField("shadowed")); BOOST_CHECK( tParent->hasField("normalVirtual")); BOOST_CHECK( tParent->hasField("pureVirtual")); Type* tChild = type<test::Child>(); BOOST_CHECK( tChild->hasField("test::Child")); BOOST_CHECK( tChild->hasField("test::Parent")); // \todo Do we want this? BOOST_CHECK( tChild->hasField("value")); BOOST_CHECK( tChild->hasField("childValue")); BOOST_CHECK( tChild->hasField("shadowed")); BOOST_CHECK( tChild->hasField("normalVirtual")); BOOST_CHECK( tChild->hasField("pureVirtual")); Type* tConvertible = type<test::Convertible>(); BOOST_CHECK( tConvertible->hasField("operator int()")); BOOST_CHECK( tConvertible->hasField("operator test::Parent()")); } BOOST_AUTO_TEST_CASE(moveCopy) { Type* tInt = type<int>(); BOOST_CHECK(tInt->isCopiable()); BOOST_CHECK(tInt->isMovable()); Type* tObject = type<test::Object>(); BOOST_CHECK(tObject->isCopiable()); BOOST_CHECK(tObject->isMovable()); Type* tNotCopiable = type<test::NotCopiable>(); BOOST_CHECK(!tNotCopiable->isCopiable()); // BOOST_CHECK( tNotCopiable->isMovable()); // \todo Type* tNotMovable = type<test::NotMovable>(); BOOST_CHECK(!tNotMovable->isCopiable()); BOOST_CHECK(!tNotMovable->isMovable()); Type* tNotConstructible = type<test::NotConstructible>(); BOOST_CHECK(!tNotConstructible->isCopiable()); // BOOST_CHECK( tNotConstructible->isMovable()); // \todo } BOOST_AUTO_TEST_CASE(parentChild) { Type* tInt = type<int>(); BOOST_CHECK( tInt->isParentOf<int>()); BOOST_CHECK(!tInt->isParentOf<unsigned>()); BOOST_CHECK(!tInt->isParentOf<test::Object>()); Type* tParent = type<test::Parent>(); BOOST_CHECK( tParent->isParentOf<test::Parent>()); BOOST_CHECK( tParent->isParentOf<test::Child>()); BOOST_CHECK(!tParent->isParentOf<test::Object>()); BOOST_CHECK( tParent->isChildOf<test::Parent>()); BOOST_CHECK(!tParent->isChildOf<test::Child>()); BOOST_CHECK(!tParent->isChildOf<test::Object>()); Type* tChild = type<test::Child>(); BOOST_CHECK(!tChild->isParentOf<test::Parent>()); BOOST_CHECK( tChild->isParentOf<test::Child>()); BOOST_CHECK(!tChild->isParentOf<test::Object>()); BOOST_CHECK( tChild->isChildOf<test::Parent>()); BOOST_CHECK( tChild->isChildOf<test::Child>()); BOOST_CHECK(!tChild->isChildOf<test::Object>()); } BOOST_AUTO_TEST_CASE(converter) { Type* tParent = type<test::Parent>(); BOOST_CHECK(!tParent->hasConverter<int>()); BOOST_CHECK(!tParent->hasConverter<test::Parent>()); BOOST_CHECK(!tParent->hasConverter<test::Convertible>()); Type* tConvertible = type<test::Convertible>(); BOOST_CHECK( tConvertible->hasConverter<int>()); BOOST_CHECK( tConvertible->hasConverter<test::Parent>()); BOOST_CHECK(!tConvertible->hasConverter<test::Convertible>()); } <commit_msg>Added Interface to the type tests.<commit_after>/* type_test.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 12 Apr 2014 FreeBSD-style copyright and disclaimer apply Tests for types. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "test_types.h" #include <boost/test/unit_test.hpp> using namespace std; using namespace reflect; BOOST_AUTO_TEST_CASE(void_) { Type* t = type<void>(); BOOST_CHECK(!t->parent()); BOOST_CHECK(t->isParentOf<void>()); BOOST_CHECK(t->isChildOf<void>()); BOOST_CHECK_EQUAL(t->fields().size(), 0); BOOST_CHECK(!t->isCopiable()); BOOST_CHECK(!t->isMovable()); } BOOST_AUTO_TEST_CASE(print) { std::cerr << type<int>()->print() << std::endl; std::cerr << type<test::Object>()->print() << std::endl; std::cerr << type<test::NotCopiable>()->print() << std::endl; std::cerr << type<test::NotMovable>()->print() << std::endl; std::cerr << type<test::NotConstructible>()->print() << std::endl; std::cerr << type<test::Child>()->print() << std::endl; std::cerr << type<test::Convertible>()->print() << std::endl; } BOOST_AUTO_TEST_CASE(field) { Type* tInt = type<int>(); BOOST_CHECK( tInt->hasField("int")); BOOST_CHECK( tInt->hasField("operator=")); BOOST_CHECK(!tInt->hasField("bob")); Type* tObject = type<test::Object>(); BOOST_CHECK( tObject->hasField("test::Object")); BOOST_CHECK(!tObject->hasField("Object")); BOOST_CHECK( tObject->hasField("value")); BOOST_CHECK( tObject->hasField("operator=")); BOOST_CHECK( tObject->hasField("operator+=")); BOOST_CHECK( tObject->hasField("operator++")); BOOST_CHECK(!tObject->hasField("bob")); Type* tParent = type<test::Parent>(); BOOST_CHECK( tParent->hasField("test::Parent")); BOOST_CHECK(!tParent->hasField("test::Child")); BOOST_CHECK( tParent->hasField("value")); BOOST_CHECK(!tParent->hasField("childValue")); BOOST_CHECK( tParent->hasField("shadowed")); BOOST_CHECK( tParent->hasField("normalVirtual")); BOOST_CHECK( tParent->hasField("pureVirtual")); Type* tChild = type<test::Child>(); BOOST_CHECK( tChild->hasField("test::Child")); BOOST_CHECK( tChild->hasField("test::Parent")); // \todo Do we want this? BOOST_CHECK( tChild->hasField("value")); BOOST_CHECK( tChild->hasField("childValue")); BOOST_CHECK( tChild->hasField("shadowed")); BOOST_CHECK( tChild->hasField("normalVirtual")); BOOST_CHECK( tChild->hasField("pureVirtual")); Type* tConvertible = type<test::Convertible>(); BOOST_CHECK( tConvertible->hasField("operator int()")); BOOST_CHECK( tConvertible->hasField("operator test::Parent()")); } BOOST_AUTO_TEST_CASE(moveCopy) { Type* tInt = type<int>(); BOOST_CHECK(tInt->isCopiable()); BOOST_CHECK(tInt->isMovable()); Type* tObject = type<test::Object>(); BOOST_CHECK(tObject->isCopiable()); BOOST_CHECK(tObject->isMovable()); Type* tNotCopiable = type<test::NotCopiable>(); BOOST_CHECK(!tNotCopiable->isCopiable()); // BOOST_CHECK( tNotCopiable->isMovable()); // \todo Type* tNotMovable = type<test::NotMovable>(); BOOST_CHECK(!tNotMovable->isCopiable()); BOOST_CHECK(!tNotMovable->isMovable()); Type* tNotConstructible = type<test::NotConstructible>(); BOOST_CHECK(!tNotConstructible->isCopiable()); // BOOST_CHECK( tNotConstructible->isMovable()); // \todo } BOOST_AUTO_TEST_CASE(parentChild) { Type* tInt = type<int>(); BOOST_CHECK( tInt->isParentOf<int>()); BOOST_CHECK(!tInt->isParentOf<unsigned>()); BOOST_CHECK(!tInt->isParentOf<test::Object>()); Type* tInterface = type<test::Interface>(); BOOST_CHECK( tInterface->isParentOf<test::Interface>()); BOOST_CHECK( tInterface->isParentOf<test::Parent>()); BOOST_CHECK( tInterface->isParentOf<test::Child>()); BOOST_CHECK(!tInterface->isParentOf<test::Object>()); BOOST_CHECK( tInterface->isChildOf<test::Interface>()); BOOST_CHECK(!tInterface->isChildOf<test::Parent>()); BOOST_CHECK(!tInterface->isChildOf<test::Child>()); BOOST_CHECK(!tInterface->isChildOf<test::Object>()); Type* tParent = type<test::Parent>(); BOOST_CHECK(!tParent->isParentOf<test::Interface>()); BOOST_CHECK( tParent->isParentOf<test::Parent>()); BOOST_CHECK( tParent->isParentOf<test::Child>()); BOOST_CHECK(!tParent->isParentOf<test::Object>()); BOOST_CHECK( tParent->isChildOf<test::Interface>()); BOOST_CHECK( tParent->isChildOf<test::Parent>()); BOOST_CHECK(!tParent->isChildOf<test::Child>()); BOOST_CHECK(!tParent->isChildOf<test::Object>()); Type* tChild = type<test::Child>(); BOOST_CHECK(!tChild->isParentOf<test::Interface>()); BOOST_CHECK(!tChild->isParentOf<test::Parent>()); BOOST_CHECK( tChild->isParentOf<test::Child>()); BOOST_CHECK(!tChild->isParentOf<test::Object>()); BOOST_CHECK( tChild->isChildOf<test::Interface>()); BOOST_CHECK( tChild->isChildOf<test::Parent>()); BOOST_CHECK( tChild->isChildOf<test::Child>()); BOOST_CHECK(!tChild->isChildOf<test::Object>()); } BOOST_AUTO_TEST_CASE(converter) { Type* tParent = type<test::Parent>(); BOOST_CHECK(!tParent->hasConverter<int>()); BOOST_CHECK(!tParent->hasConverter<test::Parent>()); BOOST_CHECK(!tParent->hasConverter<test::Convertible>()); Type* tConvertible = type<test::Convertible>(); BOOST_CHECK( tConvertible->hasConverter<int>()); BOOST_CHECK( tConvertible->hasConverter<test::Parent>()); BOOST_CHECK(!tConvertible->hasConverter<test::Convertible>()); } <|endoftext|>
<commit_before>#include <config.h> #include <assert.h> #include <dune/common/exceptions.hh> #include <dune/xt/common/logging.hh> #include <dune/xt/common/validation.hh> #include <dune/xt/common/configuration.hh> #include <sstream> #include "dune/multiscale/problems/base.hh" #include "spe10.hh" namespace Dune { namespace Multiscale { namespace Problem { namespace SPE10 { static const std::string model2_filename = "spe10_permeability.dat"; static const size_t model2_x_elements = 60; static const size_t model2_y_elements = 220; static const size_t model2_z_elements = 85; static const double model_2_length_x = 365.76; static const double model_2_length_y = 670.56; static const double model_2_length_z = 51.816; static const double model_2_min_value = 6.65e-8; // isotropic: 0.000665 static const double model_2_max_value = 20000; ModelProblemData::ModelProblemData(MPIHelper::MPICommunicator global, MPIHelper::MPICommunicator local, Dune::XT::Common::Configuration config_in) : IModelProblemData(global, local, config_in) , subBoundaryInfo_() { boundaryInfo_ = std::unique_ptr<ModelProblemData::BoundaryInfoType>( DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings())); subBoundaryInfo_ = std::unique_ptr<ModelProblemData::SubBoundaryInfoType>( DSG::BoundaryInfos::NormalBased<typename SubView::Intersection>::create(boundary_settings())); } Dune::XT::Common::Configuration default_config() { Dune::XT::Common::Configuration config; config["filename"] = model2_filename; config["name"] = "Spe10Diffusion"; config["lower_left"] = "[0 0 0]"; config["upper_right"] = "[" + Dune::XT::Common::to_string(model_2_length_x) + " " + Dune::XT::Common::to_string(model_2_length_y) + " " + Dune::XT::Common::to_string(model_2_length_z)+ "]"; config["upper_right"] = "[2 5 1]"; config["anisotropic"] = "true"; config["min"] = Dune::XT::Common::to_string(model_2_min_value); config["max"] = Dune::XT::Common::to_string(model_2_max_value); return config; } // ... default_config(...) std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const { CommonTraits::DomainType lowerLeft(0.0); CommonTraits::DomainType upperRight(0.0); if(View::dimension != 3) DUNE_THROW(Dune::InvalidStateException, "SPE data only available for world dim == 3"); const auto ll = default_config().get< CommonTraits::DomainType >("lower_left"); const auto ur = default_config().get< CommonTraits::DomainType >("upper_right"); return {ll, ur}; } const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; } const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return *subBoundaryInfo_; } ParameterTree ModelProblemData::boundary_settings() const { Dune::ParameterTree boundarySettings; if (DXTC_CONFIG.has_sub("problem.boundaryInfo")) { boundarySettings = DXTC_CONFIG.sub("problem.boundaryInfo"); } else { boundarySettings["default"] = "neumann"; boundarySettings["compare_tolerance"] = "1e-10"; switch (View::dimension /*View is defined in IModelProblemData*/) { case 1: DUNE_THROW(NotImplemented, "Boundary values are not implemented for SPE10 in 1D!"); break; case 2: boundarySettings["dirichlet.0"] = "[0.0 1.0]"; break; case 3: boundarySettings["dirichlet.0"] = "[0.0 1.0 0.0]"; } } return boundarySettings; } void DirichletData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.0; } // evaluate void NeumannData::evaluate(const DomainType& x, RangeType& y) const { if (Dune::XT::Common::FloatCmp::eq(x[0], CommonTraits::RangeFieldType(0))) y = 1.0; else y = 0.0; } // evaluate Source::Source(MPIHelper::MPICommunicator /*global*/, MPIHelper::MPICommunicator /*local*/, Dune::XT::Common::Configuration /*config_in*/) {} void __attribute__((hot)) Source::evaluate(const DomainType& /*x*/, RangeType& y) const { y = typename CommonTraits::RangeType(0.0); } // evaluate Diffusion::Diffusion(MPIHelper::MPICommunicator /*global*/, MPIHelper::MPICommunicator /*local*/, Dune::XT::Common::Configuration /*config_in*/) : permeability_(nullptr) { readPermeability(); } Diffusion::~Diffusion() { } void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& y) const { BOOST_ASSERT_MSG(x.size() <= 3, "SPE 10 model is only defined for up to three dimensions!"); // TODO this class does not seem to work in 2D, when changing 'spe10.dgf' to a 2D grid? if (!permeability_) { MS_LOG_ERROR_0 << "The SPE10-permeability data file could not be opened. This file does\n" << "not come with the dune-multiscale repository due to file size. To download it\n" << "execute\n" << "wget http://www.spe.org/web/csp/datasets/por_perm_case2a.zip\n" << "unzip the file and move the file 'spe_perm.dat' to\n" << "dune-multiscale/dune/multiscale/problems/spe10_permeability.dat!\n"; DUNE_THROW(IOError, "Data file for Groundwaterflow permeability could not be opened!"); } // 3 is the maximum space dimension const auto center = x; std::vector<size_t> whichPartition(dimDomain, 0); const Dune::XT::Common::FieldVector< CommonTraits::DomainFieldType, CommonTraits::world_dim > ll = default_config().get< CommonTraits::DomainType >("lower_left"); const Dune::XT::Common::FieldVector< CommonTraits::DomainFieldType, CommonTraits::world_dim > ur = default_config().get< CommonTraits::DomainType >("upper_right"); std::array<size_t, CommonTraits::world_dim> ne{{model2_x_elements, model2_y_elements, model2_z_elements}}; for (size_t dd = 0; dd < dimDomain; ++dd) { // for points that are on upperRight_[d], this selects one partition too much // so we need to cap this whichPartition[dd] = std::min(size_t(std::floor(ne[dd] * ((center[dd] - ll[dd]) / (ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1] * ne[0]; else subdomain = whichPartition[0] + whichPartition[1] * ne[0] + whichPartition[2] * ne[1] * ne[0]; const auto ii = subdomain; const size_t entries_per_dim = model2_x_elements*model2_y_elements*model2_z_elements; const bool anisotropic = true; y[0][0] = permeability_[ii]; y[1][1] = permeability_[anisotropic ? entries_per_dim + ii : ii]; y[2][2] = permeability_[anisotropic ? 2*entries_per_dim + ii : ii]; } void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction, Problem::JacobianRangeType& flux) const { Diffusion::RangeType eval_tmp; evaluate(x, eval_tmp); eval_tmp.mv(direction[0], flux[0]); } // diffusiveFlux void Diffusion::readPermeability() { auto min = default_config().get< RangeFieldType >("min"); auto max = default_config().get< RangeFieldType >("max"); std::ifstream datafile(model2_filename); if (!datafile.is_open()) DUNE_THROW(spe10_model2_data_file_missing, "could not open '" << model2_filename << "'!"); if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (model_2_max_value - model_2_min_value); const RangeFieldType shift = min - scale*model_2_min_value; // read all the data from the file const size_t entries_per_dim = model2_x_elements*model2_y_elements*model2_z_elements; // std::vector< double > data(3*entries_per_dim); const size_t data_size = 3*entries_per_dim; permeability_ = std::unique_ptr<double[]>(new double[data_size]()); double tmp = 0; size_t counter = 0; while (datafile >> tmp) { permeability_[counter++] = (tmp*scale) + shift; } datafile.close(); if (counter != data_size) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << model2_filename << "' (are " << counter << ", should be " << data_size << ")!"); return; } /* readPermeability */ } // namespace SPE10 } // namespace Problem } // namespace Multiscale { } // namespace Dune { <commit_msg>[spe10] fix neumann boundary values<commit_after>#include <config.h> #include <assert.h> #include <dune/common/exceptions.hh> #include <dune/xt/common/logging.hh> #include <dune/xt/common/validation.hh> #include <dune/xt/common/configuration.hh> #include <sstream> #include "dune/multiscale/problems/base.hh" #include "spe10.hh" namespace Dune { namespace Multiscale { namespace Problem { namespace SPE10 { static const std::string model2_filename = "spe10_permeability.dat"; static const size_t model2_x_elements = 60; static const size_t model2_y_elements = 220; static const size_t model2_z_elements = 85; static const double model_2_length_x = 365.76; static const double model_2_length_y = 670.56; static const double model_2_length_z = 51.816; static const double model_2_min_value = 6.65e-8; // isotropic: 0.000665 static const double model_2_max_value = 20000; ModelProblemData::ModelProblemData(MPIHelper::MPICommunicator global, MPIHelper::MPICommunicator local, Dune::XT::Common::Configuration config_in) : IModelProblemData(global, local, config_in) , subBoundaryInfo_() { boundaryInfo_ = std::unique_ptr<ModelProblemData::BoundaryInfoType>( DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings())); subBoundaryInfo_ = std::unique_ptr<ModelProblemData::SubBoundaryInfoType>( DSG::BoundaryInfos::NormalBased<typename SubView::Intersection>::create(boundary_settings())); } Dune::XT::Common::Configuration default_config() { Dune::XT::Common::Configuration config; config["filename"] = model2_filename; config["name"] = "Spe10Diffusion"; config["lower_left"] = "[0 0 0]"; config["upper_right"] = "[" + Dune::XT::Common::to_string(model_2_length_x) + " " + Dune::XT::Common::to_string(model_2_length_y) + " " + Dune::XT::Common::to_string(model_2_length_z)+ "]"; config["upper_right"] = "[2 5 1]"; config["anisotropic"] = "true"; config["min"] = Dune::XT::Common::to_string(model_2_min_value); config["max"] = Dune::XT::Common::to_string(model_2_max_value); return config; } // ... default_config(...) std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const { CommonTraits::DomainType lowerLeft(0.0); CommonTraits::DomainType upperRight(0.0); if(View::dimension != 3) DUNE_THROW(Dune::InvalidStateException, "SPE data only available for world dim == 3"); const auto ll = default_config().get< CommonTraits::DomainType >("lower_left"); const auto ur = default_config().get< CommonTraits::DomainType >("upper_right"); return {ll, ur}; } const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; } const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return *subBoundaryInfo_; } ParameterTree ModelProblemData::boundary_settings() const { Dune::ParameterTree boundarySettings; if (DXTC_CONFIG.has_sub("problem.boundaryInfo")) { boundarySettings = DXTC_CONFIG.sub("problem.boundaryInfo"); } else { boundarySettings["default"] = "neumann"; boundarySettings["compare_tolerance"] = "1e-10"; switch (View::dimension /*View is defined in IModelProblemData*/) { case 1: DUNE_THROW(NotImplemented, "Boundary values are not implemented for SPE10 in 1D!"); break; case 2: boundarySettings["dirichlet.0"] = "[0.0 1.0]"; break; case 3: boundarySettings["dirichlet.0"] = "[0.0 1.0 0.0]"; } } return boundarySettings; } void DirichletData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.0; } // evaluate void NeumannData::evaluate(const DomainType& x, RangeType& y) const { if (Dune::XT::Common::FloatCmp::eq(x[1], CommonTraits::RangeFieldType(0))) y = 1.0; else y = 0.0; } // evaluate Source::Source(MPIHelper::MPICommunicator /*global*/, MPIHelper::MPICommunicator /*local*/, Dune::XT::Common::Configuration /*config_in*/) {} void __attribute__((hot)) Source::evaluate(const DomainType& /*x*/, RangeType& y) const { y = typename CommonTraits::RangeType(0.0); } // evaluate Diffusion::Diffusion(MPIHelper::MPICommunicator /*global*/, MPIHelper::MPICommunicator /*local*/, Dune::XT::Common::Configuration /*config_in*/) : permeability_(nullptr) { readPermeability(); } Diffusion::~Diffusion() { } void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& y) const { BOOST_ASSERT_MSG(x.size() <= 3, "SPE 10 model is only defined for up to three dimensions!"); // TODO this class does not seem to work in 2D, when changing 'spe10.dgf' to a 2D grid? if (!permeability_) { MS_LOG_ERROR_0 << "The SPE10-permeability data file could not be opened. This file does\n" << "not come with the dune-multiscale repository due to file size. To download it\n" << "execute\n" << "wget http://www.spe.org/web/csp/datasets/por_perm_case2a.zip\n" << "unzip the file and move the file 'spe_perm.dat' to\n" << "dune-multiscale/dune/multiscale/problems/spe10_permeability.dat!\n"; DUNE_THROW(IOError, "Data file for Groundwaterflow permeability could not be opened!"); } // 3 is the maximum space dimension const auto center = x; std::vector<size_t> whichPartition(dimDomain, 0); const Dune::XT::Common::FieldVector< CommonTraits::DomainFieldType, CommonTraits::world_dim > ll = default_config().get< CommonTraits::DomainType >("lower_left"); const Dune::XT::Common::FieldVector< CommonTraits::DomainFieldType, CommonTraits::world_dim > ur = default_config().get< CommonTraits::DomainType >("upper_right"); std::array<size_t, CommonTraits::world_dim> ne{{model2_x_elements, model2_y_elements, model2_z_elements}}; for (size_t dd = 0; dd < dimDomain; ++dd) { // for points that are on upperRight_[d], this selects one partition too much // so we need to cap this whichPartition[dd] = std::min(size_t(std::floor(ne[dd] * ((center[dd] - ll[dd]) / (ur[dd] - ll[dd])))), ne[dd] - 1); } size_t subdomain = 0; if (dimDomain == 1) subdomain = whichPartition[0]; else if (dimDomain == 2) subdomain = whichPartition[0] + whichPartition[1] * ne[0]; else subdomain = whichPartition[0] + whichPartition[1] * ne[0] + whichPartition[2] * ne[1] * ne[0]; const auto ii = subdomain; const size_t entries_per_dim = model2_x_elements*model2_y_elements*model2_z_elements; const bool anisotropic = true; y[0][0] = permeability_[ii]; y[1][1] = permeability_[anisotropic ? entries_per_dim + ii : ii]; y[2][2] = permeability_[anisotropic ? 2*entries_per_dim + ii : ii]; } void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction, Problem::JacobianRangeType& flux) const { Diffusion::RangeType eval_tmp; evaluate(x, eval_tmp); eval_tmp.mv(direction[0], flux[0]); } // diffusiveFlux void Diffusion::readPermeability() { auto min = default_config().get< RangeFieldType >("min"); auto max = default_config().get< RangeFieldType >("max"); std::ifstream datafile(model2_filename); if (!datafile.is_open()) DUNE_THROW(spe10_model2_data_file_missing, "could not open '" << model2_filename << "'!"); if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (model_2_max_value - model_2_min_value); const RangeFieldType shift = min - scale*model_2_min_value; // read all the data from the file const size_t entries_per_dim = model2_x_elements*model2_y_elements*model2_z_elements; // std::vector< double > data(3*entries_per_dim); const size_t data_size = 3*entries_per_dim; permeability_ = std::unique_ptr<double[]>(new double[data_size]()); double tmp = 0; size_t counter = 0; while (datafile >> tmp) { permeability_[counter++] = (tmp*scale) + shift; } datafile.close(); if (counter != data_size) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << model2_filename << "' (are " << counter << ", should be " << data_size << ")!"); return; } /* readPermeability */ } // namespace SPE10 } // namespace Problem } // namespace Multiscale { } // namespace Dune { <|endoftext|>
<commit_before>// Copyright @ Chun Shen 2016 // to compile the code: // g++ convert_to_binary.cpp -lz -o convert_to_binary.e #include <iostream> #include <sstream> #include <fstream> #include <cstdlib> #include "zlib.h" using namespace std; int main(int argc, char *argv[]) { string input_filename; if (argc < 2) { cout << "Usage: " << argv[0] << " filename [format]" << endl; cout << "--- format: gz [default], binary" << endl; exit(0); } else { input_filename = argv[1]; } string output_mode = "gz"; if (argc == 3) { output_mode = argv[2]; } string temp_filename = input_filename.substr(0, input_filename.find(".")); stringstream output_filename; output_filename << temp_filename << ".gz"; stringstream output_filename1; output_filename1 << temp_filename << ".bin"; ifstream urqmd_file(input_filename.c_str()); if (!urqmd_file.is_open()) { cout << "can not open " << input_filename << endl; cout << "exit" << endl; exit(1); } ofstream outbin; if (output_mode == "binary") { outbin.open(output_filename1.str().c_str(), ios::out | ios::binary); } gzFile fp_gz; if (output_mode == "gz") { fp_gz = gzopen(output_filename.str().c_str(), "wb"); } string temp_string; double dummy; int urqmd_id, urqmd_iso3, urqmd_charge, n_coll; int parent_id, parent_proc_type; double mass, t, x, y, z, E, px, py, pz; getline(urqmd_file, temp_string); while (!urqmd_file.eof()) { // skip the header for (int i = 0; i < 16; i++) getline(urqmd_file, temp_string); // get total number of particles getline(urqmd_file, temp_string); stringstream temp1(temp_string); int n_particles; temp1 >> n_particles; // get some information int n_info[8]; getline(urqmd_file, temp_string); stringstream temp2(temp_string); for (int i = 0; i < 8; i++) { temp2 >> n_info[i]; } if (output_mode == "gz") { gzprintf(fp_gz, "%d \n", n_particles); for (int i = 0; i < 8; i++) { gzprintf(fp_gz, "%d ", n_info[i]); } gzprintf(fp_gz, "\n"); } else if (output_mode == "binary") { outbin.write(reinterpret_cast<char *>(&n_particles), sizeof(int)); for (int i = 0; i < 8; i++) { outbin.write(reinterpret_cast<char *>(&n_info[i]), sizeof(int)); } } for (int i = 0; i < n_particles; i++) { getline(urqmd_file, temp_string); stringstream temp3(temp_string); temp3 >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> mass >> urqmd_id >> urqmd_iso3 >> urqmd_charge >> parent_id >> n_coll >> parent_proc_type >> t >> x >> y >> z >> E >> px >> py >> pz; if (output_mode == "gz") { gzprintf(fp_gz, "%d %d %d %d %d %d ", urqmd_id, urqmd_iso3, urqmd_charge, n_coll, parent_id, parent_proc_type); gzprintf(fp_gz, "%.7e %.7e %.7e %.7e %.7e %.7e %.7e %.7e %.7e\n", mass, t, x, y, z, E, px, py, pz); } else if (output_mode == "binary") { int info_array[] = {urqmd_id, urqmd_iso3, urqmd_charge, n_coll, parent_id, parent_proc_type}; float particle_array[] = {mass, t, x, y, z, E, px, py, pz}; for (int ii = 0; ii < 6; ii++) { outbin.write(reinterpret_cast<char *>(&(info_array[ii])), sizeof(int)); } for (int ii = 0; ii < 9; ii++) { outbin.write( reinterpret_cast<char *>(&(particle_array[ii])), sizeof(float)); } } } getline(urqmd_file, temp_string); } if (output_mode == "gz") { gzclose(fp_gz); } else if (output_mode == "binary") { outbin.close(); } urqmd_file.close(); return 0; } <commit_msg>supress warning for the converting script<commit_after>// Copyright @ Chun Shen 2016 // to compile the code: // g++ convert_to_binary.cpp -lz -o convert_to_binary.e #include <iostream> #include <sstream> #include <fstream> #include <cstdlib> #include "zlib.h" using namespace std; int main(int argc, char *argv[]) { string input_filename; if (argc < 2) { cout << "Usage: " << argv[0] << " filename [format]" << endl; cout << "--- format: gz [default], binary" << endl; exit(0); } else { input_filename = argv[1]; } string output_mode = "gz"; if (argc == 3) { output_mode = argv[2]; } string temp_filename = input_filename.substr(0, input_filename.find(".")); stringstream output_filename; output_filename << temp_filename << ".gz"; stringstream output_filename1; output_filename1 << temp_filename << ".bin"; ifstream urqmd_file(input_filename.c_str()); if (!urqmd_file.is_open()) { cout << "can not open " << input_filename << endl; cout << "exit" << endl; exit(1); } ofstream outbin; if (output_mode == "binary") { outbin.open(output_filename1.str().c_str(), ios::out | ios::binary); } gzFile fp_gz; if (output_mode == "gz") { fp_gz = gzopen(output_filename.str().c_str(), "wb"); } string temp_string; double dummy; int urqmd_id, urqmd_iso3, urqmd_charge, n_coll; int parent_id, parent_proc_type; double mass, t, x, y, z, E, px, py, pz; getline(urqmd_file, temp_string); while (!urqmd_file.eof()) { // skip the header for (int i = 0; i < 16; i++) getline(urqmd_file, temp_string); // get total number of particles getline(urqmd_file, temp_string); stringstream temp1(temp_string); int n_particles; temp1 >> n_particles; // get some information int n_info[8]; getline(urqmd_file, temp_string); stringstream temp2(temp_string); for (int i = 0; i < 8; i++) { temp2 >> n_info[i]; } if (output_mode == "gz") { gzprintf(fp_gz, "%d \n", n_particles); for (int i = 0; i < 8; i++) { gzprintf(fp_gz, "%d ", n_info[i]); } gzprintf(fp_gz, "\n"); } else if (output_mode == "binary") { outbin.write(reinterpret_cast<char *>(&n_particles), sizeof(int)); for (int i = 0; i < 8; i++) { outbin.write(reinterpret_cast<char *>(&n_info[i]), sizeof(int)); } } for (int i = 0; i < n_particles; i++) { getline(urqmd_file, temp_string); stringstream temp3(temp_string); temp3 >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> mass >> urqmd_id >> urqmd_iso3 >> urqmd_charge >> parent_id >> n_coll >> parent_proc_type >> t >> x >> y >> z >> E >> px >> py >> pz; if (output_mode == "gz") { gzprintf(fp_gz, "%d %d %d %d %d %d ", urqmd_id, urqmd_iso3, urqmd_charge, n_coll, parent_id, parent_proc_type); gzprintf(fp_gz, "%.7e %.7e %.7e %.7e %.7e %.7e %.7e %.7e %.7e\n", mass, t, x, y, z, E, px, py, pz); } else if (output_mode == "binary") { int info_array[] = {urqmd_id, urqmd_iso3, urqmd_charge, n_coll, parent_id, parent_proc_type}; float particle_array[] = {static_cast<float>(mass), static_cast<float>(t), static_cast<float>(x), static_cast<float>(y), static_cast<float>(z), static_cast<float>(E), static_cast<float>(px), static_cast<float>(py), static_cast<float>(pz)}; for (int ii = 0; ii < 6; ii++) { outbin.write(reinterpret_cast<char *>(&(info_array[ii])), sizeof(int)); } for (int ii = 0; ii < 9; ii++) { outbin.write( reinterpret_cast<char *>(&(particle_array[ii])), sizeof(float)); } } } getline(urqmd_file, temp_string); } if (output_mode == "gz") { gzclose(fp_gz); } else if (output_mode == "binary") { outbin.close(); } urqmd_file.close(); return 0; } <|endoftext|>
<commit_before>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/compiler/ast/expressions.h" #include "base/logging.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { namespace ast { ////////////////////////////////////////////////////////////////////// // // Expression // Expression::Expression(Token* op) : Node(nullptr, op) { } ArrayAccess::ArrayAccess(Zone* zone, Token* bracket, Expression* array, const std::vector<Expression*>& indexes) : Expression(bracket), array_(array), indexes_(zone, indexes) { DCHECK_EQ(bracket, TokenType::LeftSquareBracket); DCHECK(!indexes.empty()); } // Assignment Assignment::Assignment(Token* op, Expression* left, Expression* right) : Expression(op), left_(left), right_(right) { } // Binary operation BinaryOperation::BinaryOperation(Token* op, Expression* left, Expression* right) : Expression(op), left_(left), right_(right) { CHECK(is_arithmetic() || is_bitwise() || is_bitwise_shift() || is_conditional() || is_equality() || is_relational()); } bool BinaryOperation::is_arithmetic() const { return op() == TokenType::Add || op() == TokenType::Div || op() == TokenType::Mod || op() == TokenType::Mul || op() == TokenType::Sub; } bool BinaryOperation::is_bitwise() const { return op() == TokenType::BitAnd || op() == TokenType::BitOr || op() == TokenType::BitXor; } bool BinaryOperation::is_bitwise_shift() const { return op() == TokenType::Shl || op() == TokenType::Shr; } bool BinaryOperation::is_conditional() const { return op() == TokenType::And || op() == TokenType::NullOr || op() == TokenType::NullOr; } bool BinaryOperation::is_equality() const { return op() == TokenType::Eq || op() == TokenType::Ne; } bool BinaryOperation::is_relational() const { return op() == TokenType::Ge || op() == TokenType::Gt || op() == TokenType::Le || op() == TokenType::Lt; } // Call Call::Call(Zone* zone, Expression* callee, const std::vector<Expression*>& arguments) : Expression(callee->token()), arguments_(zone, arguments), callee_(callee) { } Conditional::Conditional(Token* op, Expression* condition, Expression* true_expression, Expression* false_expression) : Expression(op), condition_(condition), false_expression_(false_expression), true_expression_(true_expression) { } // ConstructedName ConstructedName::ConstructedName(Zone* zone, NameReference* reference, const std::vector<Type*>& args) : Expression(reference->name()), arguments_(zone, args), reference_(reference) { DCHECK(!arguments_.empty()); } // InvalidExpression InvalidExpression::InvalidExpression(Token* token) : Expression(token) { // We should have non-null |token| for source code location. DCHECK(token); } Literal::Literal(Token* literal) : Expression(literal) { } MemberAccess::MemberAccess(Zone* zone, Token* name, const std::vector<Expression*>& components) : Expression(name), components_(zone, components) { DCHECK_GE(components.size(), 2u); } NameReference::NameReference(Token* name) : Expression(name) { DCHECK(name->is_name() || name->is_type_name() || name == TokenType::Var); } // ParameterReference ParameterReference::ParameterReference(Token* name, Parameter* parameter) : Expression(name), parameter_(parameter) { } UnaryOperation::UnaryOperation(Token* op, Expression* expression) : Expression(op), expression_(expression) { } // Variable Variable::Variable(Token* keyword, Type* type, Token* name, Expression* value) : NamedNode(nullptr, keyword, name), type_(type), value_(value) { DCHECK(keyword == type->token() || keyword == TokenType::Const || keyword == TokenType::Catch || keyword == TokenType::For || keyword == TokenType::Using) << *keyword << " " << *type << *name; } bool Variable::is_const() const { return token() == TokenType::Const || token() == TokenType::Using; } // VariableReference VariableReference::VariableReference(Token* name, Variable* variable) : Expression(name), variable_(variable) { } ////////////////////////////////////////////////////////////////////// // // Types // // Type Type::Type(Token* token) : Expression(token) { } // ArrayType ArrayType::ArrayType(Zone* zone, Token* op, Type* element_type, const std::vector<int>& ranks) : Type(op), element_type_(element_type), ranks_(zone, ranks) { } // ConstructedType ConstructedType::ConstructedType(ConstructedName* reference) : Type(reference->token()), reference_(reference) { } // InvalidType InvalidType::InvalidType(Expression* expression) : Type(expression->token()), expression_(expression) { } // OptionalType OptionalType::OptionalType(Token* op, Type* base_type) : Type(op), base_type_(base_type) { DCHECK_EQ(op, TokenType::OptionalType); } // TypeMemberAccess TypeMemberAccess::TypeMemberAccess(MemberAccess* reference) : Type(reference->token()), reference_(reference) { } // TypeNameReference TypeNameReference::TypeNameReference(NameReference* reference) : Type(reference->token()), reference_(reference) { } Token* TypeNameReference::name() const { return reference_->name(); } } // namespace ast } // namespace compiler } // namespace elang <commit_msg>elang/compiler: Make |ast::BinaryOperation| constructor to accept |TokenType::Or|.<commit_after>// Copyright 2014-2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/compiler/ast/expressions.h" #include "base/logging.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { namespace ast { ////////////////////////////////////////////////////////////////////// // // Expression // Expression::Expression(Token* op) : Node(nullptr, op) { } ArrayAccess::ArrayAccess(Zone* zone, Token* bracket, Expression* array, const std::vector<Expression*>& indexes) : Expression(bracket), array_(array), indexes_(zone, indexes) { DCHECK_EQ(bracket, TokenType::LeftSquareBracket); DCHECK(!indexes.empty()); } // Assignment Assignment::Assignment(Token* op, Expression* left, Expression* right) : Expression(op), left_(left), right_(right) { } // Binary operation BinaryOperation::BinaryOperation(Token* op, Expression* left, Expression* right) : Expression(op), left_(left), right_(right) { CHECK(is_arithmetic() || is_bitwise() || is_bitwise_shift() || is_conditional() || is_equality() || is_relational()); } bool BinaryOperation::is_arithmetic() const { return op() == TokenType::Add || op() == TokenType::Div || op() == TokenType::Mod || op() == TokenType::Mul || op() == TokenType::Sub; } bool BinaryOperation::is_bitwise() const { return op() == TokenType::BitAnd || op() == TokenType::BitOr || op() == TokenType::BitXor; } bool BinaryOperation::is_bitwise_shift() const { return op() == TokenType::Shl || op() == TokenType::Shr; } bool BinaryOperation::is_conditional() const { return op() == TokenType::And || op() == TokenType::NullOr || op() == TokenType::Or; } bool BinaryOperation::is_equality() const { return op() == TokenType::Eq || op() == TokenType::Ne; } bool BinaryOperation::is_relational() const { return op() == TokenType::Ge || op() == TokenType::Gt || op() == TokenType::Le || op() == TokenType::Lt; } // Call Call::Call(Zone* zone, Expression* callee, const std::vector<Expression*>& arguments) : Expression(callee->token()), arguments_(zone, arguments), callee_(callee) { } Conditional::Conditional(Token* op, Expression* condition, Expression* true_expression, Expression* false_expression) : Expression(op), condition_(condition), false_expression_(false_expression), true_expression_(true_expression) { } // ConstructedName ConstructedName::ConstructedName(Zone* zone, NameReference* reference, const std::vector<Type*>& args) : Expression(reference->name()), arguments_(zone, args), reference_(reference) { DCHECK(!arguments_.empty()); } // InvalidExpression InvalidExpression::InvalidExpression(Token* token) : Expression(token) { // We should have non-null |token| for source code location. DCHECK(token); } Literal::Literal(Token* literal) : Expression(literal) { } MemberAccess::MemberAccess(Zone* zone, Token* name, const std::vector<Expression*>& components) : Expression(name), components_(zone, components) { DCHECK_GE(components.size(), 2u); } NameReference::NameReference(Token* name) : Expression(name) { DCHECK(name->is_name() || name->is_type_name() || name == TokenType::Var); } // ParameterReference ParameterReference::ParameterReference(Token* name, Parameter* parameter) : Expression(name), parameter_(parameter) { } UnaryOperation::UnaryOperation(Token* op, Expression* expression) : Expression(op), expression_(expression) { } // Variable Variable::Variable(Token* keyword, Type* type, Token* name, Expression* value) : NamedNode(nullptr, keyword, name), type_(type), value_(value) { DCHECK(keyword == type->token() || keyword == TokenType::Const || keyword == TokenType::Catch || keyword == TokenType::For || keyword == TokenType::Using) << *keyword << " " << *type << *name; } bool Variable::is_const() const { return token() == TokenType::Const || token() == TokenType::Using; } // VariableReference VariableReference::VariableReference(Token* name, Variable* variable) : Expression(name), variable_(variable) { } ////////////////////////////////////////////////////////////////////// // // Types // // Type Type::Type(Token* token) : Expression(token) { } // ArrayType ArrayType::ArrayType(Zone* zone, Token* op, Type* element_type, const std::vector<int>& ranks) : Type(op), element_type_(element_type), ranks_(zone, ranks) { } // ConstructedType ConstructedType::ConstructedType(ConstructedName* reference) : Type(reference->token()), reference_(reference) { } // InvalidType InvalidType::InvalidType(Expression* expression) : Type(expression->token()), expression_(expression) { } // OptionalType OptionalType::OptionalType(Token* op, Type* base_type) : Type(op), base_type_(base_type) { DCHECK_EQ(op, TokenType::OptionalType); } // TypeMemberAccess TypeMemberAccess::TypeMemberAccess(MemberAccess* reference) : Type(reference->token()), reference_(reference) { } // TypeNameReference TypeNameReference::TypeNameReference(NameReference* reference) : Type(reference->token()), reference_(reference) { } Token* TypeNameReference::name() const { return reference_->name(); } } // namespace ast } // namespace compiler } // namespace elang <|endoftext|>
<commit_before>/* * Copyright (C) 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "platform.h" #include "base_swapchain.h" namespace swapchain { namespace { VkResult createSemaphore(const DeviceData *device_functions, VkDevice device, const VkAllocationCallbacks *pAllocator, VkSemaphore *pSem) { VkSemaphoreCreateInfo createInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, // sType nullptr, // pNext 0, // flags }; return device_functions->vkCreateSemaphore(device, &createInfo, pAllocator, pSem); } VkResult createSemaphores(const DeviceData *device_functions, VkDevice device, const VkAllocationCallbacks *pAllocator, size_t count, std::vector<VkSemaphore> &sems) { sems.resize(count); for (VkSemaphore &sem : sems) { VkResult res; if ((res = createSemaphore(device_functions, device, pAllocator, &sem)) != VK_SUCCESS) { return res; } } return VK_SUCCESS; } void destroySemaphores(const DeviceData *device_functions, VkDevice device, const VkAllocationCallbacks *pAllocator, std::vector<VkSemaphore> &sems) { for (VkSemaphore sem : sems) { device_functions->vkDestroySemaphore(device, sem, pAllocator); } sems.clear(); } } // namespace BaseSwapchain::BaseSwapchain(VkInstance instance, VkDevice device, uint32_t queue, VkCommandPool command_pool, uint32_t num_images, const InstanceData *instance_functions, const DeviceData *device_functions, const VkSwapchainCreateInfoKHR *swapchain_info, const VkAllocationCallbacks *pAllocator, const void *platform_info) : instance_(instance), device_(device), instance_functions_(instance_functions), device_functions_(device_functions), swapchain_info_(*swapchain_info) { if (platform_info == nullptr) { return; } CreateSurface(instance_functions, instance, platform_info, pAllocator, &surface_); if (surface_ == 0) { // Surface creation failed return; } { // Create the swapchain VkSwapchainCreateInfoKHR createInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, // sType nullptr, // pNext 0, // flags surface_, // surface num_images, // minImageCount swapchain_info_.imageFormat, // imageFormat swapchain_info_.imageColorSpace, // imageColorSpace swapchain_info_.imageExtent, // imageExtent swapchain_info_.imageArrayLayers, // arrayLayers VK_IMAGE_USAGE_TRANSFER_DST_BIT, // imageUsage VK_SHARING_MODE_EXCLUSIVE, // imageSharingMode, 0, // queueFamilyIndexCount nullptr, // pQueueFamilyIndices swapchain_info_.preTransform, // preTransform swapchain_info_.compositeAlpha, // compositeAlpha VK_PRESENT_MODE_FIFO_KHR, // presentMode VK_TRUE, // clipped 0, // oldSwapchain }; if (device_functions_->vkCreateSwapchainKHR( device_, &createInfo, pAllocator, &swapchain_) != VK_SUCCESS) { // Creating swapchain failed swapchain_ = 0; return; } } uint32_t num_base_images = 0; device_functions_->vkGetSwapchainImagesKHR(device, swapchain_, &num_base_images, nullptr); images_.resize(num_base_images); device_functions_->vkGetSwapchainImagesKHR(device, swapchain_, &num_base_images, images_.data()); // Create a command buffer for each virtual image to blit from VkCommandBufferAllocateInfo command_buffer_info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType nullptr, // pNext command_pool, // commandPool VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level num_images, // commandBufferCount }; command_buffers_.resize(num_images); if (device_functions_->vkAllocateCommandBuffers(device, &command_buffer_info, command_buffers_.data()) != VK_SUCCESS) { return; } for (VkCommandBuffer cmdbuf : command_buffers_) { set_dispatch_from_parent(cmdbuf, device); } if (createSemaphore(device_functions_, device_, pAllocator, &acquire_semaphore_) != VK_SUCCESS) { return; } if (createSemaphores(device_functions_, device_, pAllocator, num_images, blit_semaphores_) != VK_SUCCESS) { return; } if (createSemaphores(device_functions_, device_, pAllocator, num_images, present_semaphores_) != VK_SUCCESS) { return; } is_pending_.resize(num_images); } void BaseSwapchain::Destroy(const VkAllocationCallbacks *pAllocator) { device_functions_->vkDestroySemaphore(device_, acquire_semaphore_, pAllocator); acquire_semaphore_ = VK_NULL_HANDLE; destroySemaphores(device_functions_, device_, pAllocator, blit_semaphores_); destroySemaphores(device_functions_, device_, pAllocator, present_semaphores_); device_functions_->vkDestroySwapchainKHR(device_, swapchain_, pAllocator); swapchain_ = VK_NULL_HANDLE; instance_functions_->vkDestroySurfaceKHR(instance_, surface_, pAllocator); surface_ = VK_NULL_HANDLE; images_.clear(); is_pending_.clear(); command_buffers_.clear(); } VkResult BaseSwapchain::PresentFrom(VkQueue queue, size_t index, VkImage image) { std::unique_lock<threading::mutex> guard(present_lock_); VkResult res; uint32_t base_index = 0; // TODO: the error return values here aren't necessarily valid return values // for VkQueueSubmit if ((res = device_functions_->vkAcquireNextImageKHR( device_, swapchain_, 0, acquire_semaphore_, VK_NULL_HANDLE, &base_index)) != VK_SUCCESS) { return res; } VkCommandBuffer cmdbuf = command_buffers_[index]; if ((res = device_functions_->vkResetCommandBuffer(cmdbuf, 0)) != VK_SUCCESS) { return res; } VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType 0, // pNext VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, // flags nullptr, // pInheritanceInfo }; if ((res = device_functions_->vkBeginCommandBuffer(cmdbuf, &beginInfo)) != VK_SUCCESS) { return res; } // The source image is already in VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, we // need to transition our image between VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL // and VK_IMAGE_LAYOUT_PRESENT_SRC_KHR VkImageMemoryBarrier initialBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType nullptr, // pNext 0, // srcAccessFlags VK_ACCESS_TRANSFER_WRITE_BIT, // dstAccessFlags VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // oldLayout VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // newLayout VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex images_[base_index], // image VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask 0, // baseMipLevel 1, // levelCount 0, // baseArrayLayer swapchain_info_.imageArrayLayers, // layerCount }, // subresourceRange }; device_functions_->vkCmdPipelineBarrier( cmdbuf, 0, // srcStageMask VK_PIPELINE_STAGE_TRANSFER_BIT, // dstStageMask 0, // dependencyFlags 0, // memoryBarrierCount nullptr, // pMemoryBarriers 0, // bufferMemoryBarrierCount nullptr, // pBufferMemoryBarriers 1, // imageMemoryBarrierCount &initialBarrier // pImageMemoryBarriers ); VkImageSubresourceLayers subresource = { VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask 0, // mipLevel 0, // baseArrayLayer swapchain_info_.imageArrayLayers, // layerCount }; VkOffset3D offsets[2] = { { 0, 0, 0, }, { (int32_t)swapchain_info_.imageExtent.width, (int32_t)swapchain_info_.imageExtent.height, 1, }, }; VkImageBlit blit = { subresource, {offsets[0], offsets[1]}, subresource, {offsets[0], offsets[1]}, }; device_functions_->vkCmdBlitImage( cmdbuf, image, // srcImage VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, // srcImageLayout images_[base_index], // dstImage VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // dstImageLayout 1, // regionCount &blit, // pRegions VK_FILTER_NEAREST // filter ); VkImageMemoryBarrier finalBarrier = initialBarrier; finalBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; finalBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; finalBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; finalBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; device_functions_->vkCmdPipelineBarrier( cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, // srcStageMask 0, // dstStageMask 0, // dependencyFlags 0, // memoryBarrierCount nullptr, // pMemoryBarriers 0, // bufferMemoryBarrierCount nullptr, // pBufferMemoryBarriers 1, // imageMemoryBarrierCount &finalBarrier // pImageMemoryBarriers ); if ((res = device_functions_->vkEndCommandBuffer(cmdbuf)) != VK_SUCCESS) { return res; } VkSemaphore signal_semaphores[] = {blit_semaphores_[index], present_semaphores_[index]}; VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_TRANSFER_BIT; VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType 0, // pNext 1, // waitSemaphoreCount &acquire_semaphore_, // pWaitSemaphores &waitStage, // pWaitDstStageMask 1, // commandBufferCount &cmdbuf, // pCommandBuffers 2, // signalSemaphoreCount signal_semaphores, // pSignalSemaphores }; auto queue_functions = GetGlobalContext().GetQueueData(queue); if ((res = queue_functions->vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)) != VK_SUCCESS) { return res; } is_pending_[index] = true; VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // sType 0, // pNext 1, // waitSemaphoreCount &present_semaphores_[index], // waitSemaphores 1, // swapchainCount &swapchain_, // pSwapchains, &base_index, // pImageIndices nullptr, // pResults }; if ((res = queue_functions->vkQueuePresentKHR(queue, &presentInfo)) != VK_SUCCESS) { return res; } return VK_SUCCESS; } VkSemaphore BaseSwapchain::BlitWaitSemaphore(size_t index) { if (!is_pending_[index]) { return VK_NULL_HANDLE; } is_pending_[index] = false; return blit_semaphores_[index]; } } // namespace swapchain <commit_msg>Set timeout on base acquire image to UINT64_MAX<commit_after>/* * Copyright (C) 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "platform.h" #include "base_swapchain.h" namespace swapchain { namespace { VkResult createSemaphore(const DeviceData *device_functions, VkDevice device, const VkAllocationCallbacks *pAllocator, VkSemaphore *pSem) { VkSemaphoreCreateInfo createInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, // sType nullptr, // pNext 0, // flags }; return device_functions->vkCreateSemaphore(device, &createInfo, pAllocator, pSem); } VkResult createSemaphores(const DeviceData *device_functions, VkDevice device, const VkAllocationCallbacks *pAllocator, size_t count, std::vector<VkSemaphore> &sems) { sems.resize(count); for (VkSemaphore &sem : sems) { VkResult res; if ((res = createSemaphore(device_functions, device, pAllocator, &sem)) != VK_SUCCESS) { return res; } } return VK_SUCCESS; } void destroySemaphores(const DeviceData *device_functions, VkDevice device, const VkAllocationCallbacks *pAllocator, std::vector<VkSemaphore> &sems) { for (VkSemaphore sem : sems) { device_functions->vkDestroySemaphore(device, sem, pAllocator); } sems.clear(); } } // namespace BaseSwapchain::BaseSwapchain(VkInstance instance, VkDevice device, uint32_t queue, VkCommandPool command_pool, uint32_t num_images, const InstanceData *instance_functions, const DeviceData *device_functions, const VkSwapchainCreateInfoKHR *swapchain_info, const VkAllocationCallbacks *pAllocator, const void *platform_info) : instance_(instance), device_(device), instance_functions_(instance_functions), device_functions_(device_functions), swapchain_info_(*swapchain_info) { if (platform_info == nullptr) { return; } CreateSurface(instance_functions, instance, platform_info, pAllocator, &surface_); if (surface_ == 0) { // Surface creation failed return; } { // Create the swapchain VkSwapchainCreateInfoKHR createInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR, // sType nullptr, // pNext 0, // flags surface_, // surface num_images, // minImageCount swapchain_info_.imageFormat, // imageFormat swapchain_info_.imageColorSpace, // imageColorSpace swapchain_info_.imageExtent, // imageExtent swapchain_info_.imageArrayLayers, // arrayLayers VK_IMAGE_USAGE_TRANSFER_DST_BIT, // imageUsage VK_SHARING_MODE_EXCLUSIVE, // imageSharingMode, 0, // queueFamilyIndexCount nullptr, // pQueueFamilyIndices swapchain_info_.preTransform, // preTransform swapchain_info_.compositeAlpha, // compositeAlpha VK_PRESENT_MODE_FIFO_KHR, // presentMode VK_TRUE, // clipped 0, // oldSwapchain }; if (device_functions_->vkCreateSwapchainKHR( device_, &createInfo, pAllocator, &swapchain_) != VK_SUCCESS) { // Creating swapchain failed swapchain_ = 0; return; } } uint32_t num_base_images = 0; device_functions_->vkGetSwapchainImagesKHR(device, swapchain_, &num_base_images, nullptr); images_.resize(num_base_images); device_functions_->vkGetSwapchainImagesKHR(device, swapchain_, &num_base_images, images_.data()); // Create a command buffer for each virtual image to blit from VkCommandBufferAllocateInfo command_buffer_info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // sType nullptr, // pNext command_pool, // commandPool VK_COMMAND_BUFFER_LEVEL_PRIMARY, // level num_images, // commandBufferCount }; command_buffers_.resize(num_images); if (device_functions_->vkAllocateCommandBuffers(device, &command_buffer_info, command_buffers_.data()) != VK_SUCCESS) { return; } for (VkCommandBuffer cmdbuf : command_buffers_) { set_dispatch_from_parent(cmdbuf, device); } if (createSemaphore(device_functions_, device_, pAllocator, &acquire_semaphore_) != VK_SUCCESS) { return; } if (createSemaphores(device_functions_, device_, pAllocator, num_images, blit_semaphores_) != VK_SUCCESS) { return; } if (createSemaphores(device_functions_, device_, pAllocator, num_images, present_semaphores_) != VK_SUCCESS) { return; } is_pending_.resize(num_images); } void BaseSwapchain::Destroy(const VkAllocationCallbacks *pAllocator) { device_functions_->vkDestroySemaphore(device_, acquire_semaphore_, pAllocator); acquire_semaphore_ = VK_NULL_HANDLE; destroySemaphores(device_functions_, device_, pAllocator, blit_semaphores_); destroySemaphores(device_functions_, device_, pAllocator, present_semaphores_); device_functions_->vkDestroySwapchainKHR(device_, swapchain_, pAllocator); swapchain_ = VK_NULL_HANDLE; instance_functions_->vkDestroySurfaceKHR(instance_, surface_, pAllocator); surface_ = VK_NULL_HANDLE; images_.clear(); is_pending_.clear(); command_buffers_.clear(); } VkResult BaseSwapchain::PresentFrom(VkQueue queue, size_t index, VkImage image) { std::unique_lock<threading::mutex> guard(present_lock_); VkResult res; uint32_t base_index = 0; // TODO: the error return values here aren't necessarily valid return values // for VkQueueSubmit if ((res = device_functions_->vkAcquireNextImageKHR( device_, swapchain_, UINT64_MAX, acquire_semaphore_, VK_NULL_HANDLE, &base_index)) != VK_SUCCESS) { return res; } VkCommandBuffer cmdbuf = command_buffers_[index]; if ((res = device_functions_->vkResetCommandBuffer(cmdbuf, 0)) != VK_SUCCESS) { return res; } VkCommandBufferBeginInfo beginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType 0, // pNext VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, // flags nullptr, // pInheritanceInfo }; if ((res = device_functions_->vkBeginCommandBuffer(cmdbuf, &beginInfo)) != VK_SUCCESS) { return res; } // The source image is already in VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, we // need to transition our image between VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL // and VK_IMAGE_LAYOUT_PRESENT_SRC_KHR VkImageMemoryBarrier initialBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType nullptr, // pNext 0, // srcAccessFlags VK_ACCESS_TRANSFER_WRITE_BIT, // dstAccessFlags VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // oldLayout VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // newLayout VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex images_[base_index], // image VkImageSubresourceRange{ VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask 0, // baseMipLevel 1, // levelCount 0, // baseArrayLayer swapchain_info_.imageArrayLayers, // layerCount }, // subresourceRange }; device_functions_->vkCmdPipelineBarrier( cmdbuf, 0, // srcStageMask VK_PIPELINE_STAGE_TRANSFER_BIT, // dstStageMask 0, // dependencyFlags 0, // memoryBarrierCount nullptr, // pMemoryBarriers 0, // bufferMemoryBarrierCount nullptr, // pBufferMemoryBarriers 1, // imageMemoryBarrierCount &initialBarrier // pImageMemoryBarriers ); VkImageSubresourceLayers subresource = { VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask 0, // mipLevel 0, // baseArrayLayer swapchain_info_.imageArrayLayers, // layerCount }; VkOffset3D offsets[2] = { { 0, 0, 0, }, { (int32_t)swapchain_info_.imageExtent.width, (int32_t)swapchain_info_.imageExtent.height, 1, }, }; VkImageBlit blit = { subresource, {offsets[0], offsets[1]}, subresource, {offsets[0], offsets[1]}, }; device_functions_->vkCmdBlitImage( cmdbuf, image, // srcImage VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, // srcImageLayout images_[base_index], // dstImage VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // dstImageLayout 1, // regionCount &blit, // pRegions VK_FILTER_NEAREST // filter ); VkImageMemoryBarrier finalBarrier = initialBarrier; finalBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; finalBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; finalBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; finalBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; device_functions_->vkCmdPipelineBarrier( cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, // srcStageMask 0, // dstStageMask 0, // dependencyFlags 0, // memoryBarrierCount nullptr, // pMemoryBarriers 0, // bufferMemoryBarrierCount nullptr, // pBufferMemoryBarriers 1, // imageMemoryBarrierCount &finalBarrier // pImageMemoryBarriers ); if ((res = device_functions_->vkEndCommandBuffer(cmdbuf)) != VK_SUCCESS) { return res; } VkSemaphore signal_semaphores[] = {blit_semaphores_[index], present_semaphores_[index]}; VkPipelineStageFlags waitStage = VK_PIPELINE_STAGE_TRANSFER_BIT; VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType 0, // pNext 1, // waitSemaphoreCount &acquire_semaphore_, // pWaitSemaphores &waitStage, // pWaitDstStageMask 1, // commandBufferCount &cmdbuf, // pCommandBuffers 2, // signalSemaphoreCount signal_semaphores, // pSignalSemaphores }; auto queue_functions = GetGlobalContext().GetQueueData(queue); if ((res = queue_functions->vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)) != VK_SUCCESS) { return res; } is_pending_[index] = true; VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // sType 0, // pNext 1, // waitSemaphoreCount &present_semaphores_[index], // waitSemaphores 1, // swapchainCount &swapchain_, // pSwapchains, &base_index, // pImageIndices nullptr, // pResults }; if ((res = queue_functions->vkQueuePresentKHR(queue, &presentInfo)) != VK_SUCCESS) { return res; } return VK_SUCCESS; } VkSemaphore BaseSwapchain::BlitWaitSemaphore(size_t index) { if (!is_pending_[index]) { return VK_NULL_HANDLE; } is_pending_[index] = false; return blit_semaphores_[index]; } } // namespace swapchain <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: componentcontext.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: ihi $ $Date: 2007-11-21 16:51:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef COMPHELPER_COMPONENTCONTEXT_HXX #define COMPHELPER_COMPONENTCONTEXT_HXX #ifndef INCLUDED_COMPHELPERDLLAPI_H #include <comphelper/comphelperdllapi.h> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif /** === end UNO includes === **/ //........................................................................ namespace comphelper { //........................................................................ //==================================================================== //= ComponentContext //==================================================================== /** a helper class for working with a component context */ class COMPHELPER_DLLPUBLIC ComponentContext { private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory > m_xORB; public: /** constructs an instance @param _rxContext the component context to manage @throws ::com::sun::star::lang::NullPointerException if the given context, or its component factory, are <NULL/> */ ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext ); /** constructs an instance @param _rxLegacyFactory the legacy service factor to obtain the <type scope="com::sun::star::uno">XComponentContext</type> from @throws ::com::sun::star::uno::RuntimeException if the given factory or does not have a DefaultContext property to obtain a component context @throws ::com::sun::star::lang::NullPointerException if the given factory is <NULL/>, or provides a component context being <NULL/>, or provides a component context whose component factory is <NULL/> */ ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxLegacyFactory ); /** returns the ->XComponentContext interface */ inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > getUNOContext() const { return m_xContext; } /** determines whether the context is not <NULL/> */ inline sal_Bool is() const { return m_xContext.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { _out_rxComponent.clear(); _out_rxComponent = _out_rxComponent.query( m_xORB->createInstanceWithContext( _rServiceName, m_xContext ) ); return _out_rxComponent.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent ); } /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { _out_rxComponent.clear(); _out_rxComponent = _out_rxComponent.query( m_xORB->createInstanceWithArgumentsAndContext( _rServiceName, _rArguments, m_xContext ) ); return _out_rxComponent.is(); } /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments, _out_rxComponent ); } /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const; /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) ); } /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments ) const; /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments ) const { return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments ); } /** retrieves a singleton instance from the context Singletons are collected below the <code>/singletons</code> key in a component context, so accessing them means retrieving the value under <code>/singletons/&lt;instance_name&gt;</code>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const ::rtl::OUString& _rInstanceName ) const; /** retrieves a singleton instance from the context Singletons are collected below the <code>/singletons</code> key in a component context, so accessing them means retrieving the value under <code>/singletons/&lt;instance_name&gt;</code>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const sal_Char* _pAsciiInstanceName ) const { return getSingleton( ::rtl::OUString::createFromAscii( _pAsciiInstanceName ) ); } /** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to older code which does not yet support ->XMultiComponentFactory @throws ::com::sun::star::uno::RuntimeException if our our component factory does not support this interface */ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getLegacyServiceFactory() const; /** retrieves a value from our component context @param _rName the name of the value to retrieve @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByAsciiName */ ::com::sun::star::uno::Any getContextValueByName( const ::rtl::OUString& _rName ) const; /** retrieves a value from our component context, specified by 8-bit ASCII string @param _rName the name of the value to retrieve, as ASCII character string @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByName */ inline ::com::sun::star::uno::Any getContextValueByAsciiName( const sal_Char* _pAsciiName ) const { return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) ); } }; //........................................................................ } // namespace comphelper //........................................................................ #endif // COMPHELPER_COMPONENTCONTEXT_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.5.58); FILE MERGED 2008/04/01 12:26:24 thb 1.5.58.2: #i85898# Stripping all external header guards 2008/03/31 12:19:27 rt 1.5.58.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: componentcontext.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef COMPHELPER_COMPONENTCONTEXT_HXX #define COMPHELPER_COMPONENTCONTEXT_HXX #include <comphelper/comphelperdllapi.h> /** === begin UNO includes === **/ #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> /** === end UNO includes === **/ //........................................................................ namespace comphelper { //........................................................................ //==================================================================== //= ComponentContext //==================================================================== /** a helper class for working with a component context */ class COMPHELPER_DLLPUBLIC ComponentContext { private: ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory > m_xORB; public: /** constructs an instance @param _rxContext the component context to manage @throws ::com::sun::star::lang::NullPointerException if the given context, or its component factory, are <NULL/> */ ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext ); /** constructs an instance @param _rxLegacyFactory the legacy service factor to obtain the <type scope="com::sun::star::uno">XComponentContext</type> from @throws ::com::sun::star::uno::RuntimeException if the given factory or does not have a DefaultContext property to obtain a component context @throws ::com::sun::star::lang::NullPointerException if the given factory is <NULL/>, or provides a component context being <NULL/>, or provides a component context whose component factory is <NULL/> */ ComponentContext( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxLegacyFactory ); /** returns the ->XComponentContext interface */ inline ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > getUNOContext() const { return m_xContext; } /** determines whether the context is not <NULL/> */ inline sal_Bool is() const { return m_xContext.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponent( const ::rtl::OUString& _rServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { _out_rxComponent.clear(); _out_rxComponent = _out_rxComponent.query( m_xORB->createInstanceWithContext( _rServiceName, m_xContext ) ); return _out_rxComponent.is(); } /** creates a component using our component factory/context @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponent( const sal_Char* _pAsciiServiceName, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _out_rxComponent ); } /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { _out_rxComponent.clear(); _out_rxComponent = _out_rxComponent.query( m_xORB->createInstanceWithArgumentsAndContext( _rServiceName, _rArguments, m_xContext ) ); return _out_rxComponent.is(); } /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::uno::Exception @return <TRUE/> if and only if the component could be successfully created */ template < typename INTERFACE > bool createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments, ::com::sun::star::uno::Reference< INTERFACE >& _out_rxComponent ) const { return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments, _out_rxComponent ); } /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const ::rtl::OUString& _rServiceName ) const; /** creates a component using our component factory/context @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponent( const sal_Char* _pAsciiServiceName ) const { return createComponent( ::rtl::OUString::createFromAscii( _pAsciiServiceName ) ); } /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponentWithArguments( const ::rtl::OUString& _rServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments ) const; /** creates a component using our component factory/context, passing creation arguments @throws ::com::sun::star::lang::ServiceNotRegisteredException if the given service is not registered @throws Exception if an exception occured during creating the component @return the newly created component. Is never <NULL/>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > createComponentWithArguments( const sal_Char* _pAsciiServiceName, const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& _rArguments ) const { return createComponentWithArguments( ::rtl::OUString::createFromAscii( _pAsciiServiceName ), _rArguments ); } /** retrieves a singleton instance from the context Singletons are collected below the <code>/singletons</code> key in a component context, so accessing them means retrieving the value under <code>/singletons/&lt;instance_name&gt;</code>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const ::rtl::OUString& _rInstanceName ) const; /** retrieves a singleton instance from the context Singletons are collected below the <code>/singletons</code> key in a component context, so accessing them means retrieving the value under <code>/singletons/&lt;instance_name&gt;</code>. */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getSingleton( const sal_Char* _pAsciiInstanceName ) const { return getSingleton( ::rtl::OUString::createFromAscii( _pAsciiInstanceName ) ); } /** returns the ->XMultiServiceFactory interface of ->m_xORB, for passing to older code which does not yet support ->XMultiComponentFactory @throws ::com::sun::star::uno::RuntimeException if our our component factory does not support this interface */ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getLegacyServiceFactory() const; /** retrieves a value from our component context @param _rName the name of the value to retrieve @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByAsciiName */ ::com::sun::star::uno::Any getContextValueByName( const ::rtl::OUString& _rName ) const; /** retrieves a value from our component context, specified by 8-bit ASCII string @param _rName the name of the value to retrieve, as ASCII character string @return the context value with the given name @seealso XComponentContext::getValueByName @seealso getContextValueByName */ inline ::com::sun::star::uno::Any getContextValueByAsciiName( const sal_Char* _pAsciiName ) const { return getContextValueByName( ::rtl::OUString::createFromAscii( _pAsciiName ) ); } }; //........................................................................ } // namespace comphelper //........................................................................ #endif // COMPHELPER_COMPONENTCONTEXT_HXX <|endoftext|>
<commit_before>#include "audio_source.h" #include "audio_mixer.h" #include "audio_source_behaviour.h" using namespace Halley; AudioSource::AudioSource(std::shared_ptr<const AudioClip> clip, AudioSourcePosition sourcePos, float gain, bool loop) : clip(clip) , sourcePos(sourcePos) , looping(loop) , gain(gain) {} AudioSource::~AudioSource() {} void AudioSource::setId(size_t i) { id = i; } size_t AudioSource::getId() const { return id; } void AudioSource::start() { Expects(isReady()); Expects(!playing); playing = true; playbackPos = 0; playbackLength = clip->getLength(); nChannels = clip->getNumberOfChannels(); if (nChannels > 1) { sourcePos = AudioSourcePosition::makeFixed(); } } void AudioSource::stop() { playing = false; done = true; } bool AudioSource::isPlaying() const { return playing; } bool AudioSource::isReady() const { return clip->isLoaded(); } bool AudioSource::isDone() const { return done; } void AudioSource::setBehaviour(std::shared_ptr<AudioSourceBehaviour> value) { behaviour = std::move(value); elapsedTime = 0; behaviour->onAttach(*this); } void AudioSource::setGain(float g) { gain = g; } void AudioSource::setAudioSourcePosition(AudioSourcePosition s) { if (nChannels == 1) { sourcePos = s; } } float AudioSource::getGain() const { return gain; } size_t AudioSource::getNumberOfChannels() const { return nChannels; } void AudioSource::update(gsl::span<const AudioChannelData> channels, const AudioListenerData& listener) { Expects(playing); if (behaviour) { bool keep = behaviour->update(elapsedTime, *this); if (!keep) { behaviour.reset(); } elapsedTime = 0; } prevChannelMix = channelMix; sourcePos.setMix(nChannels, channels, channelMix, gain, listener); if (isFirstUpdate) { prevChannelMix = channelMix; isFirstUpdate = false; } } void AudioSource::mixTo(gsl::span<AudioBuffer> dst, AudioMixer& mixer, AudioBufferPool& pool) { Expects(dst.size() > 0); Expects(this != nullptr); const size_t numPacks = dst[0].packs.size(); const size_t numSamples = numPacks * 16; const size_t nSrcChannels = getNumberOfChannels(); const size_t nDstChannels = size_t(dst.size()); // Figure out the total mix in the previous update, and now. If it's zero, then there's nothing to listen here. float totalMix = 0.0f; const size_t nMixes = nSrcChannels * nDstChannels; Expects (nMixes < 16); for (size_t i = 0; i < nMixes; ++i) { totalMix += prevChannelMix[i] + channelMix[i]; } if (totalMix < 0.01f) { // Early out, this sample is not audible return; } // Render each source channel auto tmp = pool.getBuffer(numSamples); for (size_t srcChannel = 0; srcChannel < nSrcChannels; ++srcChannel) { // Read to buffer readSourceToBuffer(srcChannel, tmp.getSpan().subspan(0, numPacks)); for (size_t dstChannel = 0; dstChannel < nDstChannels; ++dstChannel) { // Compute mix const size_t mixIndex = (srcChannel * nChannels) + dstChannel; const float gain0 = prevChannelMix[mixIndex]; const float gain1 = channelMix[mixIndex]; // Render to destination if (gain0 + gain1 > 0.01f) { mixer.mixAudio(tmp.getSpan(), dst[dstChannel].packs, gain0, gain1); } } } advancePlayback(numSamples); } void AudioSource::readSourceToBuffer(size_t srcChannel, gsl::span<AudioSamplePack> dst) const { Expects(clip); Expects(srcChannel < 2); Expects(playbackPos <= playbackLength); const size_t requestedLen = size_t(dst.size()) * 16; const size_t len = std::min(requestedLen, playbackLength - playbackPos); const size_t remainingLen = requestedLen - len; if (len > 0) { auto src = clip->getChannelData(srcChannel, playbackPos, len); Expects(src.size_bytes() < requestedLen * sizeof(AudioConfig::SampleFormat)); if (src.size_bytes() > 0) { memcpy(dst.data(), src.data(), src.size_bytes()); } } if (remainingLen > 0) { const size_t remainingBytes = remainingLen * sizeof(AudioConfig::SampleFormat); char* dst2 = reinterpret_cast<char*>(dst.data()) + len * sizeof(AudioConfig::SampleFormat); if (looping) { // Copy from start auto src2 = clip->getChannelData(srcChannel, 0, len); memcpy(dst2, src2.data(), remainingBytes); } else { // Pad with zeroes memset(dst2, 0, remainingBytes); } } } void AudioSource::advancePlayback(size_t samples) { elapsedTime += float(samples) / AudioConfig::sampleRate; playbackPos += samples; if (playbackPos >= playbackLength) { if (looping) { playbackPos %= playbackLength; } else { playbackPos = playbackLength; stop(); } } } <commit_msg>Fix assert. :|<commit_after>#include "audio_source.h" #include "audio_mixer.h" #include "audio_source_behaviour.h" using namespace Halley; AudioSource::AudioSource(std::shared_ptr<const AudioClip> clip, AudioSourcePosition sourcePos, float gain, bool loop) : clip(clip) , sourcePos(sourcePos) , looping(loop) , gain(gain) {} AudioSource::~AudioSource() {} void AudioSource::setId(size_t i) { id = i; } size_t AudioSource::getId() const { return id; } void AudioSource::start() { Expects(isReady()); Expects(!playing); playing = true; playbackPos = 0; playbackLength = clip->getLength(); nChannels = clip->getNumberOfChannels(); if (nChannels > 1) { sourcePos = AudioSourcePosition::makeFixed(); } } void AudioSource::stop() { playing = false; done = true; } bool AudioSource::isPlaying() const { return playing; } bool AudioSource::isReady() const { return clip->isLoaded(); } bool AudioSource::isDone() const { return done; } void AudioSource::setBehaviour(std::shared_ptr<AudioSourceBehaviour> value) { behaviour = std::move(value); elapsedTime = 0; behaviour->onAttach(*this); } void AudioSource::setGain(float g) { gain = g; } void AudioSource::setAudioSourcePosition(AudioSourcePosition s) { if (nChannels == 1) { sourcePos = s; } } float AudioSource::getGain() const { return gain; } size_t AudioSource::getNumberOfChannels() const { return nChannels; } void AudioSource::update(gsl::span<const AudioChannelData> channels, const AudioListenerData& listener) { Expects(playing); if (behaviour) { bool keep = behaviour->update(elapsedTime, *this); if (!keep) { behaviour.reset(); } elapsedTime = 0; } prevChannelMix = channelMix; sourcePos.setMix(nChannels, channels, channelMix, gain, listener); if (isFirstUpdate) { prevChannelMix = channelMix; isFirstUpdate = false; } } void AudioSource::mixTo(gsl::span<AudioBuffer> dst, AudioMixer& mixer, AudioBufferPool& pool) { Expects(dst.size() > 0); Expects(this != nullptr); const size_t numPacks = dst[0].packs.size(); const size_t numSamples = numPacks * 16; const size_t nSrcChannels = getNumberOfChannels(); const size_t nDstChannels = size_t(dst.size()); // Figure out the total mix in the previous update, and now. If it's zero, then there's nothing to listen here. float totalMix = 0.0f; const size_t nMixes = nSrcChannels * nDstChannels; Expects (nMixes < 16); for (size_t i = 0; i < nMixes; ++i) { totalMix += prevChannelMix[i] + channelMix[i]; } if (totalMix < 0.01f) { // Early out, this sample is not audible return; } // Render each source channel auto tmp = pool.getBuffer(numSamples); for (size_t srcChannel = 0; srcChannel < nSrcChannels; ++srcChannel) { // Read to buffer readSourceToBuffer(srcChannel, tmp.getSpan().subspan(0, numPacks)); for (size_t dstChannel = 0; dstChannel < nDstChannels; ++dstChannel) { // Compute mix const size_t mixIndex = (srcChannel * nChannels) + dstChannel; const float gain0 = prevChannelMix[mixIndex]; const float gain1 = channelMix[mixIndex]; // Render to destination if (gain0 + gain1 > 0.01f) { mixer.mixAudio(tmp.getSpan(), dst[dstChannel].packs, gain0, gain1); } } } advancePlayback(numSamples); } void AudioSource::readSourceToBuffer(size_t srcChannel, gsl::span<AudioSamplePack> dst) const { Expects(clip); Expects(srcChannel < 2); Expects(playbackPos <= playbackLength); const size_t requestedLen = size_t(dst.size()) * 16; const size_t len = std::min(requestedLen, playbackLength - playbackPos); const size_t remainingLen = requestedLen - len; if (len > 0) { auto src = clip->getChannelData(srcChannel, playbackPos, len); Expects(size_t(src.size_bytes()) <= requestedLen * sizeof(AudioConfig::SampleFormat)); if (src.size_bytes() > 0) { memcpy(dst.data(), src.data(), src.size_bytes()); } } if (remainingLen > 0) { const size_t remainingBytes = remainingLen * sizeof(AudioConfig::SampleFormat); char* dst2 = reinterpret_cast<char*>(dst.data()) + len * sizeof(AudioConfig::SampleFormat); if (looping) { // Copy from start auto src2 = clip->getChannelData(srcChannel, 0, len); memcpy(dst2, src2.data(), remainingBytes); } else { // Pad with zeroes memset(dst2, 0, remainingBytes); } } } void AudioSource::advancePlayback(size_t samples) { elapsedTime += float(samples) / AudioConfig::sampleRate; playbackPos += samples; if (playbackPos >= playbackLength) { if (looping) { playbackPos %= playbackLength; } else { playbackPos = playbackLength; stop(); } } } <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_ENGINE_HPP_INCLUDED #define METHCLA_ENGINE_HPP_INCLUDED #include <methcla/engine.h> #include <methcla/lv2/atom.hpp> #include <future> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <thread> #include <unordered_map> #include <boost/optional.hpp> #include <boost/serialization/strong_typedef.hpp> #include <boost/variant.hpp> #include <boost/variant/apply_visitor.hpp> #include <oscpp/client.hpp> #include <oscpp/server.hpp> namespace Methcla { inline static void dumpMessage(std::ostream& out, const OSC::Server::Message& msg) { out << msg.address() << ' '; OSC::Server::ArgStream args(msg.args()); while (!args.atEnd()) { const char t = args.tag(); out << t << ':'; switch (t) { case 'i': out << args.int32(); break; case 'f': out << args.float32(); break; case 's': out << args.string(); break; case 'b': out << args.blob().size; break; default: out << '?'; break; } out << ' '; } } inline static void dumpRequest(std::ostream& out, const OSC::Server::Packet& packet) { out << "Request (send): "; dumpMessage(out, packet); out << std::endl; } inline static std::exception_ptr responseToException(const OSC::Server::Packet& packet) { if (packet.isMessage()) { OSC::Server::Message msg(packet); if (msg == "/error") { auto args(msg.args()); args.drop(); // request id const char* error = args.string(); return std::make_exception_ptr(std::runtime_error(error)); } else { return std::exception_ptr(); } } else { return std::make_exception_ptr(std::invalid_argument("Response is not a message")); } } BOOST_STRONG_TYPEDEF(int32_t, SynthId); BOOST_STRONG_TYPEDEF(int32_t, AudioBusId); template <class T> class ExceptionVisitor : public boost::static_visitor<T> { public: T operator()(const std::exception_ptr& e) const { std::rethrow_exception(e); } T operator()(const T& x) const { return x; } }; namespace impl { struct Result : boost::noncopyable { Result() : m_cond(false) { } inline void notify() { m_cond = true; m_cond_var.notify_one(); } inline void wait() { std::unique_lock<std::mutex> lock(m_mutex); while (!m_cond) { m_cond_var.wait(lock); } if (m_exc) { std::rethrow_exception(m_exc); } } void set_exception(std::exception_ptr exc) { BOOST_ASSERT(m_cond); std::lock_guard<std::mutex> lock(m_mutex); m_exc = exc; notify(); } std::mutex m_mutex; std::condition_variable m_cond_var; bool m_cond; std::exception_ptr m_exc; }; }; template <class T> class Result : impl::Result { public: void set(std::exception_ptr exc) { set_exception(exc); } void set(const T& value) { BOOST_ASSERT(!m_cond); std::lock_guard<std::mutex> lock(m_mutex); m_value = value; notify(); } const T& get() { wait(); return m_value; } private: T m_value; }; template <> class Result<void> : impl::Result { public: void set(std::exception_ptr exc) { set_exception(exc); } void set() { BOOST_ASSERT(!m_cond); std::lock_guard<std::mutex> lock(m_mutex); notify(); } void get() { wait(); } }; template <typename T> bool checkResponse(const OSC::Server::Packet& response, Result<T>& result) { auto error = responseToException(response); if (error) { result.set(error); return false; } return true; } class Engine { public: Engine(const Methcla_Option* options) : m_engine(methcla_engine_new(handlePacket, this, options)) , m_requestId(kMethcla_Notification+1) { check(m_engine); } ~Engine() { methcla_engine_free(m_engine); } void* impl() { return methcla_engine_impl(m_engine); } void start() { methcla_engine_start(m_engine); check(m_engine); } void stop() { methcla_engine_stop(m_engine); check(m_engine); } SynthId synth(const char* synthDef) { const char address[] = "/s_new"; const size_t numArgs = 4; const size_t packetSize = OSC::Size::message(address, numArgs) + OSC::Size::int32() + OSC::Size::string(256) + 2 * OSC::Size::int32(); const Methcla_RequestId requestId = getRequestId(); OSC::Client::StaticPacket<packetSize> request; request .openMessage(address, numArgs) .int32(requestId) .string(synthDef) .int32(0) .int32(0) .closeMessage(); dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size())); Result<SynthId> result; withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){ OSC::Server::Packet response(buffer, size); if (checkResponse(response, result)) { auto args = ((OSC::Server::Message)response).args(); int32_t requestId_ = args.int32(); BOOST_ASSERT_MSG( requestId_ == requestId, "Request id mismatch"); int32_t nodeId = args.int32(); std::cerr << "synth: " << requestId << " " << nodeId << std::endl; result.set(SynthId(nodeId)); } }); return result.get(); } void mapOutput(const SynthId& synth, size_t index, AudioBusId bus) { const char address[] = "/synth/map/output"; const size_t numArgs = 4; const size_t packetSize = OSC::Size::message(address, numArgs) + numArgs * OSC::Size::int32(); Methcla_RequestId requestId = getRequestId(); OSC::Client::StaticPacket<packetSize> request; request .openMessage(address, numArgs) .int32(requestId) .int32(synth) .int32(index) .int32(bus) .closeMessage(); dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size())); Result<void> result; withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){ if (checkResponse(OSC::Server::Packet(buffer, size), result)) { result.set(); } }); result.get(); } private: static void check(const Methcla_Engine* engine) { Methcla_Error err = methcla_engine_error(engine); if (err != kMethcla_NoError) { const char* msg = methcla_engine_error_message(engine); if (err == kMethcla_InvalidArgument) throw std::invalid_argument(msg); else if (err == kMethcla_BadAlloc) throw std::bad_alloc(); else throw std::runtime_error(msg); } } static void handlePacket(void* data, Methcla_RequestId requestId, const void* packet, size_t size) { static_cast<Engine*>(data)->handlePacket(requestId, packet, size); } void handlePacket(Methcla_RequestId requestId, const void* packet, size_t size) { std::lock_guard<std::mutex> lock(m_callbacksMutex); // look up request id and invoke callback auto it = m_callbacks.find(requestId); if (it != m_callbacks.end()) { it->second(requestId, packet, size); m_callbacks.erase(it); } } void send(const void* packet, size_t size) { methcla_engine_send(m_engine, packet, size); } void send(const OSC::Client::Packet& packet) { send(packet.data(), packet.size()); } Methcla_RequestId getRequestId() { std::lock_guard<std::mutex> lock(m_requestIdMutex); Methcla_RequestId result = m_requestId; if (result == kMethcla_Notification) { result++; } m_requestId = result + 1; return result; } void registerResponse(Methcla_RequestId requestId, std::function<void (Methcla_RequestId, const void*, size_t)> callback) { std::lock_guard<std::mutex> lock(m_callbacksMutex); BOOST_ASSERT_MSG( m_callbacks.find(requestId) == m_callbacks.end(), "Duplicate request id" ); m_callbacks[requestId] = callback; } void withRequest(Methcla_RequestId requestId, const OSC::Client::Packet& request, std::function<void (Methcla_RequestId, const void*, size_t)> callback) { registerResponse(requestId, callback); send(request); } private: Methcla_Engine* m_engine; Methcla_RequestId m_requestId; std::mutex m_requestIdMutex; std::unordered_map<Methcla_RequestId,std::function<void (Methcla_RequestId, const void*, size_t)>> m_callbacks; std::mutex m_callbacksMutex; }; }; #endif // METHCLA_ENGINE_HPP_INCLUDED <commit_msg>Remove callback even if exception is thrown<commit_after>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_ENGINE_HPP_INCLUDED #define METHCLA_ENGINE_HPP_INCLUDED #include <methcla/engine.h> #include <methcla/lv2/atom.hpp> #include <future> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <thread> #include <unordered_map> #include <boost/optional.hpp> #include <boost/serialization/strong_typedef.hpp> #include <boost/variant.hpp> #include <boost/variant/apply_visitor.hpp> #include <oscpp/client.hpp> #include <oscpp/server.hpp> namespace Methcla { inline static void dumpMessage(std::ostream& out, const OSC::Server::Message& msg) { out << msg.address() << ' '; OSC::Server::ArgStream args(msg.args()); while (!args.atEnd()) { const char t = args.tag(); out << t << ':'; switch (t) { case 'i': out << args.int32(); break; case 'f': out << args.float32(); break; case 's': out << args.string(); break; case 'b': out << args.blob().size; break; default: out << '?'; break; } out << ' '; } } inline static void dumpRequest(std::ostream& out, const OSC::Server::Packet& packet) { out << "Request (send): "; dumpMessage(out, packet); out << std::endl; } inline static std::exception_ptr responseToException(const OSC::Server::Packet& packet) { if (packet.isMessage()) { OSC::Server::Message msg(packet); if (msg == "/error") { auto args(msg.args()); args.drop(); // request id const char* error = args.string(); return std::make_exception_ptr(std::runtime_error(error)); } else { return std::exception_ptr(); } } else { return std::make_exception_ptr(std::invalid_argument("Response is not a message")); } } BOOST_STRONG_TYPEDEF(int32_t, SynthId); BOOST_STRONG_TYPEDEF(int32_t, AudioBusId); template <class T> class ExceptionVisitor : public boost::static_visitor<T> { public: T operator()(const std::exception_ptr& e) const { std::rethrow_exception(e); } T operator()(const T& x) const { return x; } }; namespace impl { struct Result : boost::noncopyable { Result() : m_cond(false) { } inline void notify() { m_cond = true; m_cond_var.notify_one(); } inline void wait() { std::unique_lock<std::mutex> lock(m_mutex); while (!m_cond) { m_cond_var.wait(lock); } if (m_exc) { std::rethrow_exception(m_exc); } } void set_exception(std::exception_ptr exc) { BOOST_ASSERT(m_cond); std::lock_guard<std::mutex> lock(m_mutex); m_exc = exc; notify(); } std::mutex m_mutex; std::condition_variable m_cond_var; bool m_cond; std::exception_ptr m_exc; }; }; template <class T> class Result : impl::Result { public: void set(std::exception_ptr exc) { set_exception(exc); } void set(const T& value) { BOOST_ASSERT(!m_cond); std::lock_guard<std::mutex> lock(m_mutex); m_value = value; notify(); } const T& get() { wait(); return m_value; } private: T m_value; }; template <> class Result<void> : impl::Result { public: void set(std::exception_ptr exc) { set_exception(exc); } void set() { BOOST_ASSERT(!m_cond); std::lock_guard<std::mutex> lock(m_mutex); notify(); } void get() { wait(); } }; template <typename T> bool checkResponse(const OSC::Server::Packet& response, Result<T>& result) { auto error = responseToException(response); if (error) { result.set(error); return false; } return true; } class Engine { public: Engine(const Methcla_Option* options) : m_engine(methcla_engine_new(handlePacket, this, options)) , m_requestId(kMethcla_Notification+1) { check(m_engine); } ~Engine() { methcla_engine_free(m_engine); } void* impl() { return methcla_engine_impl(m_engine); } void start() { methcla_engine_start(m_engine); check(m_engine); } void stop() { methcla_engine_stop(m_engine); check(m_engine); } SynthId synth(const char* synthDef) { const char address[] = "/s_new"; const size_t numArgs = 4; const size_t packetSize = OSC::Size::message(address, numArgs) + OSC::Size::int32() + OSC::Size::string(256) + 2 * OSC::Size::int32(); const Methcla_RequestId requestId = getRequestId(); OSC::Client::StaticPacket<packetSize> request; request .openMessage(address, numArgs) .int32(requestId) .string(synthDef) .int32(0) .int32(0) .closeMessage(); dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size())); Result<SynthId> result; withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){ OSC::Server::Packet response(buffer, size); if (checkResponse(response, result)) { auto args = ((OSC::Server::Message)response).args(); int32_t requestId_ = args.int32(); BOOST_ASSERT_MSG( requestId_ == requestId, "Request id mismatch"); int32_t nodeId = args.int32(); std::cerr << "synth: " << requestId << " " << nodeId << std::endl; result.set(SynthId(nodeId)); } }); return result.get(); } void mapOutput(const SynthId& synth, size_t index, AudioBusId bus) { const char address[] = "/synth/map/output"; const size_t numArgs = 4; const size_t packetSize = OSC::Size::message(address, numArgs) + numArgs * OSC::Size::int32(); Methcla_RequestId requestId = getRequestId(); OSC::Client::StaticPacket<packetSize> request; request .openMessage(address, numArgs) .int32(requestId) .int32(synth) .int32(index) .int32(bus) .closeMessage(); dumpRequest(std::cerr, OSC::Server::Packet(request.data(), request.size())); Result<void> result; withRequest(requestId, request, [&result](Methcla_RequestId requestId, const void* buffer, size_t size){ if (checkResponse(OSC::Server::Packet(buffer, size), result)) { result.set(); } }); result.get(); } private: static void check(const Methcla_Engine* engine) { Methcla_Error err = methcla_engine_error(engine); if (err != kMethcla_NoError) { const char* msg = methcla_engine_error_message(engine); if (err == kMethcla_InvalidArgument) throw std::invalid_argument(msg); else if (err == kMethcla_BadAlloc) throw std::bad_alloc(); else throw std::runtime_error(msg); } } static void handlePacket(void* data, Methcla_RequestId requestId, const void* packet, size_t size) { static_cast<Engine*>(data)->handlePacket(requestId, packet, size); } void handlePacket(Methcla_RequestId requestId, const void* packet, size_t size) { std::lock_guard<std::mutex> lock(m_callbacksMutex); // look up request id and invoke callback auto it = m_callbacks.find(requestId); if (it != m_callbacks.end()) { try { it->second(requestId, packet, size); m_callbacks.erase(it); } catch (...) { m_callbacks.erase(it); throw; } } } void send(const void* packet, size_t size) { methcla_engine_send(m_engine, packet, size); } void send(const OSC::Client::Packet& packet) { send(packet.data(), packet.size()); } Methcla_RequestId getRequestId() { std::lock_guard<std::mutex> lock(m_requestIdMutex); Methcla_RequestId result = m_requestId; if (result == kMethcla_Notification) { result++; } m_requestId = result + 1; return result; } void registerResponse(Methcla_RequestId requestId, std::function<void (Methcla_RequestId, const void*, size_t)> callback) { std::lock_guard<std::mutex> lock(m_callbacksMutex); BOOST_ASSERT_MSG( m_callbacks.find(requestId) == m_callbacks.end(), "Duplicate request id" ); m_callbacks[requestId] = callback; } void withRequest(Methcla_RequestId requestId, const OSC::Client::Packet& request, std::function<void (Methcla_RequestId, const void*, size_t)> callback) { registerResponse(requestId, callback); send(request); } private: Methcla_Engine* m_engine; Methcla_RequestId m_requestId; std::mutex m_requestIdMutex; std::unordered_map<Methcla_RequestId,std::function<void (Methcla_RequestId, const void*, size_t)>> m_callbacks; std::mutex m_callbacksMutex; }; }; #endif // METHCLA_ENGINE_HPP_INCLUDED <|endoftext|>
<commit_before>// Copyright 2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_PLUGIN_HPP_INCLUDED #define METHCLA_PLUGIN_HPP_INCLUDED #include <methcla/plugin.h> #include <oscpp/server.hpp> #include <cstring> // NOTE: This API is unstable and subject to change! namespace Methcla { namespace Plugin { template <class Synth> class World { const Methcla_World* m_world; public: World(const Methcla_World* world) : m_world(world) { } double sampleRate() const { return methcla_world_samplerate(m_world); } size_t blockSize() const { return methcla_world_block_size(m_world); } void* alloc(size_t size) const { return methcla_world_alloc(m_world, size); } void* allocAligned(size_t alignment, size_t size) const { return methcla_world_alloc_aligned(m_world, alignment, size); } void free(void* ptr) { methcla_world_free(m_world, ptr); } void performCommand(Methcla_HostPerformFunction perform, void* data) { methcla_world_perform_command(m_world, perform, data); } void synthRetain(Synth* synth) const { methcla_world_synth_retain(m_world, synth); } void synthRelease(Synth* synth) const { methcla_world_synth_release(m_world, synth); } void synthDone(Synth* synth) const { methcla_world_synth_done(m_world, synth); } }; class NoPorts { public: enum Port { }; static size_t numPorts() { return 0; } static Methcla_PortDescriptor descriptor(Port) { Methcla_PortDescriptor result; std::memset(&result, 0, sizeof(result)); return result; } }; template <class Options, class PortDescriptor> class StaticSynthOptions { public: typedef Options Type; static void configure( const void* tag_buffer , size_t tag_buffer_size , const void* arg_buffer , size_t arg_buffer_size , Methcla_SynthOptions* options ) { OSCPP::Server::ArgStream args( OSCPP::ReadStream(tag_buffer, tag_buffer_size), OSCPP::ReadStream(arg_buffer, arg_buffer_size) ); new (options) Type(args); } static bool port_descriptor( const Methcla_SynthOptions* , Methcla_PortCount index , Methcla_PortDescriptor* port ) { if (index < PortDescriptor::numPorts()) { *port = PortDescriptor::descriptor(static_cast<typename PortDescriptor::Port>(index)); return true; } return false; } }; template <class Synth, class Options, class PortDescriptor> class SynthClass { static void construct( const Methcla_World* world , const Methcla_SynthDef* synthDef , const Methcla_SynthOptions* options , Methcla_Synth* synth ) { assert(world != nullptr); assert(options != nullptr); new (synth) Synth(World<Synth>(world), synthDef, *static_cast<const typename Options::Type*>(options)); } static void connect( Methcla_Synth* synth , Methcla_PortCount port , void* data) { static_cast<Synth*>(synth)->connect(static_cast<typename PortDescriptor::Port>(port), data); } static void activate(const Methcla_World* world, Methcla_Synth* synth) { static_cast<Synth*>(synth)->activate(World<Synth>(world)); } static void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) { static_cast<Synth*>(synth)->process(World<Synth>(world), numFrames); } static void destroy(const Methcla_World*, Methcla_Synth* synth) { static_cast<Synth*>(synth)->~Synth(); } public: void operator()(const Methcla_Host* host, const char* uri) { static const Methcla_SynthDef kClass = { uri, sizeof(Synth), sizeof(typename Options::Type), Options::configure, Options::port_descriptor, construct, connect, activate, process, destroy }; methcla_host_register_synthdef(host, &kClass); } }; template <class Synth, class Options, class Ports> using StaticSynthClass = SynthClass<Synth, StaticSynthOptions<Options,Ports>, Ports>; } } #endif // METHCLA_PLUGIN_HPP_INCLUDED <commit_msg>Add port descriptor convenience functions to C++ plugin interface<commit_after>// Copyright 2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_PLUGIN_HPP_INCLUDED #define METHCLA_PLUGIN_HPP_INCLUDED #include <methcla/plugin.h> #include <oscpp/server.hpp> #include <cstring> // NOTE: This API is unstable and subject to change! namespace Methcla { namespace Plugin { template <class Synth> class World { const Methcla_World* m_world; public: World(const Methcla_World* world) : m_world(world) { } double sampleRate() const { return methcla_world_samplerate(m_world); } size_t blockSize() const { return methcla_world_block_size(m_world); } void* alloc(size_t size) const { return methcla_world_alloc(m_world, size); } void* allocAligned(size_t alignment, size_t size) const { return methcla_world_alloc_aligned(m_world, alignment, size); } void free(void* ptr) { methcla_world_free(m_world, ptr); } void performCommand(Methcla_HostPerformFunction perform, void* data) { methcla_world_perform_command(m_world, perform, data); } void synthRetain(Synth* synth) const { methcla_world_synth_retain(m_world, synth); } void synthRelease(Synth* synth) const { methcla_world_synth_release(m_world, synth); } void synthDone(Synth* synth) const { methcla_world_synth_done(m_world, synth); } }; class NoPorts { public: enum Port { }; static size_t numPorts() { return 0; } static Methcla_PortDescriptor descriptor(Port) { Methcla_PortDescriptor result; std::memset(&result, 0, sizeof(result)); return result; } }; class PortDescriptor { public: static Methcla_PortDescriptor make(Methcla_PortDirection direction, Methcla_PortType type, Methcla_PortFlags flags=kMethcla_PortFlags) { Methcla_PortDescriptor pd; pd.direction = direction; pd.type = type; pd.flags = flags; return pd; } static Methcla_PortDescriptor audioInput(Methcla_PortFlags flags=kMethcla_PortFlags) { return make(kMethcla_Input, kMethcla_AudioPort, flags); } static Methcla_PortDescriptor audioOutput(Methcla_PortFlags flags=kMethcla_PortFlags) { return make(kMethcla_Output, kMethcla_AudioPort, flags); } static Methcla_PortDescriptor controlInput(Methcla_PortFlags flags=kMethcla_PortFlags) { return make(kMethcla_Input, kMethcla_ControlPort, flags); } static Methcla_PortDescriptor controlOutput(Methcla_PortFlags flags=kMethcla_PortFlags) { return make(kMethcla_Output, kMethcla_ControlPort, flags); } }; template <class Options, class PortDescriptor> class StaticSynthOptions { public: typedef Options Type; static void configure( const void* tag_buffer , size_t tag_buffer_size , const void* arg_buffer , size_t arg_buffer_size , Methcla_SynthOptions* options ) { OSCPP::Server::ArgStream args( OSCPP::ReadStream(tag_buffer, tag_buffer_size), OSCPP::ReadStream(arg_buffer, arg_buffer_size) ); new (options) Type(args); } static bool port_descriptor( const Methcla_SynthOptions* , Methcla_PortCount index , Methcla_PortDescriptor* port ) { if (index < PortDescriptor::numPorts()) { *port = PortDescriptor::descriptor(static_cast<typename PortDescriptor::Port>(index)); return true; } return false; } }; template <class Synth, class Options, class PortDescriptor> class SynthClass { static void construct( const Methcla_World* world , const Methcla_SynthDef* synthDef , const Methcla_SynthOptions* options , Methcla_Synth* synth ) { assert(world != nullptr); assert(options != nullptr); new (synth) Synth(World<Synth>(world), synthDef, *static_cast<const typename Options::Type*>(options)); } static void connect( Methcla_Synth* synth , Methcla_PortCount port , void* data) { static_cast<Synth*>(synth)->connect(static_cast<typename PortDescriptor::Port>(port), data); } static void activate(const Methcla_World* world, Methcla_Synth* synth) { static_cast<Synth*>(synth)->activate(World<Synth>(world)); } static void process(const Methcla_World* world, Methcla_Synth* synth, size_t numFrames) { static_cast<Synth*>(synth)->process(World<Synth>(world), numFrames); } static void destroy(const Methcla_World*, Methcla_Synth* synth) { static_cast<Synth*>(synth)->~Synth(); } public: void operator()(const Methcla_Host* host, const char* uri) { static const Methcla_SynthDef kClass = { uri, sizeof(Synth), sizeof(typename Options::Type), Options::configure, Options::port_descriptor, construct, connect, activate, process, destroy }; methcla_host_register_synthdef(host, &kClass); } }; template <class Synth, class Options, class Ports> using StaticSynthClass = SynthClass<Synth, StaticSynthOptions<Options,Ports>, Ports>; } } #endif // METHCLA_PLUGIN_HPP_INCLUDED <|endoftext|>
<commit_before>#include <cassert> #include <functional> #include <iostream> #include <memory> #include <type_traits> #include <utility> #include <vector> // Variation 1: Accept std::reference_wrapper<>. #ifndef ACCEPT_REFERENCE_WRAPPER #define ACCEPT_REFERENCE_WRAPPER 1 #endif #ifndef INSTRUMENT_COPIES #define INSTRUMENT_COPIES 1 #endif #if INSTRUMENT_COPIES std::size_t& allocations () { static std::size_t allocations_ = 0; return allocations_; } void reset_allocations () { allocations() = 0; } #endif class any_printable { public: // Contructors any_printable () = default; template <typename T> any_printable (T value) : handle_ ( new handle<typename std::remove_reference<T>::type>( std::forward<T>(value) ) ) { #if INSTRUMENT_COPIES ++allocations(); #endif } any_printable (const any_printable & rhs) : handle_ (rhs.handle_->clone()) {} any_printable (any_printable && rhs) noexcept = default; // Assignment template <typename T> any_printable& operator= (T value) { any_printable temp(std::forward<T>(value)); std::swap(temp, *this); return *this; } any_printable & operator= (const any_printable & rhs) { any_printable temp(rhs); std::swap(temp, *this); return *this; } any_printable & operator= (any_printable && rhs) noexcept = default; // Public interface void print () const { assert(handle_); handle_->print(); } private: struct handle_base { virtual ~handle_base () {} virtual handle_base* clone () const = 0; // Public interface virtual void print () const = 0; }; template <typename T> struct handle : handle_base { #if ACCEPT_REFERENCE_WRAPPER template <typename U = T> handle (T value, typename std::enable_if< std::is_reference<U>::value >::type* = 0) : value_ (value) {} template <typename U = T> handle (T value, typename std::enable_if< !std::is_reference<U>::value, int >::type* = 0) noexcept : value_ (std::move(value)) {} #else handle (T value) : value_ (value) {} handle (T && value) noexcept : value_ (std::move(value)) {} #endif virtual handle_base* clone () const { #if INSTRUMENT_COPIES ++allocations(); #endif return new handle(value_); } // Public interface virtual void print () const { value_.print(); } T value_; }; #if ACCEPT_REFERENCE_WRAPPER template <typename T> struct handle<std::reference_wrapper<T>> : handle<T &> { handle (std::reference_wrapper<T> ref) : handle<T &> (ref.get()) {} }; #endif std::unique_ptr<handle_base> handle_; }; struct hi_printable { void print () const { std::cout << "Hello, world!\n"; } }; struct bye_printable { void print () const { std::cout << "Bye, now!\n"; } }; struct large_printable : std::vector<std::string> { large_printable () : std::vector<std::string> (1000, std::string(1000, ' ')) { ++allocations(); } large_printable (const large_printable & rhs) : std::vector<std::string> (rhs) { ++allocations(); } large_printable & operator= (const large_printable & rhs) { ++allocations(); static_cast<std::vector<std::string> &>(*this) = rhs; return *this; } large_printable (large_printable && rhs) = default; large_printable & operator= (large_printable && rhs) = default; void print () const { std::cout << "I'm expensive to copy.\n"; } }; /* Limitations: 1 - Each member functions must be repeated in 3 places. 2 - Macros, which could be used to address this, are evil. 3 - How do you define an any_fooable type, where foo() is a free function? 4 - How do you define an any_barable type, where bar is an operator? */ <commit_msg>Add include guards to hand_rolled.hpp.<commit_after>#ifndef HAND_ROLLED_INCLUDED__ #define HAND_ROLLED_INCLUDED__ #include <cassert> #include <functional> #include <iostream> #include <memory> #include <type_traits> #include <utility> #include <vector> // Variation 1: Accept std::reference_wrapper<>. #ifndef ACCEPT_REFERENCE_WRAPPER #define ACCEPT_REFERENCE_WRAPPER 1 #endif #ifndef INSTRUMENT_COPIES #define INSTRUMENT_COPIES 1 #endif #if INSTRUMENT_COPIES std::size_t& allocations () { static std::size_t allocations_ = 0; return allocations_; } void reset_allocations () { allocations() = 0; } #endif class any_printable { public: // Contructors any_printable () = default; template <typename T> any_printable (T value) : handle_ ( new handle<typename std::remove_reference<T>::type>( std::forward<T>(value) ) ) { #if INSTRUMENT_COPIES ++allocations(); #endif } any_printable (const any_printable & rhs) : handle_ (rhs.handle_->clone()) {} any_printable (any_printable && rhs) noexcept = default; // Assignment template <typename T> any_printable& operator= (T value) { any_printable temp(std::forward<T>(value)); std::swap(temp, *this); return *this; } any_printable & operator= (const any_printable & rhs) { any_printable temp(rhs); std::swap(temp, *this); return *this; } any_printable & operator= (any_printable && rhs) noexcept = default; // Public interface void print () const { assert(handle_); handle_->print(); } private: struct handle_base { virtual ~handle_base () {} virtual handle_base* clone () const = 0; // Public interface virtual void print () const = 0; }; template <typename T> struct handle : handle_base { #if ACCEPT_REFERENCE_WRAPPER template <typename U = T> handle (T value, typename std::enable_if< std::is_reference<U>::value >::type* = 0) : value_ (value) {} template <typename U = T> handle (T value, typename std::enable_if< !std::is_reference<U>::value, int >::type* = 0) noexcept : value_ (std::move(value)) {} #else handle (T value) : value_ (value) {} handle (T && value) noexcept : value_ (std::move(value)) {} #endif virtual handle_base* clone () const { #if INSTRUMENT_COPIES ++allocations(); #endif return new handle(value_); } // Public interface virtual void print () const { value_.print(); } T value_; }; #if ACCEPT_REFERENCE_WRAPPER template <typename T> struct handle<std::reference_wrapper<T>> : handle<T &> { handle (std::reference_wrapper<T> ref) : handle<T &> (ref.get()) {} }; #endif std::unique_ptr<handle_base> handle_; }; struct hi_printable { void print () const { std::cout << "Hello, world!\n"; } }; struct bye_printable { void print () const { std::cout << "Bye, now!\n"; } }; struct large_printable : std::vector<std::string> { large_printable () : std::vector<std::string> (1000, std::string(1000, ' ')) { ++allocations(); } large_printable (const large_printable & rhs) : std::vector<std::string> (rhs) { ++allocations(); } large_printable & operator= (const large_printable & rhs) { ++allocations(); static_cast<std::vector<std::string> &>(*this) = rhs; return *this; } large_printable (large_printable && rhs) = default; large_printable & operator= (large_printable && rhs) = default; void print () const { std::cout << "I'm expensive to copy.\n"; } }; /* Limitations: 1 - Each member functions must be repeated in 3 places. 2 - Macros, which could be used to address this, are evil. 3 - How do you define an any_fooable type, where foo() is a free function? 4 - How do you define an any_barable type, where bar is an operator? */ #endif <|endoftext|>
<commit_before>// Copyright (c) 2009-2016 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander /*! \file Logger.cc \brief Defines the Logger class */ #include "Logger.h" #include "Filesystem.h" #ifdef ENABLE_MPI #include "Communicator.h" #endif namespace py = pybind11; #include <stdexcept> #include <iomanip> using namespace std; /*! \param sysdef Specified for Analyzer, but not used directly by Logger \param fname File name to write the log to \param header_prefix String to write before the header \param overwrite Will overwrite an exiting file if true (default is to append) Constructing a logger will open the file \a fname, overwriting it when overwrite is True, and appending if overwrite is false. If \a fname is an empty string, no file is output. */ Logger::Logger(std::shared_ptr<SystemDefinition> sysdef, const std::string& fname, const std::string& header_prefix, bool overwrite) : Analyzer(sysdef), m_delimiter("\t"), m_filename(fname), m_header_prefix(header_prefix), m_appending(!overwrite), m_is_initialized(false), m_file_output(true) { m_exec_conf->msg->notice(5) << "Constructing Logger: " << fname << " " << header_prefix << " " << overwrite << endl; if (m_filename == string("")) m_file_output=false; } void Logger::openOutputFiles() { // do nothing if we are not writing a file if (!m_file_output) return; #ifdef ENABLE_MPI // only output to file on root processor if (m_comm) if (! m_exec_conf->isRoot()) return; #endif // open the file if (filesystem::exists(m_filename) && m_appending) { m_exec_conf->msg->notice(3) << "analyze.log: Appending log to existing file \"" << m_filename << "\"" << endl; m_file.open(m_filename.c_str(), ios_base::in | ios_base::out | ios_base::ate); } else { m_exec_conf->msg->notice(3) << "analyze.log: Creating new log in file \"" << m_filename << "\"" << endl; m_file.open(m_filename.c_str(), ios_base::out); m_appending = false; } if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.log: Error opening log file " << m_filename << endl; throw runtime_error("Error initializing Logger"); } } Logger::~Logger() { m_exec_conf->msg->notice(5) << "Destroying Logger" << endl; } /*! \param compute The Compute to register After the compute is registered, all of the compute's provided log quantities are available for logging. */ void Logger::registerCompute(std::shared_ptr<Compute> compute) { vector< string > provided_quantities = compute->getProvidedLogQuantities(); // loop over all log quantities for (unsigned int i = 0; i < provided_quantities.size(); i++) { // first check if this quantity is already set, printing a warning if so if ( m_compute_quantities.count(provided_quantities[i]) || m_updater_quantities.count(provided_quantities[i]) || m_callback_quantities.count(provided_quantities[i]) ) m_exec_conf->msg->warning() << "analyze.log: The log quantity " << provided_quantities[i] << " has been registered more than once. Only the most recent registration takes effect" << endl; m_compute_quantities[provided_quantities[i]] = compute; m_exec_conf->msg->notice(6) << "analyze.log: Registering log quantity " << provided_quantities[i] << endl; } } /*! \param updater The Updater to register After the updater is registered, all of the updater's provided log quantities are available for logging. */ void Logger::registerUpdater(std::shared_ptr<Updater> updater) { vector< string > provided_quantities = updater->getProvidedLogQuantities(); // loop over all log quantities for (unsigned int i = 0; i < provided_quantities.size(); i++) { // first check if this quantity is already set, printing a warning if so if ( m_compute_quantities.count(provided_quantities[i]) || m_updater_quantities.count(provided_quantities[i]) || m_callback_quantities.count(provided_quantities[i]) ) m_exec_conf->msg->warning() << "analyze.log: The log quantity " << provided_quantities[i] << " has been registered more than once. Only the most recent registration takes effect" << endl; m_updater_quantities[provided_quantities[i]] = updater; } } /*! \param name Name of the quantity \param callback Python callback that produces the quantity After the callback is registered \a name is available as a logger quantity. The callback must return a scalar value and accept the time step as an argument. */ void Logger::registerCallback(std::string name, py::object callback) { // first check if this quantity is already set, printing a warning if so if ( m_compute_quantities.count(name) || m_updater_quantities.count(name) || m_callback_quantities.count(name) ) m_exec_conf->msg->warning() << "analyze.log: The log quantity " << name << " has been registered more than once. Only the most recent registration takes effect" << endl; m_callback_quantities[name] = callback; } /*! After calling removeAll(), no quantities are registered for logging */ void Logger::removeAll() { m_compute_quantities.clear(); m_updater_quantities.clear(); m_callback_quantities.clear(); } /*! \param quantities A list of quantities to log When analyze() is called, each quantitiy in the list will, in order, be requested from the matching registered compute or updtaer and written to the file separated by delimiters. After all quantities are written to the file a newline is written. Each time setLoggedQuantities is called, a header listing the column names is also written. */ void Logger::setLoggedQuantities(const std::vector< std::string >& quantities) { m_logged_quantities = quantities; // prepare or adjust storage for caching the logger properties. m_cached_timestep = -1; m_cached_quantities.resize(quantities.size()); #ifdef ENABLE_MPI // only output to file on root processor if (m_pdata->getDomainDecomposition()) if (! m_exec_conf->isRoot()) return; #endif // open output files for writing if (! m_is_initialized) openOutputFiles(); m_is_initialized = true; // only write the header if this is a new file if (!m_appending && m_file_output) { // write out the header prefix m_file << m_header_prefix; // timestep is always output m_file << "timestep"; } if (quantities.size() == 0) { m_exec_conf->msg->warning() << "analyze.log: No quantities specified for logging" << endl; return; } // only write the header if this is a new file if (!m_appending && m_file_output) { // only print the delimiter after the timestep if there are more quantities logged m_file << m_delimiter; // write all but the last of the quantities separated by the delimiter for (unsigned int i = 0; i < quantities.size()-1; i++) m_file << quantities[i] << m_delimiter; // write the last one with no delimiter after it m_file << quantities[quantities.size()-1] << endl; m_file.flush(); } } /*! \param delimiter Delimiter to place between columns in the output file */ void Logger::setDelimiter(const std::string& delimiter) { m_delimiter = delimiter; } /*! \param timestep Time step to write out data for Writes a single line of output to the log file with each specified quantity separated by the delimiter; */ void Logger::analyze(unsigned int timestep) { // do nothing if we do not output to a file if (!m_file_output) return; if (m_prof) m_prof->push("Log"); // update info in cache for later use and for immediate output. for (unsigned int i = 0; i < m_logged_quantities.size(); i++) m_cached_quantities[i] = getValue(m_logged_quantities[i], timestep); m_cached_timestep = timestep; #ifdef ENABLE_MPI // only output to file on root processor if (m_comm) if (! m_exec_conf->isRoot()) { if (m_prof) m_prof->pop(); return; } #endif // The timestep is always output m_file << setprecision(10) << timestep; // quit now if there is nothing to log if (m_logged_quantities.size() == 0) { return; } // only print the delimiter after the timestep if there are more quantities logged m_file << m_delimiter; // write all but the last of the quantities separated by the delimiter for (unsigned int i = 0; i < m_logged_quantities.size()-1; i++) m_file << setprecision(10) << m_cached_quantities[i] << m_delimiter; // write the last one with no delimiter after it m_file << setprecision(10) << m_cached_quantities[m_logged_quantities.size()-1] << endl; m_file.flush(); if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.log: I/O error while writing log file" << endl; throw runtime_error("Error writting log file"); } if (m_prof) m_prof->pop(); } /*! \param quantity Quantity to get */ Scalar Logger::getQuantity(const std::string &quantity, unsigned int timestep, bool use_cache) { // update info in cache for later use if (!use_cache && timestep != m_cached_timestep) { for (unsigned int i = 0; i < m_logged_quantities.size(); i++) m_cached_quantities[i] = getValue(m_logged_quantities[i], timestep); m_cached_timestep = timestep; } // first see if it is the timestep number if (quantity == "timestep") { return Scalar(m_cached_timestep); } // check to see if the quantity exists in the compute list for (unsigned int i = 0; i < m_logged_quantities.size(); i++) if (m_logged_quantities[i] == quantity) return m_cached_quantities[i]; m_exec_conf->msg->warning() << "analyze.log: Log quantity " << quantity << " is not registered, returning a value of 0" << endl; return Scalar(0.0); } /*! \param quantity Quantity to get \param timestep Time step to compute value for (needed for Compute classes) */ Scalar Logger::getValue(const std::string &quantity, int timestep) { // first see if it is the built-in time quantity if (quantity == "time") { return Scalar(double(m_clk.getTime())/1e9); } // check to see if the quantity exists in the compute list else if (m_compute_quantities.count(quantity)) { // update the compute m_compute_quantities[quantity]->compute(timestep); // get the log value return m_compute_quantities[quantity]->getLogValue(quantity, timestep); } // check to see if the quantity exists in the updaters list else if (m_updater_quantities.count(quantity)) { // get the log value return m_updater_quantities[quantity]->getLogValue(quantity, timestep); } else if (m_callback_quantities.count(quantity)) { // get a quantity from a callback try { py::object rv = m_callback_quantities[quantity](timestep); Scalar extracted_rv = rv.cast<Scalar>(); return extracted_rv; } catch (py::cast_error) { m_exec_conf->msg->warning() << "analyze.log: Log callback " << quantity << " returned invalid value, logging 0." << endl; return Scalar(0.0); } } else { m_exec_conf->msg->warning() << "analyze.log: Log quantity " << quantity << " is not registered, logging a value of 0" << endl; return Scalar(0.0); } } void export_Logger(py::module& m) { py::class_<Logger, std::shared_ptr<Logger> >(m,"Logger", py::base<Analyzer>()) .def(py::init< std::shared_ptr<SystemDefinition>, const std::string&, const std::string&, bool >()) .def("registerCompute", &Logger::registerCompute) .def("registerUpdater", &Logger::registerUpdater) .def("registerCallback", &Logger::registerCallback) .def("removeAll", &Logger::removeAll) .def("setLoggedQuantities", &Logger::setLoggedQuantities) .def("setDelimiter", &Logger::setDelimiter) .def("getQuantity", &Logger::getQuantity) ; } <commit_msg>clarify with a comment to not clear python callbacks.<commit_after>// Copyright (c) 2009-2016 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainer: joaander /*! \file Logger.cc \brief Defines the Logger class */ #include "Logger.h" #include "Filesystem.h" #ifdef ENABLE_MPI #include "Communicator.h" #endif namespace py = pybind11; #include <stdexcept> #include <iomanip> using namespace std; /*! \param sysdef Specified for Analyzer, but not used directly by Logger \param fname File name to write the log to \param header_prefix String to write before the header \param overwrite Will overwrite an exiting file if true (default is to append) Constructing a logger will open the file \a fname, overwriting it when overwrite is True, and appending if overwrite is false. If \a fname is an empty string, no file is output. */ Logger::Logger(std::shared_ptr<SystemDefinition> sysdef, const std::string& fname, const std::string& header_prefix, bool overwrite) : Analyzer(sysdef), m_delimiter("\t"), m_filename(fname), m_header_prefix(header_prefix), m_appending(!overwrite), m_is_initialized(false), m_file_output(true) { m_exec_conf->msg->notice(5) << "Constructing Logger: " << fname << " " << header_prefix << " " << overwrite << endl; if (m_filename == string("")) m_file_output=false; } void Logger::openOutputFiles() { // do nothing if we are not writing a file if (!m_file_output) return; #ifdef ENABLE_MPI // only output to file on root processor if (m_comm) if (! m_exec_conf->isRoot()) return; #endif // open the file if (filesystem::exists(m_filename) && m_appending) { m_exec_conf->msg->notice(3) << "analyze.log: Appending log to existing file \"" << m_filename << "\"" << endl; m_file.open(m_filename.c_str(), ios_base::in | ios_base::out | ios_base::ate); } else { m_exec_conf->msg->notice(3) << "analyze.log: Creating new log in file \"" << m_filename << "\"" << endl; m_file.open(m_filename.c_str(), ios_base::out); m_appending = false; } if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.log: Error opening log file " << m_filename << endl; throw runtime_error("Error initializing Logger"); } } Logger::~Logger() { m_exec_conf->msg->notice(5) << "Destroying Logger" << endl; } /*! \param compute The Compute to register After the compute is registered, all of the compute's provided log quantities are available for logging. */ void Logger::registerCompute(std::shared_ptr<Compute> compute) { vector< string > provided_quantities = compute->getProvidedLogQuantities(); // loop over all log quantities for (unsigned int i = 0; i < provided_quantities.size(); i++) { // first check if this quantity is already set, printing a warning if so if ( m_compute_quantities.count(provided_quantities[i]) || m_updater_quantities.count(provided_quantities[i]) || m_callback_quantities.count(provided_quantities[i]) ) m_exec_conf->msg->warning() << "analyze.log: The log quantity " << provided_quantities[i] << " has been registered more than once. Only the most recent registration takes effect" << endl; m_compute_quantities[provided_quantities[i]] = compute; m_exec_conf->msg->notice(6) << "analyze.log: Registering log quantity " << provided_quantities[i] << endl; } } /*! \param updater The Updater to register After the updater is registered, all of the updater's provided log quantities are available for logging. */ void Logger::registerUpdater(std::shared_ptr<Updater> updater) { vector< string > provided_quantities = updater->getProvidedLogQuantities(); // loop over all log quantities for (unsigned int i = 0; i < provided_quantities.size(); i++) { // first check if this quantity is already set, printing a warning if so if ( m_compute_quantities.count(provided_quantities[i]) || m_updater_quantities.count(provided_quantities[i]) || m_callback_quantities.count(provided_quantities[i]) ) m_exec_conf->msg->warning() << "analyze.log: The log quantity " << provided_quantities[i] << " has been registered more than once. Only the most recent registration takes effect" << endl; m_updater_quantities[provided_quantities[i]] = updater; } } /*! \param name Name of the quantity \param callback Python callback that produces the quantity After the callback is registered \a name is available as a logger quantity. The callback must return a scalar value and accept the time step as an argument. */ void Logger::registerCallback(std::string name, py::object callback) { // first check if this quantity is already set, printing a warning if so if ( m_compute_quantities.count(name) || m_updater_quantities.count(name) || m_callback_quantities.count(name) ) m_exec_conf->msg->warning() << "analyze.log: The log quantity " << name << " has been registered more than once. Only the most recent registration takes effect" << endl; m_callback_quantities[name] = callback; } /*! After calling removeAll(), no quantities are registered for logging */ void Logger::removeAll() { m_compute_quantities.clear(); m_updater_quantities.clear(); //The callbacks are intentionally not cleared, because before each //run all compute and updaters should be cleared, but the python //callbacks should not be cleared for this. } /*! \param quantities A list of quantities to log When analyze() is called, each quantitiy in the list will, in order, be requested from the matching registered compute or updtaer and written to the file separated by delimiters. After all quantities are written to the file a newline is written. Each time setLoggedQuantities is called, a header listing the column names is also written. */ void Logger::setLoggedQuantities(const std::vector< std::string >& quantities) { m_logged_quantities = quantities; // prepare or adjust storage for caching the logger properties. m_cached_timestep = -1; m_cached_quantities.resize(quantities.size()); #ifdef ENABLE_MPI // only output to file on root processor if (m_pdata->getDomainDecomposition()) if (! m_exec_conf->isRoot()) return; #endif // open output files for writing if (! m_is_initialized) openOutputFiles(); m_is_initialized = true; // only write the header if this is a new file if (!m_appending && m_file_output) { // write out the header prefix m_file << m_header_prefix; // timestep is always output m_file << "timestep"; } if (quantities.size() == 0) { m_exec_conf->msg->warning() << "analyze.log: No quantities specified for logging" << endl; return; } // only write the header if this is a new file if (!m_appending && m_file_output) { // only print the delimiter after the timestep if there are more quantities logged m_file << m_delimiter; // write all but the last of the quantities separated by the delimiter for (unsigned int i = 0; i < quantities.size()-1; i++) m_file << quantities[i] << m_delimiter; // write the last one with no delimiter after it m_file << quantities[quantities.size()-1] << endl; m_file.flush(); } } /*! \param delimiter Delimiter to place between columns in the output file */ void Logger::setDelimiter(const std::string& delimiter) { m_delimiter = delimiter; } /*! \param timestep Time step to write out data for Writes a single line of output to the log file with each specified quantity separated by the delimiter; */ void Logger::analyze(unsigned int timestep) { // do nothing if we do not output to a file if (!m_file_output) return; if (m_prof) m_prof->push("Log"); // update info in cache for later use and for immediate output. for (unsigned int i = 0; i < m_logged_quantities.size(); i++) m_cached_quantities[i] = getValue(m_logged_quantities[i], timestep); m_cached_timestep = timestep; #ifdef ENABLE_MPI // only output to file on root processor if (m_comm) if (! m_exec_conf->isRoot()) { if (m_prof) m_prof->pop(); return; } #endif // The timestep is always output m_file << setprecision(10) << timestep; // quit now if there is nothing to log if (m_logged_quantities.size() == 0) { return; } // only print the delimiter after the timestep if there are more quantities logged m_file << m_delimiter; // write all but the last of the quantities separated by the delimiter for (unsigned int i = 0; i < m_logged_quantities.size()-1; i++) m_file << setprecision(10) << m_cached_quantities[i] << m_delimiter; // write the last one with no delimiter after it m_file << setprecision(10) << m_cached_quantities[m_logged_quantities.size()-1] << endl; m_file.flush(); if (!m_file.good()) { m_exec_conf->msg->error() << "analyze.log: I/O error while writing log file" << endl; throw runtime_error("Error writting log file"); } if (m_prof) m_prof->pop(); } /*! \param quantity Quantity to get */ Scalar Logger::getQuantity(const std::string &quantity, unsigned int timestep, bool use_cache) { // update info in cache for later use if (!use_cache && timestep != m_cached_timestep) { for (unsigned int i = 0; i < m_logged_quantities.size(); i++) m_cached_quantities[i] = getValue(m_logged_quantities[i], timestep); m_cached_timestep = timestep; } // first see if it is the timestep number if (quantity == "timestep") { return Scalar(m_cached_timestep); } // check to see if the quantity exists in the compute list for (unsigned int i = 0; i < m_logged_quantities.size(); i++) if (m_logged_quantities[i] == quantity) return m_cached_quantities[i]; m_exec_conf->msg->warning() << "analyze.log: Log quantity " << quantity << " is not registered, returning a value of 0" << endl; return Scalar(0.0); } /*! \param quantity Quantity to get \param timestep Time step to compute value for (needed for Compute classes) */ Scalar Logger::getValue(const std::string &quantity, int timestep) { // first see if it is the built-in time quantity if (quantity == "time") { return Scalar(double(m_clk.getTime())/1e9); } // check to see if the quantity exists in the compute list else if (m_compute_quantities.count(quantity)) { // update the compute m_compute_quantities[quantity]->compute(timestep); // get the log value return m_compute_quantities[quantity]->getLogValue(quantity, timestep); } // check to see if the quantity exists in the updaters list else if (m_updater_quantities.count(quantity)) { // get the log value return m_updater_quantities[quantity]->getLogValue(quantity, timestep); } else if (m_callback_quantities.count(quantity)) { // get a quantity from a callback try { py::object rv = m_callback_quantities[quantity](timestep); Scalar extracted_rv = rv.cast<Scalar>(); return extracted_rv; } catch (py::cast_error) { m_exec_conf->msg->warning() << "analyze.log: Log callback " << quantity << " returned invalid value, logging 0." << endl; return Scalar(0.0); } } else { m_exec_conf->msg->warning() << "analyze.log: Log quantity " << quantity << " is not registered, logging a value of 0" << endl; return Scalar(0.0); } } void export_Logger(py::module& m) { py::class_<Logger, std::shared_ptr<Logger> >(m,"Logger", py::base<Analyzer>()) .def(py::init< std::shared_ptr<SystemDefinition>, const std::string&, const std::string&, bool >()) .def("registerCompute", &Logger::registerCompute) .def("registerUpdater", &Logger::registerUpdater) .def("registerCallback", &Logger::registerCallback) .def("removeAll", &Logger::removeAll) .def("setLoggedQuantities", &Logger::setLoggedQuantities) .def("setDelimiter", &Logger::setDelimiter) .def("getQuantity", &Logger::getQuantity) ; } <|endoftext|>
<commit_before>#include "ros/ros.h" #include <ros/console.h> #include "api_application/Announce.h" #include <vector> class API { public: API(int argc, char **argv) { idCounter = 0; ros::init(argc, argv, "api_server"); ros::NodeHandle n; ros::ServiceServer service = n.advertiseService("announce", announce); ROS_INFO("Ready to deliver IDs."); ros::spin(); return 0; } private: int idCounter; //the ids of modules by category std::vector<int[2]> cameras; //first value is the module id, second the camera id std::vector<int> quadcopters; std::vector<int> controllers; std::vector<int> positions; bool announce(api_application::Announce::Request &req, api_application::Announce::Response &res) { res.id = idCounter++; switch (req.type) { case 0: cameras.push_back({res.id, req.camera_id}); break; case 1: quadcopters.push_back(res.id); break; case 2: controllers.push_back(res.id); break; case 3: positions.push_back(res.id); break; default: ROS_ERROR("Malformed register attempt!"); res.id = -1; return false; ROS_INFO("Registered new module with type %d and id %d", req.type, res.id); return true; } } <commit_msg>Corrected bad programming<commit_after>#include "ros/ros.h" #include <ros/console.h> #include "api_application/Announce.h" #include <vector> class API { public: API(int argc, char **argv) { idCounter = 0; ros::init(argc, argv, "api_server"); ros::NodeHandle n; ros::ServiceServer service = n.advertiseService("announce", this->announce); ROS_INFO("Ready to deliver IDs."); ros::spin(); return 0; } bool announce(api_application::Announce::Request &req, api_application::Announce::Response &res) { res.id = idCounter++; switch (req.type) { case 0: cameras.push_back({res.id, req.camera_id}); break; case 1: quadcopters.push_back(res.id); break; case 2: controllers.push_back(res.id); break; case 3: positions.push_back(res.id); break; default: ROS_ERROR("Malformed register attempt!"); res.id = -1; return false; } ROS_INFO("Registered new module with type %d and id %d", req.type, res.id); return true; } private: int idCounter; //the ids of modules by category std::vector<int[2]> cameras; //first value is the module id, second the camera id std::vector<int> quadcopters; std::vector<int> controllers; std::vector<int> positions; } <|endoftext|>
<commit_before>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); it++) { Decl *decl = NULL; if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); } /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCImplementationDecl, *it) continue; else if_cast(x, clang::ObjCMethodDecl, *it) continue; /* Always should be last */ else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); } else decl = make_decl(*it); if(decl) { decl->set_location(_ci, (*it)); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); delete decl; } } return true; } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); const clang::Type *return_type = d->getResultType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic()); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(), value = ""; bool is_string = false; if(name.substr(0, 8) == "__c2ffi_") name = name.substr(8, std::string::npos); if(d->hasInit() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); const clang::Expr *e = base.get<const clang::Expr*>(); if_const_cast(s, clang::StringLiteral, e) { value = s->getString(); is_string = true; } } else { value = value_to_string(v); } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); return new VarDecl(name, t, value, d->hasExternalStorage(), is_string); } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); clang::ASTContext &ctx = _ci.getASTContext(); const clang::Type *t = d->getTypeForDecl(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); if(!t->isIncompleteType()) { rd->set_bit_size(ctx.getTypeSize(t)); rd->set_bit_alignment(ctx.getTypeAlign(t)); } else { rd->set_bit_size(0); rd->set_bit_alignment(0); } if(name == "") { _anon_decls[d] = _anon_id; rd->set_id(_anon_id); _anon_id++; } for(clang::RecordDecl::field_iterator i = d->field_begin(); i != d->field_end(); i++) rd->add_field(this, *i); return rd; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr())); } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { _anon_decls[d] = _anon_id; decl->set_id(_anon_id); _anon_id++; } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); i++) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _anon_decls.find(d); if(it != _anon_decls.end()) return it->second; else return 0; } <commit_msg>Check for Decl validity and skip if invalid<commit_after>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); it++) { Decl *decl = NULL; if((*it)->isInvalidDecl()) { std::cerr << "Skipping invalid Decl:" << std::endl; (*it)->dump(); continue; } if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); } /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCImplementationDecl, *it) continue; else if_cast(x, clang::ObjCMethodDecl, *it) continue; /* Always should be last */ else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); } else decl = make_decl(*it); if(decl) { decl->set_location(_ci, (*it)); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); delete decl; } } return true; } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); const clang::Type *return_type = d->getResultType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic()); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(), value = ""; bool is_string = false; if(name.substr(0, 8) == "__c2ffi_") name = name.substr(8, std::string::npos); if(d->hasInit() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); const clang::Expr *e = base.get<const clang::Expr*>(); if_const_cast(s, clang::StringLiteral, e) { value = s->getString(); is_string = true; } } else { value = value_to_string(v); } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); return new VarDecl(name, t, value, d->hasExternalStorage(), is_string); } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); clang::ASTContext &ctx = _ci.getASTContext(); const clang::Type *t = d->getTypeForDecl(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); if(!t->isIncompleteType()) { rd->set_bit_size(ctx.getTypeSize(t)); rd->set_bit_alignment(ctx.getTypeAlign(t)); } else { rd->set_bit_size(0); rd->set_bit_alignment(0); } if(name == "") { _anon_decls[d] = _anon_id; rd->set_id(_anon_id); _anon_id++; } for(clang::RecordDecl::field_iterator i = d->field_begin(); i != d->field_end(); i++) rd->add_field(this, *i); return rd; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr())); } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { _anon_decls[d] = _anon_id; decl->set_id(_anon_id); _anon_id++; } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); i++) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _anon_decls.find(d); if(it != _anon_decls.end()) return it->second; else return 0; } <|endoftext|>
<commit_before>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); it++) { Decl *decl = NULL; if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); } /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCImplementationDecl, *it) continue; else if_cast(x, clang::ObjCMethodDecl, *it) continue; /* Always should be last */ else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); } else decl = make_decl(*it); if(decl) { decl->set_location(_ci, (*it)); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); delete decl; } } return true; } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); const clang::Type *return_type = d->getResultType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic()); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(), value = ""; if(name.substr(0, 8) == "__c2ffi_") name = name.substr(8, std::string::npos); if(d->hasInit() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { /* FIXME: massive hack. Should probably implement our own printing for strings, but this requires further delving into the StmtPrinter source. */ if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); const clang::Expr *e = base.get<const clang::Expr*>(); if(e) { llvm::raw_string_ostream ss(value); e->printPretty(ss, 0, ctx.getPrintingPolicy()); ss.flush(); } } else { value = value_to_string(v); } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); return new VarDecl(name, t, value, d->hasExternalStorage()); } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); clang::ASTContext &ctx = _ci.getASTContext(); const clang::Type *t = d->getTypeForDecl(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); rd->set_bit_size(ctx.getTypeSize(t)); rd->set_bit_alignment(ctx.getTypeAlign(t)); if(name == "") { _anon_decls[d] = _anon_id; rd->set_id(_anon_id); _anon_id++; } for(clang::RecordDecl::field_iterator i = d->field_begin(); i != d->field_end(); i++) rd->add_field(this, *i); return rd; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr())); } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { _anon_decls[d] = _anon_id; decl->set_id(_anon_id); _anon_id++; } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); i++) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _anon_decls.find(d); if(it != _anon_decls.end()) return it->second; else return 0; } <commit_msg>Don't query size of incomplete types<commit_after>/* c2ffi Copyright (C) 2013 Ryan Pavlik This file is part of c2ffi. c2ffi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. c2ffi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with c2ffi. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <map> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/Host.h> #include <llvm/ADT/IntrusiveRefCntPtr.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Basic/TargetOptions.h> #include <clang/Basic/TargetInfo.h> #include <clang/Basic/FileManager.h> #include <clang/Basic/SourceManager.h> #include <clang/Lex/HeaderSearch.h> #include <clang/Lex/Preprocessor.h> #include <clang/Basic/Diagnostic.h> #include <clang/AST/ASTContext.h> #include <clang/AST/ASTConsumer.h> #include <clang/Parse/Parser.h> #include <clang/Parse/ParseAST.h> #include "c2ffi.h" #include "c2ffi/ast.h" using namespace c2ffi; static std::string value_to_string(clang::APValue *v) { std::string s; llvm::raw_string_ostream ss(s); if(v->isInt() && v->getInt().isSigned()) v->getInt().print(ss, true); else if(v->isInt()) v->getInt().print(ss, false); else if(v->isFloat()) ss << v->getFloat().convertToDouble(); ss.flush(); return s; } void C2FFIASTConsumer::HandleTopLevelDeclInObjCContainer(clang::DeclGroupRef d) { _od->write_comment("HandleTopLevelDeclInObjCContainer"); } bool C2FFIASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d) { clang::DeclGroupRef::iterator it; for(it = d.begin(); it != d.end(); it++) { Decl *decl = NULL; if_cast(x, clang::VarDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::FunctionDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::RecordDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::EnumDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::TypedefDecl, *it) { decl = make_decl(x); } /* ObjC */ else if_cast(x, clang::ObjCInterfaceDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCCategoryDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCProtocolDecl, *it) { decl = make_decl(x); } else if_cast(x, clang::ObjCImplementationDecl, *it) continue; else if_cast(x, clang::ObjCMethodDecl, *it) continue; /* Always should be last */ else if_cast(x, clang::NamedDecl, *it) { decl = make_decl(x); } else decl = make_decl(*it); if(decl) { decl->set_location(_ci, (*it)); if(_mid) _od->write_between(); else _mid = true; _od->write(*decl); delete decl; } } return true; } bool C2FFIASTConsumer::is_cur_decl(const clang::Decl *d) const { return _cur_decls.count(d); } Decl* C2FFIASTConsumer::make_decl(const clang::Decl *d, bool is_toplevel) { return new UnhandledDecl("", d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::NamedDecl *d, bool is_toplevel) { return new UnhandledDecl(d->getDeclName().getAsString(), d->getDeclKindName()); } Decl* C2FFIASTConsumer::make_decl(const clang::FunctionDecl *d, bool is_toplevel) { _cur_decls.insert(d); const clang::Type *return_type = d->getResultType().getTypePtr(); FunctionDecl *fd = new FunctionDecl(d->getDeclName().getAsString(), Type::make_type(this, return_type), d->isVariadic()); for(clang::FunctionDecl::param_const_iterator i = d->param_begin(); i != d->param_end(); i++) { fd->add_field(this, *i); } return fd; } Decl* C2FFIASTConsumer::make_decl(const clang::VarDecl *d, bool is_toplevel) { clang::ASTContext &ctx = _ci.getASTContext(); clang::APValue *v = NULL; std::string name = d->getDeclName().getAsString(), value = ""; if(name.substr(0, 8) == "__c2ffi_") name = name.substr(8, std::string::npos); if(d->hasInit() && ((v = d->evaluateValue()) || (v = d->getEvaluatedValue()))) { /* FIXME: massive hack. Should probably implement our own printing for strings, but this requires further delving into the StmtPrinter source. */ if(v->isLValue()) { clang::APValue::LValueBase base = v->getLValueBase(); const clang::Expr *e = base.get<const clang::Expr*>(); if(e) { llvm::raw_string_ostream ss(value); e->printPretty(ss, 0, ctx.getPrintingPolicy()); ss.flush(); } } else { value = value_to_string(v); } } Type *t = Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr()); return new VarDecl(name, t, value, d->hasExternalStorage()); } Decl* C2FFIASTConsumer::make_decl(const clang::RecordDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); clang::ASTContext &ctx = _ci.getASTContext(); const clang::Type *t = d->getTypeForDecl(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); RecordDecl *rd = new RecordDecl(name, d->isUnion()); if(!t->isIncompleteType()) { rd->set_bit_size(ctx.getTypeSize(t)); rd->set_bit_alignment(ctx.getTypeAlign(t)); } else { rd->set_bit_size(-1); rd->set_bit_alignment(-1); } if(name == "") { _anon_decls[d] = _anon_id; rd->set_id(_anon_id); _anon_id++; } for(clang::RecordDecl::field_iterator i = d->field_begin(); i != d->field_end(); i++) rd->add_field(this, *i); return rd; } Decl* C2FFIASTConsumer::make_decl(const clang::TypedefDecl *d, bool is_toplevel) { return new TypedefDecl(d->getDeclName().getAsString(), Type::make_type(this, d->getTypeSourceInfo()->getType().getTypePtr())); } Decl* C2FFIASTConsumer::make_decl(const clang::EnumDecl *d, bool is_toplevel) { std::string name = d->getDeclName().getAsString(); if(is_toplevel && name == "") return NULL; _cur_decls.insert(d); EnumDecl *decl = new EnumDecl(name); if(name == "") { _anon_decls[d] = _anon_id; decl->set_id(_anon_id); _anon_id++; } for(clang::EnumDecl::enumerator_iterator i = d->enumerator_begin(); i != d->enumerator_end(); i++) { const clang::EnumConstantDecl *ecd = (*i); decl->add_field(ecd->getDeclName().getAsString(), ecd->getInitVal().getLimitedValue()); } return decl; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCInterfaceDecl *d, bool is_toplevel) { const clang::ObjCInterfaceDecl *super = d->getSuperClass(); _cur_decls.insert(d); ObjCInterfaceDecl *r = new ObjCInterfaceDecl(d->getDeclName().getAsString(), super ? super->getDeclName().getAsString() : "", !d->hasDefinition()); for(clang::ObjCInterfaceDecl::protocol_iterator i = d->protocol_begin(); i != d->protocol_end(); i++) r->add_protocol((*i)->getDeclName().getAsString()); for(clang::ObjCInterfaceDecl::ivar_iterator i = d->ivar_begin(); i != d->ivar_end(); i++) { r->add_field(this, *i); } r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCCategoryDecl *d, bool is_toplevel) { ObjCCategoryDecl *r = new ObjCCategoryDecl(d->getClassInterface()->getDeclName().getAsString(), d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } Decl* C2FFIASTConsumer::make_decl(const clang::ObjCProtocolDecl *d, bool is_toplevel) { ObjCProtocolDecl *r = new ObjCProtocolDecl(d->getDeclName().getAsString()); _cur_decls.insert(d); r->add_functions(this, d); return r; } unsigned int C2FFIASTConsumer::decl_id(const clang::Decl *d) const { ClangDeclIDMap::const_iterator it = _anon_decls.find(d); if(it != _anon_decls.end()) return it->second; else return 0; } <|endoftext|>
<commit_before>#include "purpleline.hpp" void PurpleLine::login_start() { purple_connection_set_state(conn, PURPLE_CONNECTING); purple_connection_update_progress(conn, "Logging in", 0, 3); std::string auth_token = purple_account_get_string(acct, LINE_ACCOUNT_AUTH_TOKEN, ""); if (auth_token != "") { // There's a stored authentication token, see if it works c_out->send_getLastOpRevision(); c_out->send([this, auth_token]() { int64_t local_rev; try { local_rev = c_out->recv_getLastOpRevision(); } catch (line::TalkException &err) { if (err.code == line::ErrorCode::AUTHENTICATION_FAILED || err.code == line::ErrorCode::NOT_AUTHORIZED_DEVICE) { // Auth token expired, get a new one purple_debug_info("line", "Existing auth token expired.\n"); purple_account_remove_setting(acct, LINE_ACCOUNT_AUTH_TOKEN); get_auth_token(); return; } // Unknown error throw; } set_auth_token(auth_token); poller.set_local_rev(local_rev); // Already got the last op revision, no need to call get_last_op_revision() get_profile(); }); } else { // Get a new auth token get_auth_token(); } } void PurpleLine::get_auth_token() { std::string certificate(purple_account_get_string(acct, LINE_ACCOUNT_CERTIFICATE, "")); purple_debug_info("line", "Logging in with credentials to get new auth token.\n"); c_out->send_loginWithIdentityCredentialForCertificate( line::IdentityProvider::LINE, purple_account_get_username(acct), purple_account_get_password(acct), true, "127.0.0.1", "purple-line (Pidgin)", certificate); c_out->send([this]() { line::LoginResult result; try { c_out->recv_loginWithIdentityCredentialForCertificate(result); } catch (line::TalkException &err) { std::string msg = "Could not log in. " + err.reason; purple_connection_error( conn, msg.c_str()); return; } if (result.type == line::LoginResultType::SUCCESS && result.authToken != "") { set_auth_token(result.authToken); get_last_op_revision(); } else if (result.type == line::LoginResultType::REQUIRE_DEVICE_CONFIRM) { purple_debug_info("line", "Starting PIN verification.\n"); pin_verifier.verify(result, [this](std::string auth_token, std::string certificate) { if (certificate != "") { purple_account_set_string( acct, LINE_ACCOUNT_CERTIFICATE, certificate.c_str()); } set_auth_token(auth_token); get_last_op_revision(); }); } else { std::stringstream ss("Could not log in. Bad LoginResult type: "); ss << result.type; std::string msg = ss.str(); purple_connection_error( conn, msg.c_str()); } }); } void PurpleLine::set_auth_token(std::string auth_token) { purple_account_set_string(acct, LINE_ACCOUNT_AUTH_TOKEN, auth_token.c_str()); // Re-open output client to update persistent headers c_out->close(); c_out->set_auto_reconnect(true); c_out->set_path(LINE_COMMAND_PATH); } void PurpleLine::get_last_op_revision() { c_out->send_getLastOpRevision(); c_out->send([this]() { poller.set_local_rev(c_out->recv_getLastOpRevision()); get_profile(); }); } void PurpleLine::get_profile() { c_out->send_getProfile(); c_out->send([this]() { c_out->recv_getProfile(profile); profile_contact.mid = profile.mid; profile_contact.displayName = profile.displayName; // Update display name purple_account_set_alias(acct, profile.displayName.c_str()); purple_connection_set_state(conn, PURPLE_CONNECTED); purple_connection_update_progress(conn, "Synchronizing buddy list", 1, 3); // Update account icon (not sure if there's a way to tell whether it has changed, maybe // pictureStatus?) if (profile.picturePath != "") { std::string pic_path = profile.picturePath.substr(1) + "/preview"; //if (icon_path != purple_account_get_string(acct, "icon_path", "")) { http.request(LINE_OS_URL + pic_path, HTTPFlag::AUTH, [this](int status, const guchar *data, gsize len) { if (status != 200 || !data) return; purple_buddy_icons_set_account_icon( acct, (guchar *)g_memdup(data, len), len); //purple_account_set_string(acct, "icon_path", icon_path.c_str()); }); //} } else { // TODO: Delete icon } get_contacts(); }); } void PurpleLine::get_contacts() { c_out->send_getAllContactIds(); c_out->send([this]() { std::vector<std::string> uids; c_out->recv_getAllContactIds(uids); c_out->send_getContacts(uids); c_out->send([this]() { std::vector<line::Contact> contacts; c_out->recv_getContacts(contacts); std::set<PurpleBuddy *> buddies_to_delete = blist_find<PurpleBuddy>(); for (line::Contact &contact: contacts) { if (contact.status == line::ContactStatus::FRIEND) buddies_to_delete.erase(blist_update_buddy(contact)); } for (PurpleBuddy *buddy: buddies_to_delete) blist_remove_buddy(purple_buddy_get_name(buddy)); { // Add self as buddy for those lonely debugging conversations // TODO: Remove line::Contact self; self.mid = profile.mid; self.displayName = profile.displayName + " [Profile]"; self.statusMessage = profile.statusMessage; self.picturePath = profile.picturePath; blist_update_buddy(self); } get_groups(); }); }); } void PurpleLine::get_groups() { c_out->send_getGroupIdsJoined(); c_out->send([this]() { std::vector<std::string> gids; c_out->recv_getGroupIdsJoined(gids); c_out->send_getGroups(gids); c_out->send([this]() { std::vector<line::Group> groups; c_out->recv_getGroups(groups); std::set<PurpleChat *> chats_to_delete = blist_find_chats_by_type(ChatType::GROUP); for (line::Group &group: groups) chats_to_delete.erase(blist_update_chat(group)); for (PurpleChat *chat: chats_to_delete) purple_blist_remove_chat(chat); get_rooms(); }); }); } void PurpleLine::get_rooms() { c_out->send_getMessageBoxCompactWrapUpList(1, 65535); c_out->send([this]() { line::TMessageBoxWrapUpResponse wrap_up_list; c_out->recv_getMessageBoxCompactWrapUpList(wrap_up_list); std::set<std::string> uids; for (line::TMessageBoxWrapUp &ent: wrap_up_list.messageBoxWrapUpList) { if (ent.messageBox.midType != line::MIDType::ROOM) continue; for (line::Contact &c: ent.contacts) uids.insert(c.mid); } if (!uids.empty()) { // Room contacts don't contain full contact information, so pull separately to get names c_out->send_getContacts(std::vector<std::string>(uids.begin(), uids.end())); c_out->send([this, wrap_up_list]{ std::vector<line::Contact> contacts; c_out->recv_getContacts(contacts); for (line::Contact &c: contacts) this->contacts[c.mid] = c; update_rooms(wrap_up_list); }); } else { update_rooms(wrap_up_list); } }); } void PurpleLine::update_rooms(line::TMessageBoxWrapUpResponse wrap_up_list) { std::set<PurpleChat *> chats_to_delete = blist_find_chats_by_type(ChatType::ROOM); for (line::TMessageBoxWrapUp &ent: wrap_up_list.messageBoxWrapUpList) { if (ent.messageBox.midType != line::MIDType::ROOM) continue; line::Room room; room.mid = ent.messageBox.id; room.contacts = ent.contacts; chats_to_delete.erase(blist_update_chat(room)); } for (PurpleChat *chat: chats_to_delete) purple_blist_remove_chat(chat); get_group_invites(); } void PurpleLine::get_group_invites() { c_out->send_getGroupIdsInvited(); c_out->send([this]() { std::vector<std::string> gids; c_out->recv_getGroupIdsInvited(gids); if (gids.size() == 0) { login_done(); return; } c_out->send_getGroups(gids); c_out->send([this]() { std::vector<line::Group> groups; c_out->recv_getGroups(groups); for (line::Group &g: groups) handle_group_invite(g, profile_contact, no_contact); login_done(); }); }); } void PurpleLine::login_done() { poller.start(); purple_connection_update_progress(conn, "Connected", 2, 3); } <commit_msg>Report actual UI name when logging in.<commit_after>#include <glib.h> #include <core.h> #include "purpleline.hpp" void PurpleLine::login_start() { purple_connection_set_state(conn, PURPLE_CONNECTING); purple_connection_update_progress(conn, "Logging in", 0, 3); std::string auth_token = purple_account_get_string(acct, LINE_ACCOUNT_AUTH_TOKEN, ""); if (auth_token != "") { // There's a stored authentication token, see if it works c_out->send_getLastOpRevision(); c_out->send([this, auth_token]() { int64_t local_rev; try { local_rev = c_out->recv_getLastOpRevision(); } catch (line::TalkException &err) { if (err.code == line::ErrorCode::AUTHENTICATION_FAILED || err.code == line::ErrorCode::NOT_AUTHORIZED_DEVICE) { // Auth token expired, get a new one purple_debug_info("line", "Existing auth token expired.\n"); purple_account_remove_setting(acct, LINE_ACCOUNT_AUTH_TOKEN); get_auth_token(); return; } // Unknown error throw; } set_auth_token(auth_token); poller.set_local_rev(local_rev); // Already got the last op revision, no need to call get_last_op_revision() get_profile(); }); } else { // Get a new auth token get_auth_token(); } } void PurpleLine::get_auth_token() { std::string certificate(purple_account_get_string(acct, LINE_ACCOUNT_CERTIFICATE, "")); purple_debug_info("line", "Logging in with credentials to get new auth token.\n"); std::string ui_name = "purple-line"; GHashTable *ui_info = purple_core_get_ui_info(); gpointer ui_name_p = g_hash_table_lookup(ui_info, "name"); if (ui_name_p) ui_name = (char *)ui_name_p; c_out->send_loginWithIdentityCredentialForCertificate( line::IdentityProvider::LINE, purple_account_get_username(acct), purple_account_get_password(acct), true, "127.0.0.1", ui_name, certificate); c_out->send([this]() { line::LoginResult result; try { c_out->recv_loginWithIdentityCredentialForCertificate(result); } catch (line::TalkException &err) { std::string msg = "Could not log in. " + err.reason; purple_connection_error( conn, msg.c_str()); return; } if (result.type == line::LoginResultType::SUCCESS && result.authToken != "") { set_auth_token(result.authToken); get_last_op_revision(); } else if (result.type == line::LoginResultType::REQUIRE_DEVICE_CONFIRM) { purple_debug_info("line", "Starting PIN verification.\n"); pin_verifier.verify(result, [this](std::string auth_token, std::string certificate) { if (certificate != "") { purple_account_set_string( acct, LINE_ACCOUNT_CERTIFICATE, certificate.c_str()); } set_auth_token(auth_token); get_last_op_revision(); }); } else { std::stringstream ss("Could not log in. Bad LoginResult type: "); ss << result.type; std::string msg = ss.str(); purple_connection_error( conn, msg.c_str()); } }); } void PurpleLine::set_auth_token(std::string auth_token) { purple_account_set_string(acct, LINE_ACCOUNT_AUTH_TOKEN, auth_token.c_str()); // Re-open output client to update persistent headers c_out->close(); c_out->set_auto_reconnect(true); c_out->set_path(LINE_COMMAND_PATH); } void PurpleLine::get_last_op_revision() { c_out->send_getLastOpRevision(); c_out->send([this]() { poller.set_local_rev(c_out->recv_getLastOpRevision()); get_profile(); }); } void PurpleLine::get_profile() { c_out->send_getProfile(); c_out->send([this]() { c_out->recv_getProfile(profile); profile_contact.mid = profile.mid; profile_contact.displayName = profile.displayName; // Update display name purple_account_set_alias(acct, profile.displayName.c_str()); purple_connection_set_state(conn, PURPLE_CONNECTED); purple_connection_update_progress(conn, "Synchronizing buddy list", 1, 3); // Update account icon (not sure if there's a way to tell whether it has changed, maybe // pictureStatus?) if (profile.picturePath != "") { std::string pic_path = profile.picturePath.substr(1) + "/preview"; //if (icon_path != purple_account_get_string(acct, "icon_path", "")) { http.request(LINE_OS_URL + pic_path, HTTPFlag::AUTH, [this](int status, const guchar *data, gsize len) { if (status != 200 || !data) return; purple_buddy_icons_set_account_icon( acct, (guchar *)g_memdup(data, len), len); //purple_account_set_string(acct, "icon_path", icon_path.c_str()); }); //} } else { // TODO: Delete icon } get_contacts(); }); } void PurpleLine::get_contacts() { c_out->send_getAllContactIds(); c_out->send([this]() { std::vector<std::string> uids; c_out->recv_getAllContactIds(uids); c_out->send_getContacts(uids); c_out->send([this]() { std::vector<line::Contact> contacts; c_out->recv_getContacts(contacts); std::set<PurpleBuddy *> buddies_to_delete = blist_find<PurpleBuddy>(); for (line::Contact &contact: contacts) { if (contact.status == line::ContactStatus::FRIEND) buddies_to_delete.erase(blist_update_buddy(contact)); } for (PurpleBuddy *buddy: buddies_to_delete) blist_remove_buddy(purple_buddy_get_name(buddy)); { // Add self as buddy for those lonely debugging conversations // TODO: Remove line::Contact self; self.mid = profile.mid; self.displayName = profile.displayName + " [Profile]"; self.statusMessage = profile.statusMessage; self.picturePath = profile.picturePath; blist_update_buddy(self); } get_groups(); }); }); } void PurpleLine::get_groups() { c_out->send_getGroupIdsJoined(); c_out->send([this]() { std::vector<std::string> gids; c_out->recv_getGroupIdsJoined(gids); c_out->send_getGroups(gids); c_out->send([this]() { std::vector<line::Group> groups; c_out->recv_getGroups(groups); std::set<PurpleChat *> chats_to_delete = blist_find_chats_by_type(ChatType::GROUP); for (line::Group &group: groups) chats_to_delete.erase(blist_update_chat(group)); for (PurpleChat *chat: chats_to_delete) purple_blist_remove_chat(chat); get_rooms(); }); }); } void PurpleLine::get_rooms() { c_out->send_getMessageBoxCompactWrapUpList(1, 65535); c_out->send([this]() { line::TMessageBoxWrapUpResponse wrap_up_list; c_out->recv_getMessageBoxCompactWrapUpList(wrap_up_list); std::set<std::string> uids; for (line::TMessageBoxWrapUp &ent: wrap_up_list.messageBoxWrapUpList) { if (ent.messageBox.midType != line::MIDType::ROOM) continue; for (line::Contact &c: ent.contacts) uids.insert(c.mid); } if (!uids.empty()) { // Room contacts don't contain full contact information, so pull separately to get names c_out->send_getContacts(std::vector<std::string>(uids.begin(), uids.end())); c_out->send([this, wrap_up_list]{ std::vector<line::Contact> contacts; c_out->recv_getContacts(contacts); for (line::Contact &c: contacts) this->contacts[c.mid] = c; update_rooms(wrap_up_list); }); } else { update_rooms(wrap_up_list); } }); } void PurpleLine::update_rooms(line::TMessageBoxWrapUpResponse wrap_up_list) { std::set<PurpleChat *> chats_to_delete = blist_find_chats_by_type(ChatType::ROOM); for (line::TMessageBoxWrapUp &ent: wrap_up_list.messageBoxWrapUpList) { if (ent.messageBox.midType != line::MIDType::ROOM) continue; line::Room room; room.mid = ent.messageBox.id; room.contacts = ent.contacts; chats_to_delete.erase(blist_update_chat(room)); } for (PurpleChat *chat: chats_to_delete) purple_blist_remove_chat(chat); get_group_invites(); } void PurpleLine::get_group_invites() { c_out->send_getGroupIdsInvited(); c_out->send([this]() { std::vector<std::string> gids; c_out->recv_getGroupIdsInvited(gids); if (gids.size() == 0) { login_done(); return; } c_out->send_getGroups(gids); c_out->send([this]() { std::vector<line::Group> groups; c_out->recv_getGroups(groups); for (line::Group &g: groups) handle_group_invite(g, profile_contact, no_contact); login_done(); }); }); } void PurpleLine::login_done() { poller.start(); purple_connection_update_progress(conn, "Connected", 2, 3); } <|endoftext|>
<commit_before>#include "GPU.hpp" void GPU::reset() { std::memset(screen, 0xFF, ScreenWidth * ScreenHeight * sizeof(color_t)); getLine() = getScrollX() = getScrollY() = getBGPalette() = getLCDControl() = getLCDStatus() = _cycles = 0; getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::OAM; } void GPU::update_mode() { switch(getLCDStatus() & LCDMode) { case Mode::HBlank: if(_cycles >= 204) { _cycles -= 204; getLine()++; if(getLine() >= ScreenHeight) { getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::VBlank; // VBlank Interrupt mmu->rw(MMU::IF) |= MMU::VBlank; exec_stat_interrupt(Mode01); _completed_frame = true; } else { getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); } } break; case Mode::VBlank: if(_cycles >= 456) { _cycles -= 456; getLine()++; if(getLine() >= 153) { getLine() = 0; getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); } } break; case Mode::OAM: if(_cycles >= 80) { _cycles -= 80; getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::VRAM; } break; case Mode::VRAM: if(_cycles >= 172) { _cycles -= 172; render_line(); getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::HBlank; exec_stat_interrupt(Mode00); } break; } // Coincidence Bit & Interrupt if(getLine() == getLYC()) { getLCDStatus() |= Coincidence; exec_stat_interrupt(LYC); } else { getLCDStatus() = getLCDStatus() & (~Coincidence); } } void GPU::render_line() { word_t line = getLine(); assert(line < ScreenHeight); // Render Background if(getLCDControl() & BGWindowDisplay) { // Selects the Tile Map & Tile Data Set addr_t mapoffs = (getLCDControl() & BGTileMapDisplaySelect) ? 0x9C00 : 0x9800; addr_t base_tile_data = (getLCDControl() & BGWindowsTileDataSelect) ? 0x8000 : 0x9000; mapoffs += 0x20 * (((line + getScrollY()) & 0xFF) >> 3); word_t lineoffs = (getScrollX() >> 3); word_t x = getScrollX() & 0b111; word_t y = (getScrollY() + line) & 0b111; // Tile Index word_t tile; word_t tile_l; word_t tile_h; word_t tile_data0 = 0, tile_data1 = 0; for(word_t i = 0; i < ScreenWidth; ++i) { if(x == 8 || i == 0) // Loading Tile Data (Next Tile) { x = x % 8; tile = mmu->read(mapoffs + lineoffs); int idx = tile; // If the second Tile Set is used, the tile index is signed. if(!(getLCDControl() & BGWindowsTileDataSelect) && (tile & 0x80)) idx = -((~tile + 1) & 0xFF); tile_l = mmu->read(base_tile_data + 16 * idx + y * 2); tile_h = mmu->read(base_tile_data + 16 * idx + y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); lineoffs = (lineoffs + 1) & 31; } word_t shift = ((7 - x) % 4) * 2; GPU::word_t color = ((x > 3 ? tile_data1 : tile_data0) >> shift) & 0b11; screen[to1D(i, line)] = getPaletteColor(color); ++x; } } // Render Sprites // @todo Check OBJSize ? (How does that work ?) // @todo Test if(getLCDControl() & OBJDisplay) { int Y, X; word_t Tile, Opt; word_t tile_l = 0; word_t tile_h = 0; word_t tile_data0 = 0, tile_data1 = 0; word_t sprite_limit = 10; // For each Sprite (4 bytes) // @todo Order Sprite by priority (x-coordinate then table ordering) for(word_t s = 0; s < 40; s++) { Y = mmu->read(0xFE00 + s * 4) - 16; X = mmu->read(0xFE00 + s * 4 + 1) - 8; Tile = mmu->read(0xFE00 + s * 4 + 2); Opt = mmu->read(0xFE00 + s * 4 + 3); // Visible on this scanline ? if(Y <= line && (Y + 8) > line) { word_t upper_tile = Tile; if(getLCDControl() & OBJSize) upper_tile &= 0xFE; word_t palette = mmu->read((Opt & Palette) ? MMU::OBP1 : MMU::OBP0); // Only Tile Set #0 ? Y = (Opt & YFlip) ? 7 - (line - Y) : line - Y; tile_l = mmu->read(0x8000 + 16 * upper_tile + Y * 2); tile_h = mmu->read(0x8000 + 16 * upper_tile + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); for(word_t x = 0; x < 8; x++) { word_t shift = (Opt & XFlip) ? (x % 4) * 2 : ((7 - x) % 4) * 2; GPU::word_t color = ((x > 3 ? tile_data1 : tile_data0) >> shift) & 0b11; if(X + x >= 0 && X + x < ScreenWidth && color != 0 && (!(Opt & Priority) || screen[to1D(x, line)] == 0)) { screen[to1D(X + x, line)] = Colors[(palette >> (color * 2)) & 0b11]; } } if(--sprite_limit == 0) break; } else if((getLCDControl() & OBJSize) && (Y + 8) <= line && (Y + 16) > line) { // 8 * 16 Sprites word_t lower_tile = Tile | 0x01; word_t palette = mmu->read((Opt & Palette) ? MMU::OBP1 : MMU::OBP0); // Only Tile Set #0 ? Y = (Opt & YFlip) ? 7 - (line - Y) : line - Y; tile_l = mmu->read(0x8000 + 16 * lower_tile + Y * 2); tile_h = mmu->read(0x8000 + 16 * lower_tile + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); for(word_t x = 0; x < 8; x++) { word_t shift = (Opt & XFlip) ? (x % 4) * 2 : ((7 - x) % 4) * 2; GPU::word_t color = ((x > 3 ? tile_data1 : tile_data0) >> shift) & 0b11; if(X + x >= 0 && X + x < ScreenWidth && color != 0 && (!(Opt & Priority) || screen[to1D(x, line)] == 0)) { screen[to1D(X + x, line)] = Colors[(palette >> (color * 2)) & 0b11]; } } if(--sprite_limit == 0) break; } } } }<commit_msg>Fix Sprite X Flip<commit_after>#include "GPU.hpp" void GPU::reset() { std::memset(screen, 0xFF, ScreenWidth * ScreenHeight * sizeof(color_t)); getLine() = getScrollX() = getScrollY() = getBGPalette() = getLCDControl() = getLCDStatus() = _cycles = 0; getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::OAM; } void GPU::update_mode() { switch(getLCDStatus() & LCDMode) { case Mode::HBlank: if(_cycles >= 204) { _cycles -= 204; getLine()++; if(getLine() >= ScreenHeight) { getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::VBlank; // VBlank Interrupt mmu->rw(MMU::IF) |= MMU::VBlank; exec_stat_interrupt(Mode01); _completed_frame = true; } else { getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); } } break; case Mode::VBlank: if(_cycles >= 456) { _cycles -= 456; getLine()++; if(getLine() >= 153) { getLine() = 0; getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::OAM; exec_stat_interrupt(Mode10); } } break; case Mode::OAM: if(_cycles >= 80) { _cycles -= 80; getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::VRAM; } break; case Mode::VRAM: if(_cycles >= 172) { _cycles -= 172; render_line(); getLCDStatus() = (getLCDStatus() & ~LCDMode) | Mode::HBlank; exec_stat_interrupt(Mode00); } break; } // Coincidence Bit & Interrupt if(getLine() == getLYC()) { getLCDStatus() |= Coincidence; exec_stat_interrupt(LYC); } else { getLCDStatus() = getLCDStatus() & (~Coincidence); } } void GPU::render_line() { word_t line = getLine(); assert(line < ScreenHeight); // Render Background if(getLCDControl() & BGWindowDisplay) { // Selects the Tile Map & Tile Data Set addr_t mapoffs = (getLCDControl() & BGTileMapDisplaySelect) ? 0x9C00 : 0x9800; addr_t base_tile_data = (getLCDControl() & BGWindowsTileDataSelect) ? 0x8000 : 0x9000; mapoffs += 0x20 * (((line + getScrollY()) & 0xFF) >> 3); word_t lineoffs = (getScrollX() >> 3); word_t x = getScrollX() & 0b111; word_t y = (getScrollY() + line) & 0b111; // Tile Index word_t tile; word_t tile_l; word_t tile_h; word_t tile_data0 = 0, tile_data1 = 0; for(word_t i = 0; i < ScreenWidth; ++i) { if(x == 8 || i == 0) // Loading Tile Data (Next Tile) { x = x % 8; tile = mmu->read(mapoffs + lineoffs); int idx = tile; // If the second Tile Set is used, the tile index is signed. if(!(getLCDControl() & BGWindowsTileDataSelect) && (tile & 0x80)) idx = -((~tile + 1) & 0xFF); tile_l = mmu->read(base_tile_data + 16 * idx + y * 2); tile_h = mmu->read(base_tile_data + 16 * idx + y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); lineoffs = (lineoffs + 1) & 31; } word_t shift = ((7 - x) % 4) * 2; GPU::word_t color = ((x > 3 ? tile_data1 : tile_data0) >> shift) & 0b11; screen[to1D(i, line)] = getPaletteColor(color); ++x; } } // Render Sprites // @todo Check OBJSize ? (How does that work ?) // @todo Test if(getLCDControl() & OBJDisplay) { int Y, X; word_t Tile, Opt; word_t tile_l = 0; word_t tile_h = 0; word_t tile_data0 = 0, tile_data1 = 0; word_t sprite_limit = 10; // For each Sprite (4 bytes) // @todo Order Sprite by priority (x-coordinate then table ordering) for(word_t s = 0; s < 40; s++) { Y = mmu->read(0xFE00 + s * 4) - 16; X = mmu->read(0xFE00 + s * 4 + 1) - 8; Tile = mmu->read(0xFE00 + s * 4 + 2); Opt = mmu->read(0xFE00 + s * 4 + 3); // Visible on this scanline ? if(Y <= line && (Y + 8) > line) { word_t upper_tile = Tile; if(getLCDControl() & OBJSize) upper_tile &= 0xFE; word_t palette = mmu->read((Opt & Palette) ? MMU::OBP1 : MMU::OBP0); // Only Tile Set #0 ? Y = (Opt & YFlip) ? 7 - (line - Y) : line - Y; tile_l = mmu->read(0x8000 + 16 * upper_tile + Y * 2); tile_h = mmu->read(0x8000 + 16 * upper_tile + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); for(word_t x = 0; x < 8; x++) { word_t color_x = (Opt & XFlip) ? x : (7 - x); word_t shift = (color_x % 4) * 2; GPU::word_t color = ((color_x > 3 ? tile_data0 : tile_data1) >> shift) & 0b11; if(X + x >= 0 && X + x < ScreenWidth && color != 0 && (!(Opt & Priority) || screen[to1D(x, line)] == 0)) { screen[to1D(X + x, line)] = Colors[(palette >> (color * 2)) & 0b11]; } } if(--sprite_limit == 0) break; } else if((getLCDControl() & OBJSize) && (Y + 8) <= line && (Y + 16) > line) { // 8 * 16 Sprites word_t lower_tile = Tile | 0x01; word_t palette = mmu->read((Opt & Palette) ? MMU::OBP1 : MMU::OBP0); // Only Tile Set #0 ? Y = (Opt & YFlip) ? 7 - (line - Y) : line - Y; tile_l = mmu->read(0x8000 + 16 * lower_tile + Y * 2); tile_h = mmu->read(0x8000 + 16 * lower_tile + Y * 2 + 1); palette_translation(tile_l, tile_h, tile_data0, tile_data1); for(word_t x = 0; x < 8; x++) { word_t color_x = (Opt & XFlip) ? x : (7 - x); word_t shift = (color_x % 4) * 2; GPU::word_t color = ((color_x > 3 ? tile_data0 : tile_data1) >> shift) & 0b11; if(X + x >= 0 && X + x < ScreenWidth && color != 0 && (!(Opt & Priority) || screen[to1D(x, line)] == 0)) { screen[to1D(X + x, line)] = Colors[(palette >> (color * 2)) & 0b11]; } } if(--sprite_limit == 0) break; } } } }<|endoftext|>
<commit_before>/* This file is part of the Kate project. * * Copyright (C) 2010 Christoph Cullmann <cullmann@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kateprojectpluginview.h" #include "kateprojectpluginview.moc" #include <kate/application.h> #include <ktexteditor/view.h> #include <ktexteditor/document.h> #include <kaction.h> #include <kactioncollection.h> #include <klocale.h> #include <kpluginfactory.h> #include <kpluginloader.h> #include <kaboutdata.h> #include <KFileDialog> #include <QDialog> #include <QVBoxLayout> K_PLUGIN_FACTORY(KateProjectPluginFactory, registerPlugin<KateProjectPlugin>();) K_EXPORT_PLUGIN(KateProjectPluginFactory(KAboutData("project","kateprojectplugin",ki18n("Hello World"), "0.1", ki18n("Example kate plugin"))) ) KateProjectPluginView::KateProjectPluginView( KateProjectPlugin *plugin, Kate::MainWindow *mainWin ) : Kate::PluginView( mainWin ) , Kate::XMLGUIClient(KateProjectPluginFactory::componentData()) , m_plugin (plugin) { /** * add us to gui */ mainWindow()->guiFactory()->addClient( this ); /** * create toolview */ m_toolView = mainWindow()->createToolView ("kateproject", Kate::MainWindow::Left, SmallIcon("project-open"), i18n("Projects")); /** * populate the toolview */ m_toolBox = new QToolBox (m_toolView); /** * connect to important signals, e.g. for auto project view creation */ connect (m_plugin, SIGNAL(projectCreated (KateProject *)), this, SLOT(viewForProject (KateProject *))); connect (mainWindow(), SIGNAL(viewChanged ()), this, SLOT(slotViewChanged ())); connect (m_toolBox, SIGNAL(currentChanged (int)), this, SLOT(slotCurrentChanged (int))); } KateProjectPluginView::~KateProjectPluginView() { /** * cu toolview */ delete m_toolView; /** * cu gui client */ mainWindow()->guiFactory()->removeClient( this ); } KateProjectView *KateProjectPluginView::viewForProject (KateProject *project) { /** * needs valid project */ Q_ASSERT (project); /** * existing view? */ if (m_project2View.contains (project)) return m_project2View.value (project); /** * create new view */ KateProjectView *view = new KateProjectView (this, project); /** * attach to toolbox */ m_toolBox->addItem (view, project->name()); /** * remember and return it */ m_project2View[project] = view; return view; } void KateProjectPluginView::readSessionConfig( KConfigBase* config, const QString& groupPrefix ) { // If you have session-dependant settings, load them here. // If you have application wide settings, you have to read your own KConfig, // see the Kate::Plugin docs for more information. Q_UNUSED( config ); Q_UNUSED( groupPrefix ); } void KateProjectPluginView::writeSessionConfig( KConfigBase* config, const QString& groupPrefix ) { // If you have session-dependant settings, save them here. // If you have application wide settings, you have to create your own KConfig, // see the Kate::Plugin docs for more information. Q_UNUSED( config ); Q_UNUSED( groupPrefix ); } QString KateProjectPluginView::projectFileName () { QWidget *active = m_toolBox->currentWidget (); if (!active) return QString (); return static_cast<KateProjectView *> (active)->project()->fileName (); } QStringList KateProjectPluginView::projectFiles () { KateProjectView *active = static_cast<KateProjectView *> (m_toolBox->currentWidget ()); if (!active) return QStringList (); return active->project()->files (); } void KateProjectPluginView::slotViewChanged () { /** * get active project view */ KateProjectView *active = static_cast<KateProjectView *> (m_toolBox->currentWidget ()); if (!active) return; /** * get active view */ KTextEditor::View *activeView = mainWindow()->activeView (); if (!activeView) return; /** * abort if empty url or no local path */ if (activeView->document()->url().isEmpty() || !activeView->document()->url().isLocalFile()) return; /** * else get local filename and then select it */ active->selectFile (activeView->document()->url().toLocalFile ()); } void KateProjectPluginView::slotCurrentChanged (int) { emit projectFileNameChanged (); } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>catch more view changes<commit_after>/* This file is part of the Kate project. * * Copyright (C) 2010 Christoph Cullmann <cullmann@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kateprojectpluginview.h" #include "kateprojectpluginview.moc" #include <kate/application.h> #include <ktexteditor/view.h> #include <ktexteditor/document.h> #include <kaction.h> #include <kactioncollection.h> #include <klocale.h> #include <kpluginfactory.h> #include <kpluginloader.h> #include <kaboutdata.h> #include <KFileDialog> #include <QDialog> #include <QVBoxLayout> K_PLUGIN_FACTORY(KateProjectPluginFactory, registerPlugin<KateProjectPlugin>();) K_EXPORT_PLUGIN(KateProjectPluginFactory(KAboutData("project","kateprojectplugin",ki18n("Hello World"), "0.1", ki18n("Example kate plugin"))) ) KateProjectPluginView::KateProjectPluginView( KateProjectPlugin *plugin, Kate::MainWindow *mainWin ) : Kate::PluginView( mainWin ) , Kate::XMLGUIClient(KateProjectPluginFactory::componentData()) , m_plugin (plugin) { /** * add us to gui */ mainWindow()->guiFactory()->addClient( this ); /** * create toolview */ m_toolView = mainWindow()->createToolView ("kateproject", Kate::MainWindow::Left, SmallIcon("project-open"), i18n("Projects")); /** * populate the toolview */ m_toolBox = new QToolBox (m_toolView); /** * connect to important signals, e.g. for auto project view creation */ connect (m_plugin, SIGNAL(projectCreated (KateProject *)), this, SLOT(viewForProject (KateProject *))); connect (mainWindow(), SIGNAL(viewChanged ()), this, SLOT(slotViewChanged ())); connect (m_toolBox, SIGNAL(currentChanged (int)), this, SLOT(slotCurrentChanged (int))); } KateProjectPluginView::~KateProjectPluginView() { /** * cu toolview */ delete m_toolView; /** * cu gui client */ mainWindow()->guiFactory()->removeClient( this ); } KateProjectView *KateProjectPluginView::viewForProject (KateProject *project) { /** * needs valid project */ Q_ASSERT (project); /** * existing view? */ if (m_project2View.contains (project)) return m_project2View.value (project); /** * create new view */ KateProjectView *view = new KateProjectView (this, project); /** * attach to toolbox */ m_toolBox->addItem (view, project->name()); /** * remember and return it */ m_project2View[project] = view; return view; } void KateProjectPluginView::readSessionConfig( KConfigBase* config, const QString& groupPrefix ) { // If you have session-dependant settings, load them here. // If you have application wide settings, you have to read your own KConfig, // see the Kate::Plugin docs for more information. Q_UNUSED( config ); Q_UNUSED( groupPrefix ); } void KateProjectPluginView::writeSessionConfig( KConfigBase* config, const QString& groupPrefix ) { // If you have session-dependant settings, save them here. // If you have application wide settings, you have to create your own KConfig, // see the Kate::Plugin docs for more information. Q_UNUSED( config ); Q_UNUSED( groupPrefix ); } QString KateProjectPluginView::projectFileName () { QWidget *active = m_toolBox->currentWidget (); if (!active) return QString (); return static_cast<KateProjectView *> (active)->project()->fileName (); } QStringList KateProjectPluginView::projectFiles () { KateProjectView *active = static_cast<KateProjectView *> (m_toolBox->currentWidget ()); if (!active) return QStringList (); return active->project()->files (); } void KateProjectPluginView::slotViewChanged () { /** * get active project view */ KateProjectView *active = static_cast<KateProjectView *> (m_toolBox->currentWidget ()); if (!active) return; /** * get active view */ KTextEditor::View *activeView = mainWindow()->activeView (); if (!activeView) return; /** * abort if empty url or no local path */ if (activeView->document()->url().isEmpty() || !activeView->document()->url().isLocalFile()) return; /** * else get local filename and then select it */ active->selectFile (activeView->document()->url().toLocalFile ()); } void KateProjectPluginView::slotCurrentChanged (int) { /** * we might need to highlight other document */ slotViewChanged (); /** * project file name might have changed */ emit projectFileNameChanged (); } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: framework.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: jl $ $Date: 2004-05-10 14:34:20 $ * * 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): _______________________________________ * * ************************************************************************/ #if !defined INCLUDED_JVMFWK_LOCAL_FRAMEWORK_HXX #define INCLUDED_JVMFWK_LOCAL_FRAMEWORK_HXX #include "rtl/ustring.hxx" #include "rtl/byteseq.hxx" #include "jvmfwk/framework.h" #include "jvmfwk/vendorplugin.h" //#define NS_JAVA_FRAMEWORK "http://openoffice.org/2004/java/framework/1.0" //#define NS_SCHEMA_INSTANCE "http://www.w3.org/2001/XMLSchema-instance" /** typedefs for functions from vendorplugin.h */ typedef javaPluginError (*jfw_plugin_getAllJavaInfos_ptr)( rtl_uString * sMinVersion, rtl_uString * sMaxVersion, rtl_uString * * arExcludeList, sal_Int32 nLenList, JavaInfo*** parJavaInfo, sal_Int32 *nLenInfoList); typedef javaPluginError (*jfw_plugin_getJavaInfoByPath_ptr)( rtl_uString * sPath, rtl_uString * sMinVersion, rtl_uString * sMaxVersion, rtl_uString * * arExcludeList, sal_Int32 nLenList, JavaInfo** ppInfo); /** starts a Java Virtual Machine. <p> The function shall ensure, that the VM does not abort the process during instantiation. </p> */ typedef javaPluginError (*jfw_plugin_startJavaVirtualMachine_ptr)( const JavaInfo *info, const JavaVMOption* options, sal_Int32 cOptions, JavaVM ** ppVM, JNIEnv ** ppEnv); namespace jfw { class CJavaInfo { CJavaInfo(const CJavaInfo &); CJavaInfo& operator = (const CJavaInfo&); static JavaInfo * copyJavaInfo(const JavaInfo * pInfo); public: ::JavaInfo * pInfo; CJavaInfo(); CJavaInfo(const ::JavaInfo* pInfo); ~CJavaInfo(); CJavaInfo& operator =(const ::JavaInfo* info); const ::JavaInfo* operator ->() const; ::JavaInfo** operator & (); operator ::JavaInfo* (); operator ::JavaInfo const * () const; ::JavaInfo* cloneJavaInfo() const; rtl::OUString getVendor() const; rtl::OUString getLocation() const; rtl::OUString getVersion() const; sal_uInt64 getFeatures() const; sal_uInt64 getRequirements() const; rtl::ByteSequence getVendorData() const; }; } #endif <commit_msg>INTEGRATION: CWS jl8 (1.3.4); FILE MERGED 2004/06/18 15:01:56 jl 1.3.4.1: #i30342# plugin supports multiple vendors<commit_after>/************************************************************************* * * $RCSfile: framework.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-07-23 11:54:52 $ * * 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): _______________________________________ * * ************************************************************************/ #if !defined INCLUDED_JVMFWK_LOCAL_FRAMEWORK_HXX #define INCLUDED_JVMFWK_LOCAL_FRAMEWORK_HXX #include "rtl/ustring.hxx" #include "rtl/byteseq.hxx" #include "jvmfwk/framework.h" #include "jvmfwk/vendorplugin.h" //#define NS_JAVA_FRAMEWORK "http://openoffice.org/2004/java/framework/1.0" //#define NS_SCHEMA_INSTANCE "http://www.w3.org/2001/XMLSchema-instance" /** typedefs for functions from vendorplugin.h */ typedef javaPluginError (*jfw_plugin_getAllJavaInfos_ptr)( rtl_uString * sVendor, rtl_uString * sMinVersion, rtl_uString * sMaxVersion, rtl_uString * * arExcludeList, sal_Int32 nLenList, JavaInfo*** parJavaInfo, sal_Int32 *nLenInfoList); typedef javaPluginError (*jfw_plugin_getJavaInfoByPath_ptr)( rtl_uString * sPath, rtl_uString * sMinVersion, rtl_uString * sMaxVersion, rtl_uString * * arExcludeList, sal_Int32 nLenList, JavaInfo** ppInfo); /** starts a Java Virtual Machine. <p> The function shall ensure, that the VM does not abort the process during instantiation. </p> */ typedef javaPluginError (*jfw_plugin_startJavaVirtualMachine_ptr)( const JavaInfo *info, const JavaVMOption* options, sal_Int32 cOptions, JavaVM ** ppVM, JNIEnv ** ppEnv); namespace jfw { class CJavaInfo { CJavaInfo(const CJavaInfo &); CJavaInfo& operator = (const CJavaInfo&); static JavaInfo * copyJavaInfo(const JavaInfo * pInfo); public: ::JavaInfo * pInfo; CJavaInfo(); CJavaInfo(const ::JavaInfo* pInfo); ~CJavaInfo(); CJavaInfo& operator =(const ::JavaInfo* info); const ::JavaInfo* operator ->() const; ::JavaInfo** operator & (); operator ::JavaInfo* (); operator ::JavaInfo const * () const; ::JavaInfo* cloneJavaInfo() const; rtl::OUString getVendor() const; rtl::OUString getLocation() const; rtl::OUString getVersion() const; sal_uInt64 getFeatures() const; sal_uInt64 getRequirements() const; rtl::ByteSequence getVendorData() const; }; } #endif <|endoftext|>
<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. * ************************************************************************/ #include <com/sun/star/io/XOutputStream.hpp> #include <tools/debug.hxx> #include <sax/tools/converter.hxx> #include <xmloff/xmltkmap.hxx> #include <xmloff/xmluconv.hxx> #include "xmloff/xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/nmspmap.hxx> #include <xmloff/XMLBase64ImportContext.hxx> #include "XMLBackgroundImageContext.hxx" using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::style; using namespace ::com::sun::star::io; using namespace ::xmloff::token; enum SvXMLTokenMapAttrs { XML_TOK_BGIMG_HREF, XML_TOK_BGIMG_TYPE, XML_TOK_BGIMG_ACTUATE, XML_TOK_BGIMG_SHOW, XML_TOK_BGIMG_POSITION, XML_TOK_BGIMG_REPEAT, XML_TOK_BGIMG_FILTER, XML_TOK_BGIMG_OPACITY, XML_TOK_NGIMG_END=XML_TOK_UNKNOWN }; static const SvXMLTokenMapEntry* lcl_getBGImgAttributesAttrTokenMap() { static SvXMLTokenMapEntry aBGImgAttributesAttrTokenMap[] = { { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_BGIMG_HREF }, { XML_NAMESPACE_XLINK, XML_TYPE, XML_TOK_BGIMG_TYPE }, { XML_NAMESPACE_XLINK, XML_ACTUATE, XML_TOK_BGIMG_ACTUATE }, { XML_NAMESPACE_XLINK, XML_SHOW, XML_TOK_BGIMG_SHOW }, { XML_NAMESPACE_STYLE, XML_POSITION, XML_TOK_BGIMG_POSITION }, { XML_NAMESPACE_STYLE, XML_REPEAT, XML_TOK_BGIMG_REPEAT }, { XML_NAMESPACE_STYLE, XML_FILTER_NAME, XML_TOK_BGIMG_FILTER }, { XML_NAMESPACE_DRAW, XML_OPACITY, XML_TOK_BGIMG_OPACITY }, XML_TOKEN_MAP_END }; return aBGImgAttributesAttrTokenMap; } static SvXMLEnumMapEntry psXML_BrushHoriPos[] = { { XML_LEFT, GraphicLocation_LEFT_MIDDLE }, { XML_RIGHT, GraphicLocation_RIGHT_MIDDLE }, { XML_TOKEN_INVALID, 0 } }; static SvXMLEnumMapEntry psXML_BrushVertPos[] = { { XML_TOP, GraphicLocation_MIDDLE_TOP }, { XML_BOTTOM, GraphicLocation_MIDDLE_BOTTOM }, { XML_TOKEN_INVALID, 0 } }; static void lcl_xmlbic_MergeHoriPos( GraphicLocation& ePos, GraphicLocation eHori ) { DBG_ASSERT( GraphicLocation_LEFT_MIDDLE==eHori || GraphicLocation_MIDDLE_MIDDLE==eHori || GraphicLocation_RIGHT_MIDDLE==eHori, "lcl_xmlbic_MergeHoriPos: vertical pos must be middle" ); switch( ePos ) { case GraphicLocation_LEFT_TOP: case GraphicLocation_MIDDLE_TOP: case GraphicLocation_RIGHT_TOP: ePos = GraphicLocation_LEFT_MIDDLE==eHori ? GraphicLocation_LEFT_TOP : (GraphicLocation_MIDDLE_MIDDLE==eHori ? GraphicLocation_MIDDLE_TOP : GraphicLocation_RIGHT_TOP); break; case GraphicLocation_LEFT_MIDDLE: case GraphicLocation_MIDDLE_MIDDLE: case GraphicLocation_RIGHT_MIDDLE: ePos = eHori; break; case GraphicLocation_LEFT_BOTTOM: case GraphicLocation_MIDDLE_BOTTOM: case GraphicLocation_RIGHT_BOTTOM: ePos = GraphicLocation_LEFT_MIDDLE==eHori ? GraphicLocation_LEFT_BOTTOM : (GraphicLocation_MIDDLE_MIDDLE==eHori ? GraphicLocation_MIDDLE_BOTTOM : GraphicLocation_RIGHT_BOTTOM); break; default: break; } } static void lcl_xmlbic_MergeVertPos( GraphicLocation& ePos, GraphicLocation eVert ) { DBG_ASSERT( GraphicLocation_MIDDLE_TOP==eVert || GraphicLocation_MIDDLE_MIDDLE==eVert || GraphicLocation_MIDDLE_BOTTOM==eVert, "lcl_xmlbic_MergeVertPos: horizontal pos must be middle" ); switch( ePos ) { case GraphicLocation_LEFT_TOP: case GraphicLocation_LEFT_MIDDLE: case GraphicLocation_LEFT_BOTTOM: ePos = GraphicLocation_MIDDLE_TOP==eVert ? GraphicLocation_LEFT_TOP : (GraphicLocation_MIDDLE_MIDDLE==eVert ? GraphicLocation_LEFT_MIDDLE : GraphicLocation_LEFT_BOTTOM); ePos = eVert; break; case GraphicLocation_MIDDLE_TOP: case GraphicLocation_MIDDLE_MIDDLE: case GraphicLocation_MIDDLE_BOTTOM: ePos = eVert; break; case GraphicLocation_RIGHT_TOP: case GraphicLocation_RIGHT_MIDDLE: case GraphicLocation_RIGHT_BOTTOM: ePos = GraphicLocation_MIDDLE_TOP==eVert ? GraphicLocation_RIGHT_TOP : (GraphicLocation_MIDDLE_MIDDLE==eVert ? GraphicLocation_RIGHT_MIDDLE : GraphicLocation_RIGHT_BOTTOM); break; default: break; } } TYPEINIT1( XMLBackgroundImageContext, XMLElementPropertyContext ); void XMLBackgroundImageContext::ProcessAttrs( const Reference< xml::sax::XAttributeList >& xAttrList ) { SvXMLTokenMap aTokenMap( lcl_getBGImgAttributesAttrTokenMap() ); ePos = GraphicLocation_NONE; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); const OUString& rValue = xAttrList->getValueByIndex( i ); switch( aTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_BGIMG_HREF: sURL = rValue; if( GraphicLocation_NONE == ePos ) ePos = GraphicLocation_TILED; break; case XML_TOK_BGIMG_TYPE: case XML_TOK_BGIMG_ACTUATE: case XML_TOK_BGIMG_SHOW: break; case XML_TOK_BGIMG_POSITION: { GraphicLocation eNewPos = GraphicLocation_NONE, eTmp; sal_uInt16 nTmp; SvXMLTokenEnumerator aTokenEnum( rValue ); OUString aToken; sal_Bool bHori = sal_False, bVert = sal_False; sal_Bool bOK = sal_True; while( bOK && aTokenEnum.getNextToken( aToken ) ) { if( bHori && bVert ) { bOK = sal_False; } else if( -1 != aToken.indexOf( sal_Unicode('%') ) ) { sal_Int32 nPrc = 50; if (::sax::Converter::convertPercent( nPrc, aToken )) { if( !bHori ) { eNewPos = nPrc < 25 ? GraphicLocation_LEFT_TOP : (nPrc < 75 ? GraphicLocation_MIDDLE_MIDDLE : GraphicLocation_RIGHT_BOTTOM); bHori = sal_True; } else { eTmp = nPrc < 25 ? GraphicLocation_LEFT_TOP : (nPrc < 75 ? GraphicLocation_LEFT_MIDDLE : GraphicLocation_LEFT_BOTTOM); lcl_xmlbic_MergeVertPos( eNewPos, eTmp ); bVert = sal_True; } } else { // wrong percentage bOK = sal_False; } } else if( IsXMLToken( aToken, XML_CENTER ) ) { if( bHori ) lcl_xmlbic_MergeVertPos( eNewPos, GraphicLocation_MIDDLE_MIDDLE ); else if ( bVert ) lcl_xmlbic_MergeHoriPos( eNewPos, GraphicLocation_MIDDLE_MIDDLE ); else eNewPos = GraphicLocation_MIDDLE_MIDDLE; } else if( SvXMLUnitConverter::convertEnum( nTmp, aToken, psXML_BrushHoriPos ) ) { if( bVert ) lcl_xmlbic_MergeHoriPos( eNewPos, (GraphicLocation)nTmp ); else if( !bHori ) eNewPos = (GraphicLocation)nTmp; else bOK = sal_False; bHori = sal_True; } else if( SvXMLUnitConverter::convertEnum( nTmp, aToken, psXML_BrushVertPos ) ) { if( bHori ) lcl_xmlbic_MergeVertPos( eNewPos, (GraphicLocation)nTmp ); else if( !bVert ) eNewPos = (GraphicLocation)nTmp; else bOK = sal_False; bVert = sal_True; } else { bOK = sal_False; } } bOK &= GraphicLocation_NONE != eNewPos; if( bOK ) ePos = eNewPos; } break; case XML_TOK_BGIMG_REPEAT: { sal_uInt16 nPos = GraphicLocation_NONE; static SvXMLEnumMapEntry psXML_BrushRepeat[] = { { XML_BACKGROUND_REPEAT, GraphicLocation_TILED }, { XML_BACKGROUND_NO_REPEAT, GraphicLocation_MIDDLE_MIDDLE }, { XML_BACKGROUND_STRETCH, GraphicLocation_AREA }, { XML_TOKEN_INVALID, 0 } }; if( SvXMLUnitConverter::convertEnum( nPos, rValue, psXML_BrushRepeat ) ) { if( GraphicLocation_MIDDLE_MIDDLE != nPos || GraphicLocation_NONE == ePos || GraphicLocation_AREA == ePos || GraphicLocation_TILED == ePos ) ePos = (GraphicLocation)nPos; } } break; case XML_TOK_BGIMG_FILTER: sFilter = rValue; break; case XML_TOK_BGIMG_OPACITY: { sal_Int32 nTmp; // convert from percent and clip if (::sax::Converter::convertPercent( nTmp, rValue )) { if( (nTmp >= 0) && (nTmp <= 100) ) nTransparency = static_cast<sal_Int8>( 100-nTmp ); } } break; } } } XMLBackgroundImageContext::XMLBackgroundImageContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< xml::sax::XAttributeList > & xAttrList, const XMLPropertyState& rProp, sal_Int32 nPosIdx, sal_Int32 nFilterIdx, sal_Int32 nTransparencyIdx, ::std::vector< XMLPropertyState > &rProps ) : XMLElementPropertyContext( rImport, nPrfx, rLName, rProp, rProps ), aPosProp( nPosIdx ), aFilterProp( nFilterIdx ), aTransparencyProp( nTransparencyIdx ), nTransparency( 0 ) { ProcessAttrs( xAttrList ); } XMLBackgroundImageContext::~XMLBackgroundImageContext() { } SvXMLImportContext *XMLBackgroundImageContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = NULL; if( (XML_NAMESPACE_OFFICE == nPrefix) && xmloff::token::IsXMLToken( rLocalName, xmloff::token::XML_BINARY_DATA ) ) { if( sURL.isEmpty() && !xBase64Stream.is() ) { xBase64Stream = GetImport().GetStreamForGraphicObjectURLFromBase64(); if( xBase64Stream.is() ) pContext = new XMLBase64ImportContext( GetImport(), nPrefix, rLocalName, xAttrList, xBase64Stream ); } } if( !pContext ) { pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); } return pContext; } void XMLBackgroundImageContext::EndElement() { if( !sURL.isEmpty() ) { sURL = GetImport().ResolveGraphicObjectURL( sURL, sal_False ); } else if( xBase64Stream.is() ) { sURL = GetImport().ResolveGraphicObjectURLFromBase64( xBase64Stream ); xBase64Stream = 0; } if( sURL.isEmpty() ) ePos = GraphicLocation_NONE; else if( GraphicLocation_NONE == ePos ) ePos = GraphicLocation_TILED; aProp.maValue <<= sURL; aPosProp.maValue <<= ePos; aFilterProp.maValue <<= sFilter; aTransparencyProp.maValue <<= nTransparency; SetInsert( sal_True ); XMLElementPropertyContext::EndElement(); if( -1 != aPosProp.mnIndex ) rProperties.push_back( aPosProp ); if( -1 != aFilterProp.mnIndex ) rProperties.push_back( aFilterProp ); if( -1 != aTransparencyProp.mnIndex ) rProperties.push_back( aTransparencyProp ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Same, cut and paste typo ?<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. * ************************************************************************/ #include <com/sun/star/io/XOutputStream.hpp> #include <tools/debug.hxx> #include <sax/tools/converter.hxx> #include <xmloff/xmltkmap.hxx> #include <xmloff/xmluconv.hxx> #include "xmloff/xmlnmspe.hxx" #include <xmloff/xmltoken.hxx> #include <xmloff/xmlimp.hxx> #include <xmloff/nmspmap.hxx> #include <xmloff/XMLBase64ImportContext.hxx> #include "XMLBackgroundImageContext.hxx" using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::style; using namespace ::com::sun::star::io; using namespace ::xmloff::token; enum SvXMLTokenMapAttrs { XML_TOK_BGIMG_HREF, XML_TOK_BGIMG_TYPE, XML_TOK_BGIMG_ACTUATE, XML_TOK_BGIMG_SHOW, XML_TOK_BGIMG_POSITION, XML_TOK_BGIMG_REPEAT, XML_TOK_BGIMG_FILTER, XML_TOK_BGIMG_OPACITY, XML_TOK_NGIMG_END=XML_TOK_UNKNOWN }; static const SvXMLTokenMapEntry* lcl_getBGImgAttributesAttrTokenMap() { static SvXMLTokenMapEntry aBGImgAttributesAttrTokenMap[] = { { XML_NAMESPACE_XLINK, XML_HREF, XML_TOK_BGIMG_HREF }, { XML_NAMESPACE_XLINK, XML_TYPE, XML_TOK_BGIMG_TYPE }, { XML_NAMESPACE_XLINK, XML_ACTUATE, XML_TOK_BGIMG_ACTUATE }, { XML_NAMESPACE_XLINK, XML_SHOW, XML_TOK_BGIMG_SHOW }, { XML_NAMESPACE_STYLE, XML_POSITION, XML_TOK_BGIMG_POSITION }, { XML_NAMESPACE_STYLE, XML_REPEAT, XML_TOK_BGIMG_REPEAT }, { XML_NAMESPACE_STYLE, XML_FILTER_NAME, XML_TOK_BGIMG_FILTER }, { XML_NAMESPACE_DRAW, XML_OPACITY, XML_TOK_BGIMG_OPACITY }, XML_TOKEN_MAP_END }; return aBGImgAttributesAttrTokenMap; } static SvXMLEnumMapEntry psXML_BrushHoriPos[] = { { XML_LEFT, GraphicLocation_LEFT_MIDDLE }, { XML_RIGHT, GraphicLocation_RIGHT_MIDDLE }, { XML_TOKEN_INVALID, 0 } }; static SvXMLEnumMapEntry psXML_BrushVertPos[] = { { XML_TOP, GraphicLocation_MIDDLE_TOP }, { XML_BOTTOM, GraphicLocation_MIDDLE_BOTTOM }, { XML_TOKEN_INVALID, 0 } }; static void lcl_xmlbic_MergeHoriPos( GraphicLocation& ePos, GraphicLocation eHori ) { DBG_ASSERT( GraphicLocation_LEFT_MIDDLE==eHori || GraphicLocation_MIDDLE_MIDDLE==eHori || GraphicLocation_RIGHT_MIDDLE==eHori, "lcl_xmlbic_MergeHoriPos: vertical pos must be middle" ); switch( ePos ) { case GraphicLocation_LEFT_TOP: case GraphicLocation_MIDDLE_TOP: case GraphicLocation_RIGHT_TOP: ePos = GraphicLocation_LEFT_MIDDLE==eHori ? GraphicLocation_LEFT_TOP : (GraphicLocation_MIDDLE_MIDDLE==eHori ? GraphicLocation_MIDDLE_TOP : GraphicLocation_RIGHT_TOP); break; case GraphicLocation_LEFT_MIDDLE: case GraphicLocation_MIDDLE_MIDDLE: case GraphicLocation_RIGHT_MIDDLE: ePos = eHori; break; case GraphicLocation_LEFT_BOTTOM: case GraphicLocation_MIDDLE_BOTTOM: case GraphicLocation_RIGHT_BOTTOM: ePos = GraphicLocation_LEFT_MIDDLE==eHori ? GraphicLocation_LEFT_BOTTOM : (GraphicLocation_MIDDLE_MIDDLE==eHori ? GraphicLocation_MIDDLE_BOTTOM : GraphicLocation_RIGHT_BOTTOM); break; default: break; } } static void lcl_xmlbic_MergeVertPos( GraphicLocation& ePos, GraphicLocation eVert ) { DBG_ASSERT( GraphicLocation_MIDDLE_TOP==eVert || GraphicLocation_MIDDLE_MIDDLE==eVert || GraphicLocation_MIDDLE_BOTTOM==eVert, "lcl_xmlbic_MergeVertPos: horizontal pos must be middle" ); switch( ePos ) { case GraphicLocation_LEFT_TOP: case GraphicLocation_LEFT_MIDDLE: case GraphicLocation_LEFT_BOTTOM: ePos = GraphicLocation_MIDDLE_TOP==eVert ? GraphicLocation_LEFT_TOP : (GraphicLocation_MIDDLE_MIDDLE==eVert ? GraphicLocation_LEFT_MIDDLE : GraphicLocation_LEFT_BOTTOM); break; case GraphicLocation_MIDDLE_TOP: case GraphicLocation_MIDDLE_MIDDLE: case GraphicLocation_MIDDLE_BOTTOM: ePos = eVert; break; case GraphicLocation_RIGHT_TOP: case GraphicLocation_RIGHT_MIDDLE: case GraphicLocation_RIGHT_BOTTOM: ePos = GraphicLocation_MIDDLE_TOP==eVert ? GraphicLocation_RIGHT_TOP : (GraphicLocation_MIDDLE_MIDDLE==eVert ? GraphicLocation_RIGHT_MIDDLE : GraphicLocation_RIGHT_BOTTOM); break; default: break; } } TYPEINIT1( XMLBackgroundImageContext, XMLElementPropertyContext ); void XMLBackgroundImageContext::ProcessAttrs( const Reference< xml::sax::XAttributeList >& xAttrList ) { SvXMLTokenMap aTokenMap( lcl_getBGImgAttributesAttrTokenMap() ); ePos = GraphicLocation_NONE; sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); const OUString& rValue = xAttrList->getValueByIndex( i ); switch( aTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_BGIMG_HREF: sURL = rValue; if( GraphicLocation_NONE == ePos ) ePos = GraphicLocation_TILED; break; case XML_TOK_BGIMG_TYPE: case XML_TOK_BGIMG_ACTUATE: case XML_TOK_BGIMG_SHOW: break; case XML_TOK_BGIMG_POSITION: { GraphicLocation eNewPos = GraphicLocation_NONE, eTmp; sal_uInt16 nTmp; SvXMLTokenEnumerator aTokenEnum( rValue ); OUString aToken; sal_Bool bHori = sal_False, bVert = sal_False; sal_Bool bOK = sal_True; while( bOK && aTokenEnum.getNextToken( aToken ) ) { if( bHori && bVert ) { bOK = sal_False; } else if( -1 != aToken.indexOf( sal_Unicode('%') ) ) { sal_Int32 nPrc = 50; if (::sax::Converter::convertPercent( nPrc, aToken )) { if( !bHori ) { eNewPos = nPrc < 25 ? GraphicLocation_LEFT_TOP : (nPrc < 75 ? GraphicLocation_MIDDLE_MIDDLE : GraphicLocation_RIGHT_BOTTOM); bHori = sal_True; } else { eTmp = nPrc < 25 ? GraphicLocation_LEFT_TOP : (nPrc < 75 ? GraphicLocation_LEFT_MIDDLE : GraphicLocation_LEFT_BOTTOM); lcl_xmlbic_MergeVertPos( eNewPos, eTmp ); bVert = sal_True; } } else { // wrong percentage bOK = sal_False; } } else if( IsXMLToken( aToken, XML_CENTER ) ) { if( bHori ) lcl_xmlbic_MergeVertPos( eNewPos, GraphicLocation_MIDDLE_MIDDLE ); else if ( bVert ) lcl_xmlbic_MergeHoriPos( eNewPos, GraphicLocation_MIDDLE_MIDDLE ); else eNewPos = GraphicLocation_MIDDLE_MIDDLE; } else if( SvXMLUnitConverter::convertEnum( nTmp, aToken, psXML_BrushHoriPos ) ) { if( bVert ) lcl_xmlbic_MergeHoriPos( eNewPos, (GraphicLocation)nTmp ); else if( !bHori ) eNewPos = (GraphicLocation)nTmp; else bOK = sal_False; bHori = sal_True; } else if( SvXMLUnitConverter::convertEnum( nTmp, aToken, psXML_BrushVertPos ) ) { if( bHori ) lcl_xmlbic_MergeVertPos( eNewPos, (GraphicLocation)nTmp ); else if( !bVert ) eNewPos = (GraphicLocation)nTmp; else bOK = sal_False; bVert = sal_True; } else { bOK = sal_False; } } bOK &= GraphicLocation_NONE != eNewPos; if( bOK ) ePos = eNewPos; } break; case XML_TOK_BGIMG_REPEAT: { sal_uInt16 nPos = GraphicLocation_NONE; static SvXMLEnumMapEntry psXML_BrushRepeat[] = { { XML_BACKGROUND_REPEAT, GraphicLocation_TILED }, { XML_BACKGROUND_NO_REPEAT, GraphicLocation_MIDDLE_MIDDLE }, { XML_BACKGROUND_STRETCH, GraphicLocation_AREA }, { XML_TOKEN_INVALID, 0 } }; if( SvXMLUnitConverter::convertEnum( nPos, rValue, psXML_BrushRepeat ) ) { if( GraphicLocation_MIDDLE_MIDDLE != nPos || GraphicLocation_NONE == ePos || GraphicLocation_AREA == ePos || GraphicLocation_TILED == ePos ) ePos = (GraphicLocation)nPos; } } break; case XML_TOK_BGIMG_FILTER: sFilter = rValue; break; case XML_TOK_BGIMG_OPACITY: { sal_Int32 nTmp; // convert from percent and clip if (::sax::Converter::convertPercent( nTmp, rValue )) { if( (nTmp >= 0) && (nTmp <= 100) ) nTransparency = static_cast<sal_Int8>( 100-nTmp ); } } break; } } } XMLBackgroundImageContext::XMLBackgroundImageContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< xml::sax::XAttributeList > & xAttrList, const XMLPropertyState& rProp, sal_Int32 nPosIdx, sal_Int32 nFilterIdx, sal_Int32 nTransparencyIdx, ::std::vector< XMLPropertyState > &rProps ) : XMLElementPropertyContext( rImport, nPrfx, rLName, rProp, rProps ), aPosProp( nPosIdx ), aFilterProp( nFilterIdx ), aTransparencyProp( nTransparencyIdx ), nTransparency( 0 ) { ProcessAttrs( xAttrList ); } XMLBackgroundImageContext::~XMLBackgroundImageContext() { } SvXMLImportContext *XMLBackgroundImageContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< xml::sax::XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = NULL; if( (XML_NAMESPACE_OFFICE == nPrefix) && xmloff::token::IsXMLToken( rLocalName, xmloff::token::XML_BINARY_DATA ) ) { if( sURL.isEmpty() && !xBase64Stream.is() ) { xBase64Stream = GetImport().GetStreamForGraphicObjectURLFromBase64(); if( xBase64Stream.is() ) pContext = new XMLBase64ImportContext( GetImport(), nPrefix, rLocalName, xAttrList, xBase64Stream ); } } if( !pContext ) { pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); } return pContext; } void XMLBackgroundImageContext::EndElement() { if( !sURL.isEmpty() ) { sURL = GetImport().ResolveGraphicObjectURL( sURL, sal_False ); } else if( xBase64Stream.is() ) { sURL = GetImport().ResolveGraphicObjectURLFromBase64( xBase64Stream ); xBase64Stream = 0; } if( sURL.isEmpty() ) ePos = GraphicLocation_NONE; else if( GraphicLocation_NONE == ePos ) ePos = GraphicLocation_TILED; aProp.maValue <<= sURL; aPosProp.maValue <<= ePos; aFilterProp.maValue <<= sFilter; aTransparencyProp.maValue <<= nTransparency; SetInsert( sal_True ); XMLElementPropertyContext::EndElement(); if( -1 != aPosProp.mnIndex ) rProperties.push_back( aPosProp ); if( -1 != aFilterProp.mnIndex ) rProperties.push_back( aFilterProp ); if( -1 != aTransparencyProp.mnIndex ) rProperties.push_back( aTransparencyProp ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * For a full copy of the license see the LGPL.txt file */ #include "DistrhoPluginInternal.hpp" #if DISTRHO_PLUGIN_HAS_UI # include "DistrhoUIInternal.hpp" #endif #include "CarlaNative.hpp" // ----------------------------------------------------------------------- START_NAMESPACE_DISTRHO #if DISTRHO_PLUGIN_HAS_UI // ----------------------------------------------------------------------- // Carla UI #if ! DISTRHO_PLUGIN_WANT_STATE static const setStateFunc setStateCallback = nullptr; #endif #if ! DISTRHO_PLUGIN_IS_SYNTH static const sendNoteFunc sendNoteCallback = nullptr; #endif class UICarla { public: UICarla(const NativeHostDescriptor* const host, PluginExporter* const plugin) : fHost(host), fPlugin(plugin), fUI(this, 0, editParameterCallback, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback, plugin->getInstancePointer()) { fUI.setTitle(host->uiName); if (host->uiParentId != 0) fUI.setTransientWinId(host->uiParentId); } // --------------------------------------------- void carla_show(const bool yesNo) { fUI.setVisible(yesNo); } void carla_idle() { fUI.idle(); } void carla_setParameterValue(const uint32_t index, const float value) { fUI.parameterChanged(index, value); } #if DISTRHO_PLUGIN_WANT_PROGRAMS void carla_setMidiProgram(const uint32_t realProgram) { fUI.programChanged(realProgram); } #endif #if DISTRHO_PLUGIN_WANT_STATE void carla_setCustomData(const char* const key, const char* const value) { fUI.stateChanged(key, value); } #endif void carla_setUiTitle(const char* const uiTitle) { fUI.setTitle(uiTitle); } // --------------------------------------------- protected: void handleEditParameter(const uint32_t, const bool) { // TODO } void handleSetParameterValue(const uint32_t rindex, const float value) { fHost->ui_parameter_changed(fHost->handle, rindex, value); } void handleSetState(const char* const key, const char* const value) { fHost->ui_custom_data_changed(fHost->handle, key, value); } void handleSendNote(const uint8_t, const uint8_t, const uint8_t) { // TODO } void handleSetSize(const uint width, const uint height) { fUI.setSize(width, height); } // --------------------------------------------- private: // Plugin stuff const NativeHostDescriptor* const fHost; PluginExporter* const fPlugin; // UI UIExporter fUI; // --------------------------------------------- // Callbacks #define handlePtr ((UICarla*)ptr) static void editParameterCallback(void* ptr, uint32_t index, bool started) { handlePtr->handleEditParameter(index, started); } static void setParameterCallback(void* ptr, uint32_t rindex, float value) { handlePtr->handleSetParameterValue(rindex, value); } #if DISTRHO_PLUGIN_WANT_STATE static void setStateCallback(void* ptr, const char* key, const char* value) { handlePtr->handleSetState(key, value); } #endif #if DISTRHO_PLUGIN_IS_SYNTH static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity) { handlePtr->handleSendNote(channel, note, velocity); } #endif static void setSizeCallback(void* ptr, uint width, uint height) { handlePtr->handleSetSize(width, height); } #undef handlePtr CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UICarla) }; #endif // DISTRHO_PLUGIN_HAS_UI // ----------------------------------------------------------------------- // Carla Plugin class PluginCarla : public NativePluginClass { public: PluginCarla(const NativeHostDescriptor* const host) : NativePluginClass(host) { #if DISTRHO_PLUGIN_HAS_UI fUiPtr = nullptr; #endif } ~PluginCarla() override { #if DISTRHO_PLUGIN_HAS_UI if (fUiPtr != nullptr) { delete fUiPtr; fUiPtr = nullptr; } #endif } protected: // ------------------------------------------------------------------- // Plugin parameter calls uint32_t getParameterCount() const override { return fPlugin.getParameterCount(); } const NativeParameter* getParameterInfo(const uint32_t index) const override { CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), nullptr); static NativeParameter param; // reset param.hints = ::PARAMETER_IS_ENABLED; param.scalePointCount = 0; param.scalePoints = nullptr; { int nativeParamHints = ::PARAMETER_IS_ENABLED; const uint32_t paramHints = fPlugin.getParameterHints(index); if (paramHints & kParameterIsAutomable) nativeParamHints |= ::PARAMETER_IS_AUTOMABLE; if (paramHints & kParameterIsBoolean) nativeParamHints |= ::PARAMETER_IS_BOOLEAN; if (paramHints & kParameterIsInteger) nativeParamHints |= ::PARAMETER_IS_INTEGER; if (paramHints & kParameterIsLogarithmic) nativeParamHints |= ::PARAMETER_IS_LOGARITHMIC; if (paramHints & kParameterIsOutput) nativeParamHints |= ::PARAMETER_IS_OUTPUT; param.hints = static_cast<NativeParameterHints>(nativeParamHints); } param.name = fPlugin.getParameterName(index); param.unit = fPlugin.getParameterUnit(index); { const ParameterRanges& ranges(fPlugin.getParameterRanges(index)); param.ranges.def = ranges.def; param.ranges.min = ranges.min; param.ranges.max = ranges.max; } return &param; } float getParameterValue(const uint32_t index) const override { CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), 0.0f); return fPlugin.getParameterValue(index); } // ------------------------------------------------------------------- // Plugin midi-program calls #if DISTRHO_PLUGIN_WANT_PROGRAMS uint32_t getMidiProgramCount() const override { return fPlugin.getProgramCount(); } const NativeMidiProgram* getMidiProgramInfo(const uint32_t index) const override { CARLA_SAFE_ASSERT_RETURN(index < getMidiProgramCount(), nullptr); static NativeMidiProgram midiProgram; midiProgram.bank = index / 128; midiProgram.program = index % 128; midiProgram.name = fPlugin.getProgramName(index); return &midiProgram; } #endif // ------------------------------------------------------------------- // Plugin state calls void setParameterValue(const uint32_t index, const float value) override { CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),); fPlugin.setParameterValue(index, value); } #if DISTRHO_PLUGIN_WANT_PROGRAMS void setMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override { const uint32_t realProgram(bank * 128 + program); CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),); fPlugin.setProgram(realProgram); } #endif #if DISTRHO_PLUGIN_WANT_STATE void setCustomData(const char* const key, const char* const value) override { CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); CARLA_SAFE_ASSERT_RETURN(value != nullptr,); fPlugin.setState(key, value); } #endif // ------------------------------------------------------------------- // Plugin process calls void activate() override { fPlugin.activate(); } void deactivate() override { fPlugin.deactivate(); } #if DISTRHO_PLUGIN_IS_SYNTH void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const midiEvents, const uint32_t midiEventCount) override { MidiEvent realMidiEvents[midiEventCount]; for (uint32_t i=0; i < midiEventCount; ++i) { const NativeMidiEvent& midiEvent(midiEvents[i]); MidiEvent& realMidiEvent(realMidiEvents[i]); realMidiEvent.frame = midiEvent.time; realMidiEvent.size = midiEvent.size; carla_copy<uint8_t>(realMidiEvent.buf, midiEvent.data, midiEvent.size); } fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames, realMidiEvents, midiEventCount); } #else void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const, const uint32_t) override { fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames); } #endif // ------------------------------------------------------------------- // Plugin UI calls #if DISTRHO_PLUGIN_HAS_UI void uiShow(const bool show) override { if (show) createUiIfNeeded(); if (fUiPtr != nullptr) fUiPtr->carla_show(show); } void uiIdle() override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); fUiPtr->carla_idle(); } void uiSetParameterValue(const uint32_t index, const float value) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),); fUiPtr->carla_setParameterValue(index, value); } # if DISTRHO_PLUGIN_WANT_PROGRAMS void uiSetMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); const uint32_t realProgram(bank * 128 + program); CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),); fUiPtr->carla_setMidiProgram(realProgram); } # endif # if DISTRHO_PLUGIN_WANT_STATE void uiSetCustomData(const char* const key, const char* const value) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); CARLA_SAFE_ASSERT_RETURN(value != nullptr,); fUiPtr->carla_setCustomData(key, value); } # endif #endif // ------------------------------------------------------------------- // Plugin dispatcher calls void bufferSizeChanged(const uint32_t bufferSize) override { fPlugin.setBufferSize(bufferSize, true); } void sampleRateChanged(const double sampleRate) override { fPlugin.setSampleRate(sampleRate, true); } #if DISTRHO_PLUGIN_HAS_UI void uiNameChanged(const char* const uiName) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); fUiPtr->carla_setUiTitle(uiName); } #endif // ------------------------------------------------------------------- private: PluginExporter fPlugin; #if DISTRHO_PLUGIN_HAS_UI // UI UICarla* fUiPtr; void createUiIfNeeded() { if (fUiPtr == nullptr) { d_lastUiSampleRate = getSampleRate(); fUiPtr = new UICarla(getHostHandle(), &fPlugin); } } #endif CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginCarla) // ------------------------------------------------------------------- public: static NativePluginHandle _instantiate(const NativeHostDescriptor* host) { d_lastBufferSize = host->get_buffer_size(host->handle); d_lastSampleRate = host->get_sample_rate(host->handle); return new PluginCarla(host); } static void _cleanup(NativePluginHandle handle) { delete (PluginCarla*)handle; } }; END_NAMESPACE_DISTRHO // ----------------------------------------------------------------------- <commit_msg>Update carla wrapper<commit_after>/* * DISTRHO Plugin Framework (DPF) * Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * For a full copy of the license see the LGPL.txt file */ #include "DistrhoPluginInternal.hpp" #if DISTRHO_PLUGIN_HAS_UI # include "DistrhoUIInternal.hpp" #endif #include "CarlaNative.hpp" // ----------------------------------------------------------------------- START_NAMESPACE_DISTRHO #if DISTRHO_PLUGIN_HAS_UI // ----------------------------------------------------------------------- // Carla UI #if ! DISTRHO_PLUGIN_WANT_STATE static const setStateFunc setStateCallback = nullptr; #endif #if ! DISTRHO_PLUGIN_IS_SYNTH static const sendNoteFunc sendNoteCallback = nullptr; #endif class UICarla { public: UICarla(const NativeHostDescriptor* const host, PluginExporter* const plugin) : fHost(host), fPlugin(plugin), fUI(this, 0, editParameterCallback, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback, plugin->getInstancePointer()) { fUI.setWindowTitle(host->uiName); if (host->uiParentId != 0) fUI.setWindowTransientWinId(host->uiParentId); } ~UICarla() { fUI.quit(); } // --------------------------------------------- void carla_show(const bool yesNo) { fUI.setWindowVisible(yesNo); } bool carla_idle() { return fUI.idle(); } void carla_setParameterValue(const uint32_t index, const float value) { fUI.parameterChanged(index, value); } #if DISTRHO_PLUGIN_WANT_PROGRAMS void carla_setMidiProgram(const uint32_t realProgram) { fUI.programChanged(realProgram); } #endif #if DISTRHO_PLUGIN_WANT_STATE void carla_setCustomData(const char* const key, const char* const value) { fUI.stateChanged(key, value); } #endif void carla_setUiTitle(const char* const uiTitle) { fUI.setWindowTitle(uiTitle); } // --------------------------------------------- protected: void handleEditParameter(const uint32_t, const bool) { // TODO } void handleSetParameterValue(const uint32_t rindex, const float value) { fHost->ui_parameter_changed(fHost->handle, rindex, value); } void handleSetState(const char* const key, const char* const value) { fHost->ui_custom_data_changed(fHost->handle, key, value); } void handleSendNote(const uint8_t, const uint8_t, const uint8_t) { // TODO } void handleSetSize(const uint width, const uint height) { fUI.setWindowSize(width, height); } // --------------------------------------------- private: // Plugin stuff const NativeHostDescriptor* const fHost; PluginExporter* const fPlugin; // UI UIExporter fUI; // --------------------------------------------- // Callbacks #define handlePtr ((UICarla*)ptr) static void editParameterCallback(void* ptr, uint32_t index, bool started) { handlePtr->handleEditParameter(index, started); } static void setParameterCallback(void* ptr, uint32_t rindex, float value) { handlePtr->handleSetParameterValue(rindex, value); } #if DISTRHO_PLUGIN_WANT_STATE static void setStateCallback(void* ptr, const char* key, const char* value) { handlePtr->handleSetState(key, value); } #endif #if DISTRHO_PLUGIN_IS_SYNTH static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity) { handlePtr->handleSendNote(channel, note, velocity); } #endif static void setSizeCallback(void* ptr, uint width, uint height) { handlePtr->handleSetSize(width, height); } #undef handlePtr CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(UICarla) }; #endif // DISTRHO_PLUGIN_HAS_UI // ----------------------------------------------------------------------- // Carla Plugin class PluginCarla : public NativePluginClass { public: PluginCarla(const NativeHostDescriptor* const host) : NativePluginClass(host) { #if DISTRHO_PLUGIN_HAS_UI fUiPtr = nullptr; #endif } ~PluginCarla() override { #if DISTRHO_PLUGIN_HAS_UI if (fUiPtr != nullptr) { delete fUiPtr; fUiPtr = nullptr; } #endif } protected: // ------------------------------------------------------------------- // Plugin parameter calls uint32_t getParameterCount() const override { return fPlugin.getParameterCount(); } const NativeParameter* getParameterInfo(const uint32_t index) const override { CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), nullptr); static NativeParameter param; param.scalePointCount = 0; param.scalePoints = nullptr; { int nativeParamHints = ::NATIVE_PARAMETER_IS_ENABLED; const uint32_t paramHints = fPlugin.getParameterHints(index); if (paramHints & kParameterIsAutomable) nativeParamHints |= ::NATIVE_PARAMETER_IS_AUTOMABLE; if (paramHints & kParameterIsBoolean) nativeParamHints |= ::NATIVE_PARAMETER_IS_BOOLEAN; if (paramHints & kParameterIsInteger) nativeParamHints |= ::NATIVE_PARAMETER_IS_INTEGER; if (paramHints & kParameterIsLogarithmic) nativeParamHints |= ::NATIVE_PARAMETER_IS_LOGARITHMIC; if (paramHints & kParameterIsOutput) nativeParamHints |= ::NATIVE_PARAMETER_IS_OUTPUT; param.hints = static_cast<NativeParameterHints>(nativeParamHints); } param.name = fPlugin.getParameterName(index); param.unit = fPlugin.getParameterUnit(index); { const ParameterRanges& ranges(fPlugin.getParameterRanges(index)); param.ranges.def = ranges.def; param.ranges.min = ranges.min; param.ranges.max = ranges.max; } return &param; } float getParameterValue(const uint32_t index) const override { CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(), 0.0f); return fPlugin.getParameterValue(index); } // ------------------------------------------------------------------- // Plugin midi-program calls #if DISTRHO_PLUGIN_WANT_PROGRAMS uint32_t getMidiProgramCount() const override { return fPlugin.getProgramCount(); } const NativeMidiProgram* getMidiProgramInfo(const uint32_t index) const override { CARLA_SAFE_ASSERT_RETURN(index < getMidiProgramCount(), nullptr); static NativeMidiProgram midiProgram; midiProgram.bank = index / 128; midiProgram.program = index % 128; midiProgram.name = fPlugin.getProgramName(index); return &midiProgram; } #endif // ------------------------------------------------------------------- // Plugin state calls void setParameterValue(const uint32_t index, const float value) override { CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),); fPlugin.setParameterValue(index, value); } #if DISTRHO_PLUGIN_WANT_PROGRAMS void setMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override { const uint32_t realProgram(bank * 128 + program); CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),); fPlugin.setProgram(realProgram); } #endif #if DISTRHO_PLUGIN_WANT_STATE void setCustomData(const char* const key, const char* const value) override { CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); CARLA_SAFE_ASSERT_RETURN(value != nullptr,); fPlugin.setState(key, value); } #endif // ------------------------------------------------------------------- // Plugin process calls void activate() override { fPlugin.activate(); } void deactivate() override { fPlugin.deactivate(); } #if DISTRHO_PLUGIN_IS_SYNTH void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const midiEvents, const uint32_t midiEventCount) override { MidiEvent realMidiEvents[midiEventCount]; for (uint32_t i=0; i < midiEventCount; ++i) { const NativeMidiEvent& midiEvent(midiEvents[i]); MidiEvent& realMidiEvent(realMidiEvents[i]); realMidiEvent.frame = midiEvent.time; realMidiEvent.size = midiEvent.size; uint8_t j=0; for (; j<midiEvent.size; ++j) realMidiEvent.data[j] = midiEvent.data[j]; for (; j<midiEvent.size; ++j) realMidiEvent.data[j] = midiEvent.data[j]; realMidiEvent.dataExt = nullptr; } fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames, realMidiEvents, midiEventCount); } #else void process(float** const inBuffer, float** const outBuffer, const uint32_t frames, const NativeMidiEvent* const, const uint32_t) override { fPlugin.run(const_cast<const float**>(inBuffer), outBuffer, frames); } #endif // ------------------------------------------------------------------- // Plugin UI calls #if DISTRHO_PLUGIN_HAS_UI void uiShow(const bool show) override { if (show) { createUiIfNeeded(); CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); fUiPtr->carla_show(show); } else if (fUiPtr != nullptr) { delete fUiPtr; fUiPtr = nullptr; } } void uiIdle() override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); if (! fUiPtr->carla_idle()) { uiClosed(); delete fUiPtr; fUiPtr = nullptr; } } void uiSetParameterValue(const uint32_t index, const float value) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); CARLA_SAFE_ASSERT_RETURN(index < getParameterCount(),); fUiPtr->carla_setParameterValue(index, value); } # if DISTRHO_PLUGIN_WANT_PROGRAMS void uiSetMidiProgram(const uint8_t, const uint32_t bank, const uint32_t program) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); const uint32_t realProgram(bank * 128 + program); CARLA_SAFE_ASSERT_RETURN(realProgram < getMidiProgramCount(),); fUiPtr->carla_setMidiProgram(realProgram); } # endif # if DISTRHO_PLUGIN_WANT_STATE void uiSetCustomData(const char* const key, const char* const value) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); CARLA_SAFE_ASSERT_RETURN(key != nullptr && key[0] != '\0',); CARLA_SAFE_ASSERT_RETURN(value != nullptr,); fUiPtr->carla_setCustomData(key, value); } # endif #endif // ------------------------------------------------------------------- // Plugin dispatcher calls void bufferSizeChanged(const uint32_t bufferSize) override { fPlugin.setBufferSize(bufferSize, true); } void sampleRateChanged(const double sampleRate) override { fPlugin.setSampleRate(sampleRate, true); } #if DISTRHO_PLUGIN_HAS_UI void uiNameChanged(const char* const uiName) override { CARLA_SAFE_ASSERT_RETURN(fUiPtr != nullptr,); fUiPtr->carla_setUiTitle(uiName); } #endif // ------------------------------------------------------------------- private: PluginExporter fPlugin; #if DISTRHO_PLUGIN_HAS_UI // UI UICarla* fUiPtr; void createUiIfNeeded() { if (fUiPtr == nullptr) { d_lastUiSampleRate = getSampleRate(); fUiPtr = new UICarla(getHostHandle(), &fPlugin); } } #endif CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PluginCarla) // ------------------------------------------------------------------- public: static NativePluginHandle _instantiate(const NativeHostDescriptor* host) { d_lastBufferSize = host->get_buffer_size(host->handle); d_lastSampleRate = host->get_sample_rate(host->handle); return new PluginCarla(host); } static void _cleanup(NativePluginHandle handle) { delete (PluginCarla*)handle; } }; END_NAMESPACE_DISTRHO // ----------------------------------------------------------------------- <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, The Regents of the University of California // All rights reserved. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * 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. // // * Neither the name of the copyright holder 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 HOLDER 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 <array> #include <stdio.h> #include <tcl.h> #include <stdlib.h> #include <signal.h> #include <limits.h> #include <string> #include <libgen.h> // We have had too many problems with this std::filesytem on various platforms // so it is disabled but kept for future reference #ifdef USE_STD_FILESYSTEM #include <filesystem> #endif #ifdef ENABLE_READLINE // If you get an error on this include be sure you have // the package tcl-tclreadline-devel installed #include <tclreadline.h> #endif #ifdef ENABLE_PYTHON3 #define PY_SSIZE_T_CLEAN #include "Python.h" #endif #ifdef ENABLE_TCLX #include <tclExtend.h> #endif #include "sta/StringUtil.hh" #include "sta/StaMain.hh" #include "ord/Version.hh" #include "ord/InitOpenRoad.hh" #include "ord/OpenRoad.hh" #include "utl/Logger.h" #include "gui/gui.h" using std::string; using sta::stringEq; using sta::findCmdLineFlag; using sta::findCmdLineKey; using sta::sourceTclFile; using sta::is_regular_file; #ifdef ENABLE_PYTHON3 extern "C" { extern PyObject* PyInit__openroad_swig_py(); extern PyObject* PyInit__odbpy(); } #endif static int cmd_argc; static char **cmd_argv; bool gui_mode = false; const char* log_filename = nullptr; const char* metrics_filename = nullptr; static const char *init_filename = ".openroad"; static void showUsage(const char *prog, const char *init_filename); static void showSplash(); #ifdef ENABLE_PYTHON3 namespace sta { extern const char *odbpy_python_inits[]; extern const char *openroad_swig_py_python_inits[]; } static void initPython() { if (PyImport_AppendInittab("_odbpy", PyInit__odbpy) == -1) { fprintf(stderr, "Error: could not add module odbpy\n"); exit(1); } if (PyImport_AppendInittab("_openroad_swig_py", PyInit__openroad_swig_py) == -1) { fprintf(stderr, "Error: could not add module openroadpy\n"); exit(1); } Py_Initialize(); char *unencoded = sta::unencode(sta::odbpy_python_inits); PyObject* odb_code = Py_CompileString(unencoded, "odbpy.py", Py_file_input); if (odb_code == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not compile odbpy\n"); exit(1); } if (PyImport_ExecCodeModule("odb", odb_code) == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not add module odb\n"); exit(1); } delete [] unencoded; unencoded = sta::unencode(sta::openroad_swig_py_python_inits); PyObject* ord_code = Py_CompileString(unencoded, "openroad.py", Py_file_input); if (ord_code == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not compile openroad.py\n"); exit(1); } if (PyImport_ExecCodeModule("openroad", ord_code) == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not add module openroad\n"); exit(1); } delete [] unencoded; } #endif int main(int argc, char *argv[]) { if (argc == 2 && stringEq(argv[1], "-help")) { showUsage(argv[0], init_filename); return 0; } if (argc == 2 && stringEq(argv[1], "-version")) { printf("%s %s\n", OPENROAD_VERSION, OPENROAD_GIT_DESCRIBE); return 0; } log_filename = findCmdLineKey(argc, argv, "-log"); if (log_filename) { remove(log_filename); } metrics_filename = findCmdLineKey(argc, argv, "-metrics"); if (metrics_filename) { remove(metrics_filename); } #ifdef ENABLE_PYTHON3 // Capture the current SIGINT handler before python changes it. struct sigaction orig_sigint_handler; sigaction(SIGINT, NULL, &orig_sigint_handler); initPython(); #endif cmd_argc = argc; cmd_argv = argv; if (findCmdLineFlag(cmd_argc, cmd_argv, "-gui")) { gui_mode = true; return gui::startGui(cmd_argc, cmd_argv); } #ifdef ENABLE_PYTHON3 if (findCmdLineFlag(cmd_argc, cmd_argv, "-python")) { std::vector<wchar_t*> args; for(int i = 0; i < cmd_argc; i++) { size_t sz = strlen(cmd_argv[i]); args.push_back(new wchar_t[sz+1]); args[i][sz] = '\0'; for(size_t j = 0;j < sz; j++) { args[i][j] = (wchar_t) cmd_argv[i][j]; } } // Setup the app with tcl auto* interp = Tcl_CreateInterp(); Tcl_Init(interp); ord::initOpenRoad(interp); if (!findCmdLineFlag(cmd_argc, cmd_argv, "-no_splash")) { showSplash(); } return Py_Main(cmd_argc, args.data()); } else { // Python wants to install its own SIGINT handler to print KeyboardInterrupt // on ctrl-C. We don't want that if python is not the main interpreter. // We restore the handler from before initPython. sigaction(SIGINT, &orig_sigint_handler, NULL); } #endif // Set argc to 1 so Tcl_Main doesn't source any files. // Tcl_Main never returns. Tcl_Main(1, argv, ord::tclAppInit); return 0; } #ifdef ENABLE_READLINE static int tclReadlineInit(Tcl_Interp *interp) { std::array<const char *, 7> readline_cmds = { "history event", "eval $auto_index(::tclreadline::ScriptCompleter)", "::tclreadline::readline builtincompleter true", "::tclreadline::readline customcompleter ::tclreadline::ScriptCompleter", "proc ::tclreadline::prompt1 {} { return \"openroad > \" }", "proc ::tclreadline::prompt2 {} { return \"...> \" }", "::tclreadline::Loop" }; for (auto cmd : readline_cmds) { if (TCL_ERROR == Tcl_Eval(interp, cmd)) { return TCL_ERROR; } } return TCL_OK; } #endif // Tcl init executed inside Tcl_Main. static int tclAppInit(int argc, char *argv[], const char *init_filename, Tcl_Interp *interp) { // source init.tcl if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef ENABLE_TCLX if (Tclx_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef ENABLE_READLINE if (!gui_mode) { if (Tclreadline_Init(interp) == TCL_ERROR) { return TCL_ERROR; } Tcl_StaticPackage(interp, "tclreadline", Tclreadline_Init, Tclreadline_SafeInit); if (Tcl_EvalFile(interp, TCLRL_LIBRARY "/tclreadlineInit.tcl") != TCL_OK) { printf("Failed to load tclreadline\n"); } } #endif ord::initOpenRoad(interp); if (!findCmdLineFlag(argc, argv, "-no_splash")) showSplash(); const char* threads = findCmdLineKey(argc, argv, "-threads"); if (threads) { ord::OpenRoad::openRoad()->setThreadCount(threads); } else { // set to default number of threads ord::OpenRoad::openRoad()->setThreadCount(ord::OpenRoad::openRoad()->getThreadCount(), false); } bool exit_after_cmd_file = findCmdLineFlag(argc, argv, "-exit"); if (!findCmdLineFlag(argc, argv, "-no_init")) { #ifdef USE_STD_FILESYSTEM std::filesystem::path init(getenv("HOME")); init /= init_filename; if (std::filesystem::is_regular_file(init)) { sourceTclFile(init.c_str(), true, true, interp); } #else string init_path = getenv("HOME"); init_path += "/"; init_path += init_filename; if (is_regular_file(init_path.c_str())) sourceTclFile(init_path.c_str(), true, true, interp); #endif } if (argc > 2 || (argc > 1 && argv[1][0] == '-')) showUsage(argv[0], init_filename); else { if (argc == 2) { char *cmd_file = argv[1]; if (cmd_file) { int result = sourceTclFile(cmd_file, false, false, interp); if (exit_after_cmd_file) { int exit_code = (result == TCL_OK) ? EXIT_SUCCESS : EXIT_FAILURE; exit(exit_code); } } } } #ifdef ENABLE_READLINE if (!gui_mode) { return tclReadlineInit(interp); } #endif return TCL_OK; } int ord::tclAppInit(Tcl_Interp *interp) { return tclAppInit(cmd_argc, cmd_argv, init_filename, interp); } static void showUsage(const char *prog, const char *init_filename) { printf("Usage: %s [-help] [-version] [-no_init] [-exit] [-gui] [-threads count|max] [-log file_name] cmd_file\n", prog); printf(" -help show help and exit\n"); printf(" -version show version and exit\n"); printf(" -no_init do not read %s init file\n", init_filename); printf(" -threads count|max use count threads\n"); printf(" -no_splash do not show the license splash at startup\n"); printf(" -exit exit after reading cmd_file\n"); printf(" -gui start in gui mode\n"); #ifdef ENABLE_PYTHON3 printf(" -python start with python interpreter [limited to db operations]\n"); #endif printf(" -log <file_name> write a log in <file_name>\n"); printf(" cmd_file source cmd_file\n"); } static void showSplash() { utl::Logger *logger = ord::OpenRoad::openRoad()->getLogger(); string sha = OPENROAD_GIT_DESCRIBE; logger->report("OpenROAD {} {}", OPENROAD_VERSION, sha.c_str()); logger->report("This program is licensed under the BSD-3 license. See the LICENSE file for details."); logger->report("Components of this program may be licensed under more restrictive licenses which must be honored."); } <commit_msg>rm space<commit_after>///////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, The Regents of the University of California // All rights reserved. // // BSD 3-Clause License // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * 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. // // * Neither the name of the copyright holder 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 HOLDER 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 <array> #include <stdio.h> #include <tcl.h> #include <stdlib.h> #include <signal.h> #include <limits.h> #include <string> #include <libgen.h> // We have had too many problems with this std::filesytem on various platforms // so it is disabled but kept for future reference #ifdef USE_STD_FILESYSTEM #include <filesystem> #endif #ifdef ENABLE_READLINE // If you get an error on this include be sure you have // the package tcl-tclreadline-devel installed #include <tclreadline.h> #endif #ifdef ENABLE_PYTHON3 #define PY_SSIZE_T_CLEAN #include "Python.h" #endif #ifdef ENABLE_TCLX #include <tclExtend.h> #endif #include "sta/StringUtil.hh" #include "sta/StaMain.hh" #include "ord/Version.hh" #include "ord/InitOpenRoad.hh" #include "ord/OpenRoad.hh" #include "utl/Logger.h" #include "gui/gui.h" using std::string; using sta::stringEq; using sta::findCmdLineFlag; using sta::findCmdLineKey; using sta::sourceTclFile; using sta::is_regular_file; #ifdef ENABLE_PYTHON3 extern "C" { extern PyObject* PyInit__openroad_swig_py(); extern PyObject* PyInit__odbpy(); } #endif static int cmd_argc; static char **cmd_argv; bool gui_mode = false; const char* log_filename = nullptr; const char* metrics_filename = nullptr; static const char *init_filename = ".openroad"; static void showUsage(const char *prog, const char *init_filename); static void showSplash(); #ifdef ENABLE_PYTHON3 namespace sta { extern const char *odbpy_python_inits[]; extern const char *openroad_swig_py_python_inits[]; } static void initPython() { if (PyImport_AppendInittab("_odbpy", PyInit__odbpy) == -1) { fprintf(stderr, "Error: could not add module odbpy\n"); exit(1); } if (PyImport_AppendInittab("_openroad_swig_py", PyInit__openroad_swig_py) == -1) { fprintf(stderr, "Error: could not add module openroadpy\n"); exit(1); } Py_Initialize(); char *unencoded = sta::unencode(sta::odbpy_python_inits); PyObject* odb_code = Py_CompileString(unencoded, "odbpy.py", Py_file_input); if (odb_code == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not compile odbpy\n"); exit(1); } if (PyImport_ExecCodeModule("odb", odb_code) == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not add module odb\n"); exit(1); } delete [] unencoded; unencoded = sta::unencode(sta::openroad_swig_py_python_inits); PyObject* ord_code = Py_CompileString(unencoded, "openroad.py", Py_file_input); if (ord_code == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not compile openroad.py\n"); exit(1); } if (PyImport_ExecCodeModule("openroad", ord_code) == nullptr) { PyErr_Print(); fprintf(stderr, "Error: could not add module openroad\n"); exit(1); } delete [] unencoded; } #endif int main(int argc, char *argv[]) { if (argc == 2 && stringEq(argv[1], "-help")) { showUsage(argv[0], init_filename); return 0; } if (argc == 2 && stringEq(argv[1], "-version")) { printf("%s %s\n", OPENROAD_VERSION, OPENROAD_GIT_DESCRIBE); return 0; } log_filename = findCmdLineKey(argc, argv, "-log"); if (log_filename) { remove(log_filename); } metrics_filename = findCmdLineKey(argc, argv, "-metrics"); if (metrics_filename) { remove(metrics_filename); } #ifdef ENABLE_PYTHON3 // Capture the current SIGINT handler before python changes it. struct sigaction orig_sigint_handler; sigaction(SIGINT, NULL, &orig_sigint_handler); initPython(); #endif cmd_argc = argc; cmd_argv = argv; if (findCmdLineFlag(cmd_argc, cmd_argv, "-gui")) { gui_mode = true; return gui::startGui(cmd_argc, cmd_argv); } #ifdef ENABLE_PYTHON3 if (findCmdLineFlag(cmd_argc, cmd_argv, "-python")) { std::vector<wchar_t*> args; for(int i = 0; i < cmd_argc; i++) { size_t sz = strlen(cmd_argv[i]); args.push_back(new wchar_t[sz+1]); args[i][sz] = '\0'; for(size_t j = 0;j < sz; j++) { args[i][j] = (wchar_t) cmd_argv[i][j]; } } // Setup the app with tcl auto* interp = Tcl_CreateInterp(); Tcl_Init(interp); ord::initOpenRoad(interp); if (!findCmdLineFlag(cmd_argc, cmd_argv, "-no_splash")) { showSplash(); } return Py_Main(cmd_argc, args.data()); } else { // Python wants to install its own SIGINT handler to print KeyboardInterrupt // on ctrl-C. We don't want that if python is not the main interpreter. // We restore the handler from before initPython. sigaction(SIGINT, &orig_sigint_handler, NULL); } #endif // Set argc to 1 so Tcl_Main doesn't source any files. // Tcl_Main never returns. Tcl_Main(1, argv, ord::tclAppInit); return 0; } #ifdef ENABLE_READLINE static int tclReadlineInit(Tcl_Interp *interp) { std::array<const char *, 7> readline_cmds = { "history event", "eval $auto_index(::tclreadline::ScriptCompleter)", "::tclreadline::readline builtincompleter true", "::tclreadline::readline customcompleter ::tclreadline::ScriptCompleter", "proc ::tclreadline::prompt1 {} { return \"openroad> \" }", "proc ::tclreadline::prompt2 {} { return \"...> \" }", "::tclreadline::Loop" }; for (auto cmd : readline_cmds) { if (TCL_ERROR == Tcl_Eval(interp, cmd)) { return TCL_ERROR; } } return TCL_OK; } #endif // Tcl init executed inside Tcl_Main. static int tclAppInit(int argc, char *argv[], const char *init_filename, Tcl_Interp *interp) { // source init.tcl if (Tcl_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #ifdef ENABLE_TCLX if (Tclx_Init(interp) == TCL_ERROR) { return TCL_ERROR; } #endif #ifdef ENABLE_READLINE if (!gui_mode) { if (Tclreadline_Init(interp) == TCL_ERROR) { return TCL_ERROR; } Tcl_StaticPackage(interp, "tclreadline", Tclreadline_Init, Tclreadline_SafeInit); if (Tcl_EvalFile(interp, TCLRL_LIBRARY "/tclreadlineInit.tcl") != TCL_OK) { printf("Failed to load tclreadline\n"); } } #endif ord::initOpenRoad(interp); if (!findCmdLineFlag(argc, argv, "-no_splash")) showSplash(); const char* threads = findCmdLineKey(argc, argv, "-threads"); if (threads) { ord::OpenRoad::openRoad()->setThreadCount(threads); } else { // set to default number of threads ord::OpenRoad::openRoad()->setThreadCount(ord::OpenRoad::openRoad()->getThreadCount(), false); } bool exit_after_cmd_file = findCmdLineFlag(argc, argv, "-exit"); if (!findCmdLineFlag(argc, argv, "-no_init")) { #ifdef USE_STD_FILESYSTEM std::filesystem::path init(getenv("HOME")); init /= init_filename; if (std::filesystem::is_regular_file(init)) { sourceTclFile(init.c_str(), true, true, interp); } #else string init_path = getenv("HOME"); init_path += "/"; init_path += init_filename; if (is_regular_file(init_path.c_str())) sourceTclFile(init_path.c_str(), true, true, interp); #endif } if (argc > 2 || (argc > 1 && argv[1][0] == '-')) showUsage(argv[0], init_filename); else { if (argc == 2) { char *cmd_file = argv[1]; if (cmd_file) { int result = sourceTclFile(cmd_file, false, false, interp); if (exit_after_cmd_file) { int exit_code = (result == TCL_OK) ? EXIT_SUCCESS : EXIT_FAILURE; exit(exit_code); } } } } #ifdef ENABLE_READLINE if (!gui_mode) { return tclReadlineInit(interp); } #endif return TCL_OK; } int ord::tclAppInit(Tcl_Interp *interp) { return tclAppInit(cmd_argc, cmd_argv, init_filename, interp); } static void showUsage(const char *prog, const char *init_filename) { printf("Usage: %s [-help] [-version] [-no_init] [-exit] [-gui] [-threads count|max] [-log file_name] cmd_file\n", prog); printf(" -help show help and exit\n"); printf(" -version show version and exit\n"); printf(" -no_init do not read %s init file\n", init_filename); printf(" -threads count|max use count threads\n"); printf(" -no_splash do not show the license splash at startup\n"); printf(" -exit exit after reading cmd_file\n"); printf(" -gui start in gui mode\n"); #ifdef ENABLE_PYTHON3 printf(" -python start with python interpreter [limited to db operations]\n"); #endif printf(" -log <file_name> write a log in <file_name>\n"); printf(" cmd_file source cmd_file\n"); } static void showSplash() { utl::Logger *logger = ord::OpenRoad::openRoad()->getLogger(); string sha = OPENROAD_GIT_DESCRIBE; logger->report("OpenROAD {} {}", OPENROAD_VERSION, sha.c_str()); logger->report("This program is licensed under the BSD-3 license. See the LICENSE file for details."); logger->report("Components of this program may be licensed under more restrictive licenses which must be honored."); } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File ExpList0D.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: Expansion list 0D definition // /////////////////////////////////////////////////////////////////////////////// #include <MultiRegions/ExpList0D.h> #include <LibUtilities/Polylib/Polylib.h> namespace Nektar { namespace MultiRegions { /** * Default constructor ExpList0D object. */ ExpList0D::ExpList0D(): ExpList() { } /** * Creates an identical copy of another ExpList0D object. */ ExpList0D::ExpList0D(const ExpList0D &In, bool DeclareCoeffPhysArrays): ExpList(In,DeclareCoeffPhysArrays) { } ExpList0D::ExpList0D(const SpatialDomains::VertexComponentSharedPtr &m_geom): ExpList() { m_point = MemoryManager<LocalRegions::PointExp>::AllocateSharedPtr(m_geom); m_ncoeffs = 1; m_npoints = 1; // Set up m_coeffs, m_phys. m_coeffs = Array<OneD, NekDouble>(m_ncoeffs); m_phys = Array<OneD, NekDouble>(m_npoints); m_coeffs[0] = m_point->GetCoeff(0); m_phys[0] = m_point->GetPhys(0); m_coeffs = m_point->UpdateCoeffs(); m_phys = m_point->UpdatePhys(); } /** * Store expansions for the trace space expansions used in * DisContField1D. * * @param bndConstraint Array of ExpList1D objects each containing a * 1D spectral/hp element expansion on a single * boundary region. * @param bndCond Array of BoundaryCondition objects which contain * information about the boundary conditions on the * different boundary regions. * @param locexp Complete domain expansion list. * @param graph1D 1D mesh corresponding to the expansion list. * @param periodicVertices List of periodic Vertices. * @param UseGenSegExp If true, create general segment expansions * instead of just normal segment expansions. */ ExpList0D::ExpList0D( const Array<OneD,const ExpListSharedPtr> &bndConstraint, const Array<OneD, const SpatialDomains ::BoundaryConditionShPtr> &bndCond, const StdRegions::StdExpansionVector &locexp, const SpatialDomains::MeshGraphSharedPtr &graph1D, const map<int,int> &periodicVertices, const bool DeclareCoeffPhysArrays): ExpList() { int i,j,cnt,id, elmtid=0; map<int,int> EdgeDone; map<int,int> NormalSet; SpatialDomains::VertexComponentSharedPtr PointGeom; LocalRegions::PointExpSharedPtr Point; // First loop over boundary conditions to renumber Dirichlet boundaries cnt = 0; for(i = 0; i < bndCond.num_elements(); ++i) { if(bndCond[i]->GetBoundaryConditionType() == SpatialDomains::eDirichlet) { for(j = 0; j < bndConstraint[i]->GetExpSize(); ++j) { PointGeom = bndConstraint[i]->GetVertex(); Point = MemoryManager<LocalRegions::PointExp>::AllocateSharedPtr(PointGeom); EdgeDone[PointGeom->GetVid()] = elmtid; Point->SetElmtId(elmtid++); (*m_exp).push_back(Point); } } } // loop over all other edges and fill out other connectivities for(i = 0; i < locexp.size(); ++i) { for(j = 0; j < 2; ++j) { PointGeom = (locexp[i]->GetGeom1D())->GetVertex(j); id = PointGeom->GetVid(); if(EdgeDone.count(id)==0) { Point = MemoryManager<LocalRegions::PointExp>::AllocateSharedPtr(PointGeom); EdgeDone[id] = elmtid; if (periodicVertices.count(id) > 0) { EdgeDone[periodicVertices.find(id)->second] = elmtid; } Point->SetElmtId(elmtid++); (*m_exp).push_back(Point); } /*else // variable modes/points { LibUtilities::BasisKey EdgeBkey = locexp[i]->DetEdgeBasisKey(j); if((*m_exp)[EdgeDone[id]]->GetNumPoints(0) >= EdgeBkey.GetNumPoints() && (*m_exp)[EdgeDone[id]]->GetBasisNumModes(0) >= EdgeBkey.GetNumModes()) { } else if((*m_exp)[EdgeDone[id]]->GetNumPoints(0) <= EdgeBkey.GetNumPoints() && (*m_exp)[EdgeDone[id]]->GetBasisNumModes(0) <= EdgeBkey.GetNumModes()) { Seg = MemoryManager<LocalRegions::SegExp>::AllocateSharedPtr(EdgeBkey, SegGeom); Seg->SetElmtId(EdgeDone[id]); (*m_exp)[EdgeDone[id]] = Seg; NormalSet.erase(id); } else { ASSERTL0(false, "inappropriate number of points/modes (max " "num of points is not set with max order)"); } }*/ } } // Setup Default optimisation information. int nel = GetExpSize(); m_globalOptParam = MemoryManager<NekOptimize::GlobalOptParam>::AllocateSharedPtr(nel); // Set up offset information and array sizes SetCoeffPhysOffsets(); // Set up m_coeffs, m_phys. if(DeclareCoeffPhysArrays) { m_coeffs = Array<OneD, NekDouble>(m_ncoeffs); m_phys = Array<OneD, NekDouble>(m_npoints); } } void ExpList0D::SetCoeffPhysOffsets() { int i; // Set up offset information and array sizes m_coeff_offset = Array<OneD,int>(m_exp->size()); m_phys_offset = Array<OneD,int>(m_exp->size()); m_offset_elmt_id = Array<OneD,int>(m_exp->size()); m_ncoeffs = m_npoints = 0; for(i = 0; i < m_exp->size(); ++i) { m_coeff_offset[i] = m_ncoeffs; m_phys_offset [i] = m_npoints; m_offset_elmt_id[i] = i; m_ncoeffs += (*m_exp)[i]->GetNcoeffs(); m_npoints += (*m_exp)[i]->GetTotPoints(); } } /** * */ ExpList0D::~ExpList0D() { } void ExpList0D::v_GetCoords(NekDouble &x, NekDouble &y, NekDouble &z) { m_point->GetCoords(x,y,z); } void ExpList0D::v_GetCoord(Array<OneD,NekDouble> &coords) { m_point->GetCoords(coords); } void ExpList0D::v_SetCoeff(NekDouble val) { m_point->SetCoeff(val); } void ExpList0D::v_SetPhys(NekDouble val) { m_point->SetPhys(val); } const SpatialDomains::VertexComponentSharedPtr &ExpList0D::v_GetGeom(void) const { return m_point->GetGeom(); } const SpatialDomains::VertexComponentSharedPtr &ExpList0D::v_GetVertex(void) const { return m_point->GetVertex(); } /** * For each local element, copy the normals stored in the element list * into the array \a normals. * @param normals Multidimensional array in which to copy normals * to. Must have dimension equal to or larger than * the spatial dimension of the elements. */ void ExpList0D::GetNormals(Array<OneD, Array<OneD, NekDouble> > &normals) { int i,j,k,e_npoints,offset; Array<OneD,Array<OneD,NekDouble> > locnormals; // Assume whole array is of same coordinate dimension int coordim = normals.num_elements(); ASSERTL1(normals.num_elements() >= coordim, "Output vector does not have sufficient dimensions to " "match coordim"); // Process each expansion. for(i = 0; i < m_exp->size(); ++i) { LocalRegions::Expansion0DSharedPtr loc_exp = boost::dynamic_pointer_cast<LocalRegions::Expansion0D>((*m_exp)[i]); LocalRegions::Expansion1DSharedPtr loc_elmt = loc_exp->GetLeftAdjacentElementExp(); // Get the number of points and normals for this expansion. e_npoints = 1; locnormals = loc_elmt->GetVertexNormal(loc_exp->GetLeftAdjacentElementVertex()); // Get the physical data offset for this expansion. offset = m_phys_offset[i]; // Process each point in the expansion. for(j = 0; j < e_npoints; ++j) { // Process each spatial dimension and copy the values into // the output array. for(k = 0; k < coordim; ++k) { normals[k][offset] = locnormals[k][0]; } } } //negate first normal inwards facing into domain for (k=0; k<coordim; k++) { normals[k][0] = locnormals[k][0]; } } /** * One-dimensional upwind. * \see ExpList1D::Upwind( * const Array<OneD, const Array<OneD, NekDouble> >, * const Array<OneD, const NekDouble>, * const Array<OneD, const NekDouble>, * Array<OneD, NekDouble>, int) * @param Vn Velocity field. * @param Fwd Left state. * @param Bwd Right state. * @param Upwind Output vector. * @param direction (Unused). */ void ExpList0D::Upwind( const Array<OneD, const NekDouble> &Vn, const Array<OneD, const NekDouble> &Fwd, const Array<OneD, const NekDouble> &Bwd, Array<OneD, NekDouble> &Upwind, int direction) { // Process each point in the expansion. for(int j = 0; j < Fwd.num_elements(); ++j) { // Upwind based on one-dimensional velocity. if(Vn[j] > 0.0) { Upwind[j] = Fwd[j]; } else { Upwind[j] = Bwd[j]; } } } } //end of namespace } //end of namespace /** * $Log: v $ * **/ <commit_msg>Commented out EdgeDone logic for periodic edges in the constructor to make it work with Dirichlet boundary conditions.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File ExpList0D.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: Expansion list 0D definition // /////////////////////////////////////////////////////////////////////////////// #include <MultiRegions/ExpList0D.h> #include <LibUtilities/Polylib/Polylib.h> namespace Nektar { namespace MultiRegions { /** * Default constructor ExpList0D object. */ ExpList0D::ExpList0D(): ExpList() { } /** * Creates an identical copy of another ExpList0D object. */ ExpList0D::ExpList0D(const ExpList0D &In, bool DeclareCoeffPhysArrays): ExpList(In,DeclareCoeffPhysArrays) { } ExpList0D::ExpList0D(const SpatialDomains::VertexComponentSharedPtr &m_geom): ExpList() { m_point = MemoryManager<LocalRegions::PointExp>::AllocateSharedPtr(m_geom); m_ncoeffs = 1; m_npoints = 1; // Set up m_coeffs, m_phys. m_coeffs = Array<OneD, NekDouble>(m_ncoeffs); m_phys = Array<OneD, NekDouble>(m_npoints); m_coeffs[0] = m_point->GetCoeff(0); m_phys[0] = m_point->GetPhys(0); m_coeffs = m_point->UpdateCoeffs(); m_phys = m_point->UpdatePhys(); } /** * Store expansions for the trace space expansions used in * DisContField1D. * * @param bndConstraint Array of ExpList1D objects each containing a * 1D spectral/hp element expansion on a single * boundary region. * @param bndCond Array of BoundaryCondition objects which contain * information about the boundary conditions on the * different boundary regions. * @param locexp Complete domain expansion list. * @param graph1D 1D mesh corresponding to the expansion list. * @param periodicVertices List of periodic Vertices. * @param UseGenSegExp If true, create general segment expansions * instead of just normal segment expansions. */ ExpList0D::ExpList0D( const Array<OneD,const ExpListSharedPtr> &bndConstraint, const Array<OneD, const SpatialDomains ::BoundaryConditionShPtr> &bndCond, const StdRegions::StdExpansionVector &locexp, const SpatialDomains::MeshGraphSharedPtr &graph1D, const map<int,int> &periodicVertices, const bool DeclareCoeffPhysArrays): ExpList() { int i,j,cnt,id, elmtid=0; map<int,int> EdgeDone; map<int,int> NormalSet; SpatialDomains::VertexComponentSharedPtr PointGeom; LocalRegions::PointExpSharedPtr Point; // First loop over boundary conditions to renumber Dirichlet boundaries cnt = 0; for(i = 0; i < bndCond.num_elements(); ++i) { if(bndCond[i]->GetBoundaryConditionType() == SpatialDomains::eDirichlet) { for(j = 0; j < bndConstraint[i]->GetExpSize(); ++j) { PointGeom = bndConstraint[i]->GetVertex(); Point = MemoryManager<LocalRegions::PointExp>::AllocateSharedPtr(PointGeom); EdgeDone[PointGeom->GetVid()] = elmtid; Point->SetElmtId(elmtid++); (*m_exp).push_back(Point); } } } // loop over all other edges and fill out other connectivities for(i = 0; i < locexp.size(); ++i) { for(j = 0; j < 2; ++j) { PointGeom = (locexp[i]->GetGeom1D())->GetVertex(j); id = PointGeom->GetVid(); if(EdgeDone.count(id)==0) { Point = MemoryManager<LocalRegions::PointExp>::AllocateSharedPtr(PointGeom); EdgeDone[id] = elmtid; //if (periodicVertices.count(id) > 0) //{ // EdgeDone[periodicVertices.find(id)->second] = elmtid; //} Point->SetElmtId(elmtid++); (*m_exp).push_back(Point); } /*else // variable modes/points { LibUtilities::BasisKey EdgeBkey = locexp[i]->DetEdgeBasisKey(j); if((*m_exp)[EdgeDone[id]]->GetNumPoints(0) >= EdgeBkey.GetNumPoints() && (*m_exp)[EdgeDone[id]]->GetBasisNumModes(0) >= EdgeBkey.GetNumModes()) { } else if((*m_exp)[EdgeDone[id]]->GetNumPoints(0) <= EdgeBkey.GetNumPoints() && (*m_exp)[EdgeDone[id]]->GetBasisNumModes(0) <= EdgeBkey.GetNumModes()) { Seg = MemoryManager<LocalRegions::SegExp>::AllocateSharedPtr(EdgeBkey, SegGeom); Seg->SetElmtId(EdgeDone[id]); (*m_exp)[EdgeDone[id]] = Seg; NormalSet.erase(id); } else { ASSERTL0(false, "inappropriate number of points/modes (max " "num of points is not set with max order)"); } }*/ } } // Setup Default optimisation information. int nel = GetExpSize(); m_globalOptParam = MemoryManager<NekOptimize::GlobalOptParam>::AllocateSharedPtr(nel); // Set up offset information and array sizes SetCoeffPhysOffsets(); // Set up m_coeffs, m_phys. if(DeclareCoeffPhysArrays) { m_coeffs = Array<OneD, NekDouble>(m_ncoeffs); m_phys = Array<OneD, NekDouble>(m_npoints); } } void ExpList0D::SetCoeffPhysOffsets() { int i; // Set up offset information and array sizes m_coeff_offset = Array<OneD,int>(m_exp->size()); m_phys_offset = Array<OneD,int>(m_exp->size()); m_offset_elmt_id = Array<OneD,int>(m_exp->size()); m_ncoeffs = m_npoints = 0; for(i = 0; i < m_exp->size(); ++i) { m_coeff_offset[i] = m_ncoeffs; m_phys_offset [i] = m_npoints; m_offset_elmt_id[i] = i; m_ncoeffs += (*m_exp)[i]->GetNcoeffs(); m_npoints += (*m_exp)[i]->GetTotPoints(); } } /** * */ ExpList0D::~ExpList0D() { } void ExpList0D::v_GetCoords(NekDouble &x, NekDouble &y, NekDouble &z) { m_point->GetCoords(x,y,z); } void ExpList0D::v_GetCoord(Array<OneD,NekDouble> &coords) { m_point->GetCoords(coords); } void ExpList0D::v_SetCoeff(NekDouble val) { m_point->SetCoeff(val); } void ExpList0D::v_SetPhys(NekDouble val) { m_point->SetPhys(val); } const SpatialDomains::VertexComponentSharedPtr &ExpList0D::v_GetGeom(void) const { return m_point->GetGeom(); } const SpatialDomains::VertexComponentSharedPtr &ExpList0D::v_GetVertex(void) const { return m_point->GetVertex(); } /** * For each local element, copy the normals stored in the element list * into the array \a normals. * @param normals Multidimensional array in which to copy normals * to. Must have dimension equal to or larger than * the spatial dimension of the elements. */ void ExpList0D::GetNormals(Array<OneD, Array<OneD, NekDouble> > &normals) { int i,j,k,e_npoints,offset; Array<OneD,Array<OneD,NekDouble> > locnormals; // Assume whole array is of same coordinate dimension int coordim = normals.num_elements(); ASSERTL1(normals.num_elements() >= coordim, "Output vector does not have sufficient dimensions to " "match coordim"); // Process each expansion. for(i = 0; i < m_exp->size(); ++i) { LocalRegions::Expansion0DSharedPtr loc_exp = boost::dynamic_pointer_cast<LocalRegions::Expansion0D>((*m_exp)[i]); LocalRegions::Expansion1DSharedPtr loc_elmt = loc_exp->GetLeftAdjacentElementExp(); // Get the number of points and normals for this expansion. e_npoints = 1; locnormals = loc_elmt->GetVertexNormal(loc_exp->GetLeftAdjacentElementVertex()); // Get the physical data offset for this expansion. offset = m_phys_offset[i]; // Process each point in the expansion. for(j = 0; j < e_npoints; ++j) { // Process each spatial dimension and copy the values into // the output array. for(k = 0; k < coordim; ++k) { normals[k][offset] = locnormals[k][0]; } } } //negate first normal inwards facing into domain for (k=0; k<coordim; k++) { normals[k][0] = locnormals[k][0]; } } /** * One-dimensional upwind. * \see ExpList1D::Upwind( * const Array<OneD, const Array<OneD, NekDouble> >, * const Array<OneD, const NekDouble>, * const Array<OneD, const NekDouble>, * Array<OneD, NekDouble>, int) * @param Vn Velocity field. * @param Fwd Left state. * @param Bwd Right state. * @param Upwind Output vector. * @param direction (Unused). */ void ExpList0D::Upwind( const Array<OneD, const NekDouble> &Vn, const Array<OneD, const NekDouble> &Fwd, const Array<OneD, const NekDouble> &Bwd, Array<OneD, NekDouble> &Upwind, int direction) { // Process each point in the expansion. for(int j = 0; j < Fwd.num_elements(); ++j) { // Upwind based on one-dimensional velocity. if(Vn[j] > 0.0) { Upwind[j] = Fwd[j]; } else { Upwind[j] = Bwd[j]; } } } } //end of namespace } //end of namespace /** * $Log: v $ * **/ <|endoftext|>
<commit_before>#include "routing/index_graph_starter.hpp" #include "routing/fake_edges_container.hpp" #include "geometry/mercator.hpp" #include <map> namespace { using namespace routing; using namespace std; Segment GetReverseSegment(Segment const & segment) { return Segment(segment.GetMwmId(), segment.GetFeatureId(), segment.GetSegmentIdx(), !segment.IsForward()); } } // namespace namespace routing { // static void IndexGraphStarter::CheckValidRoute(vector<Segment> const & segments) { // Valid route contains at least 3 segments: // start fake, finish fake and at least one normal nearest segment. CHECK_GREATER_OR_EQUAL(segments.size(), 3, ()); CHECK(IsFakeSegment(segments.front()), ()); CHECK(IsFakeSegment(segments.back()), ()); } // static size_t IndexGraphStarter::GetRouteNumPoints(vector<Segment> const & segments) { CheckValidRoute(segments); return segments.size() + 1; } IndexGraphStarter::IndexGraphStarter(FakeEnding const & startEnding, FakeEnding const & finishEnding, uint32_t fakeNumerationStart, bool strictForward, WorldGraph & graph) : m_graph(graph) , m_startId(fakeNumerationStart) , m_startPassThroughAllowed(EndingPassThroughAllowed(startEnding)) , m_finishPassThroughAllowed(EndingPassThroughAllowed(finishEnding)) { AddStart(startEnding, finishEnding, strictForward, fakeNumerationStart); m_finishId = fakeNumerationStart; AddFinish(finishEnding, startEnding, fakeNumerationStart); auto const startPoint = GetPoint(GetStartSegment(), false /* front */); auto const finishPoint = GetPoint(GetFinishSegment(), true /* front */); m_startToFinishDistanceM = MercatorBounds::DistanceOnEarth(startPoint, finishPoint); } void IndexGraphStarter::Append(FakeEdgesContainer const & container) { m_finishId = container.m_finishId; m_finishPassThroughAllowed = container.m_finishPassThroughAllowed; auto const startPoint = GetPoint(GetStartSegment(), false /* front */); auto const finishPoint = GetPoint(GetFinishSegment(), true /* front */); m_startToFinishDistanceM = MercatorBounds::DistanceOnEarth(startPoint, finishPoint); m_fake.Append(container.m_fake); } Junction const & IndexGraphStarter::GetStartJunction() const { auto const & startSegment = GetStartSegment(); return m_fake.GetVertex(startSegment).GetJunctionFrom(); } Junction const & IndexGraphStarter::GetFinishJunction() const { auto const & finishSegment = GetFinishSegment(); return m_fake.GetVertex(finishSegment).GetJunctionTo(); } bool IndexGraphStarter::ConvertToReal(Segment & segment) const { if (!IsFakeSegment(segment)) return true; return m_fake.FindReal(Segment(segment), segment); } Junction const & IndexGraphStarter::GetJunction(Segment const & segment, bool front) const { if (!IsFakeSegment(segment)) return m_graph.GetJunction(segment, front); auto const & vertex = m_fake.GetVertex(segment); return front ? vertex.GetJunctionTo() : vertex.GetJunctionFrom(); } Junction const & IndexGraphStarter::GetRouteJunction(vector<Segment> const & segments, size_t pointIndex) const { CHECK(!segments.empty(), ()); CHECK_LESS_OR_EQUAL( pointIndex, segments.size(), ("Point with index", pointIndex, "does not exist in route with size", segments.size())); if (pointIndex == segments.size()) return GetJunction(segments[pointIndex - 1], true /* front */); return GetJunction(segments[pointIndex], false); } m2::PointD const & IndexGraphStarter::GetPoint(Segment const & segment, bool front) const { return GetJunction(segment, front).GetPoint(); } set<NumMwmId> IndexGraphStarter::GetMwms() const { set<NumMwmId> mwms; for (auto const & kv : m_fake.GetFakeToReal()) mwms.insert(kv.second.GetMwmId()); return mwms; } bool IndexGraphStarter::CheckLength(RouteWeight const & weight) const { // We allow 1 pass-through/non-pass-through crossing per ending located in // non-pass-through zone to allow user to leave this zone. int const nonPassThroughCrossAllowed = (m_startPassThroughAllowed ? 0 : 1) + (m_finishPassThroughAllowed ? 0 : 1); return weight.GetNonPassThroughCross() <= nonPassThroughCrossAllowed && m_graph.CheckLength(weight, m_startToFinishDistanceM); } void IndexGraphStarter::GetEdgesList(Segment const & segment, bool isOutgoing, vector<SegmentEdge> & edges) const { edges.clear(); if (IsFakeSegment(segment)) { Segment real; if (m_fake.FindReal(segment, real)) { bool const haveSameFront = GetJunction(segment, true /* front */) == GetJunction(real, true); bool const haveSameBack = GetJunction(segment, false /* front */) == GetJunction(real, false); if ((isOutgoing && haveSameFront) || (!isOutgoing && haveSameBack)) AddRealEdges(real, isOutgoing, edges); } for (auto const & s : m_fake.GetEdges(segment, isOutgoing)) edges.emplace_back(s, CalcSegmentWeight(isOutgoing ? s : segment)); } else { AddRealEdges(segment, isOutgoing, edges); } AddFakeEdges(segment, edges); } RouteWeight IndexGraphStarter::CalcSegmentWeight(Segment const & segment) const { if (!IsFakeSegment(segment)) { return m_graph.CalcSegmentWeight(segment); } auto const & vertex = m_fake.GetVertex(segment); Segment real; if (m_fake.FindReal(segment, real)) { auto const partLen = MercatorBounds::DistanceOnEarth(vertex.GetPointFrom(), vertex.GetPointTo()); auto const fullLen = MercatorBounds::DistanceOnEarth(GetPoint(real, false /* front */), GetPoint(real, true /* front */)); CHECK_GREATER(fullLen, 0.0, ()); return partLen / fullLen * m_graph.CalcSegmentWeight(real); } return m_graph.CalcOffroadWeight(vertex.GetPointFrom(), vertex.GetPointTo()); } RouteWeight IndexGraphStarter::CalcRouteSegmentWeight(vector<Segment> const & route, size_t segmentIndex) const { CHECK_LESS( segmentIndex, route.size(), ("Segment with index", segmentIndex, "does not exist in route with size", route.size())); return CalcSegmentWeight(route[segmentIndex]); } bool IndexGraphStarter::IsLeap(NumMwmId mwmId) const { if (mwmId == kFakeNumMwmId) return false; for (auto const & kv : m_fake.GetFakeToReal()) { if (kv.second.GetMwmId() == mwmId) return false; } return m_graph.LeapIsAllowed(mwmId); } void IndexGraphStarter::AddEnding(FakeEnding const & thisEnding, FakeEnding const & otherEnding, bool isStart, bool strictForward, uint32_t & fakeNumerationStart) { Segment const dummy = Segment(); map<Segment, Junction> otherSegments; for (auto const & p : otherEnding.m_projections) { otherSegments[p.m_segment] = p.m_junction; // We use |otherEnding| to generate proper fake edges in case both endings have projections // to the same segment. Direction of p.m_segment does not matter. otherSegments[GetReverseSegment(p.m_segment)] = p.m_junction; } // Add pure fake vertex auto const fakeSegment = GetFakeSegmentAndIncr(fakeNumerationStart); FakeVertex fakeVertex(thisEnding.m_originJunction, thisEnding.m_originJunction, FakeVertex::Type::PureFake); m_fake.AddStandaloneVertex(fakeSegment, fakeVertex); for (auto const & projection : thisEnding.m_projections) { // Add projection edges auto const projectionSegment = GetFakeSegmentAndIncr(fakeNumerationStart); FakeVertex projectionVertex(isStart ? thisEnding.m_originJunction : projection.m_junction, isStart ? projection.m_junction : thisEnding.m_originJunction, FakeVertex::Type::PureFake); m_fake.AddVertex(fakeSegment, projectionSegment, projectionVertex, isStart /* isOutgoing */, false /* isPartOfReal */, dummy /* realSegment */); // Add fake parts of real auto frontJunction = projection.m_segmentFront; auto backJunction = projection.m_segmentBack; // Check whether we have projections to same real segment from both endings. auto const it = otherSegments.find(projection.m_segment); if (it != otherSegments.end()) { auto const & otherJunction = it->second; auto const distBackToThis = MercatorBounds::DistanceOnEarth(backJunction.GetPoint(), projection.m_junction.GetPoint()); auto const distBackToOther = MercatorBounds::DistanceOnEarth(backJunction.GetPoint(), otherJunction.GetPoint()); if (distBackToThis < distBackToOther) frontJunction = otherJunction; else backJunction = otherJunction; } FakeVertex forwardPartOfReal(isStart ? projection.m_junction : backJunction, isStart ? frontJunction : projection.m_junction, FakeVertex::Type::PartOfReal); Segment fakeForwardSegment; if (!m_fake.FindSegment(forwardPartOfReal, fakeForwardSegment)) fakeForwardSegment = GetFakeSegmentAndIncr(fakeNumerationStart); m_fake.AddVertex(projectionSegment, fakeForwardSegment, forwardPartOfReal, isStart /* isOutgoing */, true /* isPartOfReal */, projection.m_segment); if (!strictForward && !projection.m_isOneWay) { auto const backwardSegment = GetReverseSegment(projection.m_segment); FakeVertex backwardPartOfReal(isStart ? projection.m_junction : frontJunction, isStart ? backJunction : projection.m_junction, FakeVertex::Type::PartOfReal); Segment fakeBackwardSegment; if (!m_fake.FindSegment(backwardPartOfReal, fakeBackwardSegment)) fakeBackwardSegment = GetFakeSegmentAndIncr(fakeNumerationStart); m_fake.AddVertex(projectionSegment, fakeBackwardSegment, backwardPartOfReal, isStart /* isOutgoing */, true /* isPartOfReal */, backwardSegment); } } } void IndexGraphStarter::AddStart(FakeEnding const & startEnding, FakeEnding const & finishEnding, bool strictForward, uint32_t & fakeNumerationStart) { AddEnding(startEnding, finishEnding, true /* isStart */, strictForward, fakeNumerationStart); } void IndexGraphStarter::AddFinish(FakeEnding const & finishEnding, FakeEnding const & startEnding, uint32_t & fakeNumerationStart) { AddEnding(finishEnding, startEnding, false /* isStart */, false /* strictForward */, fakeNumerationStart); } void IndexGraphStarter::AddFakeEdges(Segment const & segment, vector<SegmentEdge> & edges) const { vector<SegmentEdge> fakeEdges; for (auto const & edge : edges) { for (auto const & s : m_fake.GetFake(edge.GetTarget())) { // Check fake segment is connected to source segment. if (GetJunction(s, false /* front */) == GetJunction(segment, true) || GetJunction(s, true) == GetJunction(segment, false)) { fakeEdges.emplace_back(s, edge.GetWeight()); } } } edges.insert(edges.end(), fakeEdges.begin(), fakeEdges.end()); } void IndexGraphStarter::AddRealEdges(Segment const & segment, bool isOutgoing, std::vector<SegmentEdge> & edges) const { bool const isEnding = !m_fake.GetFake(segment).empty(); m_graph.GetEdgeList(segment, isOutgoing, IsLeap(segment.GetMwmId()), isEnding, edges); } bool IndexGraphStarter::EndingPassThroughAllowed(FakeEnding const & ending) { return any_of(ending.m_projections.cbegin(), ending.m_projections.cend(), [this](Projection const & projection) { return m_graph.IsPassThroughAllowed(projection.m_segment.GetMwmId(), projection.m_segment.GetFeatureId()); }); } } // namespace routing <commit_msg>Fix m_startToFinishDistanceM calculation for routes with intermediate point.<commit_after>#include "routing/index_graph_starter.hpp" #include "routing/fake_edges_container.hpp" #include "geometry/mercator.hpp" #include <map> namespace { using namespace routing; using namespace std; Segment GetReverseSegment(Segment const & segment) { return Segment(segment.GetMwmId(), segment.GetFeatureId(), segment.GetSegmentIdx(), !segment.IsForward()); } } // namespace namespace routing { // static void IndexGraphStarter::CheckValidRoute(vector<Segment> const & segments) { // Valid route contains at least 3 segments: // start fake, finish fake and at least one normal nearest segment. CHECK_GREATER_OR_EQUAL(segments.size(), 3, ()); CHECK(IsFakeSegment(segments.front()), ()); CHECK(IsFakeSegment(segments.back()), ()); } // static size_t IndexGraphStarter::GetRouteNumPoints(vector<Segment> const & segments) { CheckValidRoute(segments); return segments.size() + 1; } IndexGraphStarter::IndexGraphStarter(FakeEnding const & startEnding, FakeEnding const & finishEnding, uint32_t fakeNumerationStart, bool strictForward, WorldGraph & graph) : m_graph(graph) , m_startId(fakeNumerationStart) , m_startPassThroughAllowed(EndingPassThroughAllowed(startEnding)) , m_finishPassThroughAllowed(EndingPassThroughAllowed(finishEnding)) { AddStart(startEnding, finishEnding, strictForward, fakeNumerationStart); m_finishId = fakeNumerationStart; AddFinish(finishEnding, startEnding, fakeNumerationStart); auto const startPoint = GetPoint(GetStartSegment(), false /* front */); auto const finishPoint = GetPoint(GetFinishSegment(), true /* front */); m_startToFinishDistanceM = MercatorBounds::DistanceOnEarth(startPoint, finishPoint); } void IndexGraphStarter::Append(FakeEdgesContainer const & container) { m_finishId = container.m_finishId; m_finishPassThroughAllowed = container.m_finishPassThroughAllowed; m_fake.Append(container.m_fake); // It's important to calculate distance after m_fake.Append() because // we don't have finish segment in fake graph before m_fake.Append(). auto const startPoint = GetPoint(GetStartSegment(), false /* front */); auto const finishPoint = GetPoint(GetFinishSegment(), true /* front */); m_startToFinishDistanceM = MercatorBounds::DistanceOnEarth(startPoint, finishPoint); } Junction const & IndexGraphStarter::GetStartJunction() const { auto const & startSegment = GetStartSegment(); return m_fake.GetVertex(startSegment).GetJunctionFrom(); } Junction const & IndexGraphStarter::GetFinishJunction() const { auto const & finishSegment = GetFinishSegment(); return m_fake.GetVertex(finishSegment).GetJunctionTo(); } bool IndexGraphStarter::ConvertToReal(Segment & segment) const { if (!IsFakeSegment(segment)) return true; return m_fake.FindReal(Segment(segment), segment); } Junction const & IndexGraphStarter::GetJunction(Segment const & segment, bool front) const { if (!IsFakeSegment(segment)) return m_graph.GetJunction(segment, front); auto const & vertex = m_fake.GetVertex(segment); return front ? vertex.GetJunctionTo() : vertex.GetJunctionFrom(); } Junction const & IndexGraphStarter::GetRouteJunction(vector<Segment> const & segments, size_t pointIndex) const { CHECK(!segments.empty(), ()); CHECK_LESS_OR_EQUAL( pointIndex, segments.size(), ("Point with index", pointIndex, "does not exist in route with size", segments.size())); if (pointIndex == segments.size()) return GetJunction(segments[pointIndex - 1], true /* front */); return GetJunction(segments[pointIndex], false); } m2::PointD const & IndexGraphStarter::GetPoint(Segment const & segment, bool front) const { return GetJunction(segment, front).GetPoint(); } set<NumMwmId> IndexGraphStarter::GetMwms() const { set<NumMwmId> mwms; for (auto const & kv : m_fake.GetFakeToReal()) mwms.insert(kv.second.GetMwmId()); return mwms; } bool IndexGraphStarter::CheckLength(RouteWeight const & weight) const { // We allow 1 pass-through/non-pass-through crossing per ending located in // non-pass-through zone to allow user to leave this zone. int const nonPassThroughCrossAllowed = (m_startPassThroughAllowed ? 0 : 1) + (m_finishPassThroughAllowed ? 0 : 1); return weight.GetNonPassThroughCross() <= nonPassThroughCrossAllowed && m_graph.CheckLength(weight, m_startToFinishDistanceM); } void IndexGraphStarter::GetEdgesList(Segment const & segment, bool isOutgoing, vector<SegmentEdge> & edges) const { edges.clear(); if (IsFakeSegment(segment)) { Segment real; if (m_fake.FindReal(segment, real)) { bool const haveSameFront = GetJunction(segment, true /* front */) == GetJunction(real, true); bool const haveSameBack = GetJunction(segment, false /* front */) == GetJunction(real, false); if ((isOutgoing && haveSameFront) || (!isOutgoing && haveSameBack)) AddRealEdges(real, isOutgoing, edges); } for (auto const & s : m_fake.GetEdges(segment, isOutgoing)) edges.emplace_back(s, CalcSegmentWeight(isOutgoing ? s : segment)); } else { AddRealEdges(segment, isOutgoing, edges); } AddFakeEdges(segment, edges); } RouteWeight IndexGraphStarter::CalcSegmentWeight(Segment const & segment) const { if (!IsFakeSegment(segment)) { return m_graph.CalcSegmentWeight(segment); } auto const & vertex = m_fake.GetVertex(segment); Segment real; if (m_fake.FindReal(segment, real)) { auto const partLen = MercatorBounds::DistanceOnEarth(vertex.GetPointFrom(), vertex.GetPointTo()); auto const fullLen = MercatorBounds::DistanceOnEarth(GetPoint(real, false /* front */), GetPoint(real, true /* front */)); CHECK_GREATER(fullLen, 0.0, ()); return partLen / fullLen * m_graph.CalcSegmentWeight(real); } return m_graph.CalcOffroadWeight(vertex.GetPointFrom(), vertex.GetPointTo()); } RouteWeight IndexGraphStarter::CalcRouteSegmentWeight(vector<Segment> const & route, size_t segmentIndex) const { CHECK_LESS( segmentIndex, route.size(), ("Segment with index", segmentIndex, "does not exist in route with size", route.size())); return CalcSegmentWeight(route[segmentIndex]); } bool IndexGraphStarter::IsLeap(NumMwmId mwmId) const { if (mwmId == kFakeNumMwmId) return false; for (auto const & kv : m_fake.GetFakeToReal()) { if (kv.second.GetMwmId() == mwmId) return false; } return m_graph.LeapIsAllowed(mwmId); } void IndexGraphStarter::AddEnding(FakeEnding const & thisEnding, FakeEnding const & otherEnding, bool isStart, bool strictForward, uint32_t & fakeNumerationStart) { Segment const dummy = Segment(); map<Segment, Junction> otherSegments; for (auto const & p : otherEnding.m_projections) { otherSegments[p.m_segment] = p.m_junction; // We use |otherEnding| to generate proper fake edges in case both endings have projections // to the same segment. Direction of p.m_segment does not matter. otherSegments[GetReverseSegment(p.m_segment)] = p.m_junction; } // Add pure fake vertex auto const fakeSegment = GetFakeSegmentAndIncr(fakeNumerationStart); FakeVertex fakeVertex(thisEnding.m_originJunction, thisEnding.m_originJunction, FakeVertex::Type::PureFake); m_fake.AddStandaloneVertex(fakeSegment, fakeVertex); for (auto const & projection : thisEnding.m_projections) { // Add projection edges auto const projectionSegment = GetFakeSegmentAndIncr(fakeNumerationStart); FakeVertex projectionVertex(isStart ? thisEnding.m_originJunction : projection.m_junction, isStart ? projection.m_junction : thisEnding.m_originJunction, FakeVertex::Type::PureFake); m_fake.AddVertex(fakeSegment, projectionSegment, projectionVertex, isStart /* isOutgoing */, false /* isPartOfReal */, dummy /* realSegment */); // Add fake parts of real auto frontJunction = projection.m_segmentFront; auto backJunction = projection.m_segmentBack; // Check whether we have projections to same real segment from both endings. auto const it = otherSegments.find(projection.m_segment); if (it != otherSegments.end()) { auto const & otherJunction = it->second; auto const distBackToThis = MercatorBounds::DistanceOnEarth(backJunction.GetPoint(), projection.m_junction.GetPoint()); auto const distBackToOther = MercatorBounds::DistanceOnEarth(backJunction.GetPoint(), otherJunction.GetPoint()); if (distBackToThis < distBackToOther) frontJunction = otherJunction; else backJunction = otherJunction; } FakeVertex forwardPartOfReal(isStart ? projection.m_junction : backJunction, isStart ? frontJunction : projection.m_junction, FakeVertex::Type::PartOfReal); Segment fakeForwardSegment; if (!m_fake.FindSegment(forwardPartOfReal, fakeForwardSegment)) fakeForwardSegment = GetFakeSegmentAndIncr(fakeNumerationStart); m_fake.AddVertex(projectionSegment, fakeForwardSegment, forwardPartOfReal, isStart /* isOutgoing */, true /* isPartOfReal */, projection.m_segment); if (!strictForward && !projection.m_isOneWay) { auto const backwardSegment = GetReverseSegment(projection.m_segment); FakeVertex backwardPartOfReal(isStart ? projection.m_junction : frontJunction, isStart ? backJunction : projection.m_junction, FakeVertex::Type::PartOfReal); Segment fakeBackwardSegment; if (!m_fake.FindSegment(backwardPartOfReal, fakeBackwardSegment)) fakeBackwardSegment = GetFakeSegmentAndIncr(fakeNumerationStart); m_fake.AddVertex(projectionSegment, fakeBackwardSegment, backwardPartOfReal, isStart /* isOutgoing */, true /* isPartOfReal */, backwardSegment); } } } void IndexGraphStarter::AddStart(FakeEnding const & startEnding, FakeEnding const & finishEnding, bool strictForward, uint32_t & fakeNumerationStart) { AddEnding(startEnding, finishEnding, true /* isStart */, strictForward, fakeNumerationStart); } void IndexGraphStarter::AddFinish(FakeEnding const & finishEnding, FakeEnding const & startEnding, uint32_t & fakeNumerationStart) { AddEnding(finishEnding, startEnding, false /* isStart */, false /* strictForward */, fakeNumerationStart); } void IndexGraphStarter::AddFakeEdges(Segment const & segment, vector<SegmentEdge> & edges) const { vector<SegmentEdge> fakeEdges; for (auto const & edge : edges) { for (auto const & s : m_fake.GetFake(edge.GetTarget())) { // Check fake segment is connected to source segment. if (GetJunction(s, false /* front */) == GetJunction(segment, true) || GetJunction(s, true) == GetJunction(segment, false)) { fakeEdges.emplace_back(s, edge.GetWeight()); } } } edges.insert(edges.end(), fakeEdges.begin(), fakeEdges.end()); } void IndexGraphStarter::AddRealEdges(Segment const & segment, bool isOutgoing, std::vector<SegmentEdge> & edges) const { bool const isEnding = !m_fake.GetFake(segment).empty(); m_graph.GetEdgeList(segment, isOutgoing, IsLeap(segment.GetMwmId()), isEnding, edges); } bool IndexGraphStarter::EndingPassThroughAllowed(FakeEnding const & ending) { return any_of(ending.m_projections.cbegin(), ending.m_projections.cend(), [this](Projection const & projection) { return m_graph.IsPassThroughAllowed(projection.m_segment.GetMwmId(), projection.m_segment.GetFeatureId()); }); } } // namespace routing <|endoftext|>
<commit_before>#include "SimplifySpecializations.h" #include "IROperator.h" #include "IRMutator.h" #include "Simplify.h" #include "Substitute.h" #include "Definition.h" #include "IREquality.h" #include <set> namespace Halide{ namespace Internal { using std::map; using std::set; using std::string; using std::vector; namespace { void substitute_value_in_var(const string &var, Expr value, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(substitute(var, value, def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(substitute(var, value, def_val)); } } } class SimplifyUsingFact : public IRMutator { public: using IRMutator::mutate; Expr mutate(Expr e) { if (e.type().is_bool()) { if (equal(fact, e) || can_prove(!fact || e)) { // fact implies e return const_true(); } if (equal(fact, !e) || equal(!fact, e) || can_prove(!fact || !e)) { // fact implies !e return const_false(); } } return IRMutator::mutate(e); } Expr fact; SimplifyUsingFact(Expr f) : fact(f) {} }; void simplify_using_fact(Expr fact, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(SimplifyUsingFact(fact).mutate(def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(SimplifyUsingFact(fact).mutate(def_val)); } } } vector<Definition> propagate_specialization_in_definition(Definition &def, const string &name) { vector<Definition> result; result.push_back(def); vector<Specialization> &specializations = def.specializations(); // Prune specializations based on constants: // -- Any Specializations that have const-false as a condition // can never trigger; go ahead and prune them now to save time & energy // during later phases. // -- Once we encounter a Specialization that is const-true, no subsequent // Specializations can ever trigger (since we evaluate them in order), // so erase them. bool seen_const_true = false; for (auto it = specializations.begin(); it != specializations.end(); /*no-increment*/) { Expr old_c = it->condition; Expr c = simplify(it->condition); // Go ahead and save the simplified condition now it->condition = c; if (is_zero(c) || seen_const_true) { debug(1) << "Erasing unreachable specialization (" << old_c << ") -> (" << c << ") for function \"" << name << "\"\n"; it = specializations.erase(it); } else { it++; } seen_const_true |= is_one(c); } for (size_t i = specializations.size(); i > 0; i--) { Expr c = specializations[i-1].condition; Definition &s_def = specializations[i-1].definition; const EQ *eq = c.as<EQ>(); const Variable *var = eq ? eq->a.as<Variable>() : c.as<Variable>(); vector<Definition> s_result = propagate_specialization_in_definition(s_def, name); if (var && eq) { // Then case substitute_value_in_var(var->name, eq->b, s_result); // Else case if (eq->b.type().is_bool()) { substitute_value_in_var(var->name, !eq->b, result); } } else if (var) { // Then case substitute_value_in_var(var->name, const_true(), s_result); // Else case substitute_value_in_var(var->name, const_false(), result); } else { simplify_using_fact(c, s_result); simplify_using_fact(!c, result); } result.insert(result.end(), s_result.begin(), s_result.end()); } return result; } } void simplify_specializations(map<string, Function> &env) { for (auto &iter : env) { Function &func = iter.second; propagate_specialization_in_definition(func.definition(), func.name()); } } namespace { uint16_t vector_store_lanes = 0; int my_trace(void *user_context, const halide_trace_event_t *ev) { if (ev->event == halide_trace_store) { if (ev->type.lanes > 1) { vector_store_lanes = ev->type.lanes; } else { vector_store_lanes = 0; } } return 0; } } // namespace void simplify_specializations_test() { std::cout << "SimplifySpecializations test passed" << std::endl; } } } <commit_msg>remove dangly code bits<commit_after>#include "SimplifySpecializations.h" #include "IROperator.h" #include "IRMutator.h" #include "Simplify.h" #include "Substitute.h" #include "Definition.h" #include "IREquality.h" #include <set> namespace Halide{ namespace Internal { using std::map; using std::set; using std::string; using std::vector; namespace { void substitute_value_in_var(const string &var, Expr value, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(substitute(var, value, def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(substitute(var, value, def_val)); } } } class SimplifyUsingFact : public IRMutator { public: using IRMutator::mutate; Expr mutate(Expr e) { if (e.type().is_bool()) { if (equal(fact, e) || can_prove(!fact || e)) { // fact implies e return const_true(); } if (equal(fact, !e) || equal(!fact, e) || can_prove(!fact || !e)) { // fact implies !e return const_false(); } } return IRMutator::mutate(e); } Expr fact; SimplifyUsingFact(Expr f) : fact(f) {} }; void simplify_using_fact(Expr fact, vector<Definition> &definitions) { for (Definition &def : definitions) { for (auto &def_arg : def.args()) { def_arg = simplify(SimplifyUsingFact(fact).mutate(def_arg)); } for (auto &def_val : def.values()) { def_val = simplify(SimplifyUsingFact(fact).mutate(def_val)); } } } vector<Definition> propagate_specialization_in_definition(Definition &def, const string &name) { vector<Definition> result; result.push_back(def); vector<Specialization> &specializations = def.specializations(); // Prune specializations based on constants: // -- Any Specializations that have const-false as a condition // can never trigger; go ahead and prune them now to save time & energy // during later phases. // -- Once we encounter a Specialization that is const-true, no subsequent // Specializations can ever trigger (since we evaluate them in order), // so erase them. bool seen_const_true = false; for (auto it = specializations.begin(); it != specializations.end(); /*no-increment*/) { Expr old_c = it->condition; Expr c = simplify(it->condition); // Go ahead and save the simplified condition now it->condition = c; if (is_zero(c) || seen_const_true) { debug(1) << "Erasing unreachable specialization (" << old_c << ") -> (" << c << ") for function \"" << name << "\"\n"; it = specializations.erase(it); } else { it++; } seen_const_true |= is_one(c); } for (size_t i = specializations.size(); i > 0; i--) { Expr c = specializations[i-1].condition; Definition &s_def = specializations[i-1].definition; const EQ *eq = c.as<EQ>(); const Variable *var = eq ? eq->a.as<Variable>() : c.as<Variable>(); vector<Definition> s_result = propagate_specialization_in_definition(s_def, name); if (var && eq) { // Then case substitute_value_in_var(var->name, eq->b, s_result); // Else case if (eq->b.type().is_bool()) { substitute_value_in_var(var->name, !eq->b, result); } } else if (var) { // Then case substitute_value_in_var(var->name, const_true(), s_result); // Else case substitute_value_in_var(var->name, const_false(), result); } else { simplify_using_fact(c, s_result); simplify_using_fact(!c, result); } result.insert(result.end(), s_result.begin(), s_result.end()); } return result; } } void simplify_specializations(map<string, Function> &env) { for (auto &iter : env) { Function &func = iter.second; propagate_specialization_in_definition(func.definition(), func.name()); } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2017, Vlad Meșco All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. 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 HOLDER 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 "window.h" #include "matrix_editor.h" #include <FL/fl_ask.H> #include <FL/Fl_Box.H> #include <FL/Fl_Button.H> #include <FL/fl_draw.H> #include <FL/Fl_Input.H> #include <FL/Fl_Menu_Item.H> #include <FL/Fl_Scroll.H> #include <FL/Fl_Tile.H> #include <cassert> #include <algorithm> Vindow::Vindow(std::shared_ptr<Model> m, int w, int h, const char* t) : Fl_Double_Window(w, h, t) , View() , model_(m) , menu_(nullptr) , mainGroup_(nullptr) { assert(model_); model_->views.push_back(this); // init menu Fl_Menu_Item menuitems[] = { { "&File", 0, 0, 0, FL_SUBMENU }, { "&New...", 0, (Fl_Callback*)FileNew }, { "&Open...", FL_COMMAND + 'o', (Fl_Callback*)FileOpen }, { "&Save", FL_COMMAND + 's', (Fl_Callback*)FileSave }, { "Save &As...", FL_COMMAND + FL_SHIFT + 's', (Fl_Callback*)FileSaveAs, }, { "&Reload", FL_F + 5, (Fl_Callback*)FileReload, 0, FL_MENU_DIVIDER }, { "E&xit", FL_COMMAND + 'x', (Fl_Callback*)FileExit, 0 }, { 0 }, { "&Edit", 0, 0, 0, FL_SUBMENU }, { "&Undo", FL_COMMAND + 'z', (Fl_Callback*)EditUndo, 0, FL_MENU_DIVIDER }, { "Cu&t", FL_COMMAND + 'x', (Fl_Callback*)EditCut }, { "&Copy", FL_COMMAND + 'c', (Fl_Callback*)EditCopy }, { "&Paste", FL_COMMAND + 'v', (Fl_Callback*)EditPaste, 0, FL_MENU_DIVIDER }, { "Over&write", FL_Insert, (Fl_Callback*)EditOverwrite, 0, FL_MENU_TOGGLE }, { "Insert &Rest", 0, (Fl_Callback*)EditInsertRest }, { "Insert &Blank", 0, (Fl_Callback*)EditInsertBlank }, { "C&lear Columns", FL_COMMAND + 'b', (Fl_Callback*)EditClearColumns }, { "&Delete Columns", FL_Delete, (Fl_Callback*)EditDeleteColumns, 0, FL_MENU_DIVIDER }, { "Add WH&AT Section", 0, (Fl_Callback*)EditAddWhat }, { "Add WH&O Section", 0, (Fl_Callback*)EditAddWho }, { "Delete &Section", 0, (Fl_Callback*)EditDeleteSection }, { 0 }, { "&Window", 0, 0, 0, FL_SUBMENU }, { "&New Window", FL_COMMAND + 'n', (Fl_Callback*)WindowNew, this }, { "&Close", FL_COMMAND + 'w', (Fl_Callback*)WindowClose, this }, { "Close &All", 0, (Fl_Callback*)WindowCloseAll, this }, { 0 }, { "&Help", 0, 0, 0, FL_SUBMENU }, { "A&bout", FL_F + 1, (Fl_Callback*)HelpAbout, this }, { 0 }, { 0 } }; auto* mb = new Fl_Menu_Bar(0, 0, w, 30); mb->copy(menuitems); // callback callback(WindowCallback, this); // init common components container_ = new Fl_Tile(0, mb->h(), w, h - mb->h()); // create something strange from FLTK test code... constexpr int dx = 150; auto* limit = new Fl_Box(container_->x() + dx, container_->y() + dx, container_->w() - 2*dx, container_->h() - 2*dx); container_->resizable(limit); CreateWhoList(); CreateWhatList(); SetLayout(Layout::OUTPUT); container_->end(); // init self border(true); resizable(container_); end(); } void Vindow::CreateWhoList() { whoGroup_ = new Fl_Group(container_->x(), container_->y(), container_->w() / 4, container_->h() / 2); container_->add(whoGroup_); whoGroup_->box(FL_DOWN_BOX); fl_font(FL_HELVETICA, 14); auto* whoLabel = new Fl_Box(5, whoGroup_->y() + 5, fl_width("WHO"), fl_height()); fl_font(whoLabel->labelfont(), whoLabel->labelsize()); whoLabel->size(fl_width("WHO"), fl_height()); whoLabel->label("WHO"); whoLabel->align(FL_ALIGN_INSIDE|FL_ALIGN_LEFT); whoGroup_->add(whoLabel); auto* scroll = new Fl_Scroll(5, whoLabel->y() + whoLabel->h(), whoGroup_->w() - 10, whoGroup_->h() - whoLabel->h() - 10); scroll->box(FL_DOWN_BOX); whoGroup_->add(scroll); int i = 0; for(auto&& who : model_->whos) { int w = fl_width(who.name.c_str()) + 0.5 + 2*Fl::box_dw(FL_UP_BOX); auto* b = new Fl_Button( scroll->x() + Fl::box_dx(scroll->box()), scroll->y() + Fl::box_dy(scroll->box()) + 20*i, w, 20); b->down_box(FL_FLAT_BOX); b->label(who.name.c_str()); b->callback(WhoClicked, this); ++i; } scroll->end(); whoGroup_->resizable(scroll); whoGroup_->end(); } void Vindow::CreateWhatList() { whatGroup_ = new Fl_Group(container_->x(), whoGroup_->y() + whoGroup_->h(), container_->w() / 4, container_->h() / 2); container_->add(whatGroup_); whatGroup_->box(FL_DOWN_BOX); fl_font(FL_HELVETICA, 14); auto* whatLabel = new Fl_Box(5, whatGroup_->y() + 5, fl_width("WHAT"), fl_height()); fl_font(whatLabel->labelfont(), whatLabel->labelsize()); whatLabel->size(fl_width("WHAT"), fl_height()); whatLabel->label("WHAT"); whatLabel->align(FL_ALIGN_INSIDE|FL_ALIGN_LEFT); whatGroup_->add(whatLabel); auto* scroll = new Fl_Scroll(5, whatLabel->y() + whatLabel->h(), whatGroup_->w() - 10, whatGroup_->h() - whatLabel->h() - 10); scroll->box(FL_DOWN_BOX); whatGroup_->add(scroll); auto* b = new Fl_Button( scroll->x() + Fl::box_dx(scroll->box()), scroll->y() + Fl::box_dy(scroll->box()), (int)(fl_width("OUTPUT") + 0.5) + Fl::box_dw(FL_UP_BOX), 20, "OUTPUT"); b->down_box(FL_FLAT_BOX); b->callback(OutputClicked, this); int i = 1; for(auto&& what : model_->whats) { int w = fl_width(what.name.c_str()) + 0.5 + 2*Fl::box_dw(FL_UP_BOX); auto* b = new Fl_Button( scroll->x() + Fl::box_dx(scroll->box()), scroll->y() + Fl::box_dy(scroll->box()) + 20*i, w, 20); b->down_box(FL_FLAT_BOX); b->label(what.name.c_str()); b->callback(WhatClicked, this); ++i; } scroll->end(); whatGroup_->resizable(scroll); whatGroup_->end(); } Vindow::~Vindow() { auto found = std::find_if(model_->views.begin(), model_->views.end(), [this](View* v) -> bool { auto* w = dynamic_cast<Vindow*>(v); return w == this; }); if(found == model_->views.end()) { fprintf(stderr, "disconnected window destroyed!\n"); return; } model_->views.erase(found); } // TODO will be useful for param changes, sequence changes etc // More relvant changes that impact the who/what lists still // need to update those #define IGNORE_OWN do{\ Vindow* w = dynamic_cast<Vindow*>(e->sourceView); \ if(w == this) return; \ }while(0) void Vindow::OnEvent(Event* e) { switch(e->type) { case Event::RELOADED: Fl::delete_widget(whoGroup_); Fl::delete_widget(whatGroup_); CreateWhoList(); CreateWhatList(); break; case Event::DELETED: switch(e->source) { case Event::WHO: Fl::delete_widget(whoGroup_); CreateWhoList(); break; case Event::WHAT: Fl::delete_widget(whoGroup_); CreateWhoList(); break; } break; case Event::NAME_CHANGED: switch(e->source) { case Event::WHO: Fl::delete_widget(whoGroup_); CreateWhoList(); break; case Event::WHAT: Fl::delete_widget(whoGroup_); CreateWhoList(); break; } break; } } void Vindow::SetLayout(Layout lyt, const char* name) { SelectButton(name); layout_ = lyt; if(mainGroup_) Fl::delete_widget(mainGroup_); mainGroup_ = nullptr; mainGroup_ = new Fl_Group(whoGroup_->w(), container_->y(), container_->w() - whoGroup_->w(), container_->h()); mainGroup_->box(FL_DOWN_BOX); container_->add(mainGroup_); // set new layout switch(lyt) { case Layout::OUTPUT: { fl_font(FL_HELVETICA, 14); auto* label = new Fl_Box( mainGroup_->x() + 5, mainGroup_->y() + 5, fl_width("Editing OUTPUT"), fl_height(), "Editing OUTPUT"); fl_font(label->labelfont(), label->labelsize()); label->size(fl_width("Editing OUTPUT"), fl_height()); label->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE); mainGroup_->add(label); auto* editor = new MatrixEditor( label->x(), label->y() + label->h(), mainGroup_->w() - 10, mainGroup_->h() - label->h() - 10, model_->output.columns.begin(), model_->output.columns.end()); mainGroup_->add(editor); mainGroup_->resizable(editor); } break; case Layout::WHO: { } break; case Layout::WHAT: { const int THIRD = (mainGroup_->w()) / 3 + 5, TWOTHIRD = mainGroup_->w() - THIRD - 5; auto* whatlbl = new Fl_Input( mainGroup_->x() + THIRD, mainGroup_->y() + 5, TWOTHIRD, 25, "WHAT"); whatlbl->value(name); mainGroup_->add(whatlbl); auto* bpmlbl = new Fl_Input( mainGroup_->x() + THIRD, whatlbl->y() + whatlbl->h() + 5, TWOTHIRD, 25, "bpm"); mainGroup_->add(bpmlbl); auto* editor = new MatrixEditor( mainGroup_->x() + 5, bpmlbl->y() + bpmlbl->h() + 5, mainGroup_->w() - 10, mainGroup_->h() - whatlbl->h() - 5 - bpmlbl->h() - 5 - 10, model_->output.columns.begin(), model_->output.columns.end()); mainGroup_->add(editor); mainGroup_->resizable(editor); } break; } mainGroup_->end(); } void Vindow::SelectButton(const char* reactivate1) { auto* whoGroup = dynamic_cast<Fl_Group*>(whoGroup_->child(1)), * whatGroup = dynamic_cast<Fl_Group*>(whatGroup_->child(1)); const char* reactivate = (reactivate1 && *reactivate1) ? reactivate1 : "OUTPUT" ; assert(whoGroup); assert(whatGroup); for(size_t i = 0; i < whoGroup->children(); ++i) { auto* b = dynamic_cast<Fl_Button*>(whoGroup->child(i)); if(b) { b->value(0); if(strcmp(b->label(), reactivate) == 0) b->value(1); } } for(size_t i = 0; i < whatGroup->children(); ++i) { auto* b = dynamic_cast<Fl_Button*>(whatGroup->child(i)); if(b) { b->value(0); if(strcmp(b->label(), reactivate) == 0) b->value(1); } } } <commit_msg>make magic value constant<commit_after>/* Copyright (c) 2017, Vlad Meșco All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. 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 HOLDER 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 "window.h" #include "matrix_editor.h" #include <FL/fl_ask.H> #include <FL/Fl_Box.H> #include <FL/Fl_Button.H> #include <FL/fl_draw.H> #include <FL/Fl_Input.H> #include <FL/Fl_Menu_Item.H> #include <FL/Fl_Scroll.H> #include <FL/Fl_Tile.H> #include <cassert> #include <algorithm> #define WHO_GROUP_BUTTON_START 1u #define WHAT_GROUP_BUTTON_START 1u Vindow::Vindow(std::shared_ptr<Model> m, int w, int h, const char* t) : Fl_Double_Window(w, h, t) , View() , model_(m) , menu_(nullptr) , mainGroup_(nullptr) { assert(model_); model_->views.push_back(this); // init menu Fl_Menu_Item menuitems[] = { { "&File", 0, 0, 0, FL_SUBMENU }, { "&New...", 0, (Fl_Callback*)FileNew }, { "&Open...", FL_COMMAND + 'o', (Fl_Callback*)FileOpen }, { "&Save", FL_COMMAND + 's', (Fl_Callback*)FileSave }, { "Save &As...", FL_COMMAND + FL_SHIFT + 's', (Fl_Callback*)FileSaveAs, }, { "&Reload", FL_F + 5, (Fl_Callback*)FileReload, 0, FL_MENU_DIVIDER }, { "E&xit", FL_COMMAND + 'x', (Fl_Callback*)FileExit, 0 }, { 0 }, { "&Edit", 0, 0, 0, FL_SUBMENU }, { "&Undo", FL_COMMAND + 'z', (Fl_Callback*)EditUndo, 0, FL_MENU_DIVIDER }, { "Cu&t", FL_COMMAND + 'x', (Fl_Callback*)EditCut }, { "&Copy", FL_COMMAND + 'c', (Fl_Callback*)EditCopy }, { "&Paste", FL_COMMAND + 'v', (Fl_Callback*)EditPaste, 0, FL_MENU_DIVIDER }, { "Over&write", FL_Insert, (Fl_Callback*)EditOverwrite, 0, FL_MENU_TOGGLE }, { "Insert &Rest", 0, (Fl_Callback*)EditInsertRest }, { "Insert &Blank", 0, (Fl_Callback*)EditInsertBlank }, { "C&lear Columns", FL_COMMAND + 'b', (Fl_Callback*)EditClearColumns }, { "&Delete Columns", FL_Delete, (Fl_Callback*)EditDeleteColumns, 0, FL_MENU_DIVIDER }, { "Add WH&AT Section", 0, (Fl_Callback*)EditAddWhat }, { "Add WH&O Section", 0, (Fl_Callback*)EditAddWho }, { "Delete &Section", 0, (Fl_Callback*)EditDeleteSection }, { 0 }, { "&Window", 0, 0, 0, FL_SUBMENU }, { "&New Window", FL_COMMAND + 'n', (Fl_Callback*)WindowNew, this }, { "&Close", FL_COMMAND + 'w', (Fl_Callback*)WindowClose, this }, { "Close &All", 0, (Fl_Callback*)WindowCloseAll, this }, { 0 }, { "&Help", 0, 0, 0, FL_SUBMENU }, { "A&bout", FL_F + 1, (Fl_Callback*)HelpAbout, this }, { 0 }, { 0 } }; auto* mb = new Fl_Menu_Bar(0, 0, w, 30); mb->copy(menuitems); // callback callback(WindowCallback, this); // init common components container_ = new Fl_Tile(0, mb->h(), w, h - mb->h()); // create something strange from FLTK test code... constexpr int dx = 150; auto* limit = new Fl_Box(container_->x() + dx, container_->y() + dx, container_->w() - 2*dx, container_->h() - 2*dx); container_->resizable(limit); CreateWhoList(); CreateWhatList(); SetLayout(Layout::OUTPUT); container_->end(); // init self border(true); resizable(container_); end(); } void Vindow::CreateWhoList() { whoGroup_ = new Fl_Group(container_->x(), container_->y(), container_->w() / 4, container_->h() / 2); container_->add(whoGroup_); whoGroup_->box(FL_DOWN_BOX); fl_font(FL_HELVETICA, 14); auto* whoLabel = new Fl_Box(5, whoGroup_->y() + 5, fl_width("WHO"), fl_height()); fl_font(whoLabel->labelfont(), whoLabel->labelsize()); whoLabel->size(fl_width("WHO"), fl_height()); whoLabel->label("WHO"); whoLabel->align(FL_ALIGN_INSIDE|FL_ALIGN_LEFT); whoGroup_->add(whoLabel); auto* scroll = new Fl_Scroll(5, whoLabel->y() + whoLabel->h(), whoGroup_->w() - 10, whoGroup_->h() - whoLabel->h() - 10); scroll->box(FL_DOWN_BOX); whoGroup_->add(scroll); int i = 0; for(auto&& who : model_->whos) { int w = fl_width(who.name.c_str()) + 0.5 + 2*Fl::box_dw(FL_UP_BOX); auto* b = new Fl_Button( scroll->x() + Fl::box_dx(scroll->box()), scroll->y() + Fl::box_dy(scroll->box()) + 20*i, w, 20); b->down_box(FL_FLAT_BOX); b->label(who.name.c_str()); b->callback(WhoClicked, this); ++i; } scroll->end(); whoGroup_->resizable(scroll); whoGroup_->end(); } void Vindow::CreateWhatList() { whatGroup_ = new Fl_Group(container_->x(), whoGroup_->y() + whoGroup_->h(), container_->w() / 4, container_->h() / 2); container_->add(whatGroup_); whatGroup_->box(FL_DOWN_BOX); fl_font(FL_HELVETICA, 14); auto* whatLabel = new Fl_Box(5, whatGroup_->y() + 5, fl_width("WHAT"), fl_height()); fl_font(whatLabel->labelfont(), whatLabel->labelsize()); whatLabel->size(fl_width("WHAT"), fl_height()); whatLabel->label("WHAT"); whatLabel->align(FL_ALIGN_INSIDE|FL_ALIGN_LEFT); whatGroup_->add(whatLabel); auto* scroll = new Fl_Scroll(5, whatLabel->y() + whatLabel->h(), whatGroup_->w() - 10, whatGroup_->h() - whatLabel->h() - 10); scroll->box(FL_DOWN_BOX); whatGroup_->add(scroll); auto* b = new Fl_Button( scroll->x() + Fl::box_dx(scroll->box()), scroll->y() + Fl::box_dy(scroll->box()), (int)(fl_width("OUTPUT") + 0.5) + Fl::box_dw(FL_UP_BOX), 20, "OUTPUT"); b->down_box(FL_FLAT_BOX); b->callback(OutputClicked, this); int i = 1; for(auto&& what : model_->whats) { int w = fl_width(what.name.c_str()) + 0.5 + 2*Fl::box_dw(FL_UP_BOX); auto* b = new Fl_Button( scroll->x() + Fl::box_dx(scroll->box()), scroll->y() + Fl::box_dy(scroll->box()) + 20*i, w, 20); b->down_box(FL_FLAT_BOX); b->label(what.name.c_str()); b->callback(WhatClicked, this); ++i; } scroll->end(); whatGroup_->resizable(scroll); whatGroup_->end(); } Vindow::~Vindow() { auto found = std::find_if(model_->views.begin(), model_->views.end(), [this](View* v) -> bool { auto* w = dynamic_cast<Vindow*>(v); return w == this; }); if(found == model_->views.end()) { fprintf(stderr, "disconnected window destroyed!\n"); return; } model_->views.erase(found); } // TODO will be useful for param changes, sequence changes etc // More relvant changes that impact the who/what lists still // need to update those #define IGNORE_OWN do{\ Vindow* w = dynamic_cast<Vindow*>(e->sourceView); \ if(w == this) return; \ }while(0) void Vindow::OnEvent(Event* e) { switch(e->type) { case Event::RELOADED: Fl::delete_widget(whoGroup_); Fl::delete_widget(whatGroup_); CreateWhoList(); CreateWhatList(); break; case Event::DELETED: switch(e->source) { case Event::WHO: Fl::delete_widget(whoGroup_); CreateWhoList(); break; case Event::WHAT: Fl::delete_widget(whoGroup_); CreateWhoList(); break; } break; case Event::NAME_CHANGED: switch(e->source) { case Event::WHO: Fl::delete_widget(whoGroup_); CreateWhoList(); break; case Event::WHAT: Fl::delete_widget(whoGroup_); CreateWhoList(); break; } break; } } void Vindow::SetLayout(Layout lyt, const char* name) { SelectButton(name); layout_ = lyt; if(mainGroup_) Fl::delete_widget(mainGroup_); mainGroup_ = nullptr; mainGroup_ = new Fl_Group(whoGroup_->w(), container_->y(), container_->w() - whoGroup_->w(), container_->h()); mainGroup_->box(FL_DOWN_BOX); container_->add(mainGroup_); // set new layout switch(lyt) { case Layout::OUTPUT: { fl_font(FL_HELVETICA, 14); auto* label = new Fl_Box( mainGroup_->x() + 5, mainGroup_->y() + 5, fl_width("Editing OUTPUT"), fl_height(), "Editing OUTPUT"); fl_font(label->labelfont(), label->labelsize()); label->size(fl_width("Editing OUTPUT"), fl_height()); label->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE); mainGroup_->add(label); auto* editor = new MatrixEditor( label->x(), label->y() + label->h(), mainGroup_->w() - 10, mainGroup_->h() - label->h() - 10, model_->output.columns.begin(), model_->output.columns.end()); mainGroup_->add(editor); mainGroup_->resizable(editor); } break; case Layout::WHO: { } break; case Layout::WHAT: { const int THIRD = (mainGroup_->w()) / 3 + 5, TWOTHIRD = mainGroup_->w() - THIRD - 5; auto* whatlbl = new Fl_Input( mainGroup_->x() + THIRD, mainGroup_->y() + 5, TWOTHIRD, 25, "WHAT"); whatlbl->value(name); mainGroup_->add(whatlbl); auto* bpmlbl = new Fl_Input( mainGroup_->x() + THIRD, whatlbl->y() + whatlbl->h() + 5, TWOTHIRD, 25, "bpm"); mainGroup_->add(bpmlbl); auto* editor = new MatrixEditor( mainGroup_->x() + 5, bpmlbl->y() + bpmlbl->h() + 5, mainGroup_->w() - 10, mainGroup_->h() - whatlbl->h() - 5 - bpmlbl->h() - 5 - 10, model_->output.columns.begin(), model_->output.columns.end()); mainGroup_->add(editor); mainGroup_->resizable(editor); } break; } mainGroup_->end(); } void Vindow::SelectButton(const char* reactivate1) { auto* whoGroup = dynamic_cast<Fl_Group*>(whoGroup_->child(WHO_GROUP_BUTTON_START)), * whatGroup = dynamic_cast<Fl_Group*>(whatGroup_->child(WHAT_GROUP_BUTTON_START)); const char* reactivate = (reactivate1 && *reactivate1) ? reactivate1 : "OUTPUT" ; assert(whoGroup); assert(whatGroup); for(size_t i = 0; i < whoGroup->children(); ++i) { auto* b = dynamic_cast<Fl_Button*>(whoGroup->child(i)); if(b) { b->value(0); if(strcmp(b->label(), reactivate) == 0) b->value(1); } } for(size_t i = 0; i < whatGroup->children(); ++i) { auto* b = dynamic_cast<Fl_Button*>(whatGroup->child(i)); if(b) { b->value(0); if(strcmp(b->label(), reactivate) == 0) b->value(1); } } } <|endoftext|>
<commit_before>#include "HardwareDetection.h" #include "ControllerDevice.h" using namespace LeapOsvr; //////////////////////////////////////////////////////////////////////////////////////////////////////// /*----------------------------------------------------------------------------------------------------*/ HardwareDetection::HardwareDetection() : mFound(false) { //do nothing... } /*----------------------------------------------------------------------------------------------------*/ OSVR_ReturnCode HardwareDetection::operator()(OSVR_PluginRegContext pContext) { if ( !mFound ) { mFound = true; osvr::pluginkit::registerObjectForDeletion(pContext, new ControllerDevice(pContext)); } return OSVR_RETURN_SUCCESS; } <commit_msg>Added an "isConnected" condition to the HardwareDetection function.<commit_after>#include "HardwareDetection.h" #include "ControllerDevice.h" using namespace LeapOsvr; //////////////////////////////////////////////////////////////////////////////////////////////////////// /*----------------------------------------------------------------------------------------------------*/ HardwareDetection::HardwareDetection() : mFound(false) { //do nothing... } /*----------------------------------------------------------------------------------------------------*/ OSVR_ReturnCode HardwareDetection::operator()(OSVR_PluginRegContext pContext) { Leap::Controller controller; if ( !controller.isConnected() ) { mFound = false; return OSVR_RETURN_FAILURE; } if ( !mFound ) { mFound = true; osvr::pluginkit::registerObjectForDeletion(pContext, new ControllerDevice(pContext)); } return OSVR_RETURN_SUCCESS; } <|endoftext|>
<commit_before>#include "parser.h" #include <cinttypes> #include <cstring> #include <curl/curl.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <vector> #include "config.h" #include "curlhandle.h" #include "exception.h" #include "logger.h" #include "remoteapi.h" #include "rssparser.h" #include "rssparserfactory.h" #include "rsspp_uris.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; static size_t my_write_data(void* buffer, size_t size, size_t nmemb, void* userp) { std::string* pbuf = static_cast<std::string*>(userp); pbuf->append(static_cast<const char*>(buffer), size * nmemb); return size * nmemb; } namespace rsspp { Parser::Parser(unsigned int timeout, const std::string& user_agent, const std::string& proxy, const std::string& proxy_auth, curl_proxytype proxy_type, const bool ssl_verify) : to(timeout) , ua(user_agent) , prx(proxy) , prxauth(proxy_auth) , prxtype(proxy_type) , verify_ssl(ssl_verify) , doc(0) , lm(0) { } Parser::~Parser() { if (doc) { xmlFreeDoc(doc); } } namespace { struct HeaderValues { time_t lastmodified; std::string etag; std::string charset; HeaderValues() : lastmodified(0) , charset("utf-8") { } }; } static size_t handle_headers(void* ptr, size_t size, size_t nmemb, void* data) { char* header = new char[size * nmemb + 1]; HeaderValues* values = static_cast<HeaderValues*>(data); memcpy(header, ptr, size * nmemb); header[size * nmemb] = '\0'; if (!strncasecmp("Last-Modified:", header, 14)) { time_t r = curl_getdate(header + 14, nullptr); if (r == -1) { LOG(Level::DEBUG, "handle_headers: last-modified %s " "(curl_getdate " "FAILED)", header + 14); } else { values->lastmodified = curl_getdate(header + 14, nullptr); LOG(Level::DEBUG, "handle_headers: got last-modified %s (%" PRId64 ")", header + 14, // On GCC, `time_t` is `long int`, which is at least 32 bits. // On x86_64, it's 64 bits. Thus, this cast is either a no-op, // or an up-cast which is always safe. static_cast<int64_t>(values->lastmodified)); } } else if (!strncasecmp("ETag:", header, 5)) { values->etag = std::string(header + 5); utils::trim(values->etag); LOG(Level::DEBUG, "handle_headers: got etag %s", values->etag); } else if (!strncasecmp("Content-Type:", header, 13)) { std::string header_str = std::string(header, size * nmemb); const std::string key = "charset="; const auto charset_index = header_str.find(key); if (charset_index != std::string::npos) { auto charset = header_str.substr(charset_index + key.size()); utils::trim(charset); if (charset.size() >= 2 && charset[0] == '"' && charset[charset.size() - 1] == '"') { charset = charset.substr(1, charset.size() - 2); } if (charset.size() > 0) { values->charset = charset; } } } delete[] header; return size * nmemb; } Feed Parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsboat::RemoteApi* api, const std::string& cookie_cache) { CurlHandle handle; return parse_url(url, handle, lastmodified, etag, api, cookie_cache); } Feed Parser::parse_url(const std::string& url, newsboat::CurlHandle& easyhandle, time_t lastmodified, const std::string& etag, newsboat::RemoteApi* api, const std::string& cookie_cache) { std::string buf; CURLcode ret; curl_slist* custom_headers{}; if (!ua.empty()) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_USERAGENT, ua.c_str()); } if (api) { api->add_custom_headers(&custom_headers); } curl_easy_setopt(easyhandle.ptr(), CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle.ptr(), CURLOPT_SSL_VERIFYPEER, verify_ssl); curl_easy_setopt(easyhandle.ptr(), CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle.ptr(), CURLOPT_WRITEDATA, &buf); curl_easy_setopt(easyhandle.ptr(), CURLOPT_NOSIGNAL, 1); curl_easy_setopt(easyhandle.ptr(), CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(easyhandle.ptr(), CURLOPT_MAXREDIRS, 10); curl_easy_setopt(easyhandle.ptr(), CURLOPT_FAILONERROR, 1); // Accept all of curl's built-in encodings curl_easy_setopt(easyhandle.ptr(), CURLOPT_ACCEPT_ENCODING, ""); if (cookie_cache != "") { curl_easy_setopt( easyhandle.ptr(), CURLOPT_COOKIEFILE, cookie_cache.c_str()); curl_easy_setopt( easyhandle.ptr(), CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (to != 0) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_TIMEOUT, to); } if (!prx.empty()) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_PROXY, prx.c_str()); } if (!prxauth.empty()) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt( easyhandle.ptr(), CURLOPT_PROXYUSERPWD, prxauth.c_str()); } curl_easy_setopt(easyhandle.ptr(), CURLOPT_PROXYTYPE, prxtype); const char* curl_ca_bundle = ::getenv("CURL_CA_BUNDLE"); if (curl_ca_bundle != nullptr) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_CAINFO, curl_ca_bundle); } HeaderValues hdrs; curl_easy_setopt(easyhandle.ptr(), CURLOPT_HEADERDATA, &hdrs); curl_easy_setopt(easyhandle.ptr(), CURLOPT_HEADERFUNCTION, handle_headers); if (lastmodified != 0) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); curl_easy_setopt(easyhandle.ptr(), CURLOPT_TIMEVALUE, lastmodified); } if (etag.length() > 0) { auto header = strprintf::fmt("If-None-Match: %s", etag); custom_headers = curl_slist_append(custom_headers, header.c_str()); } if (lastmodified != 0 || etag.length() > 0) { custom_headers = curl_slist_append(custom_headers, "A-IM: feed"); } if (custom_headers) { curl_easy_setopt( easyhandle.ptr(), CURLOPT_HTTPHEADER, custom_headers); } ret = curl_easy_perform(easyhandle.ptr()); lm = hdrs.lastmodified; et = hdrs.etag; if (custom_headers) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_HTTPHEADER, 0); curl_slist_free_all(custom_headers); } LOG(Level::DEBUG, "rsspp::Parser::parse_url: ret = %d (%s)", ret, curl_easy_strerror(ret)); long status; CURLcode infoOk = curl_easy_getinfo(easyhandle.ptr(), CURLINFO_RESPONSE_CODE, &status); curl_easy_reset(easyhandle.ptr()); if (cookie_cache != "") { curl_easy_setopt( easyhandle.ptr(), CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (ret != 0) { LOG(Level::ERROR, "rsspp::Parser::parse_url: curl_easy_perform returned " "err " "%d: %s", ret, curl_easy_strerror(ret)); std::string msg; if (ret == CURLE_HTTP_RETURNED_ERROR && infoOk == CURLE_OK) { msg = strprintf::fmt( "%s %" PRIi64, curl_easy_strerror(ret), // `status` is `long`, which is at least 32 bits, and on x86_64 // it's actually 64 bits. Thus casting to `int64_t` is either // a no-op, or an up-cast which are always safe. static_cast<int64_t>(status)); } else { msg = curl_easy_strerror(ret); } throw Exception(msg); } LOG(Level::INFO, "Parser::parse_url: retrieved data for %s: %s", url, buf); if (buf.length() > 0) { LOG(Level::DEBUG, "Parser::parse_url: converting data from %s to utf-8", hdrs.charset); const auto utf8_buf = (hdrs.charset == "utf-8" ? buf : utils::convert_text(buf, "utf-8", hdrs.charset)); LOG(Level::DEBUG, "Parser::parse_url: handing over data to parse_buffer()"); return parse_buffer(utf8_buf, url); } return Feed(); } Feed Parser::parse_buffer(const std::string& buffer, const std::string& url) { doc = xmlReadMemory(buffer.c_str(), buffer.length(), url.c_str(), nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == nullptr) { throw Exception(_("could not parse buffer")); } xmlNode* root_element = xmlDocGetRootElement(doc); Feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char*)doc->encoding; } LOG(Level::INFO, "Parser::parse_buffer: encoding = %s", f.encoding); return f; } Feed Parser::parse_file(const std::string& filename) { doc = xmlReadFile(filename.c_str(), nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); xmlNode* root_element = xmlDocGetRootElement(doc); if (root_element == nullptr) { throw Exception(_("could not parse file")); } Feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char*)doc->encoding; } LOG(Level::INFO, "Parser::parse_file: encoding = %s", f.encoding); return f; } Feed Parser::parse_xmlnode(xmlNode* node) { Feed f; if (node) { if (node->name && node->type == XML_ELEMENT_NODE) { if (strcmp((const char*)node->name, "rss") == 0) { const char* version = (const char*)xmlGetProp( node, (const xmlChar*)"version"); if (!version) { xmlFree((void*)version); throw Exception(_("no RSS version")); } if (strcmp(version, "0.91") == 0) { f.rss_version = Feed::RSS_0_91; } else if (strcmp(version, "0.92") == 0) { f.rss_version = Feed::RSS_0_92; } else if (strcmp(version, "0.94") == 0) { f.rss_version = Feed::RSS_0_94; } else if (strcmp(version, "2.0") == 0 || strcmp(version, "2") == 0) { f.rss_version = Feed::RSS_2_0; } else if (strcmp(version, "1.0") == 0) { f.rss_version = Feed::RSS_0_91; } else { xmlFree((void*)version); throw Exception( _("invalid RSS version")); } xmlFree((void*)version); } else if (strcmp((const char*)node->name, "RDF") == 0) { f.rss_version = Feed::RSS_1_0; } else if (strcmp((const char*)node->name, "feed") == 0) { if (node->ns && node->ns->href) { if (strcmp((const char*)node->ns->href, ATOM_0_3_URI) == 0) { f.rss_version = Feed::ATOM_0_3; } else if (strcmp((const char*)node->ns ->href, ATOM_1_0_URI) == 0) { f.rss_version = Feed::ATOM_1_0; } else { const char* version = (const char*)xmlGetProp(node, (const xmlChar*)"version"); if (!version) { xmlFree((void*)version); throw Exception(_( "invalid Atom " "version")); } if (strcmp(version, "0.3") == 0) { xmlFree((void*)version); f.rss_version = Feed::ATOM_0_3_NONS; } else { xmlFree((void*)version); throw Exception(_( "invalid Atom " "version")); } } } else { throw Exception(_("no Atom version")); } } std::shared_ptr<RssParser> parser = RssParserFactory::get_object(f.rss_version, doc); try { parser->parse_feed(f, node); } catch (Exception& e) { throw; } } } else { throw Exception(_("XML root node is NULL")); } return f; } void Parser::global_init() { LIBXML_TEST_VERSION curl_global_init(CURL_GLOBAL_ALL); } void Parser::global_cleanup() { xmlCleanupParser(); curl_global_cleanup(); } } // namespace rsspp <commit_msg>Get rid of raw new/delete useage in parser.cpp's handle_headers<commit_after>#include "parser.h" #include <cinttypes> #include <cstring> #include <curl/curl.h> #include <libxml/parser.h> #include <libxml/tree.h> #include <vector> #include "config.h" #include "curlhandle.h" #include "exception.h" #include "logger.h" #include "remoteapi.h" #include "rssparser.h" #include "rssparserfactory.h" #include "rsspp_uris.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; static size_t my_write_data(void* buffer, size_t size, size_t nmemb, void* userp) { std::string* pbuf = static_cast<std::string*>(userp); pbuf->append(static_cast<const char*>(buffer), size * nmemb); return size * nmemb; } namespace rsspp { Parser::Parser(unsigned int timeout, const std::string& user_agent, const std::string& proxy, const std::string& proxy_auth, curl_proxytype proxy_type, const bool ssl_verify) : to(timeout) , ua(user_agent) , prx(proxy) , prxauth(proxy_auth) , prxtype(proxy_type) , verify_ssl(ssl_verify) , doc(0) , lm(0) { } Parser::~Parser() { if (doc) { xmlFreeDoc(doc); } } namespace { struct HeaderValues { time_t lastmodified; std::string etag; std::string charset; HeaderValues() : lastmodified(0) , charset("utf-8") { } }; } static size_t handle_headers(void* ptr, size_t size, size_t nmemb, void* data) { const auto header = std::string(reinterpret_cast<const char*>(ptr), size * nmemb); HeaderValues* values = static_cast<HeaderValues*>(data); if (header.find("Last-Modified:") == 0) { const std::string header_value = header.substr(14); time_t r = curl_getdate(header_value.c_str(), nullptr); if (r == -1) { LOG(Level::DEBUG, "handle_headers: last-modified %s " "(curl_getdate " "FAILED)", header_value.c_str()); } else { values->lastmodified = r; curl_getdate(header_value.c_str(), nullptr); LOG(Level::DEBUG, "handle_headers: got last-modified %s (%" PRId64 ")", header_value.c_str(), // On GCC, `time_t` is `long int`, which is at least 32 bits. // On x86_64, it's 64 bits. Thus, this cast is either a no-op, // or an up-cast which is always safe. static_cast<int64_t>(values->lastmodified)); } } else if (header.find("ETag:") == 0) { values->etag = header.substr(5); utils::trim(values->etag); LOG(Level::DEBUG, "handle_headers: got etag %s", values->etag); } else if (header.find("Content-Type:") == 0) { const std::string key = "charset="; const auto charset_index = header.find(key); if (charset_index != std::string::npos) { auto charset = header.substr(charset_index + key.size()); utils::trim(charset); if (charset.size() >= 2 && charset[0] == '"' && charset[charset.size() - 1] == '"') { charset = charset.substr(1, charset.size() - 2); } if (charset.size() > 0) { values->charset = charset; } } } return size * nmemb; } Feed Parser::parse_url(const std::string& url, time_t lastmodified, const std::string& etag, newsboat::RemoteApi* api, const std::string& cookie_cache) { CurlHandle handle; return parse_url(url, handle, lastmodified, etag, api, cookie_cache); } Feed Parser::parse_url(const std::string& url, newsboat::CurlHandle& easyhandle, time_t lastmodified, const std::string& etag, newsboat::RemoteApi* api, const std::string& cookie_cache) { std::string buf; CURLcode ret; curl_slist* custom_headers{}; if (!ua.empty()) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_USERAGENT, ua.c_str()); } if (api) { api->add_custom_headers(&custom_headers); } curl_easy_setopt(easyhandle.ptr(), CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle.ptr(), CURLOPT_SSL_VERIFYPEER, verify_ssl); curl_easy_setopt(easyhandle.ptr(), CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle.ptr(), CURLOPT_WRITEDATA, &buf); curl_easy_setopt(easyhandle.ptr(), CURLOPT_NOSIGNAL, 1); curl_easy_setopt(easyhandle.ptr(), CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(easyhandle.ptr(), CURLOPT_MAXREDIRS, 10); curl_easy_setopt(easyhandle.ptr(), CURLOPT_FAILONERROR, 1); // Accept all of curl's built-in encodings curl_easy_setopt(easyhandle.ptr(), CURLOPT_ACCEPT_ENCODING, ""); if (cookie_cache != "") { curl_easy_setopt( easyhandle.ptr(), CURLOPT_COOKIEFILE, cookie_cache.c_str()); curl_easy_setopt( easyhandle.ptr(), CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (to != 0) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_TIMEOUT, to); } if (!prx.empty()) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_PROXY, prx.c_str()); } if (!prxauth.empty()) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_PROXYAUTH, CURLAUTH_ANY); curl_easy_setopt( easyhandle.ptr(), CURLOPT_PROXYUSERPWD, prxauth.c_str()); } curl_easy_setopt(easyhandle.ptr(), CURLOPT_PROXYTYPE, prxtype); const char* curl_ca_bundle = ::getenv("CURL_CA_BUNDLE"); if (curl_ca_bundle != nullptr) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_CAINFO, curl_ca_bundle); } HeaderValues hdrs; curl_easy_setopt(easyhandle.ptr(), CURLOPT_HEADERDATA, &hdrs); curl_easy_setopt(easyhandle.ptr(), CURLOPT_HEADERFUNCTION, handle_headers); if (lastmodified != 0) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE); curl_easy_setopt(easyhandle.ptr(), CURLOPT_TIMEVALUE, lastmodified); } if (etag.length() > 0) { auto header = strprintf::fmt("If-None-Match: %s", etag); custom_headers = curl_slist_append(custom_headers, header.c_str()); } if (lastmodified != 0 || etag.length() > 0) { custom_headers = curl_slist_append(custom_headers, "A-IM: feed"); } if (custom_headers) { curl_easy_setopt( easyhandle.ptr(), CURLOPT_HTTPHEADER, custom_headers); } ret = curl_easy_perform(easyhandle.ptr()); lm = hdrs.lastmodified; et = hdrs.etag; if (custom_headers) { curl_easy_setopt(easyhandle.ptr(), CURLOPT_HTTPHEADER, 0); curl_slist_free_all(custom_headers); } LOG(Level::DEBUG, "rsspp::Parser::parse_url: ret = %d (%s)", ret, curl_easy_strerror(ret)); long status; CURLcode infoOk = curl_easy_getinfo(easyhandle.ptr(), CURLINFO_RESPONSE_CODE, &status); curl_easy_reset(easyhandle.ptr()); if (cookie_cache != "") { curl_easy_setopt( easyhandle.ptr(), CURLOPT_COOKIEJAR, cookie_cache.c_str()); } if (ret != 0) { LOG(Level::ERROR, "rsspp::Parser::parse_url: curl_easy_perform returned " "err " "%d: %s", ret, curl_easy_strerror(ret)); std::string msg; if (ret == CURLE_HTTP_RETURNED_ERROR && infoOk == CURLE_OK) { msg = strprintf::fmt( "%s %" PRIi64, curl_easy_strerror(ret), // `status` is `long`, which is at least 32 bits, and on x86_64 // it's actually 64 bits. Thus casting to `int64_t` is either // a no-op, or an up-cast which are always safe. static_cast<int64_t>(status)); } else { msg = curl_easy_strerror(ret); } throw Exception(msg); } LOG(Level::INFO, "Parser::parse_url: retrieved data for %s: %s", url, buf); if (buf.length() > 0) { LOG(Level::DEBUG, "Parser::parse_url: converting data from %s to utf-8", hdrs.charset); const auto utf8_buf = (hdrs.charset == "utf-8" ? buf : utils::convert_text(buf, "utf-8", hdrs.charset)); LOG(Level::DEBUG, "Parser::parse_url: handing over data to parse_buffer()"); return parse_buffer(utf8_buf, url); } return Feed(); } Feed Parser::parse_buffer(const std::string& buffer, const std::string& url) { doc = xmlReadMemory(buffer.c_str(), buffer.length(), url.c_str(), nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (doc == nullptr) { throw Exception(_("could not parse buffer")); } xmlNode* root_element = xmlDocGetRootElement(doc); Feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char*)doc->encoding; } LOG(Level::INFO, "Parser::parse_buffer: encoding = %s", f.encoding); return f; } Feed Parser::parse_file(const std::string& filename) { doc = xmlReadFile(filename.c_str(), nullptr, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING); xmlNode* root_element = xmlDocGetRootElement(doc); if (root_element == nullptr) { throw Exception(_("could not parse file")); } Feed f = parse_xmlnode(root_element); if (doc->encoding) { f.encoding = (const char*)doc->encoding; } LOG(Level::INFO, "Parser::parse_file: encoding = %s", f.encoding); return f; } Feed Parser::parse_xmlnode(xmlNode* node) { Feed f; if (node) { if (node->name && node->type == XML_ELEMENT_NODE) { if (strcmp((const char*)node->name, "rss") == 0) { const char* version = (const char*)xmlGetProp( node, (const xmlChar*)"version"); if (!version) { xmlFree((void*)version); throw Exception(_("no RSS version")); } if (strcmp(version, "0.91") == 0) { f.rss_version = Feed::RSS_0_91; } else if (strcmp(version, "0.92") == 0) { f.rss_version = Feed::RSS_0_92; } else if (strcmp(version, "0.94") == 0) { f.rss_version = Feed::RSS_0_94; } else if (strcmp(version, "2.0") == 0 || strcmp(version, "2") == 0) { f.rss_version = Feed::RSS_2_0; } else if (strcmp(version, "1.0") == 0) { f.rss_version = Feed::RSS_0_91; } else { xmlFree((void*)version); throw Exception( _("invalid RSS version")); } xmlFree((void*)version); } else if (strcmp((const char*)node->name, "RDF") == 0) { f.rss_version = Feed::RSS_1_0; } else if (strcmp((const char*)node->name, "feed") == 0) { if (node->ns && node->ns->href) { if (strcmp((const char*)node->ns->href, ATOM_0_3_URI) == 0) { f.rss_version = Feed::ATOM_0_3; } else if (strcmp((const char*)node->ns ->href, ATOM_1_0_URI) == 0) { f.rss_version = Feed::ATOM_1_0; } else { const char* version = (const char*)xmlGetProp(node, (const xmlChar*)"version"); if (!version) { xmlFree((void*)version); throw Exception(_( "invalid Atom " "version")); } if (strcmp(version, "0.3") == 0) { xmlFree((void*)version); f.rss_version = Feed::ATOM_0_3_NONS; } else { xmlFree((void*)version); throw Exception(_( "invalid Atom " "version")); } } } else { throw Exception(_("no Atom version")); } } std::shared_ptr<RssParser> parser = RssParserFactory::get_object(f.rss_version, doc); try { parser->parse_feed(f, node); } catch (Exception& e) { throw; } } } else { throw Exception(_("XML root node is NULL")); } return f; } void Parser::global_init() { LIBXML_TEST_VERSION curl_global_init(CURL_GLOBAL_ALL); } void Parser::global_cleanup() { xmlCleanupParser(); curl_global_cleanup(); } } // namespace rsspp <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: MCatalog.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: mmaher $ $Date: 2001-10-11 10:07:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_MOZAB_CATALOG_HXX_ #include "MCatalog.hxx" #endif #ifndef _CONNECTIVITY_MOZAB_BCONNECTION_HXX_ #include "MConnection.hxx" #endif #ifndef _CONNECTIVITY_MOZAB_TABLES_HXX_ #include "MTables.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif // ------------------------------------------------------------------------- using namespace connectivity::mozab; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- OCatalog::OCatalog(OConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon) ,m_pConnection(_pCon) ,m_xMetaData(m_pConnection->getMetaData( )) { // osl_incrementInterlockedCount( &m_refCount ); // refreshTables(); // refreshViews(); // refreshGroups(); // refreshUsers(); // osl_decrementInterlockedCount( &m_refCount ); } // ------------------------------------------------------------------------- void OCatalog::refreshTables() { TStringVector aVector; Sequence< ::rtl::OUString > aTypes(1); aTypes[0] = ::rtl::OUString::createFromAscii("%"); Reference< XResultSet > xResult = m_xMetaData->getTables(Any(), ::rtl::OUString::createFromAscii("%"),::rtl::OUString::createFromAscii("%"),aTypes); if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); ::rtl::OUString aName; const ::rtl::OUString& sDot = OCatalog::getDot(); while(xResult->next()) { // aName = xRow->getString(2); // aName += sDot; aName = xRow->getString(3); aVector.push_back(aName); } } if(m_pTables) m_pTables->reFill(aVector); else m_pTables = new OTables(m_xMetaData,*this,m_aMutex,aVector); } // ------------------------------------------------------------------------- void OCatalog::refreshViews() { } // ------------------------------------------------------------------------- void OCatalog::refreshGroups() { } // ------------------------------------------------------------------------- void OCatalog::refreshUsers() { } // ------------------------------------------------------------------------- const ::rtl::OUString& OCatalog::getDot() { static const ::rtl::OUString sDot = ::rtl::OUString::createFromAscii("."); return sDot; } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS mozab04 (1.1.186); FILE MERGED 2004/04/13 09:15:18 windly 1.1.186.2: #1000# replace createFromAscii to RTL_CONSTASCII_USTRINGPARAM 2004/04/12 10:15:51 windly 1.1.186.1: #i6883# make mozab driver threadsafe<commit_after>/************************************************************************* * * $RCSfile: MCatalog.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hjs $ $Date: 2004-06-25 18:26:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_MOZAB_CATALOG_HXX_ #include "MCatalog.hxx" #endif #ifndef _CONNECTIVITY_MOZAB_BCONNECTION_HXX_ #include "MConnection.hxx" #endif #ifndef _CONNECTIVITY_MOZAB_TABLES_HXX_ #include "MTables.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_H_ #include <cppuhelper/interfacecontainer.h> #endif // ------------------------------------------------------------------------- using namespace connectivity::mozab; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::cppu; // ------------------------------------------------------------------------- OCatalog::OCatalog(OConnection* _pCon) : connectivity::sdbcx::OCatalog(_pCon) ,m_pConnection(_pCon) ,m_xMetaData(m_pConnection->getMetaData( )) { // osl_incrementInterlockedCount( &m_refCount ); // refreshTables(); // refreshViews(); // refreshGroups(); // refreshUsers(); // osl_decrementInterlockedCount( &m_refCount ); } // ------------------------------------------------------------------------- void OCatalog::refreshTables() { TStringVector aVector; Sequence< ::rtl::OUString > aTypes(1); aTypes[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("%")); Reference< XResultSet > xResult = m_xMetaData->getTables(Any(), ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("%")),::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("%")),aTypes); if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); ::rtl::OUString aName; const ::rtl::OUString& sDot = OCatalog::getDot(); while(xResult->next()) { // aName = xRow->getString(2); // aName += sDot; aName = xRow->getString(3); aVector.push_back(aName); } } if(m_pTables) m_pTables->reFill(aVector); else m_pTables = new OTables(m_xMetaData,*this,m_aMutex,aVector); } // ------------------------------------------------------------------------- void OCatalog::refreshViews() { } // ------------------------------------------------------------------------- void OCatalog::refreshGroups() { } // ------------------------------------------------------------------------- void OCatalog::refreshUsers() { } // ------------------------------------------------------------------------- const ::rtl::OUString& OCatalog::getDot() { static const ::rtl::OUString sDot = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(".")); return sDot; } // ----------------------------------------------------------------------------- // XTablesSupplier Reference< XNameAccess > SAL_CALL OCatalog::getTables( ) throw(RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); checkDisposed(rBHelper.bDisposed); try { if(!m_pTables || m_pConnection->getForceLoadTables()) refreshTables(); } catch( const RuntimeException& ) { // allowed to leave this method throw; } catch( const Exception& ) { // allowed } return const_cast<OCatalog*>(this)->m_pTables; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file XPM.cxx ** Define a class that holds data in the X Pixmap (XPM) format. **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string.h> #include <stdlib.h> #include "Platform.h" #include "XPM.h" static const char *NextField(const char *s) { // In case there are leading spaces in the string while (*s && *s == ' ') { s++; } while (*s && *s != ' ') { s++; } while (*s && *s == ' ') { s++; } return s; } // Data lines in XPM can be terminated either with NUL or " static size_t MeasureLength(const char *s) { size_t i = 0; while (s[i] && (s[i] != '\"')) i++; return i; } ColourAllocated XPM::ColourFromCode(int ch) { return colourCodeTable[ch]->allocated; #ifdef SLOW for (int i=0; i<nColours; i++) { if (codes[i] == ch) { return colours[i].allocated; } } return colours[0].allocated; #endif } void XPM::FillRun(Surface *surface, int code, int startX, int y, int x) { if ((code != codeTransparent) && (startX != x)) { PRectangle rc(startX, y, x, y+1); surface->FillRectangle(rc, ColourFromCode(code)); } } XPM::XPM(const char *textForm) : data(0), codes(0), colours(0), lines(0) { Init(textForm); } XPM::XPM(const char * const *linesForm) : data(0), codes(0), colours(0), lines(0) { Init(linesForm); } XPM::~XPM() { Clear(); } void XPM::Init(const char *textForm) { Clear(); // Test done is two parts to avoid possibility of overstepping the memory // if memcmp implemented strangely. Must be 4 bytes at least at destination. if ((0 == memcmp(textForm, "/* X", 4)) && (0 == memcmp(textForm, "/* XPM */", 9))) { // Build the lines form out of the text form const char **linesForm = LinesFormFromTextForm(textForm); if (linesForm != 0) { Init(linesForm); delete []linesForm; } } else { // It is really in line form Init(reinterpret_cast<const char * const *>(textForm)); } } void XPM::Init(const char * const *linesForm) { Clear(); height = 1; width = 1; nColours = 1; data = NULL; codeTransparent = ' '; codes = NULL; colours = NULL; lines = NULL; if (!linesForm) return; const char *line0 = linesForm[0]; width = atoi(line0); line0 = NextField(line0); height = atoi(line0); line0 = NextField(line0); nColours = atoi(line0); codes = new char[nColours]; colours = new ColourPair[nColours]; int strings = 1+height+nColours; lines = new char *[strings]; size_t allocation = 0; for (int i=0; i<strings; i++) { allocation += MeasureLength(linesForm[i]) + 1; } data = new char[allocation]; char *nextBit = data; for (int j=0; j<strings; j++) { lines[j] = nextBit; size_t len = MeasureLength(linesForm[j]); memcpy(nextBit, linesForm[j], len); nextBit += len; *nextBit++ = '\0'; } for (int code=0; code<256; code++) { colourCodeTable[code] = 0; } for (int c=0; c<nColours; c++) { const char *colourDef = linesForm[c+1]; codes[c] = colourDef[0]; colourDef += 4; if (*colourDef == '#') { colours[c].desired.Set(colourDef); } else { colours[c].desired = ColourDesired(0xff, 0xff, 0xff); codeTransparent = codes[c]; } colourCodeTable[static_cast<unsigned char>(codes[c])] = &(colours[c]); } } void XPM::Clear() { delete []data; data = 0; delete []codes; codes = 0; delete []colours; colours = 0; delete []lines; lines = 0; } void XPM::RefreshColourPalette(Palette &pal, bool want) { if (!data || !codes || !colours || !lines) { return; } for (int i=0; i<nColours; i++) { pal.WantFind(colours[i], want); } } void XPM::CopyDesiredColours() { if (!data || !codes || !colours || !lines) { return; } for (int i=0; i<nColours; i++) { colours[i].Copy(); } } void XPM::Draw(Surface *surface, PRectangle &rc) { if (!data || !codes || !colours || !lines) { return; } // Centre the pixmap int startY = rc.top + (rc.Height() - height) / 2; int startX = rc.left + (rc.Width() - width) / 2; for (int y=0;y<height;y++) { int prevCode = 0; int xStartRun = 0; for (int x=0; x<width; x++) { int code = lines[y+nColours+1][x]; if (code != prevCode) { FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + x); xStartRun = x; prevCode = code; } } FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + width); } } const char **XPM::LinesFormFromTextForm(const char *textForm) { // Build the lines form out of the text form const char **linesForm = 0; int countQuotes = 0; int strings=1; int j=0; for (; countQuotes < (2*strings) && textForm[j] != '\0'; j++) { if (textForm[j] == '\"') { if (countQuotes == 0) { // First field: width, height, number of colors, chars per pixel const char *line0 = textForm + j + 1; // Skip width line0 = NextField(line0); // Add 1 line for each pixel of height strings += atoi(line0); line0 = NextField(line0); // Add 1 line for each colour strings += atoi(line0); linesForm = new const char *[strings]; if (linesForm == 0) { break; // Memory error! } } if (countQuotes / 2 >= strings) { break; // Bad height or number of colors! } if ((countQuotes & 1) == 0) { linesForm[countQuotes / 2] = textForm + j + 1; } countQuotes++; } } if (textForm[j] == '\0' || countQuotes / 2 > strings) { // Malformed XPM! Height + number of colors too high or too low delete []linesForm; linesForm = 0; } return linesForm; } // In future, may want to minimize search time by sorting and using a binary search. XPMSet::XPMSet() : set(0), len(0), maximum(0), height(-1), width(-1) { } XPMSet::~XPMSet() { Clear(); } void XPMSet::Clear() { for (int i = 0; i < len; i++) { delete set[i]; } delete []set; set = 0; len = 0; maximum = 0; height = -1; width = -1; } void XPMSet::Add(int id, const char *textForm) { // Invalidate cached dimensions height = -1; width = -1; // Replace if this id already present for (int i = 0; i < len; i++) { if (set[i]->GetId() == id) { set[i]->Init(textForm); set[i]->CopyDesiredColours(); return; } } // Not present, so add to end XPM *pxpm = new XPM(textForm); if (pxpm) { pxpm->SetId(id); pxpm->CopyDesiredColours(); if (len == maximum) { maximum += 64; XPM **setNew = new XPM *[maximum]; for (int i = 0; i < len; i++) { setNew[i] = set[i]; } delete []set; set = setNew; } set[len] = pxpm; len++; } } XPM *XPMSet::Get(int id) { for (int i = 0; i < len; i++) { if (set[i]->GetId() == id) { return set[i]; } } return 0; } int XPMSet::GetHeight() { if (height < 0) { for (int i = 0; i < len; i++) { if (height < set[i]->GetHeight()) { height = set[i]->GetHeight(); } } } return (height > 0) ? height : 0; } int XPMSet::GetWidth() { if (width < 0) { for (int i = 0; i < len; i++) { if (width < set[i]->GetWidth()) { width = set[i]->GetWidth(); } } } return (width > 0) ? width : 0; } <commit_msg>Avoid crashes with XPM files that use more than 1 byte per pixel.<commit_after>// Scintilla source code edit control /** @file XPM.cxx ** Define a class that holds data in the X Pixmap (XPM) format. **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <string.h> #include <stdlib.h> #include "Platform.h" #include "XPM.h" static const char *NextField(const char *s) { // In case there are leading spaces in the string while (*s && *s == ' ') { s++; } while (*s && *s != ' ') { s++; } while (*s && *s == ' ') { s++; } return s; } // Data lines in XPM can be terminated either with NUL or " static size_t MeasureLength(const char *s) { size_t i = 0; while (s[i] && (s[i] != '\"')) i++; return i; } ColourAllocated XPM::ColourFromCode(int ch) { return colourCodeTable[ch]->allocated; #ifdef SLOW for (int i=0; i<nColours; i++) { if (codes[i] == ch) { return colours[i].allocated; } } return colours[0].allocated; #endif } void XPM::FillRun(Surface *surface, int code, int startX, int y, int x) { if ((code != codeTransparent) && (startX != x)) { PRectangle rc(startX, y, x, y+1); surface->FillRectangle(rc, ColourFromCode(code)); } } XPM::XPM(const char *textForm) : data(0), codes(0), colours(0), lines(0) { Init(textForm); } XPM::XPM(const char * const *linesForm) : data(0), codes(0), colours(0), lines(0) { Init(linesForm); } XPM::~XPM() { Clear(); } void XPM::Init(const char *textForm) { Clear(); // Test done is two parts to avoid possibility of overstepping the memory // if memcmp implemented strangely. Must be 4 bytes at least at destination. if ((0 == memcmp(textForm, "/* X", 4)) && (0 == memcmp(textForm, "/* XPM */", 9))) { // Build the lines form out of the text form const char **linesForm = LinesFormFromTextForm(textForm); if (linesForm != 0) { Init(linesForm); delete []linesForm; } } else { // It is really in line form Init(reinterpret_cast<const char * const *>(textForm)); } } void XPM::Init(const char * const *linesForm) { Clear(); height = 1; width = 1; nColours = 1; data = NULL; codeTransparent = ' '; codes = NULL; colours = NULL; lines = NULL; if (!linesForm) return; const char *line0 = linesForm[0]; width = atoi(line0); line0 = NextField(line0); height = atoi(line0); line0 = NextField(line0); nColours = atoi(line0); line0 = NextField(line0); if (atoi(line0) != 1) { // Only one char per pixel is supported return; } codes = new char[nColours]; colours = new ColourPair[nColours]; int strings = 1+height+nColours; lines = new char *[strings]; size_t allocation = 0; for (int i=0; i<strings; i++) { allocation += MeasureLength(linesForm[i]) + 1; } data = new char[allocation]; char *nextBit = data; for (int j=0; j<strings; j++) { lines[j] = nextBit; size_t len = MeasureLength(linesForm[j]); memcpy(nextBit, linesForm[j], len); nextBit += len; *nextBit++ = '\0'; } for (int code=0; code<256; code++) { colourCodeTable[code] = 0; } for (int c=0; c<nColours; c++) { const char *colourDef = linesForm[c+1]; codes[c] = colourDef[0]; colourDef += 4; if (*colourDef == '#') { colours[c].desired.Set(colourDef); } else { colours[c].desired = ColourDesired(0xff, 0xff, 0xff); codeTransparent = codes[c]; } colourCodeTable[static_cast<unsigned char>(codes[c])] = &(colours[c]); } } void XPM::Clear() { delete []data; data = 0; delete []codes; codes = 0; delete []colours; colours = 0; delete []lines; lines = 0; } void XPM::RefreshColourPalette(Palette &pal, bool want) { if (!data || !codes || !colours || !lines) { return; } for (int i=0; i<nColours; i++) { pal.WantFind(colours[i], want); } } void XPM::CopyDesiredColours() { if (!data || !codes || !colours || !lines) { return; } for (int i=0; i<nColours; i++) { colours[i].Copy(); } } void XPM::Draw(Surface *surface, PRectangle &rc) { if (!data || !codes || !colours || !lines) { return; } // Centre the pixmap int startY = rc.top + (rc.Height() - height) / 2; int startX = rc.left + (rc.Width() - width) / 2; for (int y=0;y<height;y++) { int prevCode = 0; int xStartRun = 0; for (int x=0; x<width; x++) { int code = lines[y+nColours+1][x]; if (code != prevCode) { FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + x); xStartRun = x; prevCode = code; } } FillRun(surface, prevCode, startX + xStartRun, startY + y, startX + width); } } const char **XPM::LinesFormFromTextForm(const char *textForm) { // Build the lines form out of the text form const char **linesForm = 0; int countQuotes = 0; int strings=1; int j=0; for (; countQuotes < (2*strings) && textForm[j] != '\0'; j++) { if (textForm[j] == '\"') { if (countQuotes == 0) { // First field: width, height, number of colors, chars per pixel const char *line0 = textForm + j + 1; // Skip width line0 = NextField(line0); // Add 1 line for each pixel of height strings += atoi(line0); line0 = NextField(line0); // Add 1 line for each colour strings += atoi(line0); linesForm = new const char *[strings]; if (linesForm == 0) { break; // Memory error! } } if (countQuotes / 2 >= strings) { break; // Bad height or number of colors! } if ((countQuotes & 1) == 0) { linesForm[countQuotes / 2] = textForm + j + 1; } countQuotes++; } } if (textForm[j] == '\0' || countQuotes / 2 > strings) { // Malformed XPM! Height + number of colors too high or too low delete []linesForm; linesForm = 0; } return linesForm; } // In future, may want to minimize search time by sorting and using a binary search. XPMSet::XPMSet() : set(0), len(0), maximum(0), height(-1), width(-1) { } XPMSet::~XPMSet() { Clear(); } void XPMSet::Clear() { for (int i = 0; i < len; i++) { delete set[i]; } delete []set; set = 0; len = 0; maximum = 0; height = -1; width = -1; } void XPMSet::Add(int id, const char *textForm) { // Invalidate cached dimensions height = -1; width = -1; // Replace if this id already present for (int i = 0; i < len; i++) { if (set[i]->GetId() == id) { set[i]->Init(textForm); set[i]->CopyDesiredColours(); return; } } // Not present, so add to end XPM *pxpm = new XPM(textForm); if (pxpm) { pxpm->SetId(id); pxpm->CopyDesiredColours(); if (len == maximum) { maximum += 64; XPM **setNew = new XPM *[maximum]; for (int i = 0; i < len; i++) { setNew[i] = set[i]; } delete []set; set = setNew; } set[len] = pxpm; len++; } } XPM *XPMSet::Get(int id) { for (int i = 0; i < len; i++) { if (set[i]->GetId() == id) { return set[i]; } } return 0; } int XPMSet::GetHeight() { if (height < 0) { for (int i = 0; i < len; i++) { if (height < set[i]->GetHeight()) { height = set[i]->GetHeight(); } } } return (height > 0) ? height : 0; } int XPMSet::GetWidth() { if (width < 0) { for (int i = 0; i < len; i++) { if (width < set[i]->GetWidth()) { width = set[i]->GetWidth(); } } } return (width > 0) ? width : 0; } <|endoftext|>
<commit_before>/** * Ice multiplatform dynamic library loader. * * @copyright 2011 David Rebbe */ #include "ice_library.h" #include "ice_exception.h" #include <sstream> using namespace ice; Library::Library(std::string name) { m_name = name; #if (defined(_WIN32) || defined(__WIN32__)) #ifdef UNICODE int len = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, NULL, 0); if (len) { wchar_t* n = new wchar_t[len]; MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, n, len); m_lib = LoadLibrary(n); delete[] n; } else m_lib = NULL; #else m_lib = LoadLibrary(name.c_str()); #endif // UNICODE if (m_lib == NULL) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to open library: '" << name << "' with error code: #" << error; throw Exception(err.str()); } #else m_lib = dlopen(name.c_str(), RTLD_NOW); if (m_lib == NULL) { std::stringstream err; err << "Failed to open library '" << name << "': " << dlerror(); throw Exception(err.str()); } #endif } Library::~Library() { if (this->isLoaded()) { #if (defined(_WIN32) || defined(__WIN32__)) FreeLibrary(m_lib); #else dlclose(m_lib); #endif } } bool Library::isLoaded() const { return m_lib != NULL; } std::string Library::getPath(bool* okay) { if (okay) *okay = false; if (!isLoaded()) return m_name; #if (defined(_WIN32) || defined(__WIN32__)) TCHAR buffer[MAX_PATH] = {0}; int len = GetModuleFileName(m_lib, buffer, MAX_PATH); if (!len) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to get Library path: '" << m_name << "' with error code: #" << error; throw Exception(err.str()); } #ifdef UNICODE int length = WideCharToMultiByte(CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL); if (length) { char* temp = new char[MAX_PATH]; WideCharToMultiByte(CP_UTF8, 0, buffer, -1, temp, length, NULL, NULL); std::stringstream ss; ss << temp; if (okay) *okay = true; delete temp; temp = NULL; return ss.str(); } #else std::stringstream ss; ss << buffer; if (okay) *okay = true; return ss.str(); #endif // UNICODE #else // Linux doesn't really have a way to get the library path from the handle and // its recommended to use absolute paths when loading with dlopen(). #endif // WIN32 return m_name; } HMODULE const& Library::_library() const { return m_lib; } <commit_msg>Revert "Fixed memory leak in Library::getPath()"<commit_after>/** * Ice multiplatform dynamic library loader. * * @copyright 2011 David Rebbe */ #include "ice_library.h" #include "ice_exception.h" #include <sstream> using namespace ice; Library::Library(std::string name) { m_name = name; #if (defined(_WIN32) || defined(__WIN32__)) #ifdef UNICODE int len = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, NULL, 0); if (len) { wchar_t* n = new wchar_t[len]; MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, n, len); m_lib = LoadLibrary(n); delete[] n; } else m_lib = NULL; #else m_lib = LoadLibrary(name.c_str()); #endif // UNICODE if (m_lib == NULL) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to open library: '" << name << "' with error code: #" << error; throw Exception(err.str()); } #else m_lib = dlopen(name.c_str(), RTLD_NOW); if (m_lib == NULL) { std::stringstream err; err << "Failed to open library '" << name << "': " << dlerror(); throw Exception(err.str()); } #endif } Library::~Library() { if (this->isLoaded()) { #if (defined(_WIN32) || defined(__WIN32__)) FreeLibrary(m_lib); #else dlclose(m_lib); #endif } } bool Library::isLoaded() const { return m_lib != NULL; } std::string Library::getPath(bool* okay) { if (okay) *okay = false; if (!isLoaded()) return m_name; #if (defined(_WIN32) || defined(__WIN32__)) TCHAR buffer[MAX_PATH] = {0}; int len = GetModuleFileName(m_lib, buffer, MAX_PATH); if (!len) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to get Library path: '" << m_name << "' with error code: #" << error; throw Exception(err.str()); } #ifdef UNICODE int length = WideCharToMultiByte(CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL); if (length) { char* temp = new char[MAX_PATH]; WideCharToMultiByte(CP_UTF8, 0, buffer, -1, temp, length, NULL, NULL); std::stringstream ss; ss << temp; if (okay) *okay = true; return ss.str(); } #else std::stringstream ss; ss << buffer; if (okay) *okay = true; return ss.str(); #endif // UNICODE #else // Linux doesn't really have a way to get the library path from the handle and // its recommended to use absolute paths when loading with dlopen(). #endif // WIN32 return m_name; } HMODULE const& Library::_library() const { return m_lib; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "LogPainterFactory.h" #include "ILogItemPainter.h" #include "LogItem.h" class LogSingleLinePainter : public ILogItemPainter { virtual void Draw(HDC hdc, const RECT& rect, const LogItem& item) { int oldBkMode = ::SetBkMode(hdc, TRANSPARENT); int oldTextColor = ::GetTextColor(hdc); if (item.selected) { HBRUSH bkgdBrush = ::CreateSolidBrush(0x00C36832); HGDIOBJ oldBrush = ::SelectObject(hdc, bkgdBrush); ::FillRect(hdc, &rect, bkgdBrush); ::SelectObject(hdc, oldBrush); ::DeleteObject(bkgdBrush); ::SetTextColor(hdc, 0x00FFFFFF); } std::basic_ostringstream<TCHAR> oss; oss << item.line << _T(" ") << item.text; tstring line = oss.str(); RECT textRect = rect; textRect.top += 1; textRect.bottom -= 1; ::DrawText(hdc, line.c_str(), line.size(), &textRect, DT_NOCLIP | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX | DT_EXPANDTABS); ::SetBkMode(hdc, oldBkMode); ::SetTextColor(hdc, oldTextColor); } }; class LogLineDetailPainter : public ILogItemPainter { virtual void Draw(HDC hdc, const RECT& rect, const LogItem& item) { RECT drawRect = rect; ::DrawText(hdc, item.text.c_str(), item.text.size(), &drawRect, DT_NOCLIP | DT_WORDBREAK | DT_NOPREFIX); } }; SHLIB_COMMON_SINGLETON_SUPPORT_IMPLEMENT(LogPainterFactory) LogPainterFactory::LogPainterFactory() : singleLinePainter(new LogSingleLinePainter()) , lineDetailPainter(new LogLineDetailPainter()) { } LogPainterFactory::~LogPainterFactory() { delete singleLinePainter; delete lineDetailPainter; } ILogItemPainter* LogPainterFactory::GetSingleLinePainter() const { return singleLinePainter; } ILogItemPainter* LogPainterFactory::GetLineDetailPainter() const { return lineDetailPainter; }<commit_msg>硬编条件高亮<commit_after>#include "stdafx.h" #include "LogPainterFactory.h" #include "ILogItemPainter.h" #include "LogItem.h" class LogSingleLinePainter : public ILogItemPainter { virtual void Draw(HDC hdc, const RECT& rect, const LogItem& item) { int oldBkMode = ::SetBkMode(hdc, TRANSPARENT); int oldTextColor = ::GetTextColor(hdc); // 背景 HBRUSH bkgdBrush = ::CreateSolidBrush(0x00FFFFFF); if (item.selected) { bkgdBrush = ::CreateSolidBrush(0x00C36832); } else if (item.text.find(_T("ERROR")) != tstring::npos) { bkgdBrush = ::CreateSolidBrush(0x000000FF); } else if (item.text.find(_T("WARN")) != tstring::npos) { bkgdBrush = ::CreateSolidBrush(0x0000FFFF); } HGDIOBJ oldBrush = ::SelectObject(hdc, bkgdBrush); ::FillRect(hdc, &rect, bkgdBrush); ::SelectObject(hdc, oldBrush); ::DeleteObject(bkgdBrush); // 文本 std::basic_ostringstream<TCHAR> oss; oss << item.line << _T(" ") << item.text; tstring line = oss.str(); RECT textRect = rect; textRect.top += 1; textRect.bottom -= 1; ::DrawText(hdc, line.c_str(), line.size(), &textRect, DT_NOCLIP | DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX | DT_EXPANDTABS); ::SetBkMode(hdc, oldBkMode); ::SetTextColor(hdc, oldTextColor); } }; class LogLineDetailPainter : public ILogItemPainter { virtual void Draw(HDC hdc, const RECT& rect, const LogItem& item) { RECT drawRect = rect; ::DrawText(hdc, item.text.c_str(), item.text.size(), &drawRect, DT_NOCLIP | DT_WORDBREAK | DT_NOPREFIX); } }; SHLIB_COMMON_SINGLETON_SUPPORT_IMPLEMENT(LogPainterFactory) LogPainterFactory::LogPainterFactory() : singleLinePainter(new LogSingleLinePainter()) , lineDetailPainter(new LogLineDetailPainter()) { } LogPainterFactory::~LogPainterFactory() { delete singleLinePainter; delete lineDetailPainter; } ILogItemPainter* LogPainterFactory::GetSingleLinePainter() const { return singleLinePainter; } ILogItemPainter* LogPainterFactory::GetLineDetailPainter() const { return lineDetailPainter; }<|endoftext|>
<commit_before>#ifndef K3_RUNTIME_DATASPACE_MAPDS_H #define K3_RUNTIME_DATASPACE_MAPDS_H #include <algorithm> #include <iostream> #include <unordered_map> #include <string> #include <functional> // K3 #include <Engine.hpp> namespace K3 { using K3::Engine; using std::shared_ptr; using std::tuple; using std::unordered_map; // MapDS only works on R_key_value template<class R> class MapDS { using Key = typename R::KeyType; using Value = typename R::ValueType; using iterator_type = typename unordered_map<Key,Value>::iterator; using const_iterator_type = typename unordered_map<Key, Value>::const_iterator; public: // Constructors MapDS(Engine * eng) : container() {} template<typename Iterator> MapDS(Engine * eng, Iterator start, Iterator finish) : container(start,finish) {} MapDS(const MapDS& other) : container(other.container) {} MapDS(unordered_map<Key,Value>& con) : container(con) {} // DS Operations: // Maybe return the first element in the DS shared_ptr<R> peek() const { shared_ptr<R> res; const_iterator_type it = container.begin(); if (it != container.end()) { R rec; rec.key = it->first; rec.value = it->second; res = std::make_shared<R>(rec); } return res; } void insert(const R& rec) { container.insert(make_pair(rec.key,rec.value)); } void erase(const R& rec) { iterator_type it; it = container.find(rec.key); if (it != container.end()) { if (it->second == container.value) { container.erase(it); } } } // TODO: verify semantics. Currently: update((1,1), (2,2)) results in (1,2)! void update(const R& rec1, const R& rec2) { iterator_type it; it = container.find(rec1.key); if (it != container.end()) { if (rec1.value == it->second) { container[rec1.key] = rec2.value; } } } template<typename Acc> Acc fold(F<F<Acc(R)>(Acc)> f, Acc init_acc) { Acc acc = init_acc; for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; acc = f(acc)(rec); } return acc; } template<typename NewElem> ListDS<NewElem> map(F<NewElem(R)> f) { ListDS<NewElem> result = ListDS<NewElem>(getEngine()); for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; NewElem new_e = f(rec); result.insert(new_e); } return result; } unit_t iterate(F<unit_t(R)> f) { for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; f(rec); } return unit_t(); } MapDS<R> filter(F<bool(R)> predicate) { MapDS<R> result = MapDS<R>(getEngine()); for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; if (predicate(rec)) { result.insert(rec); } } return result; } tuple< MapDS, MapDS > split() { // Find midpoint size_t size = container.size(); size_t half = size / 2; // Setup iterators const_iterator_type beg = container.begin(); const_iterator_type mid = container.begin(); std::advance(mid, half); const_iterator_type end = container.end(); // Construct DS from iterators MapDS p1 = MapDS(nullptr, beg, mid); MapDS p2 = MapDS(nullptr, mid, end); return std::make_tuple(p1, p2); } MapDS combine(MapDS other) const { // copy this DS MapDS result = MapDS(nullptr,container.begin(), container.end()); // copy other DS for (std::pair<Key,Value> p: other.container) { result.container.insert(p); } return result; } protected: unordered_map<Key,Value> container; // In-memory Dataspaces do not keep a handle to an engine Engine* getEngine() {return nullptr; } private: friend class boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & container; } }; } #endif // K3_RUNTIME_DATASPACE_MAPDS_H <commit_msg>Map: Minor fixes / Cleanup<commit_after>#ifndef K3_RUNTIME_DATASPACE_MAPDS_H #define K3_RUNTIME_DATASPACE_MAPDS_H #include <algorithm> #include <iostream> #include <unordered_map> #include <string> #include <functional> // K3 #include <Engine.hpp> namespace K3 { using K3::Engine; using std::shared_ptr; using std::tuple; using std::unordered_map; // MapDS only works on R_key_value template<class R> class MapDS { using Key = typename R::KeyType; using Value = typename R::ValueType; using iterator_type = typename unordered_map<Key,Value>::iterator; using const_iterator_type = typename unordered_map<Key, Value>::const_iterator; public: // Constructors MapDS(Engine * eng) : container() {} template<typename Iterator> MapDS(Engine * eng, Iterator start, Iterator finish) : container(start,finish) {} MapDS(const MapDS& other) : container(other.container) {} MapDS(unordered_map<Key,Value>& con) : container(con) {} // DS Operations: // Maybe return the first element in the DS shared_ptr<R> peek() const { shared_ptr<R> res; const_iterator_type it = container.begin(); if (it != container.end()) { R rec; rec.key = it->first; rec.value = it->second; res = std::make_shared<R>(rec); } return res; } void insert(const R& rec) { container.insert(make_pair(rec.key,rec.value)); } void erase(const R& rec) { iterator_type it; it = container.find(rec.key); if (it != container.end() && it->second == rec.value) { container.erase(it); } } void update(const R& rec1, const R& rec2) { iterator_type it; it = container.find(rec1.key); if (it != container.end()) { if (rec1.value == it->second) { container[rec2.key] = rec2.value; } } } template<typename Acc> Acc fold(F<F<Acc(R)>(Acc)> f, Acc init_acc) { Acc acc = init_acc; for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; acc = f(acc)(rec); } return acc; } template<typename NewElem> ListDS<NewElem> map(F<NewElem(R)> f) { ListDS<NewElem> result = ListDS<NewElem>(getEngine()); for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; NewElem new_e = f(rec); result.insert(new_e); } return result; } unit_t iterate(F<unit_t(R)> f) { for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; f(rec); } return unit_t(); } MapDS<R> filter(F<bool(R)> predicate) { MapDS<R> result = MapDS<R>(getEngine()); for (std::pair<Key,Value> p : container) { R rec; rec.key = p.first; rec.value = p.second; if (predicate(rec)) { result.insert(rec); } } return result; } tuple< MapDS, MapDS > split() { // Find midpoint size_t size = container.size(); size_t half = size / 2; // Setup iterators const_iterator_type beg = container.begin(); const_iterator_type mid = container.begin(); std::advance(mid, half); const_iterator_type end = container.end(); // Construct DS from iterators MapDS p1 = MapDS(nullptr, beg, mid); MapDS p2 = MapDS(nullptr, mid, end); return std::make_tuple(p1, p2); } MapDS combine(MapDS other) const { // copy this DS MapDS result = MapDS(nullptr,container.begin(), container.end()); // copy other DS for (std::pair<Key,Value> p: other.container) { result.container.insert(p); } return result; } protected: unordered_map<Key,Value> container; // In-memory Dataspaces do not keep a handle to an engine Engine* getEngine() {return nullptr; } private: friend class boost::serialization::access; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & container; } }; } #endif // K3_RUNTIME_DATASPACE_MAPDS_H <|endoftext|>
<commit_before>#include <exception> #include <string> #include <map> #include <utility> #include <boost/python.hpp> #include <boost/python/suite/indexing/map_indexing_suite.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/return_arg.hpp> #include <vigra/numpy_array.hxx> #include <vigra/numpy_array_converters.hxx> #include <vigra/multi_array.hxx> #include "../../tracking/include/track.h" #include "../../tracking/include/traxels.h" namespace Tracking { using namespace std; using namespace vigra; // extending Traxel void add_feature_array(Traxel& t, string key, size_t size) { t.features[key] = feature_array(size, 0); } float get_feature_value(Traxel& t, string key, MultiArrayIndex i) { FeatureMap::const_iterator it = t.features.find(key); if(it == t.features.end()) { throw std::runtime_error("key not present in feature map"); } if( !(static_cast<size_t>(i) < it->second.size())) { throw std::runtime_error("index out of range"); } return it->second[i]; } void set_feature_value(Traxel& t, string key, MultiArrayIndex i, float value) { FeatureMap::iterator it = t.features.find(key); if(it == t.features.end()) { throw std::runtime_error("key not present in feature map"); } if( !(static_cast<size_t>(i) < it->second.size())) { throw std::runtime_error("index out of range"); } it->second[i] = value; } // extending Traxels void add_traxel(Traxels& ts, const Traxel& t) { ts[t.Id] = t; } // extending TraxelStore void add_traxel_to_traxelstore(TraxelStore& ts, const Traxel& t) { add(ts, t); } void add_Traxels_to_traxelstore(TraxelStore& ts, const Traxels& traxels) { for(Traxels::const_iterator it = traxels.begin(); it!= traxels.end(); ++it){ add(ts, it->second); } } } BOOST_PYTHON_MODULE( ctracking ) { using namespace boost::python; using namespace Tracking; // traxels.h class_< feature_array >("feature_array"); class_< ComLocator >("ComLocator") .def_readwrite("x_scale", &ComLocator::x_scale) .def_readwrite("y_scale", &ComLocator::y_scale) .def_readwrite("z_scale", &ComLocator::z_scale) ; class_< IntmaxposLocator >("IntmaxposLocator") .def_readwrite("x_scale", &ComLocator::x_scale) .def_readwrite("y_scale", &ComLocator::y_scale) .def_readwrite("z_scale", &ComLocator::z_scale) ; class_< std::map<std::string,feature_array> >("FeatureMap") .def(map_indexing_suite<std::map<std::string,feature_array> >()) ; class_<Traxel>("Traxel") .def_readwrite("Id", &Traxel::Id) .def_readwrite("Timestep", &Traxel::Timestep) .def("set_locator", &Traxel::set_locator, return_self<>()) .def("X", &Traxel::X) .def("Y", &Traxel::Y) .def("Z", &Traxel::Z) .def_readwrite("features", &Traxel::features) .def("add_feature_array", &add_feature_array, args("self","name", "size"), "Add a new feature array to the features map; initialize with zeros. If the name is already present, the old feature array will be replaced.") .def("get_feature_value", &get_feature_value, args("self", "name", "index")) .def("set_feature_value", &set_feature_value, args("self", "name", "index", "value")) ; class_<map<unsigned int, Traxel> >("Traxels") .def("add_traxel", &add_traxel) .def("__len__", &Traxels::size) ; class_<TraxelStore>("TraxelStore") .def("add", &add_traxel_to_traxelstore) .def("add_from_Traxels", &add_Traxels_to_traxelstore) ; // track.h class_<vector<Event> >("EventVector") .def(vector_indexing_suite<vector<Event> >()) ; class_<vector<vector<Event> > >("NestedEventVector") .def(vector_indexing_suite<vector<vector<Event> > >()) ; class_<BotTracking>("BotTracking", init<double,double,double>( args("detection", "misdetection", "opportunity_cost"))) .def("__call__", &BotTracking::operator()) ; class_<MrfTracking>("MrfTracking", init<string,double,double,double,double,bool,double,double,double>( args("random_forest_filename", "appearance", "disappearance", "detection", "misdetection", "use_random_forest", "opportunity_cost", "mean_div_dist", "min_angle"))) .def("__call__", &MrfTracking::operator()) ; class_<FixedCostTracking>("FixedCostTracking", init<double,double,double,double,double>( args("division", "move", "disappearance", "appearance", "distance_threshold"))) .def("__call__", &FixedCostTracking::operator()) ; class_<ShortestDistanceTracking>("ShortestDistanceTracking", init<double, double, double, double, unsigned int>( args("division", "disappearance", "appearance", "distance_threshold", "max_nearest_neighbors"))) .def("__call__", &ShortestDistanceTracking::operator()) ; class_<CellnessTracking>("CellnessTracking", init<string, double, double, double, double, double, double>( args("random_forest_file", "w_div1", "w_div2", "w_move", "w_app", "w_disapp", "distance_threshold"), "Weights description" "\n\nDivision:" "\n w_div1: weight for the difference of the children's cellness" "\n w_div2: weight for the parent cellness" "\n Move:" "\n w_move: weight for the cellness difference" "\n Appearance:" "\n w_app: scale of the appearance cost" "\n Disappearance:" "\n w_disapp: scale of the disappearance cost")) .def("__call__", &CellnessTracking::operator()) ; // ilp_construction.h enum_<Event::EventType>("EventType") .value("Move", Event::Move) .value("Division", Event::Division) .value("Appearance", Event::Appearance) .value("Disappearance", Event::Disappearance) .value("Void", Event::Void) ; class_<vector<unsigned int> >("IdVector") .def(vector_indexing_suite<vector<unsigned int> >()) ; class_<Event>("Event") .def_readonly("type", &Event::type) .def_readonly("traxel_ids", &Event::traxel_ids) .def_readonly("energy", &Event::energy) ; //class_<AdaptiveEnergiesFormulation>("AdaptiveEnergiesFormulation") //; } <commit_msg>wrapped MrfTracking::detections()<commit_after>#include <exception> #include <string> #include <map> #include <utility> #include <boost/python.hpp> #include <boost/python/suite/indexing/map_indexing_suite.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/return_arg.hpp> #include <vigra/numpy_array.hxx> #include <vigra/numpy_array_converters.hxx> #include <vigra/multi_array.hxx> #include "../../tracking/include/track.h" #include "../../tracking/include/traxels.h" namespace Tracking { using namespace std; using namespace vigra; // extending Traxel void add_feature_array(Traxel& t, string key, size_t size) { t.features[key] = feature_array(size, 0); } float get_feature_value(Traxel& t, string key, MultiArrayIndex i) { FeatureMap::const_iterator it = t.features.find(key); if(it == t.features.end()) { throw std::runtime_error("key not present in feature map"); } if( !(static_cast<size_t>(i) < it->second.size())) { throw std::runtime_error("index out of range"); } return it->second[i]; } void set_feature_value(Traxel& t, string key, MultiArrayIndex i, float value) { FeatureMap::iterator it = t.features.find(key); if(it == t.features.end()) { throw std::runtime_error("key not present in feature map"); } if( !(static_cast<size_t>(i) < it->second.size())) { throw std::runtime_error("index out of range"); } it->second[i] = value; } // extending Traxels void add_traxel(Traxels& ts, const Traxel& t) { ts[t.Id] = t; } // extending TraxelStore void add_traxel_to_traxelstore(TraxelStore& ts, const Traxel& t) { add(ts, t); } void add_Traxels_to_traxelstore(TraxelStore& ts, const Traxels& traxels) { for(Traxels::const_iterator it = traxels.begin(); it!= traxels.end(); ++it){ add(ts, it->second); } } } BOOST_PYTHON_MODULE( ctracking ) { using namespace boost::python; using namespace Tracking; // traxels.h class_< feature_array >("feature_array"); class_< ComLocator >("ComLocator") .def_readwrite("x_scale", &ComLocator::x_scale) .def_readwrite("y_scale", &ComLocator::y_scale) .def_readwrite("z_scale", &ComLocator::z_scale) ; class_< IntmaxposLocator >("IntmaxposLocator") .def_readwrite("x_scale", &ComLocator::x_scale) .def_readwrite("y_scale", &ComLocator::y_scale) .def_readwrite("z_scale", &ComLocator::z_scale) ; class_< std::map<std::string,feature_array> >("FeatureMap") .def(map_indexing_suite<std::map<std::string,feature_array> >()) ; class_<Traxel>("Traxel") .def_readwrite("Id", &Traxel::Id) .def_readwrite("Timestep", &Traxel::Timestep) .def("set_locator", &Traxel::set_locator, return_self<>()) .def("X", &Traxel::X) .def("Y", &Traxel::Y) .def("Z", &Traxel::Z) .def_readwrite("features", &Traxel::features) .def("add_feature_array", &add_feature_array, args("self","name", "size"), "Add a new feature array to the features map; initialize with zeros. If the name is already present, the old feature array will be replaced.") .def("get_feature_value", &get_feature_value, args("self", "name", "index")) .def("set_feature_value", &set_feature_value, args("self", "name", "index", "value")) ; class_<map<unsigned int, Traxel> >("Traxels") .def("add_traxel", &add_traxel) .def("__len__", &Traxels::size) ; class_<TraxelStore>("TraxelStore") .def("add", &add_traxel_to_traxelstore) .def("add_from_Traxels", &add_Traxels_to_traxelstore) ; // track.h class_<vector<Event> >("EventVector") .def(vector_indexing_suite<vector<Event> >()) ; class_<vector<vector<Event> > >("NestedEventVector") .def(vector_indexing_suite<vector<vector<Event> > >()) ; class_<map<unsigned int, bool> >("DetectionMap") .def(map_indexing_suite<map<unsigned int, bool> >()) ; class_<vector<map<unsigned int, bool> > >("DetectionMapsVector") .def(vector_indexing_suite<vector<map<unsigned int, bool> > >()) ; class_<BotTracking>("BotTracking", init<double,double,double>( args("detection", "misdetection", "opportunity_cost"))) .def("__call__", &BotTracking::operator()) ; class_<MrfTracking>("MrfTracking", init<string,double,double,double,double,bool,double,double,double>( args("random_forest_filename", "appearance", "disappearance", "detection", "misdetection", "use_random_forest", "opportunity_cost", "mean_div_dist", "min_angle"))) .def("__call__", &MrfTracking::operator()) .def("detections", &MrfTracking::detections) ; class_<FixedCostTracking>("FixedCostTracking", init<double,double,double,double,double>( args("division", "move", "disappearance", "appearance", "distance_threshold"))) .def("__call__", &FixedCostTracking::operator()) ; class_<ShortestDistanceTracking>("ShortestDistanceTracking", init<double, double, double, double, unsigned int>( args("division", "disappearance", "appearance", "distance_threshold", "max_nearest_neighbors"))) .def("__call__", &ShortestDistanceTracking::operator()) ; class_<CellnessTracking>("CellnessTracking", init<string, double, double, double, double, double, double>( args("random_forest_file", "w_div1", "w_div2", "w_move", "w_app", "w_disapp", "distance_threshold"), "Weights description" "\n\nDivision:" "\n w_div1: weight for the difference of the children's cellness" "\n w_div2: weight for the parent cellness" "\n Move:" "\n w_move: weight for the cellness difference" "\n Appearance:" "\n w_app: scale of the appearance cost" "\n Disappearance:" "\n w_disapp: scale of the disappearance cost")) .def("__call__", &CellnessTracking::operator()) ; // ilp_construction.h enum_<Event::EventType>("EventType") .value("Move", Event::Move) .value("Division", Event::Division) .value("Appearance", Event::Appearance) .value("Disappearance", Event::Disappearance) .value("Void", Event::Void) ; class_<vector<unsigned int> >("IdVector") .def(vector_indexing_suite<vector<unsigned int> >()) ; class_<Event>("Event") .def_readonly("type", &Event::type) .def_readonly("traxel_ids", &Event::traxel_ids) .def_readonly("energy", &Event::energy) ; //class_<AdaptiveEnergiesFormulation>("AdaptiveEnergiesFormulation") //; } <|endoftext|>
<commit_before>#include <boost/asio/io_service.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/ip/tcp.hpp> #include <iostream> #include <warpcoil/then.hpp> namespace { namespace asio = boost::asio; void delay(std::chrono::steady_clock::duration duration, asio::io_service &io, asio::yield_context yield) { asio::steady_timer timeout(io); timeout.expires_from_now(duration); timeout.async_wait(yield); } void try_to_connect(asio::ip::tcp::endpoint server, asio::io_service &io, asio::yield_context yield) { using warpcoil::future; asio::ip::tcp::socket socket(io, asio::ip::tcp::v4()); asio::steady_timer timeout(io); timeout.expires_from_now(std::chrono::seconds(2)); warpcoil::when_all(timeout.async_wait(warpcoil::then([&](boost::system::error_code) { socket.cancel(); })), socket.async_connect( server, warpcoil::then([&](boost::system::error_code ec) { timeout.cancel(); if (!!ec) { std::cerr << server << " Failed with error " << ec << '\n'; } else { std::cerr << server << " Succeeded\n"; } }))) .async_wait(yield); } } int main() { boost::asio::io_service io; #ifdef _MSC_VER { // WinSock initialization crashes with an access violation if done // within a Boost coroutine, so we do it here: asio::ip::tcp::socket dummy(io, asio::ip::tcp::v4()); } #endif boost::asio::spawn(io, [&io](asio::yield_context yield) { for (;;) { try_to_connect( asio::ip::tcp::endpoint( asio::ip::address_v4::from_string("172.217.20.195"), 80), io, yield); delay(std::chrono::seconds(1), io, yield); } }); boost::asio::spawn(io, [&io](asio::yield_context yield) { for (;;) { try_to_connect(asio::ip::tcp::endpoint( asio::ip::address_v4::from_string("1.2.3.4"), 80), io, yield); } }); io.run(); } <commit_msg>remove unnecessary warpcoil::<commit_after>#include <boost/asio/io_service.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/ip/tcp.hpp> #include <iostream> #include <warpcoil/then.hpp> namespace { namespace asio = boost::asio; void delay(std::chrono::steady_clock::duration duration, asio::io_service &io, asio::yield_context yield) { asio::steady_timer timeout(io); timeout.expires_from_now(duration); timeout.async_wait(yield); } void try_to_connect(asio::ip::tcp::endpoint server, asio::io_service &io, asio::yield_context yield) { using warpcoil::future; using warpcoil::then; using warpcoil::when_all; asio::ip::tcp::socket socket(io, asio::ip::tcp::v4()); asio::steady_timer timeout(io); timeout.expires_from_now(std::chrono::seconds(2)); when_all(timeout.async_wait(then([&](boost::system::error_code) { socket.cancel(); })), socket.async_connect(server, then([&](boost::system::error_code ec) { timeout.cancel(); if (!!ec) { std::cerr << server << " Failed with error " << ec << '\n'; } else { std::cerr << server << " Succeeded\n"; } }))) .async_wait(yield); } } int main() { boost::asio::io_service io; #ifdef _MSC_VER { // WinSock initialization crashes with an access violation if done // within a Boost coroutine, so we do it here: asio::ip::tcp::socket dummy(io, asio::ip::tcp::v4()); } #endif boost::asio::spawn(io, [&io](asio::yield_context yield) { for (;;) { try_to_connect( asio::ip::tcp::endpoint( asio::ip::address_v4::from_string("172.217.20.195"), 80), io, yield); delay(std::chrono::seconds(1), io, yield); } }); boost::asio::spawn(io, [&io](asio::yield_context yield) { for (;;) { try_to_connect(asio::ip::tcp::endpoint( asio::ip::address_v4::from_string("1.2.3.4"), 80), io, yield); } }); io.run(); } <|endoftext|>
<commit_before>#include <iostream> #include <boost/algorithm/string.hpp> #include <redox/redox.hpp> #include <json/json.hpp> #include <nghttp2/asio_http2_server.h> using namespace nghttp2::asio_http2; using namespace nghttp2::asio_http2::server; using json = nlohmann::json; generator_cb loading_templete(std::string path, const response &res) { auto fd = open(path.c_str(), O_RDONLY); if (fd == -1) { return 0; } return file_generator_from_fd(fd); } std::string getParamters(std::string uri, int count) { std::vector<std::string> strs; boost::split(strs, uri, boost::is_any_of("/")); return strs[count]; } int main(int argc, char *argv[]) { boost::system::error_code ec; boost::asio::ssl::context tls(boost::asio::ssl::context::sslv23); tls.use_private_key_file("static/cert/privkey1.pem", boost::asio::ssl::context::sslv23); tls.use_certificate_chain_file("static/cert/chain1.pem"); configure_tls_context_easy(ec, tls); http2 server; redox::Redox rdx; rdx.connect("172.17.0.3", 6379); //config std::string port = "443"; std::cout << "uniquehttp2 is loading..." << std::endl; server.handle("/", [](const request &req, const response &res) { auto body = loading_templete("../static/index.html", res); if (!body) { res.write_head(404); res.end(); } res.write_head(200); res.end(body); // header_map mmp = req.header(); // header_map::iterator pos; // for(pos = mmp.begin(); pos != mmp.end(); ++pos) { // std::cout << "value for " << pos->first <<" can be " << (pos->second).value << std::endl; // } // log: // accept */* // user-agent curl/7.53.1 // *** another workaround *** // // auto headers = req.header(); // for(const auto &header : headers) { // std::cout << "value for " << header.first <<" can be " << (header.second).value << std::endl; // } }); server.handle("/api/article/", [&rdx](const request &req, const response &res) { std::string article_id = getParamters(req.uri().path, 3); auto method = req.method(); if (method == "POST") { //data } json data; data["method"] = method; // if (!article_id) { // json articles; // std::vector<std::string> tips = {"author", "content", "date"}; // int total = stoi(rdx.get("article-count")); // for (int i = 0;i < total; i ++) { // json article; // std::string n = std::to_string(i + 1); // for (const auto& tip : tips) { // article[tip] = rdx.get("article-" + n + "-" + tip); // } // articles[i] = article; // } // data["data"] = articles; // data["total"] = rdx.get("article-count"); // data["msg"] = "hello " + rdx.get("hello"); // } // data["article_id"] = article_id; // data["article_header"] = "第一个篇章"; // data["article_info"] = { // {"date", "2017/4/6"}, // {"author", "zH"}, // {"weather", "sunny"} // }; // data["article_content"] = "这是unique.moe的第一篇测试用文章,也许今后不会有第二篇测试用文章了,所以请好好珍惜我!"; res.write_head(200); res.end(data.dump()); }); std::cout << "welcome to uniquehttp2, master." << std::endl; if (server.listen_and_serve(ec, tls, "0.0.0.0", port)) { std::cout << "my http port is " << port <<" , master." << std::endl; std::cerr << "error: " << ec.message() << std::endl; }else { std::cout << "server.listen_and_serv has undefined." << std::endl; } } <commit_msg>add http2 support<commit_after>#include <iostream> #include <boost/algorithm/string.hpp> #include <redox/redox.hpp> #include <json/json.hpp> #include <nghttp2/asio_http2_server.h> using namespace nghttp2::asio_http2; using namespace nghttp2::asio_http2::server; using json = nlohmann::json; generator_cb loading_templete(std::string path, const response &res) { auto fd = open(path.c_str(), O_RDONLY); if (fd == -1) { return 0; } return file_generator_from_fd(fd); } std::string getParamters(std::string uri, int count) { std::vector<std::string> strs; boost::split(strs, uri, boost::is_any_of("/")); return strs[count]; } int main(int argc, char *argv[]) { boost::system::error_code ec; boost::asio::ssl::context tls(boost::asio::ssl::context::sslv23); tls.use_private_key_file("../static/cert/privkey1.pem", boost::asio::ssl::context::pem); tls.use_certificate_chain_file("../static/cert/cert1.pem"); configure_tls_context_easy(ec, tls); http2 server; redox::Redox rdx; rdx.connect("172.17.0.3", 6379); //config std::string port = "443"; std::cout << "uniquehttp2 is loading..." << std::endl; server.handle("/", [](const request &req, const response &res) { auto body = loading_templete("../static/index.html", res); if (!body) { res.write_head(404); res.end(); } std::cout << "some one find me!\n" << std::endl; res.write_head(200); res.end(body); // header_map mmp = req.header(); // header_map::iterator pos; // for(pos = mmp.begin(); pos != mmp.end(); ++pos) { // std::cout << "value for " << pos->first <<" can be " << (pos->second).value << std::endl; // } // log: // accept */* // user-agent curl/7.53.1 // *** another workaround *** // // auto headers = req.header(); // for(const auto &header : headers) { // std::cout << "value for " << header.first <<" can be " << (header.second).value << std::endl; // } }); server.handle("/api/article/", [&rdx](const request &req, const response &res) { std::string article_id = getParamters(req.uri().path, 3); auto method = req.method(); if (method == "POST") { //data } json data; data["method"] = method; // if (!article_id) { // json articles; // std::vector<std::string> tips = {"author", "content", "date"}; // int total = stoi(rdx.get("article-count")); // for (int i = 0;i < total; i ++) { // json article; // std::string n = std::to_string(i + 1); // for (const auto& tip : tips) { // article[tip] = rdx.get("article-" + n + "-" + tip); // } // articles[i] = article; // } // data["data"] = articles; // data["total"] = rdx.get("article-count"); // data["msg"] = "hello " + rdx.get("hello"); // } // data["article_id"] = article_id; // data["article_header"] = "第一个篇章"; // data["article_info"] = { // {"date", "2017/4/6"}, // {"author", "zH"}, // {"weather", "sunny"} // }; // data["article_content"] = "这是unique.moe的第一篇测试用文章,也许今后不会有第二篇测试用文章了,所以请好好珍惜我!"; res.write_head(200); res.end(data.dump()); }); std::cout << "welcome to uniquehttp2, master." << std::endl; if (server.listen_and_serve(ec, tls, "0.0.0.0", port)) { std::cout << "my http port is " << port <<" , master." << std::endl; std::cerr << "error: " << ec.message() << std::endl; }else { std::cout << "server.listen_and_serv has undefined." << std::endl; } } <|endoftext|>
<commit_before><commit_msg>`Entity` destructor: do not print an error if the `Entity` has no name.<commit_after><|endoftext|>
<commit_before>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // #include <dlfcn.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include "icushim.h" // Define pointers to all the used ICU functions #define PER_FUNCTION_BLOCK(fn, lib) decltype(fn)* fn##_ptr; FOR_ALL_ICU_FUNCTIONS #undef PER_FUNCTION_BLOCK static void* libicuuc = nullptr; static void* libicui18n = nullptr; // .x.x.x, considering the max number of decimal digits for each component static const int MaxICUVersionStringLength = 33; #ifdef __APPLE__ bool FindICULibs(char* symbolName, char* symbolVersion) { #ifndef OSX_ICU_LIBRARY_PATH static_assert(false, "The ICU Library path is not defined"); #endif // OSX_ICU_LIBRARY_PATH // Usually OSX_ICU_LIBRARY_PATH is "/usr/lib/libicucore.dylib" libicuuc = dlopen(OSX_ICU_LIBRARY_PATH, RTLD_LAZY); if (libicuuc == nullptr) { return false; } // in OSX all ICU APIs exist in the same library libicucore.A.dylib libicui18n = libicuuc; return true; } #else // __APPLE__ // Version ranges to search for each of the three version components // The rationale for major version range is that we support versions higher or // equal to the version we are built against and less or equal to that version // plus 20 to give us enough headspace. The ICU seems to version about twice // a year. static const int MinICUVersion = U_ICU_VERSION_MAJOR_NUM; static const int MaxICUVersion = MinICUVersion + 20; static const int MinMinorICUVersion = 1; static const int MaxMinorICUVersion = 5; static const int MinSubICUVersion = 1; static const int MaxSubICUVersion = 5; // Get filename of an ICU library with the requested version in the name // There are three possible cases of the version components values: // 1. Only majorVer is not equal to -1 => result is baseFileName.majorver // 2. Only majorVer and minorVer are not equal to -1 => result is baseFileName.majorver.minorVer // 3. All components are not equal to -1 => result is baseFileName.majorver.minorVer.subver void GetVersionedLibFileName(const char* baseFileName, int majorVer, int minorVer, int subVer, char* result) { assert(majorVer != -1); int nameLen = sprintf(result, "%s.%d", baseFileName, majorVer); if (minorVer != -1) { nameLen += sprintf(result + nameLen, ".%d", minorVer); if (subVer != -1) { sprintf(result + nameLen, ".%d", subVer); } } } bool FindSymbolVersion(int majorVer, int minorVer, int subVer, char* symbolName, char* symbolVersion) { // Find out the format of the version string added to each symbol // First try just the unversioned symbol if (dlsym(libicuuc, "u_strlen") == nullptr) { // Now try just the _majorVer added sprintf(symbolVersion, "_%d", majorVer); sprintf(symbolName, "u_strlen%s", symbolVersion); if ((dlsym(libicuuc, symbolName) == nullptr) && (minorVer != -1)) { // Now try the _majorVer_minorVer added sprintf(symbolVersion, "_%d_%d", majorVer, minorVer); sprintf(symbolName, "u_strlen%s", symbolVersion); if ((dlsym(libicuuc, symbolName) == nullptr) && (subVer != -1)) { // Finally, try the _majorVer_minorVer_subVer added sprintf(symbolVersion, "_%d_%d_%d", majorVer, minorVer, subVer); sprintf(symbolName, "u_strlen%s", symbolVersion); if (dlsym(libicuuc, symbolName) == nullptr) { return false; } } } } return true; } // Try to open the necessary ICU libraries bool OpenICULibraries(int majorVer, int minorVer, int subVer, char* symbolName, char* symbolVersion) { char libicuucName[64]; char libicui18nName[64]; static_assert(sizeof("libicuuc.so") + MaxICUVersionStringLength <= sizeof(libicuucName), "The libicuucName is too small"); GetVersionedLibFileName("libicuuc.so", majorVer, minorVer, subVer, libicuucName); static_assert(sizeof("libicui18n.so") + MaxICUVersionStringLength <= sizeof(libicui18nName), "The libicui18nName is too small"); GetVersionedLibFileName("libicui18n.so", majorVer, minorVer, subVer, libicui18nName); libicuuc = dlopen(libicuucName, RTLD_LAZY); if (libicuuc != nullptr) { if (FindSymbolVersion(majorVer, minorVer, subVer, symbolName, symbolVersion)) { libicui18n = dlopen(libicui18nName, RTLD_LAZY); } if (libicui18n == nullptr) { dlclose(libicuuc); libicuuc = nullptr; } } return libicuuc != nullptr; } // Select libraries using the version override specified by the CLR_ICU_VERSION_OVERRIDE // environment variable. // The format of the string in this variable is majorVer[.minorVer[.subVer]] (the brackets // indicate optional parts). bool FindLibUsingOverride(char* symbolName, char* symbolVersion) { char* versionOverride = getenv("CLR_ICU_VERSION_OVERRIDE"); if (versionOverride != nullptr) { int first = -1; int second = -1; int third = -1; int matches = sscanf(versionOverride, "%d.%d.%d", &first, &second, &third); if (matches > 0) { if (OpenICULibraries(first, second, third, symbolName, symbolVersion)) { return true; } } } return false; } // Search for library files with names including the major version. bool FindLibWithMajorVersion(char* symbolName, char* symbolVersion) { // ICU packaging documentation (http://userguide.icu-project.org/packaging) // describes applications link against the major (e.g. libicuuc.so.54). // Select the version of ICU present at build time. if (OpenICULibraries(MinICUVersion, -1, -1, symbolName, symbolVersion)) { return true; } // Select the highest supported version of ICU present on the local machine for (int i = MaxICUVersion; i > MinICUVersion; i--) { if (OpenICULibraries(i, -1, -1, symbolName, symbolVersion)) { return true; } } return false; } // Select the highest supported version of ICU present on the local machine // Search for library files with names including the major and minor version. bool FindLibWithMajorMinorVersion(char* symbolName, char* symbolVersion) { for (int i = MaxICUVersion; i >= MinICUVersion; i--) { for (int j = MaxMinorICUVersion; j >= MinMinorICUVersion; j--) { if (OpenICULibraries(i, j, -1, symbolName, symbolVersion)) { return true; } } } return false; } // Select the highest supported version of ICU present on the local machine // Search for library files with names including the major, minor and sub version. bool FindLibWithMajorMinorSubVersion(char* symbolName, char* symbolVersion) { for (int i = MaxICUVersion; i >= MinICUVersion; i--) { for (int j = MaxMinorICUVersion; j >= MinMinorICUVersion; j--) { for (int k = MaxSubICUVersion; k >= MinSubICUVersion; k--) { if (OpenICULibraries(i, j, k, symbolName, symbolVersion)) { return true; } } } } return false; } bool FindICULibs(char* symbolName, char* symbolVersion) { return FindLibUsingOverride(symbolName, symbolVersion) || FindLibWithMajorVersion(symbolName, symbolVersion) || FindLibWithMajorMinorVersion(symbolName, symbolVersion) || FindLibWithMajorMinorSubVersion(symbolName, symbolVersion); } #endif // __APPLE__ // GlobalizationNative_LoadICU // This method get called from the managed side during the globalization initialization. // This method shouldn't get called at all if we are running in globalization invariant mode // return 0 if failed to load ICU and 1 otherwise extern "C" int32_t GlobalizationNative_LoadICU() { char symbolName[128]; char symbolVersion[MaxICUVersionStringLength + 1] = ""; if (!FindICULibs(symbolName, symbolVersion)) return 0; // Get pointers to all the ICU functions that are needed #define PER_FUNCTION_BLOCK(fn, lib) \ static_assert((sizeof(#fn) + MaxICUVersionStringLength + 1) <= sizeof(symbolName), "The symbolName is too small for symbol " #fn); \ sprintf(symbolName, #fn "%s", symbolVersion); \ fn##_ptr = (decltype(fn)*)dlsym(lib, symbolName); \ if (fn##_ptr == NULL) { fprintf(stderr, "Cannot get symbol %s from " #lib "\n", symbolName); abort(); } FOR_ALL_ICU_FUNCTIONS #undef PER_FUNCTION_BLOCK #ifdef __APPLE__ // libicui18n initialized with libicuuc so we null it to avoid double closing same handle libicui18n = nullptr; #endif // __APPLE__ return 1; } // GlobalizationNative_GetICUVersion // return the current loaded ICU version extern "C" int32_t GlobalizationNative_GetICUVersion() { int32_t version; u_getVersion((uint8_t *) &version); return version; } __attribute__((destructor)) void ShutdownICUShim() { if (libicuuc != nullptr) { dlclose(libicuuc); libicuuc = nullptr; } if (libicui18n != nullptr) { dlclose(libicui18n); libicui18n = nullptr; } }<commit_msg>Adding dlerr() diagnostics for libicu dlsym errors (#17454)<commit_after>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // #include <dlfcn.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include "icushim.h" // Define pointers to all the used ICU functions #define PER_FUNCTION_BLOCK(fn, lib) decltype(fn)* fn##_ptr; FOR_ALL_ICU_FUNCTIONS #undef PER_FUNCTION_BLOCK static void* libicuuc = nullptr; static void* libicui18n = nullptr; // .x.x.x, considering the max number of decimal digits for each component static const int MaxICUVersionStringLength = 33; #ifdef __APPLE__ bool FindICULibs(char* symbolName, char* symbolVersion) { #ifndef OSX_ICU_LIBRARY_PATH static_assert(false, "The ICU Library path is not defined"); #endif // OSX_ICU_LIBRARY_PATH // Usually OSX_ICU_LIBRARY_PATH is "/usr/lib/libicucore.dylib" libicuuc = dlopen(OSX_ICU_LIBRARY_PATH, RTLD_LAZY); if (libicuuc == nullptr) { return false; } // in OSX all ICU APIs exist in the same library libicucore.A.dylib libicui18n = libicuuc; return true; } #else // __APPLE__ // Version ranges to search for each of the three version components // The rationale for major version range is that we support versions higher or // equal to the version we are built against and less or equal to that version // plus 20 to give us enough headspace. The ICU seems to version about twice // a year. static const int MinICUVersion = U_ICU_VERSION_MAJOR_NUM; static const int MaxICUVersion = MinICUVersion + 20; static const int MinMinorICUVersion = 1; static const int MaxMinorICUVersion = 5; static const int MinSubICUVersion = 1; static const int MaxSubICUVersion = 5; // Get filename of an ICU library with the requested version in the name // There are three possible cases of the version components values: // 1. Only majorVer is not equal to -1 => result is baseFileName.majorver // 2. Only majorVer and minorVer are not equal to -1 => result is baseFileName.majorver.minorVer // 3. All components are not equal to -1 => result is baseFileName.majorver.minorVer.subver void GetVersionedLibFileName(const char* baseFileName, int majorVer, int minorVer, int subVer, char* result) { assert(majorVer != -1); int nameLen = sprintf(result, "%s.%d", baseFileName, majorVer); if (minorVer != -1) { nameLen += sprintf(result + nameLen, ".%d", minorVer); if (subVer != -1) { sprintf(result + nameLen, ".%d", subVer); } } } bool FindSymbolVersion(int majorVer, int minorVer, int subVer, char* symbolName, char* symbolVersion) { // Find out the format of the version string added to each symbol // First try just the unversioned symbol if (dlsym(libicuuc, "u_strlen") == nullptr) { // Now try just the _majorVer added sprintf(symbolVersion, "_%d", majorVer); sprintf(symbolName, "u_strlen%s", symbolVersion); if ((dlsym(libicuuc, symbolName) == nullptr) && (minorVer != -1)) { // Now try the _majorVer_minorVer added sprintf(symbolVersion, "_%d_%d", majorVer, minorVer); sprintf(symbolName, "u_strlen%s", symbolVersion); if ((dlsym(libicuuc, symbolName) == nullptr) && (subVer != -1)) { // Finally, try the _majorVer_minorVer_subVer added sprintf(symbolVersion, "_%d_%d_%d", majorVer, minorVer, subVer); sprintf(symbolName, "u_strlen%s", symbolVersion); if (dlsym(libicuuc, symbolName) == nullptr) { return false; } } } } return true; } // Try to open the necessary ICU libraries bool OpenICULibraries(int majorVer, int minorVer, int subVer, char* symbolName, char* symbolVersion) { char libicuucName[64]; char libicui18nName[64]; static_assert(sizeof("libicuuc.so") + MaxICUVersionStringLength <= sizeof(libicuucName), "The libicuucName is too small"); GetVersionedLibFileName("libicuuc.so", majorVer, minorVer, subVer, libicuucName); static_assert(sizeof("libicui18n.so") + MaxICUVersionStringLength <= sizeof(libicui18nName), "The libicui18nName is too small"); GetVersionedLibFileName("libicui18n.so", majorVer, minorVer, subVer, libicui18nName); libicuuc = dlopen(libicuucName, RTLD_LAZY); if (libicuuc != nullptr) { if (FindSymbolVersion(majorVer, minorVer, subVer, symbolName, symbolVersion)) { libicui18n = dlopen(libicui18nName, RTLD_LAZY); } if (libicui18n == nullptr) { dlclose(libicuuc); libicuuc = nullptr; } } return libicuuc != nullptr; } // Select libraries using the version override specified by the CLR_ICU_VERSION_OVERRIDE // environment variable. // The format of the string in this variable is majorVer[.minorVer[.subVer]] (the brackets // indicate optional parts). bool FindLibUsingOverride(char* symbolName, char* symbolVersion) { char* versionOverride = getenv("CLR_ICU_VERSION_OVERRIDE"); if (versionOverride != nullptr) { int first = -1; int second = -1; int third = -1; int matches = sscanf(versionOverride, "%d.%d.%d", &first, &second, &third); if (matches > 0) { if (OpenICULibraries(first, second, third, symbolName, symbolVersion)) { return true; } } } return false; } // Search for library files with names including the major version. bool FindLibWithMajorVersion(char* symbolName, char* symbolVersion) { // ICU packaging documentation (http://userguide.icu-project.org/packaging) // describes applications link against the major (e.g. libicuuc.so.54). // Select the version of ICU present at build time. if (OpenICULibraries(MinICUVersion, -1, -1, symbolName, symbolVersion)) { return true; } // Select the highest supported version of ICU present on the local machine for (int i = MaxICUVersion; i > MinICUVersion; i--) { if (OpenICULibraries(i, -1, -1, symbolName, symbolVersion)) { return true; } } return false; } // Select the highest supported version of ICU present on the local machine // Search for library files with names including the major and minor version. bool FindLibWithMajorMinorVersion(char* symbolName, char* symbolVersion) { for (int i = MaxICUVersion; i >= MinICUVersion; i--) { for (int j = MaxMinorICUVersion; j >= MinMinorICUVersion; j--) { if (OpenICULibraries(i, j, -1, symbolName, symbolVersion)) { return true; } } } return false; } // Select the highest supported version of ICU present on the local machine // Search for library files with names including the major, minor and sub version. bool FindLibWithMajorMinorSubVersion(char* symbolName, char* symbolVersion) { for (int i = MaxICUVersion; i >= MinICUVersion; i--) { for (int j = MaxMinorICUVersion; j >= MinMinorICUVersion; j--) { for (int k = MaxSubICUVersion; k >= MinSubICUVersion; k--) { if (OpenICULibraries(i, j, k, symbolName, symbolVersion)) { return true; } } } } return false; } bool FindICULibs(char* symbolName, char* symbolVersion) { return FindLibUsingOverride(symbolName, symbolVersion) || FindLibWithMajorVersion(symbolName, symbolVersion) || FindLibWithMajorMinorVersion(symbolName, symbolVersion) || FindLibWithMajorMinorSubVersion(symbolName, symbolVersion); } #endif // __APPLE__ // GlobalizationNative_LoadICU // This method get called from the managed side during the globalization initialization. // This method shouldn't get called at all if we are running in globalization invariant mode // return 0 if failed to load ICU and 1 otherwise extern "C" int32_t GlobalizationNative_LoadICU() { char symbolName[128]; char symbolVersion[MaxICUVersionStringLength + 1] = ""; if (!FindICULibs(symbolName, symbolVersion)) return 0; // Get pointers to all the ICU functions that are needed #define PER_FUNCTION_BLOCK(fn, lib) \ static_assert((sizeof(#fn) + MaxICUVersionStringLength + 1) <= sizeof(symbolName), "The symbolName is too small for symbol " #fn); \ sprintf(symbolName, #fn "%s", symbolVersion); \ fn##_ptr = (decltype(fn)*)dlsym(lib, symbolName); \ if (fn##_ptr == NULL) { fprintf(stderr, "Cannot get symbol %s from " #lib "\nError: %s\n", symbolName, dlerror()); abort(); } FOR_ALL_ICU_FUNCTIONS #undef PER_FUNCTION_BLOCK #ifdef __APPLE__ // libicui18n initialized with libicuuc so we null it to avoid double closing same handle libicui18n = nullptr; #endif // __APPLE__ return 1; } // GlobalizationNative_GetICUVersion // return the current loaded ICU version extern "C" int32_t GlobalizationNative_GetICUVersion() { int32_t version; u_getVersion((uint8_t *) &version); return version; } __attribute__((destructor)) void ShutdownICUShim() { if (libicuuc != nullptr) { dlclose(libicuuc); libicuuc = nullptr; } if (libicui18n != nullptr) { dlclose(libicui18n); libicui18n = nullptr; } }<|endoftext|>
<commit_before>/** * Ice multiplatform dynamic library loader. * * @copyright 2011 David Rebbe */ #include "ice_library.h" #include "ice_exception.h" #include <sstream> using namespace ice; Library::Library(std::string name) { m_name = name; #if (defined(_WIN32) || defined(__WIN32__)) #ifdef UNICODE int len = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, NULL, 0); if (len) { wchar_t* n = new wchar_t[len]; MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, n, len); m_lib = LoadLibrary(n); delete[] n; } else m_lib = NULL; #else m_lib = LoadLibrary(name.c_str()); #endif // UNICODE if (m_lib == NULL) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to open library: '" << name << "' with error code: #" << error; throw Exception(err.str()); } #else m_lib = dlopen(name.c_str(), RTLD_NOW); if (m_lib == NULL) { std::stringstream err; err << "Failed to open library '" << name << "': " << dlerror(); throw Exception(err.str()); } #endif } Library::~Library() { if (this->isLoaded()) { #if (defined(_WIN32) || defined(__WIN32__)) FreeLibrary(m_lib); #else dlclose(m_lib); #endif } } bool Library::isLoaded() const { return m_lib != NULL; } std::string Library::getPath(bool* okay) { if (okay) *okay = false; if (!isLoaded()) return m_name; #if (defined(_WIN32) || defined(__WIN32__)) TCHAR buffer[MAX_PATH] = {0}; int len = GetModuleFileName(m_lib, buffer, MAX_PATH); if (!len) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to get Library path: '" << m_name << "' with error code: #" << error; throw Exception(err.str()); } #ifdef UNICODE int length = WideCharToMultiByte(CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL); if (length) { char* temp = new char[MAX_PATH]; WideCharToMultiByte(CP_UTF8, 0, buffer, -1, temp, length, NULL, NULL); std::stringstream ss; ss << temp; if (okay) *okay = true; return ss.str(); } #else std::stringstream ss; ss << buffer; if (okay) *okay = true; return ss.str(); #endif // UNICODE #else // Linux doesn't really have a way to get the library path from the handle and // its recommended to use absolute paths when loading with dlopen(). #endif // WIN32 return m_name; } HMODULE const& Library::_library() const { return m_lib; } <commit_msg>Fixed memory leak in Library::getPath()<commit_after>/** * Ice multiplatform dynamic library loader. * * @copyright 2011 David Rebbe */ #include "ice_library.h" #include "ice_exception.h" #include <sstream> using namespace ice; Library::Library(std::string name) { m_name = name; #if (defined(_WIN32) || defined(__WIN32__)) #ifdef UNICODE int len = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, NULL, 0); if (len) { wchar_t* n = new wchar_t[len]; MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, n, len); m_lib = LoadLibrary(n); delete[] n; } else m_lib = NULL; #else m_lib = LoadLibrary(name.c_str()); #endif // UNICODE if (m_lib == NULL) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to open library: '" << name << "' with error code: #" << error; throw Exception(err.str()); } #else m_lib = dlopen(name.c_str(), RTLD_NOW); if (m_lib == NULL) { std::stringstream err; err << "Failed to open library '" << name << "': " << dlerror(); throw Exception(err.str()); } #endif } Library::~Library() { if (this->isLoaded()) { #if (defined(_WIN32) || defined(__WIN32__)) FreeLibrary(m_lib); #else dlclose(m_lib); #endif } } bool Library::isLoaded() const { return m_lib != NULL; } std::string Library::getPath(bool* okay) { if (okay) *okay = false; if (!isLoaded()) return m_name; #if (defined(_WIN32) || defined(__WIN32__)) TCHAR buffer[MAX_PATH] = {0}; int len = GetModuleFileName(m_lib, buffer, MAX_PATH); if (!len) { DWORD error = GetLastError(); std::stringstream err; err << "Failed to get Library path: '" << m_name << "' with error code: #" << error; throw Exception(err.str()); } #ifdef UNICODE int length = WideCharToMultiByte(CP_UTF8, 0, buffer, -1, NULL, 0, NULL, NULL); if (length) { char* temp = new char[MAX_PATH]; WideCharToMultiByte(CP_UTF8, 0, buffer, -1, temp, length, NULL, NULL); std::stringstream ss; ss << temp; if (okay) *okay = true; delete[] temp; temp = NULL; return ss.str(); } #else std::stringstream ss; ss << buffer; if (okay) *okay = true; return ss.str(); #endif // UNICODE #else // Linux doesn't really have a way to get the library path from the handle and // its recommended to use absolute paths when loading with dlopen(). #endif // WIN32 return m_name; } HMODULE const& Library::_library() const { return m_lib; } <|endoftext|>
<commit_before>/* * Copyright Andrey Semashev 2007 - 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file snprintf.hpp * \author Andrey Semashev * \date 20.02.2009 * * \brief This header is the Boost.Log library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html. */ #ifndef BOOST_LOG_DETAIL_SNPRINTF_HPP_INCLUDED_ #define BOOST_LOG_DETAIL_SNPRINTF_HPP_INCLUDED_ #include <cstdio> #include <cstdarg> #include <boost/log/detail/config.hpp> #ifdef BOOST_LOG_USE_WCHAR_T #include <cwchar> #endif // BOOST_LOG_USE_WCHAR_T #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace aux { #if !defined(_MSC_VER) // Standard-conforming compilers already have the correct snprintfs using ::snprintf; using ::vsnprintf; # ifdef BOOST_LOG_USE_WCHAR_T using ::swprintf; using ::vswprintf; # endif // BOOST_LOG_USE_WCHAR_T #else // !defined(_MSC_VER) # if _MSC_VER >= 1400 // MSVC 2005 and later provide the safe-CRT implementation of the conforming snprintf inline int vsnprintf(char* buf, std::size_t size, const char* format, std::va_list args) { return ::vsprintf_s(buf, size, format, args); } # ifdef BOOST_LOG_USE_WCHAR_T inline int vswprintf(wchar_t* buf, std::size_t size, const wchar_t* format, std::va_list args) { return ::vswprintf_s(buf, size, format, args); } # endif // BOOST_LOG_USE_WCHAR_T # else // _MSC_VER >= 1400 // MSVC prior to 2005 had a non-conforming extension _vsnprintf, that sometimes did not put a terminating '\0' inline int vsnprintf(char* buf, std::size_t size, const char* format, std::va_list args) { register int n = _vsnprintf(buf, size - 1, format, args); buf[size - 1] = '\0'; return n; } # ifdef BOOST_LOG_USE_WCHAR_T inline int vswprintf(wchar_t* buf, std::size_t size, const wchar_t* format, std::va_list args) { register int n = _vsnwprintf(buf, size - 1, format, args); buf[size - 1] = L'\0'; return n; } # endif // BOOST_LOG_USE_WCHAR_T # endif // _MSC_VER >= 1400 inline int snprintf(char* buf, std::size_t size, const char* format, ...) { std::va_list args; va_start(args, format); register int n = vsnprintf(buf, size, format, args); va_end(args); return n; } # ifdef BOOST_LOG_USE_WCHAR_T inline int swprintf(wchar_t* buf, std::size_t size, const wchar_t* format, ...) { std::va_list args; va_start(args, format); register int n = vswprintf(buf, size, format, args); va_end(args); return n; } # endif // BOOST_LOG_USE_WCHAR_T #endif // !defined(_MSC_VER) } // namespace aux BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_DETAIL_SNPRINTF_HPP_INCLUDED_ <commit_msg>Corrected included headers to fix compilation problems on Solaris.<commit_after>/* * Copyright Andrey Semashev 2007 - 2013. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file snprintf.hpp * \author Andrey Semashev * \date 20.02.2009 * * \brief This header is the Boost.Log library implementation, see the library documentation * at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html. */ #ifndef BOOST_LOG_DETAIL_SNPRINTF_HPP_INCLUDED_ #define BOOST_LOG_DETAIL_SNPRINTF_HPP_INCLUDED_ #include <stdio.h> #include <cstddef> #include <cstdarg> #include <boost/log/detail/config.hpp> #ifdef BOOST_LOG_USE_WCHAR_T #include <wchar.h> #endif // BOOST_LOG_USE_WCHAR_T #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace aux { #if !defined(_MSC_VER) // Standard-conforming compilers already have the correct snprintfs using ::snprintf; using ::vsnprintf; # ifdef BOOST_LOG_USE_WCHAR_T using ::swprintf; using ::vswprintf; # endif // BOOST_LOG_USE_WCHAR_T #else // !defined(_MSC_VER) # if _MSC_VER >= 1400 // MSVC 2005 and later provide the safe-CRT implementation of the conforming snprintf inline int vsnprintf(char* buf, std::size_t size, const char* format, std::va_list args) { return ::vsprintf_s(buf, size, format, args); } # ifdef BOOST_LOG_USE_WCHAR_T inline int vswprintf(wchar_t* buf, std::size_t size, const wchar_t* format, std::va_list args) { return ::vswprintf_s(buf, size, format, args); } # endif // BOOST_LOG_USE_WCHAR_T # else // _MSC_VER >= 1400 // MSVC prior to 2005 had a non-conforming extension _vsnprintf, that sometimes did not put a terminating '\0' inline int vsnprintf(char* buf, std::size_t size, const char* format, std::va_list args) { register int n = _vsnprintf(buf, size - 1, format, args); buf[size - 1] = '\0'; return n; } # ifdef BOOST_LOG_USE_WCHAR_T inline int vswprintf(wchar_t* buf, std::size_t size, const wchar_t* format, std::va_list args) { register int n = _vsnwprintf(buf, size - 1, format, args); buf[size - 1] = L'\0'; return n; } # endif // BOOST_LOG_USE_WCHAR_T # endif // _MSC_VER >= 1400 inline int snprintf(char* buf, std::size_t size, const char* format, ...) { std::va_list args; va_start(args, format); register int n = vsnprintf(buf, size, format, args); va_end(args); return n; } # ifdef BOOST_LOG_USE_WCHAR_T inline int swprintf(wchar_t* buf, std::size_t size, const wchar_t* format, ...) { std::va_list args; va_start(args, format); register int n = vswprintf(buf, size, format, args); va_end(args); return n; } # endif // BOOST_LOG_USE_WCHAR_T #endif // !defined(_MSC_VER) } // namespace aux BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_DETAIL_SNPRINTF_HPP_INCLUDED_ <|endoftext|>
<commit_before>#include "messages/messageref.hpp" #include "emotemanager.hpp" #include "settingsmanager.hpp" #include <QDebug> #define MARGIN_LEFT 8 #define MARGIN_RIGHT 8 #define MARGIN_TOP 4 #define MARGIN_BOTTOM 4 using namespace chatterino::messages; namespace chatterino { namespace messages { MessageRef::MessageRef(SharedMessage _message) : message(_message) , wordParts() { } Message *MessageRef::getMessage() { return this->message.get(); } int MessageRef::getHeight() const { return this->height; } // return true if redraw is required bool MessageRef::layout(int width, float dpiMultiplyer) { bool layoutRequired = false; // check if width changed bool widthChanged = width != this->currentLayoutWidth; layoutRequired |= widthChanged; this->currentLayoutWidth = width; // check if emotes changed bool imagesChanged = this->emoteGeneration != EmoteManager::instance->getGeneration(); layoutRequired |= imagesChanged; this->emoteGeneration = EmoteManager::instance->getGeneration(); // check if text changed bool textChanged = this->fontGeneration != FontManager::getInstance().getGeneration(); layoutRequired |= textChanged; this->fontGeneration = FontManager::getInstance().getGeneration(); // check if work mask changed bool wordMaskChanged = this->currentWordTypes != SettingsManager::getInstance().getWordTypeMask(); layoutRequired |= wordMaskChanged; this->currentWordTypes = SettingsManager::getInstance().getWordTypeMask(); // check if dpi changed bool dpiChanged = this->dpiMultiplyer != dpiMultiplyer; layoutRequired |= dpiChanged; this->dpiMultiplyer = dpiMultiplyer; imagesChanged |= dpiChanged; textChanged |= dpiChanged; // update word sizes if needed if (imagesChanged) { this->updateImageSizes(); } if (textChanged) { this->updateTextSizes(); } if (widthChanged) { this->buffer = nullptr; } // return if no layout is required if (!layoutRequired) { return false; } this->actuallyLayout(width); return true; } void MessageRef::actuallyLayout(int width) { auto &settings = SettingsManager::getInstance(); const int spaceWidth = 4; const int right = width - MARGIN_RIGHT; // clear word parts this->wordParts.clear(); // layout int x = MARGIN_LEFT; int y = MARGIN_TOP; int lineNumber = 0; int lineStart = 0; int lineHeight = 0; bool first = true; uint32_t flags = settings.getWordTypeMask(); // loop throught all the words and add them when a line is full for (auto it = this->message->getWords().begin(); it != this->message->getWords().end(); ++it) { Word &word = *it; // Check if given word is supposed to be rendered by comparing it to the current setting if ((word.getType() & flags) == Word::None) { continue; } int xOffset = 0, yOffset = 0; /// if (enableEmoteMargins) { /// if (word.isImage() && word.getImage().isHat()) { /// xOffset = -word.getWidth() + 2; /// } else { xOffset = word.getXOffset(); yOffset = word.getYOffset(); /// } /// } // word wrapping if (word.isText() && word.getWidth() + MARGIN_LEFT > right) { // align and end the current line alignWordParts(lineStart, lineHeight, width); y += lineHeight; int currentPartStart = 0; int currentLineWidth = 0; // go through the text, break text when it doesn't fit in the line anymore for (int i = 1; i <= word.getText().length(); i++) { currentLineWidth += word.getCharWidth(i - 1); if (currentLineWidth + MARGIN_LEFT > right) { // add the current line QString mid = word.getText().mid(currentPartStart, i - currentPartStart - 1); this->wordParts.push_back(WordPart(word, MARGIN_LEFT, y, currentLineWidth, word.getHeight(), lineNumber, mid, mid, false, currentPartStart)); y += word.getFontMetrics().height(); currentPartStart = i - 1; currentLineWidth = 0; lineNumber++; } } QString mid(word.getText().mid(currentPartStart)); currentLineWidth = word.getFontMetrics().width(mid); this->wordParts.push_back(WordPart(word, MARGIN_LEFT, y - word.getHeight(), currentLineWidth, word.getHeight(), lineNumber, mid, mid, true, currentPartStart)); x = currentLineWidth + MARGIN_LEFT + spaceWidth; lineHeight = word.getHeight(); lineStart = this->wordParts.size() - 1; first = false; } // fits in the current line else if (first || x + word.getWidth() + xOffset <= right) { this->wordParts.push_back( WordPart(word, x, y - word.getHeight(), lineNumber, word.getCopyText())); x += word.getWidth() + xOffset; x += spaceWidth; lineHeight = std::max(word.getHeight(), lineHeight); first = false; } // doesn't fit in the line else { // align and end the current line alignWordParts(lineStart, lineHeight, width); y += lineHeight; lineNumber++; this->wordParts.push_back( WordPart(word, MARGIN_LEFT, y - word.getHeight(), lineNumber, word.getCopyText())); lineStart = this->wordParts.size() - 1; lineHeight = word.getHeight(); x = word.getWidth() + MARGIN_LEFT; x += spaceWidth; } } // align and end the current line alignWordParts(lineStart, lineHeight, width); // update height int oldHeight = this->height; this->height = y + lineHeight + MARGIN_BOTTOM; // invalidate buffer if height changed if (oldHeight != this->height) { this->buffer = nullptr; } updateBuffer = true; } void MessageRef::updateTextSizes() { for (auto &word : this->message->getWords()) { if (!word.isText()) continue; QFontMetrics &metrics = word.getFontMetrics(); word.setSize((int)(metrics.width(word.getText()) * this->dpiMultiplyer), (int)(metrics.height() * this->dpiMultiplyer)); } } void MessageRef::updateImageSizes() { const int mediumTextLineHeight = FontManager::getInstance().getFontMetrics(FontManager::Medium).height(); const qreal emoteScale = SettingsManager::getInstance().emoteScale.get() * this->dpiMultiplyer; const bool scaleEmotesByLineHeight = SettingsManager::getInstance().scaleEmotesByLineHeight.get(); for (auto &word : this->message->getWords()) { if (!word.isImage()) continue; auto &image = word.getImage(); qreal w = image.getWidth(); qreal h = image.getHeight(); if (scaleEmotesByLineHeight) { word.setSize(w * mediumTextLineHeight / h * emoteScale, mediumTextLineHeight * emoteScale); } else { word.setSize(w * image.getScale() * emoteScale, h * image.getScale() * emoteScale); } } } const std::vector<WordPart> &MessageRef::getWordParts() const { return this->wordParts; } void MessageRef::alignWordParts(int lineStart, int lineHeight, int width) { int xOffset = 0; if (this->message->centered && this->wordParts.size() > 0) { xOffset = (width - this->wordParts.at(this->wordParts.size() - 1).getRight()) / 2; } for (size_t i = lineStart; i < this->wordParts.size(); i++) { WordPart &wordPart2 = this->wordParts.at(i); wordPart2.setPosition(wordPart2.getX() + xOffset, wordPart2.getY() + lineHeight); } } const Word *MessageRef::tryGetWordPart(QPoint point) { // go through all words and return the first one that contains the point. for (WordPart &wordPart : this->wordParts) { if (wordPart.getRect().contains(point)) { return &wordPart.getWord(); } } return nullptr; } // XXX(pajlada): This is probably not the optimal way to calculate this int MessageRef::getLastCharacterIndex() const { // find out in which line the cursor is int lineNumber = 0, lineStart = 0, lineEnd = 0; for (size_t i = 0; i < this->wordParts.size(); i++) { const WordPart &part = this->wordParts[i]; if (part.getLineNumber() != lineNumber) { lineStart = i; lineNumber = part.getLineNumber(); } lineEnd = i + 1; } // count up to the cursor int index = 0; for (int i = 0; i < lineStart; i++) { const WordPart &part = this->wordParts[i]; index += part.getWord().isImage() ? 2 : part.getText().length() + 1; } for (int i = lineStart; i < lineEnd; i++) { const WordPart &part = this->wordParts[i]; index += part.getCharacterLength(); } return index; } int MessageRef::getSelectionIndex(QPoint position) { if (this->wordParts.size() == 0) { return 0; } // find out in which line the cursor is int lineNumber = 0, lineStart = 0, lineEnd = 0; for (size_t i = 0; i < this->wordParts.size(); i++) { WordPart &part = this->wordParts[i]; if (part.getLineNumber() != 0 && position.y() < part.getY()) { break; } if (part.getLineNumber() != lineNumber) { lineStart = i; lineNumber = part.getLineNumber(); } lineEnd = i + 1; } // count up to the cursor int index = 0; for (int i = 0; i < lineStart; i++) { WordPart &part = this->wordParts[i]; index += part.getWord().isImage() ? 2 : part.getText().length() + 1; } for (int i = lineStart; i < lineEnd; i++) { WordPart &part = this->wordParts[i]; // curser is left of the word part if (position.x() < part.getX()) { break; } // cursor is right of the word part if (position.x() > part.getX() + part.getWidth()) { index += part.getCharacterLength(); continue; } // cursor is over the word part if (part.getWord().isImage()) { if (position.x() - part.getX() > part.getWidth() / 2) { index++; } } else { // TODO: use word.getCharacterWidthCache(); auto text = part.getText(); int x = part.getX(); for (int j = 0; j < text.length(); j++) { if (x > position.x()) { break; } index++; x = part.getX() + part.getWord().getFontMetrics().width(text, j + 1); } } break; } return index; } } // namespace messages } // namespace chatterino <commit_msg>fixed msgs not layouting after changing settings<commit_after>#include "messages/messageref.hpp" #include "emotemanager.hpp" #include "settingsmanager.hpp" #include <QDebug> #define MARGIN_LEFT 8 #define MARGIN_RIGHT 8 #define MARGIN_TOP 4 #define MARGIN_BOTTOM 4 using namespace chatterino::messages; namespace chatterino { namespace messages { MessageRef::MessageRef(SharedMessage _message) : message(_message) , wordParts() { } Message *MessageRef::getMessage() { return this->message.get(); } int MessageRef::getHeight() const { return this->height; } // return true if redraw is required bool MessageRef::layout(int width, float dpiMultiplyer) { bool layoutRequired = false; // check if width changed bool widthChanged = width != this->currentLayoutWidth; layoutRequired |= widthChanged; this->currentLayoutWidth = width; // check if emotes changed bool imagesChanged = this->emoteGeneration != EmoteManager::instance->getGeneration(); layoutRequired |= imagesChanged; this->emoteGeneration = EmoteManager::instance->getGeneration(); // check if text changed bool textChanged = this->fontGeneration != FontManager::getInstance().getGeneration(); layoutRequired |= textChanged; this->fontGeneration = FontManager::getInstance().getGeneration(); // check if work mask changed bool wordMaskChanged = this->currentWordTypes != SettingsManager::getInstance().getWordTypeMask(); layoutRequired |= wordMaskChanged; this->currentWordTypes = SettingsManager::getInstance().getWordTypeMask(); // check if dpi changed bool dpiChanged = this->dpiMultiplyer != dpiMultiplyer; layoutRequired |= dpiChanged; this->dpiMultiplyer = dpiMultiplyer; imagesChanged |= dpiChanged; textChanged |= dpiChanged; // update word sizes if needed if (imagesChanged) { this->updateImageSizes(); } if (textChanged) { this->updateTextSizes(); } if (widthChanged || wordMaskChanged) { this->buffer = nullptr; } // return if no layout is required if (!layoutRequired) { return false; } this->actuallyLayout(width); return true; } void MessageRef::actuallyLayout(int width) { auto &settings = SettingsManager::getInstance(); const int spaceWidth = 4; const int right = width - MARGIN_RIGHT; // clear word parts this->wordParts.clear(); // layout int x = MARGIN_LEFT; int y = MARGIN_TOP; int lineNumber = 0; int lineStart = 0; int lineHeight = 0; bool first = true; uint32_t flags = settings.getWordTypeMask(); // loop throught all the words and add them when a line is full for (auto it = this->message->getWords().begin(); it != this->message->getWords().end(); ++it) { Word &word = *it; // Check if given word is supposed to be rendered by comparing it to the current setting if ((word.getType() & flags) == Word::None) { continue; } int xOffset = 0, yOffset = 0; /// if (enableEmoteMargins) { /// if (word.isImage() && word.getImage().isHat()) { /// xOffset = -word.getWidth() + 2; /// } else { xOffset = word.getXOffset(); yOffset = word.getYOffset(); /// } /// } // word wrapping if (word.isText() && word.getWidth() + MARGIN_LEFT > right) { // align and end the current line alignWordParts(lineStart, lineHeight, width); y += lineHeight; int currentPartStart = 0; int currentLineWidth = 0; // go through the text, break text when it doesn't fit in the line anymore for (int i = 1; i <= word.getText().length(); i++) { currentLineWidth += word.getCharWidth(i - 1); if (currentLineWidth + MARGIN_LEFT > right) { // add the current line QString mid = word.getText().mid(currentPartStart, i - currentPartStart - 1); this->wordParts.push_back(WordPart(word, MARGIN_LEFT, y, currentLineWidth, word.getHeight(), lineNumber, mid, mid, false, currentPartStart)); y += word.getFontMetrics().height(); currentPartStart = i - 1; currentLineWidth = 0; lineNumber++; } } QString mid(word.getText().mid(currentPartStart)); currentLineWidth = word.getFontMetrics().width(mid); this->wordParts.push_back(WordPart(word, MARGIN_LEFT, y - word.getHeight(), currentLineWidth, word.getHeight(), lineNumber, mid, mid, true, currentPartStart)); x = currentLineWidth + MARGIN_LEFT + spaceWidth; lineHeight = word.getHeight(); lineStart = this->wordParts.size() - 1; first = false; } // fits in the current line else if (first || x + word.getWidth() + xOffset <= right) { this->wordParts.push_back( WordPart(word, x, y - word.getHeight(), lineNumber, word.getCopyText())); x += word.getWidth() + xOffset; x += spaceWidth; lineHeight = std::max(word.getHeight(), lineHeight); first = false; } // doesn't fit in the line else { // align and end the current line alignWordParts(lineStart, lineHeight, width); y += lineHeight; lineNumber++; this->wordParts.push_back( WordPart(word, MARGIN_LEFT, y - word.getHeight(), lineNumber, word.getCopyText())); lineStart = this->wordParts.size() - 1; lineHeight = word.getHeight(); x = word.getWidth() + MARGIN_LEFT; x += spaceWidth; } } // align and end the current line alignWordParts(lineStart, lineHeight, width); // update height int oldHeight = this->height; this->height = y + lineHeight + MARGIN_BOTTOM; // invalidate buffer if height changed if (oldHeight != this->height) { this->buffer = nullptr; } updateBuffer = true; } void MessageRef::updateTextSizes() { for (auto &word : this->message->getWords()) { if (!word.isText()) continue; QFontMetrics &metrics = word.getFontMetrics(); word.setSize((int)(metrics.width(word.getText()) * this->dpiMultiplyer), (int)(metrics.height() * this->dpiMultiplyer)); } } void MessageRef::updateImageSizes() { const int mediumTextLineHeight = FontManager::getInstance().getFontMetrics(FontManager::Medium).height(); const qreal emoteScale = SettingsManager::getInstance().emoteScale.get() * this->dpiMultiplyer; const bool scaleEmotesByLineHeight = SettingsManager::getInstance().scaleEmotesByLineHeight.get(); for (auto &word : this->message->getWords()) { if (!word.isImage()) continue; auto &image = word.getImage(); qreal w = image.getWidth(); qreal h = image.getHeight(); if (scaleEmotesByLineHeight) { word.setSize(w * mediumTextLineHeight / h * emoteScale, mediumTextLineHeight * emoteScale); } else { word.setSize(w * image.getScale() * emoteScale, h * image.getScale() * emoteScale); } } } const std::vector<WordPart> &MessageRef::getWordParts() const { return this->wordParts; } void MessageRef::alignWordParts(int lineStart, int lineHeight, int width) { int xOffset = 0; if (this->message->centered && this->wordParts.size() > 0) { xOffset = (width - this->wordParts.at(this->wordParts.size() - 1).getRight()) / 2; } for (size_t i = lineStart; i < this->wordParts.size(); i++) { WordPart &wordPart2 = this->wordParts.at(i); wordPart2.setPosition(wordPart2.getX() + xOffset, wordPart2.getY() + lineHeight); } } const Word *MessageRef::tryGetWordPart(QPoint point) { // go through all words and return the first one that contains the point. for (WordPart &wordPart : this->wordParts) { if (wordPart.getRect().contains(point)) { return &wordPart.getWord(); } } return nullptr; } // XXX(pajlada): This is probably not the optimal way to calculate this int MessageRef::getLastCharacterIndex() const { // find out in which line the cursor is int lineNumber = 0, lineStart = 0, lineEnd = 0; for (size_t i = 0; i < this->wordParts.size(); i++) { const WordPart &part = this->wordParts[i]; if (part.getLineNumber() != lineNumber) { lineStart = i; lineNumber = part.getLineNumber(); } lineEnd = i + 1; } // count up to the cursor int index = 0; for (int i = 0; i < lineStart; i++) { const WordPart &part = this->wordParts[i]; index += part.getWord().isImage() ? 2 : part.getText().length() + 1; } for (int i = lineStart; i < lineEnd; i++) { const WordPart &part = this->wordParts[i]; index += part.getCharacterLength(); } return index; } int MessageRef::getSelectionIndex(QPoint position) { if (this->wordParts.size() == 0) { return 0; } // find out in which line the cursor is int lineNumber = 0, lineStart = 0, lineEnd = 0; for (size_t i = 0; i < this->wordParts.size(); i++) { WordPart &part = this->wordParts[i]; if (part.getLineNumber() != 0 && position.y() < part.getY()) { break; } if (part.getLineNumber() != lineNumber) { lineStart = i; lineNumber = part.getLineNumber(); } lineEnd = i + 1; } // count up to the cursor int index = 0; for (int i = 0; i < lineStart; i++) { WordPart &part = this->wordParts[i]; index += part.getWord().isImage() ? 2 : part.getText().length() + 1; } for (int i = lineStart; i < lineEnd; i++) { WordPart &part = this->wordParts[i]; // curser is left of the word part if (position.x() < part.getX()) { break; } // cursor is right of the word part if (position.x() > part.getX() + part.getWidth()) { index += part.getCharacterLength(); continue; } // cursor is over the word part if (part.getWord().isImage()) { if (position.x() - part.getX() > part.getWidth() / 2) { index++; } } else { // TODO: use word.getCharacterWidthCache(); auto text = part.getText(); int x = part.getX(); for (int j = 0; j < text.length(); j++) { if (x > position.x()) { break; } index++; x = part.getX() + part.getWord().getFontMetrics().width(text, j + 1); } } break; } return index; } } // namespace messages } // namespace chatterino <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief Arithmetic テンプレート @n ※テキストの数式を展開して、計算結果を得る。@n 演算式解析 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2015, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include "common/bitset.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief Arithmetic クラス @param[in] VTYPE 基本型 @param[in] SYMBOL シンボルクラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <typename VTYPE> struct basic_arith { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief エラー・タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class error : uint8_t { fatal, ///< エラー number_fatal, ///< 数字の変換に関するエラー zero_divide, ///< 0除算エラー binary_fatal, ///< 2進データの変換に関するエラー octal_fatal, ///< 8進データの変換に関するエラー hexdecimal_fatal, ///< 16進データの変換に関するエラー num_fatal, ///< 数値の変換に関するエラー symbol_fatal, ///< シンボルデータの変換に関するエラー }; typedef bitset<uint16_t, error> error_t; private: const char* tx_; char ch_; error_t error_; VTYPE value_; void skip_space_() { while(ch_ == ' ' || ch_ == '\t') { ch_ = *tx_++; } } VTYPE number_() { bool inv = false; /// bool neg = false; bool point = false; uint32_t v = 0; uint32_t fp = 0; uint32_t fs = 1; skip_space_(); // 符号、反転の判定 if(ch_ == '-') { inv = true; ch_ = *tx_++; } else if(ch_ == '+') { ch_ = *tx_++; // } else if(ch_ == '!' || ch_ == '~') { // neg = true; // ch_ = *tx_++; } skip_space_(); if(ch_ == '(') { v = factor_(); } else { skip_space_(); // if(ch_ >= 'A' && ch_ <= 'Z') symbol = true; // else if(ch_ >= 'a' && ch_ <= 'z') symbol = true; // else if(ch_ == '_' || ch_ == '?') symbol = true; while(ch_ != 0) { if(ch_ == '+') break; else if(ch_ == '-') break; else if(ch_ == '*') break; else if(ch_ == '/') break; else if(ch_ == '&') break; else if(ch_ == '^') break; else if(ch_ == '|') break; else if(ch_ == '%') break; else if(ch_ == ')') break; else if(ch_ == '<') break; else if(ch_ == '>') break; else if(ch_ == '!') break; else if(ch_ == '~') break; else if(ch_ == '.') { if(point) { error_.set(error::fatal); break; } else { point = true; } } else if(ch_ >= '0' && ch_ <= '9') { if(point) { fp *= 10; fp += ch_ - '0'; fs *= 10; } else { v *= 10; v += ch_ - '0'; } } ch_ = *tx_++; } #if 0 if(symbol) { symbol_map_cit cit = symbol_.find(sym); if(cit != symbol_.end()) { v = (*cit).second; } else { error_.set(error::symbol_fatal); } } #endif } if(inv) { v = -v; } /// if(neg) { v = ~v; } if(point) { return static_cast<VTYPE>(v) + static_cast<VTYPE>(fp) / static_cast<VTYPE>(fs); } else { return static_cast<VTYPE>(v); } } VTYPE factor_() { VTYPE v = 0; if(ch_ == '(') { ch_ = *tx_++; v = expression_(); if(ch_ == ')') { ch_ = *tx_++; } else { error_.set(error::fatal); } } else { v = number_(); } return v; } VTYPE term_() { VTYPE v = factor_(); VTYPE tmp; while(error_() == 0) { switch(ch_) { case ' ': case '\t': ch_ = *tx_++; break; case '*': ch_ = *tx_++; v *= factor_(); break; case '%': ch_ = *tx_++; tmp = factor_(); if(tmp == 0) { error_.set(error::zero_divide); break; } v /= tmp; break; case '/': ch_ = *tx_++; if(ch_ == '/') { ch_ = *tx_++; tmp = factor_(); if(tmp == 0) { error_.set(error::zero_divide); break; } v %= tmp; } else { tmp = factor_(); if(tmp == 0) { error_.set(error::zero_divide); break; } v /= tmp; } break; case '<': ch_ = *tx_++; if(ch_ == '<') { ch_ = *tx_++; v <<= factor_(); } else { error_.set(error::fatal); } break; case '>': ch_ = *tx_++; if(ch_ == '>') { ch_ = *tx_++; v <<= factor_(); } else { error_.set(error::fatal); } break; default: return v; break; } } return v; } VTYPE expression_() { VTYPE v = term_(); while(error_() == 0) { switch(ch_) { case ' ': case '\t': ch_ = *tx_++; break; case '+': ch_ = *tx_++; v += term_(); break; case '-': ch_ = *tx_++; v -= term_(); break; case '&': ch_ = *tx_++; v &= term_(); break; case '^': ch_ = *tx_++; v ^= term_(); break; case '|': ch_ = *tx_++; v |= term_(); break; default: return v; break; } } return v; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// basic_arith() : tx_(nullptr), ch_(0), error_(), value_(0) { } //-----------------------------------------------------------------// /*! @brief 解析を開始 @param[in] text 解析テキスト @return 文法にエラーがあった場合、「false」 */ //-----------------------------------------------------------------// bool analize(const char* text) { if(text == nullptr) { error_.set(error::fatal); return false; } tx_ = text; error_.clear(); ch_ = *tx_++; if(ch_ != 0) { value_ = expression_(); } else { error_.set(error::fatal); } if(error_() != 0) { return false; } else if(ch_ != 0) { error_.set(error::fatal); return false; } return true; } //-----------------------------------------------------------------// /*! @brief エラーを受け取る @return エラー */ //-----------------------------------------------------------------// const error_t& get_error() const { return error_; } //-----------------------------------------------------------------// /*! @brief 結果を取得 @return 結果 */ //-----------------------------------------------------------------// VTYPE get() const { return value_; } //-----------------------------------------------------------------// /*! @brief () で結果を取得 @return 結果 */ //-----------------------------------------------------------------// VTYPE operator() () const { return value_; } }; } <commit_msg>Update: cleanup<commit_after>#pragma once //=====================================================================// /*! @file @brief Arithmetic テンプレート @n ※テキストの数式を展開して、計算結果を得る。@n 演算式解析 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2015, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include <cstdint> #include "common/bitset.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief Arithmetic クラス @param[in] VTYPE 基本型 @param[in] SYMBOL シンボルクラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <typename VTYPE> struct basic_arith { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief エラー・タイプ */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class error : uint8_t { fatal, ///< エラー number_fatal, ///< 数字の変換に関するエラー zero_divide, ///< 0除算エラー binary_fatal, ///< 2進データの変換に関するエラー octal_fatal, ///< 8進データの変換に関するエラー hexdecimal_fatal, ///< 16進データの変換に関するエラー num_fatal, ///< 数値の変換に関するエラー symbol_fatal, ///< シンボルデータの変換に関するエラー }; typedef bitset<uint16_t, error> error_t; private: const char* tx_; char ch_; error_t error_; VTYPE value_; void skip_space_() { while(ch_ == ' ' || ch_ == '\t') { ch_ = *tx_++; } } VTYPE number_() { bool inv = false; /// bool neg = false; bool point = false; uint32_t v = 0; uint32_t fp = 0; uint32_t fs = 1; skip_space_(); // 符号、反転の判定 if(ch_ == '-') { inv = true; ch_ = *tx_++; } else if(ch_ == '+') { ch_ = *tx_++; // } else if(ch_ == '!' || ch_ == '~') { // neg = true; // ch_ = *tx_++; } skip_space_(); if(ch_ == '(') { v = factor_(); } else { skip_space_(); // if(ch_ >= 'A' && ch_ <= 'Z') symbol = true; // else if(ch_ >= 'a' && ch_ <= 'z') symbol = true; // else if(ch_ == '_' || ch_ == '?') symbol = true; while(ch_ != 0) { if(ch_ == '+') break; else if(ch_ == '-') break; else if(ch_ == '*') break; else if(ch_ == '/') break; // else if(ch_ == '&') break; // else if(ch_ == '^') break; // else if(ch_ == '|') break; // else if(ch_ == '%') break; else if(ch_ == ')') break; // else if(ch_ == '<') break; // else if(ch_ == '>') break; // else if(ch_ == '!') break; // else if(ch_ == '~') break; else if(ch_ == '.') { if(point) { error_.set(error::fatal); break; } else { point = true; } } else if(ch_ >= '0' && ch_ <= '9') { if(point) { fp *= 10; fp += ch_ - '0'; fs *= 10; } else { v *= 10; v += ch_ - '0'; } } ch_ = *tx_++; } #if 0 if(symbol) { symbol_map_cit cit = symbol_.find(sym); if(cit != symbol_.end()) { v = (*cit).second; } else { error_.set(error::symbol_fatal); } } #endif } if(inv) { v = -v; } /// if(neg) { v = ~v; } if(point) { return static_cast<VTYPE>(v) + static_cast<VTYPE>(fp) / static_cast<VTYPE>(fs); } else { return static_cast<VTYPE>(v); } } VTYPE factor_() { VTYPE v = 0; if(ch_ == '(') { ch_ = *tx_++; v = expression_(); if(ch_ == ')') { ch_ = *tx_++; } else { error_.set(error::fatal); } } else { v = number_(); } return v; } VTYPE term_() { VTYPE v = factor_(); VTYPE tmp; while(error_() == 0) { switch(ch_) { case ' ': case '\t': ch_ = *tx_++; break; case '*': ch_ = *tx_++; v *= factor_(); break; #if 0 case '%': ch_ = *tx_++; tmp = factor_(); if(tmp == 0) { error_.set(error::zero_divide); break; } v %= tmp; break; #endif case '/': ch_ = *tx_++; if(ch_ == '/') { ch_ = *tx_++; tmp = factor_(); if(tmp == 0) { error_.set(error::zero_divide); break; } /// v %= tmp; } else { tmp = factor_(); if(tmp == 0) { error_.set(error::zero_divide); break; } v /= tmp; } break; #if 0 case '<': ch_ = *tx_++; if(ch_ == '<') { ch_ = *tx_++; v <<= factor_(); } else { error_.set(error::fatal); } break; case '>': ch_ = *tx_++; if(ch_ == '>') { ch_ = *tx_++; v <<= factor_(); } else { error_.set(error::fatal); } break; #endif default: return v; break; } } return v; } VTYPE expression_() { VTYPE v = term_(); while(error_() == 0) { switch(ch_) { case ' ': case '\t': ch_ = *tx_++; break; case '+': ch_ = *tx_++; v += term_(); break; case '-': ch_ = *tx_++; v -= term_(); break; #if 0 case '&': ch_ = *tx_++; v &= term_(); break; case '^': ch_ = *tx_++; v ^= term_(); break; case '|': ch_ = *tx_++; v |= term_(); break; #endif default: return v; break; } } return v; } public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// basic_arith() : tx_(nullptr), ch_(0), error_(), value_(0) { } //-----------------------------------------------------------------// /*! @brief 解析を開始 @param[in] text 解析テキスト @return 文法にエラーがあった場合、「false」 */ //-----------------------------------------------------------------// bool analize(const char* text) { if(text == nullptr) { error_.set(error::fatal); return false; } tx_ = text; error_.clear(); ch_ = *tx_++; if(ch_ != 0) { value_ = expression_(); } else { error_.set(error::fatal); } if(error_() != 0) { return false; } else if(ch_ != 0) { error_.set(error::fatal); return false; } return true; } //-----------------------------------------------------------------// /*! @brief エラーを受け取る @return エラー */ //-----------------------------------------------------------------// const error_t& get_error() const { return error_; } //-----------------------------------------------------------------// /*! @brief 結果を取得 @return 結果 */ //-----------------------------------------------------------------// VTYPE get() const { return value_; } //-----------------------------------------------------------------// /*! @brief () で結果を取得 @return 結果 */ //-----------------------------------------------------------------// VTYPE operator() () const { return value_; } }; } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mhome. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <assert.h> #include "stubbase.h" #include "methodcall.h" QList<MethodCall *> StubBase::stubCallHistory() const { return _stubCallHistory; } void StubBase::stubReset() const { foreach(ParameterBase * p, _stubReturnValues) { delete p; } foreach(MethodCall * p, _stubCallHistory) { delete p; } _stubReturnValues.clear(); _stubCallCounts.clear(); _stubCallHistory.clear(); } int StubBase::stubCallCount(const QString &method) const { return _stubCallCounts[method]; } void StubBase::stubMethodEntered(const QString &methodName, QList<ParameterBase *> params) const { MethodCall *method = new MethodCall(methodName, params, stubReturnValue(methodName)); _stubCallCounts[methodName] = _stubCallCounts[methodName] + 1; _stubCallHistory.append(method); } void StubBase::stubMethodEntered(const QString &methodName) const { MethodCall *method = new MethodCall(methodName, QList<ParameterBase *>(), stubReturnValue(methodName)); _stubCallCounts[methodName] = _stubCallCounts[methodName] + 1; _stubCallHistory.append(method); } ParameterBase *StubBase::stubReturnValue(const QString &methodName) const { ParameterBase *retVal = NULL; if (_stubReturnValues.contains(methodName)) retVal = _stubReturnValues[methodName]; return retVal; } StubBase::~StubBase() { stubReset(); } MethodCall &StubBase::stubLastCall() const { return *(_stubCallHistory.last()); } MethodCall &StubBase::stubLastCallTo(const QString &method) const { for (int i = _stubCallHistory.count() - 1; i >= 0; i--) { if (_stubCallHistory.at(i)->name() == method) { return *(_stubCallHistory.at(i)); } } qDebug() << "StubBase::lastCallTo: call not found to:" << method; return *((MethodCall *)0); } QList<MethodCall *> StubBase::stubCallsTo(const QString &method) const { QList<MethodCall *> calls; for (int i = 0; i < _stubCallHistory.count(); i++) { if (_stubCallHistory.at(i)->name() == method) { calls.append(_stubCallHistory.at(i)); } } return calls; } <commit_msg>Changes: make fatal error a fatal error<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mhome. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <assert.h> #include "stubbase.h" #include "methodcall.h" QList<MethodCall *> StubBase::stubCallHistory() const { return _stubCallHistory; } void StubBase::stubReset() const { foreach(ParameterBase * p, _stubReturnValues) { delete p; } foreach(MethodCall * p, _stubCallHistory) { delete p; } _stubReturnValues.clear(); _stubCallCounts.clear(); _stubCallHistory.clear(); } int StubBase::stubCallCount(const QString &method) const { return _stubCallCounts[method]; } void StubBase::stubMethodEntered(const QString &methodName, QList<ParameterBase *> params) const { MethodCall *method = new MethodCall(methodName, params, stubReturnValue(methodName)); _stubCallCounts[methodName] = _stubCallCounts[methodName] + 1; _stubCallHistory.append(method); } void StubBase::stubMethodEntered(const QString &methodName) const { MethodCall *method = new MethodCall(methodName, QList<ParameterBase *>(), stubReturnValue(methodName)); _stubCallCounts[methodName] = _stubCallCounts[methodName] + 1; _stubCallHistory.append(method); } ParameterBase *StubBase::stubReturnValue(const QString &methodName) const { ParameterBase *retVal = NULL; if (_stubReturnValues.contains(methodName)) retVal = _stubReturnValues[methodName]; return retVal; } StubBase::~StubBase() { stubReset(); } MethodCall &StubBase::stubLastCall() const { return *(_stubCallHistory.last()); } MethodCall &StubBase::stubLastCallTo(const QString &method) const { int i = _stubCallHistory.count() - 1; bool found = false; for (; i >= 0; i--) { if (_stubCallHistory.at(i)->name() == method) { found = true; break; } } if (!found) { QString msg = QString("StubBase::") + __func__ + ": no calls found to '" + method + "'"; qFatal("%s", qPrintable(msg)); } return *(_stubCallHistory.at(i)); } QList<MethodCall *> StubBase::stubCallsTo(const QString &method) const { QList<MethodCall *> calls; for (int i = 0; i < _stubCallHistory.count(); i++) { if (_stubCallHistory.at(i)->name() == method) { calls.append(_stubCallHistory.at(i)); } } return calls; } <|endoftext|>
<commit_before>#ifndef BLOCK_MAP_HPP_ #define BLOCK_MAP_HPP_ #include "clotho/powerset/normalized_key.hpp" #include "clotho/powerset/next_available_order_tag.hpp" namespace clotho { namespace powersets { template < class Element, class Block, class Tag = next_available_order_tag > struct block_map { typedef Element element_type; typedef Block size_type; static const unsigned int bits_per_block = sizeof( size_type ) * 8; size_type operator()( const element_type & elem ) { return -1; } }; template < class Element, class Block > struct block_map< Element, Block, normalized_key< Element > > { typedef Element element_type; typedef Block size_type; typedef normalized_key< Element > keyer; static const unsigned int bits_per_block = sizeof( size_type ) * 8; constexpr static const double width_per_bin = ((keyer::range) / (double) bits_per_block); inline size_type operator()( const element_type & elem ) { static keyer k; return k(elem) * bits_per_block; } }; } // namespace powersets } // namespace clotho #endif // BLOCK_MAP_HPP_ <commit_msg>separated block bit mapping to bit_range since not dependent upon element<commit_after>#ifndef BLOCK_MAP_HPP_ #define BLOCK_MAP_HPP_ #include "clotho/powerset/bit_range.hpp" #include "clotho/powerset/normalized_key.hpp" #include "clotho/powerset/next_available_order_tag.hpp" namespace clotho { namespace powersets { template < class Element, class Block, class Tag = next_available_order_tag > struct block_map { typedef Element element_type; typedef Block size_type; static const unsigned int bits_per_block = sizeof( size_type ) * 8; size_type operator()( const element_type & elem ) { return -1; } }; template < class Element, class Block > struct block_map< Element, Block, normalized_key< Element > > : public bit_range< Block, typename normalized_key< Element >::range_type > { typedef Element element_type; typedef Block size_type; typedef normalized_key< Element > keyer; typedef bit_range< Block, typename normalized_key< Element >::range_type > bit_range_type; // static const unsigned int bits_per_block = sizeof( size_type ) * 8; // constexpr static const double width_per_bin = ((keyer::range) / (double) bits_per_block); inline size_type operator()( const element_type & elem ) { static keyer k; return k(elem) * bit_range_type::bits_per_block; } }; } // namespace powersets } // namespace clotho #endif // BLOCK_MAP_HPP_ <|endoftext|>
<commit_before>#include <iomanip> #include "solver.h" #include "version.h" #include "core/tuner.h" #include "core/logger.h" #include "core/random.h" #include "model_gboost.h" #include "core/ibstream.h" #include "core/obstream.h" #include "core/algorithm.h" #include "gboost_loss_avg.h" #include "gboost_loss_var.h" using namespace nano; template <typename tloss> static auto update_result(const tloss& loss_tr, const tloss& loss_vd, const tloss& loss_te, const nano::timer_t& timer, const int epoch, const int patience, training_t& result) { const auto measure_tr = training_t::measurement_t{loss_tr.value(), loss_tr.error()}; const auto measure_vd = training_t::measurement_t{loss_vd.value(), loss_vd.error()}; const auto measure_te = training_t::measurement_t{loss_te.value(), loss_te.error()}; return result.update( training_t::state_t{timer.milliseconds(), epoch, measure_tr, measure_vd, measure_te}, patience); } template <typename tloss, typename tweak_learner = typename tloss::weak_learner_t> static auto train_config( const task_t& task, const size_t fold, const loss_t& loss, const json_t& json, const string_t& solver_id, const int rounds, const int patience) { scalar_t lambda = 0, shrinkage = 0, subsampling = 0; nano::from_json(json, "lambda", lambda, "shrinkage", shrinkage, "subsampling", subsampling); // create loss functions tloss loss_tr(task, fold_t{fold, protocol::train}, loss, lambda); tloss loss_vd(task, fold_t{fold, protocol::valid}, loss, lambda); tloss loss_te(task, fold_t{fold, protocol::test}, loss, lambda); // check if the solver is properly set rsolver_t solver; critical(solver = get_solvers().get(solver_id), strcat("search solver (", solver_id, ")")); nano::timer_t timer; auto config = json.dump(); config = nano::replace(config, "\"", ""); config = nano::replace(config, ",}", ""); config = nano::replace(config, "}", ""); config = nano::replace(config, "{", ""); config = nano::replace(config, ":", "="); training_t result(config); auto status = update_result(loss_tr, loss_vd, loss_te, timer, 0, patience, result); log_info() << std::setprecision(4) << "[" << 0 << "/" << rounds << "]:tr=" << result.history().rbegin()->m_train << ",vd=" << result.history().rbegin()->m_valid << "|" << status << ",te=" << result.history().rbegin()->m_test << "," << config << "."; // add weak learners at each boosting round ... std::vector<tweak_learner> wlearners; for (auto round = 0; round < rounds && !result.is_done(); ++ round) { // subsampling const auto indices = nano::sample_without_replacement( task.size(fold_t{fold, protocol::train}), static_cast<size_t>(subsampling)); // fit weak learner tweak_learner wlearner; wlearner_t::fit(task, fold_t{fold, protocol::train}, loss_tr.gradients(), indices, wlearner); loss_tr.wlearner(wlearner); // line-search const auto epsilon = epsilon2<scalar_t>(); const auto x0 = vector_t{vector_t::Zero(loss_tr.size())}; const auto state = solver->minimize(100, epsilon, loss_tr, x0); wlearner.scale(state.x); wlearner.scale(shrinkage); wlearners.push_back(wlearner); // update current predictions loss_tr.add_wlearner(wlearner); loss_vd.add_wlearner(wlearner); loss_te.add_wlearner(wlearner); status = update_result(loss_tr, loss_vd, loss_te, timer, round + 1, patience, result); log_info() << std::setprecision(4) << "[" << (round + 1) << "/" << rounds << "]:tr=" << result.last().m_train << ",vd=" << result.last().m_valid << "|" << status << ",te=" << result.last().m_test << std::setprecision(2) << "," << wlearner << std::setprecision(4) << ",solver=(" << state.m_status << ",i=" << state.m_iterations << ",f=" << state.f << ")."; } // keep only the weak learners up to optimum epoch (on the validation dataset) wlearners.erase( wlearners.begin() + result.optimum().m_epoch, wlearners.end()); return std::make_pair(result, wlearners); } template <typename tloss, typename tweak_learner = typename tloss::weak_learner_t> static auto train(const task_t& task, const size_t fold, const loss_t& loss, const tuner_t& tuner, const string_t& solver_id, const int rounds, const int patience) { training_t result; std::vector<tweak_learner> wlearners; for (const auto& config : tuner.get(tuner.n_configs())) { const auto config_result = train_config<tloss>( task, fold, loss, config, solver_id, rounds, patience); if (config_result.first < result) { result = config_result.first; wlearners = config_result.second; } } log_info() << ">>>" << std::setprecision(4) << " tr=" << result.optimum().m_train << ",vd=" << result.optimum().m_valid << ",te=" << result.optimum().m_test << ",round=" << result.optimum().m_epoch << "," << result.config() << "."; return std::make_pair(result, wlearners); } template <typename tweak_learner> void model_gboost_t<tweak_learner>::to_json(json_t& json) const { nano::to_json(json, "rounds", m_rounds, "patience", m_patience, "solver", m_solver, "cumloss", to_string(m_cumloss) + join(enum_values<cumloss>()), "shrinkage", to_string(m_shrinkage) + join(enum_values<shrinkage>()), "subsampling", to_string(m_subsampling) + join(enum_values<subsampling>())); } template <typename tweak_learner> void model_gboost_t<tweak_learner>::from_json(const json_t& json) { nano::from_json(json, "rounds", m_rounds, "patience", m_patience, "solver", m_solver, "cumloss", m_cumloss, "shrinkage", m_shrinkage, "subsampling", m_subsampling); } template <typename tweak_learner> training_t model_gboost_t<tweak_learner>::train(const task_t& task, const size_t fold, const loss_t& loss) { m_idims = task.idims(); m_odims = task.odims(); tuner_t tuner; switch (m_shrinkage) { case shrinkage::off: tuner.add_finite("shrinkage", 1.0); break; case shrinkage::on: tuner.add_finite("shrinkage", 0.1, 0.2, 0.5, 1.0); break; } switch (m_subsampling) { case subsampling::off: tuner.add_finite("subsampling", 100); break; case subsampling::on: tuner.add_finite("subsampling", 10, 20, 50, 100); break; } training_t result; switch (m_cumloss) { case cumloss::variance: tuner.add_pow10s("lambda", 0.0, -6, +6); std::tie(result, m_wlearners) = ::train<gboost_loss_var_t<tweak_learner>>( task, fold, loss, tuner, m_solver, m_rounds, m_patience); break; case cumloss::average: default: tuner.add_finite("lambda", 1.0); std::tie(result, m_wlearners) = ::train<gboost_loss_avg_t<tweak_learner>>( task, fold, loss, tuner, m_solver, m_rounds, m_patience); break; } return result; } template <typename tweak_learner> tensor3d_t model_gboost_t<tweak_learner>::output(const tensor3d_t& input) const { assert(input.dims() == m_idims); tensor3d_t output(m_odims); output.zero(); for (const auto& wlearner : m_wlearners) { output.vector() += wlearner.output(input).vector(); } return output; } template <typename tweak_learner> bool model_gboost_t<tweak_learner>::save(obstream_t& stream) const { const auto vmajor = static_cast<uint8_t>(major_version); const auto vminor = static_cast<uint8_t>(minor_version); if ( !stream.write(vmajor) || !stream.write(vminor) || !stream.write(m_idims) || !stream.write(m_odims) || !stream.write(m_rounds) || !stream.write(m_cumloss) || !stream.write(m_shrinkage) || !stream.write(m_subsampling) || !stream.write(m_wlearners.size())) { return false; } return std::all_of(m_wlearners.begin(), m_wlearners.end(), [&] (const auto& wlearner) { return wlearner.save(stream); }); } template <typename tweak_learner> bool model_gboost_t<tweak_learner>::load(ibstream_t& stream) { uint8_t vmajor = 0x00; uint8_t vminor = 0x00; size_t n_wlearners = 0; if ( !stream.read(vmajor) || !stream.read(vminor) || !stream.read(m_idims) || !stream.read(m_odims) || !stream.read(m_rounds) || !stream.read(m_cumloss) || !stream.read(m_shrinkage) || !stream.read(m_subsampling) || !stream.read(n_wlearners)) { return false; } m_wlearners.resize(n_wlearners); for (auto& wlearner : m_wlearners) { if (!wlearner.load(stream)) { return false; } } // todo: more verbose loading (#weak learners, feature or coefficient statistics, idims...) return true; } template class nano::model_gboost_t<nano::wlearner_linear_t>; template class nano::model_gboost_t<nano::wlearner_real_stump_t>; template class nano::model_gboost_t<nano::wlearner_real_table_t>; template class nano::model_gboost_t<nano::wlearner_discrete_stump_t>; template class nano::model_gboost_t<nano::wlearner_discrete_table_t>; <commit_msg>log the range of the scaling factors for weak learners<commit_after>#include <iomanip> #include "solver.h" #include "version.h" #include "core/tuner.h" #include "core/logger.h" #include "core/random.h" #include "model_gboost.h" #include "core/ibstream.h" #include "core/obstream.h" #include "core/algorithm.h" #include "gboost_loss_avg.h" #include "gboost_loss_var.h" using namespace nano; template <typename tloss> static auto update_result(const tloss& loss_tr, const tloss& loss_vd, const tloss& loss_te, const nano::timer_t& timer, const int epoch, const int patience, training_t& result) { const auto measure_tr = training_t::measurement_t{loss_tr.value(), loss_tr.error()}; const auto measure_vd = training_t::measurement_t{loss_vd.value(), loss_vd.error()}; const auto measure_te = training_t::measurement_t{loss_te.value(), loss_te.error()}; return result.update( training_t::state_t{timer.milliseconds(), epoch, measure_tr, measure_vd, measure_te}, patience); } template <typename tloss, typename tweak_learner = typename tloss::weak_learner_t> static auto train_config( const task_t& task, const size_t fold, const loss_t& loss, const json_t& json, const string_t& solver_id, const int rounds, const int patience) { scalar_t lambda = 0, shrinkage = 0, subsampling = 0; nano::from_json(json, "lambda", lambda, "shrinkage", shrinkage, "subsampling", subsampling); // create loss functions tloss loss_tr(task, fold_t{fold, protocol::train}, loss, lambda); tloss loss_vd(task, fold_t{fold, protocol::valid}, loss, lambda); tloss loss_te(task, fold_t{fold, protocol::test}, loss, lambda); // check if the solver is properly set rsolver_t solver; critical(solver = get_solvers().get(solver_id), strcat("search solver (", solver_id, ")")); nano::timer_t timer; auto config = json.dump(); config = nano::replace(config, "\"", ""); config = nano::replace(config, ",}", ""); config = nano::replace(config, "}", ""); config = nano::replace(config, "{", ""); config = nano::replace(config, ":", "="); training_t result(config); auto status = update_result(loss_tr, loss_vd, loss_te, timer, 0, patience, result); log_info() << std::setprecision(4) << "[" << 0 << "/" << rounds << "]:tr=" << result.history().rbegin()->m_train << ",vd=" << result.history().rbegin()->m_valid << "|" << status << ",te=" << result.history().rbegin()->m_test << "," << config << "."; // add weak learners at each boosting round ... std::vector<tweak_learner> wlearners; for (auto round = 0; round < rounds && !result.is_done(); ++ round) { // subsampling const auto indices = nano::sample_without_replacement( task.size(fold_t{fold, protocol::train}), static_cast<size_t>(subsampling)); // fit weak learner tweak_learner wlearner; wlearner_t::fit(task, fold_t{fold, protocol::train}, loss_tr.gradients(), indices, wlearner); loss_tr.wlearner(wlearner); // line-search const auto epsilon = epsilon2<scalar_t>(); const auto x0 = vector_t{vector_t::Constant(loss_tr.size(), 10)}; const auto state = solver->minimize(100, epsilon, loss_tr, x0); wlearner.scale(state.x); wlearner.scale(shrinkage); wlearners.push_back(wlearner); // update current predictions loss_tr.add_wlearner(wlearner); loss_vd.add_wlearner(wlearner); loss_te.add_wlearner(wlearner); status = update_result(loss_tr, loss_vd, loss_te, timer, round + 1, patience, result); log_info() << std::setprecision(4) << "[" << (round + 1) << "/" << rounds << "]:tr=" << result.last().m_train << ",vd=" << result.last().m_valid << "|" << status << ",te=" << result.last().m_test << std::setprecision(2) << "," << wlearner << std::setprecision(4) << ",solver=(" << state.m_status << ",i=" << state.m_iterations << ",x=[" << state.x.minCoeff() << "," << state.x.maxCoeff() << "]" << ",f=" << state.f << ")."; } // keep only the weak learners up to optimum epoch (on the validation dataset) wlearners.erase( wlearners.begin() + result.optimum().m_epoch, wlearners.end()); return std::make_pair(result, wlearners); } template <typename tloss, typename tweak_learner = typename tloss::weak_learner_t> static auto train(const task_t& task, const size_t fold, const loss_t& loss, const tuner_t& tuner, const string_t& solver_id, const int rounds, const int patience) { training_t result; std::vector<tweak_learner> wlearners; for (const auto& config : tuner.get(tuner.n_configs())) { const auto config_result = train_config<tloss>( task, fold, loss, config, solver_id, rounds, patience); if (config_result.first < result) { result = config_result.first; wlearners = config_result.second; } } log_info() << ">>>" << std::setprecision(4) << " tr=" << result.optimum().m_train << ",vd=" << result.optimum().m_valid << ",te=" << result.optimum().m_test << ",round=" << result.optimum().m_epoch << "," << result.config() << "."; return std::make_pair(result, wlearners); } template <typename tweak_learner> void model_gboost_t<tweak_learner>::to_json(json_t& json) const { nano::to_json(json, "rounds", m_rounds, "patience", m_patience, "solver", m_solver, "cumloss", to_string(m_cumloss) + join(enum_values<cumloss>()), "shrinkage", to_string(m_shrinkage) + join(enum_values<shrinkage>()), "subsampling", to_string(m_subsampling) + join(enum_values<subsampling>())); } template <typename tweak_learner> void model_gboost_t<tweak_learner>::from_json(const json_t& json) { nano::from_json(json, "rounds", m_rounds, "patience", m_patience, "solver", m_solver, "cumloss", m_cumloss, "shrinkage", m_shrinkage, "subsampling", m_subsampling); } template <typename tweak_learner> training_t model_gboost_t<tweak_learner>::train(const task_t& task, const size_t fold, const loss_t& loss) { m_idims = task.idims(); m_odims = task.odims(); tuner_t tuner; switch (m_shrinkage) { case shrinkage::off: tuner.add_finite("shrinkage", 1.0); break; case shrinkage::on: tuner.add_finite("shrinkage", 0.1, 0.2, 0.5, 1.0); break; } switch (m_subsampling) { case subsampling::off: tuner.add_finite("subsampling", 100); break; case subsampling::on: tuner.add_finite("subsampling", 10, 20, 50, 100); break; } training_t result; switch (m_cumloss) { case cumloss::variance: tuner.add_pow10s("lambda", 0.0, -6, +6); std::tie(result, m_wlearners) = ::train<gboost_loss_var_t<tweak_learner>>( task, fold, loss, tuner, m_solver, m_rounds, m_patience); break; case cumloss::average: default: tuner.add_finite("lambda", 1.0); std::tie(result, m_wlearners) = ::train<gboost_loss_avg_t<tweak_learner>>( task, fold, loss, tuner, m_solver, m_rounds, m_patience); break; } return result; } template <typename tweak_learner> tensor3d_t model_gboost_t<tweak_learner>::output(const tensor3d_t& input) const { assert(input.dims() == m_idims); tensor3d_t output(m_odims); output.zero(); for (const auto& wlearner : m_wlearners) { output.vector() += wlearner.output(input).vector(); } return output; } template <typename tweak_learner> bool model_gboost_t<tweak_learner>::save(obstream_t& stream) const { const auto vmajor = static_cast<uint8_t>(major_version); const auto vminor = static_cast<uint8_t>(minor_version); if ( !stream.write(vmajor) || !stream.write(vminor) || !stream.write(m_idims) || !stream.write(m_odims) || !stream.write(m_rounds) || !stream.write(m_cumloss) || !stream.write(m_shrinkage) || !stream.write(m_subsampling) || !stream.write(m_wlearners.size())) { return false; } return std::all_of(m_wlearners.begin(), m_wlearners.end(), [&] (const auto& wlearner) { return wlearner.save(stream); }); } template <typename tweak_learner> bool model_gboost_t<tweak_learner>::load(ibstream_t& stream) { uint8_t vmajor = 0x00; uint8_t vminor = 0x00; size_t n_wlearners = 0; if ( !stream.read(vmajor) || !stream.read(vminor) || !stream.read(m_idims) || !stream.read(m_odims) || !stream.read(m_rounds) || !stream.read(m_cumloss) || !stream.read(m_shrinkage) || !stream.read(m_subsampling) || !stream.read(n_wlearners)) { return false; } m_wlearners.resize(n_wlearners); for (auto& wlearner : m_wlearners) { if (!wlearner.load(stream)) { return false; } } // todo: more verbose loading (#weak learners, feature or coefficient statistics, idims...) return true; } template class nano::model_gboost_t<nano::wlearner_linear_t>; template class nano::model_gboost_t<nano::wlearner_real_stump_t>; template class nano::model_gboost_t<nano::wlearner_real_table_t>; template class nano::model_gboost_t<nano::wlearner_discrete_stump_t>; template class nano::model_gboost_t<nano::wlearner_discrete_table_t>; <|endoftext|>
<commit_before>/* * File: main.cpp * Author: ruehle * * Created on July 6, 2010, 12:15 PM */ #include <stdlib.h> #include <votca/csg/csgapplication.h> #include <votca/tools/histogramnew.h> #include <votca/csg/beadlist.h> #include <votca/csg/nblist.h> #include <votca/csg/nblistgrid.h> //using namespace votca::tools; using namespace std; using namespace votca::csg; class CsgTestApp : public CsgApplication { string ProgramName() { return "template_nblist"; } void HelpText(ostream &out) { out << "rough template for rdf calculations"; } void Initialize(); bool DoTrajectory() {return true;} void BeginEvaluate(Topology *top, Topology *top_ref); void EvalConfiguration(Topology *top, Topology *top_ref); void EndEvaluate(); protected: HistogramNew _rdf; double _cut_off; }; int main(int argc, char** argv) { CsgTestApp app; return app.Exec(argc, argv); } void CsgTestApp::EvalConfiguration(Topology *top, Topology *top_ref) { BeadList b; b.Generate(*top, "*"); NBListGrid nb; nb.setCutoff(_cut_off); nb.Generate(b); NBList::iterator i; for(i=nb.begin(); i!=nb.end(); ++i) _rdf.Process((*i)->dist()); } void CsgTestApp::Initialize() { CsgApplication::Initialize(); AddProgramOptions("RDF options") ("c", boost::program_options::value<double>()->default_value(1.0), "the cutoff"); } void CsgTestApp::BeginEvaluate(Topology *top, Topology *top_ref) { _cut_off = OptionsMap()["c"].as<double>(); _rdf.Initialize(0, _cut_off, 50); } void CsgTestApp::EndEvaluate() { _rdf.data().Save("rdf.dat"); } <commit_msg>template.cc added ASL-2.0 header<commit_after>/* * Copyright 2009,2010 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdlib.h> #include <votca/csg/csgapplication.h> #include <votca/tools/histogramnew.h> #include <votca/csg/beadlist.h> #include <votca/csg/nblist.h> #include <votca/csg/nblistgrid.h> //using namespace votca::tools; using namespace std; using namespace votca::csg; class CsgTestApp : public CsgApplication { string ProgramName() { return "template_nblist"; } void HelpText(ostream &out) { out << "rough template for rdf calculations"; } void Initialize(); bool DoTrajectory() {return true;} void BeginEvaluate(Topology *top, Topology *top_ref); void EvalConfiguration(Topology *top, Topology *top_ref); void EndEvaluate(); protected: HistogramNew _rdf; double _cut_off; }; int main(int argc, char** argv) { CsgTestApp app; return app.Exec(argc, argv); } void CsgTestApp::EvalConfiguration(Topology *top, Topology *top_ref) { BeadList b; b.Generate(*top, "*"); NBListGrid nb; nb.setCutoff(_cut_off); nb.Generate(b); NBList::iterator i; for(i=nb.begin(); i!=nb.end(); ++i) _rdf.Process((*i)->dist()); } void CsgTestApp::Initialize() { CsgApplication::Initialize(); AddProgramOptions("RDF options") ("c", boost::program_options::value<double>()->default_value(1.0), "the cutoff"); } void CsgTestApp::BeginEvaluate(Topology *top, Topology *top_ref) { _cut_off = OptionsMap()["c"].as<double>(); _rdf.Initialize(0, _cut_off, 50); } void CsgTestApp::EndEvaluate() { _rdf.data().Save("rdf.dat"); } <|endoftext|>
<commit_before>// test_app.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> #define PAGE_SIZE 4096 int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFile; hFile = CreateFile ( L"\\\\.\\viosdev", GENERIC_READ | GENERIC_WRITE, 0, NULL, // no SECURITY_ATTRIBUTES structure OPEN_EXISTING, // No special create flags 0, // No special attributes NULL); if(INVALID_HANDLE_VALUE == hFile) { printf("Failed to open the device with error %d\n", GetLastError()); return 0; } DWORD size; char buffer[PAGE_SIZE*2] = "hello world!\n\r"; char read_buffer[PAGE_SIZE+1]; /* for(int i = 0; i < 512; i++) { sprintf(buffer, "Hello world %d\n\r ", i ); if(!WriteFile(hFile, buffer, 5012, &size, NULL)) { printf("Error writing to file %d\n", GetLastError()); } } */ while(true) { printf("\n>"); gets(buffer); if(!WriteFile(hFile, buffer, strlen(buffer) + 1, &size, NULL)) { printf("Error writing to file %d\n", GetLastError()); } if(ReadFile(hFile, read_buffer, PAGE_SIZE, &size, NULL)) { read_buffer[size] = '\0'; //printf("Got from device %d bytes>>> \n%s\n", size, read_buffer); printf("%s", read_buffer); } } CloseHandle(hFile); return 0; } <commit_msg>[virtio-serial] Test app. Add async file operation tests.<commit_after>// test_app.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> #define PAGE_SIZE 4096 VOID CALLBACK FileIOCompletionRoutine( __in DWORD dwErrorCode, __in DWORD dwNumberOfBytesTransfered, __in LPOVERLAPPED lpOverlapped ) { printf("Write complete with error %d, transfered %d\n", dwErrorCode, dwNumberOfBytesTransfered); __asm int 3; } int _tmain(int argc, _TCHAR* argv[]) { HANDLE hFile; hFile = CreateFile ( L"\\\\.\\viosdev", GENERIC_READ | GENERIC_WRITE, 0, NULL, // no SECURITY_ATTRIBUTES structure OPEN_EXISTING, // No special create flags FILE_FLAG_OVERLAPPED,//0, // No special attributes NULL); if(INVALID_HANDLE_VALUE == hFile) { printf("Failed to open the device with error %d\n", GetLastError()); return 0; } DWORD size; char buffer[PAGE_SIZE*2] = "hello world!\n\r"; char read_buffer[PAGE_SIZE+1]; /* for(int i = 0; i < 512; i++) { sprintf(buffer, "Hello world %d\n\r ", i ); if(!WriteFile(hFile, buffer, 5012, &size, NULL)) { printf("Error writing to file %d\n", GetLastError()); } } */ HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, L"Just_event"); printf ("Created event %x\n", hEvent); BOOL bSomethingToRead = TRUE; OVERLAPPED Overlapped; OVERLAPPED OverlappedRead; while(true) { printf("\n>"); gets(buffer); /* if(!WriteFile(hFile, buffer, strlen(buffer) + 1, &size, NULL)) { printf("Error writing to file %d\n", GetLastError()); }*/ memset(&Overlapped, 0, sizeof(OVERLAPPED)); if(!WriteFileEx(hFile, buffer, strlen(buffer) + 1, &Overlapped, FileIOCompletionRoutine)) { printf("Error writing to file %d\n", GetLastError()); } if(bSomethingToRead) { memset(&OverlappedRead, 0, sizeof(OVERLAPPED)); OverlappedRead.hEvent = hEvent; bSomethingToRead = FALSE; if(ReadFile(hFile, read_buffer, PAGE_SIZE, &size, &OverlappedRead)) { read_buffer[size] = '\0'; bSomethingToRead = TRUE; //printf("Got from device %d bytes>>> \n%s\n", size, read_buffer); printf("%s", read_buffer); } } if(WAIT_TIMEOUT != WaitForSingleObject(hEvent, 1000)) { bSomethingToRead = TRUE; if (GetOverlappedResult(hFile, &OverlappedRead, &size, TRUE)) { read_buffer[size] = '\0'; printf("Got from device %d bytes>>> \n%s\n", size, read_buffer); // printf("%s", read_buffer); } } } CloseHandle(hFile); return 0; } <|endoftext|>
<commit_before>{ gStyle->SetOptStat(0); TFile *FCy = new TFile("cyclus_exo1_1.root"); TFile *FCl = new TFile("Scenario.root"); TTree *TCy = (TTree *) FCy->Get("TT"); TTree *TCl = (TTree *) FCl->Get("TreeScenario"); TCanvas *C0 = new TCanvas("C0","Pu",1400,900); C0->Divide(2,2,0.01,0.01); C0->cd(1); TH2D *tmp1 = new TH2D("tmp1","Total Pu",10,0,102,10,0,50); tmp1->GetXaxis()->SetTitle("Time (y)"); tmp1->GetXaxis()->CenterTitle(); tmp1->GetXaxis()->SetTitleOffset(1.0); tmp1->GetYaxis()->SetTitle("Mass (tons)"); tmp1->GetYaxis()->CenterTitle(); tmp1->GetYaxis()->SetTitleOffset(1.0); tmp1->Draw(""); TCy->Draw("B93:T","","Lsame"); TCl->Draw("B93:T","","Lsame"); C0->cd(2); TH2D *tmp2 = new TH2D("tmp2","Pu in Stock",10,0,102,10,0,50); tmp2->GetXaxis()->SetTitle("Time (y)"); tmp2->GetXaxis()->CenterTitle(); tmp2->GetXaxis()->SetTitleOffset(1.0); tmp2->GetYaxis()->SetTitle("Mass (tons)"); tmp2->GetYaxis()->CenterTitle(); tmp2->GetYaxis()->SetTitleOffset(1.0); tmp2->Draw(""); TCy->Draw("B3:T","","Lsame"); TCl->Draw("B3:T","","Lsame"); C0->cd(3); TH2D *tmp3 = new TH2D("tmp3","Pu in Reactor",10,0,102,10,0,1); tmp3->GetXaxis()->SetTitle("Time (y)"); tmp3->GetXaxis()->CenterTitle(); tmp3->GetXaxis()->SetTitleOffset(1.0); tmp3->GetYaxis()->SetTitle("Mass (tons)"); tmp3->GetYaxis()->CenterTitle(); tmp3->GetYaxis()->SetTitleOffset(1.0); tmp3->Draw(""); TCy->Draw("B57:T","","Lsame"); TCl->Draw("B57:T","","Lsame"); C0->cd(4); C0->GetPad(4)->SetPhi(120); TH2D *tmp4 = new TH2D("tmp4","Pu 239 in Reactor",10,0,102,10,0,1); tmp4->GetXaxis()->SetTitle("Time (y)"); tmp4->GetXaxis()->SetTitleOffset(1.0); tmp4->GetXaxis()->CenterTitle(); tmp4->GetYaxis()->SetTitle("Mass (tons)"); tmp4->GetYaxis()->SetTitleOffset(1.0); tmp4->GetYaxis()->CenterTitle(); tmp4->Draw(""); TCy->Draw("B170:T","","Lsame"); TCl->Draw("B170:T","","Lsame"); } <commit_msg>Update Drawing script<commit_after>{ gStyle->SetOptStat(0); TFile *FCy = new TFile("cyclus_exo1_1.root"); TFile *FCl = new TFile("Scenario.root"); TTree *TCy = (TTree *) FCy->Get("TT"); TTree *TCl = (TTree *) FCl->Get("TreeScenario"); TCy->SetLineColor(kRed); TCy->SetMarkerColor(kRed); TCy->SetLineWidth(3); TCl->SetLineColor(kBlue); TCl->SetMarkerColor(kBlue); TCl->SetLineWidth(3); TCanvas *C0 = new TCanvas("C0","Pu",1400,900); C0->Divide(2,2,0.01,0.01); C0->cd(1); TH2D *tmp1 = new TH2D("tmp1","Total Pu",10,0,102,10,0,50); tmp1->GetXaxis()->SetTitle("Time (y)"); tmp1->GetXaxis()->CenterTitle(); tmp1->GetXaxis()->SetTitleOffset(1.0); tmp1->GetYaxis()->SetTitle("Mass (tons)"); tmp1->GetYaxis()->CenterTitle(); tmp1->GetYaxis()->SetTitleOffset(1.0); tmp1->Draw(""); TCy->Draw("B93:T","","Lsame"); TCl->Draw("B93:T","","Lsame"); C0->cd(2); TH2D *tmp2 = new TH2D("tmp2","Pu in Stock",10,0,102,10,0,50); tmp2->GetXaxis()->SetTitle("Time (y)"); tmp2->GetXaxis()->CenterTitle(); tmp2->GetXaxis()->SetTitleOffset(1.0); tmp2->GetYaxis()->SetTitle("Mass (tons)"); tmp2->GetYaxis()->CenterTitle(); tmp2->GetYaxis()->SetTitleOffset(1.0); tmp2->Draw(""); TCy->Draw("B3:T","","Lsame"); TCl->Draw("B3:T","","Lsame"); C0->cd(3); TH2D *tmp3 = new TH2D("tmp3","Pu in Reactor",10,0,102,10,0,1); tmp3->GetXaxis()->SetTitle("Time (y)"); tmp3->GetXaxis()->CenterTitle(); tmp3->GetXaxis()->SetTitleOffset(1.0); tmp3->GetYaxis()->SetTitle("Mass (tons)"); tmp3->GetYaxis()->CenterTitle(); tmp3->GetYaxis()->SetTitleOffset(1.0); tmp3->Draw(""); TCy->Draw("B57:T","","Lsame"); TCl->Draw("B57:T","","Lsame"); C0->cd(4); C0->GetPad(4)->SetPhi(120); TH2D *tmp4 = new TH2D("tmp4","Pu 239 in Reactor",10,0,102,10,0,0.6); tmp4->GetXaxis()->SetTitle("Time (y)"); tmp4->GetXaxis()->SetTitleOffset(1.0); tmp4->GetXaxis()->CenterTitle(); tmp4->GetYaxis()->SetTitle("Mass (tons)"); tmp4->GetYaxis()->SetTitleOffset(1.0); tmp4->GetYaxis()->CenterTitle(); tmp4->Draw(""); TCy->Draw("B170:T","","Lsame"); TCl->Draw("B170:T","","Lsame"); } <|endoftext|>
<commit_before>//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a trivial dead store elimination that only considers // basic-block local redundant stores. // // FIXME: This should eventually be extended to be a post-dominator tree // traversal. Doing so would be pretty trivial. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasSetTracker.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/Statistic.h" using namespace llvm; namespace { Statistic<> NumStores("dse", "Number of stores deleted"); Statistic<> NumOther ("dse", "Number of other instrs removed"); struct DSE : public FunctionPass { virtual bool runOnFunction(Function &F) { bool Changed = false; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed; } bool runOnBasicBlock(BasicBlock &BB); void DeleteDeadValueChains(Value *V, AliasSetTracker &AST); // getAnalysisUsage - We require post dominance frontiers (aka Control // Dependence Graph) virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<TargetData>(); AU.addRequired<AliasAnalysis>(); AU.addPreserved<AliasAnalysis>(); } }; RegisterOpt<DSE> X("dse", "Dead Store Elimination"); } Pass *llvm::createDeadStoreEliminationPass() { return new DSE(); } bool DSE::runOnBasicBlock(BasicBlock &BB) { TargetData &TD = getAnalysis<TargetData>(); AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); AliasSetTracker KillLocs(AA); // If this block ends in a return, unwind, and eventually tailcall/barrier, // then all allocas are dead at its end. if (BB.getTerminator()->getNumSuccessors() == 0) { } bool MadeChange = false; for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ) { Instruction *I = --BBI; // Keep moving iterator backwards #if 0 // AST doesn't support malloc/free/alloca??? if (isa<FreeInst>(I)) { // Free instructions make any stores to the free'd location dead. KillLocs.insert(I); } #endif if (!isa<StoreInst>(I) || cast<StoreInst>(I)->isVolatile()) { // If this is a non-store instruction, it makes everything referenced no // longer killed. Remove anything aliased from the alias set tracker. KillLocs.remove(I); continue; } // If this is a non-volatile store instruction, and if it is already in // the stored location is already in the tracker, then this is a dead // store. We can just delete it here, but while we're at it, we also // delete any trivially dead expression chains. unsigned ValSize = TD.getTypeSize(I->getOperand(0)->getType()); Value *Ptr = I->getOperand(1); if (AliasSet *AS = KillLocs.getAliasSetForPointerIfExists(Ptr, ValSize)) for (AliasSet::iterator ASI = AS->begin(), E = AS->end(); ASI != E; ++ASI) if (AA.alias(ASI.getPointer(), ASI.getSize(), Ptr, ValSize) == AliasAnalysis::MustAlias) { // If we found a must alias in the killed set, then this store really // is dead. Delete it now. ++BBI; // Don't invalidate iterator. Value *Val = I->getOperand(0); BB.getInstList().erase(I); // Nuke the store! ++NumStores; DeleteDeadValueChains(Val, KillLocs); // Delete any now-dead instrs DeleteDeadValueChains(Ptr, KillLocs); // Delete any now-dead instrs MadeChange = true; goto BigContinue; } // Otherwise, this is a non-dead store just add it to the set of dead // locations. KillLocs.add(cast<StoreInst>(I)); BigContinue:; } return MadeChange; } void DSE::DeleteDeadValueChains(Value *V, AliasSetTracker &AST) { // Value must be dead. if (!V->use_empty()) return; if (Instruction *I = dyn_cast<Instruction>(V)) if (isInstructionTriviallyDead(I)) { AST.deleteValue(I); getAnalysis<AliasAnalysis>().deleteValue(I); // See if this made any operands dead. We do it this way in case the // instruction uses the same operand twice. We don't want to delete a // value then reference it. while (unsigned NumOps = I->getNumOperands()) { Value *Op = I->getOperand(NumOps-1); I->op_erase(I->op_end()-1); // Drop from the operand list. DeleteDeadValueChains(Op, AST); // Attempt to nuke it. } I->getParent()->getInstList().erase(I); ++NumOther; } } <commit_msg>Free instructions kill values too. This implements DeadStoreElim/free.llx<commit_after>//===- DeadStoreElimination.cpp - Dead Store Elimination ------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements a trivial dead store elimination that only considers // basic-block local redundant stores. // // FIXME: This should eventually be extended to be a post-dominator tree // traversal. Doing so would be pretty trivial. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar.h" #include "llvm/Function.h" #include "llvm/Instructions.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/AliasSetTracker.h" #include "llvm/Target/TargetData.h" #include "llvm/Transforms/Utils/Local.h" #include "Support/Statistic.h" using namespace llvm; namespace { Statistic<> NumStores("dse", "Number of stores deleted"); Statistic<> NumOther ("dse", "Number of other instrs removed"); struct DSE : public FunctionPass { virtual bool runOnFunction(Function &F) { bool Changed = false; for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) Changed |= runOnBasicBlock(*I); return Changed; } bool runOnBasicBlock(BasicBlock &BB); void DeleteDeadValueChains(Value *V, AliasSetTracker &AST); // getAnalysisUsage - We require post dominance frontiers (aka Control // Dependence Graph) virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<TargetData>(); AU.addRequired<AliasAnalysis>(); AU.addPreserved<AliasAnalysis>(); } }; RegisterOpt<DSE> X("dse", "Dead Store Elimination"); } Pass *llvm::createDeadStoreEliminationPass() { return new DSE(); } bool DSE::runOnBasicBlock(BasicBlock &BB) { TargetData &TD = getAnalysis<TargetData>(); AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); AliasSetTracker KillLocs(AA); // If this block ends in a return, unwind, and eventually tailcall/barrier, // then all allocas are dead at its end. if (BB.getTerminator()->getNumSuccessors() == 0) { } bool MadeChange = false; for (BasicBlock::iterator BBI = BB.end(); BBI != BB.begin(); ) { Instruction *I = --BBI; // Keep moving iterator backwards #if 0 // AST doesn't support malloc/free/alloca??? if (isa<FreeInst>(I)) { // Free instructions make any stores to the free'd location dead. KillLocs.insert(I); } #endif if (!isa<FreeInst>(I) && (!isa<StoreInst>(I) || cast<StoreInst>(I)->isVolatile())) { // If this is a non-store instruction, it makes everything referenced no // longer killed. Remove anything aliased from the alias set tracker. KillLocs.remove(I); continue; } // If this is a non-volatile store instruction, and if it is already in // the stored location is already in the tracker, then this is a dead // store. We can just delete it here, but while we're at it, we also // delete any trivially dead expression chains. unsigned ValSize; Value *Ptr; if (isa<StoreInst>(I)) { Ptr = I->getOperand(1); ValSize = TD.getTypeSize(I->getOperand(0)->getType()); } else { Ptr = I->getOperand(0); ValSize = ~0; } if (AliasSet *AS = KillLocs.getAliasSetForPointerIfExists(Ptr, ValSize)) for (AliasSet::iterator ASI = AS->begin(), E = AS->end(); ASI != E; ++ASI) if (AA.alias(ASI.getPointer(), ASI.getSize(), Ptr, ValSize) == AliasAnalysis::MustAlias) { // If we found a must alias in the killed set, then this store really // is dead. Delete it now. ++BBI; // Don't invalidate iterator. Value *Val = I->getOperand(0); BB.getInstList().erase(I); // Nuke the store! ++NumStores; DeleteDeadValueChains(Val, KillLocs); // Delete any now-dead instrs DeleteDeadValueChains(Ptr, KillLocs); // Delete any now-dead instrs MadeChange = true; goto BigContinue; } // Otherwise, this is a non-dead store just add it to the set of dead // locations. KillLocs.add(I); BigContinue:; } return MadeChange; } void DSE::DeleteDeadValueChains(Value *V, AliasSetTracker &AST) { // Value must be dead. if (!V->use_empty()) return; if (Instruction *I = dyn_cast<Instruction>(V)) if (isInstructionTriviallyDead(I)) { AST.deleteValue(I); getAnalysis<AliasAnalysis>().deleteValue(I); // See if this made any operands dead. We do it this way in case the // instruction uses the same operand twice. We don't want to delete a // value then reference it. while (unsigned NumOps = I->getNumOperands()) { Value *Op = I->getOperand(NumOps-1); I->op_erase(I->op_end()-1); // Drop from the operand list. DeleteDeadValueChains(Op, AST); // Attempt to nuke it. } I->getParent()->getInstList().erase(I); ++NumOther; } } <|endoftext|>
<commit_before>#include "app.h" #include "palette_manager.h" namespace cistft { Application::Application() : mGlobals(mWorkManager, mAudioNodes, mStftRenderer, mGridRenderer, mAppConfig) , mAudioNodes(mGlobals) , mStftRenderer(mGlobals) , mMonitorRenderer(mGlobals) , mGridRenderer(mGlobals) {} void Application::prepareSettings(Settings *settings) { // We do not need console for this application settings->enableConsoleWindow(false); // It's ok if a user resizes the window, we'll respond accordingly settings->setResizable(true); // Title of the graphical window when it pops up settings->setTitle("Cinder STFT"); // Get the current display (monitor) dimensions const auto current_display_size = settings->getDisplay()->getSize(); // calculate the window size to be 90% of the monitor size const auto window_size = (current_display_size * 9) / 10; // calculate the window position (top left) to be at 10% of monitor size const auto window_position = (current_display_size * 5) / 100; // set the window size to be 90% of the monitor size settings->setWindowSize(window_size); // set the window position (top left) to be at 10% of monitor size settings->setWindowPos(window_position); // cap at 300.0 fps! settings->setFrameRate(300.0f); } void Application::setup() { // sets up pre-launch GUI setupPreLaunchGUI(); // setup audio input from microphone mAudioNodes.setupInput(); // setup basic waveform monitor input, used to plot // the real-time pre-launch audio waveform. mAudioNodes.setupMonitor(); } void Application::update() { // Update STFT renderer (a no-op if it's not setup) mStftRenderer.update(); // Update audio input and pull the latest data in mAudioNodes.update(); // Check if we have to swap GUI with post-launch one if (mAppConfig.shouldLaunch()) setupPostLaunchGUI(); } void Application::draw() { // clear screen black ci::gl::clear(); // we're not 3D rendering so turn it off ci::gl::disableDepthRead(); ci::gl::disableDepthWrite(); // enable alpha blending ci::gl::enableAlphaBlending(); // if recorder is not recording then... if (!mGlobals.getAudioNodes().isRecorderReady()) { // render pre-launch waveform mMonitorRenderer.draw(); } else { // render STFT data mStftRenderer.draw(); } // draw grid mGridRenderer.draw(); // draw FPS drawFps(); // draw GUI mGuiInstance->draw(); // Turn off Alpha blending ci::gl::disableAlphaBlending(); } void Application::mouseDown(ci::app::MouseEvent event) { // If user clicks anywhere on screen if (mAudioNodes.isInputReady()) { mAudioNodes.toggleInput(); } } void Application::keyDown(ci::app::KeyEvent event) { // If user enters SPACE if (event.getChar() == ' ') { if (mAudioNodes.isInputReady()) { mAudioNodes.toggleInput(); } } } void Application::drawFps() { std::stringstream buf; buf << "FPS: " << ci::app::App::getAverageFps(); ci::gl::drawStringRight(buf.str(), ci::Vec2i(ci::app::getWindowWidth() - 25, 10)); } void Application::setupPreLaunchGUI() { static std::once_flag __setup_gui_flag; std::call_once(__setup_gui_flag, [this] { mGuiInstance = ci::params::InterfaceGl::create("Cinder STFT parameters", ci::Vec2i(425, 500)); mGuiInstance->addText("Portland State University, Winter 2015"); mGuiInstance->addSeparator(); // ----------------------------------------------- mGuiInstance->addText("Developed by: Sepehr Laal, Raghad Boulos"); mGuiInstance->addText("Instructor: Dr. James McNames"); mGuiInstance->addSeparator(); // ----------------------------------------------- mGuiInstance->addText("This project performs STFT analysis on real time audio signal."); mGuiInstance->addSeparator(); // ----------------------------------------------- mAppConfig.setupPreLaunchGUI(mGuiInstance.get()); }); } void Application::setupPostLaunchGUI() { static std::once_flag __setup_gui_flag; std::call_once(__setup_gui_flag, [this] { mAppConfig.setupPostLaunchGUI(mGuiInstance.get()); //mGridRenderer.removeFromGui(mGuiInstance.get()); mAppConfig.performLaunch(); mAudioNodes.setupRecorder(); mStftRenderer.setup(); }); } } //!namespace cistft CINDER_APP_NATIVE(cistft::Application, ci::app::RendererGl)<commit_msg>minor comment clean up<commit_after>#include "app.h" #include "palette_manager.h" namespace cistft { Application::Application() : mGlobals(mWorkManager, mAudioNodes, mStftRenderer, mGridRenderer, mAppConfig) , mAudioNodes(mGlobals) , mStftRenderer(mGlobals) , mMonitorRenderer(mGlobals) , mGridRenderer(mGlobals) {} void Application::prepareSettings(Settings *settings) { // We do not need console for this application settings->enableConsoleWindow(false); // It's ok if a user resizes the window, we'll respond accordingly settings->setResizable(true); // Title of the graphical window when it pops up settings->setTitle("Cinder STFT"); // Get the current display (monitor) dimensions const auto current_display_size = settings->getDisplay()->getSize(); // calculate the window size to be 90% of the monitor size const auto window_size = (current_display_size * 9) / 10; // calculate the window position (top left) to be at 10% of monitor size const auto window_position = (current_display_size * 5) / 100; // set the window size to be 90% of the monitor size settings->setWindowSize(window_size); // set the window position (top left) to be at 10% of monitor size settings->setWindowPos(window_position); // cap at 300.0 fps! settings->setFrameRate(300.0f); } void Application::setup() { // sets up pre-launch GUI setupPreLaunchGUI(); // setup audio input from microphone mAudioNodes.setupInput(); // setup basic waveform monitor input, used to plot // the real-time pre-launch audio waveform. mAudioNodes.setupMonitor(); } void Application::update() { // Update STFT renderer (a no-op if it's not setup) mStftRenderer.update(); // Update audio input and pull the latest data in mAudioNodes.update(); // Check if we have to swap GUI with post-launch one if (mAppConfig.shouldLaunch()) setupPostLaunchGUI(); } void Application::draw() { // clear screen black ci::gl::clear(); // we're not 3D rendering so turn it off ci::gl::disableDepthRead(); ci::gl::disableDepthWrite(); // enable alpha blending ci::gl::enableAlphaBlending(); // if recorder is not recording then... if (!mGlobals.getAudioNodes().isRecorderReady()) { // render pre-launch waveform mMonitorRenderer.draw(); } else { // render STFT data mStftRenderer.draw(); } // draw grid mGridRenderer.draw(); // draw FPS drawFps(); // draw GUI mGuiInstance->draw(); // Turn off Alpha blending ci::gl::disableAlphaBlending(); } void Application::mouseDown(ci::app::MouseEvent event) { // If user clicks anywhere on screen if (mAudioNodes.isInputReady()) { mAudioNodes.toggleInput(); } } void Application::keyDown(ci::app::KeyEvent event) { // If user enters SPACE if (event.getChar() == ' ') { if (mAudioNodes.isInputReady()) { mAudioNodes.toggleInput(); } } } void Application::drawFps() { std::stringstream buf; buf << "FPS: " << ci::app::App::getAverageFps(); ci::gl::drawStringRight(buf.str(), ci::Vec2i(ci::app::getWindowWidth() - 25, 10)); } void Application::setupPreLaunchGUI() { static std::once_flag __setup_gui_flag; std::call_once(__setup_gui_flag, [this] { mGuiInstance = ci::params::InterfaceGl::create("Cinder STFT parameters", ci::Vec2i(425, 500)); // ----------------------------------------------- mGuiInstance->addText("Portland State University, Winter 2015"); mGuiInstance->addSeparator(); // ----------------------------------------------- mGuiInstance->addText("Developed by: Sepehr Laal and Raghad Boulos"); mGuiInstance->addText("Instructor: Dr. James McNames"); mGuiInstance->addSeparator(); // ----------------------------------------------- mGuiInstance->addText("This project performs STFT analysis on real time audio signal."); mGuiInstance->addSeparator(); // ----------------------------------------------- mAppConfig.setupPreLaunchGUI(mGuiInstance.get()); }); } void Application::setupPostLaunchGUI() { static std::once_flag __setup_gui_flag; std::call_once(__setup_gui_flag, [this] { mAppConfig.setupPostLaunchGUI(mGuiInstance.get()); mAppConfig.performLaunch(); mAudioNodes.setupRecorder(); mStftRenderer.setup(); }); } } //!namespace cistft CINDER_APP_NATIVE(cistft::Application, ci::app::RendererGl)<|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ #ifndef GCN_CONTAINER_HPP #define GCN_CONTAINER_HPP #include <list> #include "guichan/basiccontainer.hpp" #include "guichan/graphics.hpp" #include "guichan/platform.hpp" namespace gcn { /** * A container able to contain other Widgets. It is in other words a * Widget that holds other Widgets. A Widgets position in the container is * always relativ to the Container itself, not the screen. Using a * Container as the top Widget in Gui is the only way to use more then one * Widget in your Gui. */ class GCN_CORE_DECLSPEC Container: public BasicContainer { public: /** * Constructor. A container is opauqe as default. * * @see setOpaque, isOpaque */ Container(); /** * Destructor. */ virtual ~Container(); /** * Sets whether the background should be drawn or not. If the * Container is not opaque it will be completely transparent. * * NOTE: This is not the same as to set visibility. A nonvisible * Container will not draw it's content. * * @param opaque true if the Container should be opaque. * @see isOpaque */ virtual void setOpaque(bool opaque); /** * Checks if the Container is opaque. * * @return true if the Container is opaque. * @see setOpaque */ virtual bool isOpaque() const; /** * Adds a Widget to the Container. * * @param widget the Widget to add. * @see remove */ virtual void add(Widget* widget); /** * Adds a Widget to the container and also specifices it's postion * * @param widget the Widget to add. * @param x the x coordinat for the Widget in the Container. * @param y the y coordinat for the Widget in the Container. * @see remove */ virtual void add(Widget* widget, int x, int y); /** * Removes a Widget from the Container. * * @param widget the Widget to remove. * @throws Exception when the Widget has not been added to the * Container. * @see add, clear */ virtual void remove(Widget* widget); /** * Clears the Container of all widgets. * * @see add, remove */ virtual void clear(); // Inherited from Widget virtual void draw(Graphics* graphics); virtual void drawBorder(Graphics* graphics); protected: bool mOpaque; }; } #endif // end GCN_CONTAINER_HPP <commit_msg>Fixed a spelling error in a comment.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004, 2005 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ #ifndef GCN_CONTAINER_HPP #define GCN_CONTAINER_HPP #include <list> #include "guichan/basiccontainer.hpp" #include "guichan/graphics.hpp" #include "guichan/platform.hpp" namespace gcn { /** * A container able to contain other Widgets. It is in other words a * Widget that holds other Widgets. A Widget's position in the container is * always relativ to the Container itself, not the screen. Using a * Container as the top Widget in Gui is the only way to use more then one * Widget in your Gui. */ class GCN_CORE_DECLSPEC Container: public BasicContainer { public: /** * Constructor. A container is opauqe as default. * * @see setOpaque, isOpaque */ Container(); /** * Destructor. */ virtual ~Container(); /** * Sets whether the background should be drawn or not. If the * Container is not opaque it will be completely transparent. * * NOTE: This is not the same as to set visibility. A nonvisible * Container will not draw it's content. * * @param opaque true if the Container should be opaque. * @see isOpaque */ virtual void setOpaque(bool opaque); /** * Checks if the Container is opaque. * * @return true if the Container is opaque. * @see setOpaque */ virtual bool isOpaque() const; /** * Adds a Widget to the Container. * * @param widget the Widget to add. * @see remove */ virtual void add(Widget* widget); /** * Adds a Widget to the container and also specifices it's postion * * @param widget the Widget to add. * @param x the x coordinat for the Widget in the Container. * @param y the y coordinat for the Widget in the Container. * @see remove */ virtual void add(Widget* widget, int x, int y); /** * Removes a Widget from the Container. * * @param widget the Widget to remove. * @throws Exception when the Widget has not been added to the * Container. * @see add, clear */ virtual void remove(Widget* widget); /** * Clears the Container of all widgets. * * @see add, remove */ virtual void clear(); // Inherited from Widget virtual void draw(Graphics* graphics); virtual void drawBorder(Graphics* graphics); protected: bool mOpaque; }; } #endif // end GCN_CONTAINER_HPP <|endoftext|>
<commit_before>/* * testSendMsg.cpp * * Author: Peter Johansson */ #ifdef _MOCK_ #include "gtest/gtest.h" #include "../src/CalvinDone/CalvinMini.h" class testMessageOut : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() {} }; TEST(testMessageOut, testStdOut) { CalvinMini mini; String str = "{\"to_rt_uuid\": \"calvin-arduino\", \"from_rt_uuid\": \"02fbd30d-c8a6-4cf6-b224-ea4ebdb3634b\", \"state\": {\"prev_connections\": {\"actor_name\": \"test3:snk\"" ", \"inports\": {\"eca87eb7-ffde-4207-b363-31f0ab760050\": [\"02fbd30d-c8a6-4cf6-b224-ea4ebdb3634b\", \"fa46a0e5-388e-45fc-b615-b8e3ed3d9594\"]}" ", \"actor_id\": \"551cdc91-633e-4f70-954d-8e28589a8e44\", \"outports\": {}}, \"actor_type\": \"io.StandardOut\", \"actor_state\": {\"store_tokens\": false" ", \"name\": \"test3:snk\", \"inports\": {\"token\": {\"name\": \"token\", \"fifo\": {\"write_pos\": 13, \"readers\": [\"eca87eb7-ffde-4207-b363-31f0ab760050\"]" ", \"fifo\": [{\"data\": 0, \"type\": \"Token\"}, {\"data\": 0, \"type\": \"Token\"}, {\"data\": 0, \"type\": \"Token\"}, {\"data\": 0, \"type\": \"Token\"}" ", {\"data\": 0, \"type\": \"Token\"}], \"N\": 5, \"tentative_read_pos\": {\"eca87eb7-ffde-4207-b363-31f0ab760050\": 13}, \"read_pos\": {\"eca87eb7-ffde-4207-b363-31f0ab760050\": 13}}" ", \"id\": \"eca87eb7-ffde-4207-b363-31f0ab760050\"}}, \"quiet\": false, \"tokens\": [], \"_managed\": [\"tokens\", \"store_tokens\", \"quiet\", \"id\", \"name\"], \"outports\": {}" ", \"id\": \"551cdc91-633e-4f70-954d-8e28589a8e44\"}}, \"cmd\": \"ACTOR_NEW\", \"msg_uuid\": \"c8472ef4-e721-4744-88d9-2ed898952547\"}"; StaticJsonBuffer<4096> jsonBuffer; JsonObject &msg = jsonBuffer.parseObject(str.c_str()); JsonObject &reply = jsonBuffer.createObject(); JsonObject &request = jsonBuffer.createObject(); mini.handleMsg(msg, reply, request); JsonObject &actor_state = msg["state"]["actor_state"]; // Test if actor_type stdOut is triggered EXPECT_STREQ("io.StandardOut", msg["state"]["actor_type"]); // Test if actor_state is store tokens // which should be false when actor is stdOut EXPECT_FALSE(actor_state.get("store_tokens")); // Test if PORT_CONNECT is returned cmd // which it should be after an actor migrate EXPECT_STREQ("PORT_CONNECT", request["cmd"]); } TEST(testMessageOut, testStdOutToken) { CalvinMini mini; String str = "{\"to_rt_uuid\": \"calvin-miniscule\", \"from_rt_uuid\": \"02fbd30d-c8a6-4cf6-b224-ea4ebdb3634b\", \"cmd\": \"TUNNEL_DATA\", \"value\": {\"sequencenbr\": 13, \"token\": {\"data\": 105" ", \"type\": \"Token\"}, \"cmd\": \"TOKEN\", \"port_id\": \"fa46a0e5-388e-45fc-b615-b8e3ed3d9594\", \"peer_port_id\": \"eca87eb7-ffde-4207-b363-31f0ab760050\"}, \"tunnel_id\": \"fake-tunnel\"}"; StaticJsonBuffer<4096> jsonBuffer; JsonObject &msg = jsonBuffer.parseObject(str.c_str()); JsonObject &reply = jsonBuffer.createObject(); JsonObject &request = jsonBuffer.createObject(); mini.handleMsg(msg, reply, request); JsonObject &value = msg.get("value"); mini.handleMsg(value,reply,request); JsonObject &tokenFromBase = msg.get("token"); JsonObject &tokenInArduino = request.get("token"); int dataFromBase = tokenFromBase.get("data"); int dataInArduino = tokenInArduino.get("data"); // Test if token is handled right EXPECT_EQ(dataFromBase, dataInArduino); // Test if TUNNEL_DATA is returned as cmd EXPECT_STREQ("TUNNEL_DATA",reply.get("cmd")); // Test if nested TOKEN_REPLY is returned as cmd EXPECT_STREQ("TOKEN_REPLY", request.get("cmd")); } #endif <commit_msg>Added tests for migrating actor stdOut<commit_after>/* * testSendMsg.cpp * * Author: Peter Johansson */ #ifdef _MOCK_ #include "gtest/gtest.h" #include "../src/CalvinDone/CalvinMini.h" class testMessageOut : public ::testing::Test { protected: virtual void SetUp() {} virtual void TearDown() {} }; TEST(testMessageOut, testStdOut) { CalvinMini mini; String str = "{\"to_rt_uuid\": \"calvin-arduino\", \"from_rt_uuid\": \"02fbd30d-c8a6-4cf6-b224-ea4ebdb3634b\", \"state\": {\"prev_connections\": {\"actor_name\": \"test3:snk\"" ", \"inports\": {\"eca87eb7-ffde-4207-b363-31f0ab760050\": [\"02fbd30d-c8a6-4cf6-b224-ea4ebdb3634b\", \"fa46a0e5-388e-45fc-b615-b8e3ed3d9594\"]}" ", \"actor_id\": \"551cdc91-633e-4f70-954d-8e28589a8e44\", \"outports\": {}}, \"actor_type\": \"io.StandardOut\", \"actor_state\": {\"store_tokens\": false" ", \"name\": \"test3:snk\", \"inports\": {\"token\": {\"name\": \"token\", \"fifo\": {\"write_pos\": 13, \"readers\": [\"eca87eb7-ffde-4207-b363-31f0ab760050\"]" ", \"fifo\": [{\"data\": 0, \"type\": \"Token\"}, {\"data\": 0, \"type\": \"Token\"}, {\"data\": 0, \"type\": \"Token\"}, {\"data\": 0, \"type\": \"Token\"}" ", {\"data\": 0, \"type\": \"Token\"}], \"N\": 5, \"tentative_read_pos\": {\"eca87eb7-ffde-4207-b363-31f0ab760050\": 13}, \"read_pos\": {\"eca87eb7-ffde-4207-b363-31f0ab760050\": 13}}" ", \"id\": \"eca87eb7-ffde-4207-b363-31f0ab760050\"}}, \"quiet\": false, \"tokens\": [], \"_managed\": [\"tokens\", \"store_tokens\", \"quiet\", \"id\", \"name\"], \"outports\": {}" ", \"id\": \"551cdc91-633e-4f70-954d-8e28589a8e44\"}}, \"cmd\": \"ACTOR_NEW\", \"msg_uuid\": \"c8472ef4-e721-4744-88d9-2ed898952547\"}"; StaticJsonBuffer<4096> jsonBuffer; JsonObject &msg = jsonBuffer.parseObject(str.c_str()); JsonObject &reply = jsonBuffer.createObject(); JsonObject &request = jsonBuffer.createObject(); mini.handleMsg(msg, reply, request); JsonObject &actor_state = msg["state"]["actor_state"]; // Test if actor_type stdOut is triggered EXPECT_STREQ("io.StandardOut", msg["state"]["actor_type"]); // Test if actor_state is store tokens // which should be false when actor is stdOut EXPECT_FALSE(actor_state.get("store_tokens")); // Test if PORT_CONNECT is returned cmd // which it should be after an actor migrate EXPECT_STREQ("PORT_CONNECT", request["cmd"]); } TEST(testMessageOut, testStdOutToken) { CalvinMini mini; String str = "{\"to_rt_uuid\": \"calvin-arduino\", \"from_rt_uuid\": \"02fbd30d-c8a6-4cf6-b224-ea4ebdb3634b\", \"cmd\": \"TUNNEL_DATA\", \"value\": {\"sequencenbr\": 13, \"token\": {\"data\": 105" ", \"type\": \"Token\"}, \"cmd\": \"TOKEN\", \"port_id\": \"fa46a0e5-388e-45fc-b615-b8e3ed3d9594\", \"peer_port_id\": \"eca87eb7-ffde-4207-b363-31f0ab760050\"}, \"tunnel_id\": \"fake-tunnel\"}"; StaticJsonBuffer<4096> jsonBuffer; JsonObject &msg = jsonBuffer.parseObject(str.c_str()); JsonObject &reply = jsonBuffer.createObject(); JsonObject &request = jsonBuffer.createObject(); mini.handleMsg(msg, reply, request); JsonObject &value = msg.get("value"); mini.handleMsg(value,reply,request); JsonObject &tokenFromBase = msg.get("token"); JsonObject &tokenInArduino = request.get("token"); int dataFromBase = tokenFromBase.get("data"); int dataInArduino = tokenInArduino.get("data"); // Test if token is handled right EXPECT_EQ(dataFromBase, dataInArduino); // Test if TUNNEL_DATA is returned as cmd EXPECT_STREQ("TUNNEL_DATA",reply.get("cmd")); // Test if nested TOKEN_REPLY is returned as cmd EXPECT_STREQ("TOKEN_REPLY", request.get("cmd")); } #endif <|endoftext|>
<commit_before>#ifndef AST_HPP #define AST_HPP #include <string> #include <sstream> #include <vector> #include <set> #include <memory> #include <typeinfo> #include "utils/error.hpp" #include "token.hpp" #include "utils/util.hpp" #include "operator.hpp" #include "utils/typeInfo.hpp" class ASTNode: public std::enable_shared_from_this<ASTNode> { public: typedef std::shared_ptr<ASTNode> Link; typedef std::weak_ptr<ASTNode> WeakLink; typedef std::vector<Link> Children; protected: WeakLink parent = WeakLink(); Children children {}; uint64 lineNumber = 0; static void printIndent(uint level) { for (uint i = 0; i < level; i++) print(" "); } public: ASTNode(uint64 lineNumber = 0): lineNumber(lineNumber) {} virtual ~ASTNode() {}; virtual void addChild(Link child) { child->setParent(shared_from_this()); children.push_back(child); } Children getChildren() const { return children; } Link at(int64 pos) const { if (pos < 0) { pos = children.size() + pos; // Negative indices count from the end of the vector } if (abs(pos) > children.size() || pos < 0) { throw InternalError("Index out of array bounds", {METADATA_PAIRS, {"index", std::to_string(pos)}}); } return children[pos]; } void setParent(WeakLink newParent) {parent = newParent;} WeakLink getParent() const {return parent;} void inline setLineNumber(uint64 newLineNumber) { lineNumber = newLineNumber; } uint64 inline getLineNumber() const { return lineNumber; } virtual void printTree(uint level) const { printIndent(level); println("Base ASTNode"); for (auto& child : children) child->printTree(level + 1); } virtual bool operator==(const ASTNode& rhs) const { if (typeid(*this) != typeid(rhs)) return false; if (children.size() != rhs.getChildren().size()) return false; for (uint64 i = 0; i < children.size(); i++) { if (*(this->at(i)) != *(rhs.at(i))) return false; } return true; } virtual bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } }; #define GET_FOR(childIndex, nameOf, linkType) \ Node<linkType>::Link get##nameOf() const {\ return Node<linkType>::dynPtrCast(children[childIndex]);\ } #define SET_FOR(childIndex, nameOf, linkType) \ void set##nameOf(std::shared_ptr<linkType> newNode) {children[childIndex] = newNode;} #define GET_SET_FOR(childIndex, nameOf, linkType) \ GET_FOR(childIndex, nameOf, linkType) \ SET_FOR(childIndex, nameOf, linkType) #define PRETTY_PRINT_FOR(childIndex, name) \ {\ printIndent(level + 1);\ println(#name":");\ children[childIndex]->printTree(level + 1);\ } class NoMoreChildrenNode: public ASTNode { public: NoMoreChildrenNode(int childrenCount) { children.resize(childrenCount, nullptr); } void addChild(Link child) { UNUSED(child); throw InternalError("Cannot add children to NoMoreChildrenNode", {METADATA_PAIRS}); } bool inline notNull(uint childIndex) const { return children[childIndex] != nullptr; } }; template<typename T, typename std::enable_if<std::is_base_of<ASTNode, T>::value>::type* = nullptr> struct Node: public PtrUtil<T> { typedef typename PtrUtil<T>::Link Link; typedef typename PtrUtil<T>::WeakLink WeakLink; static inline bool isSameType(ASTNode::Link node) { return typeid(T) == typeid(*node); } static inline Link dynPtrCast(ASTNode::Link node) { return std::dynamic_pointer_cast<T>(node); } }; class BlockNode: public ASTNode { public: void printTree(uint level) const { printIndent(level); println("Block Node"); for (auto& child : children) child->printTree(level + 1); } bool operator==(const ASTNode& rhs) const { return ASTNode::operator==(rhs); } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } }; class ExpressionNode: public ASTNode { private: Token tok = Token(UNPROCESSED, 0); public: ExpressionNode() {} ExpressionNode(Token token): tok(token) { switch (tok.type) { case IDENTIFIER: case OPERATOR: case L_INTEGER: case L_FLOAT: case L_STRING: case L_BOOLEAN: break; default: throw InternalError("Trying to add unsupported token to ExpressionNode", {METADATA_PAIRS, {"token", token.toString()}}); } } std::shared_ptr<ExpressionNode> at(int64 pos) { return std::dynamic_pointer_cast<ExpressionNode>(ASTNode::at(pos)); } Token getToken() const { return tok; } void printTree(uint level) const { printIndent(level); println("Expression Node:", tok); for (auto& child : children) child->printTree(level + 1); } bool operator==(const ASTNode& rhs) const { if (!ASTNode::operator==(rhs)) return false; if (this->tok != dynamic_cast<const ExpressionNode&>(rhs).tok) return false; return true; } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } }; class DeclarationNode: public NoMoreChildrenNode { private: std::string identifier; DefiniteTypeInfo info; public: DeclarationNode(std::string identifier, TypeList typeList): NoMoreChildrenNode(1), identifier(identifier), info(typeList) {} std::string getIdentifier() const { return identifier; } DefiniteTypeInfo getTypeInfo() const { return info; } bool isDynamic() const { return info.isDynamic(); } GET_SET_FOR(0, Init, ExpressionNode) bool hasInit() const { return children[0] != nullptr; } void printTree(uint level) const { printIndent(level); println("Declaration Node: " + identifier + " (" + info.toString() + ")"); if (children.size() > 0) children[0]->printTree(level + 1); } bool operator==(const ASTNode& rhs) const { if (!ASTNode::operator==(rhs)) return false; auto decl = dynamic_cast<const DeclarationNode&>(rhs); if (this->identifier != decl.identifier) return false; if (this->info != decl.info) return false; return true; } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } }; class BranchNode: public NoMoreChildrenNode { public: BranchNode(): NoMoreChildrenNode(3) {} GET_SET_FOR(0, Condition, ExpressionNode) GET_SET_FOR(1, SuccessBlock, BlockNode) GET_FOR(2, FailiureBlock, ASTNode) SET_FOR(2, FailiureBlock, BlockNode) SET_FOR(2, FailiureBlock, BranchNode) bool operator==(const ASTNode& rhs) const { return ASTNode::operator==(rhs); } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } void printTree(uint level) const { printIndent(level); println("Branch Node:"); PRETTY_PRINT_FOR(0, Condition) PRETTY_PRINT_FOR(1, Success) if (notNull(2)) PRETTY_PRINT_FOR(2, Failiure) } }; class LoopNode: public NoMoreChildrenNode { public: LoopNode(): NoMoreChildrenNode(4) {} GET_SET_FOR(0, Init, DeclarationNode) GET_SET_FOR(1, Condition, ExpressionNode) GET_SET_FOR(2, Update, ExpressionNode) GET_SET_FOR(3, Code, BlockNode) void printTree(uint level) const { printIndent(level); println("Loop Node"); if (notNull(0)) PRETTY_PRINT_FOR(0, Init) if (notNull(1)) PRETTY_PRINT_FOR(1, Condition) if (notNull(2)) PRETTY_PRINT_FOR(2, Update) if (notNull(3)) PRETTY_PRINT_FOR(3, Code) } bool operator==(const ASTNode& rhs) const { return ASTNode::operator==(rhs); } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } }; class AST { private: BlockNode root = BlockNode(); public: bool operator==(const AST& rhs) const { if (this->root != rhs.root) return false; return true; } bool operator!=(const AST& rhs) const { return !operator==(rhs); } void print() const { root.printTree(0); } void setRoot(BlockNode rootNode) { root = rootNode; } BlockNode getRoot() const { return root; } Node<BlockNode>::Link getRootAsLink() const { return Node<BlockNode>::make(root); } }; #undef PRETTY_PRINT_FOR #undef GET_FOR #undef SET_FOR #undef GET_SET_FOR #endif <commit_msg>Added ASTVisitor to visit ASTNodes<commit_after>#ifndef AST_HPP #define AST_HPP #include <string> #include <sstream> #include <vector> #include <set> #include <memory> #include <typeinfo> #include "utils/error.hpp" #include "token.hpp" #include "utils/util.hpp" #include "operator.hpp" #include "utils/typeInfo.hpp" class ASTVisitor; using ASTVisitorLink = PtrUtil<ASTVisitor>::Link; class ASTNode: public std::enable_shared_from_this<ASTNode> { public: typedef std::shared_ptr<ASTNode> Link; typedef std::weak_ptr<ASTNode> WeakLink; typedef std::vector<Link> Children; protected: WeakLink parent = WeakLink(); Children children {}; uint64 lineNumber = 0; static void printIndent(uint level) { for (uint i = 0; i < level; i++) print(" "); } public: ASTNode(uint64 lineNumber = 0): lineNumber(lineNumber) {} virtual ~ASTNode() {}; virtual void addChild(Link child) { child->setParent(shared_from_this()); children.push_back(child); } Children getChildren() const { return children; } Link at(int64 pos) const { if (pos < 0) { pos = children.size() + pos; // Negative indices count from the end of the vector } if (abs(pos) > children.size() || pos < 0) { throw InternalError("Index out of array bounds", {METADATA_PAIRS, {"index", std::to_string(pos)}}); } return children[pos]; } void setParent(WeakLink newParent) {parent = newParent;} WeakLink getParent() const {return parent;} void inline setLineNumber(uint64 newLineNumber) { lineNumber = newLineNumber; } uint64 inline getLineNumber() const { return lineNumber; } virtual void printTree(uint level) const { printIndent(level); println("Base ASTNode"); for (auto& child : children) child->printTree(level + 1); } virtual bool operator==(const ASTNode& rhs) const { if (typeid(*this) != typeid(rhs)) return false; if (children.size() != rhs.getChildren().size()) return false; for (uint64 i = 0; i < children.size(); i++) { if (*(this->at(i)) != *(rhs.at(i))) return false; } return true; } virtual bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } virtual void visit(ASTVisitorLink visitor) = 0; }; template<typename T, typename std::enable_if<std::is_base_of<ASTNode, T>::value>::type* = nullptr> struct Node: public PtrUtil<T> { typedef typename PtrUtil<T>::Link Link; typedef typename PtrUtil<T>::WeakLink WeakLink; static inline bool isSameType(ASTNode::Link node) { return typeid(T) == typeid(*node); } static inline Link dynPtrCast(ASTNode::Link node) { return std::dynamic_pointer_cast<T>(node); } }; #define GET_FOR(childIndex, nameOf, linkType) \ Node<linkType>::Link get##nameOf() const {\ return Node<linkType>::dynPtrCast(children[childIndex]);\ } #define SET_FOR(childIndex, nameOf, linkType) \ void set##nameOf(std::shared_ptr<linkType> newNode) {children[childIndex] = newNode;} #define GET_SET_FOR(childIndex, nameOf, linkType) \ GET_FOR(childIndex, nameOf, linkType) \ SET_FOR(childIndex, nameOf, linkType) #define PRETTY_PRINT_FOR(childIndex, name) \ {\ printIndent(level + 1);\ println(#name":");\ children[childIndex]->printTree(level + 1);\ } class NoMoreChildrenNode: public ASTNode { public: NoMoreChildrenNode(int childrenCount) { children.resize(childrenCount, nullptr); } void addChild(Link child) { UNUSED(child); throw InternalError("Cannot add children to NoMoreChildrenNode", {METADATA_PAIRS}); } bool inline notNull(uint childIndex) const { return children[childIndex] != nullptr; } }; class BlockNode: public ASTNode { public: void printTree(uint level) const { printIndent(level); println("Block Node"); for (auto& child : children) child->printTree(level + 1); } bool operator==(const ASTNode& rhs) const { return ASTNode::operator==(rhs); } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } void visit(ASTVisitorLink visitor); }; class ExpressionNode: public ASTNode { private: Token tok = Token(UNPROCESSED, 0); public: ExpressionNode() {} ExpressionNode(Token token): tok(token) { switch (tok.type) { case IDENTIFIER: case OPERATOR: case L_INTEGER: case L_FLOAT: case L_STRING: case L_BOOLEAN: break; default: throw InternalError("Trying to add unsupported token to ExpressionNode", {METADATA_PAIRS, {"token", token.toString()}}); } } std::shared_ptr<ExpressionNode> at(int64 pos) { return std::dynamic_pointer_cast<ExpressionNode>(ASTNode::at(pos)); } Token getToken() const { return tok; } void printTree(uint level) const { printIndent(level); println("Expression Node:", tok); for (auto& child : children) child->printTree(level + 1); } bool operator==(const ASTNode& rhs) const { if (!ASTNode::operator==(rhs)) return false; if (this->tok != dynamic_cast<const ExpressionNode&>(rhs).tok) return false; return true; } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } void visit(ASTVisitorLink visitor); }; class DeclarationNode: public NoMoreChildrenNode { private: std::string identifier; DefiniteTypeInfo info; public: DeclarationNode(std::string identifier, TypeList typeList): NoMoreChildrenNode(1), identifier(identifier), info(typeList) {} std::string getIdentifier() const { return identifier; } DefiniteTypeInfo getTypeInfo() const { return info; } bool isDynamic() const { return info.isDynamic(); } GET_SET_FOR(0, Init, ExpressionNode) bool hasInit() const { return children[0] != nullptr; } void printTree(uint level) const { printIndent(level); println("Declaration Node: " + identifier + " (" + info.toString() + ")"); if (children.size() > 0) children[0]->printTree(level + 1); } bool operator==(const ASTNode& rhs) const { if (!ASTNode::operator==(rhs)) return false; auto decl = dynamic_cast<const DeclarationNode&>(rhs); if (this->identifier != decl.identifier) return false; if (this->info != decl.info) return false; return true; } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } void visit(ASTVisitorLink visitor); }; class BranchNode: public NoMoreChildrenNode { public: BranchNode(): NoMoreChildrenNode(3) {} GET_SET_FOR(0, Condition, ExpressionNode) GET_SET_FOR(1, SuccessBlock, BlockNode) GET_FOR(2, FailiureBlock, ASTNode) SET_FOR(2, FailiureBlock, BlockNode) SET_FOR(2, FailiureBlock, BranchNode) bool operator==(const ASTNode& rhs) const { return ASTNode::operator==(rhs); } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } void printTree(uint level) const { printIndent(level); println("Branch Node:"); PRETTY_PRINT_FOR(0, Condition) PRETTY_PRINT_FOR(1, Success) if (notNull(2)) PRETTY_PRINT_FOR(2, Failiure) } void visit(ASTVisitorLink visitor); }; class LoopNode: public NoMoreChildrenNode { public: LoopNode(): NoMoreChildrenNode(4) {} GET_SET_FOR(0, Init, DeclarationNode) GET_SET_FOR(1, Condition, ExpressionNode) GET_SET_FOR(2, Update, ExpressionNode) GET_SET_FOR(3, Code, BlockNode) void printTree(uint level) const { printIndent(level); println("Loop Node"); if (notNull(0)) PRETTY_PRINT_FOR(0, Init) if (notNull(1)) PRETTY_PRINT_FOR(1, Condition) if (notNull(2)) PRETTY_PRINT_FOR(2, Update) if (notNull(3)) PRETTY_PRINT_FOR(3, Code) } bool operator==(const ASTNode& rhs) const { return ASTNode::operator==(rhs); } bool operator!=(const ASTNode& rhs) const { return !operator==(rhs); } void visit(ASTVisitorLink visitor); }; class AST { private: BlockNode root = BlockNode(); public: bool operator==(const AST& rhs) const { if (this->root != rhs.root) return false; return true; } bool operator!=(const AST& rhs) const { return !operator==(rhs); } void print() const { root.printTree(0); } void setRoot(BlockNode rootNode) { root = rootNode; } BlockNode getRoot() const { return root; } Node<BlockNode>::Link getRootAsLink() const { return Node<BlockNode>::make(root); } }; #define VISITOR_IMPL(nodeName) virtual void visit##nodeName(nodeName##Node* node) = 0; class ASTVisitor { public: VISITOR_IMPL(Block) VISITOR_IMPL(Expression) VISITOR_IMPL(Declaration) VISITOR_IMPL(Branch) VISITOR_IMPL(Loop) }; #undef VISITOR_IMPL #define VISITED_NODE_FUNC(nodeName) \ void nodeName##Node::visit(ASTVisitorLink visitor) {\ visitor->visit##nodeName(this);\ } VISITED_NODE_FUNC(Block) VISITED_NODE_FUNC(Expression) VISITED_NODE_FUNC(Declaration) VISITED_NODE_FUNC(Branch) VISITED_NODE_FUNC(Loop) #undef VISITED_NODE_FUNC #undef PRETTY_PRINT_FOR #undef GET_FOR #undef SET_FOR #undef GET_SET_FOR #endif <|endoftext|>
<commit_before>#include <network.hpp> #include <utility> using namespace MCPP::NetworkImpl; namespace MCPP { void SendHandle::Then (std::function<void (SendState)> callback) { lock.Execute([&] () mutable { callbacks.Add(std::move(callback)); }); } void SendHandle::Complete () noexcept { state=SendState::Succeeded; } SendState SendHandle::State () const noexcept { return lock.Execute([&] () { return state; }); } SendState SendHandle::Wait () const noexcept { return lock.Execute([&] () { while (state==SendState::InProgress) wait.Sleep(lock); return state; }); } void SendHandle::Fail () noexcept { lock.Execute([&] () mutable { for (auto & callback : callbacks) try { if (callback) callback(SendState::Failed); // We don't care abouc exceptions } catch (...) { } // Set state state=SendState::Failed; // Wake up waiting threads wait.WakeAll(); }); } } <commit_msg>Network Fix - Adding Callbacks to Already-Completed Sends<commit_after>#include <network.hpp> #include <utility> using namespace MCPP::NetworkImpl; namespace MCPP { void SendHandle::Then (std::function<void (SendState)> callback) { auto s=lock.Execute([&] () mutable { // Add callback to pending unless // the send has already completed if (state==SendState::InProgress) callbacks.Add(std::move(callback)); return state; }); // If send has already completed, // fire callback at once if (s!=SendState::InProgress) if (callback) try { callback(s); // If callback was actually invoked asynchronously, // use would not get exceptions, therefore // simulate that behaviour by not propagating them // here } catch (...) { } } void SendHandle::Complete () noexcept { state=SendState::Succeeded; } SendState SendHandle::State () const noexcept { return lock.Execute([&] () { return state; }); } SendState SendHandle::Wait () const noexcept { return lock.Execute([&] () { while (state==SendState::InProgress) wait.Sleep(lock); return state; }); } void SendHandle::Fail () noexcept { lock.Execute([&] () mutable { for (auto & callback : callbacks) try { if (callback) callback(SendState::Failed); // We don't care abouc exceptions } catch (...) { } // Set state state=SendState::Failed; // Wake up waiting threads wait.WakeAll(); }); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/PlatformUtils.hpp> #include <sax/SAXException.hpp> #include <sax/SAXParseException.hpp> #include <parsers/IDOMParser.hpp> #include <idom/IDOM_DOMException.hpp> #include <idom/IDOM_Document.hpp> #include "IDOMCount.hpp" #include <string.h> #include <stdlib.h> #include <fstream.h> // --------------------------------------------------------------------------- // This is a simple program which invokes the DOMParser to build a DOM // tree for the specified input file. It then walks the tree and counts // the number of elements. The element count is then printed. // --------------------------------------------------------------------------- static void usage() { cout << "\nUsage:\n" " IDOMCount [options] <XML file | List file>\n\n" "This program invokes the IDOM parser, builds the DOM tree,\n" "and then prints the number of elements found in each XML file.\n\n" "Options:\n" " -l Indicate the input file is a List File that has a list of xml files.\n" " Default to off (Input file is an XML file).\n" " -v=xxx Validation scheme [always | never | auto*].\n" " -n Enable namespace processing. Defaults to off.\n" " -s Enable schema processing. Defaults to off.\n" " -f Enable full schema constraint checking. Defaults to off.\n" " -? Show this help.\n\n" " * = Default if not provided explicitly.\n" << endl; } // --------------------------------------------------------------------------- // // Recursively Count up the total number of child Elements under the specified Node. // // --------------------------------------------------------------------------- static int countChildElements(IDOM_Node *n) { IDOM_Node *child; int count = 0; if (n) { if (n->getNodeType() == IDOM_Node::ELEMENT_NODE) { count++; for (child = n->getFirstChild(); child != 0; child=child->getNextSibling()) { if (child->getNodeType() == IDOM_Node::ELEMENT_NODE) { count += countChildElements(child); } } } } return count; } // --------------------------------------------------------------------------- // // main // // --------------------------------------------------------------------------- int main(int argC, char* argV[]) { // Initialize the XML4C system try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { cerr << "Error during initialization! :\n" << StrX(toCatch.getMessage()) << endl; return 1; } // Check command line and extract arguments. if (argC < 2) { usage(); XMLPlatformUtils::Terminate(); return 1; } const char* xmlFile = 0; IDOMParser::ValSchemes valScheme = IDOMParser::Val_Auto; bool doNamespaces = false; bool doSchema = false; bool schemaFullChecking = false; bool doList = false; bool errorOccurred = false; int argInd; for (argInd = 1; argInd < argC; argInd++) { // Break out on first parm not starting with a dash if (argV[argInd][0] != '-') break; // Watch for special case help request if (!strcmp(argV[argInd], "-?")) { usage(); XMLPlatformUtils::Terminate(); return 2; } else if (!strncmp(argV[argInd], "-v=", 3) || !strncmp(argV[argInd], "-V=", 3)) { const char* const parm = &argV[argInd][3]; if (!strcmp(parm, "never")) valScheme = IDOMParser::Val_Never; else if (!strcmp(parm, "auto")) valScheme = IDOMParser::Val_Auto; else if (!strcmp(parm, "always")) valScheme = IDOMParser::Val_Always; else { cerr << "Unknown -v= value: " << parm << endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strcmp(argV[argInd], "-n") || !strcmp(argV[argInd], "-N")) { doNamespaces = true; } else if (!strcmp(argV[argInd], "-s") || !strcmp(argV[argInd], "-S")) { doSchema = true; } else if (!strcmp(argV[argInd], "-f") || !strcmp(argV[argInd], "-F")) { schemaFullChecking = true; } else if (!strcmp(argV[argInd], "-l") || !strcmp(argV[argInd], "-L")) { doList = true; } else { cerr << "Unknown option '" << argV[argInd] << "', ignoring it\n" << endl; } } // // There should be only one and only one parameter left, and that // should be the file name. // if (argInd != argC - 1) { usage(); XMLPlatformUtils::Terminate(); return 1; } // Instantiate the DOM parser. IDOMParser* parser = new IDOMParser; parser->setValidationScheme(valScheme); parser->setDoNamespaces(doNamespaces); parser->setDoSchema(doSchema); parser->setValidationSchemaFullChecking(schemaFullChecking); // And create our error handler and install it DOMCountErrorHandler errorHandler; parser->setErrorHandler(&errorHandler); // // Get the starting time and kick off the parse of the indicated // file. Catch any exceptions that might propogate out of it. // unsigned long duration; bool more = true; ifstream fin; // the input is a list file if (doList) fin.open(argV[argInd]); while (more) { char fURI[1000]; //initialize the array to zeros memset(fURI,0,sizeof(fURI)); if (doList) { if (! fin.eof() ) { fin.getline (fURI, sizeof(fURI)); if (!*fURI) continue; else { xmlFile = fURI; cerr << "==Parsing== " << xmlFile << endl; } } else break; } else { xmlFile = argV[argInd]; more = false; } //reset error count first errorHandler.resetErrors(); try { const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis(); parser->resetDocumentPool(); parser->parse(xmlFile); const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis(); duration = endMillis - startMillis; } catch (const XMLException& toCatch) { cerr << "\nError during parsing: '" << xmlFile << "'\n" << "Exception message is: \n" << StrX(toCatch.getMessage()) << "\n" << endl; errorOccurred = true; continue; } catch (const IDOM_DOMException& toCatch) { cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n" << "DOMException code is: \n" << toCatch.code << "\n" << endl; errorOccurred = true; continue; } catch (...) { cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n"; errorOccurred = true; continue; } // // Extract the DOM tree, get the list of all the elements and report the // length as the count of elements. // if (errorHandler.getSawErrors()) { cout << "\nErrors occured, no output available\n" << endl; errorOccurred = true; } else { IDOM_Document *doc = parser->getDocument(); unsigned int elementCount = 0; if (doc) elementCount = countChildElements((IDOM_Node*)doc->getDocumentElement()); // Print out the stats that we collected and time taken. cout << xmlFile << ": " << duration << " ms (" << elementCount << " elems)." << endl; } } // // Delete the parser itself. Must be done prior to calling Terminate, below. // delete parser; // And call the termination method XMLPlatformUtils::Terminate(); if (doList) fin.close(); if (errorOccurred) return 4; else return 0; } DOMCountErrorHandler::DOMCountErrorHandler() : fSawErrors(false) { } DOMCountErrorHandler::~DOMCountErrorHandler() { } // --------------------------------------------------------------------------- // DOMCountHandlers: Overrides of the SAX ErrorHandler interface // --------------------------------------------------------------------------- void DOMCountErrorHandler::error(const SAXParseException& e) { fSawErrors = true; cerr << "\nError at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void DOMCountErrorHandler::fatalError(const SAXParseException& e) { fSawErrors = true; cerr << "\nFatal Error at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void DOMCountErrorHandler::warning(const SAXParseException& e) { cerr << "\nWarning at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void DOMCountErrorHandler::resetErrors() { fSawErrors = false; } <commit_msg>[Bug 4544] DOM_NodeList::getLength incorrect when called twice for empty list. Test the getElementsByTagName and getLength in IDOMCount.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/PlatformUtils.hpp> #include <sax/SAXException.hpp> #include <sax/SAXParseException.hpp> #include <parsers/IDOMParser.hpp> #include <idom/IDOM_DOMException.hpp> #include <idom/IDOM_Document.hpp> #include <idom/IDOM_NodeList.hpp> #include "IDOMCount.hpp" #include <string.h> #include <stdlib.h> #include <fstream.h> // --------------------------------------------------------------------------- // This is a simple program which invokes the DOMParser to build a DOM // tree for the specified input file. It then walks the tree and counts // the number of elements. The element count is then printed. // --------------------------------------------------------------------------- static void usage() { cout << "\nUsage:\n" " IDOMCount [options] <XML file | List file>\n\n" "This program invokes the IDOM parser, builds the DOM tree,\n" "and then prints the number of elements found in each XML file.\n\n" "Options:\n" " -l Indicate the input file is a List File that has a list of xml files.\n" " Default to off (Input file is an XML file).\n" " -v=xxx Validation scheme [always | never | auto*].\n" " -n Enable namespace processing. Defaults to off.\n" " -s Enable schema processing. Defaults to off.\n" " -f Enable full schema constraint checking. Defaults to off.\n" " -? Show this help.\n\n" " * = Default if not provided explicitly.\n" << endl; } // --------------------------------------------------------------------------- // // Recursively Count up the total number of child Elements under the specified Node. // // --------------------------------------------------------------------------- static int countChildElements(IDOM_Node *n) { IDOM_Node *child; int count = 0; if (n) { if (n->getNodeType() == IDOM_Node::ELEMENT_NODE) { count++; for (child = n->getFirstChild(); child != 0; child=child->getNextSibling()) { if (child->getNodeType() == IDOM_Node::ELEMENT_NODE) { count += countChildElements(child); } } } } return count; } // --------------------------------------------------------------------------- // // main // // --------------------------------------------------------------------------- int main(int argC, char* argV[]) { // Initialize the XML4C system try { XMLPlatformUtils::Initialize(); } catch (const XMLException& toCatch) { cerr << "Error during initialization! :\n" << StrX(toCatch.getMessage()) << endl; return 1; } // Check command line and extract arguments. if (argC < 2) { usage(); XMLPlatformUtils::Terminate(); return 1; } const char* xmlFile = 0; IDOMParser::ValSchemes valScheme = IDOMParser::Val_Auto; bool doNamespaces = false; bool doSchema = false; bool schemaFullChecking = false; bool doList = false; bool errorOccurred = false; int argInd; for (argInd = 1; argInd < argC; argInd++) { // Break out on first parm not starting with a dash if (argV[argInd][0] != '-') break; // Watch for special case help request if (!strcmp(argV[argInd], "-?")) { usage(); XMLPlatformUtils::Terminate(); return 2; } else if (!strncmp(argV[argInd], "-v=", 3) || !strncmp(argV[argInd], "-V=", 3)) { const char* const parm = &argV[argInd][3]; if (!strcmp(parm, "never")) valScheme = IDOMParser::Val_Never; else if (!strcmp(parm, "auto")) valScheme = IDOMParser::Val_Auto; else if (!strcmp(parm, "always")) valScheme = IDOMParser::Val_Always; else { cerr << "Unknown -v= value: " << parm << endl; XMLPlatformUtils::Terminate(); return 2; } } else if (!strcmp(argV[argInd], "-n") || !strcmp(argV[argInd], "-N")) { doNamespaces = true; } else if (!strcmp(argV[argInd], "-s") || !strcmp(argV[argInd], "-S")) { doSchema = true; } else if (!strcmp(argV[argInd], "-f") || !strcmp(argV[argInd], "-F")) { schemaFullChecking = true; } else if (!strcmp(argV[argInd], "-l") || !strcmp(argV[argInd], "-L")) { doList = true; } else { cerr << "Unknown option '" << argV[argInd] << "', ignoring it\n" << endl; } } // // There should be only one and only one parameter left, and that // should be the file name. // if (argInd != argC - 1) { usage(); XMLPlatformUtils::Terminate(); return 1; } // Instantiate the DOM parser. IDOMParser* parser = new IDOMParser; parser->setValidationScheme(valScheme); parser->setDoNamespaces(doNamespaces); parser->setDoSchema(doSchema); parser->setValidationSchemaFullChecking(schemaFullChecking); // And create our error handler and install it DOMCountErrorHandler errorHandler; parser->setErrorHandler(&errorHandler); // // Get the starting time and kick off the parse of the indicated // file. Catch any exceptions that might propogate out of it. // unsigned long duration; bool more = true; ifstream fin; // the input is a list file if (doList) fin.open(argV[argInd]); while (more) { char fURI[1000]; //initialize the array to zeros memset(fURI,0,sizeof(fURI)); if (doList) { if (! fin.eof() ) { fin.getline (fURI, sizeof(fURI)); if (!*fURI) continue; else { xmlFile = fURI; cerr << "==Parsing== " << xmlFile << endl; } } else break; } else { xmlFile = argV[argInd]; more = false; } //reset error count first errorHandler.resetErrors(); try { const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis(); parser->resetDocumentPool(); parser->parse(xmlFile); const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis(); duration = endMillis - startMillis; } catch (const XMLException& toCatch) { cerr << "\nError during parsing: '" << xmlFile << "'\n" << "Exception message is: \n" << StrX(toCatch.getMessage()) << "\n" << endl; errorOccurred = true; continue; } catch (const IDOM_DOMException& toCatch) { cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n" << "DOMException code is: \n" << toCatch.code << "\n" << endl; errorOccurred = true; continue; } catch (...) { cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n"; errorOccurred = true; continue; } // // Extract the DOM tree, get the list of all the elements and report the // length as the count of elements. // if (errorHandler.getSawErrors()) { cout << "\nErrors occured, no output available\n" << endl; errorOccurred = true; } else { IDOM_Document *doc = parser->getDocument(); unsigned int elementCount = 0; if (doc) { elementCount = countChildElements((IDOM_Node*)doc->getDocumentElement()); // test getElementsByTagName and getLength XMLCh xa[] = {chAsterisk, chNull}; if (elementCount != doc->getElementsByTagName(xa)->getLength()) { cout << "\nErrors occured, element count is wrong\n" << endl; errorOccurred = true; } } // Print out the stats that we collected and time taken. cout << xmlFile << ": " << duration << " ms (" << elementCount << " elems)." << endl; } } // // Delete the parser itself. Must be done prior to calling Terminate, below. // delete parser; // And call the termination method XMLPlatformUtils::Terminate(); if (doList) fin.close(); if (errorOccurred) return 4; else return 0; } DOMCountErrorHandler::DOMCountErrorHandler() : fSawErrors(false) { } DOMCountErrorHandler::~DOMCountErrorHandler() { } // --------------------------------------------------------------------------- // DOMCountHandlers: Overrides of the SAX ErrorHandler interface // --------------------------------------------------------------------------- void DOMCountErrorHandler::error(const SAXParseException& e) { fSawErrors = true; cerr << "\nError at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void DOMCountErrorHandler::fatalError(const SAXParseException& e) { fSawErrors = true; cerr << "\nFatal Error at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void DOMCountErrorHandler::warning(const SAXParseException& e) { cerr << "\nWarning at file " << StrX(e.getSystemId()) << ", line " << e.getLineNumber() << ", char " << e.getColumnNumber() << "\n Message: " << StrX(e.getMessage()) << endl; } void DOMCountErrorHandler::resetErrors() { fSawErrors = false; } <|endoftext|>
<commit_before>/* * wav.hpp * A struct to read / write headers in the form of RIFF WAV linear PCM * * written by janus_wel<janus.wel.3@gmail.com> * This source code is in public domain, and has NO WARRANTY. * * refer * RIFF WAV specifications * http://msdn.microsoft.com/en-us/library/ms713231.aspx * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html * */ #ifndef WAV_HPP #define WAV_HPP #include <cassert> #include <fstream> #include <istream> #include <ostream> #include <stdint.h> #include "cast.hpp" #include "dlogger.hpp" namespace format { namespace riff_wav { // utilitie functions // This function return little-endian value. // RIFF WAV file is written as little-endian, then we've met our needs // by this. template<const char _1, const char _2, const char _3, const char _4> struct quartet2uint { static const uint32_t value = static_cast<uint32_t>(_1) + (_2 << 8) + (_3 << 16) + (_4 << 24); }; // basic properties of linear PCM data struct elements_type { uint16_t channels; uint16_t bit_depth; uint32_t numof_samples; uint32_t sampling_rate; }; /* * The struct for RIFF WAV header * that doesn't contain actual audio data(wav samples). * * RIFF WAV file has: * RIFF chunk * * RIFF chunk has: * id "RIFF" * size 4 + sizeof(data) * format-kind "WAVE" * data fmt subchunk, data subchunk * * fmt subchunk * id "fmt " * size 16 * data fmt-code, channels, sampling-rate, data-per-sec, * block-size, bit-depth * * data subchunk * id "data" * size sizeof(data) * data samples (excluded) * * fmt id: linear PCM(0x01) * 0 1 2 3 4 5 6 7 8 9 a b c d e f * +---------------+---------------+---------------+---------------+ * 0x00 |'R' 'I' 'F' 'F'| riff size |'W' 'A' 'V' 'E'|'f' 'm' 't' ' '| * +---------------+-------+-------+---------------+---------------+ * 0x10 |fmt subchk size| code | ch | sampling rate | data per sec | * +-------+-------+-------+-------+---------------+---------------+ * 0x20 |blk sz |bit dep|'d' 'a' 't' 'a'| data size | samples ... * +-------+-------+---------------+---------------+ * */ struct header_type { // member variables uint32_t id; uint32_t size; uint32_t format_kind; struct fmt_subchunk_type { uint32_t id; uint32_t size; struct data_type { uint16_t code; uint16_t channels; uint32_t sampling_rate; uint32_t data_per_sec; uint16_t block_size; uint16_t bit_depth; // constants enum { LINEAR_PCM = 1 }; // constructor data_type(void) {} explicit data_type(const elements_type& p) : code(LINEAR_PCM), channels(p.channels), sampling_rate(p.sampling_rate), data_per_sec(p.sampling_rate * p.channels * (p.bit_depth / 8)), block_size(p.channels * (p.bit_depth / 8)), bit_depth(p.bit_depth) {} // utility function bool validate(void) const { uint32_t calculated_block_size = channels * (bit_depth / 8); if (block_size != calculated_block_size) { DBGLOG("There is a difference between block size" " and calculated value from a number of" " channels and bit depth: " << block_size << " != " << calculated_block_size); return false; } uint32_t calculated_data_per_sec = block_size * sampling_rate; if (data_per_sec != calculated_data_per_sec) { DBGLOG("There is a difference between a number of" " data per second and calculated value" " from block size and sampling rate: " << data_per_sec << " != " << calculated_data_per_sec); return false; } return true; } } data; // constants static const uint32_t fmt_id = quartet2uint<'f', 'm', 't', ' '>::value; // constructor fmt_subchunk_type(void) {} explicit fmt_subchunk_type(const elements_type& p) : id(fmt_id), size(sizeof(data_type)), data(p) {} // utility function bool validate(void) const { if (id != fmt_id) { DBGLOG("The id of fmt subchunk is incorrect: " << std::hex << "0x" << id << " != " << "0x" << fmt_id << std::dec); return false; } return data.validate(); } } fmt_subchunk; struct data_subchunk_type { uint32_t id; uint32_t size; // constants static const uint32_t data_id = quartet2uint<'d', 'a', 't', 'a'>::value; // constructor data_subchunk_type(void) {} explicit data_subchunk_type(const elements_type& p) : id(data_id), size(p.numof_samples * p.channels * (p.bit_depth / 8)) {} // utility function bool validate(void) const { if (id != data_id) { DBGLOG("The id of data subchunk is incorrect: " << std::hex << "0x" << id << " != " << "0x" << data_id << std::dec); return false; } return true; } } data_subchunk; // constants static const uint32_t riff_id = quartet2uint<'R', 'I', 'F', 'F'>::value; static const uint32_t wave_kind = quartet2uint<'W', 'A', 'V', 'E'>::value; static const uint32_t size_offset = sizeof(uint32_t) // size of format_kind + sizeof(fmt_subchunk_type) + sizeof(data_subchunk_type); // constructor header_type(void) {} explicit header_type(const elements_type& p) : id(riff_id), size(p.numof_samples * p.channels * (p.bit_depth / 8) + size_offset), format_kind(wave_kind), fmt_subchunk(p), data_subchunk(p) {} // utility function bool validate(void) const { if (id != riff_id) { DBGLOG("Not RIFF: " << std::hex << "0x" << id << " != " << "0x" << riff_id << std::dec); return false; } if (size != data_subchunk.size + size_offset) { DBGLOG("Data size of the RIFF chunk is incorrect: " << size << " != " << data_subchunk.size + size_offset); return false; } if (format_kind != wave_kind) { DBGLOG("Not WAV: " << std::hex << "0x" << format_kind << " != " << "0x" << wave_kind << std::dec); return false; } return fmt_subchunk.validate() && data_subchunk.validate(); } template<typename Char> inline bool validate(std::basic_istream<Char>& in) const { typename std::basic_istream<Char>::streampos current = in.tellg(); in.seekg(0, std::ios::end); uint32_t file_size = static_cast<uint32_t>(in.tellg()); in.seekg(current, std::ios::beg); uint32_t supposed_size = data_subchunk.size + sizeof(header_type); if (file_size != supposed_size) { DBGLOG("There is a difference between the wav file size" " and the size of data that is written in the" " header: " << file_size << " != " << supposed_size); return false; } return true; } template<typename Char> inline bool validate(std::basic_ostream<Char>& out) const { typename std::basic_ostream<Char>::streampos current = out.tellp(); out.seekp(0, std::ios::end); uint32_t file_size = static_cast<uint32_t>(out.tellp()); out.seekp(current, std::ios::beg); uint32_t supposed_size = data_subchunk.size + sizeof(header_type); if (file_size != supposed_size) { DBGLOG("There is a difference between the wav file size" " and the size of data that is written in the" " header: " << file_size << " != " << supposed_size); return false; } return true; } // getter // expect NRVO elements_type elements(void) { const fmt_subchunk_type::data_type& d = fmt_subchunk.data; elements_type e = { d.channels, d.bit_depth, (data_subchunk.size * 8) / (d.channels * d.bit_depth), d.sampling_rate }; return e; } }; /* * You should execute following expressions before reading header from * [i]fstream * * in.seekg(0, std::ios::beg); * */ template<typename Char> inline std::basic_istream<Char>& operator >>(std::basic_istream<Char>& in, header_type& header) { in.read( util::cast::pointer_cast<char*>(&header), sizeof(header_type)); return in; } /* * You should execute following expressions before writing header to * [o]fstream * * out.seekp(0, std::ios::beg); * */ template<typename Char> inline std::basic_ostream<Char>& operator <<(std::basic_ostream<Char>& out, const header_type& header) { out.write( util::cast::constpointer_cast<const char*>(&header), sizeof(header_type)); return out; } enum channel_type { // for mono MONO = 0, // for stereo LEFT = 0, RIGHT, // for 5.1ch FRONT_LEFT = 0, FRONT_RIGHT, FRONT_CENTER, LOW_FREQUENCY, BACK_LEFT, BACK_RIGHT }; /* * the class to manipulate data * */ template<const unsigned int Channels, const unsigned int Byte> class basic_sample { public: typedef basic_sample<1, Byte> mono_type; typedef char value8_type; typedef uint16_t value16_type; typedef uint32_t value24_type; typedef uint32_t value32_type; private: char data[Byte * Channels]; public: // constructor basic_sample(void) {} basic_sample(const char* rhs) { std::copy(rhs, rhs + Byte, data); } // to get data of a channel mono_type channel(channel_type ch) const { assert(ch < Channels); return mono_type(&data[Byte * ch]); } // to get value of a channel in the form of char char value8(channel_type ch) const { assert(ch < Channels); assert(Byte == 1); return data[ch]; } // to get value of a channel in the form of uint16_t uint16_t value16(channel_type ch) const { assert(ch < Channels); assert(Byte == 2); return *(util::cast::constpointer_cast<const uint16_t*>( &data[ch * 2])); } // to get value of a channel in the form of uint32_t uint32_t value24(channel_type ch) const { assert(ch < Channels); assert(Byte == 3); return *(util::cast::constpointer_cast<const uint32_t*>( &data[ch * 4])) & 0x00ffffff; } // to get value of a channel in the form of uint32_t uint32_t value32(channel_type ch) const { assert(ch < Channels); assert(Byte == 4); return *(util::cast::constpointer_cast<const uint32_t*>( &data[ch * 4])); } }; template<const unsigned int Channels, const unsigned int Byte> inline std::istream& operator >>(std::istream& i, basic_sample<Channels, Byte>& m) { i.read(util::cast::pointer_cast<char*>(&m), sizeof(m)); return i; } template<const unsigned int Channels, const unsigned int Byte> inline std::ostream& operator <<(std::ostream& o, const basic_sample<Channels, Byte>& m) { o.write(util::cast::constpointer_cast<const char*>(&m), sizeof(m)); return o; } } } #endif // WAV_HPP <commit_msg>Fix warnings<commit_after>/* * wav.hpp * A struct to read / write headers in the form of RIFF WAV linear PCM * * written by janus_wel<janus.wel.3@gmail.com> * This source code is in public domain, and has NO WARRANTY. * * refer * RIFF WAV specifications * http://msdn.microsoft.com/en-us/library/ms713231.aspx * http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html * */ #ifndef WAV_HPP #define WAV_HPP #include <cassert> #include <fstream> #include <istream> #include <ostream> #include <stdint.h> #include "cast.hpp" #include "dlogger.hpp" namespace format { namespace riff_wav { // utilitie functions // This function return little-endian value. // RIFF WAV file is written as little-endian, then we've met our needs // by this. template<const char _1, const char _2, const char _3, const char _4> struct quartet2uint { static const uint32_t value = static_cast<uint32_t>(_1) + (_2 << 8) + (_3 << 16) + (_4 << 24); }; // basic properties of linear PCM data struct elements_type { uint16_t channels; uint16_t bit_depth; uint32_t numof_samples; uint32_t sampling_rate; }; /* * The struct for RIFF WAV header * that doesn't contain actual audio data(wav samples). * * RIFF WAV file has: * RIFF chunk * * RIFF chunk has: * id "RIFF" * size 4 + sizeof(data) * format-kind "WAVE" * data fmt subchunk, data subchunk * * fmt subchunk * id "fmt " * size 16 * data fmt-code, channels, sampling-rate, data-per-sec, * block-size, bit-depth * * data subchunk * id "data" * size sizeof(data) * data samples (excluded) * * fmt id: linear PCM(0x01) * 0 1 2 3 4 5 6 7 8 9 a b c d e f * +---------------+---------------+---------------+---------------+ * 0x00 |'R' 'I' 'F' 'F'| riff size |'W' 'A' 'V' 'E'|'f' 'm' 't' ' '| * +---------------+-------+-------+---------------+---------------+ * 0x10 |fmt subchk size| code | ch | sampling rate | data per sec | * +-------+-------+-------+-------+---------------+---------------+ * 0x20 |blk sz |bit dep|'d' 'a' 't' 'a'| data size | samples ... * +-------+-------+---------------+---------------+ * */ struct header_type { // member variables uint32_t id; uint32_t size; uint32_t format_kind; struct fmt_subchunk_type { uint32_t id; uint32_t size; struct data_type { uint16_t code; uint16_t channels; uint32_t sampling_rate; uint32_t data_per_sec; uint16_t block_size; uint16_t bit_depth; // constants enum { LINEAR_PCM = 1 }; // constructor data_type(void) {} explicit data_type(const elements_type& p) : code(LINEAR_PCM), channels(p.channels), sampling_rate(p.sampling_rate), data_per_sec(p.sampling_rate * p.channels * (p.bit_depth / 8)), block_size(p.channels * (p.bit_depth / 8)), bit_depth(p.bit_depth) {} // utility function bool validate(void) const { uint32_t calculated_block_size = channels * (bit_depth / 8); if (block_size != calculated_block_size) { DBGLOG("There is a difference between block size" " and calculated value from a number of" " channels and bit depth: " << block_size << " != " << calculated_block_size); return false; } uint32_t calculated_data_per_sec = block_size * sampling_rate; if (data_per_sec != calculated_data_per_sec) { DBGLOG("There is a difference between a number of" " data per second and calculated value" " from block size and sampling rate: " << data_per_sec << " != " << calculated_data_per_sec); return false; } return true; } } data; // constants static const uint32_t fmt_id = quartet2uint<'f', 'm', 't', ' '>::value; // constructor fmt_subchunk_type(void) {} explicit fmt_subchunk_type(const elements_type& p) : id(fmt_id), size(sizeof(data_type)), data(p) {} // utility function bool validate(void) const { if (id != fmt_id) { DBGLOG("The id of fmt subchunk is incorrect: " << std::hex << "0x" << id << " != " << "0x" << fmt_id << std::dec); return false; } return data.validate(); } } fmt_subchunk; struct data_subchunk_type { uint32_t id; uint32_t size; // constants static const uint32_t data_id = quartet2uint<'d', 'a', 't', 'a'>::value; // constructor data_subchunk_type(void) {} explicit data_subchunk_type(const elements_type& p) : id(data_id), size(p.numof_samples * p.channels * (p.bit_depth / 8)) {} // utility function bool validate(void) const { if (id != data_id) { DBGLOG("The id of data subchunk is incorrect: " << std::hex << "0x" << id << " != " << "0x" << data_id << std::dec); return false; } return true; } } data_subchunk; // constants static const uint32_t riff_id = quartet2uint<'R', 'I', 'F', 'F'>::value; static const uint32_t wave_kind = quartet2uint<'W', 'A', 'V', 'E'>::value; static const uint32_t size_offset = sizeof(uint32_t) // size of format_kind + sizeof(fmt_subchunk_type) + sizeof(data_subchunk_type); // constructor header_type(void) {} explicit header_type(const elements_type& p) : id(riff_id), size(p.numof_samples * p.channels * (p.bit_depth / 8) + size_offset), format_kind(wave_kind), fmt_subchunk(p), data_subchunk(p) {} // utility function bool validate(void) const { if (id != riff_id) { DBGLOG("Not RIFF: " << std::hex << "0x" << id << " != " << "0x" << riff_id << std::dec); return false; } if (size != data_subchunk.size + size_offset) { DBGLOG("Data size of the RIFF chunk is incorrect: " << size << " != " << data_subchunk.size + size_offset); return false; } if (format_kind != wave_kind) { DBGLOG("Not WAV: " << std::hex << "0x" << format_kind << " != " << "0x" << wave_kind << std::dec); return false; } return fmt_subchunk.validate() && data_subchunk.validate(); } template<typename Char> inline bool validate(std::basic_istream<Char>& in) const { typename std::basic_istream<Char>::streampos current = in.tellg(); in.seekg(0, std::ios::end); uint32_t file_size = static_cast<uint32_t>(in.tellg()); in.seekg(current, std::ios::beg); uint32_t supposed_size = data_subchunk.size + sizeof(header_type); if (file_size != supposed_size) { DBGLOG("There is a difference between the wav file size" " and the size of data that is written in the" " header: " << file_size << " != " << supposed_size); return false; } return true; } template<typename Char> inline bool validate(std::basic_ostream<Char>& out) const { typename std::basic_ostream<Char>::streampos current = out.tellp(); out.seekp(0, std::ios::end); uint32_t file_size = static_cast<uint32_t>(out.tellp()); out.seekp(current, std::ios::beg); uint32_t supposed_size = data_subchunk.size + sizeof(header_type); if (file_size != supposed_size) { DBGLOG("There is a difference between the wav file size" " and the size of data that is written in the" " header: " << file_size << " != " << supposed_size); return false; } return true; } // getter // expect NRVO elements_type elements(void) { const fmt_subchunk_type::data_type& d = fmt_subchunk.data; elements_type e = { d.channels, d.bit_depth, (data_subchunk.size * 8) / (d.channels * d.bit_depth), d.sampling_rate }; return e; } }; /* * You should execute following expressions before reading header from * [i]fstream * * in.seekg(0, std::ios::beg); * */ template<typename Char> inline std::basic_istream<Char>& operator >>(std::basic_istream<Char>& in, header_type& header) { in.read( util::cast::pointer_cast<char*>(&header), sizeof(header_type)); return in; } /* * You should execute following expressions before writing header to * [o]fstream * * out.seekp(0, std::ios::beg); * */ template<typename Char> inline std::basic_ostream<Char>& operator <<(std::basic_ostream<Char>& out, const header_type& header) { out.write( util::cast::constpointer_cast<const char*>(&header), sizeof(header_type)); return out; } enum channel_type { // for mono MONO = 0, // for stereo LEFT = 0, RIGHT, // for 5.1ch FRONT_LEFT = 0, FRONT_RIGHT, FRONT_CENTER, LOW_FREQUENCY, BACK_LEFT, BACK_RIGHT }; /* * the class to manipulate data * */ template<const unsigned int Channels, const unsigned int Byte> class basic_sample { public: typedef basic_sample<1, Byte> mono_type; typedef char value8_type; typedef uint16_t value16_type; typedef uint32_t value24_type; typedef uint32_t value32_type; private: char data[Byte * Channels]; public: // constructor basic_sample(void) {} basic_sample(const char* rhs) { std::copy(rhs, rhs + Byte, data); } // to get data of a channel mono_type channel(channel_type ch) const { assert(static_cast<unsigned int>(ch) < Channels); return mono_type(&data[Byte * ch]); } // to get value of a channel in the form of char char value8(channel_type ch) const { assert(static_cast<unsigned int>(ch) < Channels); assert(Byte == 1); return data[ch]; } // to get value of a channel in the form of uint16_t uint16_t value16(channel_type ch) const { assert(static_cast<unsigned int>(ch) < Channels); assert(Byte == 2); return *(util::cast::constpointer_cast<const uint16_t*>( &data[ch * 2])); } // to get value of a channel in the form of uint32_t uint32_t value24(channel_type ch) const { assert(static_cast<unsigned int>(ch) < Channels); assert(Byte == 3); return *(util::cast::constpointer_cast<const uint32_t*>( &data[ch * 4])) & 0x00ffffff; } // to get value of a channel in the form of uint32_t uint32_t value32(channel_type ch) const { assert(static_cast<unsigned int>(ch) < Channels); assert(Byte == 4); return *(util::cast::constpointer_cast<const uint32_t*>( &data[ch * 4])); } }; template<const unsigned int Channels, const unsigned int Byte> inline std::istream& operator >>(std::istream& i, basic_sample<Channels, Byte>& m) { i.read(util::cast::pointer_cast<char*>(&m), sizeof(m)); return i; } template<const unsigned int Channels, const unsigned int Byte> inline std::ostream& operator <<(std::ostream& o, const basic_sample<Channels, Byte>& m) { o.write(util::cast::constpointer_cast<const char*>(&m), sizeof(m)); return o; } } } #endif // WAV_HPP <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 3:53:32 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll W, H, K; public: Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {} ll answer() { ll ans{0}; for (auto s{0LL}; s < W - 1; ++s) { for (auto y{1LL}; rhs_bound(s, y) >= 0 && y < H; ++y) { ll tmp{calc(s, y)}; if (s == 0) { ans += tmp; } else { ans += 2 * tmp; } } } return ans; } private: ll rhs(ll s, ll y) { return 2 * K - s * (H - y) + gcd(s, H) - 2; } ll rhs_bound(ll s, ll y) { return 2 * K - s * (H - y) + H - 2; } ll lhs(ll x, ll s, ll y) { return H * x - gcd(H - y, x) - gcd(y, x + s); } ll calc(ll s, ll y) { ll R{rhs(s, y)}; if (R < 0) { return 0; } ll ans{min(W - s - 1, R / H)}; ll x{R / H + 1}; if (x + s < W && lhs(x, s, y) <= R) { ++ans; } return ans; } }; // ----- main() ----- int main() { ll W, H, K; cin >> W >> H >> K; Solve solve(W, H, K), solve2(H, W, K); ll ans{2 * solve.answer() + 2 * solve2.answer()}; cout << ans << endl; } <commit_msg>submit F.cpp to 'F - Triangles' (tokiomarine2020) [C++ (GCC 9.2.1)]<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 3:53:32 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll W, H, K; public: Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {} ll answer() { ll ans{0}; for (auto s{0LL}; s < W - 1; ++s) { for (auto y{H - 1}; rhs_bound(s, y) >= 0 && y > 0; --y) { ll tmp{calc(s, y)}; if (s == 0) { ans += tmp; } else { ans += 2 * tmp; } } } return ans; } private: ll rhs(ll s, ll y) { return 2 * K - s * (H - y) + gcd(s, H) - 2; } ll rhs_bound(ll s, ll y) { return 2 * K - s * (H - y) + H - 2; } ll lhs(ll x, ll s, ll y) { return H * x - gcd(H - y, x) - gcd(y, x + s); } ll calc(ll s, ll y) { ll R{rhs(s, y)}; if (R < 0) { return 0; } ll ans{min(W - s - 1, R / H)}; ll x{R / H + 1}; if (x + s < W && lhs(x, s, y) <= R) { ++ans; } return ans; } }; // ----- main() ----- int main() { ll W, H, K; cin >> W >> H >> K; Solve solve(W, H, K), solve2(H, W, K); ll ans{2 * solve.answer() + 2 * solve2.answer()}; cout << ans << endl; } <|endoftext|>
<commit_before>#pragma once #include <memory> #include <utility> #include <type_traits> #include "signal.hpp" namespace eventpp { namespace details { template<class E> struct ETag { using type = E; }; template<int N, int M> struct Choice: public Choice<N+1, M> { }; template<int N> struct Choice<N, N> { }; template<typename... T> using VoidType = void; template<typename, typename, typename = VoidType<>> struct HasReceiveMember: std::false_type { }; template<typename C, typename E> struct HasReceiveMember < C, E, VoidType<decltype(std::declval<C>().receive(std::declval<E>()))> >: std::true_type { }; template<typename C, typename E> constexpr bool HasReceiveMemberValue = HasReceiveMember<C, E>::value; } template<class D> struct Receiver: public std::enable_shared_from_this<D> { }; template<int S, class... T> class BusBase; template<int S, class E, class... O> class BusBase<S, E, O...>: public BusBase<S, O...> { using Base = BusBase<S, O...>; protected: using Base::get; using Base::reg; using Base::unreg; Signal<E>& get(details::ETag<E>) { return signal; } template<class C> std::enable_if_t<details::HasReceiveMemberValue<C, E>, void> reg(details::Choice<S-(sizeof...(O)+1), S>, std::weak_ptr<C> ptr) { signal.template add<C, &C::receive>(ptr); Base::reg(details::Choice<S-sizeof...(O), S>{}, ptr); } template<class C> std::enable_if_t<details::HasReceiveMemberValue<C, E>, void> unreg(details::Choice<S-(sizeof...(O)+1), S>, std::weak_ptr<C> ptr) { signal.template remove<C, &C::receive>(ptr); Base::unreg(details::Choice<S-sizeof...(O), S>{}, ptr); } std::size_t size() const noexcept { return signal.size() + Base::size(); } private: Signal<E> signal; }; template<int S> class BusBase<S> { protected: virtual ~BusBase() { } void get(); void reg(details::Choice<S, S>, std::weak_ptr<void>) { } void unreg(details::Choice<S, S>, std::weak_ptr<void>) { } std::size_t size() const noexcept { return 0; } }; template<class... T> class Bus: public BusBase<sizeof...(T), T...> { using Base = BusBase<sizeof...(T), T...>; public: using Base::size; template<class C, template<typename> class P> typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type reg(P<C> &ptr) { auto wptr = static_cast<std::weak_ptr<C>>(ptr); Base::reg(details::Choice<0, sizeof...(T)>{}, wptr); } template<class C, template<typename> class P> typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type unreg(P<C> &ptr) { auto wptr = static_cast<std::weak_ptr<C>>(ptr); Base::unreg(details::Choice<0, sizeof...(T)>{}, wptr); } template<class E, void(*F)(const E &)> void add() { Signal<E> &signal = Base::get(details::ETag<E>{}); signal.template add<F>(); } template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P> typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type add(P<C> &ptr) { Signal<E> &signal = Base::get(details::ETag<E>{}); auto wptr = static_cast<std::weak_ptr<C>>(ptr); signal.template add<C, M>(wptr); } template<class E, void(*F)(const E &)> void remove() { Signal<E> &signal = Base::get(details::ETag<E>{}); signal.template remove<F>(); } template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P> typename std::enable_if<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void>::type remove(P<C> &ptr) { Signal<E> &signal = Base::get(details::ETag<E>{}); auto wptr = static_cast<std::weak_ptr<C>>(ptr); signal.template remove<C, M>(wptr); } template<class E, class... A> void publish(A&&... args) { Signal<E> &signal = Base::get(details::ETag<E>{}); E e(std::forward<A>(args)...); signal.publish(e); } }; } <commit_msg>minor changes<commit_after>#pragma once #include <memory> #include <utility> #include <type_traits> #include "signal.hpp" namespace eventpp { namespace details { template<class E> struct ETag { using type = E; }; template<int N, int M> struct Choice: public Choice<N+1, M> { }; template<int N> struct Choice<N, N> { }; template<typename... T> using VoidType = void; template<typename, typename, typename = VoidType<>> struct HasReceiveMember: std::false_type { }; template<typename C, typename E> struct HasReceiveMember < C, E, VoidType<decltype(std::declval<C>().receive(std::declval<E>()))> >: std::true_type { }; template<typename C, typename E> constexpr bool HasReceiveMemberValue = HasReceiveMember<C, E>::value; } template<class D> struct Receiver: public std::enable_shared_from_this<D> { }; template<int S, class... T> class BusBase; template<int S, class E, class... O> class BusBase<S, E, O...>: public BusBase<S, O...> { using Base = BusBase<S, O...>; protected: using Base::get; using Base::reg; using Base::unreg; Signal<E>& get(details::ETag<E>) { return signal; } template<class C> std::enable_if_t<details::HasReceiveMemberValue<C, E>> reg(details::Choice<S-(sizeof...(O)+1), S>, std::weak_ptr<C> ptr) { signal.template add<C, &C::receive>(ptr); Base::reg(details::Choice<S-sizeof...(O), S>{}, ptr); } template<class C> std::enable_if_t<details::HasReceiveMemberValue<C, E>> unreg(details::Choice<S-(sizeof...(O)+1), S>, std::weak_ptr<C> ptr) { signal.template remove<C, &C::receive>(ptr); Base::unreg(details::Choice<S-sizeof...(O), S>{}, ptr); } std::size_t size() const noexcept { return signal.size() + Base::size(); } private: Signal<E> signal; }; template<int S> class BusBase<S> { protected: virtual ~BusBase() { } void get(); void reg(details::Choice<S, S>, std::weak_ptr<void>) { } void unreg(details::Choice<S, S>, std::weak_ptr<void>) { } std::size_t size() const noexcept { return 0; } }; template<class... T> class Bus: public BusBase<sizeof...(T), T...> { using Base = BusBase<sizeof...(T), T...>; public: using Base::size; template<class C, template<typename> class P> std::enable_if_t<std::is_convertible<P<C>, std::weak_ptr<C>>::value> reg(P<C> &ptr) { auto wptr = static_cast<std::weak_ptr<C>>(ptr); Base::reg(details::Choice<0, sizeof...(T)>{}, wptr); } template<class C, template<typename> class P> std::enable_if_t<std::is_convertible<P<C>, std::weak_ptr<C>>::value> unreg(P<C> &ptr) { auto wptr = static_cast<std::weak_ptr<C>>(ptr); Base::unreg(details::Choice<0, sizeof...(T)>{}, wptr); } template<class E, void(*F)(const E &)> void add() { Signal<E> &signal = Base::get(details::ETag<E>{}); signal.template add<F>(); } template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P> std::enable_if_t<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void> add(P<C> &ptr) { Signal<E> &signal = Base::get(details::ETag<E>{}); auto wptr = static_cast<std::weak_ptr<C>>(ptr); signal.template add<C, M>(wptr); } template<class E, void(*F)(const E &)> void remove() { Signal<E> &signal = Base::get(details::ETag<E>{}); signal.template remove<F>(); } template<class E, class C, void(C::*M)(const E &) = &C::receive, template<typename> class P> std::enable_if_t<std::is_convertible<P<C>, std::weak_ptr<C>>::value, void> remove(P<C> &ptr) { Signal<E> &signal = Base::get(details::ETag<E>{}); auto wptr = static_cast<std::weak_ptr<C>>(ptr); signal.template remove<C, M>(wptr); } template<class E, class... A> void publish(A&&... args) { Signal<E> &signal = Base::get(details::ETag<E>{}); E e(std::forward<A>(args)...); signal.publish(e); } }; } <|endoftext|>
<commit_before>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file cnf_view.hpp \brief Creates a CNF while creating a network \author Mathias Soeken */ #pragma once #include <cstdint> #include <vector> #include "../algorithms/cnf.hpp" #include "../traits.hpp" #include <fmt/format.h> #include <percy/solvers/bsat2.hpp> namespace mockturtle { /*! \brief A view to connect logic network creation to SAT solving. * * When using this view to create a new network, it creates a CNF internally * while nodes are added to the network. It also contains a SAT solver. The * network can be solved by calling the `solve` method, which by default assumes * that each output should compute `true` (an overload of the `solve` method can * override this default behaviour and apply custom assumptions). Further, * the methods `value` and `pi_values` can be used to access model values in * case solving was satisfiable. Finally, methods `var` and `lit` can be used * to access variable and literal information for nodes and signals, * respectively, in order to add custom clauses with the `add_clause` methods. * * The CNF is generated additively and cannot be modified after nodes have been * added. Therefore, a network cannot modify or delete nodes when wrapped in a * `cnf_view`. */ template<typename Ntk> class cnf_view : public Ntk { public: using storage = typename Ntk::storage; using node = typename Ntk::node; using signal = typename Ntk::signal; public: // can only be constructed as empty network cnf_view() : Ntk() { static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" ); static_assert( has_node_to_index_v<Ntk>, "Ntk does not implement the node_to_index method" ); static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" ); static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" ); static_assert( has_foreach_pi_v<Ntk>, "Ntk does not implement the foreach_pi method" ); static_assert( has_foreach_po_v<Ntk>, "Ntk does not implement the foreach_po method" ); static_assert( has_foreach_fanin_v<Ntk>, "Ntk does not implement the foreach_fanin method" ); static_assert( has_node_function_v<Ntk>, "Ntk does not implement the node_function method" ); register_events(); } /* \brief Returns the variable associated to a node. */ inline uint32_t var( node const& n ) const { return Ntk::node_to_index( n ); } /*! \brief Returns the literal associated to a signal. */ inline uint32_t lit( signal const& f ) const { return make_lit( var( Ntk::get_node( f ) ), Ntk::is_complemented( f ) ); } /*! \brief Solves the network with a set of custom assumptions. * * This function does not assert any primary output, unless specified * explicitly through the assumptions. * * The function returns `nullopt`, if no solution can be found (due to a * conflict limit), or `true` in case of SAT, and `false` in case of UNSAT. * * \param assumptions Vector of literals to be assumped when solving * \param limit Conflict limit (unlimited if 0) */ inline std::optional<bool> solve( std::vector<int> assumptions, int limit = 0 ) { switch ( solver_.solve( &assumptions[0], &assumptions[0] + assumptions.size(), limit ) ) { case percy::success: return true; case percy::failure: return false; default: case percy::timeout: return std::nullopt; } } /*! \brief Solves the network by asserting all primary outputs to be true * * The function returns `nullopt`, if no solution can be found (due to a * conflict limit), or `true` in case of SAT, and `false` in case of UNSAT. * * \param limit Conflict limit (unlimited if 0) */ inline std::optional<bool> solve( int limit = 0 ) { std::vector<int> assumptions; Ntk::foreach_po( [&]( auto const& f ) { assumptions.push_back( lit( f ) ); } ); return solve( assumptions, limit ); } /*! \brief Return model value for a node. */ inline bool value( node const& n ) { return solver_.var_value( var( n ) ); } /* \brief Returns all model values for all primary inputs. */ std::vector<bool> pi_values() { std::vector<bool> values( Ntk::num_pis() ); Ntk::foreach_pi( [&]( auto const& n, auto i ) { values[i] = value( n ); } ); return values; } /*! \brief Blocks last model for primary input values. */ void block() { std::vector<uint32_t> blocking_clause( Ntk::num_pis() ); Ntk::foreach_pi( [&]( auto const& n, auto i ) { blocking_clause[i] = make_lit( var( n ), value( n ) ); }); add_clause( blocking_clause ); } /*! \brief Adds a clause to the solver. */ void add_clause( std::vector<uint32_t> const& clause ) { solver_.add_clause( clause ); } /*! \brief Adds a clause to the solver. */ template<typename... Lit, typename = std::enable_if_t<std::conjunction_v<std::is_same<Lit, uint32_t>...>>> void add_clause( Lit... lits ) { solver_.add_clause( std::vector<uint32_t>{{lits...}} ); } private: void register_events() { Ntk::events().on_add.push_back( [this]( auto const& n ) { on_add( n ); } ); Ntk::events().on_modified.push_back( []( auto const& n, auto const& previous ) { (void)n; (void)previous; assert( false && "nodes should not be modified in cnf_view" ); std::abort(); } ); Ntk::events().on_delete.push_back( []( auto const& n ) { (void)n; assert( false && "nodes should not be deleted in cnf_view" ); std::abort(); } ); } void on_add( node const& n ) { const auto _add_clause = [&]( std::vector<uint32_t> const& clause ) { add_clause( clause ); }; const auto node_lit = lit( Ntk::make_signal( n ) ); std::vector<uint32_t> child_lits; Ntk::foreach_fanin( n, [&]( auto const& f ) { child_lits.push_back( lit( f ) ); } ); if constexpr ( has_is_and_v<Ntk> ) { if ( Ntk::is_and( n ) ) { detail::on_and( node_lit, child_lits[0], child_lits[1], _add_clause ); return; } } if constexpr ( has_is_or_v<Ntk> ) { if ( Ntk::is_or( n ) ) { detail::on_or( node_lit, child_lits[0], child_lits[1], _add_clause ); return; } } if constexpr ( has_is_xor_v<Ntk> ) { if ( Ntk::is_xor( n ) ) { detail::on_xor( node_lit, child_lits[0], child_lits[1], _add_clause ); return; } } if constexpr ( has_is_maj_v<Ntk> ) { if ( Ntk::is_maj( n ) ) { detail::on_maj( node_lit, child_lits[0], child_lits[1], child_lits[2], _add_clause ); return; } } if constexpr ( has_is_ite_v<Ntk> ) { if ( Ntk::is_ite( n ) ) { detail::on_ite( node_lit, child_lits[0], child_lits[1], child_lits[2], _add_clause ); return; } } if constexpr ( has_is_xor3_v<Ntk> ) { if ( Ntk::is_xor3( n ) ) { detail::on_xor3( node_lit, child_lits[0], child_lits[1], child_lits[2], _add_clause ); return; } } detail::on_function( node_lit, child_lits, Ntk::node_function( n ), _add_clause ); } private: percy::bsat_wrapper solver_; }; } /* namespace mockturtle */ <commit_msg>Convenience in add_clause, stats. (#284)<commit_after>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file cnf_view.hpp \brief Creates a CNF while creating a network \author Mathias Soeken */ #pragma once #include <cstdint> #include <vector> #include "../algorithms/cnf.hpp" #include "../traits.hpp" #include <fmt/format.h> #include <percy/solvers/bsat2.hpp> namespace mockturtle { /*! \brief A view to connect logic network creation to SAT solving. * * When using this view to create a new network, it creates a CNF internally * while nodes are added to the network. It also contains a SAT solver. The * network can be solved by calling the `solve` method, which by default assumes * that each output should compute `true` (an overload of the `solve` method can * override this default behaviour and apply custom assumptions). Further, * the methods `value` and `pi_values` can be used to access model values in * case solving was satisfiable. Finally, methods `var` and `lit` can be used * to access variable and literal information for nodes and signals, * respectively, in order to add custom clauses with the `add_clause` methods. * * The CNF is generated additively and cannot be modified after nodes have been * added. Therefore, a network cannot modify or delete nodes when wrapped in a * `cnf_view`. */ template<typename Ntk> class cnf_view : public Ntk { public: using storage = typename Ntk::storage; using node = typename Ntk::node; using signal = typename Ntk::signal; public: // can only be constructed as empty network cnf_view() : Ntk() { static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" ); static_assert( has_node_to_index_v<Ntk>, "Ntk does not implement the node_to_index method" ); static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" ); static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" ); static_assert( has_foreach_pi_v<Ntk>, "Ntk does not implement the foreach_pi method" ); static_assert( has_foreach_po_v<Ntk>, "Ntk does not implement the foreach_po method" ); static_assert( has_foreach_fanin_v<Ntk>, "Ntk does not implement the foreach_fanin method" ); static_assert( has_node_function_v<Ntk>, "Ntk does not implement the node_function method" ); register_events(); } /* \brief Returns the variable associated to a node. */ inline uint32_t var( node const& n ) const { return Ntk::node_to_index( n ); } /*! \brief Returns the literal associated to a signal. */ inline uint32_t lit( signal const& f ) const { return make_lit( var( Ntk::get_node( f ) ), Ntk::is_complemented( f ) ); } /*! \brief Solves the network with a set of custom assumptions. * * This function does not assert any primary output, unless specified * explicitly through the assumptions. * * The function returns `nullopt`, if no solution can be found (due to a * conflict limit), or `true` in case of SAT, and `false` in case of UNSAT. * * \param assumptions Vector of literals to be assumped when solving * \param limit Conflict limit (unlimited if 0) */ inline std::optional<bool> solve( std::vector<int> assumptions, int limit = 0 ) { switch ( solver_.solve( &assumptions[0], &assumptions[0] + assumptions.size(), limit ) ) { case percy::success: return true; case percy::failure: return false; default: case percy::timeout: return std::nullopt; } } /*! \brief Solves the network by asserting all primary outputs to be true * * The function returns `nullopt`, if no solution can be found (due to a * conflict limit), or `true` in case of SAT, and `false` in case of UNSAT. * * \param limit Conflict limit (unlimited if 0) */ inline std::optional<bool> solve( int limit = 0 ) { std::vector<int> assumptions; Ntk::foreach_po( [&]( auto const& f ) { assumptions.push_back( lit( f ) ); } ); return solve( assumptions, limit ); } /*! \brief Return model value for a node. */ inline bool value( node const& n ) { return solver_.var_value( var( n ) ); } /* \brief Returns all model values for all primary inputs. */ std::vector<bool> pi_values() { std::vector<bool> values( Ntk::num_pis() ); Ntk::foreach_pi( [&]( auto const& n, auto i ) { values[i] = value( n ); } ); return values; } /*! \brief Blocks last model for primary input values. */ void block() { std::vector<uint32_t> blocking_clause( Ntk::num_pis() ); Ntk::foreach_pi( [&]( auto const& n, auto i ) { blocking_clause[i] = make_lit( var( n ), value( n ) ); }); add_clause( blocking_clause ); } /*! \brief Number of variables. */ inline uint32_t num_vars() { return solver_.nr_vars(); } /*! \brief Number of clauses. */ inline uint32_t num_clauses() { return solver_.nr_clauses(); } /*! \brief Adds a clause to the solver. */ void add_clause( std::vector<uint32_t> const& clause ) { solver_.add_clause( clause ); } /*! \brief Adds a clause to the solver. * * Entries are either all literals or network signals. */ template<typename... Lit, typename = std::enable_if_t< std::disjunction_v< std::conjunction<std::is_same<Lit, uint32_t>...>, std::conjunction<std::is_same<Lit, signal>...>>>> void add_clause( Lit... lits ) { if constexpr ( std::conjunction_v<std::is_same<Lit, uint32_t>...> ) { solver_.add_clause( std::vector<uint32_t>{{lits...}} ); } else { solver_.add_clause( std::vector<uint32_t>{{lit( lits )...}} ); } } private: void register_events() { Ntk::events().on_add.push_back( [this]( auto const& n ) { on_add( n ); } ); Ntk::events().on_modified.push_back( []( auto const& n, auto const& previous ) { (void)n; (void)previous; assert( false && "nodes should not be modified in cnf_view" ); std::abort(); } ); Ntk::events().on_delete.push_back( []( auto const& n ) { (void)n; assert( false && "nodes should not be deleted in cnf_view" ); std::abort(); } ); } void on_add( node const& n ) { const auto _add_clause = [&]( std::vector<uint32_t> const& clause ) { add_clause( clause ); }; const auto node_lit = lit( Ntk::make_signal( n ) ); std::vector<uint32_t> child_lits; Ntk::foreach_fanin( n, [&]( auto const& f ) { child_lits.push_back( lit( f ) ); } ); if constexpr ( has_is_and_v<Ntk> ) { if ( Ntk::is_and( n ) ) { detail::on_and( node_lit, child_lits[0], child_lits[1], _add_clause ); return; } } if constexpr ( has_is_or_v<Ntk> ) { if ( Ntk::is_or( n ) ) { detail::on_or( node_lit, child_lits[0], child_lits[1], _add_clause ); return; } } if constexpr ( has_is_xor_v<Ntk> ) { if ( Ntk::is_xor( n ) ) { detail::on_xor( node_lit, child_lits[0], child_lits[1], _add_clause ); return; } } if constexpr ( has_is_maj_v<Ntk> ) { if ( Ntk::is_maj( n ) ) { detail::on_maj( node_lit, child_lits[0], child_lits[1], child_lits[2], _add_clause ); return; } } if constexpr ( has_is_ite_v<Ntk> ) { if ( Ntk::is_ite( n ) ) { detail::on_ite( node_lit, child_lits[0], child_lits[1], child_lits[2], _add_clause ); return; } } if constexpr ( has_is_xor3_v<Ntk> ) { if ( Ntk::is_xor3( n ) ) { detail::on_xor3( node_lit, child_lits[0], child_lits[1], child_lits[2], _add_clause ); return; } } detail::on_function( node_lit, child_lits, Ntk::node_function( n ), _add_clause ); } private: percy::bsat_wrapper solver_; }; } /* namespace mockturtle */ <|endoftext|>
<commit_before>#include <jni.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <android/log.h> #include "cpu/CPUOdroid.h" #include "cpu/CPUNexus5.h" #include "gpu/GPUOdroid.h" #include "gpu/GPUNexus5.h" #include "IOStuff.h" #include "RetrieveModel.h" #define CLASSNAME "DVFS-ndk" #define POLL_RATE_IN_MICROSECOND 1000000 //1 second #define DO_NOT_PURSUE_FPS_VALUE -1 #define TARGET_CPU_UTILISATION 80 int fpsLowBound; int fpsHighBound; int slidingWindowLength; bool dvfsInProgress; int currentSlidingWindowPosition; pthread_t threadTask; void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength); void * threadFunction(void *arg); int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1); int shouldPursueFPSRecalculationToThisFPS(int fps); void processInputs(int currentFPS, int newFPSValue, bool fpsInRange, CPU * cpu, GPU * gpu); void runThisRegularly(CPU * cpu, GPU * gpu); int findLowestFreqPositionThatMeetsThisCost(double costToMeet, vector<long> availableFrequencies, float factor); void makeCPUMeetThisFPS(int targetFPS, int currentFPS, CPU * cpu); void makeGPUMeetThisFPS(int targetFPS, int currentFPS, GPU * gpu); extern "C" JNIEXPORT void JNICALL Java_com_example_dvfs_DVFSNdk_startDVFS( JNIEnv* env, jobject thiz, jint fpsLowbound, jint fpsHighBound, jint slidingWindowLength){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "lowbound: %d, highbound: %d, slidingWindow: %d", fpsLowbound, fpsHighBound, slidingWindowLength); startDVFS(fpsLowbound, fpsHighBound, slidingWindowLength); } extern "C" JNIEXPORT void JNICALL Java_com_example_dvfs_DVFSNdk_stopDVFS( JNIEnv* env, jobject thiz ){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Stop DVFS"); dvfsInProgress = false; } void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength){ fpsLowBound = _fpsLowBound; fpsHighBound = _fpsHighBound; slidingWindowLength = _slidingWindowLength; dvfsInProgress = true; pthread_create(&threadTask, NULL, threadFunction, NULL); } //From http://stackoverflow.com/questions/1468596/calculating-elapsed-time-in-a-c-program-in-milliseconds /* Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1){ long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); result->tv_sec = diff / 1000000; result->tv_usec = diff % 1000000; return (diff<0); } void * threadFunction(void *arg){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Thread function start"); startShell(); __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Shell started"); CPU * cpu; GPU * gpu; __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "After var declaration"); if(isPhoneNexus5()){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Model %s", "Nexus 5"); cpu = new CPUNexus5(); gpu = new GPUNexus5(); } else { __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Model %s", "Not Nexus 5"); cpu = new CPUOdroid(); gpu = new GPUOdroid(); } struct timeval tvBegin, tvEnd, tvDiff; while(dvfsInProgress){ gettimeofday(&tvBegin, NULL); runThisRegularly(cpu, gpu); gettimeofday(&tvEnd, NULL); timeval_subtract(&tvDiff, &tvEnd, &tvBegin); int elapsedTime = tvDiff.tv_usec; //This is to calculate how much time to sleep before the next poll if(elapsedTime < POLL_RATE_IN_MICROSECOND){ int timeToSleep = POLL_RATE_IN_MICROSECOND - elapsedTime; usleep(timeToSleep); } } free(gpu); free(cpu); stopShell(); return NULL; } int shouldPursueFPSRecalculationToThisFPS(int fps){ if(fps > fpsHighBound){ //We need to decrease FPS return fpsLowBound; } else if(fps < fpsLowBound){ //We need to increase FPS return fpsHighBound; } else { currentSlidingWindowPosition = 0; return DO_NOT_PURSUE_FPS_VALUE; } } void runThisRegularly(CPU * cpu, GPU * gpu){ int currentFPS = gpu->getFPS(); __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "FPS %d", currentFPS); if(currentFPS != NO_FPS_CALCULATED){ int newValueFPS = shouldPursueFPSRecalculationToThisFPS(currentFPS); if(newValueFPS == DO_NOT_PURSUE_FPS_VALUE){ processInputs(currentFPS, currentFPS, true, cpu, gpu); } else { processInputs(currentFPS, newValueFPS, false, cpu , gpu); } } } int findLowestFreqPositionThatMeetsThisCost(double costToMeet, vector<long> availableFrequencies, float factor){ for(int position = 0; position < availableFrequencies.size(); position++){ long chosenFreq = availableFrequencies[position]; double calculatedCost = chosenFreq * factor; if(calculatedCost >= costToMeet){ return position; } } return availableFrequencies.size() - 1; } void makeCPUMeetThisFPS(int targetFPS, int currentFPS, CPU * cpu){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "CPU meet this FPS: %d", targetFPS); int currentCPUFreqPosition = cpu->getCpuFreqPosition(); vector<long> cpuFreqs = cpu->getCPUFreqs(); double cpuUtil = cpu->getUtilisationOfHighestCore(); __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "CPU Highest Util %f", cpuUtil); long currentCPUFrequency = cpuFreqs[currentCPUFreqPosition]; double currentCost = (cpuUtil * currentCPUFrequency) * (((double)targetFPS) / currentFPS); float targetCPUUtil; if(cpuUtil > TARGET_CPU_UTILISATION){ targetCPUUtil = cpuUtil; } else { targetCPUUtil = TARGET_CPU_UTILISATION; } int newCPUFreqPosition = findLowestFreqPositionThatMeetsThisCost(currentCost, cpuFreqs, targetCPUUtil); if(currentCPUFreqPosition != newCPUFreqPosition){ cpu->setCPUFreq(newCPUFreqPosition); } __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "New CPU Freq Pos: %d", newCPUFreqPosition); } void makeGPUMeetThisFPS(int targetFPS, int currentFPS, GPU * gpu){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "GPU meet this FPS: %d", targetFPS); int currentGPUFreqPosition = gpu->getGpuFreqPosition(); vector<long> gpuFreqs = gpu->getGPUFreqs(); long currentGPUFrequency = gpuFreqs[currentGPUFreqPosition]; double currentCost = currentGPUFrequency * (((double)targetFPS) / currentFPS); int newGPUFreqPosition = findLowestFreqPositionThatMeetsThisCost(currentCost, gpuFreqs, 1); if(currentGPUFreqPosition != newGPUFreqPosition){ gpu->setGPUFreq(newGPUFreqPosition); } __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "New GPU Freq Pos: %d", newGPUFreqPosition); } void processInputs(int currentFPS, int newFPSValue, bool fpsInRange, CPU * cpu, GPU * gpu){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Current FPS: %d, target FPS: %d", currentFPS, newFPSValue); makeCPUMeetThisFPS(newFPSValue, currentFPS, cpu); if(fpsInRange){ return; } currentSlidingWindowPosition++; if(currentSlidingWindowPosition > slidingWindowLength){ currentSlidingWindowPosition = 0; makeGPUMeetThisFPS(newFPSValue, currentFPS, gpu); } } <commit_msg>change cpu util to float<commit_after>#include <jni.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #include <android/log.h> #include "cpu/CPUOdroid.h" #include "cpu/CPUNexus5.h" #include "gpu/GPUOdroid.h" #include "gpu/GPUNexus5.h" #include "IOStuff.h" #include "RetrieveModel.h" #define CLASSNAME "DVFS-ndk" #define POLL_RATE_IN_MICROSECOND 1000000 //1 second #define DO_NOT_PURSUE_FPS_VALUE -1 #define TARGET_CPU_UTILISATION 80 int fpsLowBound; int fpsHighBound; int slidingWindowLength; bool dvfsInProgress; int currentSlidingWindowPosition; pthread_t threadTask; void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength); void * threadFunction(void *arg); int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1); int shouldPursueFPSRecalculationToThisFPS(int fps); void processInputs(int currentFPS, int newFPSValue, bool fpsInRange, CPU * cpu, GPU * gpu); void runThisRegularly(CPU * cpu, GPU * gpu); int findLowestFreqPositionThatMeetsThisCost(double costToMeet, vector<long> availableFrequencies, float factor); void makeCPUMeetThisFPS(int targetFPS, int currentFPS, CPU * cpu); void makeGPUMeetThisFPS(int targetFPS, int currentFPS, GPU * gpu); extern "C" JNIEXPORT void JNICALL Java_com_example_dvfs_DVFSNdk_startDVFS( JNIEnv* env, jobject thiz, jint fpsLowbound, jint fpsHighBound, jint slidingWindowLength){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "lowbound: %d, highbound: %d, slidingWindow: %d", fpsLowbound, fpsHighBound, slidingWindowLength); startDVFS(fpsLowbound, fpsHighBound, slidingWindowLength); } extern "C" JNIEXPORT void JNICALL Java_com_example_dvfs_DVFSNdk_stopDVFS( JNIEnv* env, jobject thiz ){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Stop DVFS"); dvfsInProgress = false; } void startDVFS(int _fpsLowBound, int _fpsHighBound, int _slidingWindowLength){ fpsLowBound = _fpsLowBound; fpsHighBound = _fpsHighBound; slidingWindowLength = _slidingWindowLength; dvfsInProgress = true; pthread_create(&threadTask, NULL, threadFunction, NULL); } //From http://stackoverflow.com/questions/1468596/calculating-elapsed-time-in-a-c-program-in-milliseconds /* Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1){ long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); result->tv_sec = diff / 1000000; result->tv_usec = diff % 1000000; return (diff<0); } void * threadFunction(void *arg){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Thread function start"); startShell(); __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Shell started"); CPU * cpu; GPU * gpu; __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "After var declaration"); if(isPhoneNexus5()){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Model %s", "Nexus 5"); cpu = new CPUNexus5(); gpu = new GPUNexus5(); } else { __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Model %s", "Not Nexus 5"); cpu = new CPUOdroid(); gpu = new GPUOdroid(); } struct timeval tvBegin, tvEnd, tvDiff; while(dvfsInProgress){ gettimeofday(&tvBegin, NULL); runThisRegularly(cpu, gpu); gettimeofday(&tvEnd, NULL); timeval_subtract(&tvDiff, &tvEnd, &tvBegin); int elapsedTime = tvDiff.tv_usec; //This is to calculate how much time to sleep before the next poll if(elapsedTime < POLL_RATE_IN_MICROSECOND){ int timeToSleep = POLL_RATE_IN_MICROSECOND - elapsedTime; usleep(timeToSleep); } } free(gpu); free(cpu); stopShell(); return NULL; } int shouldPursueFPSRecalculationToThisFPS(int fps){ if(fps > fpsHighBound){ //We need to decrease FPS return fpsLowBound; } else if(fps < fpsLowBound){ //We need to increase FPS return fpsHighBound; } else { currentSlidingWindowPosition = 0; return DO_NOT_PURSUE_FPS_VALUE; } } void runThisRegularly(CPU * cpu, GPU * gpu){ int currentFPS = gpu->getFPS(); __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "FPS %d", currentFPS); if(currentFPS != NO_FPS_CALCULATED){ int newValueFPS = shouldPursueFPSRecalculationToThisFPS(currentFPS); if(newValueFPS == DO_NOT_PURSUE_FPS_VALUE){ processInputs(currentFPS, currentFPS, true, cpu, gpu); } else { processInputs(currentFPS, newValueFPS, false, cpu , gpu); } } } int findLowestFreqPositionThatMeetsThisCost(double costToMeet, vector<long> availableFrequencies, float factor){ for(int position = 0; position < availableFrequencies.size(); position++){ long chosenFreq = availableFrequencies[position]; double calculatedCost = chosenFreq * factor; if(calculatedCost >= costToMeet){ return position; } } return availableFrequencies.size() - 1; } void makeCPUMeetThisFPS(int targetFPS, int currentFPS, CPU * cpu){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "CPU meet this FPS: %d", targetFPS); int currentCPUFreqPosition = cpu->getCpuFreqPosition(); vector<long> cpuFreqs = cpu->getCPUFreqs(); float cpuUtil = cpu->getUtilisationOfHighestCore(); __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "CPU Highest Util %f", cpuUtil); long currentCPUFrequency = cpuFreqs[currentCPUFreqPosition]; double currentCost = (cpuUtil * currentCPUFrequency) * (((double)targetFPS) / currentFPS); float targetCPUUtil; if(cpuUtil > TARGET_CPU_UTILISATION){ targetCPUUtil = cpuUtil; } else { targetCPUUtil = TARGET_CPU_UTILISATION; } int newCPUFreqPosition = findLowestFreqPositionThatMeetsThisCost(currentCost, cpuFreqs, targetCPUUtil); if(currentCPUFreqPosition != newCPUFreqPosition){ cpu->setCPUFreq(newCPUFreqPosition); } __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "New CPU Freq Pos: %d", newCPUFreqPosition); } void makeGPUMeetThisFPS(int targetFPS, int currentFPS, GPU * gpu){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "GPU meet this FPS: %d", targetFPS); int currentGPUFreqPosition = gpu->getGpuFreqPosition(); vector<long> gpuFreqs = gpu->getGPUFreqs(); long currentGPUFrequency = gpuFreqs[currentGPUFreqPosition]; double currentCost = currentGPUFrequency * (((double)targetFPS) / currentFPS); int newGPUFreqPosition = findLowestFreqPositionThatMeetsThisCost(currentCost, gpuFreqs, 1); if(currentGPUFreqPosition != newGPUFreqPosition){ gpu->setGPUFreq(newGPUFreqPosition); } __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "New GPU Freq Pos: %d", newGPUFreqPosition); } void processInputs(int currentFPS, int newFPSValue, bool fpsInRange, CPU * cpu, GPU * gpu){ __android_log_print(ANDROID_LOG_INFO, CLASSNAME, "Current FPS: %d, target FPS: %d", currentFPS, newFPSValue); makeCPUMeetThisFPS(newFPSValue, currentFPS, cpu); if(fpsInRange){ return; } currentSlidingWindowPosition++; if(currentSlidingWindowPosition > slidingWindowLength){ currentSlidingWindowPosition = 0; makeGPUMeetThisFPS(newFPSValue, currentFPS, gpu); } } <|endoftext|>
<commit_before>#include "Crown.h" using namespace Crown; int main(int argc, char** argv) { XMLReader xml; xml.LoadFile("res/window.xml"); xml.Print(); getchar(); return 0; } <commit_msg>Delete xmlreader sample<commit_after><|endoftext|>
<commit_before>#undef PV_USE_OPENCL #include "../src/arch/opencl/CLDevice.hpp" #include "../src/arch/opencl/CLKernel.hpp" #include "../src/arch/opencl/CLBuffer.hpp" #include "../src/arch/opencl/pv_uint4.h" #include "../src/utils/Timer.hpp" #include "../src/utils/cl_random.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #define DEVICE 1 #define NX 256 #define NY 256 #define NXL 16 #define NYL 8 int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count); void c_rand(uint4 * rnd_state, int count); int main(int argc, char * argv[]) { unsigned int nxl, nyl; PV::Timer timer; int argid = 0; int query = 0; int device = DEVICE; int status = CL_SUCCESS; int nWarm = 10, nLoops = 100; if (argc > 1) { device = atoi(argv[1]); } PV::CLKernel * kernel; PV::CLDevice * cld = new PV::CLDevice(device); // query and print information about the devices found // if (query) cld->query_device_info(); if (device == 0) { nxl = NXL; nyl = NYL; } else { nxl = 1; nyl = 1; } kernel = cld->createKernel("kernels/test_cl_random.cl", "cl_rand"); const size_t mem_size = NX*NY*sizeof(uint4); uint4 * rnd_state = cl_random_init(NX*NY); uint4 * rnd_state2 = cl_random_init(NX*NY); assert(rnd_state != NULL); assert(rnd_state2 != NULL); // create device buffer // PV::CLBuffer * d_rnd_state = cld->createBuffer(CL_MEM_COPY_HOST_PTR, mem_size, rnd_state); status |= kernel->setKernelArg(argid++, NX); status |= kernel->setKernelArg(argid++, NY); status |= kernel->setKernelArg(argid++, 1); status |= kernel->setKernelArg(argid++, 0); status |= kernel->setKernelArg(argid++, d_rnd_state); printf("Executing on device..."); kernel->run(NX*NY, nxl*nyl); // Check results for accuracy // printf("\nChecking results..."); d_rnd_state->copyFromDevice(); status = check_results(rnd_state, rnd_state2, NX*NY); if (status != CL_SUCCESS) { exit(status); } printf(" CORRECT\n"); for (int n = 0; n < nWarm; n++) { kernel->run(NX*NY, nxl*nyl); } printf("Timing %d loops on device... ", nLoops); timer.start(); for (int n = 0; n < nLoops; n++) { kernel->run(NX*NY, nxl*nyl); } status |= kernel->finish(); timer.stop(); timer.elapsed_time(); printf("Timing %d loops on host..... ", nLoops); timer.start(); for (int n = 0; n < nLoops; n++) { c_rand(rnd_state2, NX*NY); } timer.stop(); timer.elapsed_time(); // Shutdown and cleanup // // clReleaseMemObject(d_rnd_state); delete cld; printf("Finished...\n"); return status; } int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count) { uint4 state; for (int k = 0; k < count; k++) { state = cl_random_get(rnd_state2[k]); if (state.s0 != rnd_state[k].s0) { printf("check_results: results differ at k==%d, rnd_state==%d, rnd_state2==%d\n", k, state.s0, rnd_state[k].s0); return 1; } float p1 = (float) ((float) state.s0 / (float) 4294967296.0); float p2 = (float) ((double) state.s0 / (double) 4294967296.0); if (p1 != p2) printf("check_results[%d]: %f %f\n", k, p1, p2); } return 0; } void c_rand(uint4 * rnd_state, int count) { for (int k = 0; k < count; k++) { rnd_state[k] = cl_random_get(rnd_state[k]); } } <commit_msg>Added print_results function to print the results so that they can be plotted to see if results looks random.<commit_after>#undef PV_USE_OPENCL #include "../src/arch/opencl/CLDevice.hpp" #include "../src/arch/opencl/CLKernel.hpp" #include "../src/arch/opencl/CLBuffer.hpp" #include "../src/arch/opencl/pv_uint4.h" #include "../src/utils/Timer.hpp" #include "../src/utils/cl_random.h" #include "../src/kernels/cl_random.hcl" #include <assert.h> #include <stdio.h> #include <stdlib.h> #undef DEBUG_OUTPUT #define DEVICE 1 #define NX 256 #define NY 256 #define NXL 16 #define NYL 8 int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count); int print_results(uint4 * rnd_state, uint4 * rnd_state2, int count); void c_rand(uint4 * rnd_state, int count); int main(int argc, char * argv[]) { unsigned int nxl, nyl; PV::Timer timer; int argid = 0; int query = 0; int device = DEVICE; int status = CL_SUCCESS; int nWarm = 10, nLoops = 100; if (argc > 1) { device = atoi(argv[1]); } PV::CLKernel * kernel; PV::CLDevice * cld = new PV::CLDevice(device); // query and print information about the devices found // if (query) cld->query_device_info(); if (device == 0) { nxl = NXL; nyl = NYL; } else { nxl = 1; nyl = 1; } kernel = cld->createKernel("kernels/test_cl_random.cl", "cl_rand"); const size_t mem_size = NX*NY*sizeof(uint4); uint4 * rnd_state = cl_random_init(NX*NY); uint4 * rnd_state2 = cl_random_init(NX*NY); assert(rnd_state != NULL); assert(rnd_state2 != NULL); // create device buffer // PV::CLBuffer * d_rnd_state = cld->createBuffer(CL_MEM_COPY_HOST_PTR, mem_size, rnd_state); status |= kernel->setKernelArg(argid++, NX); status |= kernel->setKernelArg(argid++, NY); status |= kernel->setKernelArg(argid++, 1); status |= kernel->setKernelArg(argid++, 0); status |= kernel->setKernelArg(argid++, d_rnd_state); printf("Executing on device..."); kernel->run(NX*NY, nxl*nyl); printf("\n"); #ifdef DEBUG_OUTPUT status = print_results(rnd_state, rnd_state2, NX*NY); #endif // Check results for accuracy // printf("Checking results..."); d_rnd_state->copyFromDevice(); status = check_results(rnd_state, rnd_state2, NX*NY); if (status != CL_SUCCESS) { exit(status); } printf(" CORRECT\n"); for (int n = 0; n < nWarm; n++) { kernel->run(NX*NY, nxl*nyl); } printf("Timing %d loops on device... ", nLoops); timer.start(); for (int n = 0; n < nLoops; n++) { kernel->run(NX*NY, nxl*nyl); } status |= kernel->finish(); timer.stop(); timer.elapsed_time(); printf("Timing %d loops on host..... ", nLoops); timer.start(); for (int n = 0; n < nLoops; n++) { c_rand(rnd_state2, NX*NY); } timer.stop(); timer.elapsed_time(); // Shutdown and cleanup // // clReleaseMemObject(d_rnd_state); delete cld; printf("Finished...\n"); return status; } int check_results(uint4 * rnd_state, uint4 * rnd_state2, int count) { uint4 state; for (int k = 0; k < count; k++) { state = cl_random_get(rnd_state2[k]); if (state.s0 != rnd_state[k].s0) { printf("check_results: results differ at k==%d, rnd_state==%d, rnd_state2==%d\n", k, state.s0, rnd_state[k].s0); return 1; } float p1 = (float) ((float) state.s0 / (float) 4294967296.0); float p2 = (float) ((double) state.s0 / (double) 4294967296.0); if (p1 != p2) printf("check_results[%d]: %f %f\n", k, p1, p2); } return 0; } int print_results(uint4 * rnd_state, uint4 * rnd_state2, int count) { uint4 state; FILE * fp = fopen("test_cl_random.results", "w"); for (int k = 1; k < count; k+=2) { fprintf(fp, "%f %f %f %f\n", cl_random_prob(rnd_state[ k-1]), cl_random_prob(rnd_state[ k]), cl_random_prob(rnd_state2[k-1]), cl_random_prob(rnd_state2[k]) ); } fclose(fp); return 0; } void c_rand(uint4 * rnd_state, int count) { for (int k = 0; k < count; k++) { rnd_state[k] = cl_random_get(rnd_state[k]); } } <|endoftext|>
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This 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. See file COPYING. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/stat.h> #include <iostream> #include <string> using namespace std; #include "config.h" #include "mon/MonMap.h" #include "mds/MDS.h" #include "msg/SimpleMessenger.h" #include "common/Timer.h" #include "mon/MonClient.h" int main(int argc, const char **argv) { vector<const char*> args; argv_to_vec(argc, argv, args); parse_config_options(args); // mds specific args const char *monhost = 0; int whoami = -1; bool standby = false; // by default, i'll start active. for (unsigned i=0; i<args.size(); i++) { if (strcmp(args[i], "--standby") == 0) standby = true; else if (strcmp(args[i], "--mds") == 0) whoami = atoi(args[++i]); else if (monhost == 0) monhost = args[i]; else { cerr << "unrecognized arg " << args[i] << std::endl; return -1; } } if (g_conf.clock_tare) g_clock.tare(); // get monmap MonMap monmap; MonClient mc; if (mc.get_monmap(&monmap) < 0) return -1; rank.bind(); cout << "starting mds? at " << rank.get_rank_addr() << std::endl; rank.start(); rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::fast_fail()); //rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::retry_forever()); // start mds Messenger *m = rank.register_entity(entity_name_t::MDS(whoami)); assert(m); MDS *mds = new MDS(whoami, m, &monmap); mds->init(standby); rank.wait(); // yuck: grab the mds lock, so we can be sure that whoever in *mds // called shutdown finishes what they were doing. mds->mds_lock.Lock(); mds->mds_lock.Unlock(); // done //delete mds; generic_dout(0) << "stopped." << dendl; return 0; } <commit_msg>mds: retry client messages indefinitely, since mds has its own timeout/markdown mechanism<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net> * * This 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. See file COPYING. * */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/stat.h> #include <iostream> #include <string> using namespace std; #include "config.h" #include "mon/MonMap.h" #include "mds/MDS.h" #include "msg/SimpleMessenger.h" #include "common/Timer.h" #include "mon/MonClient.h" int main(int argc, const char **argv) { vector<const char*> args; argv_to_vec(argc, argv, args); parse_config_options(args); // mds specific args const char *monhost = 0; int whoami = -1; bool standby = false; // by default, i'll start active. for (unsigned i=0; i<args.size(); i++) { if (strcmp(args[i], "--standby") == 0) standby = true; else if (strcmp(args[i], "--mds") == 0) whoami = atoi(args[++i]); else if (monhost == 0) monhost = args[i]; else { cerr << "unrecognized arg " << args[i] << std::endl; return -1; } } if (g_conf.clock_tare) g_clock.tare(); // get monmap MonMap monmap; MonClient mc; if (mc.get_monmap(&monmap) < 0) return -1; rank.bind(); cout << "starting mds? at " << rank.get_rank_addr() << std::endl; rank.start(); rank.set_policy(entity_name_t::TYPE_MON, Rank::Policy::fast_fail()); rank.set_policy(entity_name_t::TYPE_CLIENT, Rank::Policy::retry_forever()); // mds does its own timeout/markdown //rank.set_policy(entity_name_t::TYPE_OSD, Rank::Policy::retry_forever()); // start mds Messenger *m = rank.register_entity(entity_name_t::MDS(whoami)); assert(m); MDS *mds = new MDS(whoami, m, &monmap); mds->init(standby); rank.wait(); // yuck: grab the mds lock, so we can be sure that whoever in *mds // called shutdown finishes what they were doing. mds->mds_lock.Lock(); mds->mds_lock.Unlock(); // done //delete mds; generic_dout(0) << "stopped." << dendl; return 0; } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgShadow/ShadowMap> #include <osgShadow/ShadowedScene> #include <osg/Notify> #include <osg/ComputeBoundsVisitor> #include <osg/PolygonOffset> #include <osg/CullFace> #include <osg/io_utils> using namespace osgShadow; ////////////////////////////////////////////////////////////////// // fragment shader // char fragmentShaderSource_noBaseTexture[] = "uniform sampler2DShadow shadowTexture; \n" "uniform vec2 ambientBias; \n" "\n" "void main(void) \n" "{ \n" " gl_FragColor = gl_Color * (ambientBias.x + shadow2DProj( shadowTexture, gl_TexCoord[0] ) * ambientBias.y); \n" "}\n"; ////////////////////////////////////////////////////////////////// // fragment shader // char fragmentShaderSource_withBaseTexture[] = "uniform sampler2D baseTexture; \n" "uniform sampler2DShadow shadowTexture; \n" "uniform vec2 ambientBias; \n" "\n" "void main(void) \n" "{ \n" " vec4 color = gl_Color * texture2D( baseTexture, gl_TexCoord[0].xy ); \n" " gl_FragColor = color * (ambientBias.x + shadow2DProj( shadowTexture, gl_TexCoord[1] ) * ambientBias.y); \n" "}\n"; ShadowMap::ShadowMap(): _textureUnit(1) { osg::notify(osg::NOTICE)<<"Warning: osgShadow::ShadowMap technique is in development."<<std::endl; } ShadowMap::ShadowMap(const ShadowMap& copy, const osg::CopyOp& copyop): ShadowTechnique(copy,copyop), _textureUnit(copy._textureUnit) { } void ShadowMap::setTextureUnit(unsigned int unit) { _textureUnit = unit; } void ShadowMap::init() { if (!_shadowedScene) return; unsigned int tex_width = 1024; unsigned int tex_height = 1024; _texture = new osg::Texture2D; _texture->setTextureSize(tex_width, tex_height); _texture->setInternalFormat(GL_DEPTH_COMPONENT); _texture->setShadowComparison(true); _texture->setShadowTextureMode(osg::Texture2D::LUMINANCE); _texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); _texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR); // set up the render to texture camera. { // create the camera _camera = new osg::Camera; _camera->setCullCallback(new CameraCullCallback(this)); _camera->setClearMask(GL_DEPTH_BUFFER_BIT); //_camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); _camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); _camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); // set viewport _camera->setViewport(0,0,tex_width,tex_height); // set the camera to render before the main camera. _camera->setRenderOrder(osg::Camera::PRE_RENDER); // tell the camera to use OpenGL frame buffer object where supported. _camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); //_camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW); // attach the texture and use it as the color buffer. _camera->attach(osg::Camera::DEPTH_BUFFER, _texture.get()); osg::StateSet* stateset = _camera->getOrCreateStateSet(); float factor = 0.0f; float units = 1.0f; osg::ref_ptr<osg::PolygonOffset> polygon_offset = new osg::PolygonOffset; polygon_offset->setFactor(factor); polygon_offset->setUnits(units); stateset->setAttribute(polygon_offset.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setMode(GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); osg::ref_ptr<osg::CullFace> cull_face = new osg::CullFace; cull_face->setMode(osg::CullFace::FRONT); stateset->setAttribute(cull_face.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setMode(GL_CULL_FACE, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } { _stateset = new osg::StateSet; _stateset->setTextureAttributeAndModes(_textureUnit,_texture.get(),osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON); _texgen = new osg::TexGen; #if 1 osg::Program* program = new osg::Program; _stateset->setAttribute(program); if (_textureUnit==0) { osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_noBaseTexture); program->addShader(fragment_shader); osg::Uniform* shadowTextureSampler = new osg::Uniform("shadowTexture",(int)_textureUnit); _stateset->addUniform(shadowTextureSampler); } else { osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_withBaseTexture); program->addShader(fragment_shader); osg::Uniform* baseTextureSampler = new osg::Uniform("baseTexture",0); _stateset->addUniform(baseTextureSampler); osg::Uniform* shadowTextureSampler = new osg::Uniform("shadowTexture",(int)_textureUnit); _stateset->addUniform(shadowTextureSampler); } osg::Uniform* ambientBias = new osg::Uniform("ambientBias",osg::Vec2(0.3f,1.2f)); _stateset->addUniform(ambientBias); #endif } _dirty = false; } void ShadowMap::update(osg::NodeVisitor& nv) { _shadowedScene->osg::Group::traverse(nv); } void ShadowMap::cull(osgUtil::CullVisitor& cv) { // record the traversal mask on entry so we can reapply it later. unsigned int traversalMask = cv.getTraversalMask(); osgUtil::RenderStage* orig_rs = cv.getRenderStage(); // do traversal of shadow recieving scene which does need to be decorated by the shadow map { cv.pushStateSet(_stateset.get()); _shadowedScene->osg::Group::traverse(cv); cv.popStateSet(); } // need to compute view frustum for RTT camera. // 1) get the light position // 2) get the center and extents of the view frustum const osg::Light* selectLight = 0; osg::Vec4 lightpos; osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList(); for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin(); itr != aml.end(); ++itr) { const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get()); if (light) { osg::RefMatrix* matrix = itr->second.get(); if (matrix) lightpos = light->getPosition() * (*matrix); else lightpos = light->getPosition(); selectLight = light; } } osg::Matrix eyeToWorld; eyeToWorld.invert(*cv.getModelViewMatrix()); lightpos = lightpos * eyeToWorld; if (selectLight) { // get the bounds of the model. osg::ComputeBoundsVisitor cbbv(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN); cbbv.setTraversalMask(getShadowedScene()->getCastsShadowTraversalMask()); _shadowedScene->osg::Group::traverse(cbbv); osg::BoundingBox bb = cbbv.getBoundingBox(); if (lightpos[3]!=0.0) { osg::Vec3 position(lightpos.x(), lightpos.y(), lightpos.z()); float centerDistance = (position-bb.center()).length(); float znear = centerDistance-bb.radius(); float zfar = centerDistance+bb.radius(); float zNearRatio = 0.001f; if (znear<zfar*zNearRatio) znear = zfar*zNearRatio; float top = (bb.radius()/centerDistance)*znear; float right = top; _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); _camera->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar); _camera->setViewMatrixAsLookAt(position,bb.center(),osg::Vec3(0.0f,1.0f,0.0f)); // compute the matrix which takes a vertex from local coords into tex coords // will use this later to specify osg::TexGen.. osg::Matrix MVPT = _camera->getViewMatrix() * _camera->getProjectionMatrix() * osg::Matrix::translate(1.0,1.0,1.0) * osg::Matrix::scale(0.5f,0.5f,0.5f); _texgen->setMode(osg::TexGen::EYE_LINEAR); _texgen->setPlanesFromMatrix(MVPT); } else { // make an orthographic projection osg::Vec3 lightDir(lightpos.x(), lightpos.y(), lightpos.z()); lightDir.normalize(); // set the position far away along the light direction osg::Vec3 position = lightDir * bb.radius() * 20; float centerDistance = (position-bb.center()).length(); float znear = centerDistance-bb.radius(); float zfar = centerDistance+bb.radius(); float zNearRatio = 0.001f; if (znear<zfar*zNearRatio) znear = zfar*zNearRatio; float top = bb.radius(); float right = top; _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); _camera->setProjectionMatrixAsOrtho(-right, right, -top, top, znear, zfar); _camera->setViewMatrixAsLookAt(position,bb.center(),osg::Vec3(0.0f,1.0f,0.0f)); // compute the matrix which takes a vertex from local coords into tex coords // will use this later to specify osg::TexGen.. osg::Matrix MVPT = _camera->getViewMatrix() * _camera->getProjectionMatrix() * osg::Matrix::translate(1.0,1.0,1.0) * osg::Matrix::scale(0.5f,0.5f,0.5f); _texgen->setMode(osg::TexGen::EYE_LINEAR); _texgen->setPlanesFromMatrix(MVPT); } cv.setTraversalMask( traversalMask & getShadowedScene()->getCastsShadowTraversalMask() ); // do RTT camera traversal _camera->accept(cv); orig_rs->getPositionalStateContainer()->addPositionedTextureAttribute(_textureUnit, cv.getModelViewMatrix(), _texgen.get()); } // reapply the original traversal mask cv.setTraversalMask( traversalMask ); } void ShadowMap::cleanSceneGraph() { } <commit_msg>Made the local shaders definitions static const char to avoid multiple definiations<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgShadow/ShadowMap> #include <osgShadow/ShadowedScene> #include <osg/Notify> #include <osg/ComputeBoundsVisitor> #include <osg/PolygonOffset> #include <osg/CullFace> #include <osg/io_utils> using namespace osgShadow; ////////////////////////////////////////////////////////////////// // fragment shader // static const char fragmentShaderSource_noBaseTexture[] = "uniform sampler2DShadow shadowTexture; \n" "uniform vec2 ambientBias; \n" "\n" "void main(void) \n" "{ \n" " gl_FragColor = gl_Color * (ambientBias.x + shadow2DProj( shadowTexture, gl_TexCoord[0] ) * ambientBias.y); \n" "}\n"; ////////////////////////////////////////////////////////////////// // fragment shader // static const char fragmentShaderSource_withBaseTexture[] = "uniform sampler2D baseTexture; \n" "uniform sampler2DShadow shadowTexture; \n" "uniform vec2 ambientBias; \n" "\n" "void main(void) \n" "{ \n" " vec4 color = gl_Color * texture2D( baseTexture, gl_TexCoord[0].xy ); \n" " gl_FragColor = color * (ambientBias.x + shadow2DProj( shadowTexture, gl_TexCoord[1] ) * ambientBias.y); \n" "}\n"; ShadowMap::ShadowMap(): _textureUnit(1) { osg::notify(osg::NOTICE)<<"Warning: osgShadow::ShadowMap technique is in development."<<std::endl; } ShadowMap::ShadowMap(const ShadowMap& copy, const osg::CopyOp& copyop): ShadowTechnique(copy,copyop), _textureUnit(copy._textureUnit) { } void ShadowMap::setTextureUnit(unsigned int unit) { _textureUnit = unit; } void ShadowMap::init() { if (!_shadowedScene) return; unsigned int tex_width = 1024; unsigned int tex_height = 1024; _texture = new osg::Texture2D; _texture->setTextureSize(tex_width, tex_height); _texture->setInternalFormat(GL_DEPTH_COMPONENT); _texture->setShadowComparison(true); _texture->setShadowTextureMode(osg::Texture2D::LUMINANCE); _texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR); _texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR); // set up the render to texture camera. { // create the camera _camera = new osg::Camera; _camera->setCullCallback(new CameraCullCallback(this)); _camera->setClearMask(GL_DEPTH_BUFFER_BIT); //_camera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); _camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f)); _camera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR); // set viewport _camera->setViewport(0,0,tex_width,tex_height); // set the camera to render before the main camera. _camera->setRenderOrder(osg::Camera::PRE_RENDER); // tell the camera to use OpenGL frame buffer object where supported. _camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); //_camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW); // attach the texture and use it as the color buffer. _camera->attach(osg::Camera::DEPTH_BUFFER, _texture.get()); osg::StateSet* stateset = _camera->getOrCreateStateSet(); float factor = 0.0f; float units = 1.0f; osg::ref_ptr<osg::PolygonOffset> polygon_offset = new osg::PolygonOffset; polygon_offset->setFactor(factor); polygon_offset->setUnits(units); stateset->setAttribute(polygon_offset.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setMode(GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); osg::ref_ptr<osg::CullFace> cull_face = new osg::CullFace; cull_face->setMode(osg::CullFace::FRONT); stateset->setAttribute(cull_face.get(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->setMode(GL_CULL_FACE, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); } { _stateset = new osg::StateSet; _stateset->setTextureAttributeAndModes(_textureUnit,_texture.get(),osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON); _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON); _texgen = new osg::TexGen; #if 1 osg::Program* program = new osg::Program; _stateset->setAttribute(program); if (_textureUnit==0) { osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_noBaseTexture); program->addShader(fragment_shader); osg::Uniform* shadowTextureSampler = new osg::Uniform("shadowTexture",(int)_textureUnit); _stateset->addUniform(shadowTextureSampler); } else { osg::Shader* fragment_shader = new osg::Shader(osg::Shader::FRAGMENT, fragmentShaderSource_withBaseTexture); program->addShader(fragment_shader); osg::Uniform* baseTextureSampler = new osg::Uniform("baseTexture",0); _stateset->addUniform(baseTextureSampler); osg::Uniform* shadowTextureSampler = new osg::Uniform("shadowTexture",(int)_textureUnit); _stateset->addUniform(shadowTextureSampler); } osg::Uniform* ambientBias = new osg::Uniform("ambientBias",osg::Vec2(0.3f,1.2f)); _stateset->addUniform(ambientBias); #endif } _dirty = false; } void ShadowMap::update(osg::NodeVisitor& nv) { _shadowedScene->osg::Group::traverse(nv); } void ShadowMap::cull(osgUtil::CullVisitor& cv) { // record the traversal mask on entry so we can reapply it later. unsigned int traversalMask = cv.getTraversalMask(); osgUtil::RenderStage* orig_rs = cv.getRenderStage(); // do traversal of shadow recieving scene which does need to be decorated by the shadow map { cv.pushStateSet(_stateset.get()); _shadowedScene->osg::Group::traverse(cv); cv.popStateSet(); } // need to compute view frustum for RTT camera. // 1) get the light position // 2) get the center and extents of the view frustum const osg::Light* selectLight = 0; osg::Vec4 lightpos; osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList(); for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin(); itr != aml.end(); ++itr) { const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get()); if (light) { osg::RefMatrix* matrix = itr->second.get(); if (matrix) lightpos = light->getPosition() * (*matrix); else lightpos = light->getPosition(); selectLight = light; } } osg::Matrix eyeToWorld; eyeToWorld.invert(*cv.getModelViewMatrix()); lightpos = lightpos * eyeToWorld; if (selectLight) { // get the bounds of the model. osg::ComputeBoundsVisitor cbbv(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN); cbbv.setTraversalMask(getShadowedScene()->getCastsShadowTraversalMask()); _shadowedScene->osg::Group::traverse(cbbv); osg::BoundingBox bb = cbbv.getBoundingBox(); if (lightpos[3]!=0.0) { osg::Vec3 position(lightpos.x(), lightpos.y(), lightpos.z()); float centerDistance = (position-bb.center()).length(); float znear = centerDistance-bb.radius(); float zfar = centerDistance+bb.radius(); float zNearRatio = 0.001f; if (znear<zfar*zNearRatio) znear = zfar*zNearRatio; float top = (bb.radius()/centerDistance)*znear; float right = top; _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); _camera->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar); _camera->setViewMatrixAsLookAt(position,bb.center(),osg::Vec3(0.0f,1.0f,0.0f)); // compute the matrix which takes a vertex from local coords into tex coords // will use this later to specify osg::TexGen.. osg::Matrix MVPT = _camera->getViewMatrix() * _camera->getProjectionMatrix() * osg::Matrix::translate(1.0,1.0,1.0) * osg::Matrix::scale(0.5f,0.5f,0.5f); _texgen->setMode(osg::TexGen::EYE_LINEAR); _texgen->setPlanesFromMatrix(MVPT); } else { // make an orthographic projection osg::Vec3 lightDir(lightpos.x(), lightpos.y(), lightpos.z()); lightDir.normalize(); // set the position far away along the light direction osg::Vec3 position = lightDir * bb.radius() * 20; float centerDistance = (position-bb.center()).length(); float znear = centerDistance-bb.radius(); float zfar = centerDistance+bb.radius(); float zNearRatio = 0.001f; if (znear<zfar*zNearRatio) znear = zfar*zNearRatio; float top = bb.radius(); float right = top; _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); _camera->setProjectionMatrixAsOrtho(-right, right, -top, top, znear, zfar); _camera->setViewMatrixAsLookAt(position,bb.center(),osg::Vec3(0.0f,1.0f,0.0f)); // compute the matrix which takes a vertex from local coords into tex coords // will use this later to specify osg::TexGen.. osg::Matrix MVPT = _camera->getViewMatrix() * _camera->getProjectionMatrix() * osg::Matrix::translate(1.0,1.0,1.0) * osg::Matrix::scale(0.5f,0.5f,0.5f); _texgen->setMode(osg::TexGen::EYE_LINEAR); _texgen->setPlanesFromMatrix(MVPT); } cv.setTraversalMask( traversalMask & getShadowedScene()->getCastsShadowTraversalMask() ); // do RTT camera traversal _camera->accept(cv); orig_rs->getPositionalStateContainer()->addPositionedTextureAttribute(_textureUnit, cv.getModelViewMatrix(), _texgen.get()); } // reapply the original traversal mask cv.setTraversalMask( traversalMask ); } void ShadowMap::cleanSceneGraph() { } <|endoftext|>
<commit_before>// sound.cxx -- Sound class implementation // // Started by Erik Hofman, February 2002 // (Reuses some code from fg_fx.cxx created by David Megginson) // // Copyright (C) 2002 Curtis L. Olson - curt@flightgear.org // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ #include <simgear/compiler.h> #ifdef SG_HAVE_STD_INCLUDES # include <cmath> #else # include <math.h> #endif #include <string.h> #include <simgear/debug/logstream.hxx> #include <simgear/props/condition.hxx> #include <simgear/math/fastmath.hxx> #include "xmlsound.hxx" // static double _snd_lin(double v) { return v; } static double _snd_inv(double v) { return (v == 0) ? 1e99 : 1/v; } static double _snd_abs(double v) { return (v >= 0) ? v : -v; } static double _snd_sqrt(double v) { return (v < 0) ? sqrt(-v) : sqrt(v); } static double _snd_log10(double v) { return (v < 1) ? 0 : fast_log10(v); } static double _snd_log(double v) { return (v < 1) ? 0 : fast_log(v); } // static double _snd_sqr(double v) { return v*v; } // static double _snd_pow3(double v) { return v*v*v; } static const struct { char *name; double (*fn)(double); } __sound_fn[] = { // {"lin", _snd_lin}, {"inv", _snd_inv}, {"abs", _snd_abs}, {"sqrt", _snd_sqrt}, {"log", _snd_log10}, {"ln", _snd_log}, // {"sqr", _snd_sqr}, // {"pow3", _snd_pow3}, {"", NULL} }; SGXmlSound::SGXmlSound() : _sample(NULL), _condition(NULL), _property(NULL), _active(false), _name(""), _mode(SGXmlSound::ONCE), _prev_value(0), _dt_play(0.0), _dt_stop(0.0), _stopping(0.0) { } SGXmlSound::~SGXmlSound() { _sample->stop(); if (_property) delete _property; if (_condition) delete _condition; _volume.clear(); _pitch.clear(); delete _sample; } void SGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr, const string &path) { // // set global sound properties // _name = node->getStringValue("name", ""); SG_LOG(SG_GENERAL, SG_INFO, "Loading sound information for: " << _name ); const char *mode_str = node->getStringValue("mode", ""); if ( !strcmp(mode_str, "looped") ) { _mode = SGXmlSound::LOOPED; } else if ( !strcmp(mode_str, "in-transit") ) { _mode = SGXmlSound::IN_TRANSIT; } else { _mode = SGXmlSound::ONCE; if ( strcmp(mode_str, "") ) SG_LOG(SG_GENERAL,SG_INFO, " Unknown sound mode, default to 'once'"); } _property = root->getNode(node->getStringValue("property", ""), true); SGPropertyNode *condition = node->getChild("condition"); if (condition != NULL) _condition = sgReadCondition(root, condition); if (!_property && !_condition) SG_LOG(SG_GENERAL, SG_WARN, " Neither a condition nor a property specified"); // // set volume properties // unsigned int i; float v = 0.0; vector<SGPropertyNode_ptr> kids = node->getChildren("volume"); for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) { _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false}; if (strcmp(kids[i]->getStringValue("property"), "")) volume.prop = root->getNode(kids[i]->getStringValue("property", ""), true); const char *intern_str = kids[i]->getStringValue("internal", ""); if (!strcmp(intern_str, "dt_play")) volume.intern = &_dt_play; else if (!strcmp(intern_str, "dt_stop")) volume.intern = &_dt_stop; if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0) if (volume.factor < 0.0) { volume.factor = -volume.factor; volume.subtract = true; } const char *type_str = kids[i]->getStringValue("type", ""); if ( strcmp(type_str, "") ) { for (int j=0; __sound_fn[j].fn; j++) if ( !strcmp(type_str, __sound_fn[j].name) ) { volume.fn = __sound_fn[j].fn; break; } if (!volume.fn) SG_LOG(SG_GENERAL,SG_INFO, " Unknown volume type, default to 'lin'"); } volume.offset = kids[i]->getDoubleValue("offset", 0.0); if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0) SG_LOG( SG_GENERAL, SG_WARN, "Volume minimum value below 0. Forced to 0."); volume.max = kids[i]->getDoubleValue("max", 0.0); if (volume.max && (volume.max < volume.min) ) SG_LOG(SG_GENERAL,SG_ALERT, " Volume maximum below minimum. Neglected."); _volume.push_back(volume); v += volume.offset; } float reference_dist = node->getDoubleValue("reference-dist", 500.0); float max_dist = node->getDoubleValue("max-dist", 3000.0); // // set pitch properties // float p = 0.0; kids = node->getChildren("pitch"); for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) { _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false}; if (strcmp(kids[i]->getStringValue("property", ""), "")) pitch.prop = root->getNode(kids[i]->getStringValue("property", ""), true); const char *intern_str = kids[i]->getStringValue("internal", ""); if (!strcmp(intern_str, "dt_play")) pitch.intern = &_dt_play; else if (!strcmp(intern_str, "dt_stop")) pitch.intern = &_dt_stop; if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0) if (pitch.factor < 0.0) { pitch.factor = -pitch.factor; pitch.subtract = true; } const char *type_str = kids[i]->getStringValue("type", ""); if ( strcmp(type_str, "") ) { for (int j=0; __sound_fn[j].fn; j++) if ( !strcmp(type_str, __sound_fn[j].name) ) { pitch.fn = __sound_fn[j].fn; break; } if (!pitch.fn) SG_LOG(SG_GENERAL,SG_INFO, " Unknown pitch type, default to 'lin'"); } pitch.offset = kids[i]->getDoubleValue("offset", 1.0); if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0) SG_LOG(SG_GENERAL,SG_WARN, " Pitch minimum value below 0. Forced to 0."); pitch.max = kids[i]->getDoubleValue("max", 0.0); if (pitch.max && (pitch.max < pitch.min) ) SG_LOG(SG_GENERAL,SG_ALERT, " Pitch maximum below minimum. Neglected"); _pitch.push_back(pitch); p += pitch.offset; } // // Relative position // sgVec3 offset_pos; sgSetVec3( offset_pos, 0.0, 0.0, 0.0 ); SGPropertyNode_ptr pos = node->getChild("position"); if ( pos != NULL ) { offset_pos[0] = pos->getDoubleValue("x", 0.0); offset_pos[1] = pos->getDoubleValue("y", 0.0); offset_pos[2] = pos->getDoubleValue("z", 0.0); } // // Initialize the sample // _mgr = sndmgr; if ( (_sample = _mgr->find(_name)) == NULL ) { _sample = new SGSoundSample( path.c_str(), node->getStringValue("path", ""), true ); _mgr->add( _sample, _name ); } _sample->set_offset_pos( offset_pos ); _sample->set_volume(v); _sample->set_reference_dist( reference_dist ); _sample->set_max_dist( max_dist ); _sample->set_pitch(p); } void SGXmlSound::update (double dt) { double curr_value = 0.0; // // If the state changes to false, stop playing. // if (_property) curr_value = _property->getDoubleValue(); if ( // Lisp, anyone? (_condition && !_condition->test()) || (!_condition && _property && ( !curr_value || ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) ) ) ) ) { if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) { if (_sample->is_playing()) { SG_LOG(SG_GENERAL, SG_INFO, "Stopping audio after " << _dt_play << " sec: " << _name ); _sample->stop(); } _active = false; _dt_stop += dt; _dt_play = 0.0; } else { _stopping += dt; } return; } // // If the mode is ONCE and the sound is still playing, // we have nothing to do anymore. // if (_active && (_mode == SGXmlSound::ONCE)) { if (!_sample->is_playing()) { _dt_stop += dt; _dt_play = 0.0; } else { _dt_play += dt; } return; } // // Update the playing time, cache the current value and // clear the delay timer. // _dt_play += dt; _prev_value = curr_value; _stopping = 0.0; // // Update the volume // int i; int max = _volume.size(); double volume = 1.0; double volume_offset = 0.0; for(i = 0; i < max; i++) { double v = 1.0; if (_volume[i].prop) v = _volume[i].prop->getDoubleValue(); else if (_volume[i].intern) v = *_volume[i].intern; if (_volume[i].fn) v = _volume[i].fn(v); v *= _volume[i].factor; if (_volume[i].max && (v > _volume[i].max)) v = _volume[i].max; else if (v < _volume[i].min) v = _volume[i].min; if (_volume[i].subtract) // Hack! volume = _volume[i].offset - v; else { volume_offset += _volume[i].offset; volume *= v; } } // // Update the pitch // max = _pitch.size(); double pitch = 1.0; double pitch_offset = 0.0; for(i = 0; i < max; i++) { double p = 1.0; if (_pitch[i].prop) p = _pitch[i].prop->getDoubleValue(); else if (_pitch[i].intern) p = *_pitch[i].intern; if (_pitch[i].fn) p = _pitch[i].fn(p); p *= _pitch[i].factor; if (_pitch[i].max && (p > _pitch[i].max)) p = _pitch[i].max; else if (p < _pitch[i].min) p = _pitch[i].min; if (_pitch[i].subtract) // Hack! pitch = _pitch[i].offset - p; else { pitch_offset += _pitch[i].offset; pitch *= p; } } // // Change sample state // _sample->set_pitch( pitch_offset + pitch ); _sample->set_volume( volume_offset + volume ); if ((volume_offset + volume ) > 1.0) { _sample->set_volume( 1.0 ); SG_LOG(SG_GENERAL, SG_WARN, "WARNING: Volume larger than 1.0 for configuration for '" << _name << "' clipping ..."); } // // Do we need to start playing the sample? // if (!_active) { if (_mode == SGXmlSound::ONCE) _sample->play(false); else _sample->play(true); SG_LOG(SG_GENERAL, SG_INFO, "Playing audio after " << _dt_stop << " sec: " << _name); SG_LOG(SG_GENERAL, SG_BULK, "Playing " << ((_mode == ONCE) ? "once" : "looped")); _active = true; _dt_stop = 0.0; } } <commit_msg>Weak excuse, but it's getting late. Do clipping right this time.<commit_after>// sound.cxx -- Sound class implementation // // Started by Erik Hofman, February 2002 // (Reuses some code from fg_fx.cxx created by David Megginson) // // Copyright (C) 2002 Curtis L. Olson - curt@flightgear.org // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ #include <simgear/compiler.h> #ifdef SG_HAVE_STD_INCLUDES # include <cmath> #else # include <math.h> #endif #include <string.h> #include <simgear/debug/logstream.hxx> #include <simgear/props/condition.hxx> #include <simgear/math/fastmath.hxx> #include "xmlsound.hxx" // static double _snd_lin(double v) { return v; } static double _snd_inv(double v) { return (v == 0) ? 1e99 : 1/v; } static double _snd_abs(double v) { return (v >= 0) ? v : -v; } static double _snd_sqrt(double v) { return (v < 0) ? sqrt(-v) : sqrt(v); } static double _snd_log10(double v) { return (v < 1) ? 0 : fast_log10(v); } static double _snd_log(double v) { return (v < 1) ? 0 : fast_log(v); } // static double _snd_sqr(double v) { return v*v; } // static double _snd_pow3(double v) { return v*v*v; } static const struct { char *name; double (*fn)(double); } __sound_fn[] = { // {"lin", _snd_lin}, {"inv", _snd_inv}, {"abs", _snd_abs}, {"sqrt", _snd_sqrt}, {"log", _snd_log10}, {"ln", _snd_log}, // {"sqr", _snd_sqr}, // {"pow3", _snd_pow3}, {"", NULL} }; SGXmlSound::SGXmlSound() : _sample(NULL), _condition(NULL), _property(NULL), _active(false), _name(""), _mode(SGXmlSound::ONCE), _prev_value(0), _dt_play(0.0), _dt_stop(0.0), _stopping(0.0) { } SGXmlSound::~SGXmlSound() { _sample->stop(); if (_property) delete _property; if (_condition) delete _condition; _volume.clear(); _pitch.clear(); delete _sample; } void SGXmlSound::init(SGPropertyNode *root, SGPropertyNode *node, SGSoundMgr *sndmgr, const string &path) { // // set global sound properties // _name = node->getStringValue("name", ""); SG_LOG(SG_GENERAL, SG_INFO, "Loading sound information for: " << _name ); const char *mode_str = node->getStringValue("mode", ""); if ( !strcmp(mode_str, "looped") ) { _mode = SGXmlSound::LOOPED; } else if ( !strcmp(mode_str, "in-transit") ) { _mode = SGXmlSound::IN_TRANSIT; } else { _mode = SGXmlSound::ONCE; if ( strcmp(mode_str, "") ) SG_LOG(SG_GENERAL,SG_INFO, " Unknown sound mode, default to 'once'"); } _property = root->getNode(node->getStringValue("property", ""), true); SGPropertyNode *condition = node->getChild("condition"); if (condition != NULL) _condition = sgReadCondition(root, condition); if (!_property && !_condition) SG_LOG(SG_GENERAL, SG_WARN, " Neither a condition nor a property specified"); // // set volume properties // unsigned int i; float v = 0.0; vector<SGPropertyNode_ptr> kids = node->getChildren("volume"); for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) { _snd_prop volume = {NULL, NULL, NULL, 1.0, 0.0, 0.0, 0.0, false}; if (strcmp(kids[i]->getStringValue("property"), "")) volume.prop = root->getNode(kids[i]->getStringValue("property", ""), true); const char *intern_str = kids[i]->getStringValue("internal", ""); if (!strcmp(intern_str, "dt_play")) volume.intern = &_dt_play; else if (!strcmp(intern_str, "dt_stop")) volume.intern = &_dt_stop; if ((volume.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0) if (volume.factor < 0.0) { volume.factor = -volume.factor; volume.subtract = true; } const char *type_str = kids[i]->getStringValue("type", ""); if ( strcmp(type_str, "") ) { for (int j=0; __sound_fn[j].fn; j++) if ( !strcmp(type_str, __sound_fn[j].name) ) { volume.fn = __sound_fn[j].fn; break; } if (!volume.fn) SG_LOG(SG_GENERAL,SG_INFO, " Unknown volume type, default to 'lin'"); } volume.offset = kids[i]->getDoubleValue("offset", 0.0); if ((volume.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0) SG_LOG( SG_GENERAL, SG_WARN, "Volume minimum value below 0. Forced to 0."); volume.max = kids[i]->getDoubleValue("max", 0.0); if (volume.max && (volume.max < volume.min) ) SG_LOG(SG_GENERAL,SG_ALERT, " Volume maximum below minimum. Neglected."); _volume.push_back(volume); v += volume.offset; } float reference_dist = node->getDoubleValue("reference-dist", 500.0); float max_dist = node->getDoubleValue("max-dist", 3000.0); // // set pitch properties // float p = 0.0; kids = node->getChildren("pitch"); for (i = 0; (i < kids.size()) && (i < SGXmlSound::MAXPROP); i++) { _snd_prop pitch = {NULL, NULL, NULL, 1.0, 1.0, 0.0, 0.0, false}; if (strcmp(kids[i]->getStringValue("property", ""), "")) pitch.prop = root->getNode(kids[i]->getStringValue("property", ""), true); const char *intern_str = kids[i]->getStringValue("internal", ""); if (!strcmp(intern_str, "dt_play")) pitch.intern = &_dt_play; else if (!strcmp(intern_str, "dt_stop")) pitch.intern = &_dt_stop; if ((pitch.factor = kids[i]->getDoubleValue("factor", 1.0)) != 0.0) if (pitch.factor < 0.0) { pitch.factor = -pitch.factor; pitch.subtract = true; } const char *type_str = kids[i]->getStringValue("type", ""); if ( strcmp(type_str, "") ) { for (int j=0; __sound_fn[j].fn; j++) if ( !strcmp(type_str, __sound_fn[j].name) ) { pitch.fn = __sound_fn[j].fn; break; } if (!pitch.fn) SG_LOG(SG_GENERAL,SG_INFO, " Unknown pitch type, default to 'lin'"); } pitch.offset = kids[i]->getDoubleValue("offset", 1.0); if ((pitch.min = kids[i]->getDoubleValue("min", 0.0)) < 0.0) SG_LOG(SG_GENERAL,SG_WARN, " Pitch minimum value below 0. Forced to 0."); pitch.max = kids[i]->getDoubleValue("max", 0.0); if (pitch.max && (pitch.max < pitch.min) ) SG_LOG(SG_GENERAL,SG_ALERT, " Pitch maximum below minimum. Neglected"); _pitch.push_back(pitch); p += pitch.offset; } // // Relative position // sgVec3 offset_pos; sgSetVec3( offset_pos, 0.0, 0.0, 0.0 ); SGPropertyNode_ptr pos = node->getChild("position"); if ( pos != NULL ) { offset_pos[0] = pos->getDoubleValue("x", 0.0); offset_pos[1] = pos->getDoubleValue("y", 0.0); offset_pos[2] = pos->getDoubleValue("z", 0.0); } // // Initialize the sample // _mgr = sndmgr; if ( (_sample = _mgr->find(_name)) == NULL ) { _sample = new SGSoundSample( path.c_str(), node->getStringValue("path", ""), true ); _mgr->add( _sample, _name ); } _sample->set_offset_pos( offset_pos ); _sample->set_volume(v); _sample->set_reference_dist( reference_dist ); _sample->set_max_dist( max_dist ); _sample->set_pitch(p); } void SGXmlSound::update (double dt) { double curr_value = 0.0; // // If the state changes to false, stop playing. // if (_property) curr_value = _property->getDoubleValue(); if ( // Lisp, anyone? (_condition && !_condition->test()) || (!_condition && _property && ( !curr_value || ( (_mode == SGXmlSound::IN_TRANSIT) && (curr_value == _prev_value) ) ) ) ) { if ((_mode != SGXmlSound::IN_TRANSIT) || (_stopping > MAX_TRANSIT_TIME)) { if (_sample->is_playing()) { SG_LOG(SG_GENERAL, SG_INFO, "Stopping audio after " << _dt_play << " sec: " << _name ); _sample->stop(); } _active = false; _dt_stop += dt; _dt_play = 0.0; } else { _stopping += dt; } return; } // // If the mode is ONCE and the sound is still playing, // we have nothing to do anymore. // if (_active && (_mode == SGXmlSound::ONCE)) { if (!_sample->is_playing()) { _dt_stop += dt; _dt_play = 0.0; } else { _dt_play += dt; } return; } // // Update the playing time, cache the current value and // clear the delay timer. // _dt_play += dt; _prev_value = curr_value; _stopping = 0.0; // // Update the volume // int i; int max = _volume.size(); double volume = 1.0; double volume_offset = 0.0; for(i = 0; i < max; i++) { double v = 1.0; if (_volume[i].prop) v = _volume[i].prop->getDoubleValue(); else if (_volume[i].intern) v = *_volume[i].intern; if (_volume[i].fn) v = _volume[i].fn(v); v *= _volume[i].factor; if (_volume[i].max && (v > _volume[i].max)) v = _volume[i].max; else if (v < _volume[i].min) v = _volume[i].min; if (_volume[i].subtract) // Hack! volume = _volume[i].offset - v; else { volume_offset += _volume[i].offset; volume *= v; } } // // Update the pitch // max = _pitch.size(); double pitch = 1.0; double pitch_offset = 0.0; for(i = 0; i < max; i++) { double p = 1.0; if (_pitch[i].prop) p = _pitch[i].prop->getDoubleValue(); else if (_pitch[i].intern) p = *_pitch[i].intern; if (_pitch[i].fn) p = _pitch[i].fn(p); p *= _pitch[i].factor; if (_pitch[i].max && (p > _pitch[i].max)) p = _pitch[i].max; else if (p < _pitch[i].min) p = _pitch[i].min; if (_pitch[i].subtract) // Hack! pitch = _pitch[i].offset - p; else { pitch_offset += _pitch[i].offset; pitch *= p; } } // // Change sample state // _sample->set_pitch( pitch_offset + pitch ); if ((volume_offset + volume ) > 1.0) { _sample->set_volume( 1.0 ); SG_LOG(SG_GENERAL, SG_WARN, "Volume larger than 1.0 in configuration for '" << _name << "', clipping."); } else _sample->set_volume( volume_offset + volume ); // // Do we need to start playing the sample? // if (!_active) { if (_mode == SGXmlSound::ONCE) _sample->play(false); else _sample->play(true); SG_LOG(SG_GENERAL, SG_INFO, "Playing audio after " << _dt_stop << " sec: " << _name); SG_LOG(SG_GENERAL, SG_BULK, "Playing " << ((_mode == ONCE) ? "once" : "looped")); _active = true; _dt_stop = 0.0; } } <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> #include <vector> #include <map> #include <libserpent/funcs.h> int main(int argv, char** argc) { if (argv == 1) { std::cerr << "Must provide a command and arguments! Try parse, rewrite, compile, assemble\n"; return 0; } std::string flag = ""; std::string command = argc[1]; std::string input; std::string secondInput; if (std::string(argc[1]) == "-s") { flag = command.substr(1); command = argc[2]; input = ""; std::string line; while (std::getline(std::cin, line)) { input += line + "\n"; } secondInput = argv == 3 ? "" : argc[3]; } else { if (argv == 2) { std::cerr << "Not enough arguments for serpent cmdline\n"; throw(0); } input = argc[2]; secondInput = argv == 3 ? "" : argc[3]; } bool haveSec = secondInput.length() > 0; if (command == "parse" || command == "parse_serpent") { std::cout << printAST(parseSerpent(input), haveSec) << "\n"; } else if (command == "rewrite") { std::cout << printAST(rewrite(parseLLL(input, true)), haveSec) << "\n"; } else if (command == "compile_to_lll") { std::cout << printAST(compileToLLL(input), haveSec) << "\n"; } else if (command == "build_fragtree") { std::cout << printAST(buildFragmentTree(parseLLL(input, true))) << "\n"; } else if (command == "compile_lll") { std::cout << binToHex(compileLLL(parseLLL(input, true))) << "\n"; } else if (command == "dereference") { std::cout << printAST(dereference(parseLLL(input, true)), haveSec) <<"\n"; } else if (command == "pretty_assemble") { std::cout << printTokens(prettyAssemble(parseLLL(input, true))) <<"\n"; } else if (command == "pretty_compile_lll") { std::cout << printTokens(prettyCompileLLL(parseLLL(input, true))) << "\n"; } else if (command == "pretty_compile") { std::cout << printTokens(prettyCompile(input)) << "\n"; } else if (command == "assemble") { std::cout << assemble(parseLLL(input, true)) << "\n"; } else if (command == "serialize") { std::cout << binToHex(serialize(tokenize(input))) << "\n"; } else if (command == "flatten") { std::cout << printTokens(flatten(parseLLL(input, true))) << "\n"; } else if (command == "deserialize") { std::cout << printTokens(deserialize(hexToBin(input))) << "\n"; } else if (command == "compile") { std::cout << binToHex(compile(input)) << "\n"; } else if (command == "encode_datalist") { std::vector<Node> tokens = tokenize(input); std::vector<std::string> o; for (int i = 0; i < (int)tokens.size(); i++) { o.push_back(tokens[i].val); } std::cout << binToHex(encodeDatalist(o)) << "\n"; } else if (command == "decode_datalist") { std::vector<std::string> o = decodeDatalist(hexToBin(input)); std::vector<Node> tokens; for (int i = 0; i < (int)o.size(); i++) tokens.push_back(token(o[i])); std::cout << printTokens(tokens) << "\n"; } else if (command == "tokenize") { std::cout << printTokens(tokenize(input)); } else if (command == "biject") { if (argv == 3) std::cerr << "Not enough arguments for biject\n"; int pos = decimalToInt(secondInput); std::vector<Node> n = prettyCompile(input); if (pos >= (int)n.size()) std::cerr << "Code position too high\n"; Metadata m = n[pos].metadata; std::cout << "Opcode: " << n[pos].val << ", file: " << m.file << ", line: " << m.ln << ", char: " << m.ch << "\n"; } } <commit_msg>Added include for std::getline() on MSVC<commit_after>#include <stdio.h> #include <iostream> #include <vector> #include <map> #include <string> #include <libserpent/funcs.h> int main(int argv, char** argc) { if (argv == 1) { std::cerr << "Must provide a command and arguments! Try parse, rewrite, compile, assemble\n"; return 0; } std::string flag = ""; std::string command = argc[1]; std::string input; std::string secondInput; if (std::string(argc[1]) == "-s") { flag = command.substr(1); command = argc[2]; input = ""; std::string line; while (std::getline(std::cin, line)) { input += line + "\n"; } secondInput = argv == 3 ? "" : argc[3]; } else { if (argv == 2) { std::cerr << "Not enough arguments for serpent cmdline\n"; throw(0); } input = argc[2]; secondInput = argv == 3 ? "" : argc[3]; } bool haveSec = secondInput.length() > 0; if (command == "parse" || command == "parse_serpent") { std::cout << printAST(parseSerpent(input), haveSec) << "\n"; } else if (command == "rewrite") { std::cout << printAST(rewrite(parseLLL(input, true)), haveSec) << "\n"; } else if (command == "compile_to_lll") { std::cout << printAST(compileToLLL(input), haveSec) << "\n"; } else if (command == "build_fragtree") { std::cout << printAST(buildFragmentTree(parseLLL(input, true))) << "\n"; } else if (command == "compile_lll") { std::cout << binToHex(compileLLL(parseLLL(input, true))) << "\n"; } else if (command == "dereference") { std::cout << printAST(dereference(parseLLL(input, true)), haveSec) <<"\n"; } else if (command == "pretty_assemble") { std::cout << printTokens(prettyAssemble(parseLLL(input, true))) <<"\n"; } else if (command == "pretty_compile_lll") { std::cout << printTokens(prettyCompileLLL(parseLLL(input, true))) << "\n"; } else if (command == "pretty_compile") { std::cout << printTokens(prettyCompile(input)) << "\n"; } else if (command == "assemble") { std::cout << assemble(parseLLL(input, true)) << "\n"; } else if (command == "serialize") { std::cout << binToHex(serialize(tokenize(input))) << "\n"; } else if (command == "flatten") { std::cout << printTokens(flatten(parseLLL(input, true))) << "\n"; } else if (command == "deserialize") { std::cout << printTokens(deserialize(hexToBin(input))) << "\n"; } else if (command == "compile") { std::cout << binToHex(compile(input)) << "\n"; } else if (command == "encode_datalist") { std::vector<Node> tokens = tokenize(input); std::vector<std::string> o; for (int i = 0; i < (int)tokens.size(); i++) { o.push_back(tokens[i].val); } std::cout << binToHex(encodeDatalist(o)) << "\n"; } else if (command == "decode_datalist") { std::vector<std::string> o = decodeDatalist(hexToBin(input)); std::vector<Node> tokens; for (int i = 0; i < (int)o.size(); i++) tokens.push_back(token(o[i])); std::cout << printTokens(tokens) << "\n"; } else if (command == "tokenize") { std::cout << printTokens(tokenize(input)); } else if (command == "biject") { if (argv == 3) std::cerr << "Not enough arguments for biject\n"; int pos = decimalToInt(secondInput); std::vector<Node> n = prettyCompile(input); if (pos >= (int)n.size()) std::cerr << "Code position too high\n"; Metadata m = n[pos].metadata; std::cout << "Opcode: " << n[pos].val << ", file: " << m.file << ", line: " << m.ln << ", char: " << m.ch << "\n"; } } <|endoftext|>
<commit_before>#include "oglWidget.h" #include <iostream> // // CONSTRUCTORS //////////////////////////////////////////////////////////////// // /** * @brief Default constructor for OGLWidget. */ OGLWidget::OGLWidget() { // Update the widget after a frameswap connect( this, SIGNAL( frameSwapped() ), this, SLOT( update() ) ); // Allows keyboard input to fall through setFocusPolicy( Qt::ClickFocus ); camera.rotate( -55.0f, 1.0f, 0.0f, 0.0f ); camera.translate( 4.0f, 14.0f, 15.0f ); renderables["Labyrinth"] = new Labyrinth( Environment::Ice, 8, 30, 30 ); renderables["Ball"] = new Ball(); } /** * @brief Destructor class to unallocate OpenGL information. */ OGLWidget::~OGLWidget() { makeCurrent(); teardownGL(); teardownBullet(); } // // OPENGL FUNCTIONS //////////////////////////////////////////////////////////// // /** * @brief Initializes any OpenGL operations. */ void OGLWidget::initializeGL() { // Init OpenGL Backend initializeOpenGLFunctions(); printContextInfo(); initializeBullet(); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->initializeGL(); } ((Labyrinth*)renderables["Labyrinth"])->addRigidBodys( m_dynamicsWorld ); m_dynamicsWorld->addRigidBody( ((Ball*)renderables["Ball"])->RigidBody ); } /** * @brief Sets the prespective whenever the window is resized. * * @param[in] width The width of the new window. * @param[in] height The height of the new window. */ void OGLWidget::resizeGL( int width, int height ) { projection.setToIdentity(); projection.perspective( 55.0f, // Field of view angle float( width ) / float( height ), // Aspect Ratio 0.001f, // Near Plane (MUST BE GREATER THAN 0) 1500.0f ); // Far Plane } /** * @brief OpenGL function to draw elements to the surface. */ void OGLWidget::paintGL() { // Set the default OpenGL states glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glDepthMask( GL_TRUE ); glEnable( GL_CULL_FACE ); glClearColor( 0.0f, 0.0f, 0.2f, 1.0f ); // Clear the screen glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->paintGL( camera, projection ); } } /** * @brief Destroys any OpenGL data. */ void OGLWidget::teardownGL() { for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->teardownGL(); } } // // SLOTS /////////////////////////////////////////////////////////////////////// // /** * @brief Updates any user interactions and model transformations. */ void OGLWidget::update() { float dt = updateTimer.deltaTime(); Input::update(); flyThroughCamera(); // not sure what to call this method controlBoard(); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->update(); } m_dynamicsWorld->stepSimulation( dt, 10 ); QOpenGLWidget::update(); } // // INPUT EVENTS //////////////////////////////////////////////////////////////// // /** * @brief Default slot for handling key press events. * * @param event The key event information. */ void OGLWidget::keyPressEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyPress( event->key() ); } /** * @brief Default slot for handling key release events. * * @param event The key event information. */ void OGLWidget::keyReleaseEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyRelease( event->key() ); } /** * @brief Default slot for handling mouse press events. * * @param event The mouse event information. */ void OGLWidget::mousePressEvent( QMouseEvent* event ) { Input::registerMousePress( event->button() ); } /** * @brief Default slot for handling mouse release events. * * @param event The mouse event information. */ void OGLWidget::mouseReleaseEvent( QMouseEvent* event ) { Input::registerMouseRelease( event->button() ); } // // PRIVATE HELPER FUNCTIONS //////////////////////////////////////////////////// // /** * @brief Helper function to initialize bullet data. */ void OGLWidget::initializeBullet() { m_broadphase = new btDbvtBroadphase(); m_collisionConfig = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher( m_collisionConfig ); m_solver = new btSequentialImpulseConstraintSolver(); m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase, m_solver, m_collisionConfig ); m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) ); } /** * @brief Helper function to delete bullet allocations. */ void OGLWidget::teardownBullet() { delete m_dynamicsWorld; delete m_solver; delete m_dispatcher; delete m_collisionConfig; delete m_broadphase; } /** * @brief Updates the main camera to behave like a Fly-Through Camera. */ void OGLWidget::flyThroughCamera() { static const float cameraTranslationSpeed = 0.02f; static const float cameraRotationSpeed = 0.1f; if( Input::buttonPressed( Qt::RightButton ) ) { // Rotate the camera based on mouse movement camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(), Camera3D::LocalUp ); camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(), camera.right() ); } // Translate the camera based on keyboard input QVector3D cameraTranslations; if( Input::keyPressed( Qt::Key_W ) ) cameraTranslations += camera.forward(); if( Input::keyPressed( Qt::Key_S ) ) cameraTranslations -= camera.forward(); if( Input::keyPressed( Qt::Key_A ) ) cameraTranslations -= camera.right(); if( Input::keyPressed( Qt::Key_D ) ) cameraTranslations += camera.right(); if( Input::keyPressed( Qt::Key_Q ) ) cameraTranslations -= camera.up(); if( Input::keyPressed( Qt::Key_E ) ) cameraTranslations += camera.up(); camera.translate( cameraTranslationSpeed * cameraTranslations ); } /** * @brief Updates board based on user input. */ void OGLWidget::controlBoard() { const float rotationSpeed = 0.5f; const float rollingSpeed = 0.25f; btVector3 gravity = m_dynamicsWorld->getGravity(); /* I suppose gravity being relative to camera would be best, here is some code incase you want to figure out a good way to do it. float cameraAngle; QVector3D cameraAxis; camera.rotation().getAxisAndAngle( &cameraAxis, &cameraAngle ); //std::cout << cameraAngle << std::endl; //std::cout << cameraAxis.x() << std::endl; */ if( Input::keyPressed( Qt::Key_Z ) ) { // Update horizontal rotation if( Input::keyPressed( Qt::Key_Left ) ) { camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) ); gravity -= btVector3( rollingSpeed, 0, 0 ); } else if( Input::keyPressed( Qt::Key_Right ) ) { camera.rotate( rotationSpeed, QVector3D(0, 0, 1) ); gravity += btVector3( rollingSpeed, 0, 0 ); } // Update vertical rotation if( Input::keyPressed( Qt::Key_Up ) ) { camera.rotate( rotationSpeed, QVector3D(1, 0, 0) ); gravity -= btVector3( 0, 0, rollingSpeed ); } else if( Input::keyPressed( Qt::Key_Down ) ) { camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) ); gravity += btVector3( 0, 0, rollingSpeed ); } } else { // Update horizontal rotation if( Input::keyPressed( Qt::Key_Left ) ) { camera.rotate( rotationSpeed, QVector3D(0, 0, 1) ); gravity -= btVector3( rollingSpeed, 0, 0 ); } else if( Input::keyPressed( Qt::Key_Right ) ) { camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) ); gravity += btVector3( rollingSpeed, 0, 0 ); } // Update vertical rotation if( Input::keyPressed( Qt::Key_Up ) ) { camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) ); gravity -= btVector3( 0, 0, rollingSpeed ); } else if( Input::keyPressed( Qt::Key_Down ) ) { camera.rotate( rotationSpeed, QVector3D(1, 0, 0) ); gravity += btVector3( 0, 0, rollingSpeed ); } } // Update gravity m_dynamicsWorld->setGravity( gravity ); } /** * @brief Helper function to print OpenGL Context information to the debug. */ void OGLWidget::printContextInfo() { QString glType; QString glVersion; QString glProfile; // Get Version Information glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL"; glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) ); // Get Profile Information switch( format().profile() ) { case QSurfaceFormat::NoProfile: glProfile = "No Profile"; break; case QSurfaceFormat::CoreProfile: glProfile = "Core Profile"; break; case QSurfaceFormat::CompatibilityProfile: glProfile = "Compatibility Profile"; break; } qDebug() << qPrintable( glType ) << qPrintable( glVersion ) << "(" << qPrintable( glProfile ) << ")"; }<commit_msg>Changed initial camera state<commit_after>#include "oglWidget.h" #include <iostream> // // CONSTRUCTORS //////////////////////////////////////////////////////////////// // /** * @brief Default constructor for OGLWidget. */ OGLWidget::OGLWidget() { // Update the widget after a frameswap connect( this, SIGNAL( frameSwapped() ), this, SLOT( update() ) ); // Allows keyboard input to fall through setFocusPolicy( Qt::ClickFocus ); camera.rotate( -90.0f, 1.0f, 0.0f, 0.0f ); camera.translate( 30.0f, 75.0f, 30.0f ); renderables["Labyrinth"] = new Labyrinth( Environment::Ice, 8, 30, 30 ); renderables["Ball"] = new Ball(); } /** * @brief Destructor class to unallocate OpenGL information. */ OGLWidget::~OGLWidget() { makeCurrent(); teardownGL(); teardownBullet(); } // // OPENGL FUNCTIONS //////////////////////////////////////////////////////////// // /** * @brief Initializes any OpenGL operations. */ void OGLWidget::initializeGL() { // Init OpenGL Backend initializeOpenGLFunctions(); printContextInfo(); initializeBullet(); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->initializeGL(); } ((Labyrinth*)renderables["Labyrinth"])->addRigidBodys( m_dynamicsWorld ); m_dynamicsWorld->addRigidBody( ((Ball*)renderables["Ball"])->RigidBody ); } /** * @brief Sets the prespective whenever the window is resized. * * @param[in] width The width of the new window. * @param[in] height The height of the new window. */ void OGLWidget::resizeGL( int width, int height ) { projection.setToIdentity(); projection.perspective( 55.0f, // Field of view angle float( width ) / float( height ), // Aspect Ratio 0.001f, // Near Plane (MUST BE GREATER THAN 0) 1500.0f ); // Far Plane } /** * @brief OpenGL function to draw elements to the surface. */ void OGLWidget::paintGL() { // Set the default OpenGL states glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); glDepthMask( GL_TRUE ); glEnable( GL_CULL_FACE ); glClearColor( 0.0f, 0.0f, 0.2f, 1.0f ); // Clear the screen glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->paintGL( camera, projection ); } } /** * @brief Destroys any OpenGL data. */ void OGLWidget::teardownGL() { for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->teardownGL(); } } // // SLOTS /////////////////////////////////////////////////////////////////////// // /** * @brief Updates any user interactions and model transformations. */ void OGLWidget::update() { float dt = updateTimer.deltaTime(); Input::update(); flyThroughCamera(); // not sure what to call this method controlBoard(); for( QMap<QString, Renderable*>::iterator iter = renderables.begin(); iter != renderables.end(); iter++ ) { (*iter)->update(); } m_dynamicsWorld->stepSimulation( dt, 10 ); QOpenGLWidget::update(); } // // INPUT EVENTS //////////////////////////////////////////////////////////////// // /** * @brief Default slot for handling key press events. * * @param event The key event information. */ void OGLWidget::keyPressEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyPress( event->key() ); } /** * @brief Default slot for handling key release events. * * @param event The key event information. */ void OGLWidget::keyReleaseEvent( QKeyEvent* event ) { if( event->isAutoRepeat() ) event->ignore(); else Input::registerKeyRelease( event->key() ); } /** * @brief Default slot for handling mouse press events. * * @param event The mouse event information. */ void OGLWidget::mousePressEvent( QMouseEvent* event ) { Input::registerMousePress( event->button() ); } /** * @brief Default slot for handling mouse release events. * * @param event The mouse event information. */ void OGLWidget::mouseReleaseEvent( QMouseEvent* event ) { Input::registerMouseRelease( event->button() ); } // // PRIVATE HELPER FUNCTIONS //////////////////////////////////////////////////// // /** * @brief Helper function to initialize bullet data. */ void OGLWidget::initializeBullet() { m_broadphase = new btDbvtBroadphase(); m_collisionConfig = new btDefaultCollisionConfiguration(); m_dispatcher = new btCollisionDispatcher( m_collisionConfig ); m_solver = new btSequentialImpulseConstraintSolver(); m_dynamicsWorld = new btDiscreteDynamicsWorld( m_dispatcher, m_broadphase, m_solver, m_collisionConfig ); m_dynamicsWorld->setGravity( btVector3( 0, -9.8, 0 ) ); } /** * @brief Helper function to delete bullet allocations. */ void OGLWidget::teardownBullet() { delete m_dynamicsWorld; delete m_solver; delete m_dispatcher; delete m_collisionConfig; delete m_broadphase; } /** * @brief Updates the main camera to behave like a Fly-Through Camera. */ void OGLWidget::flyThroughCamera() { static const float cameraTranslationSpeed = 0.02f; static const float cameraRotationSpeed = 0.1f; if( Input::buttonPressed( Qt::RightButton ) ) { // Rotate the camera based on mouse movement camera.rotate( -cameraRotationSpeed * Input::mouseDelta().x(), Camera3D::LocalUp ); camera.rotate( -cameraRotationSpeed * Input::mouseDelta().y(), camera.right() ); } // Translate the camera based on keyboard input QVector3D cameraTranslations; if( Input::keyPressed( Qt::Key_W ) ) cameraTranslations += camera.forward(); if( Input::keyPressed( Qt::Key_S ) ) cameraTranslations -= camera.forward(); if( Input::keyPressed( Qt::Key_A ) ) cameraTranslations -= camera.right(); if( Input::keyPressed( Qt::Key_D ) ) cameraTranslations += camera.right(); if( Input::keyPressed( Qt::Key_Q ) ) cameraTranslations -= camera.up(); if( Input::keyPressed( Qt::Key_E ) ) cameraTranslations += camera.up(); camera.translate( cameraTranslationSpeed * cameraTranslations ); } /** * @brief Updates board based on user input. */ void OGLWidget::controlBoard() { const float rotationSpeed = 0.5f; const float rollingSpeed = 0.25f; btVector3 gravity = m_dynamicsWorld->getGravity(); /* I suppose gravity being relative to camera would be best, here is some code incase you want to figure out a good way to do it. float cameraAngle; QVector3D cameraAxis; camera.rotation().getAxisAndAngle( &cameraAxis, &cameraAngle ); //std::cout << cameraAngle << std::endl; //std::cout << cameraAxis.x() << std::endl; */ if( Input::keyPressed( Qt::Key_Z ) ) { // Update horizontal rotation if( Input::keyPressed( Qt::Key_Left ) ) { camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) ); gravity -= btVector3( rollingSpeed, 0, 0 ); } else if( Input::keyPressed( Qt::Key_Right ) ) { camera.rotate( rotationSpeed, QVector3D(0, 0, 1) ); gravity += btVector3( rollingSpeed, 0, 0 ); } // Update vertical rotation if( Input::keyPressed( Qt::Key_Up ) ) { camera.rotate( rotationSpeed, QVector3D(1, 0, 0) ); gravity -= btVector3( 0, 0, rollingSpeed ); } else if( Input::keyPressed( Qt::Key_Down ) ) { camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) ); gravity += btVector3( 0, 0, rollingSpeed ); } } else { // Update horizontal rotation if( Input::keyPressed( Qt::Key_Left ) ) { camera.rotate( rotationSpeed, QVector3D(0, 0, 1) ); gravity -= btVector3( rollingSpeed, 0, 0 ); } else if( Input::keyPressed( Qt::Key_Right ) ) { camera.rotate( -rotationSpeed, QVector3D(0, 0, 1) ); gravity += btVector3( rollingSpeed, 0, 0 ); } // Update vertical rotation if( Input::keyPressed( Qt::Key_Up ) ) { camera.rotate( -rotationSpeed, QVector3D(1, 0, 0) ); gravity -= btVector3( 0, 0, rollingSpeed ); } else if( Input::keyPressed( Qt::Key_Down ) ) { camera.rotate( rotationSpeed, QVector3D(1, 0, 0) ); gravity += btVector3( 0, 0, rollingSpeed ); } } // Update gravity m_dynamicsWorld->setGravity( gravity ); } /** * @brief Helper function to print OpenGL Context information to the debug. */ void OGLWidget::printContextInfo() { QString glType; QString glVersion; QString glProfile; // Get Version Information glType = ( context()->isOpenGLES() ) ? "OpenGL ES" : "OpenGL"; glVersion = reinterpret_cast<const char*>( glGetString( GL_VERSION ) ); // Get Profile Information switch( format().profile() ) { case QSurfaceFormat::NoProfile: glProfile = "No Profile"; break; case QSurfaceFormat::CoreProfile: glProfile = "Core Profile"; break; case QSurfaceFormat::CompatibilityProfile: glProfile = "Compatibility Profile"; break; } qDebug() << qPrintable( glType ) << qPrintable( glVersion ) << "(" << qPrintable( glProfile ) << ")"; }<|endoftext|>
<commit_before>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the copyright holder 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 HOLDER 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. * */ #ifndef INCLUDE_OTF2XX_DEFINITION_PRE_FWD_HPP #define INCLUDE_OTF2XX_DEFINITION_PRE_FWD_HPP #include <otf2xx/common.hpp> namespace otf2 { namespace definition { namespace detail { class group_base; template <typename Impl> class impl_base; class location_impl; class location_group_impl; class system_tree_node_impl; template <typename T, otf2::common::group_type GroupType> class group_impl; class comm_impl; class region_impl; class attribute_impl; class parameter_impl; class string_impl; class clock_properties_impl; class source_code_location_impl; class calling_context_impl; class interrupt_generator_impl; class io_file_base; class io_handle_base; class io_file_impl; class io_directory_impl; class io_handle_impl; class io_paradigm_impl; class io_pre_created_handle_state_impl; class mapping_table_impl; class metric_base; class metric_class_impl; class metric_instance_impl; class metric_member_impl; template <typename Definition> class property_impl; class marker_impl; template <typename Definition> class weak_ref; } class location; class location_group; class system_tree_node; template <typename T, otf2::common::group_type GroupType> class group; class comm; class region; class attribute; class parameter; class string; class clock_properties; class source_code_location; class calling_context; class interrupt_generator; class io_file; class io_regular_file; class io_directory; class io_handle; class io_paradigm; class io_pre_created_handle_state; class mapping_table; class unknown; using locations_group = group<otf2::definition::location, otf2::common::group_type::locations>; using regions_group = group<otf2::definition::region, otf2::common::group_type::regions>; using comm_locations_group = group<otf2::definition::location, otf2::common::group_type::comm_locations>; using comm_group = group<otf2::definition::location, otf2::common::group_type::comm_group>; using comm_self_group = group<otf2::definition::location, otf2::common::group_type::comm_self>; class metric_member; class metric_class; class metric_instance; // TODO: which class of metric foo? // using metric_group = group<otf2::definition::metric, // otf2::common::group_type::metric>; template <typename Definition> class container; template <typename Definition> class property; using location_property = property<location>; using location_group_property = property<location_group>; using system_tree_node_property = property<system_tree_node>; using calling_context_property = property<calling_context>; using io_file_property = property<io_regular_file>; class marker; template <typename Definition> detail::weak_ref<Definition> make_weak_ref(const Definition&); } } // namespace otf2::definition #endif // INCLUDE_OTF2XX_DEFINITION_PRE_FWD_HPP <commit_msg>Removes forward declaration of non-existant class.<commit_after>/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the copyright holder 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 HOLDER 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. * */ #ifndef INCLUDE_OTF2XX_DEFINITION_PRE_FWD_HPP #define INCLUDE_OTF2XX_DEFINITION_PRE_FWD_HPP #include <otf2xx/common.hpp> namespace otf2 { namespace definition { namespace detail { class group_base; template <typename Impl> class impl_base; class location_impl; class location_group_impl; class system_tree_node_impl; template <typename T, otf2::common::group_type GroupType> class group_impl; class comm_impl; class region_impl; class attribute_impl; class parameter_impl; class string_impl; class clock_properties_impl; class source_code_location_impl; class calling_context_impl; class interrupt_generator_impl; class io_file_impl; class io_directory_impl; class io_handle_impl; class io_paradigm_impl; class io_pre_created_handle_state_impl; class mapping_table_impl; class metric_base; class metric_class_impl; class metric_instance_impl; class metric_member_impl; template <typename Definition> class property_impl; class marker_impl; template <typename Definition> class weak_ref; } class location; class location_group; class system_tree_node; template <typename T, otf2::common::group_type GroupType> class group; class comm; class region; class attribute; class parameter; class string; class clock_properties; class source_code_location; class calling_context; class interrupt_generator; class io_file; class io_regular_file; class io_directory; class io_handle; class io_paradigm; class io_pre_created_handle_state; class mapping_table; class unknown; using locations_group = group<otf2::definition::location, otf2::common::group_type::locations>; using regions_group = group<otf2::definition::region, otf2::common::group_type::regions>; using comm_locations_group = group<otf2::definition::location, otf2::common::group_type::comm_locations>; using comm_group = group<otf2::definition::location, otf2::common::group_type::comm_group>; using comm_self_group = group<otf2::definition::location, otf2::common::group_type::comm_self>; class metric_member; class metric_class; class metric_instance; // TODO: which class of metric foo? // using metric_group = group<otf2::definition::metric, // otf2::common::group_type::metric>; template <typename Definition> class container; template <typename Definition> class property; using location_property = property<location>; using location_group_property = property<location_group>; using system_tree_node_property = property<system_tree_node>; using calling_context_property = property<calling_context>; using io_file_property = property<io_regular_file>; class marker; template <typename Definition> detail::weak_ref<Definition> make_weak_ref(const Definition&); } } // namespace otf2::definition #endif // INCLUDE_OTF2XX_DEFINITION_PRE_FWD_HPP <|endoftext|>